问:
using svn://localhost/repos works fine. using svn+ssh://localhost/repos: got No repository found
i am setting up a svn repository.
   everything got ready.
   when i typed  svn list svn://localhost/repos/, it showed the repository correctly.
   when i typed  svn list svn+ssh://localhost/repos, it said svn: No repository found in 'svn+ssh://localhost/repos/ktbdbms'

```<code>user account and password all correct.
</code>```

do i miss anything?

Thanks

答:
svn+ssh uses svnserve.  if you do a pgrep for svnserve it is likely run with -r /path/to/repos and the repository on the filesystem would be /path/to/repos/ktbdbms

a common solution is to move svnserve to svnserve.bin and create a bash script named svnserve which runs:

```<code>#!/bin/bash
svnserve -r /path/to/repos $*
</code>```

Body:
i am setting up a svn repository.
   everything got ready.
   when i typed  svn list svn://localhost/repos/, it showed the repository correctly.
   when i typed  svn list svn+ssh://localhost/repos, it said svn: No repository found in 'svn+ssh://localhost/repos/ktbdbms'

user account and password all correct.

do i miss anything?

Thanks

Body:
svn+ssh uses svnserve.  if you do a pgrep for svnserve it is likely run with -r /path/to/repos and the repository on the filesystem would be /path/to/repos/ktbdbms

a common solution is to move svnserve to svnserve.bin and create a bash script named svnserve which runs:

#!/bin/bash
svnserve -r /path/to/repos $*


来源: stackexchange

问:
Backing up a Single Table in mysql
what is the proper way to backup a Single file in Mysql and save it as a .bak Extention?

I tried

```<code>mysqldump db_name table_name > table_name.sql
</code>```

but i just get a syntax error saying its not a proper statement

Thankyou

答:
```<code>mysqldump -uUsername -pPassword db_name table_name>C:\table_name.sql
</code>```

-u: your db username

-p your db password

C:\table_name.sql    need be absolute path

ContentLicense: CC BY-SA 4.0

Title: Backing up a Single Table in mysql

Body:
what is the proper way to backup a Single file in Mysql and save it as a .bak Extention?

I tried

mysqldump db_name table_name > table_name.sql

but i just get a syntax error saying its not a proper statement

Thankyou

Body:
mysqldump -uUsername -pPassword db_name table_name>C:\table_name.sql

-u: your db username

-p your db password

C:\table_name.sql    need be absolute path


问:
Fork subdirectory of repo as a different repo in github
I'd like to create a bower package / stylesheet for League of Moveable Type's Chunk typeface amongst other similar tasks.

I'm wondering if it's possible to fork their "webfonts" directory into a "fonts" directory in a new repo. This would allow me to create a bower.json file and stylesheet.

Thanks,

答:
Github has posted an article how to do this at https://help.github.com/en/articles/splitting-a-subfolder-out-into-a-new-repository:

You can turn a folder within a Git repository into a brand new
  repository.

If you create a new clone of the repository, you won't lose any of
  your Git history or changes when you split a folder into a separate
  repository.

Open Terminal.

Change the current working directory to the location where you want to create your new repository.

Clone the repository that contains the subfolder.

```<code>$ git clone https://github.com/USERNAME/REPOSITORY-NAME
</code>```

Change the current working directory to your cloned repository.

```<code>$ cd REPOSITORY-NAME
</code>```

To filter out the subfolder from the rest of the files in the repository, run git filter-branch, supplying this information:

FOLDER-NAME: The folder within your project that you'd like to create a separate repository from.

BRANCH-NAME: The default branch for your current project, for example, master or gh-pages.

```<code>$ git filter-branch --prune-empty --subdirectory-filter FOLDER-NAME  BRANCH-NAME
 # Filter the specified branch in your directory and remove empty commits
 > Rewrite 48dc599c80e20527ed902928085e7861e6b3cbe6 (89/89)
 > Ref 'refs/heads/BRANCH-NAME' was rewritten
</code>```

The repository should now only contain the files that were in your subfolder.

Create a new repository on GitHub.

At the top of your new GitHub repository's Quick Setup page, click the clipboard to copy the remote repository URL.

Copy remote repository URL field

Check the existing remote name for your repository. For example, origin or upstream are two common choices.

```<code>$ git remote -v
 > origin  https://github.com/USERNAME/REPOSITORY-NAME.git (fetch)
 > origin  https://github.com/USERNAME/REPOSITORY-NAME.git (push)
</code>```

Set up a new remote URL for your new repository using the existing
  remote name and the remote repository URL you copied in step 7.

```<code>git remote set-url origin
https://github.com/USERNAME/NEW-REPOSITORY-NAME.git
</code>```

Verify that the remote URL has changed with your new repository name.

```<code>$ git remote -v
 # Verify new remote URL
 > origin  https://github.com/USERNAME/NEW-REPOSITORY-NAME.git (fetch)
 > origin  https://github.com/USERNAME/NEW-REPOSITORY-NAME.git (push)
</code>```

Push your changes to the new repository on GitHub.

```<code>git push -u origin BRANCH-NAME
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Github has posted an article how to do this at https://help.github.com/en/articles/splitting-a-subfolder-out-into-a-new-repository:

You can turn a folder within a Git repository into a brand new
  repository.

If you create a new clone of the repository, you won't lose any of
  your Git history or changes when you split a folder into a separate
  repository.

Open Terminal.

Change the current working directory to the location where you want to create your new repository.

Clone the repository that contains the subfolder.

$ git clone https://github.com/USERNAME/REPOSITORY-NAME

Change the current working directory to your cloned repository.

$ cd REPOSITORY-NAME

To filter out the subfolder from the rest of the files in the repository, run git filter-branch, supplying this information:

FOLDER-NAME: The folder within your project that you'd like to create a separate repository from.

BRANCH-NAME: The default branch for your current project, for example, master or gh-pages.

$ git filter-branch --prune-empty --subdirectory-filter FOLDER-NAME  BRANCH-NAME
 # Filter the specified branch in your directory and remove empty commits
 > Rewrite 48dc599c80e20527ed902928085e7861e6b3cbe6 (89/89)
 > Ref 'refs/heads/BRANCH-NAME' was rewritten

The repository should now only contain the files that were in your subfolder.

Create a new repository on GitHub.

At the top of your new GitHub repository's Quick Setup page, click the clipboard to copy the remote repository URL.

Copy remote repository URL field

Check the existing remote name for your repository. For example, origin or upstream are two common choices.

$ git remote -v
 > origin  https://github.com/USERNAME/REPOSITORY-NAME.git (fetch)
 > origin  https://github.com/USERNAME/REPOSITORY-NAME.git (push)

Set up a new remote URL for your new repository using the existing
  remote name and the remote repository URL you copied in step 7.

git remote set-url origin
https://github.com/USERNAME/NEW-REPOSITORY-NAME.git

Verify that the remote URL has changed with your new repository name.

$ git remote -v
 # Verify new remote URL
 > origin  https://github.com/USERNAME/NEW-REPOSITORY-NAME.git (fetch)
 > origin  https://github.com/USERNAME/NEW-REPOSITORY-NAME.git (push)

Push your changes to the new repository on GitHub.

git push -u origin BRANCH-NAME


问:
Create big navigation bars with title in Xcode
I'm new into iOS development and I'd like to know how to create navigation bars like this one:

I've been creating this manually for some time, but have recently discovered there was a way to accomplish this by using Navigation Items and Bars.

I've also tried looking up on the internet on how to do this, but haven't found anything.

Sorry if it is a stupid question and something really easy to do.

Thanks

答:
UINavigationController‘s UINavigationBar has the prefersLargeTitles property. Set it to true to enable large title

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Home"
    self.navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refreshBtnAction(_:)))
}
@objc func refreshBtnAction(_ sender: Any) {

}
</code>```

Body:
UINavigationController‘s UINavigationBar has the prefersLargeTitles property. Set it to true to enable large title

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Home"
    self.navigationController?.navigationBar.prefersLargeTitles = true
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refreshBtnAction(_:)))
}
@objc func refreshBtnAction(_ sender: Any) {

}


问:
Rancher Kube API Health Check Failure via Cluster API Build
I am trying to create a new cluster using API calls + Ansible with AWS as Cloud Provider. I have generated the required Node Templates and moving onto triggering the build.

When I trigger the Cluster creation from UI using the built nodetemplates, the cluster creation is successful as expected.

When I trigger the Cluster creation via code, the cluster deploys most of the cluster but then fails at Health Check.

I have attempted to build via UI - and it works every time.

I also tried changing the API called parameters, but none of them takes effect.

```<code>      shell: "`curl -s 'https://{{ rancher_server }}/v3/cluster' -H 'content-type: application/json' -H 'Authorization: Bearer {{ racherlogintoken.stdout }}' --data-binary '{\"dockerRootDir\":\"/var/lib/docker\",\"enableNetworkPolicy\":false,\"type\":\"cluster\",\"rancherKubernetesEngineConfig\":{\"addonJobTimeout\":30,\"ignoreDockerVersion\":true,\"kubernetesVersion\": \"v1.11.5-rancher1-1\",\"sshAgentAuth\":false,\"type\":\"rancherKubernetesEngineConfig\",\"authentication\":{\"type\":\"authnConfig\",\"strategy\":\"x509\"},\"network\":{\"type\":\"networkConfig\",\"plugin\":\"calico\"}, \"cloudProvider\":{\"awsCloudProvider\":{\"type\":\"/v3/schemas/awsCloudProvider\"}, \"name\":\"aws\", \"type\":\"/v3/schemas/cloudProvider\"},\"monitoring\":{\"type\":\"monitoringConfig\",\"provider\":\"metrics-server\"}, \"services\":{\"type\":\"rkeConfigServices\",\"kubeApi\":{\"podSecurityPolicy\":false,\"type\":\"kubeAPIService\"},\"etcd\":{\"snapshot\":false,\"type\":\"etcdService\",\"extraArgs\":{\"heartbeat-interva\":500,\"election-timeout\":5000}}}},\"name\":\"{{ mdio_cluster_name }}\"}' --insecure` | jq -r .data[].id"

Errors:

2019/06/01 07:40:28 [ERROR] cluster [c-sgd2w] provisioning: [controlPlane] Failed to bring up Control Plane: Failed to verify healthcheck: Failed to check https://localhost:6443/healthz for service [kube-apiserver] on host [x.x.x.x]: Get https://localhost:6443/healthz: read tcp [::1]:60288->[::1]:6443: read: connection reset by peer, log: I0601 07:40:24.813709       1 plugins.go:161] Loaded 6 validating admission controller(s) successfully in the following order: LimitRanger,ServiceAccount,Priority,PersistentVolumeClaimResize,ValidatingAdmissionWebhook,ResourceQuota.
2019/06/01 07:40:28 [ERROR] ClusterController c-sgd2w [cluster-provisioner-controller] failed with : [controlPlane] Failed to bring up Control Plane: Failed to verify healthcheck: Failed to check https://localhost:6443/healthz for service [kube-apiserver] on host [x.x.x.x]: Get https://localhost:6443/healthz: read tcp [::1]:60288->[::1]:6443: read: connection reset by peer, log: I0601 07:40:24.813709       1 plugins.go:161] Loaded 6 validating admission controller(s) successfully in the following order: LimitRanger,ServiceAccount,Priority,PersistentVolumeClaimResize,ValidatingAdmissionWebhook,ResourceQuota.
2019/06/01 07:40:30 [INFO] 2019/06/01 07:40:30 http: multiple response.WriteHeader calls
2019/06/01 07:40:40 [INFO] 2019/06/01 07:40:40 http: multiple response.WriteHeader calls
2019/06/01 07:40:50 [INFO] 2019/06/01 07:40:50 http: multiple response.WriteHeader calls
</code>```

答: and looks like it was the networking "calico" that was causing the problem. Used 'canal' and things are behaving better.</p>

Body:
I am trying to create a new cluster using API calls + Ansible with AWS as Cloud Provider. I have generated the required Node Templates and moving onto triggering the build.

When I trigger the Cluster creation from UI using the built nodetemplates, the cluster creation is successful as expected.

When I trigger the Cluster creation via code, the cluster deploys most of the cluster but then fails at Health Check.

I have attempted to build via UI - and it works every time.

I also tried changing the API called parameters, but none of them takes effect.

      shell: "`curl -s 'https://{{ rancher_server }}/v3/cluster' -H 'content-type: application/json' -H 'Authorization: Bearer {{ racherlogintoken.stdout }}' --data-binary '{\"dockerRootDir\":\"/var/lib/docker\",\"enableNetworkPolicy\":false,\"type\":\"cluster\",\"rancherKubernetesEngineConfig\":{\"addonJobTimeout\":30,\"ignoreDockerVersion\":true,\"kubernetesVersion\": \"v1.11.5-rancher1-1\",\"sshAgentAuth\":false,\"type\":\"rancherKubernetesEngineConfig\",\"authentication\":{\"type\":\"authnConfig\",\"strategy\":\"x509\"},\"network\":{\"type\":\"networkConfig\",\"plugin\":\"calico\"}, \"cloudProvider\":{\"awsCloudProvider\":{\"type\":\"/v3/schemas/awsCloudProvider\"}, \"name\":\"aws\", \"type\":\"/v3/schemas/cloudProvider\"},\"monitoring\":{\"type\":\"monitoringConfig\",\"provider\":\"metrics-server\"}, \"services\":{\"type\":\"rkeConfigServices\",\"kubeApi\":{\"podSecurityPolicy\":false,\"type\":\"kubeAPIService\"},\"etcd\":{\"snapshot\":false,\"type\":\"etcdService\",\"extraArgs\":{\"heartbeat-interva\":500,\"election-timeout\":5000}}}},\"name\":\"{{ mdio_cluster_name }}\"}' --insecure` | jq -r .data[].id"

Errors:

2019/06/01 07:40:28 [ERROR] cluster [c-sgd2w] provisioning: [controlPlane] Failed to bring up Control Plane: Failed to verify healthcheck: Failed to check https://localhost:6443/healthz for service [kube-apiserver] on host [x.x.x.x]: Get https://localhost:6443/healthz: read tcp [::1]:60288->[::1]:6443: read: connection reset by peer, log: I0601 07:40:24.813709       1 plugins.go:161] Loaded 6 validating admission controller(s) successfully in the following order: LimitRanger,ServiceAccount,Priority,PersistentVolumeClaimResize,ValidatingAdmissionWebhook,ResourceQuota.
2019/06/01 07:40:28 [ERROR] ClusterController c-sgd2w [cluster-provisioner-controller] failed with : [controlPlane] Failed to bring up Control Plane: Failed to verify healthcheck: Failed to check https://localhost:6443/healthz for service [kube-apiserver] on host [x.x.x.x]: Get https://localhost:6443/healthz: read tcp [::1]:60288->[::1]:6443: read: connection reset by peer, log: I0601 07:40:24.813709       1 plugins.go:161] Loaded 6 validating admission controller(s) successfully in the following order: LimitRanger,ServiceAccount,Priority,PersistentVolumeClaimResize,ValidatingAdmissionWebhook,ResourceQuota.
2019/06/01 07:40:30 [INFO] 2019/06/01 07:40:30 http: multiple response.WriteHeader calls
2019/06/01 07:40:40 [INFO] 2019/06/01 07:40:40 http: multiple response.WriteHeader calls
2019/06/01 07:40:50 [INFO] 2019/06/01 07:40:50 http: multiple response.WriteHeader calls


问:
How to efficiently get values of each row in a tensor using indices?
I have a tensor called my_tensor with tha shape of [batch_size, seq_length] and I have another tensor named idx with tha shape of [batch_size, 1] which is comprised of indices which start at 0 and finish at "seq_length".

I want to extract the values of in each row of my_tensor on using the indices defined in idx.

I tried to use tf.gather_nd and tf.gather but I was not successful.

Consider the following example:

```<code>batch_size = 3
seq_length = 5
idx = [2, 0, 4]

my_tensor = tf.random.uniform(shape=(batch_size, seq_length))
</code>```

I want to get the values at

```<code>[[0, 2],
 [1, 0],
 [3, 4]]
</code>```

from my_tensor.

I have to do further process over them, so I would like to have them at the same time (I don't know if it is even possible) and in an efficient way; however, I could not come up with any other methods.

I appreciate any help :)

答:
The trick is to first convert your set of indices into a boolean mask which you can then use to reduce my_tensor as you have described using the boolean_mask operation.

You can accomplish this by one-hot encoding the idx tensor.

So, where idx = [2, 0, 4] we can do tf.one_hot(idx, seq_length) in order to convert it to something like this:

[ [0., 0., 1., 0., 0.],
  [1., 0., 0., 0., 0.],
  [0., 0., 0., 0., 1.] ]
```

<p>Then, putting it all together for, say <code>my_tensor</code>:</p>

<pre class="lang-py prettyprint-override"><code>[ [0.6413697 , 0.4079175 , 0.42499018, 0.3037368 , 0.8580252 ],
  [0.8698617 , 0.29096508, 0.11531639, 0.25421357, 0.5844104 ],
  [0.6442119 , 0.31816053, 0.6245482 , 0.7249261 , 0.7595779 ] ]

</code>```

we can proceed as follows:

result = tf.boolean_mask(my_tensor, tf.one_hot(idx,seq_length))
```

<p>to give:</p>

<pre class="lang-py prettyprint-override"><code>[0.42499018, 0.8698617 , 0.7595779 ]
</code>```

as expected

Body:
I have a tensor called my_tensor with tha shape of [batch_size, seq_length] and I have another tensor named idx with tha shape of [batch_size, 1] which is comprised of indices which start at 0 and finish at "seq_length".

I want to extract the values of in each row of my_tensor on using the indices defined in idx.

I tried to use tf.gather_nd and tf.gather but I was not successful.

Consider the following example:

batch_size = 3
seq_length = 5
idx = [2, 0, 4]

my_tensor = tf.random.uniform(shape=(batch_size, seq_length))

I want to get the values at

[[0, 2],
 [1, 0],
 [3, 4]]

from my_tensor.

I have to do further process over them, so I would like to have them at the same time (I don't know if it is even possible) and in an efficient way; however, I could not come up with any other methods.

I appreciate any help :)

Body:
The trick is to first convert your set of indices into a boolean mask which you can then use to reduce my_tensor as you have described using the boolean_mask operation.

You can accomplish this by one-hot encoding the idx tensor.

So, where idx = [2, 0, 4] we can do tf.one_hot(idx, seq_length) in order to convert it to something like this:

[ [0., 0., 1., 0., 0.],
  [1., 0., 0., 0., 0.],
  [0., 0., 0., 0., 1.] ]

Then, putting it all together for, say my_tensor:

[ [0.6413697 , 0.4079175 , 0.42499018, 0.3037368 , 0.8580252 ],
  [0.8698617 , 0.29096508, 0.11531639, 0.25421357, 0.5844104 ],
  [0.6442119 , 0.31816053, 0.6245482 , 0.7249261 , 0.7595779 ] ]

we can proceed as follows:

result = tf.boolean_mask(my_tensor, tf.one_hot(idx,seq_length))

to give:

[0.42499018, 0.8698617 , 0.7595779 ]

as expected


问:
how to fetch a images from database using retrofit 2
Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to fetch a image using retrofit2. I am trying to fetch the image in recyclerview from the database

Code is Here:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_product);
    Intent intent = getIntent();
    parent = intent.getStringExtra("Parent");
    child = intent.getStringExtra("Child");
    Toast.makeText(this, parent+child, Toast.LENGTH_SHORT).show();
    //init firebase
    //load menu
    recycler_menu =(RecyclerView)findViewById(R.id.recycler_view);
    apiInterface =
    ApiClient.getRetrofit().create(ApiInterface.class);
    recycler_menu.setLayoutManager(new GridLayoutManager(this, 2));
    recycler_menu.setHasFixedSize(true);

    mUploads = new ArrayList<>();
    loadMenu();

   }
     private void loadMenu(){

     Toast.makeText(Product.this, "Hello",
     Toast.LENGTH_SHORT).show();
     Call<Upload> call = apiInterface.performProduct(parent,child);
     call.enqueue(new Callback<Upload>() {
         @Override
         public void onResponse(Call<Upload> call, Response<Upload>
        response) {
             Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
             mAdapter = new ImageAdapter(Product.this, mUploads);
             mRecyclerView.setAdapter(mAdapter);
         }
         @Override
         public void onFailure(Call<Upload> call, Throwable t) {

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

ImageAdapter.java .

```<code>public ImageAdapter(Context context, List<Upload> uploads) {
    mContext = context;
    mUploads = uploads;
}

@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
    return new ImageViewHolder(v);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getImgName());
    holder.textViewPrice.setText(uploadCurrent.getPrice());
    Picasso.get()
            .load(uploadCurrent.getImgUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);
    //holder.collection.setText(uploadCurrent.getmRadioGroup());
}

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

public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
        View.OnCreateContextMenuListener {
    public TextView textViewName;
    public TextView textViewPrice;
    public ImageView imageView;

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

        textViewName = itemView.findViewById(R.id.menu_name);
        textViewPrice = itemView.findViewById(R.id.menu_price);
        imageView = itemView.findViewById(R.id.menu_price);

        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onClick(View v) {
        if (mListener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                mListener.onItemClick(position);
            }
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select Action");
        MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
        MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
    }

}

public interface OnItemClickListener {
    void onItemClick(int position);
}

public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
}
</code>```

Upload.class

```<code>public class Upload {
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@SerializedName("id")
private String id;
@SerializedName("image")
private String imgName;
@SerializedName("imgUrl")
private String imgUrl;
@SerializedName("price")
private String price;
@SerializedName("description")
private String Description;
@SerializedName("response")
private String Response;

public  String getResponse(){
    return Response;
}

public Upload() {
}

public Upload(String id,String imgName, String imgUrl, String price, String Description) {
    this.id = id;
    this.imgName = imgName;
    this.imgUrl = imgUrl;
    this.price = price;
    this.Description = Description;
}

public String getImgName() {
    return imgName;
}

public void setImgName(String imgName) {
    this.imgName = imgName;
}

public String getImgUrl() {
    return imgUrl;
}

public void setImgUrl(String imgUrl) {
    this.imgUrl = imgUrl;
}

public String getDescription() {
    return Description;
}

public void setDescription(String Description) {
    this.Description = Description;
}
public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}
</code>```

}

PHP File:

```<code> <?php include ("conn.php");
 $type = $_GET["parent"];
 $ttype = $_GET["child"];
 $sth = $conn->prepare("SELECT * from product where type='$type' &&
 s_type='$ttype'");
 $sth->execute();
 While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
 $name = $data['name'];
 $id = $data['id'];
 $des = $data['description'];
 $price = $data['price'];
 $image = $data['image'];
 $status = "ok";
 echo
 json_encode(array("response"=>$status,
 "img"=>$image,"name"=>$name,
 "id"=>$id,"description"=>$des,"price"=>$price));
  }?>
</code>```

this code does nothing a blank screen appers

答:
From your endpoint I got the following response

```<code>{"response":"ok","img":"greypant.jpg","name":"GreyPant","id":"1","description":"A very fine pant with great finishing.","price":"1500"}
</code>```

you can try making the following edits to your PHP file to get the full path to the image file(s).

```<code><?php
include ("conn.php");
$type = $_GET["parent"];
$ttype = $_GET["child"];
$sth = $conn->prepare("SELECT * from product where type='$type' &&
s_type='$ttype'");
$sth->execute();
While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
    $name = $data['name'];
    $id = $data['id'];
    $des = $data['description'];
    $price = $data['price'];
    $image = $data['image'];
    $status = "ok";
    echo json_encode(array("response"=>$status,
       "img"=> "http://yourdomain.com/{$image}",
       "name"=>$name,
       "id"=>$id,
       "description"=>$des,
       "price"=>$price));
   }
?>
</code>```

replace http://yourdomain.com/ with the full path to the directory where your image is saved. Good luck!

Body:
Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to fetch a image using retrofit2. I am trying to fetch the image in recyclerview from the database

Code is Here:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_product);
    Intent intent = getIntent();
    parent = intent.getStringExtra("Parent");
    child = intent.getStringExtra("Child");
    Toast.makeText(this, parent+child, Toast.LENGTH_SHORT).show();
    //init firebase
    //load menu
    recycler_menu =(RecyclerView)findViewById(R.id.recycler_view);
    apiInterface =
    ApiClient.getRetrofit().create(ApiInterface.class);
    recycler_menu.setLayoutManager(new GridLayoutManager(this, 2));
    recycler_menu.setHasFixedSize(true);

    mUploads = new ArrayList<>();
    loadMenu();

   }
     private void loadMenu(){

     Toast.makeText(Product.this, "Hello",
     Toast.LENGTH_SHORT).show();
     Call<Upload> call = apiInterface.performProduct(parent,child);
     call.enqueue(new Callback<Upload>() {
         @Override
         public void onResponse(Call<Upload> call, Response<Upload>
        response) {
             Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
             mAdapter = new ImageAdapter(Product.this, mUploads);
             mRecyclerView.setAdapter(mAdapter);
         }
         @Override
         public void onFailure(Call<Upload> call, Throwable t) {

         }
     });
 }}

ImageAdapter.java .

public ImageAdapter(Context context, List<Upload> uploads) {
    mContext = context;
    mUploads = uploads;
}

@Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
    return new ImageViewHolder(v);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getImgName());
    holder.textViewPrice.setText(uploadCurrent.getPrice());
    Picasso.get()
            .load(uploadCurrent.getImgUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);
    //holder.collection.setText(uploadCurrent.getmRadioGroup());
}

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

public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
        View.OnCreateContextMenuListener {
    public TextView textViewName;
    public TextView textViewPrice;
    public ImageView imageView;

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

        textViewName = itemView.findViewById(R.id.menu_name);
        textViewPrice = itemView.findViewById(R.id.menu_price);
        imageView = itemView.findViewById(R.id.menu_price);

        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onClick(View v) {
        if (mListener != null) {
            int position = getAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                mListener.onItemClick(position);
            }
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select Action");
        MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
        MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
    }

}

public interface OnItemClickListener {
    void onItemClick(int position);
}

public void setOnItemClickListener(OnItemClickListener listener) {
    mListener = listener;
}

Upload.class

public class Upload {
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@SerializedName("id")
private String id;
@SerializedName("image")
private String imgName;
@SerializedName("imgUrl")
private String imgUrl;
@SerializedName("price")
private String price;
@SerializedName("description")
private String Description;
@SerializedName("response")
private String Response;

public  String getResponse(){
    return Response;
}

public Upload() {
}

public Upload(String id,String imgName, String imgUrl, String price, String Description) {
    this.id = id;
    this.imgName = imgName;
    this.imgUrl = imgUrl;
    this.price = price;
    this.Description = Description;
}

public String getImgName() {
    return imgName;
}

public void setImgName(String imgName) {
    this.imgName = imgName;
}

public String getImgUrl() {
    return imgUrl;
}

public void setImgUrl(String imgUrl) {
    this.imgUrl = imgUrl;
}

public String getDescription() {
    return Description;
}

public void setDescription(String Description) {
    this.Description = Description;
}
public String getPrice() {
    return price;
}

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

}

PHP File:

 <?php include ("conn.php");
 $type = $_GET["parent"];
 $ttype = $_GET["child"];
 $sth = $conn->prepare("SELECT * from product where type='$type' &&
 s_type='$ttype'");
 $sth->execute();
 While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
 $name = $data['name'];
 $id = $data['id'];
 $des = $data['description'];
 $price = $data['price'];
 $image = $data['image'];
 $status = "ok";
 echo
 json_encode(array("response"=>$status,
 "img"=>$image,"name"=>$name,
 "id"=>$id,"description"=>$des,"price"=>$price));
  }?>

this code does nothing a blank screen appers

Body:
From your endpoint I got the following response

{"response":"ok","img":"greypant.jpg","name":"GreyPant","id":"1","description":"A very fine pant with great finishing.","price":"1500"}

you can try making the following edits to your PHP file to get the full path to the image file(s).

<?php
include ("conn.php");
$type = $_GET["parent"];
$ttype = $_GET["child"];
$sth = $conn->prepare("SELECT * from product where type='$type' &&
s_type='$ttype'");
$sth->execute();
While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
    $name = $data['name'];
    $id = $data['id'];
    $des = $data['description'];
    $price = $data['price'];
    $image = $data['image'];
    $status = "ok";
    echo json_encode(array("response"=>$status,
       "img"=> "http://yourdomain.com/{$image}",
       "name"=>$name,
       "id"=>$id,
       "description"=>$des,
       "price"=>$price));
   }
?>

replace http://yourdomain.com/ with the full path to the directory where your image is saved. Good luck!


问:
IIS Rewrite Not Working
I'm trying to get URL rewriting working but having problems. I have several rules set up with BlogEngine.NET and I want to redirect several pages to a "Coming Soon" page. Despite being able to access a valid page at mydomain.com/page/coming-soon.aspx by typing it directly, if I try to access it via mydomain.com/category.aspx, the rule below does not work - I just get a 404 that '/page/coming-soon.aspx' does not exist. </p>

```<code>  <rule name="Coming Soon4" stopProcessing="true">
      <match url="^category.aspx/?$" />
      <action type="Rewrite" url="page/Coming-Soon.aspx" />
  </rule>
</code>```

答: Don't you mean to have type="Redirect" instead of Rewrite?

Title: IIS Rewrite Not Working

Body:
I'm trying to get URL rewriting working but having problems. I have several rules set up with BlogEngine.NET and I want to redirect several pages to a "Coming Soon" page. Despite being able to access a valid page at mydomain.com/page/coming-soon.aspx by typing it directly, if I try to access it via mydomain.com/category.aspx, the rule below does not work - I just get a 404 that '/page/coming-soon.aspx' does not exist.

  <rule name="Coming Soon4" stopProcessing="true">
      <match url="^category.aspx/?$" />
      <action type="Rewrite" url="page/Coming-Soon.aspx" />
  </rule>


答:
First Make Sure that you run your MYSQL then</p>

```<code>mysqldump –u[user name] -p[password] -h[hostname] [database name] [table_name] > dump.sql
</code>```

Title: Backing up a Single Table in mysql

Body:
First Make Sure that you run your MYSQL then

mysqldump –u[user name] -p[password] -h[hostname] [database name] [table_name] > dump.sql


问:
How to remove Vendor: from Dokan customer order emails
I am trying to remove the Vendor / Seller store name / URL from the emails that are sent to a customer when an order is placed.

I have looked everywhere and can find all of the email php files but still can't figure out how to remove the vendor. I can probably recreate the whole template but just want to make this simple change.

答:
When a customer purchases any product from the vendor that time a customer receives the default e-mail which sent by WooCommerce which is the new order email template. That should not have any vendor store details. Dokan is just adding the vendor email address with the admin e-mail to send the new-order notification to the vendor. Kindly check this function- dokan_wc_email_recipient_add_selleravailable in dokan-lite/includes/functions.php

If you can share a screenshot then I can provide the correct location.


问:
Php Carbon custom time range and judge whether it expires
description：

I need to get the date from the current date to the next 5 days.
  And need to customize the current time, and make some restrictions

start date：

2019-06-01

end date：

2019-06-05

Daily time period：

08 ~ 10
  10 ~ 12
  12 ~ 14
  14 ~ 16
  16 ~ 18
  18 ~ 20

Example 1:

If the current time is in the range of 2019-06-01 00:00 - 10:00

result：

array:2 [▼
  0 => [
    'date' => '2019-06-01',
    "weekstr":"Saturday",
    "subdate":"06-01"
    'timelist' => [
        [
            'period'    => '08 ~ 10',
            'starthour' => '08',
            'endhour'   => '10',
            'expired'   => false
        ]
        [
            'period'    => '10 ~ 12',
            'starthour' => '10',
            'endhour'   => '12',
            'expired'   => false
        ]
    ]
  ]
  1 => [
    'date' => '2019-06-02',
    "weekstr":"Saturday",
    "subdate":"06-01"
    'timelist' => [
        [
            'period'    => '08 ~ 10',
            'starthour' => '08',
            'endhour'   => '10',
            'expire'    => false
        ]
        [
            'period'    => '10 ~ 12',
            'starthour' => '10',
            'endhour'   => '12',
            'expire'    => false
        ]
    ]
  ]
]
```

<p>Example 2:</p>

<blockquote>
  <p>If the current time is within the range of 2019-06-01 10:00 - 11:00</p>
</blockquote>

<p>result：</p>

<pre class="lang-sh prettyprint-override"><code>array:2 [▼
  0 => [
    'date' => '2019-06-01',
    "weekstr":"Saturday",
    "subdate":"06-01"
    'timelist' => [
        [
            'period'    => '08 ~ 10',
            'starthour' => '08',
            'endhour'   => '10',
            'expire'    => true //Has passed 08:00 - 10:00 has expired, displayed as true
        ]
        [
            'period'    => '10 ~ 12',
            'starthour' => '10',
            'endhour'   => '12',
            'expire'    => false
        ]
    ]
  ]
  1 => [
    'date' => '2019-06-02',
    "weekstr":"Saturday",
    "subdate":"06-01"
    'timelist' => [
        [
            'period'    => '08 ~ 10',
            'starthour' => '08',
            'endhour'   => '10',
            'expired'   => false
        ]
        [
            'period'    => '10 ~ 12',
            'starthour' => '10',
            'endhour'   => '12',
            'expired'   => false
        ]
    ]
  ]
]
</code>```

summary: To achieve this function, I don't have a good idea at present. I want to ask for help and give me some ideas and methods, or I can give some sample code for my reference. Thank you.

Latest situation

According to the prompt given by Fabián Montero Rodríguez, I have implemented the date processing, but there is no good idea to deal with the time period.

code:

$start_date   = Carbon::now();
$end_date     = Carbon::now()->addDays(2);
$date_periods = CarbonPeriod::create($start_date, $end_date);
$dates = [];
foreach ($date_periods as $key => $date){
    $dates[$key]['date']    = $date->format('Y-m-d');
    $dates[$key]['week']    = $date->localeDayOfWeek;
    $dates[$key]['subdate'] = $date->format('m-d');
}
dd($dates);
```

<p>result:</p>

<pre class="lang-sh prettyprint-override"><code>array:3 [▼
  0 => array:3 [▼
    "date" => "2019-05-31"
    "week" => "Friday"
    "subdate" => "05-31"
  ]
  1 => array:3 [▼
    "date" => "2019-06-01"
    "week" => "Saturday"
    "subdate" => "06-01"
  ]
  2 => array:3 [▼
    "date" => "2019-06-02"
    "week" => "Sunday"
    "subdate" => "06-02"
  ]
]
</code>```

Current problem

The date range has been thought of, but the time range in each date timelist still has no good ideas to deal with, request help me

答:
Since I don't clearly understand your requirement I have separate route in web.php

Caution: be careful with setting timezones. Setting the wrong timezone in config/app.php may result in a big in expired parameter.

And written a Closure function:

```<code>    Route::any('/carbonintervaltest/', function () {
    $startDate   = Carbon::now();
    $endDate     = Carbon::now()->addDays(2);
    $dateRange = CarbonPeriod::create($startDate, $endDate);

    $dates = [];
    foreach ($dateRange as $dateKey =>  $date) {
        $dates[$dateKey]['date']    = $date->format('Y-m-d');
        $dates[$dateKey]['week']    = $date->localeDayOfWeek;
        $dates[$dateKey]['subdate'] = $date->format('m-d');
        $dates[$dateKey]['timelist'] = generateTime($date);
    }
    dd($dates);
});
function generateTime(Carbon $date)
{
    $startOfDay = $date->startOfDay();

    $eightTen = generateTwoHoursDifference($startOfDay, 8);

    $eightTenPeriod = getPeriod($eightTen);
    $tenTwelve = generateTwoHoursDifference($startOfDay, 10);
    $tenTwelvePeriod = getPeriod($tenTwelve);
    $totalTime = [$eightTenPeriod,$tenTwelvePeriod];
    return $totalTime;
}
function getPeriod(array $arrayObCarbonObj)
{
    foreach ($arrayObCarbonObj as $singleCarbonObj) {
        $eachHour[] = $singleCarbonObj->format('H');
    }
    $period = implode(' ~ ', $eachHour);
    $starthour = $eachHour[0];
    $endhour = $eachHour[1];
    $expired = !$arrayObCarbonObj['timeTwo']->isFuture();
    return   [
            'period'    => $period,
            'starthour' => $starthour,
            'endhour'   => $endhour,
            'expired'   => $expired
    ];
}
function generateTwoHoursDifference(Carbon $date, int $start, int $increment = 2)
{
    $dateFirstObj = (new Carbon)->parse($date->toDateTimeString());
    $dateSecondtObj = (new Carbon)->parse($date->toDateTimeString());
    $firstTime = $dateFirstObj->addHours($start);
    $secondTime = $dateSecondtObj->addHours($start+$increment);
    $allTime = ['timeOne' => $firstTime , 'timeTwo' => $secondTime];
    return $allTime;
}
</code>```

Import these classes in web.php:

```<code>use Carbon\Carbon;
use Carbon\CarbonPeriod;
</code>```

Paste the code at the top of the web.php file and hit the route

yourapp/carbonintervaltest

So it will give the dd result if the result is What you are looking for.

If you are not clear about it, I have created a Gist for that and pasted the entire file.

If you are facing any issue kindly comment below

https://gist.github.com/ManojKiranA/993383025928c285c30db6418e10708b

Here is the dd result

```<code>array:3 [▼
  0 => array:4 [▼
    "date" => "2019-06-01"
    "week" => "Saturday"
    "subdate" => "06-01"
    "timelist" => array:2 [▼
      0 => array:4 [▼
        "period" => "08 ~ 10"
        "starthour" => "08"
        "endhour" => "10"
        "expired" => true
      ]
      1 => array:4 [▼
        "period" => "10 ~ 12"
        "starthour" => "10"
        "endhour" => "12"
        "expired" => true
      ]
    ]
  ]
  1 => array:4 [▼
    "date" => "2019-06-02"
    "week" => "Sunday"
    "subdate" => "06-02"
    "timelist" => array:2 [▼
      0 => array:4 [▼
        "period" => "08 ~ 10"
        "starthour" => "08"
        "endhour" => "10"
        "expired" => false
      ]
      1 => array:4 [▼
        "period" => "10 ~ 12"
        "starthour" => "10"
        "endhour" => "12"
        "expired" => false
      ]
    ]
  ]
  2 => array:4 [▼
    "date" => "2019-06-03"
    "week" => "Monday"
    "subdate" => "06-03"
    "timelist" => array:2 [▼
      0 => array:4 [▼
        "period" => "08 ~ 10"
        "starthour" => "08"
        "endhour" => "10"
        "expired" => false
      ]
      1 => array:4 [▼
        "period" => "10 ~ 12"
        "starthour" => "10"
        "endhour" => "12"
        "expired" => false
      ]
    ]
  ]
]
</code>```

Body:
description：

I need to get the date from the current date to the next 5 days.
  And need to customize the current time, and make some restrictions

start date：

2019-06-01

end date：

2019-06-05

Daily time period：

08 ~ 10
  10 ~ 12
  12 ~ 14
  14 ~ 16
  16 ~ 18
  18 ~ 20

Example 1:

If the current time is in the range of 2019-06-01 00:00 - 10:00

result：

array:2 [▼
  0 => [
    'date' => '2019-06-01',
    "weekstr":"Saturday",
    "subdate":"06-01"
    'timelist' => [
        [
            'period'    => '08 ~ 10',
            'starthour' => '08',
            'endhour'   => '10',
            'expired'   => false
        ]
        [
            'period'    => '10 ~ 12',
            'starthour' => '10',
            'endhour'   => '12',
            'expired'   => false
        ]
    ]
  ]
  1 => [
    'date' => '2019-06-02',
    "weekstr":"Saturday",
    "subdate":"06-01"
    'timelist' => [
        [
            'period'    => '08 ~ 10',
            'starthour' => '08',
            'endhour'   => '10',
            'expire'    => false
        ]
        [
            'period'    => '10 ~ 12',
            'starthour' => '10',
            'endhour'   => '12',
            'expire'    => false
        ]
    ]
  ]
]

Example 2:

If the current time is within the range of 2019-06-01 10:00 - 11:00

result：

array:2 [▼
  0 => [
    'date' => '2019-06-01',
    "weekstr":"Saturday",
    "subdate":"06-01"
    'timelist' => [
        [
            'period'    => '08 ~ 10',
            'starthour' => '08',
            'endhour'   => '10',
            'expire'    => true //Has passed 08:00 - 10:00 has expired, displayed as true
        ]
        [
            'period'    => '10 ~ 12',
            'starthour' => '10',
            'endhour'   => '12',
            'expire'    => false
        ]
    ]
  ]
  1 => [
    'date' => '2019-06-02',
    "weekstr":"Saturday",
    "subdate":"06-01"
    'timelist' => [
        [
            'period'    => '08 ~ 10',
            'starthour' => '08',
            'endhour'   => '10',
            'expired'   => false
        ]
        [
            'period'    => '10 ~ 12',
            'starthour' => '10',
            'endhour'   => '12',
            'expired'   => false
        ]
    ]
  ]
]

summary: To achieve this function, I don't have a good idea at present. I want to ask for help and give me some ideas and methods, or I can give some sample code for my reference. Thank you.

Latest situation

According to the prompt given by Fabián Montero Rodríguez, I have implemented the date processing, but there is no good idea to deal with the time period.

code:

$start_date   = Carbon::now();
$end_date     = Carbon::now()->addDays(2);
$date_periods = CarbonPeriod::create($start_date, $end_date);
$dates = [];
foreach ($date_periods as $key => $date){
    $dates[$key]['date']    = $date->format('Y-m-d');
    $dates[$key]['week']    = $date->localeDayOfWeek;
    $dates[$key]['subdate'] = $date->format('m-d');
}
dd($dates);

result:

array:3 [▼
  0 => array:3 [▼
    "date" => "2019-05-31"
    "week" => "Friday"
    "subdate" => "05-31"
  ]
  1 => array:3 [▼
    "date" => "2019-06-01"
    "week" => "Saturday"
    "subdate" => "06-01"
  ]
  2 => array:3 [▼
    "date" => "2019-06-02"
    "week" => "Sunday"
    "subdate" => "06-02"
  ]
]

Current problem

The date range has been thought of, but the time range in each date timelist still has no good ideas to deal with, request help me

Body:
Since I don't clearly understand your requirement I have separate route in web.php

Caution: be careful with setting timezones. Setting the wrong timezone in config/app.php may result in a big in expired parameter.

And written a Closure function:

    Route::any('/carbonintervaltest/', function () {
    $startDate   = Carbon::now();
    $endDate     = Carbon::now()->addDays(2);
    $dateRange = CarbonPeriod::create($startDate, $endDate);

    $dates = [];
    foreach ($dateRange as $dateKey =>  $date) {
        $dates[$dateKey]['date']    = $date->format('Y-m-d');
        $dates[$dateKey]['week']    = $date->localeDayOfWeek;
        $dates[$dateKey]['subdate'] = $date->format('m-d');
        $dates[$dateKey]['timelist'] = generateTime($date);
    }
    dd($dates);
});
function generateTime(Carbon $date)
{
    $startOfDay = $date->startOfDay();

    $eightTen = generateTwoHoursDifference($startOfDay, 8);

    $eightTenPeriod = getPeriod($eightTen);
    $tenTwelve = generateTwoHoursDifference($startOfDay, 10);
    $tenTwelvePeriod = getPeriod($tenTwelve);
    $totalTime = [$eightTenPeriod,$tenTwelvePeriod];
    return $totalTime;
}
function getPeriod(array $arrayObCarbonObj)
{
    foreach ($arrayObCarbonObj as $singleCarbonObj) {
        $eachHour[] = $singleCarbonObj->format('H');
    }
    $period = implode(' ~ ', $eachHour);
    $starthour = $eachHour[0];
    $endhour = $eachHour[1];
    $expired = !$arrayObCarbonObj['timeTwo']->isFuture();
    return   [
            'period'    => $period,
            'starthour' => $starthour,
            'endhour'   => $endhour,
            'expired'   => $expired
    ];
}
function generateTwoHoursDifference(Carbon $date, int $start, int $increment = 2)
{
    $dateFirstObj = (new Carbon)->parse($date->toDateTimeString());
    $dateSecondtObj = (new Carbon)->parse($date->toDateTimeString());
    $firstTime = $dateFirstObj->addHours($start);
    $secondTime = $dateSecondtObj->addHours($start+$increment);
    $allTime = ['timeOne' => $firstTime , 'timeTwo' => $secondTime];
    return $allTime;
}

Import these classes in web.php:

use Carbon\Carbon;
use Carbon\CarbonPeriod;

Paste the code at the top of the web.php file and hit the route

yourapp/carbonintervaltest

So it will give the dd result if the result is What you are looking for.

If you are not clear about it, I have created a Gist for that and pasted the entire file.

If you are facing any issue kindly comment below

https://gist.github.com/ManojKiranA/993383025928c285c30db6418e10708b

Here is the dd result

array:3 [▼
  0 => array:4 [▼
    "date" => "2019-06-01"
    "week" => "Saturday"
    "subdate" => "06-01"
    "timelist" => array:2 [▼
      0 => array:4 [▼
        "period" => "08 ~ 10"
        "starthour" => "08"
        "endhour" => "10"
        "expired" => true
      ]
      1 => array:4 [▼
        "period" => "10 ~ 12"
        "starthour" => "10"
        "endhour" => "12"
        "expired" => true
      ]
    ]
  ]
  1 => array:4 [▼
    "date" => "2019-06-02"
    "week" => "Sunday"
    "subdate" => "06-02"
    "timelist" => array:2 [▼
      0 => array:4 [▼
        "period" => "08 ~ 10"
        "starthour" => "08"
        "endhour" => "10"
        "expired" => false
      ]
      1 => array:4 [▼
        "period" => "10 ~ 12"
        "starthour" => "10"
        "endhour" => "12"
        "expired" => false
      ]
    ]
  ]
  2 => array:4 [▼
    "date" => "2019-06-03"
    "week" => "Monday"
    "subdate" => "06-03"
    "timelist" => array:2 [▼
      0 => array:4 [▼
        "period" => "08 ~ 10"
        "starthour" => "08"
        "endhour" => "10"
        "expired" => false
      ]
      1 => array:4 [▼
        "period" => "10 ~ 12"
        "starthour" => "10"
        "endhour" => "12"
        "expired" => false
      ]
    ]
  ]
]


问:
How to get last month record from databse in laravel?

i have a table remaining_bus_fees.

```<code>id    | date         | student_id | remaining_balance
-----------------------------------------------------
1     | 2019-04-05   | 1          |     500
2     | 2019-05-10   | 2          |     400
3     | 2019-05-13   | 3          |     300
</code>```

Now i need how to get last month record against student_id. here is
  query i am using. but this is not working for me.

```<code>$remain_fee = \DB::table('remaining_bus_fees')
        ->whereMonth('date', '<', Carbon::now()->subMonth()->month)
        ->where('student_id', '=', 2)->get();
</code>```

答:
At the minute your code is saying where date is "before a month ago" whereas it should be where the date is a month ago (i.e. remove <). Also, I would suggest adding the year to the query as well otherwise you'll start to get previous years results.

This should get you what you need:

```<code>$date = Carbon::now()->subMonth();

$remain_fee = \DB::table('remaining_bus_fees')
    ->whereMonth('date', $date->month)
    ->whereYear('date', $date->year)
    ->where('student_id', 2)
    ->get();
</code>```

Body:
i have a table remaining_bus_fees.

id    | date         | student_id | remaining_balance
-----------------------------------------------------
1     | 2019-04-05   | 1          |     500
2     | 2019-05-10   | 2          |     400
3     | 2019-05-13   | 3          |     300

Now i need how to get last month record against student_id. here is
  query i am using. but this is not working for me.

$remain_fee = \DB::table('remaining_bus_fees')
        ->whereMonth('date', '<', Carbon::now()->subMonth()->month)
        ->where('student_id', '=', 2)->get();

Body:
At the minute your code is saying where date is "before a month ago" whereas it should be where the date is a month ago (i.e. remove <). Also, I would suggest adding the year to the query as well otherwise you'll start to get previous years results.

This should get you what you need:

$date = Carbon::now()->subMonth();

$remain_fee = \DB::table('remaining_bus_fees')
    ->whereMonth('date', $date->month)
    ->whereYear('date', $date->year)
    ->where('student_id', 2)
    ->get();


问:
Is @Import annotation necessary with Spring Boot?
I'm working with Spring Boot 2.1.5. I have multiple classes annotated with @Configuration.

I want to know if it's necessary to list all of these configuration classes with @Import? Or will the component scanner find all the @Configuration annotated classes and do it automatically?

答: It's not necessary to use @Import annotation.  As the @Configuration is a Meta-annotation for @Component , the Component scanner will pick it . But Spring docs suggest to use @Import annotation when you have many @Configuration classes. This is just for better management.</p>


问:
IEnumerable<T> null coalescing Extension
I frequently face the problem to check whether an IEnumerable<T> is null before iterating over it through foreach or LINQ queries, then I often come into codes like this:

```<code>var myProjection = (myList ?? Enumerable.Empty<T>()).Select(x => x.Foo)...
</code>```

Hence, I thought to add this extension-method to an Extensions class:

```<code>public static class MyExtensions
{
    public static IEnumerable<T> AsEmptyIfNull<T>(this IEnumerable<T> source)
    {
        return source ?? Enumerable.Empty<T>();
    }
}
</code>```

A little issue comes immediately in my mind looking at this code, i.e., given the "instance-methods aspect" of extension-methods, it should be implemented as a mere static method, otherwise something like this would be perfectly legal:

```<code>IEnumerable<int> list = null;
list.AsEmptyIfNull();
</code>```

Do you see any other drawback in using it ?

Can such extension leading to some kind of bad-trend in the developer(s), if massively used?

Bonus question:

Can you suggest a better name to it ?  :)

(English is not my first language, then I'm not so good in naming...)

Thanks in advance.

答:
It's generally a bad idea to return a null instead of an empty sequence if you can control it. This is self-explanatory if you consider that when someone is asked to produce a collection, returning null is not like saying "the collection is empty" but "there is no such collection at all".

If you own the methods returning the enumerables, then returning an empty IEnumerable (which can even be a special purpose readonly static object if it might be returned a lot) is the way to go, period.

If you are forced to use a bad-mannered library that has the habit of returning null in such cases, then this an extension method might be a solution, but again I wouldn't prefer it. It's probably better to wrap the bad-mannered methods in your own versions that do the coalescing where people won't see it. This way you get both the convenience of always having an enumerable instead of null and the correctness of not supporting the "return null" paradigm.

Body:
I frequently face the problem to check whether an IEnumerable<T> is null before iterating over it through foreach or LINQ queries, then I often come into codes like this:

var myProjection = (myList ?? Enumerable.Empty<T>()).Select(x => x.Foo)...

Hence, I thought to add this extension-method to an Extensions class:

public static class MyExtensions
{
    public static IEnumerable<T> AsEmptyIfNull<T>(this IEnumerable<T> source)
    {
        return source ?? Enumerable.Empty<T>();
    }
}

A little issue comes immediately in my mind looking at this code, i.e., given the "instance-methods aspect" of extension-methods, it should be implemented as a mere static method, otherwise something like this would be perfectly legal:

IEnumerable<int> list = null;
list.AsEmptyIfNull();

Do you see any other drawback in using it ?

Can such extension leading to some kind of bad-trend in the developer(s), if massively used?

Bonus question:

Can you suggest a better name to it ?  :)

(English is not my first language, then I'm not so good in naming...)

Thanks in advance.


问:
Change css dynamically from controller
I'm new with ASP.NET MVC, at the cshtml I have some style:

```<code> .circle {
     border: 2px solid red;
     background-color: #FFFFFF;
     height: 100px;
     border-radius:50%;
     width: 100px;
 }

<div class="circle"></div>
</code>```

And I want to change the circle position from the controller, I can I achieve that? In the controller I need something like:

```<code>circle.MarginLeft = 120;
</code>```

答:
You can use your model or ViewBag.

In controller pass your data into an object like circle.MarginLeft = 12 or use ViewBag['marginLeft'] = 12

and in your .cshtml file set

```<code><div class="circle" style="margin-left:@ViewBag.marginLeft"></div>
</code>```

or

```<code><div class="circle" style="margin-left:@Model.marginLeft"></div>
</code>```

Title: Change css dynamically from controller

Body:
I'm new with ASP.NET MVC, at the cshtml I have some style:

 .circle {
     border: 2px solid red;
     background-color: #FFFFFF;
     height: 100px;
     border-radius:50%;
     width: 100px;
 }

And I want to change the circle position from the controller, I can I achieve that? In the controller I need something like:

circle.MarginLeft = 120;

Body:
You can use your model or ViewBag.

In controller pass your data into an object like circle.MarginLeft = 12 or use ViewBag['marginLeft'] = 12

and in your .cshtml file set

<div class="circle" style="margin-left:@ViewBag.marginLeft"></div>

or

<div class="circle" style="margin-left:@Model.marginLeft"></div>


问:
API call working through server side code (node.js, php) but not through JS in browser using fetch()
I am trying to make an API POST request via fetch(). When I execute it server side ( PHP or Node.js ) it works properly. When trying to execute it in the browser I get two errors:
1) 405 Error - Method not allowed
2) Access to fetch at 'url' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried adding: mode: "no-cors". I then get the following error:
"401 Unauthorized"
with the following response:
401 response

Here is my standard js setup:

```<code>const TrailData = {
      email: "test@test.com",
      first_name: "sample string 5",
      last_name: "sample string 6",
      phone2: "12121212"
    };

    // TRAIL POST ( NOT WORKING )
    fetch('http://webapi.mymarketing.co.il/api/contacts', {
            method: "POST",
            mode: 'no-cors',
            headers: {
              "Authorization": "API CODE //here comes the API CODE",
              "Content-Type": "application/json"
            },
            body: JSON.stringify(TrailData)
          })
          .then(res => console.log(res) )
          .then(data => console.log(data))
          .catch(err => console.log(err))
</code>```

My Node js setup is:

```<code>var postData = {

    sms_status: "None",
    email: "test@test.com",
    first_name: "sample string 5",
    last_name: "sample string 6",
  };

  let axiosConfig = {
headers: {
    "Authorization": "API CODE",
    'Content-Type': 'application/json;charset=UTF-8',
    "Access-Control-Allow-Origin": "*",
}
  };

const Trail = async () =>{
try {
    const response = await axios.post('http://webapi.mymarketing.co.il/api/contacts', postData, axiosConfig)
    console.log(response)
} catch (error) {
    throw new Error(error)
}

  }

 Trail()
</code>```

Node JS works. I get a 200 OK response. The first one doesnt!

Is it possible that the API blocks requests made from the browser?
I have tried so many ways and failed every time using the browser.

Thank you for any help!

答:
you can't send extra headers without CORS (Authorization header)

because server does not respond to preflight request you are not allowed to send that request

without CORS you are allowed to send only "Simple requests" see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

and https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

for more information

Body:
I am trying to make an API POST request via fetch(). When I execute it server side ( PHP or Node.js ) it works properly. When trying to execute it in the browser I get two errors:
1) 405 Error - Method not allowed
2) Access to fetch at 'url' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried adding: mode: "no-cors". I then get the following error:
"401 Unauthorized"
with the following response:
401 response

Here is my standard js setup:

const TrailData = {
      email: "test@test.com",
      first_name: "sample string 5",
      last_name: "sample string 6",
      phone2: "12121212"
    };

    // TRAIL POST ( NOT WORKING )
    fetch('http://webapi.mymarketing.co.il/api/contacts', {
            method: "POST",
            mode: 'no-cors',
            headers: {
              "Authorization": "API CODE //here comes the API CODE",
              "Content-Type": "application/json"
            },
            body: JSON.stringify(TrailData)
          })
          .then(res => console.log(res) )
          .then(data => console.log(data))
          .catch(err => console.log(err))

My Node js setup is:

var postData = {

    sms_status: "None",
    email: "test@test.com",
    first_name: "sample string 5",
    last_name: "sample string 6",
  };

  let axiosConfig = {
headers: {
    "Authorization": "API CODE",
    'Content-Type': 'application/json;charset=UTF-8',
    "Access-Control-Allow-Origin": "*",
}
  };

const Trail = async () =>{
try {
    const response = await axios.post('http://webapi.mymarketing.co.il/api/contacts', postData, axiosConfig)
    console.log(response)
} catch (error) {
    throw new Error(error)
}

  }

 Trail()

Node JS works. I get a 200 OK response. The first one doesnt!

Is it possible that the API blocks requests made from the browser?
I have tried so many ways and failed every time using the browser.

Thank you for any help!


问:
How to download a file from a url, without the involvement of browser in javascript
I want to download a file from https://www.sec.gov/Archives/edgar/full-index/2018/QTR1/company.zip and I want to specify a path for it to be saved on my computer, but I dont want to use any browser intermediate. Can someone guide me how to write a script in javascript to download the file from url and save it on my pc

答:
As chintuyadavsara said, filling in this answer with your url does the trick:</p>

```<code>const https = require('https');
const fs = require('fs');

function go (src, dest) {
    const file = fs.createWriteStream(dest);
    const request = https.get(src, function(response) {
        response.pipe(file);
    });
}

go('https://www.sec.gov/Archives/edgar/full-index/2018/QTR1/company.zip', './company.zip');
</code>```

Body:
As chintuyadavsara said, filling in this answer with your url does the trick:

const https = require('https');
const fs = require('fs');

function go (src, dest) {
    const file = fs.createWriteStream(dest);
    const request = https.get(src, function(response) {
        response.pipe(file);
    });
}

go('https://www.sec.gov/Archives/edgar/full-index/2018/QTR1/company.zip', './company.zip');


问:
.htaccess/mod_rewrite: running Angular app in sub-folder?
I've

a light index.php which provides simple pages and

a more complex/heavy Angular 8.0 app, stored in the sub-folder /app.

Example URLs:

```<code>/ ......................... works: index.php, loads home page
/my-blog-post.html ........ works: index.php, loads a blog post
/any-page.htm ............. works: index.php, loads a page
/app ...................... works: home page of the Angular app
/app/login ................ DOES "NOT" WORK: sub-page of the Angular app
</code>```

Folder structure:

```<code>app/dist/app ........................................... Angular App (built files)
app/dist/app/3rdpartylicenses.txt
app/dist/app/4-es5.86e9c53554535b1b46a8.js
app/dist/app/4-es2015.bb174fcd0205a5f23647.js
app/dist/app/5-es5.b8f3fede0599cda91cf0.js
app/dist/app/5-es2015.f4890df5957b350d78ca.js
app/dist/app/favicon.ico
app/dist/app/index.html
app/dist/app/main-es5.8059496aa1855103a2ad.js
app/dist/app/main-es2015.0629f594e2c4c056133c.js
app/dist/app/polyfills-es5.943113ac054b16d954ae.js
app/dist/app/polyfills-es2015.e954256595c973372414.js
app/dist/app/runtime-es5.f2faa6ae2b23db85cc8d.js
app/dist/app/runtime-es2015.f40f45bfff52b2130730.js
app/dist/app/styles.3ff695c00d717f2d2a11.css
.htaccess ..............................................
index.php ..............................................
</code>```

app/dist/app/index.html

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>App</title>
  <base href="/app/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.3ff695c00d717f2d2a11.css"></head>
<body>
  <app-root></app-root>
<script src="runtime-es2015.f40f45bfff52b2130730.js" type="module"></script><script src="polyfills-es2015.e954256595c973372414.js" type="module"></script><script src="runtime-es5.f2faa6ae2b23db85cc8d.js" nomodule></script><script src="polyfills-es5.943113ac054b16d954ae.js" nomodule></script><script src="main-es2015.0629f594e2c4c056133c.js" type="module"></script><script src="main-es5.8059496aa1855103a2ad.js" nomodule></script></body>
</html>

</code>```

Problem:

It's possible to reach /app and afterwards app/login by clicking a link within the Angular App. It is not possible to reach the URL directly via the browsers address bar:

app/login does not work when called directly (error below)

app/ -> click Login-link -> app/login works

.htaccess

```<code>RewriteEngine on
RewriteBase /

# Page
RewriteRule ^(.*).html$ /index.php?module=page&slug=$1

# Blog
RewriteRule ^(.*).htm$ /index.php?module=blog&slug=$1

# Angular app
RewriteRule ^app/$ app/dist/app/index.html [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/(.*) app/dist/app/$1 [L]

# Remove www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# Force https
RewriteCond %{HTTPS} on
</code>```

Error

```<code># /var/log/apache2/myproject_error.log
AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
</code>```

I think the bug is somewhere in the routing of Angular app part of the .htaccess.
 index.php and the Angular app themselves work perfectly fine.

Edit

After setting imports: [RouterModule.forRoot(routes, {useHash: true})] it works with #, but I'd like to avoid the HashLocationStrategy.

Any idea?
Thanks in advance!

答:
You need to configure your HTTP server to redirect all URI which began with www.domain.com/app/ to the index.html(angular app) file so that it always serve index.html on app/.

Here's how angular suggests: Angular Deployment Server Configuration

Body:
I've

a light index.php which provides simple pages and

a more complex/heavy Angular 8.0 app, stored in the sub-folder /app.

Example URLs:

/ ......................... works: index.php, loads home page
/my-blog-post.html ........ works: index.php, loads a blog post
/any-page.htm ............. works: index.php, loads a page
/app ...................... works: home page of the Angular app
/app/login ................ DOES "NOT" WORK: sub-page of the Angular app

Folder structure:

app/dist/app ........................................... Angular App (built files)
app/dist/app/3rdpartylicenses.txt
app/dist/app/4-es5.86e9c53554535b1b46a8.js
app/dist/app/4-es2015.bb174fcd0205a5f23647.js
app/dist/app/5-es5.b8f3fede0599cda91cf0.js
app/dist/app/5-es2015.f4890df5957b350d78ca.js
app/dist/app/favicon.ico
app/dist/app/index.html
app/dist/app/main-es5.8059496aa1855103a2ad.js
app/dist/app/main-es2015.0629f594e2c4c056133c.js
app/dist/app/polyfills-es5.943113ac054b16d954ae.js
app/dist/app/polyfills-es2015.e954256595c973372414.js
app/dist/app/runtime-es5.f2faa6ae2b23db85cc8d.js
app/dist/app/runtime-es2015.f40f45bfff52b2130730.js
app/dist/app/styles.3ff695c00d717f2d2a11.css
.htaccess ..............................................
index.php ..............................................

app/dist/app/index.html

<!doctype html>

  <meta charset="utf-8">
  <title>App</title>
  <base href="/app/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.3ff695c00d717f2d2a11.css">

  <app-root></app-root>

Problem:

It's possible to reach /app and afterwards app/login by clicking a link within the Angular App. It is not possible to reach the URL directly via the browsers address bar:

app/login does not work when called directly (error below)

app/ -> click Login-link -> app/login works

.htaccess

RewriteEngine on
RewriteBase /

# Page
RewriteRule ^(.*).html$ /index.php?module=page&slug=$1

# Blog
RewriteRule ^(.*).htm$ /index.php?module=blog&slug=$1

# Angular app
RewriteRule ^app/$ app/dist/app/index.html [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/(.*) app/dist/app/$1 [L]

# Remove www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# Force https
RewriteCond %{HTTPS} on

Error

# /var/log/apache2/myproject_error.log
AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

I think the bug is somewhere in the routing of Angular app part of the .htaccess.
 index.php and the Angular app themselves work perfectly fine.

Edit

After setting imports: [RouterModule.forRoot(routes, {useHash: true})] it works with #, but I'd like to avoid the HashLocationStrategy.

Any idea?
Thanks in advance!


问:
Clock based 8 bit prime number detector
I am developing a 8 bit unsigned prime number detector in VHDL, synthesizable, for a project.The objective is to do not only avoiding to use any sort of loops or latches as well as restricting it to only the FPGA 50Mhz clock.

We tried a clock-based using successive divisions but such implementation does not meet the timing requirements in Quartus Timequest when we try to output the result.
When we comment the output it seems to work just fine, and we don't fully understand the why.

```<code>library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity primeChecker is
    generic(NumCyclesWait :integer := 1000);
    port(   clock: in  std_logic;
            enable: in  std_logic;
            reset   : in  std_logic;
            input   : in std_logic_vector(7 downto 0);
            output  : out std_logic_vector(7 downto 0);
            isPrime   : out std_logic_vector(0 downto 0));
end primeChecker;

architecture arch of primeChecker is

    signal count: integer := 0;
    signal numToCheck : integer := 0;
    signal prime, primeOut : integer := 1;
    signal s_out: unsigned(7 downto 0);
    signal div : integer := 2;
    signal clockCount : unsigned(0 downto 0) := "0";

begin

    numToCheck <= to_integer(unsigned(input));

    process(clock)
    begin
        if(rising_edge(clock)) then
                if(count = NumCyclesWait) then

                    if ((numToCheck = 1) OR (numToCheck = 0)) then

                        prime <= 0;     --Not Prime

                    elsif(numToCheck > 2 and prime =1 and div < numToCheck) then
                            if (numToCheck rem div = 0) then
                                -- if the number is divisible
                                prime <= 0;
                            end if;
                            div <= div +1;

                    end if;
                else

                    count <= count +1;

                end if;

                if(enable = '1') then
                    s_out <= to_unsigned(numToCheck,8);
                    count <= 0;
                    div <= 2;
                    primeOut <= prime;
                    prime <= 1;
                else
                    s_out <= s_out;
                end if;
        end if;

    end process;

    isPrime <= std_logic_vector(to_unsigned(primeOut,1));
    output <= std_logic_vector(s_out);

end arch ; -- arch
</code>```

I expect for it not to trigger the "Timing requirement not met" error and for it to fully compile.

答:
For fastest constant time response, I would take a different approach. Your task is to deal with eight bit numbers only and your FPGA probably has more than enough RAM to set up an 8-bit prime number lookup table where each table entry just indicates whether its index is a prime number or not:

```<code>type prime_numbers_type is array(0 to 255) of std_ulogic;
constant prime_numbers    : prime_numbers_type :=
                            ( '0', '0', '1', '1', '0', '1', ... );
</code>```

This makes the vital part of your prime number detector overly simple:

```<code>is_prime <= prime_numbers(to_integer(unsigned(num_to_check)));
</code>```

I would probably just write a small Tcl script to set up the lookup table.

Title: Clock based 8 bit prime number detector

Body:
I am developing a 8 bit unsigned prime number detector in VHDL, synthesizable, for a project.The objective is to do not only avoiding to use any sort of loops or latches as well as restricting it to only the FPGA 50Mhz clock.

We tried a clock-based using successive divisions but such implementation does not meet the timing requirements in Quartus Timequest when we try to output the result.
When we comment the output it seems to work just fine, and we don't fully understand the why.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity primeChecker is
    generic(NumCyclesWait :integer := 1000);
    port(   clock: in  std_logic;
            enable: in  std_logic;
            reset   : in  std_logic;
            input   : in std_logic_vector(7 downto 0);
            output  : out std_logic_vector(7 downto 0);
            isPrime   : out std_logic_vector(0 downto 0));
end primeChecker;

architecture arch of primeChecker is

    signal count: integer := 0;
    signal numToCheck : integer := 0;
    signal prime, primeOut : integer := 1;
    signal s_out: unsigned(7 downto 0);
    signal div : integer := 2;
    signal clockCount : unsigned(0 downto 0) := "0";

begin

    numToCheck <= to_integer(unsigned(input));

    process(clock)
    begin
        if(rising_edge(clock)) then
                if(count = NumCyclesWait) then

                    if ((numToCheck = 1) OR (numToCheck = 0)) then

                        prime <= 0;     --Not Prime

                    elsif(numToCheck > 2 and prime =1 and div < numToCheck) then
                            if (numToCheck rem div = 0) then
                                -- if the number is divisible
                                prime <= 0;
                            end if;
                            div <= div +1;

                    end if;
                else

                    count <= count +1;

                end if;

                if(enable = '1') then
                    s_out <= to_unsigned(numToCheck,8);
                    count <= 0;
                    div <= 2;
                    primeOut <= prime;
                    prime <= 1;
                else
                    s_out <= s_out;
                end if;
        end if;

    end process;

    isPrime <= std_logic_vector(to_unsigned(primeOut,1));
    output <= std_logic_vector(s_out);

end arch ; -- arch

I expect for it not to trigger the "Timing requirement not met" error and for it to fully compile.

Body:
For fastest constant time response, I would take a different approach. Your task is to deal with eight bit numbers only and your FPGA probably has more than enough RAM to set up an 8-bit prime number lookup table where each table entry just indicates whether its index is a prime number or not:

type prime_numbers_type is array(0 to 255) of std_ulogic;
constant prime_numbers    : prime_numbers_type :=
                            ( '0', '0', '1', '1', '0', '1', ... );

This makes the vital part of your prime number detector overly simple:

is_prime <= prime_numbers(to_integer(unsigned(num_to_check)));

I would probably just write a small Tcl script to set up the lookup table.


问:
What does key mean when creating a kubernetes configmap from a file
I see here a syntax like this:

```<code>kubectl create cm configmap4 --from-file=special=config4.txt
</code>```

I did not find a description of what repetition of = and the special means here.
Kubernetes documentation here only denotes one time usage of = after --from-file while creating configmaps in kubectl.

答:
It appears from generating the YAML that this middle key mean all the keys that are being loaded from the file to be nested inside the mentioned key (special keyword in the question example).

It appears like this:

```<code>apiVersion: v1
data:
  special: |
    var3=val3
    var4=val4
kind: ConfigMap
metadata:
  creationTimestamp: "2019-06-01T08:20:15Z"
  name: configmap4
  namespace: default
  resourceVersion: "123320"
  selfLink: /api/v1/namespaces/default/configmaps/configmap4
  uid: 1582b155-8446-11e9-87b7-0800277f619d
</code>```

Body:
I see here a syntax like this:

kubectl create cm configmap4 --from-file=special=config4.txt

I did not find a description of what repetition of = and the special means here.
Kubernetes documentation here only denotes one time usage of = after --from-file while creating configmaps in kubectl.

Body:
It appears from generating the YAML that this middle key mean all the keys that are being loaded from the file to be nested inside the mentioned key (special keyword in the question example).

It appears like this:

apiVersion: v1
data:
  special: |
    var3=val3
    var4=val4
kind: ConfigMap
metadata:
  creationTimestamp: "2019-06-01T08:20:15Z"
  name: configmap4
  namespace: default
  resourceVersion: "123320"
  selfLink: /api/v1/namespaces/default/configmaps/configmap4
  uid: 1582b155-8446-11e9-87b7-0800277f619d


问:
Why Facebook Graph Api returns "Field is empty or disallowed by the access token"?
I want to list Facebook Page Post in a application. Therefor I use the Facebook Graph API.

I use the following URL:
https://graph.facebook.com/v2.9/674600022698736/feed?limit=100&fields=name,comments.limit(0).summary(true),permalink_url,shares.limit(0).summary(true)&access_token=XXX

I get the response, except for the fields': icon and shares. In the feature I need more, so maybe the problem is with more fields.

De Graph Explorer gives the following response for the fields icon and shared: "Field is empty or disallowed by the access token".
The shares are certainly filled!

See:

I've made the call with both the user and the page tokens, same result.

How can I solve this problem?

答:
Although this post is old but has no answer, my answer might help someone:

If those edges are greyed out, it means you did not give or add those attributes in the access token your calling with. You need to give those permissions.
After adding such permissions for example for your case: like, comments you need to regenerate the token by clicking on the Get Access Token button and you should see it not grey anymore. Finally, you can Submit and get your desired response.

Classic Graph Explorer

1.

2

3.

Better yet, try the new beta Graph Explorer. Has a better GUI for the permissions option.
Beta Graph Explorer


问:
Is it possible to extend IEntityHistoryStore to store per-table rather than track all in the same table?
In asp.net boilerplate, we have the need to track changes to entities. I see that ABP has entity tracking (new) but it's storing all changes across entities in one table, which won't work for us. Is it possible to create a custom IEntityHistoryStore to store those changes per entity (in their own table)?

For example, let's say there's an entity Task.

[Table("Task", Schema = "Tasks")]
public class Task : Entity<int>
{
    [Column(TypeName = "varchar(255)")]
    public string Description { get; set; }
    // some more poco properties
}
```

<p>Then what I would like to define is another table, zzLog.Tasks_Task and I would like that table to look like this:</p>

```╔════════╦════════════════════════╦══════╦══════════╦════════════════════╗
║ TaskId ║      Description       ║ lgId ║ lgAction ║       lgTime       ║
╠════════╬════════════════════════╬══════╬══════════╬════════════════════╣
║      1 ║ Some description       ║    1 ║        1 ║ 2019-05-30 9:05 AM ║
║      1 ║ Some other description ║    2 ║        2 ║ 2019-05-30 9:06 AM ║
║      1 ║ Changed again          ║    3 ║        2 ║ 2019-05-30 9:07 AM ║
║      1 ║ Changed again          ║    4 ║        3 ║ 2019-05-30 9:08 AM ║
╚════════╩════════════════════════╩══════╩══════════╩════════════════════╝
```

lgAction is an enum, 1 = create, 2 = update, 3 = delete

Is this possible? Instinct says no since IEntityHistoryStore likely can't work this way.

答:
Yes, from https://aspnetboilerplate.com/Pages/Documents/Entity-History#about-ientityhistorystore:

The Entity History tracking system uses IEntityHistoryStore to save change information.  ... you can implement it in your own way ...

Implement MyEntityHistoryStore:

public class MyEntityHistoryStore : IEntityHistoryStore
{
    private readonly IRepository<zzLog.Tasks_Task> _taskLogRepository;

    public EntityHistoryStore(IRepository<zzLog.Tasks_Task> taskLogRepository)
    {
        _taskLogRepository = taskLogRepository;
    }

    public virtual async Task SaveAsync(EntityChangeSet changeSet)
    {
        foreach (var entityChange in changeSet.EntityChanges)
        {
            var taskLog = new zzLog.Tasks_Task()
            {
                TaskId = entityChange.EntityId,
                Description = entityChange.PropertyChanges
                    .Where(pc => pc.PropertyName == "Description")
                    .FirstOrDefault()?
                    .NewValue,
                // lgId = 0,  // Auto-increment
                lgAction =
                    entityChange.ChangeType == EntityChangeType.Created ? 1 :
                    entityChange.ChangeType == EntityChangeType.Updated ? 2 :
                    entityChange.ChangeType == EntityChangeType.Deleted ? 3 : 0,
                lgTime = entityChange.ChangeTime
            };

            await _taskLogRepository.InsertAsync(taskLog);
        }
    }
}
```

<p>Replace the service for <code>IEntityHistoryStore</code> in your module's <code>PreInitialize</code> method:</p>

<pre class="lang-cs prettyprint-override"><code>// using Abp.Configuration.Startup;

Configuration.ReplaceService<IEntityHistoryStore, MyEntityHistoryStore>(DependencyLifeStyle.Transient);
</code>```

Body:
In asp.net boilerplate, we have the need to track changes to entities. I see that ABP has entity tracking (new) but it's storing all changes across entities in one table, which won't work for us. Is it possible to create a custom IEntityHistoryStore to store those changes per entity (in their own table)?

For example, let's say there's an entity Task.

[Table("Task", Schema = "Tasks")]
public class Task : Entity<int>
{
    [Column(TypeName = "varchar(255)")]
    public string Description { get; set; }
    // some more poco properties
}

Then what I would like to define is another table, zzLog.Tasks_Task and I would like that table to look like this:

╔════════╦════════════════════════╦══════╦══════════╦════════════════════╗
║ TaskId ║      Description       ║ lgId ║ lgAction ║       lgTime       ║
╠════════╬════════════════════════╬══════╬══════════╬════════════════════╣
║      1 ║ Some description       ║    1 ║        1 ║ 2019-05-30 9:05 AM ║
║      1 ║ Some other description ║    2 ║        2 ║ 2019-05-30 9:06 AM ║
║      1 ║ Changed again          ║    3 ║        2 ║ 2019-05-30 9:07 AM ║
║      1 ║ Changed again          ║    4 ║        3 ║ 2019-05-30 9:08 AM ║
╚════════╩════════════════════════╩══════╩══════════╩════════════════════╝

lgAction is an enum, 1 = create, 2 = update, 3 = delete

Is this possible? Instinct says no since IEntityHistoryStore likely can't work this way.

Body:
Yes, from https://aspnetboilerplate.com/Pages/Documents/Entity-History#about-ientityhistorystore:

The Entity History tracking system uses IEntityHistoryStore to save change information.  ... you can implement it in your own way ...

Implement MyEntityHistoryStore:

public class MyEntityHistoryStore : IEntityHistoryStore
{
    private readonly IRepository<zzLog.Tasks_Task> _taskLogRepository;

    public EntityHistoryStore(IRepository<zzLog.Tasks_Task> taskLogRepository)
    {
        _taskLogRepository = taskLogRepository;
    }

    public virtual async Task SaveAsync(EntityChangeSet changeSet)
    {
        foreach (var entityChange in changeSet.EntityChanges)
        {
            var taskLog = new zzLog.Tasks_Task()
            {
                TaskId = entityChange.EntityId,
                Description = entityChange.PropertyChanges
                    .Where(pc => pc.PropertyName == "Description")
                    .FirstOrDefault()?
                    .NewValue,
                // lgId = 0,  // Auto-increment
                lgAction =
                    entityChange.ChangeType == EntityChangeType.Created ? 1 :
                    entityChange.ChangeType == EntityChangeType.Updated ? 2 :
                    entityChange.ChangeType == EntityChangeType.Deleted ? 3 : 0,
                lgTime = entityChange.ChangeTime
            };

            await _taskLogRepository.InsertAsync(taskLog);
        }
    }
}

Replace the service for IEntityHistoryStore in your module's PreInitialize method:

// using Abp.Configuration.Startup;

Configuration.ReplaceService<IEntityHistoryStore, MyEntityHistoryStore>(DependencyLifeStyle.Transient);


问:
I do need help to understand a runtime error
I have following following error which will cause my android app to jump out, where it jumps out is very inconsistent i can't pin point the code causing it. Anyone can read and understand what it is?</p>

```<code>E/AndroidRuntime: FATAL EXCEPTION: Thread-22
    Process: my.zen.com.uselessapp.xxxxxxxx, PID: 16384
    java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion;
        at com.google.android.gms.internal.ads.zzaj.zzb(Unknown Source:3)
        at com.google.android.gms.internal.ads.zzai.zza(Unknown Source:4)
        at com.google.android.gms.internal.ads.zzak.zzc(Unknown Source:32)
        at com.google.android.gms.internal.ads.zzayl.zzc(Unknown Source:27)
        at com.google.android.gms.internal.ads.zzn.processRequest(Unknown Source:28)
        at com.google.android.gms.internal.ads.zzn.run(Unknown Source:12)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/base.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_dependencies_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_resources_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_0_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_1_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_2_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_3_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_4_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_5_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_6_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_7_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_8_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/lib/arm64, /system/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.google.android.gms.internal.ads.zzaj.zzb(Unknown Source:3)
        at com.google.android.gms.internal.ads.zzai.zza(Unknown Source:4)
        at com.google.android.gms.internal.ads.zzak.zzc(Unknown Source:32)
        at com.google.android.gms.internal.ads.zzayl.zzc(Unknown Source:27)
        at com.google.android.gms.internal.ads.zzn.processRequest(Unknown Source:28)
        at com.google.android.gms.internal.ads.zzn.run(Unknown Source:12)
        Suppressed: java.io.IOException: No original dex files found for dex location /data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_resources_apk.apk
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:354)
        at dalvik.system.DexFile.<init>(DexFile.java:101)
        at dalvik.system.DexFile.<init>(DexFile.java:75)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:394)
        at dalvik.system.DexPathList.makeDexElements(DexPathList.java:354)
        at dalvik.system.DexPathList.<init>(DexPathList.java:164)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:74)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
        at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:73)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:88)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:74)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:40)
        at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:727)
        at android.app.LoadedApk.getClassLoader(LoadedApk.java:810)
        at android.app.LoadedApk.getResources(LoadedApk.java:1032)
        at android.app.ContextImpl.createAppContext(ContextImpl.java:2345)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5798)
        at android.app.ActivityThread.access$1100(ActivityThread.java:200)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6718)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Application terminated.

</code>```

答:
Add this in you AndroidMenifest.xml inside <application> tag

```<code><application
   android:theme="@style/AppTheme">

      <uses-library
          android:name="org.apache.http.legacy"
          android:required="false" />
</application>
</code>```

Body:
I have following following error which will cause my android app to jump out, where it jumps out is very inconsistent i can't pin point the code causing it. Anyone can read and understand what it is?

E/AndroidRuntime: FATAL EXCEPTION: Thread-22
    Process: my.zen.com.uselessapp.xxxxxxxx, PID: 16384
    java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion;
        at com.google.android.gms.internal.ads.zzaj.zzb(Unknown Source:3)
        at com.google.android.gms.internal.ads.zzai.zza(Unknown Source:4)
        at com.google.android.gms.internal.ads.zzak.zzc(Unknown Source:32)
        at com.google.android.gms.internal.ads.zzayl.zzc(Unknown Source:27)
        at com.google.android.gms.internal.ads.zzn.processRequest(Unknown Source:28)
        at com.google.android.gms.internal.ads.zzn.run(Unknown Source:12)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/base.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_dependencies_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_resources_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_0_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_1_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_2_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_3_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_4_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_5_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_6_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_7_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_8_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/lib/arm64, /system/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.google.android.gms.internal.ads.zzaj.zzb(Unknown Source:3)
        at com.google.android.gms.internal.ads.zzai.zza(Unknown Source:4)
        at com.google.android.gms.internal.ads.zzak.zzc(Unknown Source:32)
        at com.google.android.gms.internal.ads.zzayl.zzc(Unknown Source:27)
        at com.google.android.gms.internal.ads.zzn.processRequest(Unknown Source:28)
        at com.google.android.gms.internal.ads.zzn.run(Unknown Source:12)
        Suppressed: java.io.IOException: No original dex files found for dex location /data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_resources_apk.apk
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:354)
        at dalvik.system.DexFile.<init>(DexFile.java:101)
        at dalvik.system.DexFile.<init>(DexFile.java:75)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:394)
        at dalvik.system.DexPathList.makeDexElements(DexPathList.java:354)
        at dalvik.system.DexPathList.<init>(DexPathList.java:164)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:74)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
        at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:73)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:88)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:74)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:40)
        at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:727)
        at android.app.LoadedApk.getClassLoader(LoadedApk.java:810)
        at android.app.LoadedApk.getResources(LoadedApk.java:1032)
        at android.app.ContextImpl.createAppContext(ContextImpl.java:2345)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5798)
        at android.app.ActivityThread.access$1100(ActivityThread.java:200)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6718)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Application terminated.

Body:
Add this in you AndroidMenifest.xml inside <application> tag

<application
   android:theme="@style/AppTheme">

      <uses-library
          android:name="org.apache.http.legacy"
          android:required="false" />
</application>