问:
Find last sequence episode and increment count variable
My data looks like this (person-period file), where hldid represents a unique identifier, variable represents time and paid is a dummy vector of interest

```<code>   hldid variable paid
1      1        1    0
2      1        2    0
3      1        3    0
4      1        4    1
5      1        5    1
6      1        6    0
7      1        7    1
8      1        8    1
9      1        9    0
10     1       10    0
11     2        1    0
12     2        2    0
13     2        3    1
14     2        4    1
15     2        5    0
16     2        6    1
17     2        7    0
18     2        8    0
19     2        9    0
20     2       10    0
</code>```

What I would like to achieve is this:

```<code>  hldid variable  paid  last wwork2
 1     1        1     0     0      0
 2     1        2     0     0      0
 3     1        3     0     0      0
 4     1        4     1     0      0
 5     1        5     1     0      0
 6     1        6     0     0     -2
 7     1        7     1     0     -1
 8     1        8     1     1      0
 9     1        9     0     0      1
10     1       10     0     0      2
11     2        1     0     0      0
12     2        2     0     0      0
13     2        3     1     0      0
14     2        4     1     0     -2
15     2        5     0     0     -1
16     2        6     1     1      0
17     2        7     0     0      1
18     2        8     0     0      2
19     2        9     0     0      0
20     2       10     0     0      0
</code>```

I would like to create a vector that (1) finds the latest episode of paid for each hldid and (2) to decrement/increment 2 episodes before and 2 episodes after the last episode of paid.

So far, this is what I did.

Find last episode of paid

What is complicated here is that paid is not a continuous sequence. For instance hldid == 1 stops paid at episode 6 and starts again at episode 7 and the last episode is at 8.

So my idea is to subset all the paid == 1, count the number of episodes and then merge it back. However, I am not sure this is the most efficient strategy.

```<code>ddw = dta %>% filter(paid == 1)
ddw$work = 0

for(i in 2:nrow(ddw)){
  if(ddw$hldid[i] == ddw$hldid[i-1] &
     ddw$paid[i] == 1){
    ddw$work[i] <- ddw$work[i-1] + 1
 }
}

ddf = merge(dta, ddw, by = c('hldid', 'variable', 'paid'), all = T)
</code>```

Then, I find the last episode with

```<code>ddw2 = ddf %>% group_by(hldid) %>% mutate(end_work = ifelse(work == max(work, na.rm = T), variable, 0))
</code>```

and finally I create a dummy indicating the position of the final paid episode

```<code>ddw2$end_work[is.na(ddw2$end_work)] <- 0
ddw2 = ddw2 %>% group_by(hldid) %>% mutate(wwork = ifelse(end_work == variable, 1, 0))
</code>```

Increment/decrement

Now, from here I don't know how to increment/decrement before and after the last episode. So far I could only come up with this:

```<code>df = ddw2
df$wwork2 = 0

for(i in 2:nrow(df)){
  if(df$hldid[i] == df$hldid[i-1] &
     df$wwork[i] == 1){
    df$wwork2[i-1] <- 1; df$wwork2[i] <- 1; df$wwork2[i+1] <- 1
  }
}
</code>```

data

```<code>dta = rbind(c(1,1,0),
      c(1,2,0),
      c(1,3,0),
      c(1,4,1),
      c(1,5,1),
      c(1,6,0),
      c(1,7,1),
      c(1,8,1),
      c(1,9,0),
      c(1,10,0),
      c(2,1,0),
      c(2,2,0),
      c(2,3,1),
      c(2,4,1),
      c(2,5,0),
      c(2,6,1),
      c(2,7,0),
      c(2,8,0),
      c(2,9,0),
      c(2,10,0))

colnames(dta) = c('hldid', 'variable', 'paid')
dta = as.data.frame(dta)

library(dplyr)
</code>```

答:
Using dplyr, group by hldid, then define end_work as the difference between variable and the max value for which paid==1, then insert 0s for values greater than 2...

```<code>library(dplyr)
dta2 <- dta %>% group_by(hldid) %>%
                mutate(last=as.numeric(variable==max(variable[paid==1]))) %>%
                mutate(end_work=variable-max(variable[paid==1])) %>%
                mutate(end_work=replace(end_work,abs(end_work)>2,0))

dta2
   hldid variable  paid  last end_work
   <dbl>    <dbl> <dbl> <dbl>    <dbl>
 1     1        1     0     0        0
 2     1        2     0     0        0
 3     1        3     0     0        0
 4     1        4     1     0        0
 5     1        5     1     0        0
 6     1        6     0     0       -2
 7     1        7     1     0       -1
 8     1        8     1     1        0
 9     1        9     0     0        1
10     1       10     0     0        2
11     2        1     0     0        0
12     2        2     0     0        0
13     2        3     1     0        0
14     2        4     1     0       -2
15     2        5     0     0       -1
16     2        6     1     1        0
17     2        7     0     0        1
18     2        8     0     0        2
19     2        9     0     0        0
20     2       10     0     0        0
</code>```

The end of work episode by id can be summarised by

```<code>end_w <- dta %>% group_by(hldid) %>% summarise(end_episode=max(variable[paid==1]))

end_w
  hldid end_episode
  <dbl>       <dbl>
1     1           8
2     2           6
</code>```

Body:
My data looks like this (person-period file), where hldid represents a unique identifier, variable represents time and paid is a dummy vector of interest

   hldid variable paid
1      1        1    0
2      1        2    0
3      1        3    0
4      1        4    1
5      1        5    1
6      1        6    0
7      1        7    1
8      1        8    1
9      1        9    0
10     1       10    0
11     2        1    0
12     2        2    0
13     2        3    1
14     2        4    1
15     2        5    0
16     2        6    1
17     2        7    0
18     2        8    0
19     2        9    0
20     2       10    0

What I would like to achieve is this:

  hldid variable  paid  last wwork2
 1     1        1     0     0      0
 2     1        2     0     0      0
 3     1        3     0     0      0
 4     1        4     1     0      0
 5     1        5     1     0      0
 6     1        6     0     0     -2
 7     1        7     1     0     -1
 8     1        8     1     1      0
 9     1        9     0     0      1
10     1       10     0     0      2
11     2        1     0     0      0
12     2        2     0     0      0
13     2        3     1     0      0
14     2        4     1     0     -2
15     2        5     0     0     -1
16     2        6     1     1      0
17     2        7     0     0      1
18     2        8     0     0      2
19     2        9     0     0      0
20     2       10     0     0      0

I would like to create a vector that (1) finds the latest episode of paid for each hldid and (2) to decrement/increment 2 episodes before and 2 episodes after the last episode of paid.

So far, this is what I did.

Find last episode of paid

What is complicated here is that paid is not a continuous sequence. For instance hldid == 1 stops paid at episode 6 and starts again at episode 7 and the last episode is at 8.

So my idea is to subset all the paid == 1, count the number of episodes and then merge it back. However, I am not sure this is the most efficient strategy.

ddw = dta %>% filter(paid == 1)
ddw$work = 0

for(i in 2:nrow(ddw)){
  if(ddw$hldid[i] == ddw$hldid[i-1] &
     ddw$paid[i] == 1){
    ddw$work[i] <- ddw$work[i-1] + 1
 }
}

ddf = merge(dta, ddw, by = c('hldid', 'variable', 'paid'), all = T)

Then, I find the last episode with

ddw2 = ddf %>% group_by(hldid) %>% mutate(end_work = ifelse(work == max(work, na.rm = T), variable, 0))

and finally I create a dummy indicating the position of the final paid episode

ddw2$end_work[is.na(ddw2$end_work)] <- 0
ddw2 = ddw2 %>% group_by(hldid) %>% mutate(wwork = ifelse(end_work == variable, 1, 0))

Increment/decrement

Now, from here I don't know how to increment/decrement before and after the last episode. So far I could only come up with this:

df = ddw2
df$wwork2 = 0

for(i in 2:nrow(df)){
  if(df$hldid[i] == df$hldid[i-1] &
     df$wwork[i] == 1){
    df$wwork2[i-1] <- 1; df$wwork2[i] <- 1; df$wwork2[i+1] <- 1
  }
}

data

dta = rbind(c(1,1,0),
      c(1,2,0),
      c(1,3,0),
      c(1,4,1),
      c(1,5,1),
      c(1,6,0),
      c(1,7,1),
      c(1,8,1),
      c(1,9,0),
      c(1,10,0),
      c(2,1,0),
      c(2,2,0),
      c(2,3,1),
      c(2,4,1),
      c(2,5,0),
      c(2,6,1),
      c(2,7,0),
      c(2,8,0),
      c(2,9,0),
      c(2,10,0))

colnames(dta) = c('hldid', 'variable', 'paid')
dta = as.data.frame(dta)

library(dplyr)

Body:
Using dplyr, group by hldid, then define end_work as the difference between variable and the max value for which paid==1, then insert 0s for values greater than 2...

library(dplyr)
dta2 <- dta %>% group_by(hldid) %>%
                mutate(last=as.numeric(variable==max(variable[paid==1]))) %>%
                mutate(end_work=variable-max(variable[paid==1])) %>%
                mutate(end_work=replace(end_work,abs(end_work)>2,0))

dta2
   hldid variable  paid  last end_work
   <dbl>    <dbl> <dbl> <dbl>    <dbl>
 1     1        1     0     0        0
 2     1        2     0     0        0
 3     1        3     0     0        0
 4     1        4     1     0        0
 5     1        5     1     0        0
 6     1        6     0     0       -2
 7     1        7     1     0       -1
 8     1        8     1     1        0
 9     1        9     0     0        1
10     1       10     0     0        2
11     2        1     0     0        0
12     2        2     0     0        0
13     2        3     1     0        0
14     2        4     1     0       -2
15     2        5     0     0       -1
16     2        6     1     1        0
17     2        7     0     0        1
18     2        8     0     0        2
19     2        9     0     0        0
20     2       10     0     0        0

The end of work episode by id can be summarised by

end_w <- dta %>% group_by(hldid) %>% summarise(end_episode=max(variable[paid==1]))

end_w
  hldid end_episode
  <dbl>       <dbl>
1     1           8
2     2           6


来源: stackexchange

问:
ConnectionError while downloading a file using requests library
I am trying to download one dataset from UCI ML repository in Python. Here is my code:

```<code>import requests

zip_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip'
r = requests.get(zip_url)
</code>```

But, after running the code I get the following error. What is the reason and how to resolve it?

ConnectionError: HTTPConnectionPool(host='archive.ics.uci.edu', port=80): Max retries exceeded with url: /ml/machine-learning-databases/00228/smsspamcollection.zip (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x11a3c15c0>: Failed to establish a new connection: [Errno 53] Software caused connection abort',))

答:
I would suggest looking into this similar discussion here and this issue.
Also i would try to get a connection to other urls using requests.get and see if that works.
Also you could try to download the file using cmd-line tools like wget or a webbrowser from the same machine to see if you can get a connection to the server. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to download one dataset from UCI ML repository in Python. Here is my code:

import requests

zip_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip'
r = requests.get(zip_url)

But, after running the code I get the following error. What is the reason and how to resolve it?

ConnectionError: HTTPConnectionPool(host='archive.ics.uci.edu', port=80): Max retries exceeded with url: /ml/machine-learning-databases/00228/smsspamcollection.zip (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x11a3c15c0>: Failed to establish a new connection: [Errno 53] Software caused connection abort',))


问:
Tensorflow not being deterministic, where it should
I have a small network. Trained [many hours] and saved to a checkpoint.
Now, I want to restore from checkpoint, in a different script, and use it.
I recreate the session: build the entire network, s.t. all ops are created again, using the exact same code I did before training. This code sets the random seed for TF, using time.time() [which is different every run].

I then restore from a checkpoint. I run the network, and get different numbers [small but meaningful differences] every time I run the restored network. Crucially, the input is fixed.
If I fixate the random seed to some value, the non deterministic behavior goes away.

I am puzzled because I thought that a restore [no Variables were given to save, so I presume all graph was checkpointed] eliminates all random behavior from this flow. Initializations etc. are overridden by the restored checkpoint, this is only a forward run.

Is this possible? make sense? Is there a way to find out what variables or factors in my graph are not set by the restored checkpoint?

答:
It seems as if this question was already answered in the comments but no-one has written down the answer explicitly yet, so here it is:

You were expecting the computation graph to return always the same values even with different random seeds because you thought that there should not be any Op in your graph which depends on the random seed.

You forgot about the dropout.

In any case, I would always keep the random seed fixed anyway. Then also this and any other random ops are deterministic, and your whole training can be as well. If you are wondering at some point how much variance you get by different random seeds, you can explicitly try other random seeds.


问:
Getting Json exception for a string
I am calling an async task which returns a json object which has result,message as a string and result as cost.

Though it shows result,message string in the response object it shows json exception as no value for result.

Asynctask

```<code>public class SearchPostsAsyncTask extends AsyncTask<String, Void, JSONObject> {
    String api;
    JSONObject jsonParams;
    Context mContext;
    private SearchPostsCallBack searchPostsCallBack;
    private ProgressDialog loadingDialog;
    private Snackbar snackbar;
    private LinearLayout parentLayout;
    private ArrayList<PostDelivery> list;
    private JSONArray listsArray;
    private JSONObject jsonObject;

    public SearchPostsAsyncTask(Context context, LinearLayout linearLayout,SearchPostsCallBack searchPostsCallBack) {

        this.mContext = context;
        this.searchPostsCallBack = searchPostsCallBack;
        this.parentLayout = linearLayout;

    }

    public interface SearchPostsCallBack {
        void doPostExecute(ArrayList<PostDelivery> list);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        loadingDialog = new ProgressDialog(mContext);

        if (!isOnline()) {

            snackbar = Snackbar.make(parentLayout, R.string.check_network, Snackbar.LENGTH_LONG);
            snackbar.show();
        } else {
            loadingDialog.show(mContext, null,mContext.getString(R.string.wait));
        }

    }

    @Override
    protected JSONObject doInBackground(String... params) {
        try {
            api = mContext.getResources().getString(R.string.url) + "requestlist";

            jsonParams = new JSONObject();
            jsonParams.put("st_lati", params[0]);
            jsonParams.put("st_longi", params[1]);
            jsonParams.put("ed_lati", params[2]);
            jsonParams.put("ed_longi", params[3]);
            jsonParams.put("pt_date", params[4]);

            ServerRequest request = new ServerRequest(api, jsonParams);
            return request.sendPostRequest(params[5]);

        } catch (JSONException je) {
            Log.e("exception",je.toString());
            return Excpetion2JSON.getJSON(je);
        } catch (Exception ue) {
            return Excpetion2JSON.getJSON(ue);
        }
    }

    @Override
    protected void onPostExecute(JSONObject response) {
        super.onPostExecute(response);
        if (loadingDialog.isShowing())
            loadingDialog.dismiss();
        try {
            list = new ArrayList<>();

                    String result = response.getString("result");
                    String message = response.getString("message");
                    if (result.equals("1")) {

                        listsArray = response.getJSONArray("cost");

                        for (int j = 0; j < listsArray.length(); j++) {

                            jsonObject = listsArray.getJSONObject(j);

                    PostDelivery postDelivery = new PostDelivery();

                    postDelivery.setmPt_id(jsonObject.getString("pt_id"));
                    postDelivery.setmPt_name(jsonObject.getString("pt_name"));
                    postDelivery.setmPtDetail(jsonObject.getString("pt_detail"));
                    postDelivery.setmPtStartLoc(jsonObject.getString("pt_start_loc"));
                    postDelivery.setmPtEndLoc(jsonObject.getString("pt_end_loc"));
                    postDelivery.setmPtDate(jsonObject.getString("pt_date"));

                    list.add(postDelivery);

                    searchPostsCallBack.doPostExecute(list);

                }
            }

                snackbar = Snackbar.make(parentLayout, "sorry", Snackbar.LENGTH_LONG);

                snackbar.show();

    }catch (JSONException je) {
            je.printStackTrace();
            //  Toast.makeText(getApplicationContext(), je.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

}
</code>```

Exception and response :

```<code>D/ServerResponse: {"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}
06-04 19:26:06.284 7129-7129/com.carryapp W/System.err: org.json.JSONException: No value for result
</code>```

What is going wrong here? Please help.Thank you..

答: In your ServerResponse {"result":1}, the "result" is int, and you use String result = response.getString("result"), you should use getInt.

Title: Getting Json exception for a string

Body:
I am calling an async task which returns a json object which has result,message as a string and result as cost.

Though it shows result,message string in the response object it shows json exception as no value for result.

Asynctask

public class SearchPostsAsyncTask extends AsyncTask<String, Void, JSONObject> {
    String api;
    JSONObject jsonParams;
    Context mContext;
    private SearchPostsCallBack searchPostsCallBack;
    private ProgressDialog loadingDialog;
    private Snackbar snackbar;
    private LinearLayout parentLayout;
    private ArrayList<PostDelivery> list;
    private JSONArray listsArray;
    private JSONObject jsonObject;

    public SearchPostsAsyncTask(Context context, LinearLayout linearLayout,SearchPostsCallBack searchPostsCallBack) {

        this.mContext = context;
        this.searchPostsCallBack = searchPostsCallBack;
        this.parentLayout = linearLayout;

    }

    public interface SearchPostsCallBack {
        void doPostExecute(ArrayList<PostDelivery> list);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        loadingDialog = new ProgressDialog(mContext);

        if (!isOnline()) {

            snackbar = Snackbar.make(parentLayout, R.string.check_network, Snackbar.LENGTH_LONG);
            snackbar.show();
        } else {
            loadingDialog.show(mContext, null,mContext.getString(R.string.wait));
        }

    }

    @Override
    protected JSONObject doInBackground(String... params) {
        try {
            api = mContext.getResources().getString(R.string.url) + "requestlist";

            jsonParams = new JSONObject();
            jsonParams.put("st_lati", params[0]);
            jsonParams.put("st_longi", params[1]);
            jsonParams.put("ed_lati", params[2]);
            jsonParams.put("ed_longi", params[3]);
            jsonParams.put("pt_date", params[4]);

            ServerRequest request = new ServerRequest(api, jsonParams);
            return request.sendPostRequest(params[5]);

        } catch (JSONException je) {
            Log.e("exception",je.toString());
            return Excpetion2JSON.getJSON(je);
        } catch (Exception ue) {
            return Excpetion2JSON.getJSON(ue);
        }
    }

    @Override
    protected void onPostExecute(JSONObject response) {
        super.onPostExecute(response);
        if (loadingDialog.isShowing())
            loadingDialog.dismiss();
        try {
            list = new ArrayList<>();

                    String result = response.getString("result");
                    String message = response.getString("message");
                    if (result.equals("1")) {

                        listsArray = response.getJSONArray("cost");

                        for (int j = 0; j < listsArray.length(); j++) {

                            jsonObject = listsArray.getJSONObject(j);

                    PostDelivery postDelivery = new PostDelivery();

                    postDelivery.setmPt_id(jsonObject.getString("pt_id"));
                    postDelivery.setmPt_name(jsonObject.getString("pt_name"));
                    postDelivery.setmPtDetail(jsonObject.getString("pt_detail"));
                    postDelivery.setmPtStartLoc(jsonObject.getString("pt_start_loc"));
                    postDelivery.setmPtEndLoc(jsonObject.getString("pt_end_loc"));
                    postDelivery.setmPtDate(jsonObject.getString("pt_date"));

                    list.add(postDelivery);

                    searchPostsCallBack.doPostExecute(list);

                }
            }

                snackbar = Snackbar.make(parentLayout, "sorry", Snackbar.LENGTH_LONG);

                snackbar.show();

    }catch (JSONException je) {
            je.printStackTrace();
            //  Toast.makeText(getApplicationContext(), je.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

}

Exception and response :

D/ServerResponse: {"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}
06-04 19:26:06.284 7129-7129/com.carryapp W/System.err: org.json.JSONException: No value for result

What is going wrong here? Please help.Thank you..


问:
How to dragdrop on a disabled TextBox in C#?
I want to make a DragDrop on a TextBox which has Enabled=false property, but DragDrop is disabled as the control is disabled. Is there a way to make it or it has to be Enabled=true

```<code>private void textBox1_DragEnter(object sender, DragEventArgs e)
{
   if (e.Data.GetDataPresent(DataFormats.FileDrop))
       e.Effect = DragDropEffects.Copy;
}
void textBox1_DragDrop(object sender, DragEventArgs e)
{
   string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
   if (files.Length < 1)
       return;
   if (new string[] { ".txt", ".csv" }.Contains(Path.GetExtension(files[0])))
   textBox1.Text = Path.GetFileNameWithoutExtension(files[0]);
   e.Effect = DragDropEffects.None;
}
</code>```

答:
Use the ReadOnly property instead of the Enabled property.  A ReadOnly control accepts Drop events but does not allow the user to otherwise modify its content.

ReadOnly likely gives the effect and behavior you seek without having to implement complicated state tracking code and doing so will keep your user interface congruent with standard practices.

Body:
I want to make a DragDrop on a TextBox which has Enabled=false property, but DragDrop is disabled as the control is disabled. Is there a way to make it or it has to be Enabled=true

private void textBox1_DragEnter(object sender, DragEventArgs e)
{
   if (e.Data.GetDataPresent(DataFormats.FileDrop))
       e.Effect = DragDropEffects.Copy;
}
void textBox1_DragDrop(object sender, DragEventArgs e)
{
   string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
   if (files.Length < 1)
       return;
   if (new string[] { ".txt", ".csv" }.Contains(Path.GetExtension(files[0])))
   textBox1.Text = Path.GetFileNameWithoutExtension(files[0]);
   e.Effect = DragDropEffects.None;
}


问:
How can I read a "ctrl+q" input from user using opencv and Python?
I am using:-

```<code>key=cv2.waitKey(1) #& 0xFF
    if key== ord('q'):
        ....................
</code>```

but I need the input from user to be ctrl+q

Thanks

答:
CTRL+Q is encoded as 17 in ASCII control key table. Below is a sample code.

```<code>cv2.imshow('frame', frame)
key = cv2.waitKey(1)
if key == 17:        # Ctrl+Q or ^Q
    break
</code>```

Body:
I am using:-

key=cv2.waitKey(1) #& 0xFF
    if key== ord('q'):
        ....................

but I need the input from user to be ctrl+q

Thanks

Body:
CTRL+Q is encoded as 17 in ASCII control key table. Below is a sample code.

cv2.imshow('frame', frame)
key = cv2.waitKey(1)
if key == 17:        # Ctrl+Q or ^Q
    break


问:
how to communicate between tabhost and actvities
I create my code like that:

```<code>        final TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("Month")
                .setIndicator("Month")
                .setContent(new Intent(this, MonthView.class)));
</code>```

How can i communicate with tabhost in monthview class?

答: Use the getParent() method on MonthView.

ContentLicense: CC BY-SA 2.5

Body:
I create my code like that:

        final TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("Month")
                .setIndicator("Month")
                .setContent(new Intent(this, MonthView.class)));

How can i communicate with tabhost in monthview class?


问:
Reset a views pressed state
I have a view based layout (no fragments, one activity) and animate between different states. For better smoothness I use two toolbars and crossfade them.

The problem is, that if I press the navigation button of one toolbar and start the crossfade animation, the navigation button does not restore it's unpressed state (probably due to the animation), resulting in the selector not vanishing... When I now reshow this toolbar, the navigation button looks pressed (the ripple drawable is still visible).

Can I manually clear the ripple animation?

What I tried

I get the toolbar navigation view like following: Get Toolbar's navigation icon view referrence

I tried clearing the animation of the view: toolbarNavigationView.clearAnimation()

I tried resetting the drawable with ViewCompat.jumpDrawablesToCurrentState(toolbarNavigationView);

I tried posting this to the toolbar to make sure the layout is layed out like following:

```<code>toolbar.post(new Runnable()
{
    @Override
    public void run()
    {
        ViewCompat.jumpDrawablesToCurrentState(toolbarNavigationView);
    }
});
</code>```

答:
Try to get the animation, and reset it, like this:</p>

```<code>Animation anim = yourView.getAnimation();
            if (anim != null) {
                yourView.reset();
            }
            yourView.clearAnimation();
</code>```

Title: Reset a views pressed state

Body:
I have a view based layout (no fragments, one activity) and animate between different states. For better smoothness I use two toolbars and crossfade them.

The problem is, that if I press the navigation button of one toolbar and start the crossfade animation, the navigation button does not restore it's unpressed state (probably due to the animation), resulting in the selector not vanishing... When I now reshow this toolbar, the navigation button looks pressed (the ripple drawable is still visible).

Can I manually clear the ripple animation?

What I tried

I get the toolbar navigation view like following: Get Toolbar's navigation icon view referrence

I tried clearing the animation of the view: toolbarNavigationView.clearAnimation()

I tried resetting the drawable with ViewCompat.jumpDrawablesToCurrentState(toolbarNavigationView);

I tried posting this to the toolbar to make sure the layout is layed out like following:

toolbar.post(new Runnable()
{
    @Override
    public void run()
    {
        ViewCompat.jumpDrawablesToCurrentState(toolbarNavigationView);
    }
});

Body:
Try to get the animation, and reset it, like this:

Animation anim = yourView.getAnimation();
            if (anim != null) {
                yourView.reset();
            }
            yourView.clearAnimation();


问:
Can't suddenly connect to my Firebase database
My issue is that all of a sudden I can't connect to my Firebase database, hence, in my case, users can't log in to my app. The issue came suddenly; my app passed Apple's review 2 days ago.

However, I only face this problem running the app on iPhone. I can still connect from Ipad!?

This OP recently had similar issue: iphone/ipad suddenly stops responding to firebase queries. In my case however I can't read nor write from/to database. Tried "activating" the database like answer suggests but nothing happens. Haven't found anything helpful elsewhere.

As of May there's some new Firebase syntax which I updated my code with. I write to my database like this, which is correct according to the docs...

```<code>let databaseRef = Database.database().reference()
databaseRef.child(someString).setValue(someValue)
</code>```

...and query it like this...

```<code>databaseRef.child(someString).queryOrdered(byChild: someString).queryEqual(toValue: someValue).observeSingleEvent(of: .value, with: { (snapshot) in })
</code>```

Nothing happens.

Any suggestions are greatly appreciated.

答:
Turns out this answer iphone/ipad suddenly stops responding to firebase queries did work for me after all.

Right before the query I just call

```<code>databaseRef.setValue(someValue)
</code>```

This  doesn't add anything to the database. However it seems to be what "wakes it up".

I'm afraid I can't tell you why or even if this is needed, but perhaps it's not a good idea to query the database first thing? Just a thought...

Thanks everyone who tried to help, and thank you @Carlos De la Mora for providing the answer to the question referred to above.

Body:
My issue is that all of a sudden I can't connect to my Firebase database, hence, in my case, users can't log in to my app. The issue came suddenly; my app passed Apple's review 2 days ago.

However, I only face this problem running the app on iPhone. I can still connect from Ipad!?

This OP recently had similar issue: iphone/ipad suddenly stops responding to firebase queries. In my case however I can't read nor write from/to database. Tried "activating" the database like answer suggests but nothing happens. Haven't found anything helpful elsewhere.

As of May there's some new Firebase syntax which I updated my code with. I write to my database like this, which is correct according to the docs...

let databaseRef = Database.database().reference()
databaseRef.child(someString).setValue(someValue)

...and query it like this...

databaseRef.child(someString).queryOrdered(byChild: someString).queryEqual(toValue: someValue).observeSingleEvent(of: .value, with: { (snapshot) in })

Nothing happens.

Any suggestions are greatly appreciated.

Body:
Turns out this answer iphone/ipad suddenly stops responding to firebase queries did work for me after all.

Right before the query I just call

databaseRef.setValue(someValue)

This  doesn't add anything to the database. However it seems to be what "wakes it up".

I'm afraid I can't tell you why or even if this is needed, but perhaps it's not a good idea to query the database first thing? Just a thought...

Thanks everyone who tried to help, and thank you @Carlos De la Mora for providing the answer to the question referred to above.


问:
Quick Python Script to see if float x ∈ range without very small steps
I have float/decimal values like 2,4378472348237483274 etc.
and for some instructions there must be a condition for these numbers.
Condition must be:   ∈ (range)
But for Python, 2 is in (1,3,1) but 2,1231837 is not in (1,3,1) because of the step. I don't know how to set range without steps...
So my idea is to code a little custom range that only looks at the unit.
For example: 2,47234723278
So it looks at "2" (unit) and confirm that it is in a range (1,3).

For now, I have a very slow script that has a very little step... not performant as you guess.

So either you help me building a range without any steps (but computationally not possible, I guess) or you help me building a custom range with a script that makes it only look at the integer part.

Example:

213,4

Only look at 213.

Thanks a lot

答:
Well you could just check the borders of your range

```<code>low = 1.0
high = 3.0

def inrange(x):
    if x<=high and x >= low:
       return true
    else:
       return false
</code>```

Or you could cast into an integer, which will always give you the lower whole number of your float:

```<code>int(213.4) = 213
</code>```

Body:
Well you could just check the borders of your range

low = 1.0
high = 3.0

def inrange(x):
    if x<=high and x >= low:
       return true
    else:
       return false

Or you could cast into an integer, which will always give you the lower whole number of your float:

int(213.4) = 213


问:
ios::exceptions(...) changes when badbit is set
When executing the following code, I get the following output: EOF FAIL. So reading a line from an empty file sets eofbit and failbit, but not badbit.

If I enable exceptions by uncommenting line 11 the output changes: EOF BAD FAIL. Now reading a line from an empty file sets eofbit, badbit, but not failbit (otherwise an exception had occured).

Can someone explain why enabling exceptions changes the way, failbit and badbit are set. Is this documented somewhere?

```<code>#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char const *argv[]) {
    ifstream f("some_empty_file");
    string line;

    // f.exceptions(std::ifstream::failbit); // (line 11)

    getline(f, line);
    if(f.eof()) cout << "EOF ";
    if(f.bad()) cout << "BAD ";
    if(f.fail()) cout << "FAIL ";

    cout << endl;
    f.close();

    return 0;
}
</code>```

Edit: I read the answer on https://stackoverflow.com/a/11085193/3821618 on the difference of badbit and failbit. But that does not answer the question, why with exceptions enabled, reading from an empty file becomes a "serious error", while it is not, if I do not call f.exceptions(...)

答:
There are 4 distinct stream states (taken from std::ios_base::iostate):

```<code> typedef /*implementation defined*/ iostate;
 static constexpr iostate goodbit = 0;
 static constexpr iostate badbit = /*implementation defined*/
 static constexpr iostate failbit = /*implementation defined*/
 static constexpr iostate eofbit = /*implementation defined*/
</code>```

So setting of the eofbit doesn't necessarily trigger your exception mask.

Body:
When executing the following code, I get the following output: EOF FAIL. So reading a line from an empty file sets eofbit and failbit, but not badbit.

If I enable exceptions by uncommenting line 11 the output changes: EOF BAD FAIL. Now reading a line from an empty file sets eofbit, badbit, but not failbit (otherwise an exception had occured).

Can someone explain why enabling exceptions changes the way, failbit and badbit are set. Is this documented somewhere?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char const *argv[]) {
    ifstream f("some_empty_file");
    string line;

    // f.exceptions(std::ifstream::failbit); // (line 11)

    getline(f, line);
    if(f.eof()) cout << "EOF ";
    if(f.bad()) cout << "BAD ";
    if(f.fail()) cout << "FAIL ";

    cout << endl;
    f.close();

    return 0;
}

Edit: I read the answer on https://stackoverflow.com/a/11085193/3821618 on the difference of badbit and failbit. But that does not answer the question, why with exceptions enabled, reading from an empty file becomes a "serious error", while it is not, if I do not call f.exceptions(...)

Body:
There are 4 distinct stream states (taken from std::ios_base::iostate):

 typedef /*implementation defined*/ iostate;
 static constexpr iostate goodbit = 0;
 static constexpr iostate badbit = /*implementation defined*/
 static constexpr iostate failbit = /*implementation defined*/
 static constexpr iostate eofbit = /*implementation defined*/

So setting of the eofbit doesn't necessarily trigger your exception mask.


问:
In Complexity Analysis why is ++ considered to be 2 operations?
In my Computer Science II class, the professor considers ++,--,*=, etc. to be 2 operations. However, at the Assembly level this is not really two operations. Can someone explain or is this just for the sake of simplicity?</p>

答:
You reminded me of a Kinda "Jury is not out" problem that I heard a long time ago.

"Preincrement is faster than postincrement"

I just did a quick google search.

Lots of people still hold that as true.

Others contend that Compilers are so optimized, the comparative high level code code can't be benchmarked.

Yet other people contend that there is no difference.


问:
Customized folder structure for Angular CLI
I am experiencing a challenge while setup my new Angular project with Angular CLI.

I would like to create a folder structure something like below:

```<code>-- src
    -- components
       -- app
       -- students
       -- faculty
       -- admin
       -- common
          -- search
          -- table
          -- table_row
          -- list
          -- list_item
          -- header
          -- footer
          -- side_panel
    -- services
    -- static
       -- jsons
           -- cities
           -- states
           -- time_zones
       -- imgs
       -- scss
</code>```

If we run ng g c some-component command it creates new component inside src/app/ only.

In terms of code, app itself is a component, then why does the Angular CLI not allow us to create another component parallel to the app component?

However, it is feasible if we create the folder's structure manually and without using CLI commands. The app also works fine.

Each application has its own size and functionality and needs some specific code design, then why impose such a limitation? Can anyone help me in understanding what the benefit of this structure is?

答: I used something like that: ng g c common\some-component if you need it goes to the \common\ directory.</p>

Body:
I am experiencing a challenge while setup my new Angular project with Angular CLI.

I would like to create a folder structure something like below:

-- src
    -- components
       -- app
       -- students
       -- faculty
       -- admin
       -- common
          -- search
          -- table
          -- table_row
          -- list
          -- list_item
          -- header
          -- footer
          -- side_panel
    -- services
    -- static
       -- jsons
           -- cities
           -- states
           -- time_zones
       -- imgs
       -- scss

If we run ng g c some-component command it creates new component inside src/app/ only.

In terms of code, app itself is a component, then why does the Angular CLI not allow us to create another component parallel to the app component?

However, it is feasible if we create the folder's structure manually and without using CLI commands. The app also works fine.

Each application has its own size and functionality and needs some specific code design, then why impose such a limitation? Can anyone help me in understanding what the benefit of this structure is?


问:
JavaScript - compare two arrays with limited values/elements
I have an array of a few numbers or strings, eg.

```<code>[4.3, 1.2, 4.5, 3.9]

['I', 'the', 'sheriff', 'shot']
</code>```

The users re-arrange the elements in a specific order. For example, in an ascending order:

```<code>[1.2, 3.9, 4.3, 4.5]
</code>```

and to create a valid sentence:

```<code>['I', 'shot', 'the', 'sheriff']
</code>```

I have those predefined answers stored in an object. How do I compare the arrays with user generated order with the ones with correct order of elements. I have seen other answers on how to compare arrays but my question does not require a wide range of 'what if....' that other answers had. The elements are generated by the app so no unexpected input would be there, no undefined values, no empty elements, etc. Users do not input anything. They just rearrange tiles with those elements.

What's the best way to compare the arrays to determine if the users have rearranged the boxes in the right way.

My first attempt is incorrect as it always seems to be outputing 'BINGO' even if the order is incorrect:

```<code>if (this.props.squares === correctOrder) {
      console.log("BINGO");
    }
</code>```

答:
If you don't mind using lodash, this also could be an option.

```<code>_.isEqual(this.props.squares, correctOrder);
</code>```

Body:
I have an array of a few numbers or strings, eg.

[4.3, 1.2, 4.5, 3.9]

['I', 'the', 'sheriff', 'shot']

The users re-arrange the elements in a specific order. For example, in an ascending order:

[1.2, 3.9, 4.3, 4.5]

and to create a valid sentence:

['I', 'shot', 'the', 'sheriff']

I have those predefined answers stored in an object. How do I compare the arrays with user generated order with the ones with correct order of elements. I have seen other answers on how to compare arrays but my question does not require a wide range of 'what if....' that other answers had. The elements are generated by the app so no unexpected input would be there, no undefined values, no empty elements, etc. Users do not input anything. They just rearrange tiles with those elements.

What's the best way to compare the arrays to determine if the users have rearranged the boxes in the right way.

My first attempt is incorrect as it always seems to be outputing 'BINGO' even if the order is incorrect:

if (this.props.squares === correctOrder) {
      console.log("BINGO");
    }

Body:
If you don't mind using lodash, this also could be an option.

_.isEqual(this.props.squares, correctOrder);


问:
Google calendar edit event - description not saved when edited by jQuery
I'm trying to write an Chrome extension to fill in the event description in Google Calendar - edit event window. But when I add text there using Jquery: $('textarea').val('test'); and save the event, the description is not saved. Does anybody know how to solve this? </p>

答:
The solution is to insert the text by JS, and focus the field:</p>

```<code>        $("#myfield").keyup(function(e){
            //text changed, update description field
            text_tv = $(this).val();
            descr.val('');
            descr.focus();
            document.execCommand('insertText', false, convert_to_tv(text_tv));
            $(this).focus();
        });
</code>```

Body:
The solution is to insert the text by JS, and focus the field:

        $("#myfield").keyup(function(e){
            //text changed, update description field
            text_tv = $(this).val();
            descr.val('');
            descr.focus();
            document.execCommand('insertText', false, convert_to_tv(text_tv));
            $(this).focus();
        });


问:
No db context provider has been configure for this DbContext... although it has
Have a solution with 3 assemblies: Data, Domain and Web. Data holds the context, Web is a .NET Core WebAPI app, and they're all in the same solution directory. I'm also using Postgre as the database.

Here's my ConfigureServices method in Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    string connectionString = Configuration.GetConnectionString("DefaultConnection");
            ...
    services.AddDbContext<WebStoreContext>(
        options => options.UseNpgsql(
            connectionString,
            (providerOptions) =>
            {
                providerOptions.CommandTimeout(20);
                providerOptions.MigrationsAssembly("WebStore.Data");
            }));

    services.AddMvc();
            ...
}
</code>```

Notice how a database provider has been configured by using AddDbContext and passing the optionsAction parameter.

Now I've created an initial migration for the db, using the command line ef tool.
I've cd-ed into WebStore.Data and ran:

```<code>dotnet ef --startup-project ..\WebStore.Web migrations add IntializeDb
</code>```

That's all good.

The problem begins when I try to, from the same directory, run:

```<code>dotnet ef database update
</code>```

No parameterless constructor was found on 'WebStoreContext'. Either add a parameterless constructor to 'WebStoreContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'WebStoreContext'.

The above error I get before I declare a parameterless constructor in my DbContext derived class, and the below error after I declare one:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

So it seems to me like the paramterless constructor keeps getting called despite me providing a DbContextOptions instance.

So then I tried this:

```<code>//parameterless constructor calling the one accepting the DbContextOptions argument
public WebStoreContext() : this(new DbContextOptionsBuilder<WebStoreContext>()
.UseNpgsql("UserID=****;Password=****;Host=localhost;Port=****;Database=webstore;Pooling=true;")
.Options){ }
</code>```

and got this:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileLoadException: Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Still trying to figure out what's going on here. Help would be greatly appreciated.

EDIT:
I applied Shay Rojansky's solution and it worked, although I had the following issue:

System.IO.FileLoadException: Could not load file or assembly
  'System.Diagnostics.DiagnosticSource, Version=4.0.1.1,
  Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The located
  assembly's manifest definition does not match the assembly reference.
  (Exception from HRESULT: 0x80131040) File name:
  'System.Diagnostics.DiagnosticSource, Version=4.0.1.1,
  Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'    at
  Microsoft.EntityFrameworkCore.Infrastructure.RelationalServiceCollectionExtensions.AddRelational(IServiceCollection
  services)    at
  Microsoft.Extensions.DependencyInjection.NpgsqlEntityFrameworkServicesBuilderExtensions.AddEntityFrameworkNpgsql(IServiceCollection
  services)    at
  Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_1.b__2(Int64
  k)    at
  System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey
  key, Func`2 valueFactory)    at
  Microsoft.EntityFrameworkCore.DbContext.InitializeServices()    at
  Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
  at
  Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1
  accessor)    at
  Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1
  factory)    at
  Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String
  contextType)    at
  Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String
  targetMigration, String contextType)    at
  Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
  at
  Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action
  action)

Could not load file or assembly
  'System.Diagnostics.DiagnosticSource, Version=4.0.1.1,
  Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The located
  assembly's manifest definition does not match the assembly reference.
  (Exception from HRESULT: 0x80131040)

To which the solution is adding this to the .csproj file:

```<code><PropertyGroup>
        <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
</PropertyGroup>
</code>```

This happens apparently due to a bug.

答:
Try adding an OnConfiguring method to your context, as suggested by the EF Core getting started docs:

```<code>protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
    optionsBuilder.UseNpgsql("...");
}
</code>```

Body:
Have a solution with 3 assemblies: Data, Domain and Web. Data holds the context, Web is a .NET Core WebAPI app, and they're all in the same solution directory. I'm also using Postgre as the database.

Here's my ConfigureServices method in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    string connectionString = Configuration.GetConnectionString("DefaultConnection");
            ...
    services.AddDbContext<WebStoreContext>(
        options => options.UseNpgsql(
            connectionString,
            (providerOptions) =>
            {
                providerOptions.CommandTimeout(20);
                providerOptions.MigrationsAssembly("WebStore.Data");
            }));

    services.AddMvc();
            ...
}

Notice how a database provider has been configured by using AddDbContext and passing the optionsAction parameter.

Now I've created an initial migration for the db, using the command line ef tool.
I've cd-ed into WebStore.Data and ran:

dotnet ef --startup-project ..\WebStore.Web migrations add IntializeDb

That's all good.

The problem begins when I try to, from the same directory, run:

dotnet ef database update

No parameterless constructor was found on 'WebStoreContext'. Either add a parameterless constructor to 'WebStoreContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'WebStoreContext'.

The above error I get before I declare a parameterless constructor in my DbContext derived class, and the below error after I declare one:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

So it seems to me like the paramterless constructor keeps getting called despite me providing a DbContextOptions instance.

So then I tried this:

//parameterless constructor calling the one accepting the DbContextOptions argument
public WebStoreContext() : this(new DbContextOptionsBuilder<WebStoreContext>()
.UseNpgsql("UserID=****;Password=****;Host=localhost;Port=****;Database=webstore;Pooling=true;")
.Options){ }

and got this:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileLoadException: Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Still trying to figure out what's going on here. Help would be greatly appreciated.

EDIT:
I applied Shay Rojansky's solution and it worked, although I had the following issue:

System.IO.FileLoadException: Could not load file or assembly
  'System.Diagnostics.DiagnosticSource, Version=4.0.1.1,
  Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The located
  assembly's manifest definition does not match the assembly reference.
  (Exception from HRESULT: 0x80131040) File name:
  'System.Diagnostics.DiagnosticSource, Version=4.0.1.1,
  Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'    at
  Microsoft.EntityFrameworkCore.Infrastructure.RelationalServiceCollectionExtensions.AddRelational(IServiceCollection
  services)    at
  Microsoft.Extensions.DependencyInjection.NpgsqlEntityFrameworkServicesBuilderExtensions.AddEntityFrameworkNpgsql(IServiceCollection
  services)    at
  Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_1.b__2(Int64
  k)    at
  System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey
  key, Func`2 valueFactory)    at
  Microsoft.EntityFrameworkCore.DbContext.InitializeServices()    at
  Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
  at
  Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1
  accessor)    at
  Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1
  factory)    at
  Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String
  contextType)    at
  Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String
  targetMigration, String contextType)    at
  Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
  at
  Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action
  action)

Could not load file or assembly
  'System.Diagnostics.DiagnosticSource, Version=4.0.1.1,
  Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The located
  assembly's manifest definition does not match the assembly reference.
  (Exception from HRESULT: 0x80131040)

To which the solution is adding this to the .csproj file:

<PropertyGroup>
        <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
</PropertyGroup>

This happens apparently due to a bug.

Body:
Try adding an OnConfiguring method to your context, as suggested by the EF Core getting started docs:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
    optionsBuilder.UseNpgsql("...");
}


问:
How do i add a transparent background when search?
My goal is to simply add a transparent background to the body of HTML when someone is searching on the input text field

Before searching

Once search

Code

```<code><body>
  <div class="container">
    <nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="/">Testing</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">

      <form novalidate="novalidate" onsubmit="return false;" class="searchbox sbx-amazon" style="margin-left: 20%" id="search-realtime">
        <div role="search" class="sbx-amazon__wrapper">
          <input type="search" id="search_input" name="search" placeholder="Search your product.." autocomplete="off" required="required" class="sbx-amazon__input">
          <button type="submit" title="Submit your search query." class="sbx-amazon__submit">
            <svg role="img" aria-label="Search">
              <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-search-11"></use>
            </svg>
          </button>
          <button type="reset" title="Clear the search query." class="sbx-amazon__reset">
            <svg role="img" aria-label="Reset">
              <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-clear-2"></use>
            </svg>
          </button>
        </div>
      </form>
    </div>
  </div>
</nav>

   </div>

</body>
</code>```

On the search input later on, type in "I will" to see the result
You can check jsfiddle for full code https://jsfiddle.net/Ldpqhkam/2/

答:
Just create a div element somewhere within the body (preferably at the bottom), like so:

```<code><div id="search-overlay"></div>
</code>```

and give it this CSS:

```<code>#search-overlay { position:fixed; top:52px; bottom:0; left:0; right:0; background:#000; opacity:.5; display:none; }
</code>```

Then you toggle the display property of this overlay div by hooking into the appropriate events of the autocomplete, namely autocomplete:shown and autocomplete:closed

See working example here:
https://jsfiddle.net/Ldpqhkam/5/

Body:
My goal is to simply add a transparent background to the body of HTML when someone is searching on the input text field

Before searching

Once search

Code

      Testing

      <form novalidate="novalidate" onsubmit="return false;" class="searchbox sbx-amazon" style="margin-left: 20%" id="search-realtime">

          <input type="search" id="search_input" name="search" placeholder="Search your product.." autocomplete="off" required="required" class="sbx-amazon__input">
          <button type="submit" title="Submit your search query." class="sbx-amazon__submit">
            <svg role="img" aria-label="Search">
              <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-search-11"></use>
            </svg>
          </button>
          <button type="reset" title="Clear the search query." class="sbx-amazon__reset">
            <svg role="img" aria-label="Reset">
              <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-clear-2"></use>
            </svg>
          </button>

      </form>

On the search input later on, type in "I will" to see the result
You can check jsfiddle for full code https://jsfiddle.net/Ldpqhkam/2/

Body:
Just create a div element somewhere within the body (preferably at the bottom), like so:

<div id="search-overlay"></div>

and give it this CSS:

#search-overlay { position:fixed; top:52px; bottom:0; left:0; right:0; background:#000; opacity:.5; display:none; }

Then you toggle the display property of this overlay div by hooking into the appropriate events of the autocomplete, namely autocomplete:shown and autocomplete:closed

See working example here:
https://jsfiddle.net/Ldpqhkam/5/


问:
Is it possible to increment a PowerShell pipe variable?
I'm trying to count a record as it passes through a pipe. My expression looks like:

```<code>$x=28
gci | Select-Object basename, fullname, @{name='x'; Expression={($x--)}}
</code>```

I get:

```<code>BaseName FullName                x
-------- --------                -
aaoeu    C:\Users\m\x\aaoeu.txt 28
aue      C:\Users\m\x\aue.txt   28
xx       C:\Users\m\x\xx.txt    28
</code>```

I've tried Add-Member instead of the @ expression as above and that did the same thing - x doesn't alter value per object.

My end-goal is to generate a CSV file so I could use Write-Host to iterate through the Get-ChildItem (gci) output if it's not possible to get my variables to change value as gci emits records.

Am I missing the correct syntax to increment a variable in Select-Object or Add-Member or is it just not possible to do that?

答:
Solution 3 (declaration into the loop):</p>

```<code>gci | foreach -Begin {$x=28 } -process { $x++; [pscustomobject]@{BaseName=$_.BaseName; FullName=$_.FullName; x=$x}}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to count a record as it passes through a pipe. My expression looks like:

$x=28
gci | Select-Object basename, fullname, @{name='x'; Expression={($x--)}}

I get:

BaseName FullName                x
-------- --------                -
aaoeu    C:\Users\m\x\aaoeu.txt 28
aue      C:\Users\m\x\aue.txt   28
xx       C:\Users\m\x\xx.txt    28

I've tried Add-Member instead of the @ expression as above and that did the same thing - x doesn't alter value per object.

My end-goal is to generate a CSV file so I could use Write-Host to iterate through the Get-ChildItem (gci) output if it's not possible to get my variables to change value as gci emits records.

Am I missing the correct syntax to increment a variable in Select-Object or Add-Member or is it just not possible to do that?

Body:
Solution 3 (declaration into the loop):

gci | foreach -Begin {$x=28 } -process { $x++; [pscustomobject]@{BaseName=$_.BaseName; FullName=$_.FullName; x=$x}}


问:
How to replace multiple sets of keywords in a string?
So I have a file of strings that I am reading in, and I have to replace certain values in them with other values. The amount of possible replacements is variable. As in, it reads the patterns to replace with in from a file. Currently I'm storing in a vector<pair<string,string>> for the patterns to find and match. However I run into issues:

Example:

Input string: abcd.eaef%afas&333

Delimiter patterns:

. %%%

% ###

& @@@

Output I want: abcd%%%eaef###afas@@@333

Output I get: abcd#########eaef###afas@@@333

The issue being it ends up replacing the % sign or any other symbol that was already a replacement for something else, it should not be doing that.

My code is (relevant portions):

```<code>std::string& replace(std::string& s, const std::string& from, const std::string& to){
    if(!from.empty())
        for(size_t pos = 0; (pos = s.find(from, pos)) != std::string::npos; pos += to.size()) s.replace(pos, from.size(), to);
    return s;
}
string line;
vector<pair<string, string>> myset;
while(getline(delimiterfile, line)){
    istringstream is(line);
    string delim, pattern;
    if(is >> delim >> pattern){
        myset.push_back(make_pair(delim, pattern));
    } else {
        throw runtime_error("Invalid pattern pair!");
    }
}

while(getline(input, line)){
    string temp = line;
    for(auto &item : myset){
        replace(temp, item.first, item.second);
    }
    output << temp << endl;
}
</code>```

Can someone please tell me what I'm messing up and how to fix it?

答:
In pseudo-code a simple replacement algorithm could look something like this:

```<code>string input = getline();
string output;  // The string containing the replacements
for (each char in input)
{
    if (char == '.')
        output += "%%%";
    // TODO: Other replacements
    else
        output += char;
}
</code>```

If you implement the above code, once it's done the variable output will contain the string with all replacements made.

Body:
So I have a file of strings that I am reading in, and I have to replace certain values in them with other values. The amount of possible replacements is variable. As in, it reads the patterns to replace with in from a file. Currently I'm storing in a vector<pair<string,string>> for the patterns to find and match. However I run into issues:

Example:

Input string: abcd.eaef%afas&333

Delimiter patterns:

. %%%

% ###

& @@@

Output I want: abcd%%%eaef###afas@@@333

Output I get: abcd#########eaef###afas@@@333

The issue being it ends up replacing the % sign or any other symbol that was already a replacement for something else, it should not be doing that.

My code is (relevant portions):

std::string& replace(std::string& s, const std::string& from, const std::string& to){
    if(!from.empty())
        for(size_t pos = 0; (pos = s.find(from, pos)) != std::string::npos; pos += to.size()) s.replace(pos, from.size(), to);
    return s;
}
string line;
vector<pair<string, string>> myset;
while(getline(delimiterfile, line)){
    istringstream is(line);
    string delim, pattern;
    if(is >> delim >> pattern){
        myset.push_back(make_pair(delim, pattern));
    } else {
        throw runtime_error("Invalid pattern pair!");
    }
}

while(getline(input, line)){
    string temp = line;
    for(auto &item : myset){
        replace(temp, item.first, item.second);
    }
    output << temp << endl;
}

Can someone please tell me what I'm messing up and how to fix it?

Body:
In pseudo-code a simple replacement algorithm could look something like this:

string input = getline();
string output;  // The string containing the replacements
for (each char in input)
{
    if (char == '.')
        output += "%%%";
    // TODO: Other replacements
    else
        output += char;
}

If you implement the above code, once it's done the variable output will contain the string with all replacements made.


答: I would suggest you use stringstream. This way you will be able to achieve what you are looking for very easily.</p>

Title: How to replace multiple sets of keywords in a string?


问:
unable to resolve getter method
I'm learning java as a beginner and I'm trying to create a program that calculates your future age as an exercise.

I have the following issue:

Error:(14, 64) java: cannot find symbol
symbol:   method getYear()
location: class ageProgram

I can't seem to get my getter methods eventho they are declared public.

ageProgram.java:

```<code>import java.util.Scanner;

public class ageProgram {
    public static void main(String[]args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("enter your birth year");
        int yearBirth = keyboard.nextInt();
        System.out.println("enter a (future) year");
        int yearTo = keyboard.nextInt();

        ageCalculator agecalculator = new ageCalculator(yearBirth, yearTo);

        if (yearBirth > yearTo) {
            System.out.println("You will be born in %s years", getYear());
        } else {
            System.out.println("You are %s years old", getYear());
        }
    }
}
</code>```

ageCalculator.java:

```<code>public class ageCalculator {
        public ageCalculator(int yearBirth, int yearTo) {
            if (yearBirth > yearTo) {
                int year = (yearBirth - yearTo);
                year = year.toString();
            } else {
                int year = (yearTo - yearBirth);
                year = year.toString();
            }
        }
        public String getYear() {
            return year;
        }
        }
</code>```

I'm not sure what I am doing wrong... I tried to check for solutions at similar / other questions on stackoverflow but nothing seems to work.

Thanks for the help!

答: You must tell which object the method getYear you are referring to. In your example, you must call getYear as agecalculator.getYear() and all should be fine.

Title: unable to resolve getter method

Body:
I'm learning java as a beginner and I'm trying to create a program that calculates your future age as an exercise.

I have the following issue:

Error:(14, 64) java: cannot find symbol
symbol:   method getYear()
location: class ageProgram

I can't seem to get my getter methods eventho they are declared public.

ageProgram.java:

import java.util.Scanner;

public class ageProgram {
    public static void main(String[]args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("enter your birth year");
        int yearBirth = keyboard.nextInt();
        System.out.println("enter a (future) year");
        int yearTo = keyboard.nextInt();

        ageCalculator agecalculator = new ageCalculator(yearBirth, yearTo);

        if (yearBirth > yearTo) {
            System.out.println("You will be born in %s years", getYear());
        } else {
            System.out.println("You are %s years old", getYear());
        }
    }
}

ageCalculator.java:

public class ageCalculator {
        public ageCalculator(int yearBirth, int yearTo) {
            if (yearBirth > yearTo) {
                int year = (yearBirth - yearTo);
                year = year.toString();
            } else {
                int year = (yearTo - yearBirth);
                year = year.toString();
            }
        }
        public String getYear() {
            return year;
        }
        }

I'm not sure what I am doing wrong... I tried to check for solutions at similar / other questions on stackoverflow but nothing seems to work.

Thanks for the help!


问:
how to deal with components inside components in angular?
Maybe It's simple question but I've been searching for a while and I don't find how to do something like this in angular :

```<code><Parent>
  <Child1>
  <Child2>
</Parent>
</code>```

And Define the behavior of the children in the parent component. Is That possible ?

答:
We can base it at <ng-content></ng-content> and CSS class-es:

HTML (app.component.html)

```<code><app-new-accordion>
      <div class="accord-head-1">Header 1</div>
      <div class="accord-head-2">Header 2</div>
      <div class="accord-body-1">Content 1</div>
      <div class="accord-body-2">Content 2</div>
  </app-new-accordion>
</code>```

Component (new-accordion.component.ts)

```<code>@Component({
  selector: 'app-new-accordion',
  templateUrl: './new-accordion.component.html',
  styleUrls: ['./new-accordion.component.css']
})
</code>```

Component HTML (new-accordion.component.html)

```<code><div>
  <h2><ng-content select=".accord-head-1"></ng-content></h2>
  <p><ng-content select=".accord-body-1"></ng-content></p>
</div>
<div>
  <h2><ng-content select=".accord-head-2"></ng-content></h2>
  <p><ng-content select=".accord-body-2"></ng-content></p>
</div>
</code>```

Body:
Maybe It's simple question but I've been searching for a while and I don't find how to do something like this in angular :

<Parent>
  <Child1>
  <Child2>
</Parent>

And Define the behavior of the children in the parent component. Is That possible ?

Body:
We can base it at <ng-content></ng-content> and CSS class-es:

HTML (app.component.html)

<app-new-accordion>
      <div class="accord-head-1">Header 1</div>
      <div class="accord-head-2">Header 2</div>
      <div class="accord-body-1">Content 1</div>
      <div class="accord-body-2">Content 2</div>
  </app-new-accordion>

Component (new-accordion.component.ts)

@Component({
  selector: 'app-new-accordion',
  templateUrl: './new-accordion.component.html',
  styleUrls: ['./new-accordion.component.css']
})

Component HTML (new-accordion.component.html)

<div>
  <h2><ng-content select=".accord-head-1"></ng-content></h2>
  <p><ng-content select=".accord-body-1"></ng-content></p>
</div>
<div>
  <h2><ng-content select=".accord-head-2"></ng-content></h2>
  <p><ng-content select=".accord-body-2"></ng-content></p>
</div>


问:
Why watson Personality Inisights shows different results using different API versions/demo
My apologies if the question is duplicated. We are facing an issue with the analysis of a profile using Watson Personality Insights API in Spanish. We have a demo we implemented using PI API version 2 and then we tested the results (exact same text) with the demo published on developer cloud(in spanish) and we found important differences on how the big five were calculated when the facet values were not that different. Is it possible that these differences are caused because of the API version? The issue that with our demo the big five values produced a kind of negative summary profile when the developercloud summary is kinder.
We could send both result jsons. For example here is how the big five rated:

BigFive             DeveloperCloud      Demo V2

Openness            0.773834349         0.847273232

Conscientiousness   0.916616088         0.914907481

Extraversion        0.796331544         0.612606551

Agreeableness       0.17445636          0.096118648

Emotional range     0.036287447         0.01623536

thanks in advance!!

答:
thanks Neil for you answer!
We tested the text using CURL and we noticed that the results didn't change by the service version used but instead by how the text was sent. If we called the service using curl passing a plain text input(formatted in UTF-8 with line breaks) it returned the same results for version2 and version 3 and also matched the ones from our demo. If we called the service using curl passing json input WITHOUT line breaks it returned the same values as well. But if we called the service passing the json input WITH line breaks then the results changed and almost matched those shown by ibm demo. My question here is which are the correct results? The ones shown when the text is sent as a plain text input(with line breaks) or when the text is sent as json input(with line breaks)? Is there any technical guideline besides the one shown in developercloud on how the text should be parsed to use this service?
Thanks again!</p>


问:
personal version control system to recommend
For personal use. Anyone can recommend the version control system for Windows</p>

答: Subversion has an excellent client, Tortoise, available on Windows. Git has a version of Tortoise as well, however, it's not as reliable.</p>


问:
Get orders for a particular year using CASE WHEN
I'm using this order dataset and trying to get 2 columns of data, one of 1998 orders and one of 1996 orders alongside each seller's name.

My SQL so far is:

```<code>select
    salesperson.name,
    case when strftime('%Y', order_date) = 1998 then sum(orders.number) end as sales_in_1998,
    case when strftime('%Y', order_date) = 1996 then sum(orders.number) end as sales_in_1996
from salesperson
left join orders on orders.salesperson_id = salesperson.id
group by salesperson.name;
</code>```

(sorry no YEAR() function since I loaded it into sqlite)

However, I'm just getting NULLs for everything. What am I doing wrong?

Here is my SQLfiddle with the data loaded in it.

答:
The CASE goes inside the SUM().

Use single quotes for string comparisons.

The resulting query:

```<code>select sp.name,
       sum(case when strftime('%Y', o.order_date) = '1998' then o.number
           end) as sales_in_1998,
       sum(case when strftime('%Y', o.order_date) = '1996' then o.number
           end) as sales_in_1996
from salesperson sp left join
     orders o
     on o.salesperson_id = sp.id
group by sp.name;
</code>```

Body:
I'm using this order dataset and trying to get 2 columns of data, one of 1998 orders and one of 1996 orders alongside each seller's name.

My SQL so far is:

select
    salesperson.name,
    case when strftime('%Y', order_date) = 1998 then sum(orders.number) end as sales_in_1998,
    case when strftime('%Y', order_date) = 1996 then sum(orders.number) end as sales_in_1996
from salesperson
left join orders on orders.salesperson_id = salesperson.id
group by salesperson.name;

(sorry no YEAR() function since I loaded it into sqlite)

However, I'm just getting NULLs for everything. What am I doing wrong?

Here is my SQLfiddle with the data loaded in it.

Body:
The CASE goes inside the SUM().

Use single quotes for string comparisons.

The resulting query:

select sp.name,
       sum(case when strftime('%Y', o.order_date) = '1998' then o.number
           end) as sales_in_1998,
       sum(case when strftime('%Y', o.order_date) = '1996' then o.number
           end) as sales_in_1996
from salesperson sp left join
     orders o
     on o.salesperson_id = sp.id
group by sp.name;


问:
Why does an AVL tree with N nodes maintain C<=N/2?
If C denotes the number of "only child" nodes (a node is called an only child when its parent is not null && it doesn't have a sibling), why do we have that for every AVL tree with N nodes : C<=(N/2) ?</p>

答:
Consider an AVL tree of height 1 (i.e. consisting only of the root): The condition clearly holds (N=1, C=0).

Now consider the AVL trees of height 2. There can be either a root with 2 children (N=3, C=0) or a root with one child (N=2, C=1). Thus the condition also holds for trees of height 2.

Now assume, the condition holds for trees of height h (h>=2) and h-1, we show that it then also holds for a tree of height h+1. We can construct a tree with height h+1 by taking a new root with one child of height h and the other child of height h or h-1. These are the only allowed configurations that keep the AVL property intact. Neither the new root nor the roots of the two subtrees are "only child" nodes. We have therefore N=1+N1+N2 and C=C1+C2. Since C1<=N1/2 and C2<=N2/2 we get also C<=N/2.

Now, by induction the condition holds for AVL trees of all heights.


问:
Why is RegOpenKeyEx() returning error code 2 on Vista 64bit?
I was making the following call:

```<code>result = RegOpenKeyEx(key, s, 0, KEY_READ, &key);
</code>```

(C++, Visual Studio 5, Vista 64bit).

It is failing with error code 2 ("File not found") even though "regedit" shows that the key exists.  This code has always worked on 32bit XP.  Why is it "file not found" when it clearly is there?

答: You have to compile with "Use Multi-Byte Character Set" or cast string in code to (LPWSTR)</p>

OwnerDisplayName: Tim Cooper

Body:
I was making the following call:

result = RegOpenKeyEx(key, s, 0, KEY_READ, &key);

(C++, Visual Studio 5, Vista 64bit).

It is failing with error code 2 ("File not found") even though "regedit" shows that the key exists.  This code has always worked on 32bit XP.  Why is it "file not found" when it clearly is there?

LastEditorDisplayName: Brian R. Bondy


问:
400 - Bad Request ( AngularJS+Passport)
I use angularJS+passport to perform user authentication and hence, i set up these below.
HTML:

```<code><div ng-controller="logincontroller">
<form>
Email:<input type="text" ng-model="user.email"/>
Password:<input type="password" ng-model="user.password"/>
<div ng-click=loginUser()>Submit</div>
</form>
</div>
</code>```

In client side javascript:

```<code>  app.controller('logincontroller',function($scope,$http){
    $scope.loginUser=function(){
    $http.post('/loginUser',JSON.stringify($scope.user));
   }
   })
</code>```

ON app.js

```<code>   passport.use(new LocalStrategy(
    {usernameField: 'user.email',
    passwordField: 'user.password',
    passReqToCallback : true
    },
    function(req,username,password,done){
      console.log("am hre");

}
))

app.post('/loginUser',passport.authenticate('local'));
</code>```

I am not sure if i have set request pattern right. I get 400 - Bad request while trying to login and i don't think strategy is invoked. Please favour.

答:
Well,Just had to add name attribute to input tag. That solves it all

In html

```<code>Email:<input type="text" name="email" ng-model="user.email"/>
Password:<input type="password" name="password" ng-model="user.password"/>
</code>```

And in app.js

```<code>passport.use(new LocalStrategy(
    {usernameField: 'email',
    passwordField: 'password',
    passReqToCallback : true
    },
    function(req,username,password,done){
      console.log("am hre");
</code>```

Title: 400 - Bad Request ( AngularJS+Passport)

Body:
I use angularJS+passport to perform user authentication and hence, i set up these below.
HTML:

<form>
Email:<input type="text" ng-model="user.email"/>
Password:<input type="password" ng-model="user.password"/>

Submit

</form>

In client side javascript:

  app.controller('logincontroller',function($scope,$http){
    $scope.loginUser=function(){
    $http.post('/loginUser',JSON.stringify($scope.user));
   }
   })

ON app.js

   passport.use(new LocalStrategy(
    {usernameField: 'user.email',
    passwordField: 'user.password',
    passReqToCallback : true
    },
    function(req,username,password,done){
      console.log("am hre");

}
))

app.post('/loginUser',passport.authenticate('local'));

I am not sure if i have set request pattern right. I get 400 - Bad request while trying to login and i don't think strategy is invoked. Please favour.

Body:
Well,Just had to add name attribute to input tag. That solves it all

In html

Email:<input type="text" name="email" ng-model="user.email"/>
Password:<input type="password" name="password" ng-model="user.password"/>

And in app.js

passport.use(new LocalStrategy(
    {usernameField: 'email',
    passwordField: 'password',
    passReqToCallback : true
    },
    function(req,username,password,done){
      console.log("am hre");


问:
Why are all the numbers print out when I want only the largest?
I want to display only the largest number (price) from a text file. Every time it shows me the whole numbers instead of the highest value. I've been using a lot of methods like the for loop and others. But I think the problem is about something else.</p>

```<code> package practice;
 import java.util.Scanner;
 import java.io.*;
 public class Practice {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
      String fileName = "C:\\Users\\Work\\Desktop\\Prices.txt";
      File inFile = new File(fileName);
      Scanner inPut = new Scanner(inFile);
      String line = inPut.nextLine();
      while(inPut.hasNext()){

        String[] Company = new String[3];
        int[] Price = new int[3];
        int[] Quality = new int[3];

        int count = 0;
        count++;

        Company[count] = inPut.next();
        Price[count] = inPut.nextInt();
        Quality[count] = inPut.nextInt();

        int HighestPrice = Price[0];

        int counter = 1;
        while(counter<Price.length-1){
          if(Price[counter]>HighestPrice){
              HighestPrice = Price[counter];
              int hi = counter;
            }
            counter++;
          }
          System.out.println(HighestPrice);
        }
      }
    }
</code>```

答:
Close the loop body after taking input in the arrays.

You should create your arrays outside the loop as their reference gets lost each time you recreate them.

```<code>String line = inPut.nextLine();
String[] Company = new String[3];
int[] Price = new int[3];
int[] Quality = new int[3];
int count = 0;
while(inPut.hasNext()){
  Company[count] = inPut.next();
  Price[count] = inPut.nextInt();
  Quality[count] = inPut.nextInt();
  count++;
}
</code>```

Body:
I want to display only the largest number (price) from a text file. Every time it shows me the whole numbers instead of the highest value. I've been using a lot of methods like the for loop and others. But I think the problem is about something else.

 package practice;
 import java.util.Scanner;
 import java.io.*;
 public class Practice {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
      String fileName = "C:\\Users\\Work\\Desktop\\Prices.txt";
      File inFile = new File(fileName);
      Scanner inPut = new Scanner(inFile);
      String line = inPut.nextLine();
      while(inPut.hasNext()){

        String[] Company = new String[3];
        int[] Price = new int[3];
        int[] Quality = new int[3];

        int count = 0;
        count++;

        Company[count] = inPut.next();
        Price[count] = inPut.nextInt();
        Quality[count] = inPut.nextInt();

        int HighestPrice = Price[0];

        int counter = 1;
        while(counter<Price.length-1){
          if(Price[counter]>HighestPrice){
              HighestPrice = Price[counter];
              int hi = counter;
            }
            counter++;
          }
          System.out.println(HighestPrice);
        }
      }
    }

Body:
Close the loop body after taking input in the arrays.

You should create your arrays outside the loop as their reference gets lost each time you recreate them.

String line = inPut.nextLine();
String[] Company = new String[3];
int[] Price = new int[3];
int[] Quality = new int[3];
int count = 0;
while(inPut.hasNext()){
  Company[count] = inPut.next();
  Price[count] = inPut.nextInt();
  Quality[count] = inPut.nextInt();
  count++;
}


问:
Easiest way to get users current location/
What is the fastest/easiest way to get the users location with the CoreLocation framework? Is there a single method that can do this? Or will I have to go thru the whole startUpdatingLocation business?</p>

答: I believe the classic "Where am I" example would be most helpful to you.</p>


问:
Regex match anything but a specific pattern
I need a regex, that matches anything but the pattern \d+-\d+

The to be ignored pattern is a number with one ore more digits followed by a hyphen then followed by another number with one or more digits.

For example:

Test 123 Test 123-123 Test

only "123-123" should not be matched

Can anyone help me to achieve this?

答:
You didn't specify if you want an expression for matching individual strings (Pattern#matches(String, CharSequence) or String#matches(String)) or if you want to find multiple matches in one string (Matcher#find()).

Matching a Single String

The following branch is taken if input is Test or 123, but not if it's 123-123:

```<code>if (input.matches("(?s)(?!\\d+-\\d+).*")) {
    // ...
}
</code>```

Although, if your code makes the actual matches call, you might as well write:

```<code>if (!input.matches("\\d+-\\d+")) {
    // ...
}
</code>```

Finding Matches in a String

If you want to find multiple matches in one string, much depends on how you want to tokenize. Here's example code that lists all whitespace-separated sequences that are not of the form \d+-\d+:

```<code>Pattern pattern = Pattern.compile("(?<=^|\\s)(?!\\d+-\\d+)\\S+(?=$|\\s)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
    System.out.println(matcher.group());
}
</code>```

For an input of "Test 123 Test 123-123 Test", the output would be:

```<code>Test
123
Test
Test
</code>```

If you want to tokenize differently, you will have to adjust the boundary matching. Java's regular expressions have a word boundary matcher (\b), but 123-123 wouldn't be considered a word, because it contains a hyphen, which is not a regex word character.

Body:
You didn't specify if you want an expression for matching individual strings (Pattern#matches(String, CharSequence) or String#matches(String)) or if you want to find multiple matches in one string (Matcher#find()).

Matching a Single String

The following branch is taken if input is Test or 123, but not if it's 123-123:

if (input.matches("(?s)(?!\\d+-\\d+).*")) {
    // ...
}

Although, if your code makes the actual matches call, you might as well write:

if (!input.matches("\\d+-\\d+")) {
    // ...
}

Finding Matches in a String

If you want to find multiple matches in one string, much depends on how you want to tokenize. Here's example code that lists all whitespace-separated sequences that are not of the form \d+-\d+:

Pattern pattern = Pattern.compile("(?<=^|\\s)(?!\\d+-\\d+)\\S+(?=$|\\s)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
    System.out.println(matcher.group());
}

For an input of "Test 123 Test 123-123 Test", the output would be:

Test
123
Test
Test

If you want to tokenize differently, you will have to adjust the boundary matching. Java's regular expressions have a word boundary matcher (\b), but 123-123 wouldn't be considered a word, because it contains a hyphen, which is not a regex word character.


答:
You put the code to find the largest number inside the while(inPut.hasNext()){ Block. because of that the while(counter<Price.length-1){ loop gets executed on every line and therefore only has one value to handle, which of course is everytime the largest.

Skip the second loop and only execute the code inside, put the System.out.println(HighestPrice); outside the outer loop and it should work.

Title: Why are all the numbers print out when I want only the largest?


答:
Try https://angular.io/docs/ts/latest/cookbook/component-communication.html.
Further references
- https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html
- https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html</p>

Title: how to deal with components inside components in angular?


问:
How to split a string using an empty separator in Python
What is a good way to do some_string.split('') in python? This syntax gives an error:

```<code>a = '1111'
a.split('')

ValueError: empty separator
</code>```

I would like to obtain:

```<code>['1', '1', '1', '1']
</code>```

答:
Method #1:

```<code>s="Amalraj"
l=[i for i in s]
print(l)
</code>```

Output:

```<code>['A', 'm', 'a', 'l', 'r', 'a', 'j']
</code>```

Method #2:

```<code>s="Amalraj"
l=list(s)
print(l)
</code>```

Output:

```<code>['A', 'm', 'a', 'l', 'r', 'a', 'j']
</code>```

Method #3:

```<code>import re; # importing regular expression module
s="Amalraj"
l=re.findall('.',s)
print(l)
</code>```

Output:

```<code>['A', 'm', 'a', 'l', 'r', 'a', 'j']
</code>```

Body:
What is a good way to do some_string.split('') in python? This syntax gives an error:

a = '1111'
a.split('')

ValueError: empty separator

I would like to obtain:

['1', '1', '1', '1']

Body:
Method #1:

s="Amalraj"
l=[i for i in s]
print(l)

Output:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Method #2:

s="Amalraj"
l=list(s)
print(l)

Output:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Method #3:

import re; # importing regular expression module
s="Amalraj"
l=re.findall('.',s)
print(l)

Output:

['A', 'm', 'a', 'l', 'r', 'a', 'j']


问:
How to setup entity relations in Entity Framework Core
Here we are on EF Core and got 3 tables:

News

Items

Links

And more (except News, Items): Content, Post, Form, etc.

And my model definitions

```<code>public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public Link Link { get; set; }
}

public class News
{
    public int Id { get; set; }
    public string Header { get; set; }
    public string Content { get; set; }
    public Link Link { get; set; }
}

public class Link
{
    public int Id { get; set; }
    public string Type { get; set; }
    public int RowId  { get; set; }
    public string Url { get; set; }
}
</code>```

Table Links describe URL for every News and every Item.
This means that Links has 4 columns:

Id

Type - news or item

RowId - contains ID of Item or News (depends on the Type)

URL

How to setup the relationships?
Keep in mind that we need to resolve Entity by URL in Links table.

答: Dapper. Just Dapper that allows write custom queries.</p>

Body:
Here we are on EF Core and got 3 tables:

News

Items

Links

And more (except News, Items): Content, Post, Form, etc.

And my model definitions

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public Link Link { get; set; }
}

public class News
{
    public int Id { get; set; }
    public string Header { get; set; }
    public string Content { get; set; }
    public Link Link { get; set; }
}

public class Link
{
    public int Id { get; set; }
    public string Type { get; set; }
    public int RowId  { get; set; }
    public string Url { get; set; }
}

Table Links describe URL for every News and every Item.
This means that Links has 4 columns:

Id

Type - news or item

RowId - contains ID of Item or News (depends on the Type)

URL

How to setup the relationships?
Keep in mind that we need to resolve Entity by URL in Links table.


问:
how to make POST action from another server - Laravel
How can i make post request from another server to my laravel server?

I have a website from another provider (lets say domainA.com) , they have CMS system, so I can make my custom pages - the question is, I want to make a form in domainA.com, and post it to domainB.com (my original Server), how can I make it in laravel? As far as I understand I should use api route file for this, is it secure to make such a POST request? because as far as I understand there is no token protection on api requests right?

sorry for my english - i am most interested in security side of such a action - if you show me an example, it would be appreciated.

答:
It's possible to accept post request to a Laravel Route and you can define route any of web.php or api.php route file but below are the differences.

web.php

Routes in Web.php will prevent the form without CSRF Token.
to avoid that you can add the route in VerifyCsrfToken.php file in except Array.

api.php

Routes will work directly but the api URL will be Example.com/api/<route>.

But for security you can share an Access Token for the routes and in the controller you can verify the requests with the access token and allow post.


问:
Why is there a difference in the content when inspecting a webpage using chrome and scraping it using BeatifulSoup?
I am trying to scrape the following webpage:

```<code>https://www.comparis.ch/immobilien/marktplatz/details/show/16792498
</code>```

When I use inspector in Chrome, I can see the coordinates in the following html snippet:

```<code><div data-fi-hf-streetview="" data-fi-hf-streetview-objectid="map-panorama-
streetview" data-fi-hf-streetview-latitude="47.373122178099064444511111111"
data-fi-hf-streetview-longitude="8.539781976138127069261111111" data-fi-hf
streetview-language="De" style="display:none;"></div>
</code>```

However, when I use BeautifulSoup to scrape the webpage, I cannot see this content anymore? Why is that? I use the following code to scrape it:

```<code>url = "https://www.comparis.ch/immobilien/marktplatz/details/show/16792498"
r = requests.get(url)
soup = BeautifulSoup(r.text)
</code>```

Even before extracting it, I cannot see the coordinates anymore.

答: That is because the HTML that your browser shows you is actually generated by Javascript at runtime.</p>

Body:
I am trying to scrape the following webpage:

https://www.comparis.ch/immobilien/marktplatz/details/show/16792498

When I use inspector in Chrome, I can see the coordinates in the following html snippet:

However, when I use BeautifulSoup to scrape the webpage, I cannot see this content anymore? Why is that? I use the following code to scrape it:

url = "https://www.comparis.ch/immobilien/marktplatz/details/show/16792498"
r = requests.get(url)
soup = BeautifulSoup(r.text)

Even before extracting it, I cannot see the coordinates anymore.


问:
dataset and UDFs using sapply
I have a dataset (employee) created from a csv, that displays data as given below;

```<code>employee[1,]

age name designation
28 Tony Manager
</code>```

I have created a function that returns a decision based on an input parameter;

```<code>   loan_eligible_decision <- function(p)
{
  if(p$designation == "manager")
  {
    decision <- "yes"
  }
  return(decision)
}
</code>```

when the function is called directly it works fine and gives the result below;

```<code>loan_eligible_decision(employee[1,])

gives me output: yes
</code>```

However when called within an sapply family it throws a reference error;

```<code>sapply(data.frame(employee[1,]),loan_eligible_decision(x))

Error in p$marital : $ operator is invalid for atomic vectors
</code>```

Any suggestions as to what could be a possible workaround/solution?

I have also tried replacing the if condition with;

```<code>if(p[[designation]] == "manager")
</code>```

and called upon the function like so;

```<code>sapply(employee['1',],loan_eligible_decision(x))

The error:
Error in loan_eligible_decision(x) : object 'designation' not found
</code>```

答:
You are calling the function incorrectly. It should be

```<code>myfun <- function(x) x^2

sapply(xy, FUN = myfun)
</code>```

In any case, try inserting a browser() call within the function and inspect what is going on. See ?browser for more info.

```<code>myfun <- function(x) {
  browser()
  x^2
}
</code>```

Title: dataset and UDFs using sapply

Body:
I have a dataset (employee) created from a csv, that displays data as given below;

employee[1,]

age name designation
28 Tony Manager

I have created a function that returns a decision based on an input parameter;

   loan_eligible_decision <- function(p)
{
  if(p$designation == "manager")
  {
    decision <- "yes"
  }
  return(decision)
}

when the function is called directly it works fine and gives the result below;

loan_eligible_decision(employee[1,])

gives me output: yes

However when called within an sapply family it throws a reference error;

sapply(data.frame(employee[1,]),loan_eligible_decision(x))

Error in p$marital : $ operator is invalid for atomic vectors

Any suggestions as to what could be a possible workaround/solution?

I have also tried replacing the if condition with;

if(p[[designation]] == "manager")

and called upon the function like so;

sapply(employee['1',],loan_eligible_decision(x))

The error:
Error in loan_eligible_decision(x) : object 'designation' not found

Body:
You are calling the function incorrectly. It should be

myfun <- function(x) x^2

sapply(xy, FUN = myfun)

In any case, try inserting a browser() call within the function and inspect what is going on. See ?browser for more info.

myfun <- function(x) {
  browser()
  x^2
}


问:
BeautifulSoup: Extracting figures and captions from JATS XML
I would like to get the images and it's descriptions from JATS XML. In my example I use http://journal.frontiersin.org/article/10.3389/fpls.2011.00008/xml/nlm

The figures are formatted like this:

```<code><fig id="F1" position="float">
<label>Figure 1</label>
<caption><p><bold>Pathways of DSB misrepair...</p></caption>
<graphic xlink:href="fpls-02-00008-g001.tif"/>
</fig>
</code>```

I would like to get both the contents of
...
 and <graphic xlink:href="..."/> of every figure.

So my idea was to use the css selectors of BeautifoulSoup and strip the html tags when printing:

```<code>#!/usr/bin/python

from bs4 import BeautifulSoup
import urllib.request

content = urllib.request.urlopen('file:///tmp/fpls-02-00008.xml').read()
soup = BeautifulSoup(content, 'xml')

##<fig><caption>XXX</caption></fig>
caption = soup.select("fig caption")

##<fig><graphic xlink:href="YYY"/></fig>
graphic = soup.select("fig graphic")

for a in caption:
    print(a.get_text().strip())

#print(b.get_text()) doesn't work
for b in graphic:
    print(b)

#separator = "|"
#print(separator.join([caption, graphic]))
</code>```

Getting just the captions or just the graphics works, but because of inconsistencies in the sources I need get it both at once. The result should not be

caption A

caption B

graphic A

graphic B

but rather

caption A, graphic A

caption B, graphic B

How do I achieve this? Thanks in advance!

答:
You can loop through two lists at once with zip:</p>

```<code>>>> A = [1,2,3,4,5]
>>> B = ['A','B','C','D','E']
>>> for number,letter in zip(A,B):
...     print number,letter
...
1 A
2 B
3 C
4 D
5 E
>>>
</code>```

Body:
I would like to get the images and it's descriptions from JATS XML. In my example I use http://journal.frontiersin.org/article/10.3389/fpls.2011.00008/xml/nlm

The figures are formatted like this:

<fig id="F1" position="float">
Figure 1

<bold>Pathways of DSB misrepair...

<graphic xlink:href="fpls-02-00008-g001.tif"/>
</fig>

I would like to get both the contents of
...
 and <graphic xlink:href="..."/> of every figure.

So my idea was to use the css selectors of BeautifoulSoup and strip the html tags when printing:

#!/usr/bin/python

from bs4 import BeautifulSoup
import urllib.request

content = urllib.request.urlopen('file:///tmp/fpls-02-00008.xml').read()
soup = BeautifulSoup(content, 'xml')

##<fig>
XXX
</fig>
caption = soup.select("fig caption")

##<fig><graphic xlink:href="YYY"/></fig>
graphic = soup.select("fig graphic")

for a in caption:
    print(a.get_text().strip())

#print(b.get_text()) doesn't work
for b in graphic:
    print(b)

#separator = "|"
#print(separator.join([caption, graphic]))

Getting just the captions or just the graphics works, but because of inconsistencies in the sources I need get it both at once. The result should not be

caption A

caption B

graphic A

graphic B

but rather

caption A, graphic A

caption B, graphic B

How do I achieve this? Thanks in advance!

Body:
You can loop through two lists at once with zip:

>>> A = [1,2,3,4,5]
>>> B = ['A','B','C','D','E']
>>> for number,letter in zip(A,B):
...     print number,letter
...
1 A
2 B
3 C
4 D
5 E
>>>