问:
Define Model Parameter as Variable
I am attempting to define the parameter of a model (block) as a variable. For example:

```<code>Real WallThickness = 0.5;
Real WallConductance = 10*WallThickness;
Modelica.Thermal.HeatTransfer.Components.ThermalConductor TopPanelConductor(G=WallConductance);
</code>```

I would like to define "G" so that it remains constant throughout the simulation but the coefficient is updated prior to the simulation based on the other variable "WallThickness". When defining the ThermalConductor parameter "G" as a variable in the model, which is being calculated elsewhere, I get the error message:

```<code>The variability of the definition equation:
TopPanelConductor.G = WallConductance;
is higher than the declared variability of the variables.
</code>```

I would like to define the parameters of a model as a variable. This allows me to create parametric definitions as the geometry of the all changes. Is there a way I can make this definition work?

答:
There is a heirachery for varaibales/parameters that restrict their use. As you are now aware, parameters are not permitted to vary with within the simulations. Thus, you get the error stating that you are trying to define a parameter with a variable value or input variable.

If you need that functionality I would recommend duplicating the ThermalConductor and change the variable type:

```<code>parameter Modelica.SIunits.ThermalConductance G
    "Constant thermal conductance of material";
</code>```

to

```<code>input  Modelica.SIunits.ThermalConductance G
"Constant thermal conductance of material" annotation (Dialog(group=”Input Variables”));
</code>```

That all there is to it. Note the additional annotation on the input variable. By default inputs do not show up in the parameter GUI. The annotation will permit them to be seen just like parameters (be careful to clearly label it an input variable versus a parameter though!)

There is work underway that has completely redone the Thermal library but is not yet released and the most-straightforward approach would probably try what I have discussed.

Title: Define Model Parameter as Variable

Body:
I am attempting to define the parameter of a model (block) as a variable. For example:

Real WallThickness = 0.5;
Real WallConductance = 10*WallThickness;
Modelica.Thermal.HeatTransfer.Components.ThermalConductor TopPanelConductor(G=WallConductance);

I would like to define "G" so that it remains constant throughout the simulation but the coefficient is updated prior to the simulation based on the other variable "WallThickness". When defining the ThermalConductor parameter "G" as a variable in the model, which is being calculated elsewhere, I get the error message:

The variability of the definition equation:
TopPanelConductor.G = WallConductance;
is higher than the declared variability of the variables.

I would like to define the parameters of a model as a variable. This allows me to create parametric definitions as the geometry of the all changes. Is there a way I can make this definition work?

Body:
There is a heirachery for varaibales/parameters that restrict their use. As you are now aware, parameters are not permitted to vary with within the simulations. Thus, you get the error stating that you are trying to define a parameter with a variable value or input variable.

If you need that functionality I would recommend duplicating the ThermalConductor and change the variable type:

parameter Modelica.SIunits.ThermalConductance G
    "Constant thermal conductance of material";

to

input  Modelica.SIunits.ThermalConductance G
"Constant thermal conductance of material" annotation (Dialog(group=”Input Variables”));

That all there is to it. Note the additional annotation on the input variable. By default inputs do not show up in the parameter GUI. The annotation will permit them to be seen just like parameters (be careful to clearly label it an input variable versus a parameter though!)

There is work underway that has completely redone the Thermal library but is not yet released and the most-straightforward approach would probably try what I have discussed.


来源: stackexchange

问:
Get number before a specified string
Given the string

```<code>RAM Statistics: 5954 / 8174 743=InUse 746=Peak
</code>```

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"
</code>```

But that's returning nothing.

UPDATE:
Per Joshua I have tried

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"
</code>```

And both $matches[0] and [1] return everything before the =Peak. So

```<code>Statistics:     5954 /     8174       743=InUse      746!
</code>```

答:
Other method, without regex</p>

```<code>$template=@"
{Data:RAM Statistics:{RamStat:   123456 /     123}       {InUseValue:743}=InUse      {PeakValue:746}=Peak}
"@

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$result=$string | ConvertFrom-String -TemplateContent $Template

write-host "RamStat : " $result.Data.RamStat
write-host "PeakValue : " $result.Data.PeakValue
write-host "InUseValue : " $result.Data.InUseValue
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get number before a specified string

Body:
Given the string

RAM Statistics: 5954 / 8174 743=InUse 746=Peak

I need a RegEx (or three) to extract the 743, the 746, and ideally the 5954 / 8174 so each can be assigned to a specific variable.

I THINK this is what LookBehind is used for, but I am having a hell of a time actually getting a RegEx to "Get the numbers between a Space and =Peak", for example.

I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(?<= )(.#)(?=\=Peak)'
$string -match $regexPeak > $null
$peak = $matches[0]
Write-Host "$peak"

But that's returning nothing.

UPDATE:
Per Joshua I have tried

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$regexPeak = '(\d+) / (\d+) (\d+)=\D+(\d+)=peak/gi'
$string -match $regexPeak
$peak = $matches[0]
Write-Host "$peak!"

And both $matches[0] and [1] return everything before the =Peak. So

Statistics:     5954 /     8174       743=InUse      746!

Body:
Other method, without regex

$template=@"
{Data:RAM Statistics:{RamStat:   123456 /     123}       {InUseValue:743}=InUse      {PeakValue:746}=Peak}
"@

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$result=$string | ConvertFrom-String -TemplateContent $Template

write-host "RamStat : " $result.Data.RamStat
write-host "PeakValue : " $result.Data.PeakValue
write-host "InUseValue : " $result.Data.InUseValue


问:
Media Queries for all screen sizes
From Large Desktop Screen to Small Mobile Device: which are the Media Queries we should use?

I am bit confused with this. I am trying to get this clearly

```<code>/*Small Desktop*/

@media (max-width:1920px){

}
</code>```

答:
@media queries apply standard CSS only where the device's screen meets certain defined criteria (height, width, and pixel-ratio; mainly)

The best resource I've found for media queries is https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

Here's a snippet of the fantastic work there:

```<code>/* ----------- iPad mini ----------- */

/* Portrait and Landscape */
@media only screen
  and (min-device-width: 768px)
  and (max-device-width: 1024px)
  and (-webkit-min-device-pixel-ratio: 1) {

}

/* Portrait */
@media only screen
  and (min-device-width: 768px)
  and (max-device-width: 1024px)
  and (orientation: portrait)
  and (-webkit-min-device-pixel-ratio: 1) {

}

/* Landscape */
@media only screen
  and (min-device-width: 768px)
  and (max-device-width: 1024px)
  and (orientation: landscape)
  and (-webkit-min-device-pixel-ratio: 1) {

}
</code>```

Title: Media Queries for all screen sizes

Body:
From Large Desktop Screen to Small Mobile Device: which are the Media Queries we should use?

I am bit confused with this. I am trying to get this clearly

/*Small Desktop*/

@media (max-width:1920px){

}

Body:
@media queries apply standard CSS only where the device's screen meets certain defined criteria (height, width, and pixel-ratio; mainly)

The best resource I've found for media queries is https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

Here's a snippet of the fantastic work there:

/* ----------- iPad mini ----------- */

/* Portrait and Landscape */
@media only screen
  and (min-device-width: 768px)
  and (max-device-width: 1024px)
  and (-webkit-min-device-pixel-ratio: 1) {

}

/* Portrait */
@media only screen
  and (min-device-width: 768px)
  and (max-device-width: 1024px)
  and (orientation: portrait)
  and (-webkit-min-device-pixel-ratio: 1) {

}

/* Landscape */
@media only screen
  and (min-device-width: 768px)
  and (max-device-width: 1024px)
  and (orientation: landscape)
  and (-webkit-min-device-pixel-ratio: 1) {

}


问:
Parsing Json and store data in sqlite database and view in a listView
Hi all I am developing an app that collects data from a fake site rest bees and stores them in a listView. So far I managed to download the JSON file and display it in a listView. These are my classes:

HomeScreen.java

```<code>import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class HomeScreen extends AppCompatActivity {
     private String classtag= HomeScreen.class.getSimpleName();  //return
        name of underlying class
     private ListView lv;
     private ProgressDialog progress;
     private String url="https://jsonplaceholder.typicode.com/posts";
     //passing url
     ArrayList<HashMap<String,String>> studentslist; //arraylist to save key
     value pair from json
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_home_screen);
         studentslist=new ArrayList<>();
         lv= (ListView) findViewById(R.id.list); //from home screen listview
         new getStudents().execute(); // it will execute your AsyncTask
     }
//--------------------------//-------------------------------//---------------------//
   public class getStudents extends AsyncTask<Void,Void,Void> {
        protected void onPreExecute(){
            super.onPreExecute(); //it will use pre defined preExecute
                                  method in async task
             progress=new ProgressDialog(HomeScreen.this);
             progress.setMessage("Fetching JSON.,."); // show what you want
                                                      in the progress dialog
             progress.setCancelable(false); //progress dialog is not
                                            cancellable here
            progress.show();
        }
        protected Void doInBackground(Void...arg0){
            HTTP_Handler hh = new HTTP_Handler(); // object of HTTP_Handler
            String jString = hh.makeHTTPCall(url); //calling makeHTTPCall
                                  method and string its response in a string
            Log.e(classtag, "Response from URL: " + jString);
            if (jString != null) {
            try {
                JSONArray students = new JSONArray(jString);
                 //our json data starts with the object
                 //fetch array from studentsinfo object
                for (int i = 0; i < students.length(); i++) {
                    JSONObject obj = students.getJSONObject(i); //get object
                                                                from i index
                    String userId=obj.getString("userId");   //save string
                                            from variable 'id' to string
                    String id=obj.getString("id");
                    String title=obj.getString("title");
                    String body=obj.getString("body");
                    HashMap<String, String> studentdata = new HashMap<>();
                      //create a hash map to set key and value pair

                    studentdata.put("userId", userId); //hash map will save
                                                    key and its value
                    studentdata.put("id", id);
                    studentdata.put("title", title);
                    studentdata.put("body", body);

                    studentslist.add(studentdata); //now save all of the key
                                                    value pairs to arraylist
                }
            } catch (final JSONException e) {
                Log.e(classtag, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show(); //show if you catch any exception
                                                                 with data
                    }
                });
            }
        } else {
            Log.e(classtag, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {Toast.makeText(getApplicationContext(),
                        "Couldn't get json from server. Check internet
                                                    connection!",
                        Toast.LENGTH_LONG).show();//show if you are unable
                        to connect with the internet or if jString is null
                }
            });
        }
        return null;
    }
    protected void onPostExecute(Void Result){
        super.onPostExecute(Result);
        if(progress.isShowing()){
            progress.dismiss();
        }
        ListAdapter adapter=new SimpleAdapter(
                HomeScreen.this,
                studentslist,
                R.layout.bucket_list,
                new String[]{"userId","id","title","body"},
                new int[]{R.id.list_Name,R.id.list_Email,R.id.list_Address
                                                       ,R.id.list_Gender});
        lv.setAdapter(adapter);

        }
    }
}
</code>```

Http_Handler.java

```<code>import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HTTP_Handler {
      private static final String classtag=
      HTTP_Handler.class.getSimpleName();  //return name of underlying class

public String makeHTTPCall(String URLinput) { // method which will request
               to server when provided with url
    String response = null;
    try {
        URL url = new URL(URLinput);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //to open connection with url
        conn.setRequestMethod("GET");   //request type is of GET, which
                           means to get information from the server

        InputStream in = new BufferedInputStream(conn.getInputStream());
         //storing the input stream we are getting for the url
        response = InputStreamToString(in); //now storing string from the
                                            input stream
    } catch (MalformedURLException e) {
        Log.e(classtag, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(classtag, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(classtag, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(classtag, "Exception: " + e.getMessage());
    }
    return response; //returning whatever we fetching from the string to the
                     method.
  }
private String InputStreamToString(InputStream is) {   //fetching string
    form the input stream
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); //it
    will read form stream
    StringBuilder sb = new StringBuilder();
    String line;
    try {
        while ((line = br.readLine()) != null) {
            sb.append(line).append('\n'); //whatever we read from the
            stream, we will append it to the stringbuilder
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
           } catch (IOException e) {
            e.printStackTrace();
           }
       }
    return sb.toString();
    }
}
</code>```

Could someone help me to integrate the saving in SQLite database and display ever in a listView.
Thanks in advance for the help.

答:
If you're asking for best practices of what to do next and you don't want to read a complete Code Apprentice then read the basics about this. Hope it helps

Java Beans (getter and setters)

GSon or any other tool to convert from JSON to objects and viceversa

How to store/retrieve your object to/from SQLite with one SQL connection

Recycler View

Holder pattern

Your question is too wide. Once you start properly with your code, keep asking.

Body:
Hi all I am developing an app that collects data from a fake site rest bees and stores them in a listView. So far I managed to download the JSON file and display it in a listView. These are my classes:

HomeScreen.java

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class HomeScreen extends AppCompatActivity {
     private String classtag= HomeScreen.class.getSimpleName();  //return
        name of underlying class
     private ListView lv;
     private ProgressDialog progress;
     private String url="https://jsonplaceholder.typicode.com/posts";
     //passing url
     ArrayList<HashMap<String,String>> studentslist; //arraylist to save key
     value pair from json
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_home_screen);
         studentslist=new ArrayList<>();
         lv= (ListView) findViewById(R.id.list); //from home screen listview
         new getStudents().execute(); // it will execute your AsyncTask
     }
//--------------------------//-------------------------------//---------------------//
   public class getStudents extends AsyncTask<Void,Void,Void> {
        protected void onPreExecute(){
            super.onPreExecute(); //it will use pre defined preExecute
                                  method in async task
             progress=new ProgressDialog(HomeScreen.this);
             progress.setMessage("Fetching JSON.,."); // show what you want
                                                      in the progress dialog
             progress.setCancelable(false); //progress dialog is not
                                            cancellable here
            progress.show();
        }
        protected Void doInBackground(Void...arg0){
            HTTP_Handler hh = new HTTP_Handler(); // object of HTTP_Handler
            String jString = hh.makeHTTPCall(url); //calling makeHTTPCall
                                  method and string its response in a string
            Log.e(classtag, "Response from URL: " + jString);
            if (jString != null) {
            try {
                JSONArray students = new JSONArray(jString);
                 //our json data starts with the object
                 //fetch array from studentsinfo object
                for (int i = 0; i < students.length(); i++) {
                    JSONObject obj = students.getJSONObject(i); //get object
                                                                from i index
                    String userId=obj.getString("userId");   //save string
                                            from variable 'id' to string
                    String id=obj.getString("id");
                    String title=obj.getString("title");
                    String body=obj.getString("body");
                    HashMap<String, String> studentdata = new HashMap<>();
                      //create a hash map to set key and value pair

                    studentdata.put("userId", userId); //hash map will save
                                                    key and its value
                    studentdata.put("id", id);
                    studentdata.put("title", title);
                    studentdata.put("body", body);

                    studentslist.add(studentdata); //now save all of the key
                                                    value pairs to arraylist
                }
            } catch (final JSONException e) {
                Log.e(classtag, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show(); //show if you catch any exception
                                                                 with data
                    }
                });
            }
        } else {
            Log.e(classtag, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {Toast.makeText(getApplicationContext(),
                        "Couldn't get json from server. Check internet
                                                    connection!",
                        Toast.LENGTH_LONG).show();//show if you are unable
                        to connect with the internet or if jString is null
                }
            });
        }
        return null;
    }
    protected void onPostExecute(Void Result){
        super.onPostExecute(Result);
        if(progress.isShowing()){
            progress.dismiss();
        }
        ListAdapter adapter=new SimpleAdapter(
                HomeScreen.this,
                studentslist,
                R.layout.bucket_list,
                new String[]{"userId","id","title","body"},
                new int[]{R.id.list_Name,R.id.list_Email,R.id.list_Address
                                                       ,R.id.list_Gender});
        lv.setAdapter(adapter);

        }
    }
}

Http_Handler.java

import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HTTP_Handler {
      private static final String classtag=
      HTTP_Handler.class.getSimpleName();  //return name of underlying class

public String makeHTTPCall(String URLinput) { // method which will request
               to server when provided with url
    String response = null;
    try {
        URL url = new URL(URLinput);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //to open connection with url
        conn.setRequestMethod("GET");   //request type is of GET, which
                           means to get information from the server

        InputStream in = new BufferedInputStream(conn.getInputStream());
         //storing the input stream we are getting for the url
        response = InputStreamToString(in); //now storing string from the
                                            input stream
    } catch (MalformedURLException e) {
        Log.e(classtag, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(classtag, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(classtag, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(classtag, "Exception: " + e.getMessage());
    }
    return response; //returning whatever we fetching from the string to the
                     method.
  }
private String InputStreamToString(InputStream is) {   //fetching string
    form the input stream
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); //it
    will read form stream
    StringBuilder sb = new StringBuilder();
    String line;
    try {
        while ((line = br.readLine()) != null) {
            sb.append(line).append('\n'); //whatever we read from the
            stream, we will append it to the stringbuilder
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
           } catch (IOException e) {
            e.printStackTrace();
           }
       }
    return sb.toString();
    }
}

Could someone help me to integrate the saving in SQLite database and display ever in a listView.
Thanks in advance for the help.


问:
JPQL: The state field path cannot be resolved to a valid type
I can't make this query work:

```<code>Query query = eManager.createQuery("select c FROM News c WHERE c.NEWSID = :id",News.class);
        return (News)query.setParameter("id", newsId).getSingleResult();
</code>```

and I got this exception:

```<code>Exception Description: Problem compiling [select c FROM News c WHERE c.NEWSID = :id].
[27, 35] The state field path 'c.NEWSID' cannot be resolved to a valid type.] with root cause
Local Exception Stack:
Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select c FROM News c WHERE c.NEWSID = :id].
</code>```

Why does it happen?
:id and named parameter are identical

EDIT:
my entity class

```<code>@Entity
@Table(name="NEWS")
public class News implements Serializable{

    @Id
    @SequenceGenerator(name = "news_seq_gen", sequenceName = "news_seq")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "news_seq_gen")
    private int newsId;
    private String newsTitle;
    private String newsBrief;
    private String newsContent;
    private Date newsDate;
    @Transient
    private boolean selected=false;

//constructor and getters and setters
</code>```

答:
entity have persistent attribute named newsId.but in query you have used NEWSID . try with this</p>

```<code>select c FROM News c WHERE c.newsId = :id
</code>```

Body:
I can't make this query work:

Query query = eManager.createQuery("select c FROM News c WHERE c.NEWSID = :id",News.class);
        return (News)query.setParameter("id", newsId).getSingleResult();

and I got this exception:

Exception Description: Problem compiling [select c FROM News c WHERE c.NEWSID = :id].
[27, 35] The state field path 'c.NEWSID' cannot be resolved to a valid type.] with root cause
Local Exception Stack:
Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select c FROM News c WHERE c.NEWSID = :id].

Why does it happen?
:id and named parameter are identical

EDIT:
my entity class

@Entity
@Table(name="NEWS")
public class News implements Serializable{

    @Id
    @SequenceGenerator(name = "news_seq_gen", sequenceName = "news_seq")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "news_seq_gen")
    private int newsId;
    private String newsTitle;
    private String newsBrief;
    private String newsContent;
    private Date newsDate;
    @Transient
    private boolean selected=false;

//constructor and getters and setters

Body:
entity have persistent attribute named newsId.but in query you have used NEWSID . try with this

select c FROM News c WHERE c.newsId = :id


问:
Select rows where string does not repeat
I'm not sure how to phrase this, but I have two tables that I use INNER JOIN on to count the number of records I have. This works fine but the problem is that I have some rows in table1 where some of the records have a string that can appear in another record. Something like this:

```<code>table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
03    aaa                03    03           1
04    ccc                04    04           4
05    bbb                05    05           2
...                      ...
</code>```

My query looks like this:

```<code>SELECT COUNT(*) FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id
</code>```

This query works fine, but I want to be able to get distinct values. So my query should bring me back only these records:

```<code>table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
04    ccc                04    04           4
...                      ...
</code>```

As you can see, it doesn't show any additional records where they share the same string. What would I write after or before my INNER JOIN? Any help would be appreciated.

答:
SELECT DISTINCT count(*) from table1
inner join table2 on table1.id = table2.table1_id

This will give you the count of distinct values in the tables

Body:
I'm not sure how to phrase this, but I have two tables that I use INNER JOIN on to count the number of records I have. This works fine but the problem is that I have some rows in table1 where some of the records have a string that can appear in another record. Something like this:

table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
03    aaa                03    03           1
04    ccc                04    04           4
05    bbb                05    05           2
...                      ...

My query looks like this:

SELECT COUNT(*) FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id

This query works fine, but I want to be able to get distinct values. So my query should bring me back only these records:

table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
04    ccc                04    04           4
...                      ...

As you can see, it doesn't show any additional records where they share the same string. What would I write after or before my INNER JOIN? Any help would be appreciated.


问:
Making directory like layout with RecyclerView
This is what I want to achieve

What I have tried is, dynamically adding layouts to recycleView on click of each item. But I don't think this is an efficient way.

Mind you it's a directory like structure, where each folder can have sub folders and each subfolder can have subfolders and so on.

Please suggest any other alternatives.

答: Why do you want to reinvent a wheel? There's a library called RecyclerTreeView with exactly that functionality. At least you can view sources and perform necessary changes on your own.

ContentLicense: CC BY-SA 4.0


问:
Php add calendar months to a date
I would like to add some calendar month to a date. I have done in javascript, but I would make the same function in Php (I'm newer).
This is javascript code:

var date = '2017-08-30';
var addMonth=6;
var arrDate = date.split("-");
var dateSrt = new Date(date);
var newSrvDate = new Date(dateSrt.getTime());

newSrvDate.setMonth(dateSrt.getMonth() + (addMonth), arrDate[2]);
if (newSrvDate.getMonth() > (dateSrt.getMonth() + (addMonth)) % 12) {
    newSrvDate.setDate(0);
}
srvDay = new Date(newSrvDate.getFullYear(), newSrvDate.getMonth() , newSrvDate.getDate());
alert("Start:"+dateSrt);
alert("End:"+srvDay);```

In this case if I add 6 months to 2017-08-30 will be 2018-02-30, but it doesn't exist, so it become 2018-03-02.
I would like that if the date exist ok, in other case the last day of the month...

I hope I'm clear... the code work perfectly in javascript, but I can not reproduce it in php

Any suggestions ere welcome

答:
Check date with checkdate() if valid date or not in  Gregorian dates. And then if not exist then subtract 1 day (24 hours) from the date and again check exist or not. Just like as in following code without using any class (plain PHP).

Here you JS equivalent code in PHP.

```<code>$date = '2017-08-30';
$newDate = strtotime($date)+6*30*24*60*60;
$exploded = explode('-',$date);
$month = $exploded[1];
$year = $exploded[0];
$day = $exploded[2];

$new_month = $exploded[1]+6;
if($new_month>12){
    $month = $new_month-12;
    $year = $year+1;
}
else{
    $month = $new_month;
}
echo $year."-".$month."-".$day;

//Function to check date recursively.............
function check_date($year,$month,$day){
    if(!checkdate($month,$day,$year)){
        $day = $day-1;
        return check_date($year,$month,$day);
    }
    else{
        return $year."-".$month."-".$day;
    }
}

$final_date = check_date($year,$month,$day);
echo date("Y-m-d",strtotime($final_date));
</code>```

But I would recommend you to look at into DateTIme class and also look date().

Note: This is the code where the day of the month will be preserved and answer for you question "I would like that if the date exist ok, in other case the last day of the month...."

Title: Php add calendar months to a date

Body:
I would like to add some calendar month to a date. I have done in javascript, but I would make the same function in Php (I'm newer).
This is javascript code:

var date = '2017-08-30';
var addMonth=6;
var arrDate = date.split("-");
var dateSrt = new Date(date);
var newSrvDate = new Date(dateSrt.getTime());

newSrvDate.setMonth(dateSrt.getMonth() + (addMonth), arrDate[2]);
if (newSrvDate.getMonth() > (dateSrt.getMonth() + (addMonth)) % 12) {
    newSrvDate.setDate(0);
}
srvDay = new Date(newSrvDate.getFullYear(), newSrvDate.getMonth() , newSrvDate.getDate());
alert("Start:"+dateSrt);
alert("End:"+srvDay);

In this case if I add 6 months to 2017-08-30 will be 2018-02-30, but it doesn't exist, so it become 2018-03-02.
I would like that if the date exist ok, in other case the last day of the month...

I hope I'm clear... the code work perfectly in javascript, but I can not reproduce it in php

Any suggestions ere welcome

Body:
Check date with checkdate() if valid date or not in  Gregorian dates. And then if not exist then subtract 1 day (24 hours) from the date and again check exist or not. Just like as in following code without using any class (plain PHP).

Here you JS equivalent code in PHP.

$date = '2017-08-30';
$newDate = strtotime($date)+6*30*24*60*60;
$exploded = explode('-',$date);
$month = $exploded[1];
$year = $exploded[0];
$day = $exploded[2];

$new_month = $exploded[1]+6;
if($new_month>12){
    $month = $new_month-12;
    $year = $year+1;
}
else{
    $month = $new_month;
}
echo $year."-".$month."-".$day;

//Function to check date recursively.............
function check_date($year,$month,$day){
    if(!checkdate($month,$day,$year)){
        $day = $day-1;
        return check_date($year,$month,$day);
    }
    else{
        return $year."-".$month."-".$day;
    }
}

$final_date = check_date($year,$month,$day);
echo date("Y-m-d",strtotime($final_date));

But I would recommend you to look at into DateTIme class and also look date().

Note: This is the code where the day of the month will be preserved and answer for you question "I would like that if the date exist ok, in other case the last day of the month...."


问:
Print a string (up to 10 chars) as a diamond
I need to print a string (up to 10 chars) as a diamond.

Well, I tried for almost 2-3 hours now to solve it and I'm still having many problems.

Here's the code: it works for outputs 'a', 'abc', 'abcde'. which means only works for strings with length of 1,3,5. and also, it only prints the first half of the diamond.

Any help is highly appreciated.

import java.util.Scanner;

```<code>public class MyFirstClass1
{
    public static void main(String[] args)
    {
        int halfSize;
        int p = 0;
        String message;
        System.out.println("Please enter a string: ");
        Scanner input = new Scanner(System.in);

        message = input.nextLine();
        //System.out.println((int)Math.ceil(message.length() / 2) + 1);
        halfSize = message.length() / 2;
         for (int i = 1; i <= message.length(); i++) {
             //Print spaces
              for (int k = 0; k < halfSize; k++)
                System.out.print(" ");
              halfSize--;

              System.out.print("\n");

              if((int)Math.ceil((float)message.length() / 2) + 1 >= p)
              {
              for (int j = 0; j < p + 1; j++)
                  System.out.print(message.charAt(j));
              }
              p+=2;
           }

    }
}
</code>```

答:
I think the code may be easier to read if you use a recursive function here. That will also be a good learning exercise for you to understand recursion. Like so:</p>

```<code>public static void printDiamond(String message) {
    diamondAbove(message, " ");
    System.out.println(message);
    diamondBelow(message, " ");
}
public static void diamondAbove(String below, String padding) {
    if(below.length() > 2) {
        String current = below.substring(0, below.length()-2);
        diamondAbove(current, padding + " ");
        System.out.println(padding + current);
    }
}
public static void diamondBelow(String above, String padding) {
    if(above.length() > 2) {
        String current = above.substring(0, above.length()-2);
        System.out.println(padding + current);
        diamondBelow(current, padding + " ");
    }
}
</code>```

Body:
I need to print a string (up to 10 chars) as a diamond.

Well, I tried for almost 2-3 hours now to solve it and I'm still having many problems.

Here's the code: it works for outputs 'a', 'abc', 'abcde'. which means only works for strings with length of 1,3,5. and also, it only prints the first half of the diamond.

Any help is highly appreciated.

import java.util.Scanner;

public class MyFirstClass1
{
    public static void main(String[] args)
    {
        int halfSize;
        int p = 0;
        String message;
        System.out.println("Please enter a string: ");
        Scanner input = new Scanner(System.in);

        message = input.nextLine();
        //System.out.println((int)Math.ceil(message.length() / 2) + 1);
        halfSize = message.length() / 2;
         for (int i = 1; i <= message.length(); i++) {
             //Print spaces
              for (int k = 0; k < halfSize; k++)
                System.out.print(" ");
              halfSize--;

              System.out.print("\n");

              if((int)Math.ceil((float)message.length() / 2) + 1 >= p)
              {
              for (int j = 0; j < p + 1; j++)
                  System.out.print(message.charAt(j));
              }
              p+=2;
           }

    }
}

Body:
I think the code may be easier to read if you use a recursive function here. That will also be a good learning exercise for you to understand recursion. Like so:

public static void printDiamond(String message) {
    diamondAbove(message, " ");
    System.out.println(message);
    diamondBelow(message, " ");
}
public static void diamondAbove(String below, String padding) {
    if(below.length() > 2) {
        String current = below.substring(0, below.length()-2);
        diamondAbove(current, padding + " ");
        System.out.println(padding + current);
    }
}
public static void diamondBelow(String above, String padding) {
    if(above.length() > 2) {
        String current = above.substring(0, above.length()-2);
        System.out.println(padding + current);
        diamondBelow(current, padding + " ");
    }
}


问:
jQuery filter to select first two and then next two
I have the following list:

```<code><li class="list one" data-number="2"></li>
<li class="list one" data-number="2"></li>
<li class="list two" data-number="3"></li>
<li class="list two" data-number="7"></li>
</code>```

And I need to pass each value from data-number attribute to a variable based on the list class.

I have these functions for that:

```<code>var list_one = 0;
var list_two = 0;

$(".one").each(function (i, val) {
  var number = $(this).data('number')
  list_one = list_one + parseInt(number); // Gives 4
});

$(".two").each(function (i, val) {
  var number = $(this).data('number')
  list_two = list_two + parseInt(number); // Gives 10
});
</code>```

But as the list grows, this becomes a long and messy code. What's the best way to get the values from the first two li, and then the two next, etc and pass the sum to the variable?

The list will always have this structure, so I don't need to concider that the number of lis with each class will vary.

答:
I believe this will work, it saves a sum of every two numbers. So if you have 20 elements, listValues will have a length of 10 </p>

```<code>var listValues = [];
$('li.list').each(function(i, val){
   if (i % 2 == 0) {
       listValues[] = parseInt($(this).data('number'));
   } else {
       listValues[listValues.length - 1] += parseInt($(this).data('number'));
   }
});
</code>```

Body:
I have the following list:

And I need to pass each value from data-number attribute to a variable based on the list class.

I have these functions for that:

var list_one = 0;
var list_two = 0;

$(".one").each(function (i, val) {
  var number = $(this).data('number')
  list_one = list_one + parseInt(number); // Gives 4
});

$(".two").each(function (i, val) {
  var number = $(this).data('number')
  list_two = list_two + parseInt(number); // Gives 10
});

But as the list grows, this becomes a long and messy code. What's the best way to get the values from the first two li, and then the two next, etc and pass the sum to the variable?

The list will always have this structure, so I don't need to concider that the number of lis with each class will vary.

Body:
I believe this will work, it saves a sum of every two numbers. So if you have 20 elements, listValues will have a length of 10

var listValues = [];
$('li.list').each(function(i, val){
   if (i % 2 == 0) {
       listValues[] = parseInt($(this).data('number'));
   } else {
       listValues[listValues.length - 1] += parseInt($(this).data('number'));
   }
});


问:
Table output - grouping column headings for PDF table
I'd like to know if there's any way of effectively grouping column headings when outputting a summary table. I realise that's a terrible explanation of what I want so here's an example.

Let's say I have a summary dataframe with 5 columns: projectName, currMonthCost, currMonthRev, prevMonthCost, prevMonthRev. I'd like to have 2 levels to the column headings, with the final output to group the columns by curr/prev - something like:

```<code>               ||     Current    ||    Previous    ||
  projectName  ||  Cost  |  Rev  ||  Cost  |  Rev  ||
_______________||________|_______||________|_______||
               ||        |       ||        |       ||
       x       ||    x   |   x   ||    x   |   x   ||
       y       ||    y   |   y   ||    y   |   y   ||
</code>```

Apologies for the poor attempt at making a table, I'm new here. But hopefully you get the idea.

Is there a package that can handle that? I'm already using formattable but can't find anything obvious in there. I'm happy for it to be a complete botch if there's nothing ready made - it's only summary numbers getting exported to PDF. I just want to avoid having to export to excel to merge cells before PDFing.

Thanks in advance.
James

答:
You need the DT library. It's a quite powerful tool for displaying data frames. In your case, you can customize the table headers using the container parameter:

```<code>library(DT)

df <- data.frame(projectName = c("x", "y"), currMonthCost = c("x", "y"), currMonthRev = c("x", "y"), prevMonthCost = c("x", "y"), prevMonthRev = c("x", "y"))

df
#  projectName currMonthCost currMonthRev prevMonthCost prevMonthRev
#1           x             x            x             x            x
#2           y             y            y             y            y

sketch = htmltools::withTags(table(
      class = 'display',
      thead(
          tr(
              th(rowspan = 2, 'projectName'),
              th(colspan = 2, 'Current'),
              th(colspan = 2, 'Previous')
          ),
          tr(
              lapply(rep(c('Cost', 'Rev'), 2), th)
          )
      )
  ))

datatable(df, container = sketch, rownames = F)
</code>```

Body:
I'd like to know if there's any way of effectively grouping column headings when outputting a summary table. I realise that's a terrible explanation of what I want so here's an example.

Let's say I have a summary dataframe with 5 columns: projectName, currMonthCost, currMonthRev, prevMonthCost, prevMonthRev. I'd like to have 2 levels to the column headings, with the final output to group the columns by curr/prev - something like:

               ||     Current    ||    Previous    ||
  projectName  ||  Cost  |  Rev  ||  Cost  |  Rev  ||
_______________||________|_______||________|_______||
               ||        |       ||        |       ||
       x       ||    x   |   x   ||    x   |   x   ||
       y       ||    y   |   y   ||    y   |   y   ||

Apologies for the poor attempt at making a table, I'm new here. But hopefully you get the idea.

Is there a package that can handle that? I'm already using formattable but can't find anything obvious in there. I'm happy for it to be a complete botch if there's nothing ready made - it's only summary numbers getting exported to PDF. I just want to avoid having to export to excel to merge cells before PDFing.

Thanks in advance.
James

Body:
You need the DT library. It's a quite powerful tool for displaying data frames. In your case, you can customize the table headers using the container parameter:

library(DT)

df <- data.frame(projectName = c("x", "y"), currMonthCost = c("x", "y"), currMonthRev = c("x", "y"), prevMonthCost = c("x", "y"), prevMonthRev = c("x", "y"))

df
#  projectName currMonthCost currMonthRev prevMonthCost prevMonthRev
#1           x             x            x             x            x
#2           y             y            y             y            y

sketch = htmltools::withTags(table(
      class = 'display',
      thead(
          tr(
              th(rowspan = 2, 'projectName'),
              th(colspan = 2, 'Current'),
              th(colspan = 2, 'Previous')
          ),
          tr(
              lapply(rep(c('Cost', 'Rev'), 2), th)
          )
      )
  ))

datatable(df, container = sketch, rownames = F)


问:
Switching to another UIView, within TabBar
Here is my app setup.

TabBar App with three tab items, tabs 2 and 3 are irrelevant

The TabBarController is located within MainWindow.xib

In interface builder for MainWindow.xib, within the TabBarController
i have the seperate viewControllers for each tab.
Then a view for each view controller underneath ( this can been seen when viewing the object in list view)

The application loads and displays the first tab.
I want to be able to have a button in the view of the first tab that can be clicked that will then animate the following:
the current view fading out
a new view fading in within the SAME tab.
Would the new view require a new viewcontroller or just an additional view under the view controller? or can i create a new view controller and load that with its view?

how would i go about this? just the method is needed.

How would i go about this?  Thanks

EDIT

my interface builder list looks like this

Where should i place this new view?

答:
You don't need the additional view controller. Just add additional view in current controller's view and that will be good enough. When user touch up on button make animation that will adjust transparency of views for desired duration. After animation is finished set transparent view as hidden so it won't capture the user actions.

```<code>@interface NewsletterViewController {
  IBOutlet UIView *view1;
  IBOUtlet UIView *view2;
}
</code>```

In interface builder, add this views to NewsletterViewController->View and connect them with these outlets.

Some code for animation setup:

```<code>[UIView beginAnimations: @"Fade" context: nil];
[UIView setAnimationDuration: 0.5];
[UIView setAnimationDelegate: self];
[UIView setAnimationDidStopSelector: @selector(onFadeFinished)];
view1.alpha = 0;
view2.alpha = 1
[UIView commitAnimations];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You don't need the additional view controller. Just add additional view in current controller's view and that will be good enough. When user touch up on button make animation that will adjust transparency of views for desired duration. After animation is finished set transparent view as hidden so it won't capture the user actions.

@interface NewsletterViewController {
  IBOutlet UIView *view1;
  IBOUtlet UIView *view2;
}

In interface builder, add this views to NewsletterViewController->View and connect them with these outlets.

Some code for animation setup:

[UIView beginAnimations: @"Fade" context: nil];
[UIView setAnimationDuration: 0.5];
[UIView setAnimationDelegate: self];
[UIView setAnimationDidStopSelector: @selector(onFadeFinished)];
view1.alpha = 0;
view2.alpha = 1
[UIView commitAnimations];


问:
NPE when calling mock
I have just started with testing and I'm also using MVP pattern in my android apps.

Currently I have a presenter which uses the following android code to test if an email address is valid :

```<code> android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()
</code>```

Since it's not possible to test it with a local JVM unit test I decided to hide it behind an interface :

```<code>public interface EmailValidator {

   boolean isValidEmail(CharSequence target);

}
</code>```

and here's the implementation :

```<code>public class EmailValidatorImpl implements EmailValidator {

@Override
public boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

}
</code>```

So now my test code is :

public class SignUpPresenterTest {

```<code>@Mock
private SignUpMVP.View view;

@Mock
private EmailValidator validator;

private SignUpPresenter presenter;

private String email = "name@gmail.com";
private String password = "ABCDabcd";
private String username = "username";

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    presenter = new SignUpPresenter(view);
}

@Test
public void onButtonSignUpClicked() throws Exception {
    when(validator.isValidEmail(email))
            .thenReturn(true);

    presenter.onButtonSignUpClicked(email, password, username);

    verify(view).executeSignUpService();
}

}
</code>```

and now I'm getting a NPE when the code above calls : EmailValidatorImpl.isValidEmail()

```<code>java.lang.NullPointerException
at com.example.signup.helpers.EmailValidatorImpl.isValidEmail(EmailValidatorImpl.java:20)
at com.example.signup.SignUpPresenter.showErrors(SignUpPresenter.java:67)
at com.example.signup.SignUpPresenter.onButtonSignUpClicked(SignUpPresenter.java:25)
at com.example.signup.SignUpPresenterTest.onButtonSignUpClicked(SignUpPresenterTest.java:43)
</code>```

and my questions are : isn't this how I Should use Mockito ? Is there anything I can do to test my code and avoid NPE ?

答:
You should try with this, because you need to provide a real implementation of your interface</p>

```<code>@InjectMocks
private EmailValidator validator = new EmailValidatorImpl();
</code>```

Title: NPE when calling mock

Body:
I have just started with testing and I'm also using MVP pattern in my android apps.

Currently I have a presenter which uses the following android code to test if an email address is valid :

 android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()

Since it's not possible to test it with a local JVM unit test I decided to hide it behind an interface :

public interface EmailValidator {

   boolean isValidEmail(CharSequence target);

}

and here's the implementation :

public class EmailValidatorImpl implements EmailValidator {

@Override
public boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

}

So now my test code is :

public class SignUpPresenterTest {

@Mock
private SignUpMVP.View view;

@Mock
private EmailValidator validator;

private SignUpPresenter presenter;

private String email = "name@gmail.com";
private String password = "ABCDabcd";
private String username = "username";

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    presenter = new SignUpPresenter(view);
}

@Test
public void onButtonSignUpClicked() throws Exception {
    when(validator.isValidEmail(email))
            .thenReturn(true);

    presenter.onButtonSignUpClicked(email, password, username);

    verify(view).executeSignUpService();
}

}

and now I'm getting a NPE when the code above calls : EmailValidatorImpl.isValidEmail()

java.lang.NullPointerException
at com.example.signup.helpers.EmailValidatorImpl.isValidEmail(EmailValidatorImpl.java:20)
at com.example.signup.SignUpPresenter.showErrors(SignUpPresenter.java:67)
at com.example.signup.SignUpPresenter.onButtonSignUpClicked(SignUpPresenter.java:25)
at com.example.signup.SignUpPresenterTest.onButtonSignUpClicked(SignUpPresenterTest.java:43)

and my questions are : isn't this how I Should use Mockito ? Is there anything I can do to test my code and avoid NPE ?

Body:
You should try with this, because you need to provide a real implementation of your interface

@InjectMocks
private EmailValidator validator = new EmailValidatorImpl();


问:
JavaScript Nesting For Loops
I have the following code where I fail to understand some parts:

```<code>var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
 for (var j=0; j < arr[i].length; j++) {
  console.log(arr[i][j]);
  }
}
</code>```

What does arr[i] mean? I have been told that arr[i] itself is an array. How is that? And What is happening in the arr[i][j] part?

答:
```<code>var arr = [ [1,2], [3,4], [5,6]];
</code>```

What you have is a multidimensional array.  This means that it is an array with arrays inside of it.

```<code>for (var i=0; i < arr.length; i++) {
</code>```

This means that while i is less than the length of arr (in this example 3, since the items inside of it are [1,2], [3,4], and [5,6] which adds up to a total of 3 items) do what ever is in the for statement and once you finish add 1 to i.

```<code>for (var j=0; j < arr[i].length; j++) {
</code>```

Same as above but when we are getting the length arr[i].  This means that whatever i is, look at the item in arr that is at that position.  So when i = 0, arr[i] = [1,2].  when i = 1, arr[i] = [3,4].

```<code>console.log(arr[i][j]);
</code>```

Write to the console the item found at position j from the array at position i in arr.  So, if i = 0 and j = 0, the console would read 1.  This is because arr at 0 is [1, 2] and the item at the 0 position in that array is 1.  if i = 0 and j = 1 it would print 2.  If i = 1 and j = 0 the console will read 3.

Hope this explain everything to you clearly.

Title: JavaScript Nesting For Loops

Body:
I have the following code where I fail to understand some parts:

var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
 for (var j=0; j < arr[i].length; j++) {
  console.log(arr[i][j]);
  }
}

What does arr[i] mean? I have been told that arr[i] itself is an array. How is that? And What is happening in the arr[i][j] part?

Body:
var arr = [ [1,2], [3,4], [5,6]];

What you have is a multidimensional array.  This means that it is an array with arrays inside of it.

for (var i=0; i < arr.length; i++) {

This means that while i is less than the length of arr (in this example 3, since the items inside of it are [1,2], [3,4], and [5,6] which adds up to a total of 3 items) do what ever is in the for statement and once you finish add 1 to i.

for (var j=0; j < arr[i].length; j++) {

Same as above but when we are getting the length arr[i].  This means that whatever i is, look at the item in arr that is at that position.  So when i = 0, arr[i] = [1,2].  when i = 1, arr[i] = [3,4].

console.log(arr[i][j]);

Write to the console the item found at position j from the array at position i in arr.  So, if i = 0 and j = 0, the console would read 1.  This is because arr at 0 is [1, 2] and the item at the 0 position in that array is 1.  if i = 0 and j = 1 it would print 2.  If i = 1 and j = 0 the console will read 3.

Hope this explain everything to you clearly.


问:
How do I correctly work with char pointer to array in C++?
I am trying to pick up my C++; I have basic understanding of pointers and references; but when it comes to char pointer to array, it seems nothing works for me.

I have a small piece of codes here (omitted include and namespace statements), I have included my questions as comments below:

I have gone through at least 5 other questions on SO to try to understand it; but those answers didn't the answer I expected and to the extent that could help understand the actual issue there.

Could you kindly explain the problems I commented below with a bit of depth from the surface (so please don't dive into it directly)?

```<code>int main(){

    // 1 this is a char pointer to a char;
    char * c = new char;
    *c ='A';
    cout << c << endl; // this gives me memory address;
    cout << *c << endl;// this gives me the value in the memory address;

    // 2 this is a char array initialised to value "world";
    char d[6] = "world";
    cout << d[0] << endl; // this gives me the first element of char array;

    // 3 this is char pointer to char array (or array of char pointers)?
    char * str = new char[6];
    for(int i=0;i<6;i++){ //
        str[i]=d[i];     // are we assigning the memory address (not value) of respective elements here?
    }                   // can I just do: *str = "world"; what's the difference between initialising with value
                       // and declaring the pointer and then assign value?

    char * strr = "morning";

    char b[6] = "hello";

    cout << b << endl;
    cout << (*str)[i] << endl; // why? error: subscripts requires array or pointer type
    cout << str[1] << endl;
    cout << (*strr)[1] << endl; // why? error: subscripts requires array or pointer type

}
</code>```

答:
// 1 this is a char pointer to a char;

Right.

// 2 this is a char array initialised to value "world";

Right, "world\0" is created by the compiler and is put in the read-only memory area of the program. Note that this is called a string literal. Then the string is copied over to the char array d.

// 3 this is char pointer to char array (or array of char pointers)?

That's a char pointer yes, a pointer to a single char.

// are we assigning the memory address (not value) of respective
  elements here?

No, you're assigning the values of the elements. This is allowed because str[i] is the same as *(str + i) so you can use the same "array style" access with the pointer str. You're looping over the individual chars you have allocated with new and are assigning them the value of the chars in the char array d.

// why? error: subscripts requires array or pointer type

Because you already dereference str (which is pointing at the start of the 6 element char array) with * which gives you a char, then you try to use that char like an array with [1] which makes no sense. *str would give you 'w' (the first element). And str[1] would give you *(str + 1) which is 'o' (the second element), don't double up.

A small-big side note, string literals are of type const char[], not char[], they're placed in read only memory and thus they can not be altered by the program (don't write to them).

```<code>char * strr = "morning";
</code>```

This is very very bad, it treats a const char[] as a char[], this has been deprecated in the standard for a while now and according to the current standard this is even illegal, yet compilers still allow it for some reason.

Because compilers allow this you could get some nasty situations like trying to modify the string literal:

```<code>char * strr = "morning";
strr[0] = 'w'; // change to "worning"
</code>```

This will attempt to write to read-only memory, which is undefined behaviour and will probably/hopefully get you a segmentation fault. Long story short, use the appropriate type to have the compiler stop you before the code reaches runtime:

```<code>const char * strr = "morning";
</code>```

side side note : don't forget to delete anything you allocated with new.

Body:
I am trying to pick up my C++; I have basic understanding of pointers and references; but when it comes to char pointer to array, it seems nothing works for me.

I have a small piece of codes here (omitted include and namespace statements), I have included my questions as comments below:

I have gone through at least 5 other questions on SO to try to understand it; but those answers didn't the answer I expected and to the extent that could help understand the actual issue there.

Could you kindly explain the problems I commented below with a bit of depth from the surface (so please don't dive into it directly)?

int main(){

    // 1 this is a char pointer to a char;
    char * c = new char;
    *c ='A';
    cout << c << endl; // this gives me memory address;
    cout << *c << endl;// this gives me the value in the memory address;

    // 2 this is a char array initialised to value "world";
    char d[6] = "world";
    cout << d[0] << endl; // this gives me the first element of char array;

    // 3 this is char pointer to char array (or array of char pointers)?
    char * str = new char[6];
    for(int i=0;i<6;i++){ //
        str[i]=d[i];     // are we assigning the memory address (not value) of respective elements here?
    }                   // can I just do: *str = "world"; what's the difference between initialising with value
                       // and declaring the pointer and then assign value?

    char * strr = "morning";

    char b[6] = "hello";

    cout << b << endl;
    cout << (*str)[i] << endl; // why? error: subscripts requires array or pointer type
    cout << str[1] << endl;
    cout << (*strr)[1] << endl; // why? error: subscripts requires array or pointer type

}

Body:
// 1 this is a char pointer to a char;

Right.

// 2 this is a char array initialised to value "world";

Right, "world\0" is created by the compiler and is put in the read-only memory area of the program. Note that this is called a string literal. Then the string is copied over to the char array d.

// 3 this is char pointer to char array (or array of char pointers)?

That's a char pointer yes, a pointer to a single char.

// are we assigning the memory address (not value) of respective
  elements here?

No, you're assigning the values of the elements. This is allowed because str[i] is the same as *(str + i) so you can use the same "array style" access with the pointer str. You're looping over the individual chars you have allocated with new and are assigning them the value of the chars in the char array d.

// why? error: subscripts requires array or pointer type

Because you already dereference str (which is pointing at the start of the 6 element char array) with * which gives you a char, then you try to use that char like an array with [1] which makes no sense. *str would give you 'w' (the first element). And str[1] would give you *(str + 1) which is 'o' (the second element), don't double up.

A small-big side note, string literals are of type const char[], not char[], they're placed in read only memory and thus they can not be altered by the program (don't write to them).

char * strr = "morning";

This is very very bad, it treats a const char[] as a char[], this has been deprecated in the standard for a while now and according to the current standard this is even illegal, yet compilers still allow it for some reason.

Because compilers allow this you could get some nasty situations like trying to modify the string literal:

char * strr = "morning";
strr[0] = 'w'; // change to "worning"

This will attempt to write to read-only memory, which is undefined behaviour and will probably/hopefully get you a segmentation fault. Long story short, use the appropriate type to have the compiler stop you before the code reaches runtime:

const char * strr = "morning";

side side note : don't forget to delete anything you allocated with new.


问:
Julia: Recompiling stale cache file?
The following message appears everytime I attempt to use 'Gadfly', 'Bio', or several other packages (I'm using 'Bio' in the example):

```<code>julia> using Bio
INFO: Recompiling stale cache file C:\Users\CaitlinG\emacs251\.julia\lib\v0.5\Di
stributions.ji for module Distributions.
INFO: Recompiling stale cache file C:\Users\CaitlinG\emacs251\.julia\lib\v0.5\Bi
o.ji for module Bio.
</code>```

Julia 0.5.1 (all packages updated)
Windows 10 (fully updated)
Emacs 25.1

This is inconvenient since I can only assume it is not a "typical" component of importing a package. Can the issue be resolved by deleting the .julia directory?

Thanks.

答:
Moving my comment to an answer since that appears to have resolved the question:

Julia caches its precompiled output within the .julia/lib folder. If any of the files there are older than the original source, it'll recompile them. It seems like Julia was having trouble overwriting the cache for a few specific packages here, so it was persistently recompiling them.  By deleting the lib folder, you clear out these caches. Julia will recompile all packages, but it should now write them with the correct permissions that will allow them to be overwritten in the future.

Deleting the entire .julia folder is a much more drastic step that risks losing edits you've made to packages, and you'd need to re-install all the packages you've added.

Title: Julia: Recompiling stale cache file?

Body:
The following message appears everytime I attempt to use 'Gadfly', 'Bio', or several other packages (I'm using 'Bio' in the example):

julia> using Bio
INFO: Recompiling stale cache file C:\Users\CaitlinG\emacs251\.julia\lib\v0.5\Di
stributions.ji for module Distributions.
INFO: Recompiling stale cache file C:\Users\CaitlinG\emacs251\.julia\lib\v0.5\Bi
o.ji for module Bio.

Julia 0.5.1 (all packages updated)
Windows 10 (fully updated)
Emacs 25.1

This is inconvenient since I can only assume it is not a "typical" component of importing a package. Can the issue be resolved by deleting the .julia directory?

Thanks.


问:
ZipArchive generating temp files but not writing content and no error given
I'm using PHPExcel to generate Excel files but it's not working. I have debugged down to this piece of code:

```<code>$objZip = new ZipArchive();

$ro = new ReflectionObject($objZip);
$zipOverWrite = $ro->getConstant('OVERWRITE');
$zipCreate = $ro->getConstant('CREATE');

// Try opening the ZIP file
// Debug result: both open() return true here
if ($objZip->open($pFilename, $zipOverWrite) !== true) {
    if ($objZip->open($pFilename, $zipCreate) !== true) {
        throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing.");
    }
}

// Debug result: $objZip->close() would return true here

// Add [Content_Types].xml to ZIP file
// Debug result: it stops running on this line, no errors or exceptions
$objZip->addFromString('[Content_Types].xml', ...);
</code>```

The line $objZip->addFromString() generates temp files in the directory, but it seems unable to write into these files somehow, as they are empty:

```<code>-rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.0BRqEn
-rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.3Hbl1n
-rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.5otErm
...
</code>```

Presumably it's a permission issue, but the PHP user www1 has write permission in the directory and fwrite() works well on these temp files as I tried. PHP version is 5.4.16.

Any ideas please?

答: Turned out to be a problem in PHP update. Resolved by restarting the web server.</p>

Body:
I'm using PHPExcel to generate Excel files but it's not working. I have debugged down to this piece of code:

$objZip = new ZipArchive();

$ro = new ReflectionObject($objZip);
$zipOverWrite = $ro->getConstant('OVERWRITE');
$zipCreate = $ro->getConstant('CREATE');

// Try opening the ZIP file
// Debug result: both open() return true here
if ($objZip->open($pFilename, $zipOverWrite) !== true) {
    if ($objZip->open($pFilename, $zipCreate) !== true) {
        throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing.");
    }
}

// Debug result: $objZip->close() would return true here

// Add [Content_Types].xml to ZIP file
// Debug result: it stops running on this line, no errors or exceptions
$objZip->addFromString('[Content_Types].xml', ...);

The line $objZip->addFromString() generates temp files in the directory, but it seems unable to write into these files somehow, as they are empty:

-rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.0BRqEn
-rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.3Hbl1n
-rw-------. 1 www1 www1 0 Mar 27 15:21 test_output_20170327.xlsx.5otErm
...

Presumably it's a permission issue, but the PHP user www1 has write permission in the directory and fwrite() works well on these temp files as I tried. PHP version is 5.4.16.

Any ideas please?


问:
Updating Hudson and plugins
I was wondering which steps are the best to upgrade hudson and the plugins.

I'm running 1.347 at the moment. I once tried to update which resulted into a mess because some plugins were incompatible.

Also i want to delete some plugins is it appropriate to just delete the hpi file? It would be nice to know how other people do this step and in which order.

Should i first upgrade hudson and then plugin by plugin?

And if a plugin breaks something downgrade it again? It seems to be a lot of work.
Or is there any easy way?

Also is it enough to save all the xml configuration files in case something breaks that i can recover?

Thanks in advance.

答:
I usually update Hudson first, then the plugins.

The recent versions of Hudson have some support for this process:

the Hudson 1.376 added downgrade support for the core and plugins.

That means after upgrading a plugin, you have a button which allows you to downgrade to the previous installed version if needed.

the Hudson 1.369 Avoid error with invalid or null primary view, such as in upgrade from older Hudson

And the upcoming Hudson 1.387  will avoid littering HUDSON_HOME with atomic *.xml files, which should make the backup process of critical config files that much easier.

(Currently, with an Hudson 1.386, I see under HUDSON_HOME:

```<code>com.mtvi.plateng.hudson.ldap.LdapMailAddressResolver.xml
config.xml                                                                 hudson.scm.SubversionSCM.xml
de.fspengler.hudson.pview.PViewProjectProperty.xml                         hudson.tasks.Ant.xml
hudson.maven.MavenModuleSet.xml                                            hudson.tasks.Mailer.xml
hudson.model.UpdateCenter.xml                                              hudson.tasks.Maven.xml
hudson.plugins.clearcase.ClearCaseInstallation.xml                         hudson.tasks.Shell.xml
hudson.plugins.clearcase.ClearCaseSCM.xml                                  hudson.triggers.SCMTrigger.xml
hudson.plugins.git.GitTool.xml                                             nodeMonitors.xml
hudson.plugins.sonar.SonarPublisher.xml                                    proxy.xml
hudson.scm.CVSSCM.xml
</code>```

)

Title: Updating Hudson and plugins

Body:
I usually update Hudson first, then the plugins.

The recent versions of Hudson have some support for this process:

the Hudson 1.376 added downgrade support for the core and plugins.

That means after upgrading a plugin, you have a button which allows you to downgrade to the previous installed version if needed.

the Hudson 1.369 Avoid error with invalid or null primary view, such as in upgrade from older Hudson

And the upcoming Hudson 1.387  will avoid littering HUDSON_HOME with atomic *.xml files, which should make the backup process of critical config files that much easier.

(Currently, with an Hudson 1.386, I see under HUDSON_HOME:

com.mtvi.plateng.hudson.ldap.LdapMailAddressResolver.xml
config.xml                                                                 hudson.scm.SubversionSCM.xml
de.fspengler.hudson.pview.PViewProjectProperty.xml                         hudson.tasks.Ant.xml
hudson.maven.MavenModuleSet.xml                                            hudson.tasks.Mailer.xml
hudson.model.UpdateCenter.xml                                              hudson.tasks.Maven.xml
hudson.plugins.clearcase.ClearCaseInstallation.xml                         hudson.tasks.Shell.xml
hudson.plugins.clearcase.ClearCaseSCM.xml                                  hudson.triggers.SCMTrigger.xml
hudson.plugins.git.GitTool.xml                                             nodeMonitors.xml
hudson.plugins.sonar.SonarPublisher.xml                                    proxy.xml
hudson.scm.CVSSCM.xml

)


问:
How can I get a Table View to register taps when each cell has an Image View covering it?
I've been trying to create table view cells each with a UIImageView serving as a background for them. However, when I tap on each cell the table view will not register the click and will not transition to the view controller I have hooked up, even while I'm using the didSelectRowAtIndexPath function.

I realize it's probably an issue with the ImageView obstructing the table views ability to register the cell tap. The cells will transition however when I drag my finger/mouse on it from left to right, just not on taps. I tried to use a Tap Gesture Recognizer on the Image View however it only worked for the cell at the very top and not all of them. How do I tackle this issue?

Here is an image of the table view cells so you have an idea of what I'm working with: http://imgur.com/a/Ku4uD. Thank you!

答:
If you uncheck User Interaction Enabled on your Image View, the problem should be solved. When running into a problem always check the user interaction of the most child view and work your way up.

One trick I have also learned is to create a subclass of a child and override touchesShouldCancel like so:

```<code>override func touchesShouldCancel(in view: UIView) -> Bool {
    print("touchesShouldCancel")
    //Run extra code that you want when the user selects this view
    //then still retrieve the tap by its parent.
    return false
}
</code>```

I am unsure of exactly what your problem is, but I would delete whatever segue that you have, add a new one by dragging from the yellow circle on the left side of the center portion of the top of your tableView ViewController inside the storyboard, to the viewController that you desire it to segue to. Give the segue an appropriate identifier, and then inside your tableView class under tableView didSelectRow add performSegue(withIdentifier: "ChosenIdentifier", sender: indexPath)

Then in prepare forSegue add in:

```<code>if let vc = sender.destination as? TheViewControllerYouAreSegueingTo {
    if let indexPath = sender as? IndexPath {
        vc.variableIdentifyingWhatCellWasClicked = indexPath.row
    }
}
</code>```

with whatever adjustment is needed to meet your specific needs.

Body:
If you uncheck User Interaction Enabled on your Image View, the problem should be solved. When running into a problem always check the user interaction of the most child view and work your way up.

One trick I have also learned is to create a subclass of a child and override touchesShouldCancel like so:

override func touchesShouldCancel(in view: UIView) -> Bool {
    print("touchesShouldCancel")
    //Run extra code that you want when the user selects this view
    //then still retrieve the tap by its parent.
    return false
}

I am unsure of exactly what your problem is, but I would delete whatever segue that you have, add a new one by dragging from the yellow circle on the left side of the center portion of the top of your tableView ViewController inside the storyboard, to the viewController that you desire it to segue to. Give the segue an appropriate identifier, and then inside your tableView class under tableView didSelectRow add performSegue(withIdentifier: "ChosenIdentifier", sender: indexPath)

Then in prepare forSegue add in:

if let vc = sender.destination as? TheViewControllerYouAreSegueingTo {
    if let indexPath = sender as? IndexPath {
        vc.variableIdentifyingWhatCellWasClicked = indexPath.row
    }
}

with whatever adjustment is needed to meet your specific needs.


问:
WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"
I'm having a problem using a WCF call from a Windows service to my WCF service running on my web server.  This call has been working for a number of weeks, but then stopped working all of a sudden, and has not worked since.

The exception I'm getting is:

General Error Occurred System.ServiceModel.CommunicationException: An error occurred while making the HTTP request

and then it says

This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.

The security I'm using on both ends is wsHttpBinding, without any kind of encryption.  It also is just using HTTP - not HTTPS, so I'm not sure why it's complaining about HTTPS.

The rest of the inner exception stack is:

SystemNet.WebException: The underlying connection was closed: An unexpected error occurred on a send.
  ---> System.IO.IOException: Unable to write data to the transport connection: An invalid argument was supplied.
  ---> System.Net.Sockets.SocketException: An invalid argument was supplied at System.Net.Sockets.Socket.MultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.MultipleWrite(BufferOffsetSize[] buffers)

I should also note that the point in my program where this occurs is on the "Execute" line of the call to the web service - that is, right as soon as I call the web service and pass it the wrapped up DataContract object, it blows up.

All this service is doing is getting passed a large amount of XML (passed as a .NET object to the call on the client side), which it then does some work with.  Probably about 100-200k of XML is being transmitted.  I've raised the limits for the data sizes on both ends to over 6 megs, but that didn't seem to help.

Any ideas?

Some more information on this issue:

When we duplicate the client environment locally, we find that we cannot upload large amounts of XML unless we make the following changes:
1. On the server, set the "maxRequestLength" to 100 MB (way higher than we are sending)
2. On the client, we set the value of maxItemsInObjectGraph under the dataContractSerializer tag to "2147483646".

With these changes, our local installation uploads successfully.  However, the client's install on their server still fails.  What interesting to note is that once we made the maxRequestLength value change on the server, our test installation started throwing an error specifically relating to the maxItemsInObjectGraph setting.  Whereas on our client's server, still the original "HTTP.sys" error is happening.

As I noted before, we are not using SSL at all, and there are 2 other web services calls that execute and upload XML in the same way.  However, since the non-working service call transmits more data, this appears to be a size issue.

However, if the issue the client is having were the same one our test install had, I don't get why the client error message wouldn't be related to the ObjectGraph error.

Is it possible that we're just getting the generic "invalid parameter" "HTTP.sys" error for every possible error on the client (ie. it's really getting the objectGraph error too, but just isn't showing it?)

答:
We had the same issue and, in our case, it was resolved by reinstalling the certificate and creating the binding again.
What lead us there was the fact that even getting a simple png image file on the site give the same error.</p>


答:
using common table expression with row_number() to select the top 1 per group of string.

```<code>;with cte as (
  select *
    , rn = row_number() over (partition by string order by id)
  from t1
)

select count(*)
  from cte
    inner join t2
      on cte.id = t2.table_1id
     and cte.rn = 1
</code>```

using a subquery instead of the cte:

```<code>select count(*)
  from (
    select *
      , rn = row_number() over (partition by string order by id)
    from t1
  ) sub
    inner join t2
      on sub.id = t2.table_1id
     and sub.rn = 1
</code>```

Title: Select rows where string does not repeat

Body:
I'm not sure how to phrase this, but I have two tables that I use INNER JOIN on to count the number of records I have. This works fine but the problem is that I have some rows in table1 where some of the records have a string that can appear in another record. Something like this:

table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
03    aaa                03    03           1
04    ccc                04    04           4
05    bbb                05    05           2
...                      ...

My query looks like this:

SELECT COUNT(*) FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id

This query works fine, but I want to be able to get distinct values. So my query should bring me back only these records:

table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
04    ccc                04    04           4
...                      ...

As you can see, it doesn't show any additional records where they share the same string. What would I write after or before my INNER JOIN? Any help would be appreciated.

Body:
using common table expression with row_number() to select the top 1 per group of string.

;with cte as (
  select *
    , rn = row_number() over (partition by string order by id)
  from t1
)

select count(*)
  from cte
    inner join t2
      on cte.id = t2.table_1id
     and cte.rn = 1

using a subquery instead of the cte:

select count(*)
  from (
    select *
      , rn = row_number() over (partition by string order by id)
    from t1
  ) sub
    inner join t2
      on sub.id = t2.table_1id
     and sub.rn = 1


问:
Facebook API Private Message image expired - How to get new image ? URL signature expired
I'm helping maintain an app that integrates with Facebook, and has lots of archived links to old private message images. Sometimes these images expire, and we go to facebook and request a new image. This works 90% of the time.

About 10% of the time we're getting back a response that we can't tell what the new image is.

What's the proper way to request a new url for an expired Facebook Private Message image, preferably using v2.5 or newer of the Graph API?

Currently we're doing a GET request to Facebook's Graph API using the message id of the private message like so:

https://graph.facebook.com/v2.3/m_mid.XXXXXXXXX:YYYYYYYYY

and that gives us a response that has a bunch of attachments in it. For 90% of use cases, there's a new attachment that has an url or name field with a new filename that contains the old filename, e.g. old file name being XXX, we'd see a new filename like ....XXXX.... in the url field.

```<code>attachments [url='*%s*']/image_data/url
attachments [name='*%s*']/image_data/url
</code>```

or sometimes

```<code>picture
</code>```

but that doesnt match what we get now, which is a bunch of attachments with no way to map to the new image.

答:
We haven't been able to find a graph API way of doing this, but have the following solutions we're considering:

When there's only one attachment in the response, we just use that one url. This works some of the time, but fails when there's more than one image of course

Save more metadata about the image, at worst case an MD5 of the file. Then compare that to MD5's of the other files until we get the one we want. Instead of an MD5, we could consider using info about the file from a HEAD request. All of this is untested.

Update our old message metadata with new metadata whenever this happens, thus avoiding the problem entirely as new image requests would come from the new metadata.

Body:
I'm helping maintain an app that integrates with Facebook, and has lots of archived links to old private message images. Sometimes these images expire, and we go to facebook and request a new image. This works 90% of the time.

About 10% of the time we're getting back a response that we can't tell what the new image is.

What's the proper way to request a new url for an expired Facebook Private Message image, preferably using v2.5 or newer of the Graph API?

Currently we're doing a GET request to Facebook's Graph API using the message id of the private message like so:

https://graph.facebook.com/v2.3/m_mid.XXXXXXXXX:YYYYYYYYY

and that gives us a response that has a bunch of attachments in it. For 90% of use cases, there's a new attachment that has an url or name field with a new filename that contains the old filename, e.g. old file name being XXX, we'd see a new filename like ....XXXX.... in the url field.

attachments [url='*%s*']/image_data/url
attachments [name='*%s*']/image_data/url

or sometimes

picture

but that doesnt match what we get now, which is a bunch of attachments with no way to map to the new image.


问:
Sending image to Python Backend - Cordova File Transfer
I'm trying to send an image from the client side (Ionic Framework) to my Python Backend (Flask). For some reason, I keep getting Error Code 3 which I understand is a Connection Error, but I'm not sure why.

Client Side Code (AngularJS):

```<code>    $scope.submit = function() {
       if($scope.details.title === '' || $scope.details.price === '' || $scope.details.description === ''
        || $scope.details.category === '') {
            ionicSuperPopup.show("Error!", "Fill out the appropriate fields!", "error");
       } else if($scope.size !== 2) {
          ionicSuperPopup.show("Error!", "You need to upload at least two images.", "error");
       } else {
          /* Post item to server, wait for success, and present success post. */
          //ItemFactory.addItem($scope.details);
          var url = 'http://127.0.0.1:5000/api/item/addItem';
          var name = $scope.details.images[0];
          var options = new FileUploadOptions();
          options.fileKey = 'image',
          options.fileName = name,
          options.chunkedMode = false,
          options.mimeType = 'image/jpg',
          options.params = { 'filename': name };
          options.headers = {
              Connection: "close"
          };

          var ft = new FileTransfer();
          ft.upload($scope.list[0], encodeURI(url), win, fail, options);
      } /* End of 'else' */
   } /* End of 'submit' */
</code>```

$scope.list[0] contains the imageURI of the picture taken.

Backend Code:

```<code>    from flask_restful import reqparse, Resource

    class Item(Resource):
        parser = reqparse.RequestParser(bundle_errors=True) #All arguments must be present

        def post(self):
            Item.parser.add_argument('image', required=True, help="You need images.")
            args = Item.parser.parse_args()
            print("We have: {}".format(args))
</code>```

Is there anything that I'm doing wrong? I feel like I've got everything covered, yet I don't understand why I have an error code 3. Thanks for the help!

答:
So I actually figured out the problem. The image needs to be loaded as a file upload and I used werkzeug's FileStorage to do this:</p>

```<code>  Item.parser.add_argument('file', required=True, help="You need image.", type=werkzeug.datastructures.FileStorage, location='files')
</code>```

Body:
I'm trying to send an image from the client side (Ionic Framework) to my Python Backend (Flask). For some reason, I keep getting Error Code 3 which I understand is a Connection Error, but I'm not sure why.

Client Side Code (AngularJS):

    $scope.submit = function() {
       if($scope.details.title === '' || $scope.details.price === '' || $scope.details.description === ''
        || $scope.details.category === '') {
            ionicSuperPopup.show("Error!", "Fill out the appropriate fields!", "error");
       } else if($scope.size !== 2) {
          ionicSuperPopup.show("Error!", "You need to upload at least two images.", "error");
       } else {
          /* Post item to server, wait for success, and present success post. */
          //ItemFactory.addItem($scope.details);
          var url = 'http://127.0.0.1:5000/api/item/addItem';
          var name = $scope.details.images[0];
          var options = new FileUploadOptions();
          options.fileKey = 'image',
          options.fileName = name,
          options.chunkedMode = false,
          options.mimeType = 'image/jpg',
          options.params = { 'filename': name };
          options.headers = {
              Connection: "close"
          };

          var ft = new FileTransfer();
          ft.upload($scope.list[0], encodeURI(url), win, fail, options);
      } /* End of 'else' */
   } /* End of 'submit' */

$scope.list[0] contains the imageURI of the picture taken.

Backend Code:

    from flask_restful import reqparse, Resource

    class Item(Resource):
        parser = reqparse.RequestParser(bundle_errors=True) #All arguments must be present

        def post(self):
            Item.parser.add_argument('image', required=True, help="You need images.")
            args = Item.parser.parse_args()
            print("We have: {}".format(args))

Is there anything that I'm doing wrong? I feel like I've got everything covered, yet I don't understand why I have an error code 3. Thanks for the help!

Body:
So I actually figured out the problem. The image needs to be loaded as a file upload and I used werkzeug's FileStorage to do this:

  Item.parser.add_argument('file', required=True, help="You need image.", type=werkzeug.datastructures.FileStorage, location='files')