问:
Return error message if input is not string
I'm trying to build an app that asks for input twice. First an integer after a string.

I want it to return an error message once the user inputs an integer for a string intended input and vice versa. I got through with returning an error message if the user inputs a string when it asks for an integer, but I'm having troubles returning an error message if the user inputs an integer when the code asks for a string.

Here's my code so far:

```<code>do {
    System.out.print("Input account number : ");
    input = s.nextLine();
}

while (!isDigit(input));
int acct = Integer.parseInt(input);

System.out.print("Input account name : ");
String name = s.nextLine();
</code>```

答:
Edit: This would allow for inputs like "34f" to be accepted. If you want to forbid [0-9], you should use regex or see if the String.contains() [0-9].

You could just check if some String can be cast to an int - and if it can't, mark that as your success condition.

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

public class Test {

    /**
     * Main.
     * @param args
     */
    public static void main(String[] args) {
        String s;

        Scanner in = new Scanner(System.in);
        System.out.print("Don't enter a number: ");
        s = in.nextLine();

        if(isInt(s)) {
            System.out.println("Seriously? That was a number.");
        } else {
            System.out.println("Not a number - thanks!");
        }

        in.close();
    }

    /**
     * Accept a String and return true if it can be parsed as an int.
     * @param s
     * @return
     */
    public static boolean isInt(String s) {
        boolean res;

        try {
            Integer.parseInt(s);
            res = true;
        } catch (NumberFormatException e) {
            res = false;
        }

        return res;
    }
}
</code>```

Body:
I'm trying to build an app that asks for input twice. First an integer after a string.

I want it to return an error message once the user inputs an integer for a string intended input and vice versa. I got through with returning an error message if the user inputs a string when it asks for an integer, but I'm having troubles returning an error message if the user inputs an integer when the code asks for a string.

Here's my code so far:

do {
    System.out.print("Input account number : ");
    input = s.nextLine();
}

while (!isDigit(input));
int acct = Integer.parseInt(input);

System.out.print("Input account name : ");
String name = s.nextLine();

Body:
Edit: This would allow for inputs like "34f" to be accepted. If you want to forbid [0-9], you should use regex or see if the String.contains() [0-9].

You could just check if some String can be cast to an int - and if it can't, mark that as your success condition.

import java.util.Scanner;

public class Test {

    /**
     * Main.
     * @param args
     */
    public static void main(String[] args) {
        String s;

        Scanner in = new Scanner(System.in);
        System.out.print("Don't enter a number: ");
        s = in.nextLine();

        if(isInt(s)) {
            System.out.println("Seriously? That was a number.");
        } else {
            System.out.println("Not a number - thanks!");
        }

        in.close();
    }

    /**
     * Accept a String and return true if it can be parsed as an int.
     * @param s
     * @return
     */
    public static boolean isInt(String s) {
        boolean res;

        try {
            Integer.parseInt(s);
            res = true;
        } catch (NumberFormatException e) {
            res = false;
        }

        return res;
    }
}


来源: stackexchange

问:
Angular's redirectTo not updating the path in the address bar
I'm successfully redirecting according to my angular routing config:

```<code>  {
    path: 'mypath',
    redirectTo: 'myotherpath',
    pathMatch: 'full',
  },
  {
    path: 'mypath',
    children: [
        {
            path: ':id',
            component: MyComponent,
        },
    ]
  }
</code>```

When you hit 'mypath' without passing an id parameter you are redirected to 'myotherpath'. Great, that all works, but in the address bar it still displays the old address (e.g. http://localhost/mypath) even though it's loaded the 'myotherpath' page.

Is this expected behaviour? I now have a page whereby the address bar is out of sync with what's being displayed. How can I configure it so that the address bar is updated once redirected?

EDIT

To confirm - 'myotherpath' already has it's own entry for routing config, it can be navigated to directly. This is more of a redirect in case the 'mypath' is invalid (in the sense that an id hasn't been provided).

答:
"path" is just the name in the address bar,

this is want you want

{
    path: 'myotherpath',
    redirectTo: 'myotherpath',
    pathMatch: 'full',
  }```

ContentLicense: CC BY-SA 4.0

Body:
I'm successfully redirecting according to my angular routing config:

  {
    path: 'mypath',
    redirectTo: 'myotherpath',
    pathMatch: 'full',
  },
  {
    path: 'mypath',
    children: [
        {
            path: ':id',
            component: MyComponent,
        },
    ]
  }

When you hit 'mypath' without passing an id parameter you are redirected to 'myotherpath'. Great, that all works, but in the address bar it still displays the old address (e.g. http://localhost/mypath) even though it's loaded the 'myotherpath' page.

Is this expected behaviour? I now have a page whereby the address bar is out of sync with what's being displayed. How can I configure it so that the address bar is updated once redirected?

EDIT

To confirm - 'myotherpath' already has it's own entry for routing config, it can be navigated to directly. This is more of a redirect in case the 'mypath' is invalid (in the sense that an id hasn't been provided).


问:
How can I return in a ObsevableCollection<T> using C# Linq, all items if no one is selected or just selected items if at least one is selected?
I'm trying to get items in C# in an ObservableCollection<MyClassSelectable> using Linq and Lambda in the following cases :

Returns All items if no one is selected

Or

Returns just selected items if at least one is selected.

MyClassSelectable has a property named Selected of bool type.

Is it possible to do it, in only one Linq query line ?

Thank you.

答:
```<code>return new ObservableCollection<MyClassSelectable>(myCol.Any(x => x.Selected)?myCol
.Where(x => x.Selected):myCol)
</code>```


问:
How to connect my host mysql in docker container?
my.cnf configured = bind-address = 172.18.0.3(Docker Container ID)
and bind-address = 0.0.0.0 in my host.
I try connecting from docker container.

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=default
DB_USERNAME=root
DB_PASSWORD=root
</code>```

But not connecting local mysql.I get this error

SQLSTATE[HY000] [2002] Connection refused

答: If you want to connect to your local database , you call give host.docker.internal in the place where we provide database url . Then give the db you want to specify along with db username and db password.

Body:
my.cnf configured = bind-address = 172.18.0.3(Docker Container ID)
and bind-address = 0.0.0.0 in my host.
I try connecting from docker container.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=default
DB_USERNAME=root
DB_PASSWORD=root

But not connecting local mysql.I get this error

SQLSTATE[HY000] [2002] Connection refused


问:
How to sample without replacement within groups in R
I have a data frame which contains a 'year' variable with values between 1 and 100000 repeating multiple times. I have another data frame with 1000 'loss amounts' with an associated probability for each loss. I'd like to merge loss amounts onto the year data frame by sampling from the loss amounts table. I want to sample without replacement within each level of the year variable e.g. within each level of the year variable the loss amounts should be unique.

Reproducible example below where I can only get it to sample without replacement across the full 'year' dataset and not just within the different levels of the year variable as required. Is there a way of doing this (ideally without using loops as I need the code to run quickly)

```<code>#mean frequency
freq <- 100
years <- 100000

#create data frame with number of losses in each year
num_losses <- rpois(years, freq)
year <- tibble(index=1:length(num_losses), num=num_losses)
year <- map2(year$index, year$num, function(x, y) rep(x, y)) %>% unlist() %>% tibble(year = .)

#lookup table with loss amounts
lookup <- tibble(prob = runif(1000, 0, 1), amount = rgamma(1000, shape = 1.688, scale = 700000)) %>%
  mutate(total_prob = cumsum(prob)/sum(prob),
         pdf = total_prob - lag(total_prob),
         pdf = ifelse(is.na(pdf), total_prob, pdf))

#add on amounts to year table by sampling from lookup table
sample_from_lookup <- function(number){
  amount <- sample(lookup$amount, number, replace = FALSE, prob = lookup$pdf)
}

amounts <- sample_from_lookup(nrow(year))
year <- tibble(year = year$year, amount = amounts)

</code>```

答:
According to your description, maybe you can try replicate within your sample_from_lookup, i.e.,

```<code>sample_from_lookup <- function(number){
  amount <- replicate(number,
                      sample(lookup$amount,
                             1,
                             replace = FALSE,
                             prob = lookup$pdf))
}
</code>```

In this case, you need to set size 1 to your sample function.

Body:
I have a data frame which contains a 'year' variable with values between 1 and 100000 repeating multiple times. I have another data frame with 1000 'loss amounts' with an associated probability for each loss. I'd like to merge loss amounts onto the year data frame by sampling from the loss amounts table. I want to sample without replacement within each level of the year variable e.g. within each level of the year variable the loss amounts should be unique.

Reproducible example below where I can only get it to sample without replacement across the full 'year' dataset and not just within the different levels of the year variable as required. Is there a way of doing this (ideally without using loops as I need the code to run quickly)

#mean frequency
freq <- 100
years <- 100000

#create data frame with number of losses in each year
num_losses <- rpois(years, freq)
year <- tibble(index=1:length(num_losses), num=num_losses)
year <- map2(year$index, year$num, function(x, y) rep(x, y)) %>% unlist() %>% tibble(year = .)

#lookup table with loss amounts
lookup <- tibble(prob = runif(1000, 0, 1), amount = rgamma(1000, shape = 1.688, scale = 700000)) %>%
  mutate(total_prob = cumsum(prob)/sum(prob),
         pdf = total_prob - lag(total_prob),
         pdf = ifelse(is.na(pdf), total_prob, pdf))

#add on amounts to year table by sampling from lookup table
sample_from_lookup <- function(number){
  amount <- sample(lookup$amount, number, replace = FALSE, prob = lookup$pdf)
}

amounts <- sample_from_lookup(nrow(year))
year <- tibble(year = year$year, amount = amounts)

Body:
According to your description, maybe you can try replicate within your sample_from_lookup, i.e.,

sample_from_lookup <- function(number){
  amount <- replicate(number,
                      sample(lookup$amount,
                             1,
                             replace = FALSE,
                             prob = lookup$pdf))
}

In this case, you need to set size 1 to your sample function.


问:
Append param to current URL with view helper in Zend
In my layout-script I wish to create a link, appending [?|&]lang=en to the current url, using the url view helper. So, I want this to happen:

http://localhost/user/edit/1 => http://localhost/user/edit/1?lang=en

  http://localhost/index?page=2 => http://localhost/index?page=2&lang=en

I have tried the solution suggested Zend Framework: Append query strings to current page url, accessing the router directly, but that does work.

My layout-script contains:

```<code><a href="<?=$this->escape( $this->url( array('lang'=>'en')) )?>">English</a>
</code>```

If the default route is used, it will append /lang/en, but when another route is used, nothing is appended at all.

So, is there any way to do this with in Zend without me having to parse the url?

Edit

Sorry for my faulty explanation. No, I haven't made a custom router. I have just added other routes. My bad. One route that doesn't work is:

```<code>$Routes = array(
    'user' => array(
        'route' => 'admin/user/:mode/:id',
        'defaults' => array('controller' => 'admin', 'action' => 'user', 'mode'=>'', 'id' => 0)
    )
);

foreach( $Routes as $k=>$v ) {
    $route = new Zend_Controller_Router_Route($v['route'], $v['defaults']);
    $router->addRoute($k, $route);
}
</code>```

答:
Upd:

You must add wildcard to your route or define 'lang' parameter explicitly.

```<code>'admin/user/:mode/:id/*'
</code>```

Additionally, according to your comment, you can do something like this:

```<code>class controllerplugin extends Zend_Controller_Plugin_Abstract
{
    function routeShutdown($request)
    {
        if($request->getParam('lang', false) {
            //store lang
            Zend_Controller_Front::getInstance()->getRouter()->setGlobalParam('lang', NULL); //check if this will remove lang from wildcard parameters, have no working zf installation here to check.
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my layout-script I wish to create a link, appending [?|&]lang=en to the current url, using the url view helper. So, I want this to happen:

http://localhost/user/edit/1 => http://localhost/user/edit/1?lang=en

  http://localhost/index?page=2 => http://localhost/index?page=2&lang=en

I have tried the solution suggested Zend Framework: Append query strings to current page url, accessing the router directly, but that does work.

My layout-script contains:

<a href="<?=$this->escape( $this->url( array('lang'=>'en')) )?>">English

If the default route is used, it will append /lang/en, but when another route is used, nothing is appended at all.

So, is there any way to do this with in Zend without me having to parse the url?

Edit

Sorry for my faulty explanation. No, I haven't made a custom router. I have just added other routes. My bad. One route that doesn't work is:

$Routes = array(
    'user' => array(
        'route' => 'admin/user/:mode/:id',
        'defaults' => array('controller' => 'admin', 'action' => 'user', 'mode'=>'', 'id' => 0)
    )
);

foreach( $Routes as $k=>$v ) {
    $route = new Zend_Controller_Router_Route($v['route'], $v['defaults']);
    $router->addRoute($k, $route);
}

Body:
Upd:

You must add wildcard to your route or define 'lang' parameter explicitly.

'admin/user/:mode/:id/*'

Additionally, according to your comment, you can do something like this:

class controllerplugin extends Zend_Controller_Plugin_Abstract
{
    function routeShutdown($request)
    {
        if($request->getParam('lang', false) {
            //store lang
            Zend_Controller_Front::getInstance()->getRouter()->setGlobalParam('lang', NULL); //check if this will remove lang from wildcard parameters, have no working zf installation here to check.
        }
    }
}


问:
ArangoDB crashes on attempt to run traversal AQL with COLLECT clause in it
Data model is:

books - documents

pages - documents. Page may contain a only one references to another book

books_pages - edges. From book to page and from page to book

Example:

```<code>book1 -> (edge) -> page1 -> (edge) -> book2
book1 -> (edge) -> page2 -> (edge) -> book2
book1 -> (edge) -> page3 -> (edge) -> book2
book1 -> (edge) -> page4 -> (edge) -> book3
book2 -> (edge) -> page5 -> (edge) -> book4
book2 -> (edge) -> page6 -> (edge) -> book4
book2 -> (edge) -> page7 -> (edge) -> book4
book2 -> (edge) -> page6 -> (edge) -> book4
...
</code>```

The goal is to build edges between books avoiding duplication. book1 contains several pages that mention book2, but I need only one edge. Id doesn't matter how many times book2 was referenced in book1.

AQL:

```<code>FOR b1 IN books
    FOR v IN 1..1 OUTBOUND b1 books_pages
       FOR b2 IN 1..1 OUTBOUND v books_pages
       COLLECT  from = b1._id, to = b2._id
  RETURN {'from':from, 'to': to}
</code>```

When number of documents in a database is significant arangodb crashes. Is something wrong with this query or this is just a bug on arangodb side?

答:
I cannot comment on the crash, not least of all reasons because you don't give any information pertaining to it and how it manifests itself -- if the reason is an out-of-memory kill/restart, you should mention that (check the system logs if the arangodb log is not helpful).

But concerning your Problem: Aren't you interested in all unique Paths of length 3 (in terms of vertices, 2 in terms of edges)? Doesn't that condense to

```<code>FOR b IN books
   FOR v,e,p IN 2..2 OUTBOUND b GRAPH 'books'
      RETURN DISTINCT {"from": p.vertices[0]._id, "to": p.vertices[2]._id}
</code>```

It works for a very small sample set.  Maybe this is a bit lighter on the query-planer, executioner?

Body:
Data model is:

books - documents

pages - documents. Page may contain a only one references to another book

books_pages - edges. From book to page and from page to book

Example:

book1 -> (edge) -> page1 -> (edge) -> book2
book1 -> (edge) -> page2 -> (edge) -> book2
book1 -> (edge) -> page3 -> (edge) -> book2
book1 -> (edge) -> page4 -> (edge) -> book3
book2 -> (edge) -> page5 -> (edge) -> book4
book2 -> (edge) -> page6 -> (edge) -> book4
book2 -> (edge) -> page7 -> (edge) -> book4
book2 -> (edge) -> page6 -> (edge) -> book4
...

The goal is to build edges between books avoiding duplication. book1 contains several pages that mention book2, but I need only one edge. Id doesn't matter how many times book2 was referenced in book1.

AQL:

FOR b1 IN books
    FOR v IN 1..1 OUTBOUND b1 books_pages
       FOR b2 IN 1..1 OUTBOUND v books_pages
       COLLECT  from = b1._id, to = b2._id
  RETURN {'from':from, 'to': to}

When number of documents in a database is significant arangodb crashes. Is something wrong with this query or this is just a bug on arangodb side?

Body:
I cannot comment on the crash, not least of all reasons because you don't give any information pertaining to it and how it manifests itself -- if the reason is an out-of-memory kill/restart, you should mention that (check the system logs if the arangodb log is not helpful).

But concerning your Problem: Aren't you interested in all unique Paths of length 3 (in terms of vertices, 2 in terms of edges)? Doesn't that condense to

FOR b IN books
   FOR v,e,p IN 2..2 OUTBOUND b GRAPH 'books'
      RETURN DISTINCT {"from": p.vertices[0]._id, "to": p.vertices[2]._id}

It works for a very small sample set.  Maybe this is a bit lighter on the query-planer, executioner?


问:
ArrayList for show products not work secondly
i have two intent city and product.first app open city intent show and user select city . now city pass to product intent for show products.
I use array list for fetching data from php api and show to user in product intent:

```<code> ArrayList<HashMap<String,String>> getDatalist;
 StringRequest stringRequest = new StringRequest(Request.Method.GET, jsonUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            obj = new JSONObject(response);
                            prdArray = obj.getJSONArray("prd");
                            for(int aind = 0 ; aind < 2; aind++) {
                                final JSONObject do_id = prdArray.getJSONObject(aind);
                                String email = do_id.getString("email");
                                String phone = do_id.getString("phone");

                                HashMap<String,String> map = new HashMap<>();
                                map.put("KEY_EMAIL",email);
                                map.put("KEY_PHONE",phone);
                                getDatalist.add(map);

                                Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_SHORT).show();
                            }
                        }catch (JSONException e) {
                             Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
</code>```

anything is OK now.Nut i have a bottom for change city when user click it . city Intent show and after city changed he coma back to product intent.but now products not show :(

```<code>    Button cityChange=(Button)findViewById(R.id.cityChange);
    cityChange.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent cityChangeIntent = new Intent(home.this,city.class);
            cityChangeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
            Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(cityChangeIntent);
            finish();
        }
    });
</code>```

Recycleviewadapter:

```<code>  public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element

    if (holder instanceof ViewHolderRow) {
        HashMap<String,String> map = mDataset.get(position);

        ViewHolderRow userViewHolder = (ViewHolderRow) holder;

        userViewHolder.txtEmail.setText(map.get("KEY_EMAIL"));
        userViewHolder.txtPhone.setText(map.get("KEY_PHONE"));

       .....
</code>```

答:
Use for loop like this </p>

```<code>for(int aind = 0 ; aind < prdArray.size; aind++) {
 //your code
}
</code>```

Body:
i have two intent city and product.first app open city intent show and user select city . now city pass to product intent for show products.
I use array list for fetching data from php api and show to user in product intent:

 ArrayList<HashMap<String,String>> getDatalist;
 StringRequest stringRequest = new StringRequest(Request.Method.GET, jsonUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            obj = new JSONObject(response);
                            prdArray = obj.getJSONArray("prd");
                            for(int aind = 0 ; aind < 2; aind++) {
                                final JSONObject do_id = prdArray.getJSONObject(aind);
                                String email = do_id.getString("email");
                                String phone = do_id.getString("phone");

                                HashMap<String,String> map = new HashMap<>();
                                map.put("KEY_EMAIL",email);
                                map.put("KEY_PHONE",phone);
                                getDatalist.add(map);

                                Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_SHORT).show();
                            }
                        }catch (JSONException e) {
                             Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
                        }

anything is OK now.Nut i have a bottom for change city when user click it . city Intent show and after city changed he coma back to product intent.but now products not show :(

    Button cityChange=(Button)findViewById(R.id.cityChange);
    cityChange.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent cityChangeIntent = new Intent(home.this,city.class);
            cityChangeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
            Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(cityChangeIntent);
            finish();
        }
    });

Recycleviewadapter:

  public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element

    if (holder instanceof ViewHolderRow) {
        HashMap<String,String> map = mDataset.get(position);

        ViewHolderRow userViewHolder = (ViewHolderRow) holder;

        userViewHolder.txtEmail.setText(map.get("KEY_EMAIL"));
        userViewHolder.txtPhone.setText(map.get("KEY_PHONE"));

       .....

Body:
Use for loop like this

for(int aind = 0 ; aind < prdArray.size; aind++) {
 //your code
}


问:
TeamCity BuildAgent does not see the network drive
I want to copy the file to a network drive using build agent (powershell or cmd (Build Steps)).

```<code>P:
# or
cd P:\foolder\
# ...
</code>```

But the commands don't work. Build log: "Disk P not found".
The disk is connected via windows. When running from windows, the commands work.
I assume java/BuildAgent doesn't have rights. But my user has rights. And java, and BuildAgent runs under my user.

Please, do not offer FTP

答:
Open command prompt as Administrator

bind your drive again using below command

```<code>net use x: \\10.1.2.3\Share
</code>```

again do the same in Command prompt without administrator (if its not bounded)

Body:
I want to copy the file to a network drive using build agent (powershell or cmd (Build Steps)).

P:
# or
cd P:\foolder\
# ...

But the commands don't work. Build log: "Disk P not found".
The disk is connected via windows. When running from windows, the commands work.
I assume java/BuildAgent doesn't have rights. But my user has rights. And java, and BuildAgent runs under my user.

Please, do not offer FTP

Body:
Open command prompt as Administrator

bind your drive again using below command

net use x: \\10.1.2.3\Share

again do the same in Command prompt without administrator (if its not bounded)


问:
How to fetch hierarchy data with dynamic changes
I have emp table like as follows:

```<code>Empname              Mgr_hierarchy
-------    ---------------------------------
arjun      Giri    | Raj    | Suresh
arun       arjun   | Giri   | Raj    | Suresh
alex       Pandey  | Ravi   | Suresh
adam       alex    | Pandey | Ravi   | Suresh
bux        alex    | Pandey | Ravi   | Suresh
bony       Agarwal | Ram    | Nitesh | Suresh
</code>```

A manager table as like follows:

```<code>Mgr_names
----------
Raj
Ram
Ravi
</code>```

I want to fetch the all the employee details who are have the listed managers in their hierarchy,

I have use the following code for that

```<code>    select empname from `project.dataset.emp`
 where
(mgr_hierarchy like '%Raj%' or mgr_hierarchy like '%Ravi%' or mgr_hierarchy like '%Ram%')
</code>```

But the problem is the manager table is dynamically changing; as of now it contains 3 values after one month these managers are replaced with another 3 or 4 values. So every time I am changing the condition. Are there any solutions for this?

答:
Use split() and unnest():

```<code>select e.*
from emp e cross join
     (unnest(split(e.Mgr_hierarchy, ' | '))) as mgr join
     manager m
     on m.mgr_name = mgr;
</code>```

I would recommend that you fix your data structure.  Encoding hierarchies as fixed strings is quite painful.  At the very least you could be using arrays.

Body:
I have emp table like as follows:

Empname              Mgr_hierarchy
-------    ---------------------------------
arjun      Giri    | Raj    | Suresh
arun       arjun   | Giri   | Raj    | Suresh
alex       Pandey  | Ravi   | Suresh
adam       alex    | Pandey | Ravi   | Suresh
bux        alex    | Pandey | Ravi   | Suresh
bony       Agarwal | Ram    | Nitesh | Suresh

A manager table as like follows:

Mgr_names
----------
Raj
Ram
Ravi

I want to fetch the all the employee details who are have the listed managers in their hierarchy,

I have use the following code for that

    select empname from `project.dataset.emp`
 where
(mgr_hierarchy like '%Raj%' or mgr_hierarchy like '%Ravi%' or mgr_hierarchy like '%Ram%')

But the problem is the manager table is dynamically changing; as of now it contains 3 values after one month these managers are replaced with another 3 or 4 values. So every time I am changing the condition. Are there any solutions for this?

Body:
Use split() and unnest():

select e.*
from emp e cross join
     (unnest(split(e.Mgr_hierarchy, ' | '))) as mgr join
     manager m
     on m.mgr_name = mgr;

I would recommend that you fix your data structure.  Encoding hierarchies as fixed strings is quite painful.  At the very least you could be using arrays.


问:
"128-bit floating-point types are not supported in this configuration" error when including any stl library in visual studio linux c++ project
so i created a c++ linux console application on my x64 bit win 10 pro 10.0.17134 with wsl.

the project compiles no problem, without showing any errors. and debugging basic variable assignments works as expected;

then when i try to include any stl library e.g. #include <iostream> i get the following errors

128-bit floating-point types are not supported in this configuration

i am using Debug configuration with x64 bit mode.
i also tried googling the error, but i can't seem to find any related answer

i also tried using different c++ versions (c++17,c++11,etc...) but i still get the same error.

but even though i get these compilation errors, the program still runs correctly.

答:
If it does not conflict with the rest of your code, you can set
__CUDACC__
 in
Project Properties | Configuration Properties > C/C++ > IntelliSense | Preprocessor Definitions

This is if you are using GCC headers. The switch may be different for other sources.


问:
Multi Row insert Query in Oracle (selecting multiple rows from one table & insert in to other table
Dear StackOverflow Community,

i have two tables users and USERQueries

   ]

My requirement is  to write a query in oracle

 "which fetch userids from users table & insert into USERQueries table"

I am able to insert one userid as below

```<code> insert into  USERSQUERIES
(APP,CLAUSENAME,USERID,DEFAULTQUERYID,OWNER)
values
('SR','Assgined_SRs_To_Me',(select userid from USERS where  groupname='IBMSDL2S' and userid='1249
),DEFAULTQUERYSEQ.NEXTVAL,'MAXADMIN')
</code>```

but didn't understand how it will work for all userids ,

 and userids shouldnt repeat.

kindly help

答:
That depends on tables' description, but - generally speaking, you'd </p>

```<code>insert into userqueries
  (app,
   clausename,
   userid)
select app,
       clausename,
       userid
from users
where ...
</code>```

Body:
Dear StackOverflow Community,

i have two tables users and USERQueries

   ]

My requirement is  to write a query in oracle

 "which fetch userids from users table & insert into USERQueries table"

I am able to insert one userid as below

 insert into  USERSQUERIES
(APP,CLAUSENAME,USERID,DEFAULTQUERYID,OWNER)
values
('SR','Assgined_SRs_To_Me',(select userid from USERS where  groupname='IBMSDL2S' and userid='1249
),DEFAULTQUERYSEQ.NEXTVAL,'MAXADMIN')

but didn't understand how it will work for all userids ,

 and userids shouldnt repeat.

kindly help

Body:
That depends on tables' description, but - generally speaking, you'd

insert into userqueries
  (app,
   clausename,
   userid)
select app,
       clausename,
       userid
from users
where ...


问:
Same-origin policy blocking API request on remote
The "on remote" section is why I am confused on this. I am trying to do a POST request to https://api.smarkets.com/v3/sessions. The route is to create a session token for subsequent requests to the API.

If I do this request on my local machine, it works fine. I get a 2xx response. However, if I try on a remote machine (DO box I spun up last night), I get a '503 Service Temporarily Unavailable' response.

I attempted to login via the browser & I got the same response. I raised this question to Smarkets & they eluded to the fact it might be due to the same-origin policy imposed by Smarkets.

After some time, I managed to login via Chrome by disabling the same-origin policy. The API request still failed.

From my limited knowledge of the same-origin policy (please correct me if I'm wrong), it specifies what resources are allowed to be returned from certain origins. Similar to CORS issues. Why would I have to explicitly disable web security on a remote browser to get it to login to smarkets.com but my browser on my local machine can login just fine without being modified?

The question I highlighted above shows what methods I have tried to get this to work. No matter what request headers I attempt to set, the response headers are always the same with X-Frame-Options response header always set to SAMEORIGIN which, again from what I understand, only allows resources to be sent to the same origin of the sender. I.e. resources sent from smarkets.com can only be accessed by requests from smarkets.com.

My current request attempt is (with httpie):

```<code>http POST https://api.smarkets.com/v3/sessions/ 'Access-Control-Request-Headers: Content-Type, Accept, Host, Origin' 'Access-Control-Request-Methods: POST, OPTIONS' 'Origin: https://smarkets.com' username=<username> password=<password> --print=Hh
</code>```

The request & response headers are:

I'm really looking for;

Clarity on what the same-origin policy is imposing

Why does this request succeed on my local machine but not a remote DO box

How can I get this request to succeed?

The user at Smarkets seems like this is a same-origin issue but it might not be.

EDIT:

It's not a firewall issue as I disabled Ubuntu's built-in firewall. I am doing other requests over http(s) from the same origin so I can't figure out what is different about this one

EDIT 2:

Below is an example of successful request/response headers:

I'm able to make other API calls from the same box to different origins, including:

https://api.betdaq.com

https://api.betfair.com

https://api.matchbook.com

I have added no configurations specifically around any origins on the box so am really unsure as to what this issue is. I have added all the possible CORS request headers that I can think of & still no luck.

EDIT 3:

Annoyingly, this has been fixed now as the vendors API blacklists DigitalOcean IPs by default...

答:
Cors is both a server and a client thing. The servers defines the policiy, a client COULD enforce it. Browsers, for example, do enforce it because it is more safe (not going into the detail here). Therefore disabling same-origin policy in you browser or using an untrusted browser is a security issue.

Again, the client COULD enforce the policy. As far as I know most commandline http clients do not enforce it. That could explain why your httpie request does not fail.

From a browser perspective, you cannot resolve the problem. Again, it is the server that defines the policy. What you can do is create a proxy server. You van specify your own cors policy. The brower makes request to your proxyserver. Your proxyserver passes the reqeust to the actual server.

Body:
The "on remote" section is why I am confused on this. I am trying to do a POST request to https://api.smarkets.com/v3/sessions. The route is to create a session token for subsequent requests to the API.

If I do this request on my local machine, it works fine. I get a 2xx response. However, if I try on a remote machine (DO box I spun up last night), I get a '503 Service Temporarily Unavailable' response.

I attempted to login via the browser & I got the same response. I raised this question to Smarkets & they eluded to the fact it might be due to the same-origin policy imposed by Smarkets.

After some time, I managed to login via Chrome by disabling the same-origin policy. The API request still failed.

From my limited knowledge of the same-origin policy (please correct me if I'm wrong), it specifies what resources are allowed to be returned from certain origins. Similar to CORS issues. Why would I have to explicitly disable web security on a remote browser to get it to login to smarkets.com but my browser on my local machine can login just fine without being modified?

The question I highlighted above shows what methods I have tried to get this to work. No matter what request headers I attempt to set, the response headers are always the same with X-Frame-Options response header always set to SAMEORIGIN which, again from what I understand, only allows resources to be sent to the same origin of the sender. I.e. resources sent from smarkets.com can only be accessed by requests from smarkets.com.

My current request attempt is (with httpie):

http POST https://api.smarkets.com/v3/sessions/ 'Access-Control-Request-Headers: Content-Type, Accept, Host, Origin' 'Access-Control-Request-Methods: POST, OPTIONS' 'Origin: https://smarkets.com' username=<username> password=<password> --print=Hh

The request & response headers are:

I'm really looking for;

Clarity on what the same-origin policy is imposing

Why does this request succeed on my local machine but not a remote DO box

How can I get this request to succeed?

The user at Smarkets seems like this is a same-origin issue but it might not be.

EDIT:

It's not a firewall issue as I disabled Ubuntu's built-in firewall. I am doing other requests over http(s) from the same origin so I can't figure out what is different about this one

EDIT 2:

Below is an example of successful request/response headers:

I'm able to make other API calls from the same box to different origins, including:

https://api.betdaq.com

https://api.betfair.com

https://api.matchbook.com

I have added no configurations specifically around any origins on the box so am really unsure as to what this issue is. I have added all the possible CORS request headers that I can think of & still no luck.

EDIT 3:

Annoyingly, this has been fixed now as the vendors API blacklists DigitalOcean IPs by default...


问:
Updating an already existing spacy NER model
I want to update and already existing spacy model 'en_core_web_sm' and train it with additional data.

My data is in the same format as mentioned in spacy's documentation
https://spacy.io/usage/training

I've followed the same steps as mentioned in the documentation for updating an NER model with my data.

```<code>def model_train(output_dir=None, n_iter=100):
    """Load the model, set up the pipeline and train the entity recognizer."""
    model=('en_core_web_sm')
    nlp = spacy.load(model, entity = False, parser = False)  # load existing spaCy model
    print("Loaded model '%s'" % model)
    print (nlp.pipe_names)

#     # create the built-in pipeline components and add them to the pipeline

    ner = nlp.get_pipe("ner")

#     # add labels
    for texts, annotations in TRAIN_DATA:
        for ent in annotations.get("entities"):
#             print (ent)
            ner.add_label(ent[2])
#             print (ent[2])

    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
    with nlp.disable_pipes(*other_pipes):  # only train NER

        if model is None:
            nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
#             # batch up the examples using spaCy's minibatch
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(
                    [texts],  # batch of texts
                    [annotations],  # batch of annotations
                    drop=0.5,  # dropout - make it harder to memorise data
                    losses=losses,
                )
            print("Losses", losses)

        nlp.to_disk(output_dir)
        print("Saved model to", output_dir)
</code>```

The error that I'm getting is

```<code>Loaded model 'en_core_web_sm'
['tagger', 'parser', 'ner']
-------------------------------------------------------------------------
</code>```

-
    TypeError                                 Traceback (most recent call last)
     in
    ----> 1 model_train()

```<code><ipython-input-337-91366511ed4d> in model_train(output_dir, n_iter)
     56                     [annotations],  # batch of annotations
     57                     drop=0.5,  # dropout - make it harder to
memorise data
---> 58                     losses=losses,
     59                 )
     60             print("Losses", losses)

C:\ProgramData\Anaconda3\lib\site-packages\spacy\language.py in
update(self, docs, golds, drop, sgd, losses, component_cfg)
    432                 doc = self.make_doc(doc)
    433             if not isinstance(gold, GoldParse):
--> 434                 gold = GoldParse(doc, **gold)
    435             doc_objs.append(doc)
    436             gold_objs.append(gold)

TypeError: type object argument after ** must be a mapping, not tuple
</code>```

答:
zip() already sending list of texts and annotation

nlp.update(
                    texts,  # batch of texts
                    annotations,  # batch of annotations
                    drop=0.5,  # dropout - make it harder to memorise data
                    losses=losses,
                )
```

Click here

Body:
I want to update and already existing spacy model 'en_core_web_sm' and train it with additional data.

My data is in the same format as mentioned in spacy's documentation
https://spacy.io/usage/training

I've followed the same steps as mentioned in the documentation for updating an NER model with my data.

def model_train(output_dir=None, n_iter=100):
    """Load the model, set up the pipeline and train the entity recognizer."""
    model=('en_core_web_sm')
    nlp = spacy.load(model, entity = False, parser = False)  # load existing spaCy model
    print("Loaded model '%s'" % model)
    print (nlp.pipe_names)

#     # create the built-in pipeline components and add them to the pipeline

    ner = nlp.get_pipe("ner")

#     # add labels
    for texts, annotations in TRAIN_DATA:
        for ent in annotations.get("entities"):
#             print (ent)
            ner.add_label(ent[2])
#             print (ent[2])

    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
    with nlp.disable_pipes(*other_pipes):  # only train NER

        if model is None:
            nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
#             # batch up the examples using spaCy's minibatch
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(
                    [texts],  # batch of texts
                    [annotations],  # batch of annotations
                    drop=0.5,  # dropout - make it harder to memorise data
                    losses=losses,
                )
            print("Losses", losses)

        nlp.to_disk(output_dir)
        print("Saved model to", output_dir)

The error that I'm getting is

Loaded model 'en_core_web_sm'
['tagger', 'parser', 'ner']
-------------------------------------------------------------------------

-
    TypeError                                 Traceback (most recent call last)
     in
    ----> 1 model_train()

<ipython-input-337-91366511ed4d> in model_train(output_dir, n_iter)
     56                     [annotations],  # batch of annotations
     57                     drop=0.5,  # dropout - make it harder to
memorise data
---> 58                     losses=losses,
     59                 )
     60             print("Losses", losses)

C:\ProgramData\Anaconda3\lib\site-packages\spacy\language.py in
update(self, docs, golds, drop, sgd, losses, component_cfg)
    432                 doc = self.make_doc(doc)
    433             if not isinstance(gold, GoldParse):
--> 434                 gold = GoldParse(doc, **gold)
    435             doc_objs.append(doc)
    436             gold_objs.append(gold)

TypeError: type object argument after ** must be a mapping, not tuple

Body:
zip() already sending list of texts and annotation

nlp.update(
                    texts,  # batch of texts
                    annotations,  # batch of annotations
                    drop=0.5,  # dropout - make it harder to memorise data
                    losses=losses,
                )

Click here


问:
Git commit opens blank text file, for what?
In all the Git tutorials I've read they say that you can do:

```<code>git init
git add .
git commit
</code>```

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

答:
Yeah, make sure you have a sensible editor set.  Not sure what your default editor will be but if, like me, it is nano (it will say so somewhere near the top after you type commit) you just need to type in a comment and then hit Ctrl-X to finish.  Then hit y, followed by enter to affirm the commit.

Also, if you want to see a simple list of the files you'll be committing rather than a huge diff listing beforehand try

git diff --name-only
```

OwnerDisplayName: Alex

LastEditorDisplayName: Baishampayan Ghose

Body:
In all the Git tutorials I've read they say that you can do:

git init
git add .
git commit

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

OwnerDisplayName: Tom Martin


问:
SharePoint List Item Not Returning Fields
Hi I have a question about SPListItem and how to retrieve values from it.  In the view I am in I can access the "Article" no problem but when I try to access the "Link" I can an error saying object not initalized.  I don't understand whats going on?  Why can I not get the Link when I can get the Article field.  Here is the code I am using:

```<code>SPList myList = eachWeb.Lists["Listings"];
SPListItemCollection myItemCollection = myList.GetItems(myList.Views["Active Announcements"]);
for (int i = 0; i < myItemCollection.Count; i++)
{
SPListItem realitem = myItemCollection[i];
writer.Write(realitem["Article"].ToString()+"<BR>"); // Works without the bottom line
writer.Write(realitem["Link"].ToString()+"<BR>");  // Causes error
</code>```

My view contains a column for both Article and Link.  Thank you.

答: The internal name of a field may not match the display name; especially if you've changed the name after creating the list. Try debugging and taking a look at the names of the fields in the SPListItemCollection and see if you can figure out which one it is there.

OwnerDisplayName: Oliver S

ContentLicense: CC BY-SA 2.5

Body:
Hi I have a question about SPListItem and how to retrieve values from it.  In the view I am in I can access the "Article" no problem but when I try to access the "Link" I can an error saying object not initalized.  I don't understand whats going on?  Why can I not get the Link when I can get the Article field.  Here is the code I am using:

SPList myList = eachWeb.Lists["Listings"];
SPListItemCollection myItemCollection = myList.GetItems(myList.Views["Active Announcements"]);
for (int i = 0; i < myItemCollection.Count; i++)
{
SPListItem realitem = myItemCollection[i];
writer.Write(realitem["Article"].ToString()+"
"); // Works without the bottom line
writer.Write(realitem["Link"].ToString()+"
");  // Causes error

My view contains a column for both Article and Link.  Thank you.

OwnerDisplayName: Andy Mikula


问:
jQuery Show/Hide Div when Section is in Viewport
My code at the moment is here: http://www.jaygeorge.co.uk/gwennan-sage

You'll see two green arrows that are in a fixed position at the bottom of the page.
I'm having trouble getting jQuery to hide these divs (#timeline-buttons) when the Timeline section is NOT in view, preferably using the fade() technique.

I've tried a Viewport plugin but can't get it to work properly with if statements, I'm sure it can be done with normal jQuery by measuring div heights somehow.

Any advice appreciated, thanks in advance.

答:
Hide the green arrows and then onscrolling, test to see if the timeline div position is greater than the window height plus scrolling offset.  If greater then that means that the timeline div is in view and the arrows should be shown.

Here is a quick fiddle demonstrating the effect: http://jsfiddle.net/EADDt/


问:
VueJS csv Filereader
I'm trying to get the input of a .csv File, after I choose it with my Html 5 input field. Therefor I use a onFileChange method and a FileReader().
Here is an example I used: http://codepen.io/Atinux/pen/qOvawK/ (except that I want to read the text input, and not an image file).

My Problem is, that I get an empty input on the first try, but on the second try it works. Why is that? Any ideas? (I'm a javascript beginner ;) )

html:

```<code><form enctype="multipart/form-data">
    <input type="file" @change="onFileChange">
</form>
</code>```

js:

```<code>new Vue({
    el: '#app',
    data: {
        fileinput: ''
    },
    methods: {
        onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.createInput(files[0]);
        },
        createInput(file) {
            var reader = new FileReader();
            var vm = this;
            reader.onload = (e) => {

            vm.fileinput = reader.result;
            }
            reader.readAsText(file);

            console.log(this.fileinput);
        }

    }
})
</code>```

答:
Here you can also try as below if you want separate function after promise and define in data.</p>

```<code>    new Vue({
    el: "#app",
    data: {
        fileinput: ""
    },
    methods: {
        readFile: function(evt) {
            const scope = this
            var promiseVar = new Promise(async (resolve, reject) => {
                try {
                    var reader = new FileReader();
                    var file = evt.target.files[0];
                    reader.readAsText(file);
                    reader.onload = function(e) {
                        scope.fileinput = e.target.result
                        resolve('complete');
                    };
                } catch (error) {
                    console.error(error);
                    reject("There must be an error");
                }
            });
            // let updateds = await Promise.all(promiseVar);
            promiseVar.then(data=>{
                scope.afterRead();
            })
        },
        afterRead:function(){
            console.log(this.fileinput)
            // write your logic for import here
        }
    }
});
</code>```

Title: VueJS csv Filereader

Body:
I'm trying to get the input of a .csv File, after I choose it with my Html 5 input field. Therefor I use a onFileChange method and a FileReader().
Here is an example I used: http://codepen.io/Atinux/pen/qOvawK/ (except that I want to read the text input, and not an image file).

My Problem is, that I get an empty input on the first try, but on the second try it works. Why is that? Any ideas? (I'm a javascript beginner ;) )

html:

<form enctype="multipart/form-data">
    <input type="file" @change="onFileChange">
</form>

js:

new Vue({
    el: '#app',
    data: {
        fileinput: ''
    },
    methods: {
        onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.createInput(files[0]);
        },
        createInput(file) {
            var reader = new FileReader();
            var vm = this;
            reader.onload = (e) => {

            vm.fileinput = reader.result;
            }
            reader.readAsText(file);

            console.log(this.fileinput);
        }

    }
})

Body:
Here you can also try as below if you want separate function after promise and define in data.

    new Vue({
    el: "#app",
    data: {
        fileinput: ""
    },
    methods: {
        readFile: function(evt) {
            const scope = this
            var promiseVar = new Promise(async (resolve, reject) => {
                try {
                    var reader = new FileReader();
                    var file = evt.target.files[0];
                    reader.readAsText(file);
                    reader.onload = function(e) {
                        scope.fileinput = e.target.result
                        resolve('complete');
                    };
                } catch (error) {
                    console.error(error);
                    reject("There must be an error");
                }
            });
            // let updateds = await Promise.all(promiseVar);
            promiseVar.then(data=>{
                scope.afterRead();
            })
        },
        afterRead:function(){
            console.log(this.fileinput)
            // write your logic for import here
        }
    }
});


问:
PowerShell script to return versions of .NET Framework on a machine?
What would a PowerShell script be to return versions of the .NET Framework on a machine?

My first guess is something involving WMI. Is there something better?

It should be a one-liner to return only the latest version for each installation of .NET [on each line].

答:
Here's my take on this question following the msft documentation:

```<code>$gpParams = @{
    Path        = 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
    ErrorAction = 'SilentlyContinue'
}
$release = Get-ItemProperty @gpParams | Select-Object -ExpandProperty Release

".NET Framework$(
    switch ($release) {
        ({ $_ -ge 528040 }) { ' 4.8'; break }
        ({ $_ -ge 461808 }) { ' 4.7.2'; break }
        ({ $_ -ge 461308 }) { ' 4.7.1'; break }
        ({ $_ -ge 460798 }) { ' 4.7'; break }
        ({ $_ -ge 394802 }) { ' 4.6.2'; break }
        ({ $_ -ge 394254 }) { ' 4.6.1'; break }
        ({ $_ -ge 393295 }) { ' 4.6'; break }
        ({ $_ -ge 379893 }) { ' 4.5.2'; break }
        ({ $_ -ge 378675 }) { ' 4.5.1'; break }
        ({ $_ -ge 378389 }) { ' 4.5'; break }
        default { ': 4.5+ not installed.' }
    }
)"
</code>```

This example works with all PowerShell versions and will work in perpetuity as 4.8 is the last .NET Framework version.

Body:
Here's my take on this question following the msft documentation:

$gpParams = @{
    Path        = 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
    ErrorAction = 'SilentlyContinue'
}
$release = Get-ItemProperty @gpParams | Select-Object -ExpandProperty Release

".NET Framework$(
    switch ($release) {
        ({ $_ -ge 528040 }) { ' 4.8'; break }
        ({ $_ -ge 461808 }) { ' 4.7.2'; break }
        ({ $_ -ge 461308 }) { ' 4.7.1'; break }
        ({ $_ -ge 460798 }) { ' 4.7'; break }
        ({ $_ -ge 394802 }) { ' 4.6.2'; break }
        ({ $_ -ge 394254 }) { ' 4.6.1'; break }
        ({ $_ -ge 393295 }) { ' 4.6'; break }
        ({ $_ -ge 379893 }) { ' 4.5.2'; break }
        ({ $_ -ge 378675 }) { ' 4.5.1'; break }
        ({ $_ -ge 378389 }) { ' 4.5'; break }
        default { ': 4.5+ not installed.' }
    }
)"

This example works with all PowerShell versions and will work in perpetuity as 4.8 is the last .NET Framework version.


问:
Must be initialized error in val variable
Following code report property must be initialized or be abstract error.

```<code>// MyApi.kt
interface MyApi {

    ...
}

// MyFetch.kt
class MyFetch {

    private val myApi: MyApi  // <- this line

    ...
}
</code>```

It can use lateinit statement in mutable variable, but how should I predefined in val?

答:
You can use lazy, or make it nullable</p>

```<code>private val myApi: MyApi? = null
</code>```

Body:
Following code report property must be initialized or be abstract error.

// MyApi.kt
interface MyApi {

    ...
}

// MyFetch.kt
class MyFetch {

    private val myApi: MyApi  // <- this line

    ...
}

It can use lateinit statement in mutable variable, but how should I predefined in val?

Body:
You can use lazy, or make it nullable

private val myApi: MyApi? = null


问:
Java: overriding equals method doesn't do the trick when looking for a key of hashtable?
I have a hashtable looking like this:

```<code>Hashtable<Mapping, Integer> mappingCount = new Hashtable<Mapping, Integer>();
</code>```

I want to use this code:

```<code>if (mappingCount.get(currentMapping) != null)
    mappingCount.put(currentMapping, mappingCount.get(currentMapping) + 1);
else
    mappingCount.put(currentMapping, 1);
</code>```

In order to be able to get the value from the hashtable, for the class Mapping I did the following:

```<code>@Override
public boolean equals(Object obj) {
    return ((Mapping)obj).mappingXML.equals(this.mappingXML);
}
</code>```

However, this doesn't do the trick since mappingCount.get(currentMapping) always results in null. To be sure that something's not wrong, I did the following:

```<code>if (aaa.contains(currentMapping.getMappingXML()))
    System.out.println("found it!");
else
    aaa.add(currentMapping.getMappingXML());
</code>```

where aaa is List<String> aaa = new ArrayList<String>(). Of course, found it is printed many times. What am I doing wrong?

答:
You have to implement hashcode() as well!

Example:

```<code>public class Employee{
    int        employeeId;
    String     name;
    Department dept;

    // other methods would be in here

    @Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 17 + employeeId;
        hash = hash * 31 + name.hashCode();
        hash = hash * 13 + (dept == null ? 0 : dept.hashCode());
        return hash;
    }
}
</code>```

Body:
I have a hashtable looking like this:

Hashtable<Mapping, Integer> mappingCount = new Hashtable<Mapping, Integer>();

I want to use this code:

if (mappingCount.get(currentMapping) != null)
    mappingCount.put(currentMapping, mappingCount.get(currentMapping) + 1);
else
    mappingCount.put(currentMapping, 1);

In order to be able to get the value from the hashtable, for the class Mapping I did the following:

@Override
public boolean equals(Object obj) {
    return ((Mapping)obj).mappingXML.equals(this.mappingXML);
}

However, this doesn't do the trick since mappingCount.get(currentMapping) always results in null. To be sure that something's not wrong, I did the following:

if (aaa.contains(currentMapping.getMappingXML()))
    System.out.println("found it!");
else
    aaa.add(currentMapping.getMappingXML());

where aaa is List<String> aaa = new ArrayList<String>(). Of course, found it is printed many times. What am I doing wrong?

Body:
You have to implement hashcode() as well!

Example:

public class Employee{
    int        employeeId;
    String     name;
    Department dept;

    // other methods would be in here

    @Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 17 + employeeId;
        hash = hash * 31 + name.hashCode();
        hash = hash * 13 + (dept == null ? 0 : dept.hashCode());
        return hash;
    }
}


问:
Angular 8: unable to set headers
I want to call a service from my component:

```<code>getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}
</code>```

The call not showing the Authorization, check the image below:

答:
send header as third params. Like</p>

```<code>const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", {},httpOptions);
</code>```

Title: Angular 8: unable to set headers

Body:
I want to call a service from my component:

getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}

The call not showing the Authorization, check the image below:

Body:
send header as third params. Like

const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", {},httpOptions);


问:
How to set mock Geolocation Long/Lat in Python/Chromedriver/Selenium
I'm running Python/Chromedriver/GoogleChrome/Selenium headless
on python, and I am having some trouble figuring out how to set a custom geolocation long / lat programmatically; the following code is not updating location on google.com or https://www.infobyip.com/browsergeolocation.php

At the moment I'm starting chromedriver with these options:

```<code>chrome_options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.media_stream_mic": 1,
    "profile.default_content_setting_values.media_stream_camera": 1,
    "profile.default_content_setting_values.geolocation": 1,
    "profile.default_content_setting_values.notifications": 1,
    "profile.default_content_settings.geolocation": 1,
    "profile.default_content_settings.popups": 0
  })
</code>```

I can call and set/get the geolocation long / lat with these commands:

```<code>    driver.execute_script("""navigator.geolocation.getCurrentPosition = function(success, failure) {
      success({
        coords: {latitude: -43.5333, longitude: 172.633},
        timestamp: Date.now(),
      });
    }""");
    time.sleep(5)
    print(driver.execute_script("var positionStr=\"\";"+
                                "window.navigator.geolocation.getCurrentPosition(function(pos){positionStr=pos.coords.latitude+\":\"+pos.coords.longitude});"+
                                "return positionStr;"))
</code>```

This does return the updated long / lat that I have set.
BUT when using https://www.infobyip.com/browsergeolocation.php or http://google.com, it does not grab the new geolocation and does not work.

How would one set a custom geolocation with chromedriver config arguments, chrome dev tools programmatically, or by modifying files in my chrome's profile directory? The other answers for pythons selenium on stack overflow do not seem to work here.

答:
It's actually now progammable by using the Chrome Devtools Protocol (cdp):</p>
```<code>params = {
    "latitude": 50.1109,
    "longitude": 8.6821,
    "accuracy": 100
}

driver = webdriver.Chrome()
driver.execute_cdp_cmd("Page.setGeolocationOverride", params)
driver.get('https://www.google.com/maps')
</code>```

Body:
I'm running Python/Chromedriver/GoogleChrome/Selenium headless
on python, and I am having some trouble figuring out how to set a custom geolocation long / lat programmatically; the following code is not updating location on google.com or https://www.infobyip.com/browsergeolocation.php

At the moment I'm starting chromedriver with these options:

chrome_options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.media_stream_mic": 1,
    "profile.default_content_setting_values.media_stream_camera": 1,
    "profile.default_content_setting_values.geolocation": 1,
    "profile.default_content_setting_values.notifications": 1,
    "profile.default_content_settings.geolocation": 1,
    "profile.default_content_settings.popups": 0
  })

I can call and set/get the geolocation long / lat with these commands:

    driver.execute_script("""navigator.geolocation.getCurrentPosition = function(success, failure) {
      success({
        coords: {latitude: -43.5333, longitude: 172.633},
        timestamp: Date.now(),
      });
    }""");
    time.sleep(5)
    print(driver.execute_script("var positionStr=\"\";"+
                                "window.navigator.geolocation.getCurrentPosition(function(pos){positionStr=pos.coords.latitude+\":\"+pos.coords.longitude});"+
                                "return positionStr;"))

This does return the updated long / lat that I have set.
BUT when using https://www.infobyip.com/browsergeolocation.php or http://google.com, it does not grab the new geolocation and does not work.

How would one set a custom geolocation with chromedriver config arguments, chrome dev tools programmatically, or by modifying files in my chrome's profile directory? The other answers for pythons selenium on stack overflow do not seem to work here.

Body:
It's actually now progammable by using the Chrome Devtools Protocol (cdp):

params = {
    "latitude": 50.1109,
    "longitude": 8.6821,
    "accuracy": 100
}

driver = webdriver.Chrome()
driver.execute_cdp_cmd("Page.setGeolocationOverride", params)
driver.get('https://www.google.com/maps')


问:
porting a python3 app from Linux to Android using kivy and bluepy
I created a simple app in python3 using Kivy for the UI and bluepy to access some Bluetooth BLE devices.
Now I like to port the app to my Android phone. I saw there is somehow a port in Kivy to Android (https://github.com/kivy/python-for-android). But I am not sure if I can port my app with the bluepy dependency.

So it comes down to the questions:

1st) is it possible to port a kivy and bluepy app to Android?

2nd) is there a tutorial showing how to do that?

答:
You can package an Android app using Buildozer. You can do it using this guide on the Kivy website. If you are using Windows you can use the WSL (Windows Subsystem for Linux). Here is a guide. I have used it to package my Android app. (By the way I installed Ubuntu from the Windows Store.) Keep in mind that this is a command-line, not a GUI (Graphical User Interface). Hope my answer works for you! (If you get any errors, make sure to comment.)

EDIT: You need to include "bluepy" in the requirements variable in the buildozer.spec file.


问:
SQL join in Laravel, how to?
Help me please, with JOINS, learning SQL and joins are painful :(

I have table: categories with column name: Name, ID

I have table: sub_categories with column name: ID

I have table: provider_services with column name: category_id & subcategory_id

When I do in laravel view blade {{$provider->providerServices()->where("status",1)->count()}}

I will receive: 2

It means, that provider, has 2 services with category_id 2, 3 and subcategory_id 4,8

Question:
How can I join this data to table categories and grab the category Name using cat_id & subcat_id?

Category_id 2 is - Painting

Category_id 3 is - Plumbing

SubCategory_id is - Aqua

SubCategory_id 8 is - Test

So, as A result I need to have something: Painting and Aqua, Plumbing and Test

Thank you very much!

答:
Strange, why this SQL query, return overall status of Categories & Sub-Categories, but not status of provider_services?</p>

```<code>SELECT categories.name, categories.id, sub_categories.id as idPodKa, sub_categories.name as ImjaPodkategorij, provider_services.status as Status
FROM categories
LEFT JOIN sub_categories
ON categories.id=sub_categories.category_id
LEFT JOIN provider_services
ON categories.id=sub_categories.category_id=provider_services.status
where provider_services.status = 1
</code>```

Title: SQL join in Laravel, how to?

Body:
Strange, why this SQL query, return overall status of Categories & Sub-Categories, but not status of provider_services?

SELECT categories.name, categories.id, sub_categories.id as idPodKa, sub_categories.name as ImjaPodkategorij, provider_services.status as Status
FROM categories
LEFT JOIN sub_categories
ON categories.id=sub_categories.category_id
LEFT JOIN provider_services
ON categories.id=sub_categories.category_id=provider_services.status
where provider_services.status = 1


问:
Disabling Spring @Autowired by-name fallback
I have the following classes defined:

```<code>public interface Thingy { ... }
public class Foo implements Thingy { ... }
public class Bar implements Thingy { ... }
</code>```

Classes Foo and Bar are both instanciated as singleton beans with same names, as in

```<code><bean id="foo" class="Foo" />
<bean id="bar" class="Bar" />
</code>```

The problem happens then trying to autowire field with same name as bean, like

```<code>@Autowired
Thingy foo;
</code>```

Here, field is autowired with Foo instance, and i don't want that. If field name doesn't match bean name, autowiring falis and that's desired.
So, is there any way to disable such fallback, so autowiring in above case would fail?

答:
I have a couple suggestions to help you out, although I am not sure exactly what you are asking for is possible.

If you are not using the annotation package-scan functionality for discovering beans, then I think in your spring.xml configuration you can specify your beans to have an autowire detection mode.  In the desired bean you specify an element 'autowire', and it has 4 or 5 possible values defined here.  I think the one you would want is 'byType'.

You could also look into using the @Qualifier annotation.  This is used for when you have multiple beans of the same type in your application context to help distinguish which bean you actually want to use.

Use a different name.  Perhaps this is more simple than you were hoping for, but I think it would help to take care of your problem.

Body:
I have the following classes defined:

public interface Thingy { ... }
public class Foo implements Thingy { ... }
public class Bar implements Thingy { ... }

Classes Foo and Bar are both instanciated as singleton beans with same names, as in

<bean id="foo" class="Foo" />
<bean id="bar" class="Bar" />

The problem happens then trying to autowire field with same name as bean, like

@Autowired
Thingy foo;

Here, field is autowired with Foo instance, and i don't want that. If field name doesn't match bean name, autowiring falis and that's desired.
So, is there any way to disable such fallback, so autowiring in above case would fail?


问:
Replace dots in filename Python
im trying to replace all dots (and accents, but's already done) in filename with underscore except extension dot of course.
I saw a lot of solutions but mainly with bash. Cant find for python. Probably I should use regex but dont have much experience here. Below my code:</p>

```<code>path2 = 'xx'
dicto = {"ą":"a",
         "ś":"s",
         "ę":"e",
         "ć":"c",
         "ż":"z",
         "ź":"z",
         "ó":"o",
         "ł":"l",
         "ń":"n"}

def find_replace(string, dictionary):
    for item in string:
        if item in dictionary.keys():
            string = string.replace(item, dictionary[item])
    return string

def change_name(path=path2):
    for root, dirs, files in os.walk(path):
        for filename in files:
            if not filename.startswith('~'):
                os.rename(os.path.join(root,filename), os.path.join(root,find_replace(filename, dicto)))

change_name()

</code>```

答:
Just use Unidecode

import unidecode

print(unidecode.unidecode('ąśęćżźółń))
```

<p>Output:</p>

```aseczzoln
```

Title: Replace dots in filename Python

Body:
im trying to replace all dots (and accents, but's already done) in filename with underscore except extension dot of course.
I saw a lot of solutions but mainly with bash. Cant find for python. Probably I should use regex but dont have much experience here. Below my code:

path2 = 'xx'
dicto = {"ą":"a",
         "ś":"s",
         "ę":"e",
         "ć":"c",
         "ż":"z",
         "ź":"z",
         "ó":"o",
         "ł":"l",
         "ń":"n"}

def find_replace(string, dictionary):
    for item in string:
        if item in dictionary.keys():
            string = string.replace(item, dictionary[item])
    return string

def change_name(path=path2):
    for root, dirs, files in os.walk(path):
        for filename in files:
            if not filename.startswith('~'):
                os.rename(os.path.join(root,filename), os.path.join(root,find_replace(filename, dicto)))

change_name()

Body:
Just use Unidecode

import unidecode

print(unidecode.unidecode('ąśęćżźółń))

Output:

aseczzoln


问:
How to count specific column name in all tables of one SQL Server Database object
I want to count tables that have a specific column name. For instance, dbo.Management has 300 tables. Some tables have ProtectionKey column, and others don't.

I need a list of all the tables that have that column ProtectionKey, or at least a count of them.
I have looked into similar examples but those are either counting ALL columns in a DB or ALL columns in one table.

答:
Use INFORMATION_SCHEMA.COLUMNS:

```<code>select c.*
from INFORMATION_SCHEMA.COLUMNS c
where column_name = 'ProtectionKey';
</code>```

This has many columns.  The ones you want are TABLE_NAME and TABLE_SCHEMA.

Also, this only works in one database at a time, so you need to run it in each database where you want to search for the tables.

Body:
Use INFORMATION_SCHEMA.COLUMNS:

select c.*
from INFORMATION_SCHEMA.COLUMNS c
where column_name = 'ProtectionKey';

This has many columns.  The ones you want are TABLE_NAME and TABLE_SCHEMA.

Also, this only works in one database at a time, so you need to run it in each database where you want to search for the tables.


问:
How to keep a button inside an image when screen gets smaller
I would like to keep a button inside an image. But when the screen gets smaller the button leaves the image field and just floats around. How could I fix it?

.slider-button {
  background: gold;
  border-radius: 8px;
  color: #262626;
  border: none;
  padding: 22px 72px;
  text-decoration: none;
  font-size: 16px;
  position: absolute;
  left: 25%;
  bottom: 25%;
}

.slider-img {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src = "https://www.mundiario.com/media/mundiario/images/2019/10/02/2019100220032812226.png" / class="slider-img">
<button class="slider-button">Press W to win</button></code>```

答:
.slider-button {
  background: gold;
  border-radius: 8px;
  color: #262626;
  border: none;
  padding: 22px 72px;
  text-decoration: none;
  font-size: 16px;
  position: absolute;
  margin: auto;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
}

img {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src = "https://www.mundiario.com/media/mundiario/images/2019/10/02/2019100220032812226.png" />
<button class="slider-button">Press W to win</button></code>```

you have to use like this ".slider-button", "img" in css and over all it's working fine. I have look your code.

Body:
I would like to keep a button inside an image. But when the screen gets smaller the button leaves the image field and just floats around. How could I fix it?

.slider-button {
  background: gold;
  border-radius: 8px;
  color: #262626;
  border: none;
  padding: 22px 72px;
  text-decoration: none;
  font-size: 16px;
  position: absolute;
  left: 25%;
  bottom: 25%;
}

.slider-img {
  position: relative;
}

<button class="slider-button">Press W to win</button>

Body:
.slider-button {
  background: gold;
  border-radius: 8px;
  color: #262626;
  border: none;
  padding: 22px 72px;
  text-decoration: none;
  font-size: 16px;
  position: absolute;
  margin: auto;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
}

img {
  position: relative;
}

<img src = "https://www.mundiario.com/media/mundiario/images/2019/10/02/2019100220032812226.png" />
<button class="slider-button">Press W to win</button>

you have to use like this ".slider-button", "img" in css and over all it's working fine. I have look your code.


问:
DBlink error when querying the remote table
I am creating DB link by using below command. I have not updated tnsnames.ora instead I used details in the commmand.

```<code>  CREATE DATABASE LINK test
  CONNECT TO apps IDENTIFIED BY xyzabc
  USING '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=awsss3270429.us.dell.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=dell122de))';
</code>```

The DBLink was created successfully. but

When I fired below query I got the error.

```<code>select * from USER_CS_SRS@test; . table `USER_CS_SRS` exist in remote database.
</code>```

Error is attached.

I am quite new to DB. Can anybody help me on the same.

答:
You are missing a closing parenthesis at the end of your connection string. Your create statement should end:

```<code>...(CONNECT_DATA=(SERVICE_NAME=opm122de)))';
-----------------------------------------^
</code>```

Recreating what you posted:

```<code>CREATE DATABASE LINK test
CONNECT TO apps IDENTIFIED BY xyzabc
USING '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=rws3270429.us.oracle.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=opm122de))';

select * from USER_CS_SRS@test;

Error report -
SQL Error: ORA-12154: TNS:could not resolve the connect identifier specified
...
</code>```

Adding the final ) changes that:

```<code>drop database link test;

CREATE DATABASE LINK test
CONNECT TO apps IDENTIFIED BY xyzabc
USING '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=rws3270429.us.oracle.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=opm122de)))';

select * from USER_CS_SRS@test;

Error report -
SQL Error: ORA-12545: Connect failed because target host or object does not exist
...
</code>```

which is a different error; for me that's entirely reasonable because I can't resolve rws3270429.us.oracle.com, never mind reach it. As your profile says you work for Oracle, presumably you can - and this either works or throws a different error. Either way the original ORA-12154 error has been fixed.

Body:
I am creating DB link by using below command. I have not updated tnsnames.ora instead I used details in the commmand.

  CREATE DATABASE LINK test
  CONNECT TO apps IDENTIFIED BY xyzabc
  USING '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=awsss3270429.us.dell.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=dell122de))';

The DBLink was created successfully. but

When I fired below query I got the error.

select * from USER_CS_SRS@test; . table `USER_CS_SRS` exist in remote database.

Error is attached.

I am quite new to DB. Can anybody help me on the same.

Body:
You are missing a closing parenthesis at the end of your connection string. Your create statement should end:

...(CONNECT_DATA=(SERVICE_NAME=opm122de)))';
-----------------------------------------^

Recreating what you posted:

CREATE DATABASE LINK test
CONNECT TO apps IDENTIFIED BY xyzabc
USING '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=rws3270429.us.oracle.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=opm122de))';

select * from USER_CS_SRS@test;

Error report -
SQL Error: ORA-12154: TNS:could not resolve the connect identifier specified
...

Adding the final ) changes that:

drop database link test;

CREATE DATABASE LINK test
CONNECT TO apps IDENTIFIED BY xyzabc
USING '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=rws3270429.us.oracle.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=opm122de)))';

select * from USER_CS_SRS@test;

Error report -
SQL Error: ORA-12545: Connect failed because target host or object does not exist
...

which is a different error; for me that's entirely reasonable because I can't resolve rws3270429.us.oracle.com, never mind reach it. As your profile says you work for Oracle, presumably you can - and this either works or throws a different error. Either way the original ORA-12154 error has been fixed.


问:
How to get percentage of combinations computed?
I have this password generator, which comute combination with length of 2 to 6 characters from a list containing small letters, capital letters and numbers (without 0) - together 61 characters.

All I need is to show percentage (with a step of 5) of the combinations already created. I tried to compute all the combinations of selected length, from that number a boundary value (the 5 % step values) and count each combination written in text file and when when the count of combinations meets the boundary value, print the xxx % completed, but this code doesn't seem to work.

Do you know how to easily show the percentage please?

Sorry for my english, I'm not a native speaker.

Thank you all!

```<code>def pw_gen(characters, length):

    """generate all characters combinations with selected length and export them to a text file"""

    # counting number of combinations according to a formula in documentation
    k = length
    n = len(characters) + k - 1
    comb_numb = math.factorial(n)/(math.factorial(n-length)*math.factorial(length))

    x = 0

    # first value
    percent = 5

    # step of percent done to display
    step = 5

    # 'step' % of combinations
    boundary_value = comb_numb/(100/step)

    try:
        # output text file
        with open("password_combinations.txt", "a+") as f:
            for p in itertools.product(characters, repeat=length):
                combination = ''.join(p)

                # write each combination and create a new line
                f.write(combination + '\n')
                x += 1

                if boundary_value <= x <= comb_numb:
                    print("{} % complete".format(percent))
                    percent += step
                    boundary_value += comb_numb/(100/step)

                elif x > comb_numb:
                    break
</code>```

答:
First of all - I think you are using incorrect formula for combinations because itertools.product creates variations with repetition, so the correct formula is n^k (n to power of k).

Also, you overcomplicated percentage calculation a little bit. I just modified your code to work as expected.

import math
import itertools

def pw_gen(characters, length):
    """generate all characters combinations with selected length and export them to a text file"""

    k = length
    n = len(characters)
    comb_numb = n ** k

    x = 0
    next_percent = 5
    percent_step = 5

    with open("password_combinations.txt", "a+") as f:
        for p in itertools.product(characters, repeat=length):
            combination = ''.join(p)

            # write each combination and create a new line
            f.write(combination + '\n')
            x += 1

            percent = 100.0 * x / comb_numb
            if percent >= next_percent:
                print(f"{next_percent} % complete")
                while next_percent < percent:
                    next_percent += percent_step
```

The tricky part is a while loop that makes sure that everything will work fine for very small sets (where one combination is more than step percentage of results).

Body:
I have this password generator, which comute combination with length of 2 to 6 characters from a list containing small letters, capital letters and numbers (without 0) - together 61 characters.

All I need is to show percentage (with a step of 5) of the combinations already created. I tried to compute all the combinations of selected length, from that number a boundary value (the 5 % step values) and count each combination written in text file and when when the count of combinations meets the boundary value, print the xxx % completed, but this code doesn't seem to work.

Do you know how to easily show the percentage please?

Sorry for my english, I'm not a native speaker.

Thank you all!

def pw_gen(characters, length):

    """generate all characters combinations with selected length and export them to a text file"""

    # counting number of combinations according to a formula in documentation
    k = length
    n = len(characters) + k - 1
    comb_numb = math.factorial(n)/(math.factorial(n-length)*math.factorial(length))

    x = 0

    # first value
    percent = 5

    # step of percent done to display
    step = 5

    # 'step' % of combinations
    boundary_value = comb_numb/(100/step)

    try:
        # output text file
        with open("password_combinations.txt", "a+") as f:
            for p in itertools.product(characters, repeat=length):
                combination = ''.join(p)

                # write each combination and create a new line
                f.write(combination + '\n')
                x += 1

                if boundary_value <= x <= comb_numb:
                    print("{} % complete".format(percent))
                    percent += step
                    boundary_value += comb_numb/(100/step)

                elif x > comb_numb:
                    break

Body:
First of all - I think you are using incorrect formula for combinations because itertools.product creates variations with repetition, so the correct formula is n^k (n to power of k).

Also, you overcomplicated percentage calculation a little bit. I just modified your code to work as expected.

import math
import itertools

def pw_gen(characters, length):
    """generate all characters combinations with selected length and export them to a text file"""

    k = length
    n = len(characters)
    comb_numb = n ** k

    x = 0
    next_percent = 5
    percent_step = 5

    with open("password_combinations.txt", "a+") as f:
        for p in itertools.product(characters, repeat=length):
            combination = ''.join(p)

            # write each combination and create a new line
            f.write(combination + '\n')
            x += 1

            percent = 100.0 * x / comb_numb
            if percent >= next_percent:
                print(f"{next_percent} % complete")
                while next_percent < percent:
                    next_percent += percent_step

The tricky part is a while loop that makes sure that everything will work fine for very small sets (where one combination is more than step percentage of results).


问:
React navigation drawer V5
I'm using react-navigation version 5.
I have tab navigation and drawer navigation together.

I'm trying to add an icon in my header to open/close drawer:

here is my custom right header for toggling the drawer:

```<code>const HeaderRight = ({ navigation }) => {
    return (
      <View style={{flexDirection: 'row'}}>
        <TouchableOpacity
        onPress={ () =>{ navigation.toggleDrawer()}}>  //here is the problem
          <Image source={require('./assets/images/icons/drawer.png')}/>
        </TouchableOpacity>
      </View>
    );}
</code>```

this is my tab navigator:

```<code>const Tab = createBottomTabNavigator();
function AppTab() {
  return (
     <Tab.Navigator>
        <Tab.Screen name="Category" component={Category} />
        <Tab.Screen name="Home" component={Home}/>
      </Tab.Navigator>
   );}
</code>```

drawer navigator:

```<code>    const Drawer = createDrawerNavigator();
    function App() {
      return (
          <Drawer.Navigator>
            <Drawer.Screen name="AppTab" component={AppTab} />
            <Drawer.Screen name="Notifications" component={NotificationsScreen} />
          </Drawer.Navigator>
      );}
</code>```

and my stack navigator to theme mix all:

```<code>const Stack = createStackNavigator();
  export default function MyStack() {
  return (
    <NavigationContainer>
    <Stack.Navigator
    headerMode="screen"
     screenOptions={{
          headerRight: ({ navigation }) => (<HeaderRight navigation={navigation} />
        ),}} >
      <Stack.Screen name="Settings" component={Settings} />
    </Stack.Navigator>
    </NavigationContainer>
  );
}
</code>```

when I press the right header icon

what I'm missing here?
the documents weren't really helpful

note:I have also try using dispatch but it didn't work:

navigation.dispatch(DrawerActions.toggleDrawer())

package.json:

```<code>{
  "name": "test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.8.0",
    "@react-native-community/masked-view": "^0.1.6",
    "@react-navigation/bottom-tabs": "^5.0.5",
    "@react-navigation/drawer": "^5.0.5",
    "@react-navigation/native": "^5.0.5",
    "@react-navigation/stack": "^5.0.5",
    "moment": "^2.24.0",
    "randomcolor": "^0.5.4",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-base64": "0.0.2",
    "react-native-gesture-handler": "^1.6.0",
    "react-native-image-slider": "^2.0.3",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.0.0-beta.4",
    "react-native-woocommerce-api": "^1.0.12"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

答:
i have created an simple example deppending upon what i understood, i hope it helps,

u can use options props of Stack.Screen to render custom right or left button and in button component use useNavigation hook to get navigation prop and toggle the drawer user navigation.dispatch(DrawerActions.toggleDrawer())

```<code>import React, {useEffect} from 'react';
import {View, Text, StyleSheet, Image} from 'react-native';
import {NavigationContainer, useNavigation, DrawerActions} from '@react-navigation/native';
import {createDrawerNavigator} from '@react-navigation/drawer';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {createStackNavigator, HeaderBackButton, Header} from '@react-navigation/stack';
import Home from './src/home';
import {TouchableOpacity} from 'react-native-gesture-handler';

const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const Tab = createBottomTabNavigator();

const TabComponent = () => {
  return (
    <Tab.Navigator>
      <Tab.Screen component={Home} name="Home1" />
      <Tab.Screen component={Home} name="Home2" />
      {/*
       * Rest Screens
       */}
    </Tab.Navigator>
  );
};

const DrawerComponent = () => {
  return (
    <Drawer.Navigator>
      <Drawer.Screen component={TabComponent} name="Main" />
      {/*
       * Rest Screens
       */}
    </Drawer.Navigator>
  );
};

const HeaderLeft = () => {
  const navigation = useNavigation();
  return (
    <View style={{flexDirection: 'row'}}>
      <TouchableOpacity
        onPress={() => {
          navigation.dispatch(DrawerActions.openDrawer());
        }}>
        <Text>Open</Text>
        {/* <Image source={require('./assets/images/icons/drawer.png')} /> */}
      </TouchableOpacity>
    </View>
  );
};

export default () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          options={{
            headerLeft: ({}) => <HeaderLeft />
          }}
          component={DrawerComponent}
          name="Drawer"
        />
        {/*
         * Rest Screens
         */}
      </Stack.Navigator>
    </NavigationContainer>
  );
};
</code>```

Title: React navigation drawer V5

Body:
I'm using react-navigation version 5.
I have tab navigation and drawer navigation together.

I'm trying to add an icon in my header to open/close drawer:

here is my custom right header for toggling the drawer:

const HeaderRight = ({ navigation }) => {
    return (
      <View style={{flexDirection: 'row'}}>
        <TouchableOpacity
        onPress={ () =>{ navigation.toggleDrawer()}}>  //here is the problem
          <Image source={require('./assets/images/icons/drawer.png')}/>
        </TouchableOpacity>
      </View>
    );}

this is my tab navigator:

const Tab = createBottomTabNavigator();
function AppTab() {
  return (
     <Tab.Navigator>
        <Tab.Screen name="Category" component={Category} />
        <Tab.Screen name="Home" component={Home}/>
      </Tab.Navigator>
   );}

drawer navigator:

    const Drawer = createDrawerNavigator();
    function App() {
      return (
          <Drawer.Navigator>
            <Drawer.Screen name="AppTab" component={AppTab} />
            <Drawer.Screen name="Notifications" component={NotificationsScreen} />
          </Drawer.Navigator>
      );}

and my stack navigator to theme mix all:

const Stack = createStackNavigator();
  export default function MyStack() {
  return (
    <NavigationContainer>
    <Stack.Navigator
    headerMode="screen"
     screenOptions={{
          headerRight: ({ navigation }) => (<HeaderRight navigation={navigation} />
        ),}} >
      <Stack.Screen name="Settings" component={Settings} />
    </Stack.Navigator>
    </NavigationContainer>
  );
}

when I press the right header icon

what I'm missing here?
the documents weren't really helpful

note:I have also try using dispatch but it didn't work:

navigation.dispatch(DrawerActions.toggleDrawer())

package.json:

{
  "name": "test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.8.0",
    "@react-native-community/masked-view": "^0.1.6",
    "@react-navigation/bottom-tabs": "^5.0.5",
    "@react-navigation/drawer": "^5.0.5",
    "@react-navigation/native": "^5.0.5",
    "@react-navigation/stack": "^5.0.5",
    "moment": "^2.24.0",
    "randomcolor": "^0.5.4",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-base64": "0.0.2",
    "react-native-gesture-handler": "^1.6.0",
    "react-native-image-slider": "^2.0.3",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.0.0-beta.4",
    "react-native-woocommerce-api": "^1.0.12"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

Body:
i have created an simple example deppending upon what i understood, i hope it helps,

u can use options props of Stack.Screen to render custom right or left button and in button component use useNavigation hook to get navigation prop and toggle the drawer user navigation.dispatch(DrawerActions.toggleDrawer())

import React, {useEffect} from 'react';
import {View, Text, StyleSheet, Image} from 'react-native';
import {NavigationContainer, useNavigation, DrawerActions} from '@react-navigation/native';
import {createDrawerNavigator} from '@react-navigation/drawer';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {createStackNavigator, HeaderBackButton, Header} from '@react-navigation/stack';
import Home from './src/home';
import {TouchableOpacity} from 'react-native-gesture-handler';

const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const Tab = createBottomTabNavigator();

const TabComponent = () => {
  return (
    <Tab.Navigator>
      <Tab.Screen component={Home} name="Home1" />
      <Tab.Screen component={Home} name="Home2" />
      {/*
       * Rest Screens
       */}
    </Tab.Navigator>
  );
};

const DrawerComponent = () => {
  return (
    <Drawer.Navigator>
      <Drawer.Screen component={TabComponent} name="Main" />
      {/*
       * Rest Screens
       */}
    </Drawer.Navigator>
  );
};

const HeaderLeft = () => {
  const navigation = useNavigation();
  return (
    <View style={{flexDirection: 'row'}}>
      <TouchableOpacity
        onPress={() => {
          navigation.dispatch(DrawerActions.openDrawer());
        }}>
        <Text>Open</Text>
        {/* <Image source={require('./assets/images/icons/drawer.png')} /> */}
      </TouchableOpacity>
    </View>
  );
};

export default () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          options={{
            headerLeft: ({}) => <HeaderLeft />
          }}
          component={DrawerComponent}
          name="Drawer"
        />
        {/*
         * Rest Screens
         */}
      </Stack.Navigator>
    </NavigationContainer>
  );
};