问:
Check if a directory is empty using C on Linux
Is this the right way of checking whether a directory is empty or not in C? Is there a more efficient way to check for an empty directory, especially if it has 1000s of files if not empty?

```<code>int isDirectoryEmpty(char *dirname) {
  int n = 0;
  struct dirent *d;
  DIR *dir = opendir(dirname);
  if (dir == NULL) //Not a directory or doesn't exist
    return 1;
  while ((d = readdir(dir)) != NULL) {
    if(++n > 2)
      break;
  }
  closedir(dir);
  if (n <= 2) //Directory Empty
    return 1;
  else
    return 0;
}
</code>```

If its an empty directory, readdir will stop after the entries '.' and '..' and hence empty if n<=2.

If its empty or doesn't exist, it should return 1, else return 0

Update:

```<code>@c$ time ./isDirEmpty /fs/dir_with_1_file; time ./isDirEmpty /fs/dir_with_lots_of_files
0

real    0m0.007s
user    0m0.000s
sys 0m0.004s

0

real    0m0.016s
user    0m0.000s
sys 0m0.008s
</code>```

Why does it take longer to check for a directory with lots of files as compared to one with just one file?

答:
Maybe this code could help you:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *cmd;
    char *folder = "/tmp";
    int status, exitcode;
    char *format="test $(ls -AU \"%s\" 2>/dev/null | head -1 | wc -l) -ne 0";
    clock_t start, stop;
    int size;

    if(argc == 2)
            folder = argv[1];

    size = strlen(format)+strlen(folder)+1;
    cmd = malloc(size * sizeof(char));

    snprintf(cmd, size, format, folder);
    printf("executing: %s\n", cmd);

    status = system(cmd);
    exitcode = WEXITSTATUS(status);

    printf ("exit code: %d, exit status: %d\n", exitcode, status);

    if (exitcode == 1)
            printf("the folder is empty\n");
    else
            printf("the folder is non empty\n");

    free(cmd);
    return 0;
}
</code>```

I check if the folder is empty using ls -AU folder 2>/dev/null | head -1 | wc -l, to count the files in the folder, if it returns zero the folder is empty else the folder is non empty. The WEXITSTATUS macro, returns the exit code of the executed command. head command doesn't wait until ls finish, just until the condition is fit.

some examples using the find command to generate long file list show that it is really effective

Command without head

```<code>/usr/bin/time -p -v find / -print | wc -l

output
Command being timed: "find / -print"
    User time (seconds): 0.63
    System time (seconds): 1.28
    Percent of CPU this job got: 98%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.94
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 6380
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 3419
    Voluntary context switches: 7
    Involuntary context switches: 140
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Files counted: 1043497
</code>```

Command modified using head

```<code>/usr/bin/time -p -v find / -print | head -1 | wc -l

Command terminated by signal 13
    Command being timed: "find / -print"
    User time (seconds): 0.00
    System time (seconds): 0.00
    Percent of CPU this job got: 100%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 2864
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 136
    Voluntary context switches: 1
    Involuntary context switches: 0
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Files counted: 1
</code>```

As you can see while the first command without "head" tooks 1.28 seconds for execution the command modified with "head" tooks 0 seconds for execution.

Moreover if we measure the execution time of the above core, with and without head we have.

Normal ls:

```<code>/usr/bin/time -p ls -A /var/lib/dpkg/info/
real 0.67
user 0.06
sys 0.06
</code>```

program without head

```<code>/usr/bin/time -p ./empty.exe /var/lib/dpkg/info/
executing: test $(ls -AU "/var/lib/dpkg/info/" 2>/dev/null | wc -l) -ne 0
exit code: 0, exit status: 0
the folder is non empty
real 0.01
user 0.00
sys 0.01
</code>```

program using head

```<code>/usr/bin/time -p ./empty.exe /var/lib/dpkg/info/
executing: test $(ls -AU "/var/lib/dpkg/info/" 2>/dev/null | head -1 | wc -l) -ne 0
exit code: 0, exit status: 0
the folder is non empty
real 0.00
user 0.00
sys 0.00
</code>```

Note: if the folder doesn't exists, or you don't have the correct permissions to access it, this program must print "the folder is empty".

The program was built using: gcc empty.c -o empty.exe

Body:
Is this the right way of checking whether a directory is empty or not in C? Is there a more efficient way to check for an empty directory, especially if it has 1000s of files if not empty?

int isDirectoryEmpty(char *dirname) {
  int n = 0;
  struct dirent *d;
  DIR *dir = opendir(dirname);
  if (dir == NULL) //Not a directory or doesn't exist
    return 1;
  while ((d = readdir(dir)) != NULL) {
    if(++n > 2)
      break;
  }
  closedir(dir);
  if (n <= 2) //Directory Empty
    return 1;
  else
    return 0;
}

If its an empty directory, readdir will stop after the entries '.' and '..' and hence empty if n<=2.

If its empty or doesn't exist, it should return 1, else return 0

Update:

@c$ time ./isDirEmpty /fs/dir_with_1_file; time ./isDirEmpty /fs/dir_with_lots_of_files
0

real    0m0.007s
user    0m0.000s
sys 0m0.004s

0

real    0m0.016s
user    0m0.000s
sys 0m0.008s

Why does it take longer to check for a directory with lots of files as compared to one with just one file?

Body:
Maybe this code could help you:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *cmd;
    char *folder = "/tmp";
    int status, exitcode;
    char *format="test $(ls -AU \"%s\" 2>/dev/null | head -1 | wc -l) -ne 0";
    clock_t start, stop;
    int size;

    if(argc == 2)
            folder = argv[1];

    size = strlen(format)+strlen(folder)+1;
    cmd = malloc(size * sizeof(char));

    snprintf(cmd, size, format, folder);
    printf("executing: %s\n", cmd);

    status = system(cmd);
    exitcode = WEXITSTATUS(status);

    printf ("exit code: %d, exit status: %d\n", exitcode, status);

    if (exitcode == 1)
            printf("the folder is empty\n");
    else
            printf("the folder is non empty\n");

    free(cmd);
    return 0;
}

I check if the folder is empty using ls -AU folder 2>/dev/null | head -1 | wc -l, to count the files in the folder, if it returns zero the folder is empty else the folder is non empty. The WEXITSTATUS macro, returns the exit code of the executed command. head command doesn't wait until ls finish, just until the condition is fit.

some examples using the find command to generate long file list show that it is really effective

Command without head

/usr/bin/time -p -v find / -print | wc -l

output
Command being timed: "find / -print"
    User time (seconds): 0.63
    System time (seconds): 1.28
    Percent of CPU this job got: 98%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.94
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 6380
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 3419
    Voluntary context switches: 7
    Involuntary context switches: 140
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Files counted: 1043497

Command modified using head

/usr/bin/time -p -v find / -print | head -1 | wc -l

Command terminated by signal 13
    Command being timed: "find / -print"
    User time (seconds): 0.00
    System time (seconds): 0.00
    Percent of CPU this job got: 100%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 2864
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 136
    Voluntary context switches: 1
    Involuntary context switches: 0
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Files counted: 1

As you can see while the first command without "head" tooks 1.28 seconds for execution the command modified with "head" tooks 0 seconds for execution.

Moreover if we measure the execution time of the above core, with and without head we have.

Normal ls:

/usr/bin/time -p ls -A /var/lib/dpkg/info/
real 0.67
user 0.06
sys 0.06

program without head

/usr/bin/time -p ./empty.exe /var/lib/dpkg/info/
executing: test $(ls -AU "/var/lib/dpkg/info/" 2>/dev/null | wc -l) -ne 0
exit code: 0, exit status: 0
the folder is non empty
real 0.01
user 0.00
sys 0.01

program using head

/usr/bin/time -p ./empty.exe /var/lib/dpkg/info/
executing: test $(ls -AU "/var/lib/dpkg/info/" 2>/dev/null | head -1 | wc -l) -ne 0
exit code: 0, exit status: 0
the folder is non empty
real 0.00
user 0.00
sys 0.00

Note: if the folder doesn't exists, or you don't have the correct permissions to access it, this program must print "the folder is empty".

The program was built using: gcc empty.c -o empty.exe


来源: stackexchange

问:
Deploy multiple Java apps on a server
I have recently started playing around with Telegram bots. I found a host (digitalocean) that gives me a linux server that is enough for my needs. The tutorial that I read said that I need to run my jar files using through using the screen command.

However, as my app runs, I cannot do anything else on that screen. I can't start another app on it, either. So here comes the question - how can I host 2 java apps on one server?

Thanks for your help!

答:
you can try this:
 nohup java -jar yourapp.jar &</p>

ContentLicense: CC BY-SA 3.0

Title: Deploy multiple Java apps on a server


问:
GSON & Volley => Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
This error drove me crazy I tried using different kind of Volley requests such as JsonArrayRequest and JsonObjectRequest but no luck !!

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Here's the JSON response link => http://www.mocky.io/v2/58df83a80f00005922eaf4e1

Here's my model class

```<code> public class Order {

@SerializedName("status")
@Expose
private String status; //status

@SerializedName("total")
@Expose
private float price; //total

@SerializedName("created_at")
@Expose
private Date time;

@SerializedName("line_items")
@Expose
public List<ItemsNum> lineItems = new ArrayList<ItemsNum>();

@SerializedName("sub_orders")
@Expose
public List<OrdersNum> subOrders = new ArrayList<OrdersNum>();

@SerializedName("shipping_address")
@Expose
public CusAddress cusAdress;

@SerializedName("customer")
@Expose
public Customer customer;

public Order(Customer customer, String status, float price, String cusPicURL, String firstName, String lastName, Date time, List<ItemsNum> lineItems, List<OrdersNum> subOrders, CusAddress cusAdress) {
    this.status = status;
    this.price = price;
    this.customer = customer;
    this.time = time;
    this.lineItems = lineItems;
    this.subOrders = subOrders;
    this.cusAdress = cusAdress;
}

public Date getTime() {
    return time;
}

public void setTime(Date time) {
    this.time = time;
}

public List<ItemsNum> getLineItems() {
    return lineItems;
}

public void setLineItems(List<ItemsNum> lineItems) {
    this.lineItems = lineItems;
}

public List<OrdersNum> getSubOrders() {
    return subOrders;
}

public void setSubOrders(List<OrdersNum> subOrders) {
    this.subOrders = subOrders;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public CusAddress getCusAdress() {
    return cusAdress;
}

public void setCusAdress(CusAddress cusAdress) {
    this.cusAdress = cusAdress;
}

// //////////// Inner-Classes

public class Customer {

    @SerializedName("avatar_url")
    @Expose
    private String cusPicURL; //avatar_url

    @SerializedName("first_name")
    @Expose
    private String firstName; //first_name

    @SerializedName("last_name")
    @Expose
    private String lastName; //last_name

    public String getCusPicURL() {
        return cusPicURL;
    }

    public void setCusPicURL(String cusPicURL) {
        this.cusPicURL = cusPicURL;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

public class CusAddress {

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @SerializedName("address_1")
    @Expose
    public String address;

    @SerializedName("city")
    @Expose
    public String city;

    @SerializedName("state")
    @Expose
    public String state;

    @SerializedName("country")
    @Expose
    public String country;
}

public class ItemsNum {

    @SerializedName("id")
    @Expose
    public Integer id;
}

public class OrdersNum {

    @SerializedName("id")
    @Expose
    public Integer id;
 }
}
</code>```

My Adapter

```<code>  public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public Context context;
private int num;
ArrayList<Order> orders;

public OrdersDataAdapter(ArrayList<Order> orders, Context context) {
    this.orders = orders;

    this.context = context;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);

    return new NewOrderVH(v);

}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Order order = this.orders.get(position);
    final NewOrderVH vh1 = (NewOrderVH) holder;
    vh1.setData(orders.get(position));

}

@Override
public int getItemCount() {
    return orders.size();
}

public class NewOrderVH extends RecyclerView.ViewHolder {

    private ImageView cusPic;
    private TextView cusName;
    private TextView CusAdress;
    private TextView vendorsNum;
    private TextView itemsNum;
    private TextView time;

    public NewOrderVH(View itemView) {
        super(itemView);

        orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
        cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
        cusName = (TextView) itemView.findViewById(R.id.cusName);
        CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
        vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
        itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
        time = (TextView) itemView.findViewById(R.id.time);

    }

    public void setData(final Order data) {

        cusName.setText(data.customer.getFirstName() + "" + data.customer.getLastName());
        Picasso.with(context).load(data.customer.getCusPicURL()).into(cusPic);
        time.setText(data.getTime().getMinutes());
        vendorsNum.setText(data.getSubOrders().size());
        itemsNum.setText(data.getLineItems().size());
        CusAdress.setText(data.cusAdress.getAddress() + "" + data.cusAdress.getCity() + "" + data.cusAdress.getCountry() + "" + data.cusAdress.getState());

    }

}
</code>```

}

Request Method inside a Fragment

```<code>private void fetchPosts() {

    requestQueue = Volley.newRequestQueue(getActivity());

    StringRequest jRequest = new StringRequest(Request.Method.GET, ENDPOINT, onPostsLoaded, onPostsError);

    requestQueue.add(jRequest);

}

private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Order>>() {}.getType();
        modelData = gson.fromJson(response, listType);

        adapter = new OrdersDataAdapter((ArrayList<Order>) modelData, getActivity());
        recyclerView.setAdapter(adapter);
        adapter.setMode(Attributes.Mode.Single);

    }
};

private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("PostActivity", error.toString());
    }
};
</code>```

答:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

This is easy to read: it means that you're parsing something like a list (so that BEGIN_ARRAY [ is expected), but the given JSON document starts with BEGIN_OBJECT {, that is caused by mismatched expected type. And it happens at the very beginning of the JSON document.

Apart from the mismanc's answer, there is also a third-way, that requires a slightly more code (can be extracted to a method though), but it does not require both wrappers or intermediate JSON trees like JsonElement and its subclasses (that may consume slightly more memory for the 1st case, and definitely more memory for the second case because the whole intermediate JSON tree must be stored in memory).

// JsonReader allows to read JSON token stream
try ( final JsonReader jsonReader = new JsonReader(new StringReader(JSON)) ) {
    // Just skip the leading `{`
    jsonReader.beginObject();
    // Check if the next property name is what we're expecting
    final String name = jsonReader.nextName();
    if ( !name.equals("orders") ) {
        throw new MalformedJsonException("Unexpected: " + name);
    }
    // If it's fine, then we:
    // * are assuming the JsonReader "pointer" is at the property value now
    // * are asking Gson for the proper type adapter
    @SuppressWarnings("unchecked")
    final TypeAdapter<List<Order>> typeAdapter = (TypeAdapter<List<Order>>) gson.getAdapter(TypeToken.get(orderListType));
    // Just read the orders
    final List<Order> orders = typeAdapter.read(jsonReader);
    System.out.println(orders);
}
```

JSON schema to POJO automatic converters/generators do not always create optimal mappings. For example:

Both ItemsNum and OrdersNum are represented by the same POJO structure, however it can be final class Id { @SerializedName("id") final Integer id = null; }.

Customer avatar_url is represented as java.lang.String, but it can be java.net.URL too.

Minor notes:

Gson class instances not required to be created every time you need deserialization. They are fully thread-safe and can be instantiated once and then re-used easily. Also, created and configured else Gson instance can be just injected to your code.

Type instances produced with TypeTokens can be considered immutable value objects therefore to be cached into a static final field too.

Body:
This error drove me crazy I tried using different kind of Volley requests such as JsonArrayRequest and JsonObjectRequest but no luck !!

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Here's the JSON response link => http://www.mocky.io/v2/58df83a80f00005922eaf4e1

Here's my model class

 public class Order {

@SerializedName("status")
@Expose
private String status; //status

@SerializedName("total")
@Expose
private float price; //total

@SerializedName("created_at")
@Expose
private Date time;

@SerializedName("line_items")
@Expose
public List<ItemsNum> lineItems = new ArrayList<ItemsNum>();

@SerializedName("sub_orders")
@Expose
public List<OrdersNum> subOrders = new ArrayList<OrdersNum>();

@SerializedName("shipping_address")
@Expose
public CusAddress cusAdress;

@SerializedName("customer")
@Expose
public Customer customer;

public Order(Customer customer, String status, float price, String cusPicURL, String firstName, String lastName, Date time, List<ItemsNum> lineItems, List<OrdersNum> subOrders, CusAddress cusAdress) {
    this.status = status;
    this.price = price;
    this.customer = customer;
    this.time = time;
    this.lineItems = lineItems;
    this.subOrders = subOrders;
    this.cusAdress = cusAdress;
}

public Date getTime() {
    return time;
}

public void setTime(Date time) {
    this.time = time;
}

public List<ItemsNum> getLineItems() {
    return lineItems;
}

public void setLineItems(List<ItemsNum> lineItems) {
    this.lineItems = lineItems;
}

public List<OrdersNum> getSubOrders() {
    return subOrders;
}

public void setSubOrders(List<OrdersNum> subOrders) {
    this.subOrders = subOrders;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public CusAddress getCusAdress() {
    return cusAdress;
}

public void setCusAdress(CusAddress cusAdress) {
    this.cusAdress = cusAdress;
}

// //////////// Inner-Classes

public class Customer {

    @SerializedName("avatar_url")
    @Expose
    private String cusPicURL; //avatar_url

    @SerializedName("first_name")
    @Expose
    private String firstName; //first_name

    @SerializedName("last_name")
    @Expose
    private String lastName; //last_name

    public String getCusPicURL() {
        return cusPicURL;
    }

    public void setCusPicURL(String cusPicURL) {
        this.cusPicURL = cusPicURL;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

public class CusAddress {

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @SerializedName("address_1")
    @Expose
    public String address;

    @SerializedName("city")
    @Expose
    public String city;

    @SerializedName("state")
    @Expose
    public String state;

    @SerializedName("country")
    @Expose
    public String country;
}

public class ItemsNum {

    @SerializedName("id")
    @Expose
    public Integer id;
}

public class OrdersNum {

    @SerializedName("id")
    @Expose
    public Integer id;
 }
}

My Adapter

  public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public Context context;
private int num;
ArrayList<Order> orders;

public OrdersDataAdapter(ArrayList<Order> orders, Context context) {
    this.orders = orders;

    this.context = context;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);

    return new NewOrderVH(v);

}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Order order = this.orders.get(position);
    final NewOrderVH vh1 = (NewOrderVH) holder;
    vh1.setData(orders.get(position));

}

@Override
public int getItemCount() {
    return orders.size();
}

public class NewOrderVH extends RecyclerView.ViewHolder {

    private ImageView cusPic;
    private TextView cusName;
    private TextView CusAdress;
    private TextView vendorsNum;
    private TextView itemsNum;
    private TextView time;

    public NewOrderVH(View itemView) {
        super(itemView);

        orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
        cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
        cusName = (TextView) itemView.findViewById(R.id.cusName);
        CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
        vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
        itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
        time = (TextView) itemView.findViewById(R.id.time);

    }

    public void setData(final Order data) {

        cusName.setText(data.customer.getFirstName() + "" + data.customer.getLastName());
        Picasso.with(context).load(data.customer.getCusPicURL()).into(cusPic);
        time.setText(data.getTime().getMinutes());
        vendorsNum.setText(data.getSubOrders().size());
        itemsNum.setText(data.getLineItems().size());
        CusAdress.setText(data.cusAdress.getAddress() + "" + data.cusAdress.getCity() + "" + data.cusAdress.getCountry() + "" + data.cusAdress.getState());

    }

}

}

Request Method inside a Fragment

private void fetchPosts() {

    requestQueue = Volley.newRequestQueue(getActivity());

    StringRequest jRequest = new StringRequest(Request.Method.GET, ENDPOINT, onPostsLoaded, onPostsError);

    requestQueue.add(jRequest);

}

private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Order>>() {}.getType();
        modelData = gson.fromJson(response, listType);

        adapter = new OrdersDataAdapter((ArrayList<Order>) modelData, getActivity());
        recyclerView.setAdapter(adapter);
        adapter.setMode(Attributes.Mode.Single);

    }
};

private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("PostActivity", error.toString());
    }
};

Body:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

This is easy to read: it means that you're parsing something like a list (so that BEGIN_ARRAY [ is expected), but the given JSON document starts with BEGIN_OBJECT {, that is caused by mismatched expected type. And it happens at the very beginning of the JSON document.

Apart from the mismanc's answer, there is also a third-way, that requires a slightly more code (can be extracted to a method though), but it does not require both wrappers or intermediate JSON trees like JsonElement and its subclasses (that may consume slightly more memory for the 1st case, and definitely more memory for the second case because the whole intermediate JSON tree must be stored in memory).

// JsonReader allows to read JSON token stream
try ( final JsonReader jsonReader = new JsonReader(new StringReader(JSON)) ) {
    // Just skip the leading `{`
    jsonReader.beginObject();
    // Check if the next property name is what we're expecting
    final String name = jsonReader.nextName();
    if ( !name.equals("orders") ) {
        throw new MalformedJsonException("Unexpected: " + name);
    }
    // If it's fine, then we:
    // * are assuming the JsonReader "pointer" is at the property value now
    // * are asking Gson for the proper type adapter
    @SuppressWarnings("unchecked")
    final TypeAdapter<List<Order>> typeAdapter = (TypeAdapter<List<Order>>) gson.getAdapter(TypeToken.get(orderListType));
    // Just read the orders
    final List<Order> orders = typeAdapter.read(jsonReader);
    System.out.println(orders);
}

JSON schema to POJO automatic converters/generators do not always create optimal mappings. For example:

Both ItemsNum and OrdersNum are represented by the same POJO structure, however it can be final class Id { @SerializedName("id") final Integer id = null; }.

Customer avatar_url is represented as java.lang.String, but it can be java.net.URL too.

Minor notes:

Gson class instances not required to be created every time you need deserialization. They are fully thread-safe and can be instantiated once and then re-used easily. Also, created and configured else Gson instance can be just injected to your code.

Type instances produced with TypeTokens can be considered immutable value objects therefore to be cached into a static final field too.


问:
How to create a VR 360 photo viewer in Unity
Can someone guide me to create a VR photo viewer in Unity using the Google VR (GVR) sdk. Thanks</p>

答:
Steps in Unity:

Add a new Sphere GameObject.

In your assets Create new Material-> change its albedo texture with your 360 photo.

Grab the Material and apply it to your Sphere.

Position the main Camera/Player inside the Sphere .

Voila


问:
How do i remove debug messages that mongo outputs
So when I connect to my mongo server/DB via java, I get messages that I've connected successfully, and along with it useless info. How do I remove this irrelevant info?

All the text in red

答:
Per the MongoDB documentation on logging (which you should read!), the Mongo driver will look for SLF4J on the classpath at runtime. If it is available, it will use it. Otherwise, it will fall back to java.util.logging aka JUL.

In your case, it would appear that no SLF4J was found, and thus, you will need to configure JUL if you want these INFO level messages to not appear. You have a couple of options to do this.

The quickest and dirtiest way (but not recommended, as it would potentially impact every Java program utilizing JUL on your machine) is to find logging.properties in your JRE's lib directory: <jre install dir>/lib. There is a line in there that will look like this:

```<code>.level=INFO
</code>```

Change the INFO level to WARNING or SEVERE

```<code>.level=WARNING
# or
.level=SEVERE
</code>```

The better way would be to make a copy of the aforementioned logging.properties file (found in <jre install dir>/lib) somewhere in your project and make the same changes. When running your program, simply add the following system property:

```<code>-Djava.util.logging.config.file=<path to logging.properties>
</code>```

Body:
Per the MongoDB documentation on logging (which you should read!), the Mongo driver will look for SLF4J on the classpath at runtime. If it is available, it will use it. Otherwise, it will fall back to java.util.logging aka JUL.

In your case, it would appear that no SLF4J was found, and thus, you will need to configure JUL if you want these INFO level messages to not appear. You have a couple of options to do this.

The quickest and dirtiest way (but not recommended, as it would potentially impact every Java program utilizing JUL on your machine) is to find logging.properties in your JRE's lib directory: <jre install dir>/lib. There is a line in there that will look like this:

.level=INFO

Change the INFO level to WARNING or SEVERE

.level=WARNING
# or
.level=SEVERE

The better way would be to make a copy of the aforementioned logging.properties file (found in <jre install dir>/lib) somewhere in your project and make the same changes. When running your program, simply add the following system property:

-Djava.util.logging.config.file=<path to logging.properties>


问:
Restricting access to AWS S3 Bucket Objects only when requests are made from certain domains
I have created a bucket policy to try and stop hotlinking to my S3 files from people who gain the direct URL. I only want my website to be able to access those files. However when I direct link even with the below policy, it still allows access to the file. The files are all set to public.

```<code>{
    "Id": "Policy1491040992219",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt14910401236760",
            "Action": [
                "s3:GetObject"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::bucketname/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": "https://mywebsite.com/*"
                }
            },
            "Principal": "*"
        },
        {
            "Sid": "Stmt14910403436760",
            "Action": [
                "s3:GetObject"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::bucketname/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": "http://localhost:8888/*"
                }
            },
            "Principal": "*"
        }
    ]
}
</code>```

Do I need to change any settings on the actual S3 bucket settings to stop all access?

Thanks!

答:
You are missing the Deny statement. Try this policy:

```<code>{
    "Version": "2008-10-17",
    "Id": "Policy1491040992219",
    "Statement": [
        {
            "Sid": "Stmt14910401236760",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucketname/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": [
                        "https://mywebsite.com/*",
                        "http://localhost:8888/*"
                    ]
                }
            }
        },
        {
            "Sid": "Stmt14910401236761",
            "Effect": "Deny",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucketname/*",
            "Condition": {
                "StringNotLike": {
                    "aws:Referer": [
                        "https://mywebsite.com/*",
                        "http://localhost:8888/*"
                    ]
                }
            }
        }
    ]
}
</code>```

Body:
I have created a bucket policy to try and stop hotlinking to my S3 files from people who gain the direct URL. I only want my website to be able to access those files. However when I direct link even with the below policy, it still allows access to the file. The files are all set to public.

{
    "Id": "Policy1491040992219",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt14910401236760",
            "Action": [
                "s3:GetObject"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::bucketname/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": "https://mywebsite.com/*"
                }
            },
            "Principal": "*"
        },
        {
            "Sid": "Stmt14910403436760",
            "Action": [
                "s3:GetObject"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::bucketname/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": "http://localhost:8888/*"
                }
            },
            "Principal": "*"
        }
    ]
}

Do I need to change any settings on the actual S3 bucket settings to stop all access?

Thanks!

Body:
You are missing the Deny statement. Try this policy:

{
    "Version": "2008-10-17",
    "Id": "Policy1491040992219",
    "Statement": [
        {
            "Sid": "Stmt14910401236760",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucketname/*",
            "Condition": {
                "StringLike": {
                    "aws:Referer": [
                        "https://mywebsite.com/*",
                        "http://localhost:8888/*"
                    ]
                }
            }
        },
        {
            "Sid": "Stmt14910401236761",
            "Effect": "Deny",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucketname/*",
            "Condition": {
                "StringNotLike": {
                    "aws:Referer": [
                        "https://mywebsite.com/*",
                        "http://localhost:8888/*"
                    ]
                }
            }
        }
    ]
}


问:
Simple Vandermonde Matrix with for loop
This is a very simple question.My aim is to eventually create a Vandermonde matrix but first i need to:

Write a function that takes a real number  α  and an integer  n  as input, and returns a vector  v=(1,α,α2,…,αn−1)

so far i have:

import numpy as np

```<code>n =6
a= 3
for i in range(n):
    v = np.array([1, a**2, a**(n-1)])
print v
</code>```

I get: [  1    9  243] which is not what i want. Please can you help, thank you!

答:
Use a list comprehension:

```<code>v = np.array([a**x for x in range(n)])
</code>```

This is equivalent to:

```<code>v = []
for x in range(n):
    v.append(a**x)
v = np.array(v)
</code>```

Title: Simple Vandermonde Matrix with for loop

Body:
This is a very simple question.My aim is to eventually create a Vandermonde matrix but first i need to:

Write a function that takes a real number  α  and an integer  n  as input, and returns a vector  v=(1,α,α2,…,αn−1)

so far i have:

import numpy as np

n =6
a= 3
for i in range(n):
    v = np.array([1, a**2, a**(n-1)])
print v

I get: [  1    9  243] which is not what i want. Please can you help, thank you!

Body:
Use a list comprehension:

v = np.array([a**x for x in range(n)])

This is equivalent to:

v = []
for x in range(n):
    v.append(a**x)
v = np.array(v)


问:
As String class is the subclass of Object class how the return type of toString() method in the Object class is String
Object is inherited by String
So how String is made available in Object class as return type of toString() method</p>

答:
Inheritance does not mean that the base class cannot have objects of child classes, if that's what you're thinking.

Inheritance does not really influence what objects can be created in a superclass or subclass.


问:
Class not recognised as implementing interface
I have the following classes:

```<code>namespace Model {
    public abstract class TrackerBase : ITrackerComponent { }

    public class ClickTracker : TrackerBase, IClickRecorder { }

    public class ClicksLeftTracker : TrackerBase, IClickRecorder { }
}

namespace Model.Interfaces {
    public interface IClickRecorder
    {
        List<DateTime> Clicks { get; }
    }
    public interface ITrackerComponent : INotifyPropertyChanged
    {
        int ID { get; set; }
        string Name { get; set; }
        ICommand OnOptionsClick { get; set; }
        // ... etc
    }
}
</code>```

ClickTracker and ClicksLeftTracker are very similar in their implementation and have implemented the IClickRecorder interface properly.

When I pass a ClickTracker as a parameter to TrackerOptionsPage(ITrackerComponent) it is recognised as implementing IClickRecorder and IsVisible is set to true.

However, when I pass a ClicksLeftTracker as a parameter, it's set to false as if it's not implementing IClickRecorder.

The full flow from start to the method in question is:

```<code>// GetAllTrackers() returns IEnumerable<ITrackerComponent>
var allTrackers = _dataSource.GetAllTrackers();
allTrackers.ToList().ForEach(AddItemToGrid);

private void AddItemToGrid(ITrackerComponent item) {
    item.OnOptionsClick =
        new Command(async () => await Navigation?.PushAsync(new TrackerOptionsPage(item, _dataSource)));
    // ...
}

public TrackerOptionsPage(ITrackerComponent trackerToShow) {
    ClickDatasSettings.IsVisible = trackerToShow is IClickRecorder;
    // ...
}
</code>```

What is going on here?

答:
I solved it by manually uninstalling the app from the android emulator I was using and running it from Xamarin studio again.

Seems there was some old assembly that wasn't being updated correctly on clean/rebuild, and it's probably related to me using two different computers with one having Xamarin Studio (OSX) and one having Visual Studio (Windows) when developing.

Thes issue with assemblies not updating on rebuild which lead me to my conclusion was found here.

Body:
I have the following classes:

namespace Model {
    public abstract class TrackerBase : ITrackerComponent { }

    public class ClickTracker : TrackerBase, IClickRecorder { }

    public class ClicksLeftTracker : TrackerBase, IClickRecorder { }
}

namespace Model.Interfaces {
    public interface IClickRecorder
    {
        List<DateTime> Clicks { get; }
    }
    public interface ITrackerComponent : INotifyPropertyChanged
    {
        int ID { get; set; }
        string Name { get; set; }
        ICommand OnOptionsClick { get; set; }
        // ... etc
    }
}

ClickTracker and ClicksLeftTracker are very similar in their implementation and have implemented the IClickRecorder interface properly.

When I pass a ClickTracker as a parameter to TrackerOptionsPage(ITrackerComponent) it is recognised as implementing IClickRecorder and IsVisible is set to true.

However, when I pass a ClicksLeftTracker as a parameter, it's set to false as if it's not implementing IClickRecorder.

The full flow from start to the method in question is:

// GetAllTrackers() returns IEnumerable<ITrackerComponent>
var allTrackers = _dataSource.GetAllTrackers();
allTrackers.ToList().ForEach(AddItemToGrid);

private void AddItemToGrid(ITrackerComponent item) {
    item.OnOptionsClick =
        new Command(async () => await Navigation?.PushAsync(new TrackerOptionsPage(item, _dataSource)));
    // ...
}

public TrackerOptionsPage(ITrackerComponent trackerToShow) {
    ClickDatasSettings.IsVisible = trackerToShow is IClickRecorder;
    // ...
}

What is going on here?


答:
The inheritance relationship between Object and String does not prevent Object from knowing about String.

String just tells you the type that this method returns.

Title: As String class is the subclass of Object class how the return type of toString() method in the Object class is String

Body:
Object is inherited by String
So how String is made available in Object class as return type of toString() method


问:
301 Redirect Best Practices - multiple sites to single site
I have around 15+ sites, and we want to drop these sites and merge them into only one site (create pages for each one in the new site).

The 15+ site's domains should be redirected to one site as below:

```<code>a.com -> z.com/a
b.com -> z.com/b
c.com -> z.com/c
..
</code>```

Also, we want to redirect (301) page by page from the old domains to the new the new domain to keep the page's ranking:

```<code> a.com/about-us     -> z.com/a/about-us
 b.com/about/abouus -> z.com/b/about-s
 c.com/contactus    -> z.com/c/contact-us
</code>```

Each one of the 15+ sites is running on its own server with a different platform while the new server is IIS.

Currently, I'm thinking of two approaches:

Point the old DNS records to the new server of z.com, and handle all the redirects on the server.

Keep the old site running, and configure redirect rules on each server to redirect each page to the matching page on the new site.

Which approach is better, any other approaches? So far I think the first approach is better since we will control all the redirects in one place - but from the performance wise, is it going to add more headache on the server?

答:
DNS records are not capable of HTTP redirection which is crucial for SEO. To make sure your redirect is 301 HTTP redirect you can use sniffer.

The answer is just make sure your redirect is 301 HTTP redirect so you get your SEO right. Other than that it's just a matter of taste / architecture / money rather than standards.

UPDATE

Read more:

wikipedia

Both Bing and Google recommend using a 301 redirect to change the URL of a page as it is shown in search engine results.

ehow.com

A 301 redirect is a search-engine friendly way to move a domain. The 301-redirected domain does not cause duplicate content in the search engines so that you do not harm your search engine rank. Using a new DNS setting is required to have a new domain name, but it does not redirect browsers or search engines. Both of these methods are used to move to a new domain.

webmasters.stackexchange.com

Duplicate content occurs when the same content is available on two different URLs. To prevent duplicate content on www vs no-www, use 301 redirects to redirect one to the other. To implement redirects, it is the webserver that needs to be configured properly. As long as DNS is pointing to the webserver (either CNAME or A record), then the webserver can be configured properly.

Body:
I have around 15+ sites, and we want to drop these sites and merge them into only one site (create pages for each one in the new site).

The 15+ site's domains should be redirected to one site as below:

a.com -> z.com/a
b.com -> z.com/b
c.com -> z.com/c
..

Also, we want to redirect (301) page by page from the old domains to the new the new domain to keep the page's ranking:

 a.com/about-us     -> z.com/a/about-us
 b.com/about/abouus -> z.com/b/about-s
 c.com/contactus    -> z.com/c/contact-us

Each one of the 15+ sites is running on its own server with a different platform while the new server is IIS.

Currently, I'm thinking of two approaches:

Point the old DNS records to the new server of z.com, and handle all the redirects on the server.

Keep the old site running, and configure redirect rules on each server to redirect each page to the matching page on the new site.

Which approach is better, any other approaches? So far I think the first approach is better since we will control all the redirects in one place - but from the performance wise, is it going to add more headache on the server?


问:
Code compiled with no error but moving empty object to new list
```<code>        <!--After loading no error from inspection but the move method not responding-->
        <!--The HTML--->
        <!doctype html>
        <html ng-app='ShoppingListCheckOff'>
        <html lang="en">
          <head>
            <title>Shopping List Check Off</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <script src="angular.min.js"></script>
            <script src="app.js"></script>
            <link rel="stylesheet" href="styles/bootstrap.min.css">
            <style>
              .emptyMessage {
                font-weight: bold;
                color: red;
                font-size: 1.2em;
              }
              li {
                margin-bottom: 7px;
                font-size: 1.2em;
              }
              li > button {
                margin-left: 6px;
              }
              button > span {
                color: green;
              }
            </style>
          </head>
        <body>
          <div class="container">
          <h1>Shopping List Check Off</h1>

          <div class="row">
           <!--i think all is ok with this div as everything loaded as i wanted it-->
        <!--the ng-hide worked also-->
            <!--To Buy List -->
            <div class="col-md-6" ng-controller='ToBuyController as itemAdder'>
             <h2>To Buy:</h2>

             <ul>
               <li ng-repeat="item in itemAdder.shoppingList2">Name: {{item.name}} , Quantity: {{item.quantity}}
                 <button class="btn btn-default" ng-click="itemAdder.move()"><span class="glyphicon glyphicon-ok"></span> Bought</button></li>
             </ul>

             <div ng-hide="itemAdder.shoppingList2.length" class="emptyMessage">Everything is bought!</div>
            </div>
        <!--I want to move the displayed items to this div on click of the bought button-->
        <!--ng-hide i think it worked-->
            <!-- Already Bought List -->
            <div class="col-md-6" ng-controller='AlreadyBoughtController as boughtItem'>
             <h2>Already Bought:</h2>
             <ul>
               <li>Bought <span ng-bind="boughtItem.boughtList.length"></span> 10 cookies</li>

               <li ng-repeat="item in boughtItem.boughtList">Name: {{item.name}} , Quantity: {{item.quantity}}</li>
             </ul>
              <div ng-hide="boughtItem.boughtList.length" class="emptyMessage">Nothing bought yet.</div>
            </div>
          </div>

        </div>
        </body>
        </html>

                               <!--Script-->
        (function () {
        'use strict';

        angular.module('ShoppingListCheckOff', [])
        .controller('ToBuyController', ToBuyController)
        .controller('AlreadyBoughtController', AlreadyBoughtController)
        .service('ShoppingListService', ShoppingListService);

         <!--This part populated with the buttons ready to be clicked-->
        ToBuyController.$inject = ['ShoppingListService'];
        function ToBuyController(ShoppingListService) {
          var itemAdder = this;
          itemAdder.shoppingList2 = ShoppingListService.shoppingList2;
        }

on click of the button i was expecting the item clicked to move to here

AlreadyBoughtController.$inject = ['ShoppingListService'];
        function AlreadyBoughtController(ShoppingListService) {
         var boughtItem= this;
          boughtItem.boughtList= ShoppingListService.bought;
        }
</code>```

Is there something i didn't do right here? But the list2 is been populated

function ShoppingListService( ) {
              var service = this;

```<code>          service.shoppingList2 = [
          {
            name: "Milk",
            quantity: "2"
          },
          {
            name: "Donuts",
            quantity: "200"
          },
          {
            name: "Cookies",
            quantity: "300"
          },
           {
            name: "Musli",
            quantity: "10"
          },
          {
            name: "Chocolate",
            quantity: "5"
          }
        ];
</code>```

This part is been populated onclick  but retuning empty object. i want the objects to move here on click but something is not complete and i can't figure it out

```<code>service.bought = [];

    service.remove = function(itemIndex){
        service.bought.push(service.shoppingList2.splice(itemIndex,1));

    }

    service.getItems = function(){
        return service.bought;
    };

}

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

答:
You left out the quotation marks for the objects name definition in your list. Add quotation marks to each object definition, they need to be written as if they were in a JSON file.

```<code> service.shoppingList2 = [
      {
       "name": "Milk",
        "quantity": "2"
      }
    ];
</code>```

https://docs.angularjs.org/guide/controller

Body:
        <!doctype html>

            <title>Shopping List Check Off</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">

            <link rel="stylesheet" href="styles/bootstrap.min.css">

Shopping List Check Off

To Buy:

Name: {{item.name}} , Quantity: {{item.quantity}}
                 <button class="btn btn-default" ng-click="itemAdder.move()"> Bought</button>

Everything is bought!

Already Bought:

Bought  10 cookies

Name: {{item.name}} , Quantity: {{item.quantity}}

Nothing bought yet.

        (function () {
        'use strict';

        angular.module('ShoppingListCheckOff', [])
        .controller('ToBuyController', ToBuyController)
        .controller('AlreadyBoughtController', AlreadyBoughtController)
        .service('ShoppingListService', ShoppingListService);

        ToBuyController.$inject = ['ShoppingListService'];
        function ToBuyController(ShoppingListService) {
          var itemAdder = this;
          itemAdder.shoppingList2 = ShoppingListService.shoppingList2;
        }

on click of the button i was expecting the item clicked to move to here

AlreadyBoughtController.$inject = ['ShoppingListService'];
        function AlreadyBoughtController(ShoppingListService) {
         var boughtItem= this;
          boughtItem.boughtList= ShoppingListService.bought;
        }

Is there something i didn't do right here? But the list2 is been populated

function ShoppingListService( ) {
              var service = this;

          service.shoppingList2 = [
          {
            name: "Milk",
            quantity: "2"
          },
          {
            name: "Donuts",
            quantity: "200"
          },
          {
            name: "Cookies",
            quantity: "300"
          },
           {
            name: "Musli",
            quantity: "10"
          },
          {
            name: "Chocolate",
            quantity: "5"
          }
        ];

This part is been populated onclick  but retuning empty object. i want the objects to move here on click but something is not complete and i can't figure it out

service.bought = [];

    service.remove = function(itemIndex){
        service.bought.push(service.shoppingList2.splice(itemIndex,1));

    }

    service.getItems = function(){
        return service.bought;
    };

}

})();

Body:
You left out the quotation marks for the objects name definition in your list. Add quotation marks to each object definition, they need to be written as if they were in a JSON file.

 service.shoppingList2 = [
      {
       "name": "Milk",
        "quantity": "2"
      }
    ];

https://docs.angularjs.org/guide/controller


问:
How to show no result found from a AngularJS search?
I am fetching data from an api and I am using it to search something. When the json returns no result how to show NO RESULT FOUND.

Html code

```<code>        <div class="item item-input-inset">
    <label class="item-input-wrapper">
      <input type="text" placeholder="Search" ng-model="search">
    </label>
    <button class="button button-small" ng-click="load(search)">
      Submit
    </button>
  </div>
  <section class="list">
       <article ng-repeat="object in news">
        <div class="item">

         <div ng-repeat="item in object.news">
        <p class="noWhiteSpace"><b>Available Size</b> - {{item.size}}</p>

         </div>

         </div>
         <div ng-repeat="item in object.news" class="button-bar bar-dark" >
  <a  ng-click = openUrl(item.url); class="button">button</a>

        </div>
      </article>
        </section>
        </ion-content>
      </ion-view>
    </script>
</code>```

This is JS Code where I am fetching data from an api and also searching it.

```<code> $http({

    method: "GET",
    url: https://news.com/json?limit=50"
  })
  .then(function(newsData){
   $scope.news= newsData.data.data.articles;
   $scope.hide();
    console.log(data);

  })

      $scope.load = function(search) {
     $scope.show();
  $http({
    method: "GET",
    url: "https://news.com/json?query_term=" + encodeURIComponent(search)
  })
  .then(function(newsData){
   $scope.newsto= newsData.data.data.article;
   $scope.hide();
    console.log(data);

  });
}

})
</code>```

答:
```<code><article ng-repeat="object in news" ng-if="news.lenght">
</code>```

//show your result

```<code><span ng-if="!news.lenght">No Result found </span>
</code>```

Updated with Fiddle link

link

Body:
I am fetching data from an api and I am using it to search something. When the json returns no result how to show NO RESULT FOUND.

Html code

      <input type="text" placeholder="Search" ng-model="search">

    <button class="button button-small" ng-click="load(search)">
      Submit
    </button>

Available Size - {{item.size}}

  button

        </ion-content>
      </ion-view>
    </script>

This is JS Code where I am fetching data from an api and also searching it.

 $http({

    method: "GET",
    url: https://news.com/json?limit=50"
  })
  .then(function(newsData){
   $scope.news= newsData.data.data.articles;
   $scope.hide();
    console.log(data);

  })

      $scope.load = function(search) {
     $scope.show();
  $http({
    method: "GET",
    url: "https://news.com/json?query_term=" + encodeURIComponent(search)
  })
  .then(function(newsData){
   $scope.newsto= newsData.data.data.article;
   $scope.hide();
    console.log(data);

  });
}

})

Body:
<article ng-repeat="object in news" ng-if="news.lenght">

//show your result

<span ng-if="!news.lenght">No Result found </span>

Updated with Fiddle link

link


问:
Can I take a snapshot of a website from the command line?
I am writing documentation for a website  database interface. Is it possible to write a script that, when executed, takes the most recent snapshot of the website and saves it as an image file?

note: I am using the tags ruby, bash, and python since those are the languages used in our group (along with R and FORTRAN; for sport, I'll set a 100 point bounty If anyone can post a FORTRAN solution).

update: as @birryree notes, a previous question provides the answer. Considering the FORTRAN offer is just for sport, perhaps this is a duplicate?

答: WkHTMLtoPDF has binaries which also convert web pages to images using webkit's renderer.</p>

ContentLicense: CC BY-SA 2.5


问:
Python code error (scalar arrays to scalar index)
I faced a problem in a python script..

I run it as :

```<code>python /path/script.py
</code>```

it gave me this error :

```<code>Traceback (most recent call last):
File "/path/script.py", line 332, in <module>
    main()
File "/path/script.py", line 283, in main
    hull1.append(points3[hullIndex[i]])
TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

this is a part of code (from line 262 to 284) :

```<code>    #Following steps detects again the original face using dlib, this time for do face swapping
    #target face is the frame taken from camera and source face is the one morphed before
    dets4 = detector(img4, 1)
    if len(dets4)<1:
        pass
    else:
        for k, d in enumerate(dets4):
            points3 = []
            #Get 68 facial landmarks and save them to an array
            landmark3=np.array([[p.x, p.y] for p in predictor(img4, dets4[0]).parts()])
            for i in range(0,68) :
                x3 = landmark3[i][0]
                y3 = landmark3[i][1]
                points3.append((int(x3), int(y3)))

    # Find convex hull
    hull1 = []
    hull2 = []
    hullIndex = cv2.convexHull(np.array(points2), returnPoints = False)

    for i in xrange(0, len(hullIndex)):
        hull1.append(points3[hullIndex[i]])
        hull2.append(points2[hullIndex[i]])
</code>```

and from (line 330 to 339) :

```<code>if __name__ == '__main__':
    try:
        main()
    except ValueError:
        img2 = cv2.resize(img2,(320,320))
        swap = cv2.resize(swap,(320,320))
        dst = cv2.addWeighted(img2,0.55,swap,0.45,0)
        cv2.imwrite(sys.argv[3], dst)
        print "Shutting down"
    print "Exit"
</code>```

Is there any part of these codes need to be fixed, or it is something related to other things (like python, dlib, any module versions)?

答:
cv2.convexHull() with returnPoints=False returns a list of point indices, however each index is contained in another sublist like this: [[index1], [index2], ...]

So you can simplify these lines

```<code>for i in xrange(0, len(hullIndex)):
    hull1.append(points3[hullIndex[i]])
    hull2.append(points2[hullIndex[i]])
</code>```

to

```<code>for point_index, in hullIndex:
    hull1.append(points3[point_index])
    hull2.append(points2[point_index])
</code>```

See the tutorial on Contour Features for more details.

Body:
I faced a problem in a python script..

I run it as :

python /path/script.py

it gave me this error :

Traceback (most recent call last):
File "/path/script.py", line 332, in <module>
    main()
File "/path/script.py", line 283, in main
    hull1.append(points3[hullIndex[i]])
TypeError: only integer scalar arrays can be converted to a scalar index

this is a part of code (from line 262 to 284) :

    #Following steps detects again the original face using dlib, this time for do face swapping
    #target face is the frame taken from camera and source face is the one morphed before
    dets4 = detector(img4, 1)
    if len(dets4)<1:
        pass
    else:
        for k, d in enumerate(dets4):
            points3 = []
            #Get 68 facial landmarks and save them to an array
            landmark3=np.array([[p.x, p.y] for p in predictor(img4, dets4[0]).parts()])
            for i in range(0,68) :
                x3 = landmark3[i][0]
                y3 = landmark3[i][1]
                points3.append((int(x3), int(y3)))

    # Find convex hull
    hull1 = []
    hull2 = []
    hullIndex = cv2.convexHull(np.array(points2), returnPoints = False)

    for i in xrange(0, len(hullIndex)):
        hull1.append(points3[hullIndex[i]])
        hull2.append(points2[hullIndex[i]])

and from (line 330 to 339) :

if __name__ == '__main__':
    try:
        main()
    except ValueError:
        img2 = cv2.resize(img2,(320,320))
        swap = cv2.resize(swap,(320,320))
        dst = cv2.addWeighted(img2,0.55,swap,0.45,0)
        cv2.imwrite(sys.argv[3], dst)
        print "Shutting down"
    print "Exit"

Is there any part of these codes need to be fixed, or it is something related to other things (like python, dlib, any module versions)?

Body:
cv2.convexHull() with returnPoints=False returns a list of point indices, however each index is contained in another sublist like this: [[index1], [index2], ...]

So you can simplify these lines

for i in xrange(0, len(hullIndex)):
    hull1.append(points3[hullIndex[i]])
    hull2.append(points2[hullIndex[i]])

to

for point_index, in hullIndex:
    hull1.append(points3[point_index])
    hull2.append(points2[point_index])

See the tutorial on Contour Features for more details.


问:
MySQL error when altering table to Fulltext
I get an error #1283 - Column 'title' cannot be part of FULLTEXT index when I try to include the columns I want to alter via FULLTEXT in my database.

```<code>ALTER TABLE users ADD FULLTEXT (`firstname`, `lastname`, `title`, `description`)
</code>```

I'm not understanding why this error shows or how to go about in fixing this problem. Would be grateful for any ideas or tips.

答:
INNODB supports FULLTEXT INDEX since Mysql 5.6

To avoid errors "Column * cannot be part of FULLTEXT index"
check TEXT INCODING of your columns ;) It must be the same.

Body:
I get an error #1283 - Column 'title' cannot be part of FULLTEXT index when I try to include the columns I want to alter via FULLTEXT in my database.

ALTER TABLE users ADD FULLTEXT (`firstname`, `lastname`, `title`, `description`)

I'm not understanding why this error shows or how to go about in fixing this problem. Would be grateful for any ideas or tips.


问:
Downloaded font doesn't showing special characters
My font display a circle instead of special characters like "#" or "-"

I'm using "Intro font"

Do you have a solution ?

Please tell me that there's a solution .. ^^

答:
Not sure if it is this font.

Anyways, if you take a look for example at the font linked above, you can see which characters contains. For example these font doesn't have the # and - characters, so it can't display it, and instead it shows something like a "not found" character: a circle with a cross in your case.


问:
Making Form at Wordpress Template
I'm a self learner so I didnt had anyone to get a clue, I wan't to make a form with POST method and I take w3 tutorial to make one.

PHP Form Validation Example

I successfully make it, and I want to make it included at wordpress theme, so I put those codes at page templates, just like this

```<code><?php
/*
Template Name: Urut Embed
*/
 get_header();
// define variables and set to empty values
$nameErr = $videocodeErr =  $embedurlErr = "";
$name = $videocode = $embed = $embedurl = $embedurut[] = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameErr = "Only letters and white space allowed";
        }
    }
    if (empty($_POST["embedurl"])) {
        $embedurl = "";
    } else {
        $embedurl = test_input($_POST["embedurl"]);
        // check if URL address syntax is valid (this regular     expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$embedurl)) {
            $embedurlErr = "Invalid URL";
        }
    }
    if (empty($_POST["videocode"])) {
        $videocode = "";
    } else {
        $videocode = test_input($_POST["videocode"]);
        // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$videocode)) {
            $videocodeErr = "Invalid URL";
        }
    }
    if (empty($_POST["embed"])) {
        $embed = "";
    } else {
        $embed = test_input($_POST["embed"]);
        if($videocode == "sf"){
            $embedurut = str_replace("http://www.savefile.co/","sf;", $embed);
            $embedurut = str_replace(" savefile.co.",".", $embed);
        } else if($videocode == "mp4"){
            $embedurut = str_replace("https://www.mp4upload.com/"," mp4;", $embed);
        } else if($videocode == "yu"){
            $embedurut = str_replace("https://www.yourupload.com/embed/","yu;", $embed);
        } else if($videocode == "gk"){
            $embedurut = str_replace("|"," - gk;", $embed);
        } else {
            $embedurut = $embed;
        }
        $embedurut = str_replace($name,"", $embedurut);
        $embedurut = explode(PHP_EOL, $embedurut);
        sort($embedurut);
    }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<nav class="navbar navbar-default">
    <div class="container">
        <div class="navbar-header">
            <a href="#" class="navbar-brand">Urut Embed Videocode</a>
        </div>
    </div>
</nav>

<div class="container">
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']);?>">
        <div class="input-group input-group-lg">
            <span class="input-group-addon">Remove Strings</span>
            <input type="text" name="name"  class="form-control" placeholder="Masukkan bagian videocode yang ingin dihilangkan" value="<?php echo $name;?>">
        </div>
        <br>
        <div class="alert alert-dismissable alert-success">
            Check sesuai dengan embed video untuk mengubah link menjadi videocode, none jika tidak ingin mengubah.
        </div>

        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="none"){ echo "checked"; } else if ($videocode==""){ echo "checked"; } ?> value="none">None</label>
        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="sf") echo "checked";?> value="sf">SaveFile</label>
        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="mp4") echo "checked";?> value="mp4">MP4Upload</label>
        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="yu") echo "checked";?> value="yu">YourUpload</label>
        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="gk") echo "checked";?> value="gk">gk</label>
        <br><br>

        <span class="label label-primary">
            Embeds
        </span>
        <textarea class="form-control" name="embed" rows="5" cols="150"><?php echo $embed;?></textarea>
        <br>

        <input class="btn btn-success" type="submit" name="submit" value="Submit">
    </form>
    <br>

    <span class="label label-primary">
        Embed Terurut
    </span>
    <textarea class="form-control" name="embed" rows="12" cols="150"><?php
    $alength = count($embedurut);
    for($x = 0; $x < $alength; $x++) {
    echo $embedurut[$x];
    }
    ?></textarea>
</div>
</code>```

But when I ran it, it comes back with 404 page, but with the page url, not 404 url. I dont have any clue at all how to make it work.
Can you guys help me? Sorry for bad English.

Regards

答:
Go to wordpress add new page.

Give the page a title.

And select "Urut Embed" as template to this page

Save and view the page.

Title: Making Form at Wordpress Template

Body:
I'm a self learner so I didnt had anyone to get a clue, I wan't to make a form with POST method and I take w3 tutorial to make one.

PHP Form Validation Example

I successfully make it, and I want to make it included at wordpress theme, so I put those codes at page templates, just like this

<?php
/*
Template Name: Urut Embed
*/
 get_header();
// define variables and set to empty values
$nameErr = $videocodeErr =  $embedurlErr = "";
$name = $videocode = $embed = $embedurl = $embedurut[] = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameErr = "Only letters and white space allowed";
        }
    }
    if (empty($_POST["embedurl"])) {
        $embedurl = "";
    } else {
        $embedurl = test_input($_POST["embedurl"]);
        // check if URL address syntax is valid (this regular     expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$embedurl)) {
            $embedurlErr = "Invalid URL";
        }
    }
    if (empty($_POST["videocode"])) {
        $videocode = "";
    } else {
        $videocode = test_input($_POST["videocode"]);
        // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$videocode)) {
            $videocodeErr = "Invalid URL";
        }
    }
    if (empty($_POST["embed"])) {
        $embed = "";
    } else {
        $embed = test_input($_POST["embed"]);
        if($videocode == "sf"){
            $embedurut = str_replace("http://www.savefile.co/","sf;", $embed);
            $embedurut = str_replace(" savefile.co.",".", $embed);
        } else if($videocode == "mp4"){
            $embedurut = str_replace("https://www.mp4upload.com/"," mp4;", $embed);
        } else if($videocode == "yu"){
            $embedurut = str_replace("https://www.yourupload.com/embed/","yu;", $embed);
        } else if($videocode == "gk"){
            $embedurut = str_replace("|"," - gk;", $embed);
        } else {
            $embedurut = $embed;
        }
        $embedurut = str_replace($name,"", $embedurut);
        $embedurut = explode(PHP_EOL, $embedurut);
        sort($embedurut);
    }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

            Urut Embed Videocode

    <form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']);?>">

            Remove Strings
            <input type="text" name="name"  class="form-control" placeholder="Masukkan bagian videocode yang ingin dihilangkan" value="<?php echo $name;?>">

            Check sesuai dengan embed video untuk mengubah link menjadi videocode, none jika tidak ingin mengubah.

        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="none"){ echo "checked"; } else if ($videocode==""){ echo "checked"; } ?> value="none">None
        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="sf") echo "checked";?> value="sf">SaveFile
        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="mp4") echo "checked";?> value="mp4">MP4Upload
        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="yu") echo "checked";?> value="yu">YourUpload
        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="gk") echo "checked";?> value="gk">gk

            Embeds

        <textarea class="form-control" name="embed" rows="5" cols="150"><?php echo $embed;?></textarea>

        <input class="btn btn-success" type="submit" name="submit" value="Submit">
    </form>

        Embed Terurut

    <textarea class="form-control" name="embed" rows="12" cols="150"><?php
    $alength = count($embedurut);
    for($x = 0; $x < $alength; $x++) {
    echo $embedurut[$x];
    }
    ?></textarea>

But when I ran it, it comes back with 404 page, but with the page url, not 404 url. I dont have any clue at all how to make it work.
Can you guys help me? Sorry for bad English.

Regards


问:
Javascript :: Paste clipboard to textarea
```<code><!DOCTYPE html>
<html>
<body>

<form action=# method=post name=test>
<textarea name=numb id=numb rows=4 cols=50></textarea>
<input type=submit>
</form>

<script>

window.onload=function(){

document.getElementById("numb").value = window.clipboardData.getData('Text');

}

</script>
</body>
</html>
</code>```

Title is pretty much self explanitory... I want to be able to paste the clipboard to the textarea onload... seems like a simple task but for some reason it's not working :/

答: That seems like a huge security issue if your javascript could access users clipboard right of the bat on onLoad :) So at the moment that can't be done directly via javascript. Maybe you should think alternative routes to that problem, like guiding people how to paste to that field e.g. via keyboard shortcuts.

Body:
<!DOCTYPE html>

<form action=# method=post name=test>
<textarea name=numb id=numb rows=4 cols=50></textarea>
<input type=submit>
</form>

Title is pretty much self explanitory... I want to be able to paste the clipboard to the textarea onload... seems like a simple task but for some reason it's not working :/


问:
400 status code when using $filter parameter in java request to dynamics crm
I'm trying query data from dynamics CRM through java HttpUrlConnection object.
I always get an HTTP 400 status code when my  request include the $filter parameter. But when I remove this parameter my request works fine.
I have tried my request directly on a browser and it works fine too. The code below shows how I built my request

```<code>public String getContactByPhoneNumber(String phoneNumber) throws Exception {
    HttpURLConnection connection = null;
    URL url = new URL(completeURL + "/contacts?select=lastname&$filter=telephone1 eq '"+phoneNumber+"'");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("OData-MaxVersion", "4.0");
    connection.setRequestProperty("OData-Version", "4.0");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Prefer", "odata.include-annotations=\"*\"");
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.addRequestProperty("Authorization", "Bearer " + token);
    if (connection.getResponseCode() == 200) {
        String response = getResponseAsString(connection);
        return response;
    } else {
        String error = getErrorAsString(connection);
        System.err.println(error);
        return null;
    }

}
</code>```

Did anyone met this error? How can I solve it?

答:
Luke mentioned you had misspelled "filter" in your original text. That may have something to do with it if it was not just a typo here in your post.

Also, "$" is a reserved character in URI syntax according to RFC 2396. http://www.faqs.org/rfcs/rfc2396.html

```<code>2.2. Reserved Characters

 Many URI include components consisting of or delimited by, certain
special characters.  These characters are called "reserved", since
their usage within the URI component is limited to their reserved
purpose.  If the data for a URI component would conflict with the
reserved purpose, then the conflicting data must be escaped before
forming the URI.

  reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
                "$" | ","

The "reserved" syntax class above refers to those characters that are
allowed within a URI, but which may not be allowed within a
particular component of the generic URI syntax; they are used as
delimiters of the components described in Section 3.

Characters in the "reserved" set are not reserved in all contexts.
The set of characters actually reserved within any given URI
component is defined by that component. In general, a character is
reserved if the semantics of the URI changes if the character is
replaced with its escaped US-ASCII encoding.
</code>```

You could try to form the URL without it and see if that works.

Body:
I'm trying query data from dynamics CRM through java HttpUrlConnection object.
I always get an HTTP 400 status code when my  request include the $filter parameter. But when I remove this parameter my request works fine.
I have tried my request directly on a browser and it works fine too. The code below shows how I built my request

public String getContactByPhoneNumber(String phoneNumber) throws Exception {
    HttpURLConnection connection = null;
    URL url = new URL(completeURL + "/contacts?select=lastname&$filter=telephone1 eq '"+phoneNumber+"'");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("OData-MaxVersion", "4.0");
    connection.setRequestProperty("OData-Version", "4.0");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Prefer", "odata.include-annotations=\"*\"");
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.addRequestProperty("Authorization", "Bearer " + token);
    if (connection.getResponseCode() == 200) {
        String response = getResponseAsString(connection);
        return response;
    } else {
        String error = getErrorAsString(connection);
        System.err.println(error);
        return null;
    }

}

Did anyone met this error? How can I solve it?

Body:
Luke mentioned you had misspelled "filter" in your original text. That may have something to do with it if it was not just a typo here in your post.

Also, "$" is a reserved character in URI syntax according to RFC 2396. http://www.faqs.org/rfcs/rfc2396.html

2.2. Reserved Characters

 Many URI include components consisting of or delimited by, certain
special characters.  These characters are called "reserved", since
their usage within the URI component is limited to their reserved
purpose.  If the data for a URI component would conflict with the
reserved purpose, then the conflicting data must be escaped before
forming the URI.

  reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
                "$" | ","

The "reserved" syntax class above refers to those characters that are
allowed within a URI, but which may not be allowed within a
particular component of the generic URI syntax; they are used as
delimiters of the components described in Section 3.

Characters in the "reserved" set are not reserved in all contexts.
The set of characters actually reserved within any given URI
component is defined by that component. In general, a character is
reserved if the semantics of the URI changes if the character is
replaced with its escaped US-ASCII encoding.

You could try to form the URL without it and see if that works.


问:
Update only one table on save for a multi-table entity
I have an entity that is made up of properties from two different tables as I described here and I'm running into problems when I try to insert a new item. When inserting I need to only update the fields in one of the two tables. Using the ReadOnly() method, I've been able to get NHibernate to ignore most of the fields from [RegistrationField] on save. However, I can't get it to not try to save a new entry into [RegistrationField] for the foreign key, even though an entry already exists for that key.

My mapping for the class is:

```<code>public class RegistrationFieldMap : ClassMap<RegistrationField>
{
    public RegistrationFieldMap()
    {
        Table("AccountRegistrationField");

        Id(r => r.ID).Column("RegistrationID");
        Map(r => r.AccountID);
        Map(r => r.DefaultValue);
        Map(r => r.FieldID);
        Map(r => r.IsRequired);
        Map(r => r.Label);
        Map(r => r.Priority);
        Join("RegistrationField", t =>
        {
            t.Map(r => r.FieldType).ReadOnly();
            t.Map(r => r.HtmlID).ReadOnly();
        });
    }
}
</code>```

When I run my test to verify the mapping, NHibernate tries to run the following two SQL statements:

```<code>INSERT INTO AccountRegistrationField (
    AccountID,
    DefaultValue,
    FieldID,
    IsRequired,
    Label,
    Priority)
VALUES (@p0, @p1, @p2, @p3, @p4, @p5);
select SCOPE_IDENTITY();
@p0 = 1 [Type: Int32 (0)],
@p1 = 'bar' [Type: String (4000)],
@p2 = 1 [Type: Int32 (0)],
@p3 = False [Type: Boolean (0)],
@p4 = 'bar' [Type: String (4000)],
@p5 = 1 [Type: Int32 (0)]

INSERT INTO RegistrationField (UserRegistrationField_id) VALUES (@p0);
@p0 = 12 [Type: Int32 (0)]
</code>```

I only need it to run the first statement, since the [RegistrationField] table contains a static list of values and new items should never be added to it.

Any and all suggestions welcome.

答:
OK, after thinking about Diego's comment and getting a good nights sleep I figured out the correct way to implement this and get the result I want. Diego is right that I should be using Reference and not Join. My original reasoning for wanting to implement this as a join was a desire to avoid adding another level to my object graph. AccountRegistrationField is already a property on the Account object and I didn't want to have to make a call like Account.AccountRegistrationField.RegistrationField.FieldType. I instead wanted the call to be Account.AccountRegistrationField.FieldType since the object I'll really be operating on is the AccountRegistrationField object.

I was able to get this behavior by designing my AccountRegistrationField class a little better. I made the RegistrationField property private and added public properties on the AccountRegistrationField class to expose the fields that I needed. And then used Fluent NHibernate's Reveal class to expose the private property to my mapping.

My AccountRegistrationField class ended up looking like this:

```<code>public class AccountRegistrationField
{
    public virtual int ID { get; set; }
    public virtual int AccountID { get; set; }
    public virtual string DefaultValue { get; set; }
    public virtual int FieldID { get; set; }
    public virtual string HtmlID
    {
        get { return RegistrationField.HtmlID; }
    }
    public virtual bool IsRequired { get; set; }
    public virtual string Label { get; set; }
    public virtual int Priority { get; set; }
    public virtual string FieldType
    {
        get { return RegistrationField.FieldType; }
    }

    private RegistrationField RegistrationField { get; set; }
}
</code>```

And my mapping for AccountRegistrationField looks like:

```<code>public class AccountRegistrationFieldMap : ClassMap<AccountRegistrationField>
{
    public AccountRegistrationFieldMap()
    {
        Table("AccountRegistrationField");

        Id(r => r.ID).Column("RegistrationID");
        Map(r => r.AccountID);
        Map(r => r.DefaultValue);
        Map(r => r.IsRequired);
        Map(r => r.Label);
        Map(r => r.Priority);
        References<RegistrationField>(
                 Reveal.Member<AccountRegistrationField>("RegistrationField"))
            .Column("FieldID");

    }
}
</code>```

Body:
I have an entity that is made up of properties from two different tables as I described here and I'm running into problems when I try to insert a new item. When inserting I need to only update the fields in one of the two tables. Using the ReadOnly() method, I've been able to get NHibernate to ignore most of the fields from [RegistrationField] on save. However, I can't get it to not try to save a new entry into [RegistrationField] for the foreign key, even though an entry already exists for that key.

My mapping for the class is:

public class RegistrationFieldMap : ClassMap<RegistrationField>
{
    public RegistrationFieldMap()
    {
        Table("AccountRegistrationField");

        Id(r => r.ID).Column("RegistrationID");
        Map(r => r.AccountID);
        Map(r => r.DefaultValue);
        Map(r => r.FieldID);
        Map(r => r.IsRequired);
        Map(r => r.Label);
        Map(r => r.Priority);
        Join("RegistrationField", t =>
        {
            t.Map(r => r.FieldType).ReadOnly();
            t.Map(r => r.HtmlID).ReadOnly();
        });
    }
}

When I run my test to verify the mapping, NHibernate tries to run the following two SQL statements:

INSERT INTO AccountRegistrationField (
    AccountID,
    DefaultValue,
    FieldID,
    IsRequired,
    Label,
    Priority)
VALUES (@p0, @p1, @p2, @p3, @p4, @p5);
select SCOPE_IDENTITY();
@p0 = 1 [Type: Int32 (0)],
@p1 = 'bar' [Type: String (4000)],
@p2 = 1 [Type: Int32 (0)],
@p3 = False [Type: Boolean (0)],
@p4 = 'bar' [Type: String (4000)],
@p5 = 1 [Type: Int32 (0)]

INSERT INTO RegistrationField (UserRegistrationField_id) VALUES (@p0);
@p0 = 12 [Type: Int32 (0)]

I only need it to run the first statement, since the [RegistrationField] table contains a static list of values and new items should never be added to it.

Any and all suggestions welcome.

Body:
OK, after thinking about Diego's comment and getting a good nights sleep I figured out the correct way to implement this and get the result I want. Diego is right that I should be using Reference and not Join. My original reasoning for wanting to implement this as a join was a desire to avoid adding another level to my object graph. AccountRegistrationField is already a property on the Account object and I didn't want to have to make a call like Account.AccountRegistrationField.RegistrationField.FieldType. I instead wanted the call to be Account.AccountRegistrationField.FieldType since the object I'll really be operating on is the AccountRegistrationField object.

I was able to get this behavior by designing my AccountRegistrationField class a little better. I made the RegistrationField property private and added public properties on the AccountRegistrationField class to expose the fields that I needed. And then used Fluent NHibernate's Reveal class to expose the private property to my mapping.

My AccountRegistrationField class ended up looking like this:

public class AccountRegistrationField
{
    public virtual int ID { get; set; }
    public virtual int AccountID { get; set; }
    public virtual string DefaultValue { get; set; }
    public virtual int FieldID { get; set; }
    public virtual string HtmlID
    {
        get { return RegistrationField.HtmlID; }
    }
    public virtual bool IsRequired { get; set; }
    public virtual string Label { get; set; }
    public virtual int Priority { get; set; }
    public virtual string FieldType
    {
        get { return RegistrationField.FieldType; }
    }

    private RegistrationField RegistrationField { get; set; }
}

And my mapping for AccountRegistrationField looks like:

public class AccountRegistrationFieldMap : ClassMap<AccountRegistrationField>
{
    public AccountRegistrationFieldMap()
    {
        Table("AccountRegistrationField");

        Id(r => r.ID).Column("RegistrationID");
        Map(r => r.AccountID);
        Map(r => r.DefaultValue);
        Map(r => r.IsRequired);
        Map(r => r.Label);
        Map(r => r.Priority);
        References<RegistrationField>(
                 Reveal.Member<AccountRegistrationField>("RegistrationField"))
            .Column("FieldID");

    }
}


问:
How should I handle error of incorrect format JSON response against my object model? [ES6]
Suppose I have a backend API service that returns a JSON object of employee

{
  id: '1',
  first_name: 'John',
  last_name: 'Doe'
}```
</div>
</div>
</p>

<p>And, in my Front-end app, I created a model of exactly same format as the expected JSON response from backend</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Employee {
  id: string;
  first_name: string;
  last_name: string
}</code>```

My app will behave correctly without any error, until one day, the backend engineer decided to change the JSON object to

{
  id: '1',
  fname: 'John',
  lname: 'Doe'
}```

As the guy who handles the front-end code, how should I handle the behaviour of my app, so it doesn't blatantly throw unexpected behaviour to user's face.

答:
If you are passing object to your constructor function you can set default values using || in case there is no specific key in object.

class Employee {
 constructor(params) {
  this.id = params.id || 'default value';
  this.first_name = params.first_name || params.fname || 'default value';
  this.last_name = params.last_name || params.lname || 'default value';
 }
}

var e = new Employee({
  id: '1',
  fname: 'John',
  lname: 'Doe'
})

console.log(e)```

Body:
Suppose I have a backend API service that returns a JSON object of employee

{
  id: '1',
  first_name: 'John',
  last_name: 'Doe'
}

And, in my Front-end app, I created a model of exactly same format as the expected JSON response from backend

class Employee {
  id: string;
  first_name: string;
  last_name: string
}

My app will behave correctly without any error, until one day, the backend engineer decided to change the JSON object to

{
  id: '1',
  fname: 'John',
  lname: 'Doe'
}

As the guy who handles the front-end code, how should I handle the behaviour of my app, so it doesn't blatantly throw unexpected behaviour to user's face.


问:
Push a bunch of files to Android Studio emulator
I want to put some files, as matter of fact, there are many (about 50 or 70), to       sd card emulator or wherever is possible.

I tried the topic below,

How to Push Files to an Emulator Instance using android studio

and I even failed to push one file.

Following the topic:

In the DDMS,Explorer everything is disabled.

DDMS Image

Using ADB, I got the message below:

adb is not recognized as an internal or external command,
  operable program or batch file.

... and I'm not quite sure how to use adb; What is the meaning of <local> or <remote>; how adb can understand where the file I want to send are?!
and is it possible to push a folder with more than one files included?

Thank you.

答:
Wow!! finally, the problem solved. Thanks of both of you guys.
I upgraded to the latest version and I tried to run the Emulator and then AVD nothing happened; frustrating.
For once again I desperately tried what @Paul Jay said and this time, it worked.
Thankyou!</p>


问:
Cron job does not load virtualenv env var for working with django.setup()
Well, I have a project structure like this one:

```<code>my_project
   |-scripts
   |  |- my_script.py
   |
   |-django_project
      |- myApp
      |  |- models.py
      |  |- ...
      |- django_project
         |- settings.py
         |- ...
</code>```

I run Django inside a virtualenv and in my_script.py I have to use some of myApp.models

So, here is how I did:

my_script.py:

```<code>#!/usr/bin/env python
import django
django.setup()

from myApp.models import foo

# do things
</code>```

Since I am inside a virtualenv, to make django.setup() work properly I set in my virtualenv ($VIRTUAL_ENV/bin/postactivate):

```<code>export DJANGO_SETTINGS_MODULE = django_project.settings
</code>```

and I added django_project to the path:

```<code>$ workon my_virtualenv
$ python -c "import sys; print sys.path"
['', '/my_project/django_project', ...]
</code>```

And that's all.

If I activate my virtualenv and then I run my_script.py all works fine.

But If I schedule a similar cron job:

00 00 * * * /.../.virtualenvs/my_virtualenv/bin/python /.../my_project/scripts/my_script.py >> /.../test/test.log 2>&1

I get this error:

django.core.exceptions.ImproperlyConfigured: Requested setting
  LOGGING_CONFIG, but settings are not configured. You must either
  define the environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings.

It seems like my_virtualenv activation settings are not properly loaded.

Why does this happen, and how can I fix?

答:
try with this on your python file:

```<code>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings")
import django
django.setup()
</code>```

and I suggest you to locate your my_scriptfile to your project root directory where the manage.pyfile is.

If not working, try like this:

```<code>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.django_project.settings")
import django
django.setup()
</code>```

Body:
Well, I have a project structure like this one:

my_project
   |-scripts
   |  |- my_script.py
   |
   |-django_project
      |- myApp
      |  |- models.py
      |  |- ...
      |- django_project
         |- settings.py
         |- ...

I run Django inside a virtualenv and in my_script.py I have to use some of myApp.models

So, here is how I did:

my_script.py:

#!/usr/bin/env python
import django
django.setup()

from myApp.models import foo

# do things

Since I am inside a virtualenv, to make django.setup() work properly I set in my virtualenv ($VIRTUAL_ENV/bin/postactivate):

export DJANGO_SETTINGS_MODULE = django_project.settings

and I added django_project to the path:

$ workon my_virtualenv
$ python -c "import sys; print sys.path"
['', '/my_project/django_project', ...]

And that's all.

If I activate my virtualenv and then I run my_script.py all works fine.

But If I schedule a similar cron job:

00 00 * * * /.../.virtualenvs/my_virtualenv/bin/python /.../my_project/scripts/my_script.py >> /.../test/test.log 2>&1

I get this error:

django.core.exceptions.ImproperlyConfigured: Requested setting
  LOGGING_CONFIG, but settings are not configured. You must either
  define the environment variable DJANGO_SETTINGS_MODULE or call
  settings.configure() before accessing settings.

It seems like my_virtualenv activation settings are not properly loaded.

Why does this happen, and how can I fix?

Body:
try with this on your python file:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings")
import django
django.setup()

and I suggest you to locate your my_scriptfile to your project root directory where the manage.pyfile is.

If not working, try like this:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.django_project.settings")
import django
django.setup()