问:
ForEach loop inside associative array PHP
I have following foreach loop

```<code>$selectedids = "1255;1256;1257";
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {

    $output1 = $idstand++;
    echo "<li>product_id_$output1 = $item,</li>";
}

</code>```

I want to add the output of the above loop inside following associative array

```<code>          $paramas = array(
                'loginId' => $cred1,
                'password' => $credpass1,
                'orderId' =>    $orderid,
                'offer' => $offerid,
                'shipid' => $shipcharge
)
</code>```

So that the final array will look like this;

```<code>          $paramas = array(
                'loginId' => $cred1,
                'password' => $credpass1,
                'orderId' =>    $orderid,
                'offer' => $offerid,
                'shipid' => $shipcharge,
                'product1_id' => 1255,
                'product2_id' => 1256,
                'product3_id' => 1257,
)
</code>```

I tried creating following solution but its not working for me

```<code>$selectedids = $boughtitem;
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';

foreach ($selectedidsarr as $item) {
    $idoutput1 = $idstand++;
    $paramas [] = array (
    'product$idoutput1_id' => $item,
        );
}
</code>```

Need advice.

答:
You don't need to define a new array, just set the key of the current array to the value you want, in the form of $array[$key] = $value to get an array that looks like [$key=>$value], or in your case...

```<code>$paramas['product' . $idoutput1 . '_id'] = $item;
</code>```

Body:
I have following foreach loop

$selectedids = "1255;1256;1257";
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {

    $output1 = $idstand++;
    echo "
product_id_$output1 = $item,
";
}

I want to add the output of the above loop inside following associative array

          $paramas = array(
                'loginId' => $cred1,
                'password' => $credpass1,
                'orderId' =>    $orderid,
                'offer' => $offerid,
                'shipid' => $shipcharge
)

So that the final array will look like this;

          $paramas = array(
                'loginId' => $cred1,
                'password' => $credpass1,
                'orderId' =>    $orderid,
                'offer' => $offerid,
                'shipid' => $shipcharge,
                'product1_id' => 1255,
                'product2_id' => 1256,
                'product3_id' => 1257,
)

I tried creating following solution but its not working for me

$selectedids = $boughtitem;
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';

foreach ($selectedidsarr as $item) {
    $idoutput1 = $idstand++;
    $paramas [] = array (
    'product$idoutput1_id' => $item,
        );
}

Need advice.

Body:
You don't need to define a new array, just set the key of the current array to the value you want, in the form of $array[$key] = $value to get an array that looks like [$key=>$value], or in your case...

$paramas['product' . $idoutput1 . '_id'] = $item;


来源: stackexchange

问:
Codeigniter how to map a class sent to a model
I have a SectorModel with this function:

```<code>public function update(Sector $sector) {
        $this->db->where('sector_id', $sector->getScetor_id());
        return $this->db->update(_SECTOR_, $sector);
}
</code>```

There are times that I’ll change only the name of the Sector object:

```<code>$Sector = new Sector();
$Sector->setSector_name = 'test';

$this->SectorModel->update($Sector);
</code>```

The generated select looks like:

```<code>UPDATE realestate_sector SET sector_name = 'teste', sector_description = NULL
</code>```

It will update but will set all other properties to NULL because it was not set on my object.
Right now, I have to fill the whole object before sending it.

Is there a way to map the Sector class and update only what was sent on the object?

Thanks in advance for any help.

Sorry for any typos, my English is not good =)

答:
The easiest to do this would be to rather use a array - docs here http://codeigniter.com/user_guide/database/active_record.html#update - you just create a array of all the columns with their values that you want to update and perform a $this->db->update('mytable', array('name' => 'test'), array('id' => $id)); call. This will only update the columns you specified in the First array. With the second array acting as your WHERE expression.

The only reason I can think of as to why your other values are being set to NULL is because in your example you create a new instance of the class and the other values must either have been set to nothing or are set to NULL. It would (If this is the case) be better to get a record from the table and then change and values on the populated record and pass that to the function to update.

Hope that helps.

ContentLicense: CC BY-SA 3.0

Body:
I have a SectorModel with this function:

public function update(Sector $sector) {
        $this->db->where('sector_id', $sector->getScetor_id());
        return $this->db->update(_SECTOR_, $sector);
}

There are times that I’ll change only the name of the Sector object:

$Sector = new Sector();
$Sector->setSector_name = 'test';

$this->SectorModel->update($Sector);

The generated select looks like:

UPDATE realestate_sector SET sector_name = 'teste', sector_description = NULL

It will update but will set all other properties to NULL because it was not set on my object.
Right now, I have to fill the whole object before sending it.

Is there a way to map the Sector class and update only what was sent on the object?

Thanks in advance for any help.

Sorry for any typos, my English is not good =)


问:
R fill in new column by filtered value by group
I want to create new column in my dat, filled in by values
satisfying a condition. So, I want to keep the value where where regime == "SA" and fill this value over the whole group in new column vals.sa.

This combines the filter and mutate, but I am unsure what is their correct combination? Filter just keeps rows satisfying condition, but how can I expand this value over all rows in a group?

My data:

```<code>dat <- data.frame(id = c(1,1,2,2,2,2,3,3),
                  regime = c("SA", "B", "SA", "B", "C", "F", "SA", "D"),
                  value = c(3,5,1,2,5,6,7,8))
</code>```

Process the data using dplyr

```<code>dat %>%
  # group data by id
  group_by(id) %>%
  # how to write this condition and get values instead or TRUE/FALSE?
  mutate(val.sa = regime == "SA")
</code>```

Expected output with filled in val.sa value corresponding regime == "SA"

```<code>     id regime value val.sa
  <dbl> <fct>  <dbl>  <dbl>
1     1 SA         3      3
2     1 B          5      3
3     2 SA         1      1
4     2 B          2      1
5     2 C          5      1
6     2 F          6      1
7     3 SA         7      7
8     3 D          8      7
</code>```

答:
We can use case_when

```<code>library(dplyr)
library(tidyr)
 dat %>%
     mutate(val.sa = case_when(regime == 'SA' ~ value) %>%
     group_by(id) %>%
     fill(val.sa)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create new column in my dat, filled in by values
satisfying a condition. So, I want to keep the value where where regime == "SA" and fill this value over the whole group in new column vals.sa.

This combines the filter and mutate, but I am unsure what is their correct combination? Filter just keeps rows satisfying condition, but how can I expand this value over all rows in a group?

My data:

dat <- data.frame(id = c(1,1,2,2,2,2,3,3),
                  regime = c("SA", "B", "SA", "B", "C", "F", "SA", "D"),
                  value = c(3,5,1,2,5,6,7,8))

Process the data using dplyr

dat %>%
  # group data by id
  group_by(id) %>%
  # how to write this condition and get values instead or TRUE/FALSE?
  mutate(val.sa = regime == "SA")

Expected output with filled in val.sa value corresponding regime == "SA"

     id regime value val.sa
  <dbl> <fct>  <dbl>  <dbl>
1     1 SA         3      3
2     1 B          5      3
3     2 SA         1      1
4     2 B          2      1
5     2 C          5      1
6     2 F          6      1
7     3 SA         7      7
8     3 D          8      7

Body:
We can use case_when

library(dplyr)
library(tidyr)
 dat %>%
     mutate(val.sa = case_when(regime == 'SA' ~ value) %>%
     group_by(id) %>%
     fill(val.sa)


问:
Can a logic app or function be triggered when a blob is scanned by Azure Advanced Threat Protection
Is it possible to capture each time advanced threat protection scans a blob in azure storage? I am aware of that ATP will create an alert in security center if the blob is detected as malware. However, it is hard to know if a blob has been scanned and not been flagged as malware.

What i am looking for is a way to mark the blobs which have passed the malware scan done by ATP.

Help is appreciated
Regards

答: At the moment, there is no such trigger for blob. You can use Azure security center or Azure Sentinel to create alert or incident and those services can invoke logic app for certain conditions</p>


问:
WooCommerce aligning pictures of products
I am trying to align the pictures of the products so that the pictures are aligned horizontally.

For example, the third picture in the first category here is upper compared to the other 2 because its title is shorter. How can I have all the pictures aligned just like in a table?

(link for the example is this)

答:
There are several options, one of which is to add a min-height with CSS for the title (h2) </p>

<pre class="lang-css prettyprint-override"><code>.type-product .woocommerce-loop-product__title {
    min-height: 63px;
}
</code>```

Body:
There are several options, one of which is to add a min-height with CSS for the title (h2)

.type-product .woocommerce-loop-product__title {
    min-height: 63px;
}


问:
imperative to functional: n-body collision
I'm a beginner in functional programming but I'm famaliar with imperative programming. I'm having trouble translating a piece of cpp code involving updatating two objects at the same time (context is n-body simulation).

It's roughly like this in c++:

for (Particle &i: particles) {
  for (Particle &j: particles) {
     collide(i, j) // function that mutates particles i and j
  }
}
```

<p>I'm translating this to Ocaml, with immutable objects and immutable Lists. The difficult part is that I need to replace two objects at the same time. So far I have this:</p>

<pre class="lang-ml prettyprint-override"><code>List.map (fun i ->
  List.map (fun j ->
    let (new_i, new_j) = collide(i, j) in // function that returns new particles i, j
    // how do i update particles with new i, j?
  ) particles
) particles
</code>```

How do I replace both objects in the List at the same time?

答:
List.map returns a new list. The function you supply to List.map may transform the elements from one type to another or just apply some operation on the same type.

For example, let's assume you start with a list of integer tuples

let int_tuples = [(1, 3); (4, 3); (8, 2)];;
```

<p>and let's assume that your update function takes an integer tuple and doubles the integers:</p>

<pre class="lang-ml prettyprint-override"><code>let update (i, j) = (i * 2, j * 2) (* update maybe your collide function *)
</code>```

If you now do:

let new_int_tuples = List.map update int_tuples
```

<p>You'll get</p>

<pre class="lang-ml prettyprint-override"><code>(* [(2, 6); (8, 6); (16, 4)] *)
</code>```

Hope this helps

Body:
I'm a beginner in functional programming but I'm famaliar with imperative programming. I'm having trouble translating a piece of cpp code involving updatating two objects at the same time (context is n-body simulation).

It's roughly like this in c++:

for (Particle &i: particles) {
  for (Particle &j: particles) {
     collide(i, j) // function that mutates particles i and j
  }
}

I'm translating this to Ocaml, with immutable objects and immutable Lists. The difficult part is that I need to replace two objects at the same time. So far I have this:

List.map (fun i ->
  List.map (fun j ->
    let (new_i, new_j) = collide(i, j) in // function that returns new particles i, j
    // how do i update particles with new i, j?
  ) particles
) particles

How do I replace both objects in the List at the same time?

Body:
List.map returns a new list. The function you supply to List.map may transform the elements from one type to another or just apply some operation on the same type.

For example, let's assume you start with a list of integer tuples

let int_tuples = [(1, 3); (4, 3); (8, 2)];;

and let's assume that your update function takes an integer tuple and doubles the integers:

let update (i, j) = (i * 2, j * 2) (* update maybe your collide function *)

If you now do:

let new_int_tuples = List.map update int_tuples

You'll get

(* [(2, 6); (8, 6); (16, 4)] *)

Hope this helps


问:
Is the length in mmap a number of bytes or a number of pages?
In the function:

```<code>void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
</code>```

Does the argument length in mmap represent a number of bytes or a number of pages? Also, can I use mmap similarly to malloc? What are the differences?

答:
The length parameter is in bytes.  The Linux man page does not say this explicitly, but the POSIX spec says (emphasis mine):

The mmap() function shall establish a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off for len bytes.

It is possible to use mmap as a way to allocate memory (you'll want to use MAP_ANONYMOUS or else map the /dev/zero device), but it's not in general a good direct replacement for malloc:

Mappings will always be made in page units (so the system will round up length to the next multiple of the page size), so it's very inefficient for small allocations.

You can't pass pointers returned by mmap to realloc or free (use mremap and munmap instead).

munmap actually returns memory to the system, whereas free may potentially keep it assigned to your process and just mark it available for use by future calls to malloc.  This has pros and cons.  On the one hand, if you know you will not be needing that memory in the future, it is nice to let the system have it back.  On the other hand, every mmap/munmap requires a system call, which is relatively slow, whereas malloc may be able to allocate previously freed memory that already belongs to your process without a system call.

Body:
In the function:

void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)

Does the argument length in mmap represent a number of bytes or a number of pages? Also, can I use mmap similarly to malloc? What are the differences?


问:
Conditional formatting django css
I pretty new to Python and Django. My first Project is a MS Teams Status Call Monitor.
Its working so far. But I asked myself if its possible to format the Table different when having a change in my Status.

```<code>Available = Green
Away = Yellow
Busy = Red
</code>```

How can I do that with Django / CSS?

```<code>{% extends "tutorial/layout.html" %}
{% block content %}
<h1>Teams</h1>
<table class="table">
  <thead>
    <tr>
     <th scope="col">Activity</th>
     <th scope="col">Availability</th>
    </tr>
  </thead>
  <tbody>
     <tr>
        <td>{{ status.status }}</td>
        <td>{{ status.availability }}</td>
     </tr>
  </tbody>
  </table>
{% endblock %}
</code>```

Thanks :)

答:
Adding this to your code should solve the thing, of course, the important part here is the nested if statement not the CSS.</p>

```<code><style>
    {%if status.avilability == Available %}

    .table{
        color:green;
    }

    {% else %}

        {% if status.avilability == Busy %}
          .table{
             color:red;
          }
        {% else %}
          .table{
             color:yellow;
          }

    </style>
</code>```

Title: Conditional formatting django css

Body:
I pretty new to Python and Django. My first Project is a MS Teams Status Call Monitor.
Its working so far. But I asked myself if its possible to format the Table different when having a change in my Status.

Available = Green
Away = Yellow
Busy = Red

How can I do that with Django / CSS?

{% extends "tutorial/layout.html" %}
{% block content %}

Teams

     Activity
     Availability

        {{ status.status }}
        {{ status.availability }}

{% endblock %}

Thanks :)

Body:
Adding this to your code should solve the thing, of course, the important part here is the nested if statement not the CSS.

<style>
    {%if status.avilability == Available %}

    .table{
        color:green;
    }

    {% else %}

        {% if status.avilability == Busy %}
          .table{
             color:red;
          }
        {% else %}
          .table{
             color:yellow;
          }

    </style>


问:
Result of function vs loop
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

```<code>input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715
</code>```

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

```<code>for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773
</code>```

答:
In your first example simply replace the command

```<code>return value[0]
</code>```

with

```<code>yield value[0]
</code>```

Then you may use a newvalue() in these forms, for example:

list(newvalue())  to obtain a list of all calculated values,

for i in newvalue(): to iterate through calculated values.

Title: Result of function vs loop

Body:
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773

Body:
In your first example simply replace the command

return value[0]

with

yield value[0]

Then you may use a newvalue() in these forms, for example:

list(newvalue())  to obtain a list of all calculated values,

for i in newvalue(): to iterate through calculated values.


问:
How to parse String to Date in Java
I want to convert a String 24 May 2020 07:40 AM to date format Mon May 24 07:40:55 IST 2020. I tried using Calendar and SimpleDateFormatter but didn't find a solution. Any help is appreciated.

I want the return type to be Date since I have to compare it with a couple of Dates.

答:
java.time

When you’ve got some Date objects — likely from a legacy API that you cannot afford to upgrade to java.time just now — I still recommend that you use java.time, the modern Java date and time API, for your comparisons.

In the following example I am using Instant from java.time, but you may use ZonedDateTime or some other modern type too.

```<code>    DateTimeFormatter fromFormatter = DateTimeFormatter.ofPattern("d MMM uuuu hh:mm a", Locale.ENGLISH);

    Date anOldfashionedDate = new Date(1_590_286_000_000L);
    Date anotherOldfashionedDate = new Date(1_590_287_000_000L);
    System.out.println("The Date objects are " + anOldfashionedDate + " and " + anotherOldfashionedDate);

    String aString = "24 May 2020 07:40 AM";

    Instant instantFromDate = anOldfashionedDate.toInstant();
    Instant instantFromAnotherDate = anotherOldfashionedDate.toInstant();
    Instant instantFromString = LocalDateTime.parse(aString, fromFormatter)
            .atZone(ZoneId.of("Asia/Kolkata"))
            .toInstant();

    System.out.println("Comparing " + instantFromDate + " and " + instantFromString + ": "
            + instantFromDate.compareTo(instantFromString));
    System.out.println("Comparing " + instantFromAnotherDate + " and " + instantFromString + ": "
            + instantFromAnotherDate.compareTo(instantFromString));
</code>```

Output is (when running in Asia/Kolkata time zone):

```<code>The Date objects are Sun May 24 07:36:40 IST 2020 and Sun May 24 07:53:20 IST 2020
Comparing 2020-05-24T02:06:40Z and 2020-05-24T02:10:00Z: -1
Comparing 2020-05-24T02:23:20Z and 2020-05-24T02:10:00Z: 1
</code>```

An Instant prints in UTC; this is what its toString method generates. The trailing Z means UTC. Since India Standard Time is 5 hours 30 minutes ahead of UTC, 07:40 AM in India is the same time as 02:10 in UTC.

Given that you embark on using java.time now, you are well prepared when one day your legacy API gets upgraded to using java.time too.

The opposite conversion

If you do insist on using Date, to answer your question as asked, the opposite conversion is easy too:

```<code>    Date oldfashionedDateFromInstantFromString = Date.from(instantFromString);
    System.out.println("Converting to old-fashioned: " + oldfashionedDateFromInstantFromString);
</code>```

Converting to old-fashioned: Sun May 24 07:40:00 IST 2020

Link

Oracle tutorial: Date Time explaining how to use java.time.

Title: How to parse String to Date in Java

Body:
java.time

When you’ve got some Date objects — likely from a legacy API that you cannot afford to upgrade to java.time just now — I still recommend that you use java.time, the modern Java date and time API, for your comparisons.

In the following example I am using Instant from java.time, but you may use ZonedDateTime or some other modern type too.

    DateTimeFormatter fromFormatter = DateTimeFormatter.ofPattern("d MMM uuuu hh:mm a", Locale.ENGLISH);

    Date anOldfashionedDate = new Date(1_590_286_000_000L);
    Date anotherOldfashionedDate = new Date(1_590_287_000_000L);
    System.out.println("The Date objects are " + anOldfashionedDate + " and " + anotherOldfashionedDate);

    String aString = "24 May 2020 07:40 AM";

    Instant instantFromDate = anOldfashionedDate.toInstant();
    Instant instantFromAnotherDate = anotherOldfashionedDate.toInstant();
    Instant instantFromString = LocalDateTime.parse(aString, fromFormatter)
            .atZone(ZoneId.of("Asia/Kolkata"))
            .toInstant();

    System.out.println("Comparing " + instantFromDate + " and " + instantFromString + ": "
            + instantFromDate.compareTo(instantFromString));
    System.out.println("Comparing " + instantFromAnotherDate + " and " + instantFromString + ": "
            + instantFromAnotherDate.compareTo(instantFromString));

Output is (when running in Asia/Kolkata time zone):

The Date objects are Sun May 24 07:36:40 IST 2020 and Sun May 24 07:53:20 IST 2020
Comparing 2020-05-24T02:06:40Z and 2020-05-24T02:10:00Z: -1
Comparing 2020-05-24T02:23:20Z and 2020-05-24T02:10:00Z: 1

An Instant prints in UTC; this is what its toString method generates. The trailing Z means UTC. Since India Standard Time is 5 hours 30 minutes ahead of UTC, 07:40 AM in India is the same time as 02:10 in UTC.

Given that you embark on using java.time now, you are well prepared when one day your legacy API gets upgraded to using java.time too.

The opposite conversion

If you do insist on using Date, to answer your question as asked, the opposite conversion is easy too:

    Date oldfashionedDateFromInstantFromString = Date.from(instantFromString);
    System.out.println("Converting to old-fashioned: " + oldfashionedDateFromInstantFromString);

Converting to old-fashioned: Sun May 24 07:40:00 IST 2020

Link

Oracle tutorial: Date Time explaining how to use java.time.


问:
XCode 4 Tutorials for Cocoa OS X Applications
There's obviously a lot of buzz around writing Cocoa Touch applications, but there doesn't seem to be much around creating applications for OS X apps using XCode 4.

Does anyone know of any resources that cover OS X Application Development using XCode 4? Are tutorials for XCode 3 usable for XCode 4 Development?

Thanks.

答: I would say tutorials for Xcode 3 are valid/close-to-ideal for learning OS X development, and then perhaps go through a tutorial on the changes between Xcode 3 and 4, as they are quite significant (but relatively easy to grasp/get used to/not too crucial to actual development). The differences between 3 and 4 are more usability/User Experience related more than actually changing how you write code.</p>


问:
putting a space between the 3rd and 4th characters of postal code in Python
I have a df (data frame) in Python with with a postal_code variable that has Canadian  postal codes. All the postal codes are collected in a row such as k1b6j2. But , for me to use the the 'pgeocode' package i need the postal code in a standard form which is like k1b 6j2 (there must be a space between the 3rd and 4th character)

So, is there a way to replace all the postal codes with the modified ones in the df?

Many Thanks,
Ben

答:
In pandas, you can use "apply" to achive your require.</p>

```<code>df['postal_code'] = df['postal_code'].apply(lambda x:x[:3]+' '+x[-3:])
</code>```

Body:
In pandas, you can use "apply" to achive your require.

df['postal_code'] = df['postal_code'].apply(lambda x:x[:3]+' '+x[-3:])


问:
Invalid command \"/bin/sh\": file not found
I have a Dockerfile with

```<code>CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app
</code>```

which fails with error: Invalid command \"/bin/sh\": file not found

but the same command runs like this:

```<code>RUN gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app
</code>```

What could be wrong?

Update: The problem starts when I have these two lines added:
ENV APP_HOME /app and WORKDIR $APP_HOME

Dockerfile:

```<code># Dockerfile
FROM penguicky/docker-python3-opencv

ENV APP_HOME /app
WORKDIR $APP_HOME

RUN apt-get update
RUN apt-get install -y libsm6 libxext6 libxrender-dev
RUN pip3 install Flask gunicorn
RUN pip3 install opencv-contrib-python

EXPOSE 8080

#RUN echo $CV_VERSION

COPY . ./

CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app
</code>```

Update

I tried using this way:

```<code>CMD ["gunicorn", "--bind", "8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]
</code>```

now I get this:

```<code>2020-06-02 22:03:27.511 EEST[2020-06-02 19:03:27 +0000] [1] [INFO] Starting gunicorn 20.0.4
2020-06-02 22:03:27.513 EEST[2020-06-02 19:03:27 +0000] [1] [ERROR] Invalid address: ('8080', 8000)
</code>```

Update2:

So it works by this:

```<code>CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]
</code>```

But I don't know the explanation why it works like this.

答:
If you check the --bind flag for gunicorn, it's mentioned as
Specify a server socket to bind. Server sockets can be any of ${HOST}, ${HOST}:${PORT}, fd://${FD}, or unix:${PATH}. An IP is a valid ${HOST}

And according to above mentioned flag, you need to mention the whole IP while specifying that flag.

This is NOT working as only 8080 port is mentioned.

```<code>CMD ["gunicorn", "--bind", "8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

</code>```

Below 1 works, because whole IP is mentioned.

```<code>CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

</code>```

Ref:- https://docs.gunicorn.org/en/stable/run.html

Body:
I have a Dockerfile with

CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app

which fails with error: Invalid command \"/bin/sh\": file not found

but the same command runs like this:

RUN gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app

What could be wrong?

Update: The problem starts when I have these two lines added:
ENV APP_HOME /app and WORKDIR $APP_HOME

Dockerfile:

# Dockerfile
FROM penguicky/docker-python3-opencv

ENV APP_HOME /app
WORKDIR $APP_HOME

RUN apt-get update
RUN apt-get install -y libsm6 libxext6 libxrender-dev
RUN pip3 install Flask gunicorn
RUN pip3 install opencv-contrib-python

EXPOSE 8080

#RUN echo $CV_VERSION

COPY . ./

CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app

Update

I tried using this way:

CMD ["gunicorn", "--bind", "8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

now I get this:

2020-06-02 22:03:27.511 EEST[2020-06-02 19:03:27 +0000] [1] [INFO] Starting gunicorn 20.0.4
2020-06-02 22:03:27.513 EEST[2020-06-02 19:03:27 +0000] [1] [ERROR] Invalid address: ('8080', 8000)

Update2:

So it works by this:

CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

But I don't know the explanation why it works like this.

Body:
If you check the --bind flag for gunicorn, it's mentioned as
Specify a server socket to bind. Server sockets can be any of ${HOST}, ${HOST}:${PORT}, fd://${FD}, or unix:${PATH}. An IP is a valid ${HOST}

And according to above mentioned flag, you need to mention the whole IP while specifying that flag.

This is NOT working as only 8080 port is mentioned.

CMD ["gunicorn", "--bind", "8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

Below 1 works, because whole IP is mentioned.

CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

Ref:- https://docs.gunicorn.org/en/stable/run.html


问:
Store does not implement IUserRoleStore<TUser> UserManager<TUser>.GetUserRoleStore() ASP.NET Core MVC 3
I have implemented Identity in Asp.Net.Core MVC 3 because we already have database tables that we want to use. I get the error when calling the methods below and they are both happening in the UserManager in the same call to the method. When looking at the source code for this method it is because the Store variable is null. But I am not quite sure how to make sure it is not null. I have looked at various solutions online but none solve my problem.

My solution is working with the SignInManager for passwords but I can not get it to get passed the error for Roles.

ConfigureServices Method

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddMvc(options =>
    {
        var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
        options.Filters.Add(new AuthorizeFilter(policy));
        options.EnableEndpointRouting = false;
    });
    services.AddDbContext<EntitiesModel>(options => options.UseSqlServer(
            Configuration["Data:ConnectionStrings:XXXXXXXXXXXXX"]));
    services.AddIdentity<UserViewModel, UserRoleViewModel>().AddDefaultTokenProviders();
    services.AddTransient<IUserStore<UserViewModel>, UserStore>();
    services.AddTransient<IRoleStore<UserRoleViewModel>, RoleStore>();
    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.LoginPath = "/Login";
        options.LogoutPath = "/Logout";
    });
}
</code>```

UserStore class

```<code>public class UserStore : IUserStore<UserViewModel>, IUserPasswordStore<UserViewModel>, IUserEmailStore<UserViewModel>, IUserRoleStore<UserRoleViewModel>
{
....
</code>```

RoleStore class

```<code>public class RoleStore : IRoleStore<UserRoleViewModel>,IUserRoleStore<UserRoleViewModel>
{
....
</code>```

UserViewModel class

```<code>public class UserViewModel
{
    [Key, Required]
    public int Id { get; set; }
    [Required, MaxLength(128)]
    public string UserName { get; set; }
    [Required, MaxLength(1024)]
    public string Password { get; set; }
    public virtual ICollection<UserRoleViewModel> UserRoles { get; set; }
}
</code>```

UserRoleViewRoleModel class

```<code>public class UserRoleViewModel
{
    [Key, Required]
    public int Id { get; set; }
    [Required, ForeignKey(nameof(User))]
    public int UserId { get; set; }
    [Required, ForeignKey(nameof(Role))]
    public int RoleId { get; set; }
    public virtual RoleViewModel Role { get; set; }
    public virtual UserViewModel User { get; set; }
}
</code>```

RoleViewModel class

```<code>public class RoleViewModel
{
    [Key,Required]
    public int RoleId  { get; set; }
    [Required]
    public string RoleName { get; set; }
    public virtual  ICollection<UserRoleViewModel> UserRoles { get; set; }
}

**Calling Code**
//this works
var result = await signInManager.PasswordSignInAsync(user.UserName, user.Password, true, false);
//this fails
var test = await userManager.IsInRoleAsync(user, "Management");
//this fails
var roles = await userManager.GetRolesAsync(user);
</code>```

Error

NotSupportedException: Store does not implement IUserRoleStore.
  Microsoft.AspNetCore.Identity.UserManager.GetUserRoleStore()

Forgive me if the way I have structured this is not right but I am new to this coming from ASP.Net Web Forms

答:
Remove the line below:

services.AddTransient, UserStore>();

Body:
I have implemented Identity in Asp.Net.Core MVC 3 because we already have database tables that we want to use. I get the error when calling the methods below and they are both happening in the UserManager in the same call to the method. When looking at the source code for this method it is because the Store variable is null. But I am not quite sure how to make sure it is not null. I have looked at various solutions online but none solve my problem.

My solution is working with the SignInManager for passwords but I can not get it to get passed the error for Roles.

ConfigureServices Method

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddMvc(options =>
    {
        var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
        options.Filters.Add(new AuthorizeFilter(policy));
        options.EnableEndpointRouting = false;
    });
    services.AddDbContext<EntitiesModel>(options => options.UseSqlServer(
            Configuration["Data:ConnectionStrings:XXXXXXXXXXXXX"]));
    services.AddIdentity<UserViewModel, UserRoleViewModel>().AddDefaultTokenProviders();
    services.AddTransient<IUserStore<UserViewModel>, UserStore>();
    services.AddTransient<IRoleStore<UserRoleViewModel>, RoleStore>();
    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.LoginPath = "/Login";
        options.LogoutPath = "/Logout";
    });
}

UserStore class

public class UserStore : IUserStore<UserViewModel>, IUserPasswordStore<UserViewModel>, IUserEmailStore<UserViewModel>, IUserRoleStore<UserRoleViewModel>
{
....

RoleStore class

public class RoleStore : IRoleStore<UserRoleViewModel>,IUserRoleStore<UserRoleViewModel>
{
....

UserViewModel class

public class UserViewModel
{
    [Key, Required]
    public int Id { get; set; }
    [Required, MaxLength(128)]
    public string UserName { get; set; }
    [Required, MaxLength(1024)]
    public string Password { get; set; }
    public virtual ICollection<UserRoleViewModel> UserRoles { get; set; }
}

UserRoleViewRoleModel class

public class UserRoleViewModel
{
    [Key, Required]
    public int Id { get; set; }
    [Required, ForeignKey(nameof(User))]
    public int UserId { get; set; }
    [Required, ForeignKey(nameof(Role))]
    public int RoleId { get; set; }
    public virtual RoleViewModel Role { get; set; }
    public virtual UserViewModel User { get; set; }
}

RoleViewModel class

public class RoleViewModel
{
    [Key,Required]
    public int RoleId  { get; set; }
    [Required]
    public string RoleName { get; set; }
    public virtual  ICollection<UserRoleViewModel> UserRoles { get; set; }
}

**Calling Code**
//this works
var result = await signInManager.PasswordSignInAsync(user.UserName, user.Password, true, false);
//this fails
var test = await userManager.IsInRoleAsync(user, "Management");
//this fails
var roles = await userManager.GetRolesAsync(user);

Error

NotSupportedException: Store does not implement IUserRoleStore.
  Microsoft.AspNetCore.Identity.UserManager.GetUserRoleStore()

Forgive me if the way I have structured this is not right but I am new to this coming from ASP.Net Web Forms


问:
Asp.Net unable to fire event on button click
I'm new to ASP.Net. I am trying to trigger action based on button click but the even is not getting triggered.

This is the button definintion in login.aspx:

```<code><button type="submit" value="submit" class="btn_3" onclick="createAccount_Clicked" runat="server">
       Create Account
</button>
</code>```

This is the intended button click event inside login.aspx.cs:

```<code>protected void createAccount_Clicked(object sender, EventArgs e)
{
     //Here's where you do stuff.
     string value = new_fullname.Value.ToString();
}
</code>```

new_fullname is the Text I'm trying to read (defined in login.aspx):

```<code><div class="col-md-12 form-group p_star" runat="server">
      <input  type="text" class="form-control" id="new_fullname" name="name" value=""
      placeholder="Full Name" runat="server">
</div>
</code>```

答:
So, you have set the button type to submit which actually submits the server form which does not guarantee the triggering of the intended event. What you should do is, set the button type to button to get it working.

This is how you will get it working:

```<code><button type="button" value="submit" class="btn_3" onclick="createAccount_Clicked" runat="server">
       Create Account
</button>
</code>```

Body:
I'm new to ASP.Net. I am trying to trigger action based on button click but the even is not getting triggered.

This is the button definintion in login.aspx:

<button type="submit" value="submit" class="btn_3" onclick="createAccount_Clicked" runat="server">
       Create Account
</button>

This is the intended button click event inside login.aspx.cs:

protected void createAccount_Clicked(object sender, EventArgs e)
{
     //Here's where you do stuff.
     string value = new_fullname.Value.ToString();
}

new_fullname is the Text I'm trying to read (defined in login.aspx):

      <input  type="text" class="form-control" id="new_fullname" name="name" value=""
      placeholder="Full Name" runat="server">

Body:
So, you have set the button type to submit which actually submits the server form which does not guarantee the triggering of the intended event. What you should do is, set the button type to button to get it working.

This is how you will get it working:

<button type="button" value="submit" class="btn_3" onclick="createAccount_Clicked" runat="server">
       Create Account
</button>


问:
Find available time slots for table reservation system
I am creating a database for table reservation system. Each table have it's own time slot list and I want to find available time slots for each table.
So I have the following tables:

```<code>time_slots table
----------------------------------
id || table_id || weekday ||  time
==================================
 1           1          1    12:00
 2           1          1    12:30
...
11           1          1    16:00
...
17           1          1    19:00
18           1          1    19:30
...
27           1          1    00:00
==================================

reservations table
-----------------------------------------------------------------
id || table_slot_id ||          start_date ||            end_date
=================================================================
 1                1    2020-06-01 12:00:00    2020-06-01 12:20:00
 2                1    2020-06-01 16:00:00    2020-06-01 19:00:00
=================================================================
</code>```

I wrote query which allows to find all reserved time slots:

```<code>SELECT *
FROM table_slots, (SELECT *
                   FROM reservations
                   WHERE reservations.start_date::date = '2020-06-01'::date) as res
WHERE table_slots.weekday = extract(dow from '2020-06-01'::date)
AND table_slots.time BETWEEN res.start_date::time and res.end_date::time
ORDER BY table_slots.time
</code>```

But I don't understand how to write query to find available time slots. So I expect that result should contain all time_slots where time is between 12:30 and 15:30; 19:30 and 00:00. How to do this?
Is it possible to write such queries with minimal overhead?
And the last question, is this good design for such systems? If not then what is the better designs in these scenerios.
Thanks!

答:
You could use not exists. This would give you all available slots on June 1st:

```<code>select ts.*
from time_slots ts
where not exists (
    select 1
    from reservations r
    where
        r.table_slot_id = ts.id
        and r.start_date >= '2020-06-01'::date
        and r.start_date <  '2020-07-01'::date
        and r.start_date::time <= ts.time
        and r.end_date::time   >  ts.time
)
</code>```

Note that this assumes that reservations do not span across days.

It might be more efficient to express the where clause of the subquery as:

```<code>    where
        r.table_slot_id = ts.id
        and r.start_date >= '2020-06-01'::date
        and r.start_date <= '2020-06-01'::date + ts.time::interval
        and r.end_date   >  '2020-06-01'::date + ts.time::interval
</code>```

This would take advantage of an index on reservations(table_slot_id, start_date, end_date).

Body:
I am creating a database for table reservation system. Each table have it's own time slot list and I want to find available time slots for each table.
So I have the following tables:

time_slots table
----------------------------------
id || table_id || weekday ||  time
==================================
 1           1          1    12:00
 2           1          1    12:30
...
11           1          1    16:00
...
17           1          1    19:00
18           1          1    19:30
...
27           1          1    00:00
==================================

reservations table
-----------------------------------------------------------------
id || table_slot_id ||          start_date ||            end_date
=================================================================
 1                1    2020-06-01 12:00:00    2020-06-01 12:20:00
 2                1    2020-06-01 16:00:00    2020-06-01 19:00:00
=================================================================

I wrote query which allows to find all reserved time slots:

SELECT *
FROM table_slots, (SELECT *
                   FROM reservations
                   WHERE reservations.start_date::date = '2020-06-01'::date) as res
WHERE table_slots.weekday = extract(dow from '2020-06-01'::date)
AND table_slots.time BETWEEN res.start_date::time and res.end_date::time
ORDER BY table_slots.time

But I don't understand how to write query to find available time slots. So I expect that result should contain all time_slots where time is between 12:30 and 15:30; 19:30 and 00:00. How to do this?
Is it possible to write such queries with minimal overhead?
And the last question, is this good design for such systems? If not then what is the better designs in these scenerios.
Thanks!

Body:
You could use not exists. This would give you all available slots on June 1st:

select ts.*
from time_slots ts
where not exists (
    select 1
    from reservations r
    where
        r.table_slot_id = ts.id
        and r.start_date >= '2020-06-01'::date
        and r.start_date <  '2020-07-01'::date
        and r.start_date::time <= ts.time
        and r.end_date::time   >  ts.time
)

Note that this assumes that reservations do not span across days.

It might be more efficient to express the where clause of the subquery as:

    where
        r.table_slot_id = ts.id
        and r.start_date >= '2020-06-01'::date
        and r.start_date <= '2020-06-01'::date + ts.time::interval
        and r.end_date   >  '2020-06-01'::date + ts.time::interval

This would take advantage of an index on reservations(table_slot_id, start_date, end_date).


问:
Python Iterate Through a Dictionary
I have dictionary like below

x_wins = {'row1_X': 'X' == x_o[0] and 'X' == x_o[1] and 'X' == x_o[2],
'row2_X' : 'X' == x_o[3] and 'X' == x_o[4] and 'X' == x_o[5],
'row3_X' : 'X' == x_o[6] and 'X' == x_o[7] and 'X' == x_o[8],
'col1_X' : 'X' == x_o[0] and 'X' == x_o[3] and 'X' == x_o[6],
'col2_X' : 'X' == x_o[1] and 'X' == x_o[4] and 'X' == x_o[7],
'col3_X' : 'X' == x_o[2] and 'X' == x_o[5] and 'X' == x_o[8],
'slant1_X' : 'X' == x_o[0] and 'X' == x_o[4] and 'X' == x_o[8],
'slant2_X' : 'X' == x_o[2] and 'X' == x_o[4] and 'X' == x_o[6]
}```

and I want to check if any key gives True. How can I do it? Thx for help.

答:
You can check if any of the dictionary values are true:

if True in x_wins.values():
  print("Success!")
else:
  print("All False...")
```

<p>You could also use <code>any</code> like this: <code>if any(x_wins.values()): ...</code></p>

<p>If you want to get the key for which the value is True then:</p>

<pre class="lang-py prettyprint-override"><code>valid_keys = [key for key, val in x_wins.items() if val is True]
</code>```

This will give the list of all keys that have a value of True.

Title: Python Iterate Through a Dictionary

Body:
I have dictionary like below

x_wins = {'row1_X': 'X' == x_o[0] and 'X' == x_o[1] and 'X' == x_o[2],
'row2_X' : 'X' == x_o[3] and 'X' == x_o[4] and 'X' == x_o[5],
'row3_X' : 'X' == x_o[6] and 'X' == x_o[7] and 'X' == x_o[8],
'col1_X' : 'X' == x_o[0] and 'X' == x_o[3] and 'X' == x_o[6],
'col2_X' : 'X' == x_o[1] and 'X' == x_o[4] and 'X' == x_o[7],
'col3_X' : 'X' == x_o[2] and 'X' == x_o[5] and 'X' == x_o[8],
'slant1_X' : 'X' == x_o[0] and 'X' == x_o[4] and 'X' == x_o[8],
'slant2_X' : 'X' == x_o[2] and 'X' == x_o[4] and 'X' == x_o[6]
}

and I want to check if any key gives True. How can I do it? Thx for help.

Body:
You can check if any of the dictionary values are true:

if True in x_wins.values():
  print("Success!")
else:
  print("All False...")

You could also use any like this: if any(x_wins.values()): ...

If you want to get the key for which the value is True then:

valid_keys = [key for key, val in x_wins.items() if val is True]

This will give the list of all keys that have a value of True.


问:
Azure custom role: authorize role assignment for a specific set of roles
I am trying to create a custom role in Azure that would allow Subscriptions "owners" to do quite everything but cancelling/renaming their own subscriptions or moving into another management group.

I would also like them to be able to grant right access to who they want (especially built-in "Contributor" role) but without allowing them to grant "Owner" right, otherwise my custom role could be tricked easily.

I ended up with the following custom role definition which is so far nice and working, apart from the role assignment of course:

```<code>{
  "Name": "MyCustomRole",
  "IsCustom": true,
  "Description": "Role designed for Azure subscriptions ownership limitations",
  "Actions": [
    "*"
  ],
  "NotActions": [
    "Microsoft.Management/managementGroups/subscriptions/write",
    "Microsoft.Subscription/cancel/action",
    "Microsoft.Subscription/rename/action"
  ],
  "DataActions": [],
  "NotDataActions": [],
  "AssignableScopes": [
    "/providers/Microsoft.Management/managementGroups/root.mg"
  ]
}
</code>```

In the Azure documentation, the only operation I found for role assignment is Microsoft.Authorization/roleAssignments/write.

Is there any way to restrict that - to Contributor role assignment for instance - directly in the custom role?

Azure Policy might technically do the trick (not even sure), but since some operational/experts/whatever guys might end up as Owner, I do not want the policy engine to display "non-compliant" resources. It would lead customers to misunderstandings that I would like to avoid.

答:
Yes it should be possible when you assign a policy, so it's not part of the definition but assignment. You can assign policy on the subscription-level scope, and exclude resource groups. You can do that via "notScopes".

Please see Azure Policy docs for how to do this (chapter Excluded scopes)

The scope of the assignment includes all child resource containers and
  child resources. If a child resource container or child resource
  shouldn't have the definition applied, each can be excluded from
  evaluation by setting notScopes. This property is an array to enable
  excluding one or more resource containers or resources from
  evaluation. notScopes can be added or updated after creation of the
  initial assignment.

https://learn.microsoft.com/en-us/azure/governance/policy/concepts/assignment-structure

You can include excluded scopes in the portal when assigning Policy or through PowerShell by including -NotScope parameter.

Body:
I am trying to create a custom role in Azure that would allow Subscriptions "owners" to do quite everything but cancelling/renaming their own subscriptions or moving into another management group.

I would also like them to be able to grant right access to who they want (especially built-in "Contributor" role) but without allowing them to grant "Owner" right, otherwise my custom role could be tricked easily.

I ended up with the following custom role definition which is so far nice and working, apart from the role assignment of course:

{
  "Name": "MyCustomRole",
  "IsCustom": true,
  "Description": "Role designed for Azure subscriptions ownership limitations",
  "Actions": [
    "*"
  ],
  "NotActions": [
    "Microsoft.Management/managementGroups/subscriptions/write",
    "Microsoft.Subscription/cancel/action",
    "Microsoft.Subscription/rename/action"
  ],
  "DataActions": [],
  "NotDataActions": [],
  "AssignableScopes": [
    "/providers/Microsoft.Management/managementGroups/root.mg"
  ]
}

In the Azure documentation, the only operation I found for role assignment is Microsoft.Authorization/roleAssignments/write.

Is there any way to restrict that - to Contributor role assignment for instance - directly in the custom role?

Azure Policy might technically do the trick (not even sure), but since some operational/experts/whatever guys might end up as Owner, I do not want the policy engine to display "non-compliant" resources. It would lead customers to misunderstandings that I would like to avoid.


问:
Use array to define indices for multidimensional numpy array
I have a multidimensional Numpy array; let's say it's

```<code> myArray = array([[[ 0,  1,  2],
                   [ 3,  4,  5],
                   [ 6,  7,  8]],

                  [[ 9, 10, 11],
                   [12, 13, 14],
                   [15, 16, 17]],

                  [[18, 19, 20],
                   [21, 22, 23],
                   [24, 25, 26]]])
</code>```

I know that running myArray[1,1,1], for instance, will return 13. However, I want to define indx = [1,1,1] then call something to the effect ofmyArray[indx].
However, this does some other multidimensional indexing stuff.

I have also tried myArray[*indx] but that understandably throws a syntax error.

Currently my very ugly workaround is to define

```<code>def array_as_indices(array, matrix):
    st = ''
    for i in array:
        st += '%s,' % i
    st = st[:-1]

    return matrix[eval(st)]
</code>```

which works but is quite inelegant and presumably slow.

Is there a more pythonic way to do what I'm looking for?

答:
This is a duplicate of Unpacking tuples/arrays/lists as indices for Numpy Arrays, but you can just create a tuple

import numpy as np

def main():
    my_array = np.array(
        [
            [[0, 1, 2], [3, 4, 5], [6, 7, 8]],
            [[9, 10, 11], [12, 13, 14], [15, 16, 17]],
            [[18, 19, 20], [21, 22, 23], [24, 25, 26]],
        ]
    )
    print(f"my_array[1,1,1]: {my_array[1,1,1]}")
    indx = (1, 1, 1)
    print(f"my_array[indx]: {my_array[indx]}")

if __name__ == "__main__":
    main()
```

<p>will give</p>

```my_array[1,1,1]: 13
my_array[indx]: 13
```

Body:
I have a multidimensional Numpy array; let's say it's

 myArray = array([[[ 0,  1,  2],
                   [ 3,  4,  5],
                   [ 6,  7,  8]],

                  [[ 9, 10, 11],
                   [12, 13, 14],
                   [15, 16, 17]],

                  [[18, 19, 20],
                   [21, 22, 23],
                   [24, 25, 26]]])

I know that running myArray[1,1,1], for instance, will return 13. However, I want to define indx = [1,1,1] then call something to the effect ofmyArray[indx].
However, this does some other multidimensional indexing stuff.

I have also tried myArray[*indx] but that understandably throws a syntax error.

Currently my very ugly workaround is to define

def array_as_indices(array, matrix):
    st = ''
    for i in array:
        st += '%s,' % i
    st = st[:-1]

    return matrix[eval(st)]

which works but is quite inelegant and presumably slow.

Is there a more pythonic way to do what I'm looking for?

Body:
This is a duplicate of Unpacking tuples/arrays/lists as indices for Numpy Arrays, but you can just create a tuple

import numpy as np

def main():
    my_array = np.array(
        [
            [[0, 1, 2], [3, 4, 5], [6, 7, 8]],
            [[9, 10, 11], [12, 13, 14], [15, 16, 17]],
            [[18, 19, 20], [21, 22, 23], [24, 25, 26]],
        ]
    )
    print(f"my_array[1,1,1]: {my_array[1,1,1]}")
    indx = (1, 1, 1)
    print(f"my_array[indx]: {my_array[indx]}")

if __name__ == "__main__":
    main()

will give

my_array[1,1,1]: 13
my_array[indx]: 13


问:
group_by, get most frequent and second most frequent
I have the following dataset:

```<code>a   b

1   a
1   a
1   a
1   none
2   none
2   none
2   b
3   a
3   c
3   c
3   d
4   a
</code>```

I want to get the most frequent value in b for any a and the second most frequent value of b for any a. in case two values in b have the same frequency I m indifferent about any of the two being considered the "first" or the "second".

in this case the expected output would be:

d2:

```<code>a    first    second
1    a        none
2    none     b
3    c        a(or d, doesn't matter)
4    a        NA
</code>```

as you can see a=4 has just one value in b, thus I expect a NA in the output column "second" as there is no second most frequent value.

data:

```<code>a <- c(1,1,1,1,2,2,2,3,3,3,3,4)
b<- c("a","a", "a", "none", "none", "none", "b", "a", "c" , "c",  "d","a")
d <-  data.frame(a,b)
</code>```

what I tried at the moment is the following

```<code>d1 <-  d %>% group_by(a) %>% summarize ( first =names(which.max(table(b)))  , second= names(which.max(table(b)[-which.max(table(b))] )))
</code>```

but it doesn't work properly, any idea on how to do this?

答:
Here is one option with data.table

```<code>library(data.table)
setDT(d)[, .N, .(a, b)][order(N), .(first = first(b), second = b[2]), a]
</code>```

Body:
I have the following dataset:

a   b

1   a
1   a
1   a
1   none
2   none
2   none
2   b
3   a
3   c
3   c
3   d
4   a

I want to get the most frequent value in b for any a and the second most frequent value of b for any a. in case two values in b have the same frequency I m indifferent about any of the two being considered the "first" or the "second".

in this case the expected output would be:

d2:

a    first    second
1    a        none
2    none     b
3    c        a(or d, doesn't matter)
4    a        NA

as you can see a=4 has just one value in b, thus I expect a NA in the output column "second" as there is no second most frequent value.

data:

a <- c(1,1,1,1,2,2,2,3,3,3,3,4)
b<- c("a","a", "a", "none", "none", "none", "b", "a", "c" , "c",  "d","a")
d <-  data.frame(a,b)

what I tried at the moment is the following

d1 <-  d %>% group_by(a) %>% summarize ( first =names(which.max(table(b)))  , second= names(which.max(table(b)[-which.max(table(b))] )))

but it doesn't work properly, any idea on how to do this?

Body:
Here is one option with data.table

library(data.table)
setDT(d)[, .N, .(a, b)][order(N), .(first = first(b), second = b[2]), a]


问:
PyQt5 QTableWidget How to re-enable a cell after disabling?
For the life of me I cant figure this out. I have a table set up, and in row 0 col 0 I have a checkbox. If that checkbox is not clicked I want to disable row 1, col 0. Otherwise if clicked, enable row 1 col 0.

To disable it I've been using flags:

```<code>if not self.example_table.cellWidget(0,0).isChecked():
    flags = QtCore.Qt.ItemFlags()
    flags != QtCore.Qt.ItemIsEnabled
    # flags != QtCore.Qt.ItemIsEditable (This also works to disable it)
    self.example_table.item(1,0).setFlags(flags)
</code>```

The problem is that when I try and make an else with the inverse, it will not re-enable the cell. Here is what I've tried.

```<code>else:
    flags = QtCore.Qt.ItemFlags()
    flags == QtCore.Qt.ItemIsEnabled #(still doesnt work)
    # flags = QtCore.Qt.ItemIsEnabled (didnt work)
    # flags == QtCore.Qt.ItemIsEditable (didnt work)
    # flags = QtCore.Qt.ItemIsEditable (didnt work)

    self.tblActivityInfo.item(1, 0).setFlags(flags)

</code>```

No matter what I try, the cell at 1,0 remains disabled.

self.example_table is just a QtWidgets.QTableWidget(self.centralwidget)

答:
What you're doing doesn't make much sense: both the second flags lines are just comparisons, they do absolutely nothing.

You should get the current flags for the existing item instead, and then use binary operators to update them.

```<code>item = self.example_table.item(1, 0)
flags = item.flags()
if not self.example_table.cellWidget(0,0).isChecked():
    # set the ItemIsEnabled flag bit to 0
    flags &= ~QtCore.Qt.ItemIsEditable
else:
    # set the ItemIsEnabled flag bit to 1
    flags |= QtCore.Qt.ItemIsEditable
    flags |= QtCore.Qt.ItemIsEnabled

item.setFlags(flags)
</code>```

I recommend you to better study what comparison operators do and how binary bitwise operations work.

Body:
For the life of me I cant figure this out. I have a table set up, and in row 0 col 0 I have a checkbox. If that checkbox is not clicked I want to disable row 1, col 0. Otherwise if clicked, enable row 1 col 0.

To disable it I've been using flags:

if not self.example_table.cellWidget(0,0).isChecked():
    flags = QtCore.Qt.ItemFlags()
    flags != QtCore.Qt.ItemIsEnabled
    # flags != QtCore.Qt.ItemIsEditable (This also works to disable it)
    self.example_table.item(1,0).setFlags(flags)

The problem is that when I try and make an else with the inverse, it will not re-enable the cell. Here is what I've tried.

else:
    flags = QtCore.Qt.ItemFlags()
    flags == QtCore.Qt.ItemIsEnabled #(still doesnt work)
    # flags = QtCore.Qt.ItemIsEnabled (didnt work)
    # flags == QtCore.Qt.ItemIsEditable (didnt work)
    # flags = QtCore.Qt.ItemIsEditable (didnt work)

    self.tblActivityInfo.item(1, 0).setFlags(flags)

No matter what I try, the cell at 1,0 remains disabled.

self.example_table is just a QtWidgets.QTableWidget(self.centralwidget)

Body:
What you're doing doesn't make much sense: both the second flags lines are just comparisons, they do absolutely nothing.

You should get the current flags for the existing item instead, and then use binary operators to update them.

item = self.example_table.item(1, 0)
flags = item.flags()
if not self.example_table.cellWidget(0,0).isChecked():
    # set the ItemIsEnabled flag bit to 0
    flags &= ~QtCore.Qt.ItemIsEditable
else:
    # set the ItemIsEnabled flag bit to 1
    flags |= QtCore.Qt.ItemIsEditable
    flags |= QtCore.Qt.ItemIsEnabled

item.setFlags(flags)

I recommend you to better study what comparison operators do and how binary bitwise operations work.


答:
You can use a list comprehension to find the "True" keys if I understand correctly:

true_keys = [x for x in x_wins if x_wins[x] == True]

Example:

```<code>x_o =['X','X','X',0,0,0,'X','X','X']
x_wins = {'row1_X': 'X' == x_o[0] and 'X' == x_o[1] and 'X' == x_o[2],
'row2_X' : 'X' == x_o[3] and 'X' == x_o[4] and 'X' == x_o[5],
'row3_X' : 'X' == x_o[6] and 'X' == x_o[7] and 'X' == x_o[8],
'col1_X' : 'X' == x_o[0] and 'X' == x_o[3] and 'X' == x_o[6],
'col2_X' : 'X' == x_o[1] and 'X' == x_o[4] and 'X' == x_o[7],
'col3_X' : 'X' == x_o[2] and 'X' == x_o[5] and 'X' == x_o[8],
'slant1_X' : 'X' == x_o[0] and 'X' == x_o[4] and 'X' == x_o[8],
'slant2_X' : 'X' == x_o[2] and 'X' == x_o[4] and 'X' == x_o[6]
}
true_keys = [x for x in x_wins if x_wins[x] == True]
print(true_keys)
</code>```

Output:

```<code>['row1_X', 'row3_X']
</code>```

Title: Python Iterate Through a Dictionary

Body:
You can use a list comprehension to find the "True" keys if I understand correctly:

true_keys = [x for x in x_wins if x_wins[x] == True]

Example:

x_o =['X','X','X',0,0,0,'X','X','X']
x_wins = {'row1_X': 'X' == x_o[0] and 'X' == x_o[1] and 'X' == x_o[2],
'row2_X' : 'X' == x_o[3] and 'X' == x_o[4] and 'X' == x_o[5],
'row3_X' : 'X' == x_o[6] and 'X' == x_o[7] and 'X' == x_o[8],
'col1_X' : 'X' == x_o[0] and 'X' == x_o[3] and 'X' == x_o[6],
'col2_X' : 'X' == x_o[1] and 'X' == x_o[4] and 'X' == x_o[7],
'col3_X' : 'X' == x_o[2] and 'X' == x_o[5] and 'X' == x_o[8],
'slant1_X' : 'X' == x_o[0] and 'X' == x_o[4] and 'X' == x_o[8],
'slant2_X' : 'X' == x_o[2] and 'X' == x_o[4] and 'X' == x_o[6]
}
true_keys = [x for x in x_wins if x_wins[x] == True]
print(true_keys)

Output:

['row1_X', 'row3_X']


问:
In Github, is there a way to search for pull requests created by any author from a provided list?
For my team's weekly builds, I go through all pull requests from the company GitHub and pull out the PRs associated to my team. This requires an annoying sieving step that requires a walk-through of the company's previous week of code contribution.

I looked at the official GitHub search documentation (HERE) and found the "author" field could be used to narrow down the search in the way I want, but when I try this at https://github.com/pulls it only works on one author at a time.

Is there a way to search across a list of authors?

For a little extra context, my team operates across a large list of repos, all of which are under a blanket organization which houses all repos across the company.

答:
Option 1: Using Github's Search Query Language

Go to https://github.com/search

Type in a query following the format of this example (replacing author:* with your usernames.

Example: is:pr repo:zino-hofmann/graphql-flutter author:apackin author:kvenn

Explained

is:pr - only PRs (since Github treats Issues and PRs both as "Issues")

repo: - only show PRs in that repo

author: - only show PRs for these authors

It shows as "Issues", but the list will only include PRs.

Option 2: Fancy Bookmark/Alfred/Spotlight Search

You can modify the query params in the following URL to have the list of people on your team.

Replacing <username1,2,3,4> with your teammates Github username's.

Replacing <your_company> with your company URL (or removing that entirely if not on enterprise).

https://github.<your_company>.com/search?q=author%3A<username1>+author%3A<username2>+author%3A<username3>+author%3A<username4>+is%3Apr&type=Issues

Option 3: Using Github's Advanced Search UI

You can use Github's "Advanced Search" to achieve what you're looking for without needing to learn Github's query language.

For public repos: http://github.com/search/advanced

For internal/enterprise repos: http://github.<your_company>.com/search/advanced

You can use the fields below for filtering:

To filter for specific repos, use "Advanced options" -> "In these repositories"

To filter for specific authors, use "Issues options" -> "Opened by the author"

It uses query params under the hood, so you can generate the search with your UI and copy and paste it (to use for Option 3).

Note: You'll need to add "is:pr" to the resulting search query, no way to do that in the UI.


问:
Retrieving from a database table a value only if the record does not contain duplicates
I have a table with the following three values without any other constraints imposed via Schema

```<code>id_a
id_b
id_c
</code>```

so, there could be more than one row with the same id_b

Now, I want to write a query, that will give me only the rows where id_b is unique and matches a given value.

something like:

```<code>select * where id_b = ? and (id_b is unique)
</code>```

I know it is simple, but my brain in not working as it should, so any help pls.

答:
If you want rows, use window functions:

```<code>select t.*
from (select t.*, count(*) over (partition by b) as cnt_b
      from t
     ) t
where t2.id_b = ? and cnt_b = 1;
</code>```

If you just want the b values, use aggregation:

```<code>select b
from t
group b
having min(b) = max(b) and min(b) = ?;
</code>```

Body:
I have a table with the following three values without any other constraints imposed via Schema

id_a
id_b
id_c

so, there could be more than one row with the same id_b

Now, I want to write a query, that will give me only the rows where id_b is unique and matches a given value.

something like:

select * where id_b = ? and (id_b is unique)

I know it is simple, but my brain in not working as it should, so any help pls.

Body:
If you want rows, use window functions:

select t.*
from (select t.*, count(*) over (partition by b) as cnt_b
      from t
     ) t
where t2.id_b = ? and cnt_b = 1;

If you just want the b values, use aggregation:

select b
from t
group b
having min(b) = max(b) and min(b) = ?;


问:
Name of my app not showing on top of activity. Showing "com.example.(appname).(file name)
When first starting a simple app, usually the title of the app is on the top of the activity. However, for me, it says com.example.inventory.MainActivity and then when I switch activities to another one, it'll say com.example.inventory.AddProduct

This is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.inventory">
  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".ProductList"></activity>
    <activity android:name=".AddProduct" />
    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
</manifest>
```

I'm a beginner so sorry if I forgot to include any other important file.

答:
You need to add a label for your activity like this:

```<code>   <activity android:name=".ProductList"
   android:label = "Product Screen"></activity>
</code>```

Replace Product Screen with the Title of your choice.
Do the same for all the other activities in the Manifest.xml

Body:
When first starting a simple app, usually the title of the app is on the top of the activity. However, for me, it says com.example.inventory.MainActivity and then when I switch activities to another one, it'll say com.example.inventory.AddProduct

This is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.inventory">
  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".ProductList"></activity>
    <activity android:name=".AddProduct" />
    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
</manifest>

I'm a beginner so sorry if I forgot to include any other important file.

Body:
You need to add a label for your activity like this:

   <activity android:name=".ProductList"
   android:label = "Product Screen"></activity>

Replace Product Screen with the Title of your choice.
Do the same for all the other activities in the Manifest.xml


答:
You can do that with the any function.

The following will print win if any values of the x_wins dict is True :

```<code>if any(x_wins.values()):
    print('win!')
</code>```

Title: Python Iterate Through a Dictionary

Body:
You can do that with the any function.

The following will print win if any values of the x_wins dict is True :

if any(x_wins.values()):
    print('win!')


问:
C# MongoDB Driver ToList() paginated query, with having indexes to slow on large data around 50M
I am using the latest MongoDB C# driver version 2.10 in my dotnet core app. I have 50+ million records. All columns indexed properly and queries are working fine on Compass.

Here is the method I have.

```<code> /// <summary>
 /// fetch all items in collection with paging and ordering in direction
 /// </summary>
 /// <param name="pageIndex">page index, based on 0</param>
 /// <param name="size">number of items in page</param>
 /// <param name="order">ordering parameters</param>
 /// <param name="fields">required fields</param>
 /// <param name="filters">search criteria</param>
 /// <returns>collection of entity</returns>

 Task<(IEnumerable<T> result, long count)> FindAllListAsync(int? pageIndex, int? size, string order = null, string fields = null, string filters = null);
</code>```

Here is the implementation

```<code>public IEnumerable<T> FindAll(int? pageIndex, int? size, out long count, string order = null, string fields = null, string filters = null)
    {
        IFindFluent<MongoDB.Bson.BsonDocument, MongoDB.Bson.BsonDocument> fluent;
        long totalCount;
        if (!string.IsNullOrEmpty(filters))
        {
            fluent = CollectionAsBson.Find(filters);
            totalCount = fluent.CountDocuments();
        }
        else
        {
            fluent = CollectionAsBson.Find(FilterDefinition<MongoDB.Bson.BsonDocument>.Empty);
            totalCount = Collection.EstimatedDocumentCount();
        }
        if (pageIndex.HasValue && size.HasValue)
            fluent = fluent.Skip((pageIndex - 1) * size);

        if (size.HasValue)
            fluent = fluent.Limit(size);

        if (!string.IsNullOrEmpty(order))
        {
            fluent = fluent.Sort(order);
        }

        fluent.Options.Collation = new Collation("en");
        IEnumerable<T> result = fluent.Project<T>(fields).ToList();

        count = totalCount;
        return result;
    }
</code>```

I called in this way

```<code>public async Task<(IEnumerable<T> result, long count)> FindAllListAsync(int? pageIndex, int? size, string order = null, string fields = null, string filters = null)
   {
       long localCount = 0;
       var list = await Task.Run(() => FindAll(pageIndex, size, out localCount, order, fields, filters)).ConfigureAwait(true);
       return (list, localCount);
   }
</code>```

This code taking too much time to get even 5 records with paging.  When I return fluent.Project<T>(fields).ToEnumerable() it returns with async cursor which is not evaluated. But when I put mapping code such as AutoMapper or even do toList() after that it takes too much time. Even countDocuments takes too much time.

Here are my indexes.

答: You can use AsQueryable(). This will transform the data you want into a query.

Body:
I am using the latest MongoDB C# driver version 2.10 in my dotnet core app. I have 50+ million records. All columns indexed properly and queries are working fine on Compass.

Here is the method I have.

 ///
 /// fetch all items in collection with paging and ordering in direction
 ///
 /// <param name="pageIndex">page index, based on 0</param>
 /// <param name="size">number of items in page</param>
 /// <param name="order">ordering parameters</param>
 /// <param name="fields">required fields</param>
 /// <param name="filters">search criteria</param>
 /// <returns>collection of entity</returns>

 Task<(IEnumerable<T> result, long count)> FindAllListAsync(int? pageIndex, int? size, string order = null, string fields = null, string filters = null);

Here is the implementation

public IEnumerable<T> FindAll(int? pageIndex, int? size, out long count, string order = null, string fields = null, string filters = null)
    {
        IFindFluent<MongoDB.Bson.BsonDocument, MongoDB.Bson.BsonDocument> fluent;
        long totalCount;
        if (!string.IsNullOrEmpty(filters))
        {
            fluent = CollectionAsBson.Find(filters);
            totalCount = fluent.CountDocuments();
        }
        else
        {
            fluent = CollectionAsBson.Find(FilterDefinition<MongoDB.Bson.BsonDocument>.Empty);
            totalCount = Collection.EstimatedDocumentCount();
        }
        if (pageIndex.HasValue && size.HasValue)
            fluent = fluent.Skip((pageIndex - 1) * size);

        if (size.HasValue)
            fluent = fluent.Limit(size);

        if (!string.IsNullOrEmpty(order))
        {
            fluent = fluent.Sort(order);
        }

        fluent.Options.Collation = new Collation("en");
        IEnumerable<T> result = fluent.Project<T>(fields).ToList();

        count = totalCount;
        return result;
    }

I called in this way

public async Task<(IEnumerable<T> result, long count)> FindAllListAsync(int? pageIndex, int? size, string order = null, string fields = null, string filters = null)
   {
       long localCount = 0;
       var list = await Task.Run(() => FindAll(pageIndex, size, out localCount, order, fields, filters)).ConfigureAwait(true);
       return (list, localCount);
   }

This code taking too much time to get even 5 records with paging.  When I return fluent.Project<T>(fields).ToEnumerable() it returns with async cursor which is not evaluated. But when I put mapping code such as AutoMapper or even do toList() after that it takes too much time. Even countDocuments takes too much time.

Here are my indexes.


问:
How would you read image data in from a program like Image Magick In Java?
I am working with ImageMagick and am wondering what the best way to read image data in from StdOut of the ImageMagick process.

I an invoking the command to the process like so:
/opt/local/bin/convert -resize 8000@ - -

and then piping a byte array to the process for processing.

what is the best way to read data from a process like this?

答:
The Runtime.exec() method returns a Process that has methods for getting the input, output and error streams of the invoked process.

I do wonder how you managed to "pipe a byte array to the process" in any other way.

Note that you'll have to use multiple threads to handle the input and the output of the spawned process because it will block if you try to "pipe in" a lot of input without reading any output.

OwnerDisplayName: DanielHonig

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Michael Borgwardt


问:
OAuth2.0 token strange behaviour (Invalid Credentials 401)
Usually, Google OAuth2.0 mechanism is working great.

The user confirms permission to access Google account with selected scopes.

The refresh token is retrieved and saved to long time storage.

Each time needed (if the access token expired) access token is retrieved and used to access APIs.

But sometimes (thus far only two times for more than 6 months) I've experienced strange behaviour:

Requests to Google APIs return Invalid Credentials (401) error.
Refreshing the access token (using the stored refresh token) does not help.

Here is some structured output I've got when testing this issue:

```
    + ------------------------------------------------------------------------- +
    | 1.TRYING TO REFRESH THE TOKEN.                                            |
    | 2.DONE REFRESHING THE TOKEN.                                              |
    + ------------------------------------------------------------------------- +
    |    access:           **************************************************** |
    |   refresh:                  ********************************************* |
    |   expires:                                                           3600 |
    |   created:                                            2013-07-23 13:12:36 |
    + ------------------------------------------------------------------------- +
```

I've also tried to verify the "fresh" access token by sending requests to
 https://www.googleapis.com/oauth2/v1/tokeninfo

```
    + ------------------------------------------------------------------------- +
    | 1. TRYING TO CHECK THE TOKEN .                                            |
    | 2. DONE CHECKING THE TOKEN THE TOKEN.                                     |
    + ------------------------------------------------------------------------- +
    |       issued_to:                  ************.apps.googleusercontent.com |
    |        audience:                  ************.apps.googleusercontent.com |
    |         user_id:                                             ************ |
    |      expires_in:                                                     3600 |
    |           email:                                     **********@gmail.com |
    |  verified_email:                                                        1 |
    |     access_type:                                                  offline |
    |         scopes::                                                          |
    + ------------------------------------------------------------------------- +
    | https://www.googleapis.com/auth/userinfo.email                            |
    | https://www.googleapis.com/auth/userinfo.profile                          |
    | https://www.googleapis.com/auth/plus.me                                   |
    | https://www.googleapis.com/auth/drive                                     |
    + ------------------------------------------------------------------------- +
```

But when I try to access drive feed the response is:

```
    Error calling GET https://www.googleapis.com/drive/v2/files (401) Invalid Credentials

    domain:         global
    reason:         authError
    message:        Invalid Credentials
    locationType:   header
    location:       Authorization
```

We also experienced the same issue with calendars.
So:

Token was valid before (everything worked).

Refreshing token still works.

Requesting a feed responds with "Invalid Credentials" error.

All the other tokens are still working great, meaning that the code is valid.

Normally when the token is revoked "invalid_grant" error is returned when trying to refresh the token.

Questions

What can be the reason for this behaviour? If the refresh token was revoked or got invalid in some other way, should the request for new access token produce error?

Is there a way to validate the refresh token?

答: If you're using an account that's part of a GSuite set up, you might need to add GSuite Basic to the account. You get to this by Users > Click on user > Licenses.

Body:
Usually, Google OAuth2.0 mechanism is working great.

The user confirms permission to access Google account with selected scopes.

The refresh token is retrieved and saved to long time storage.

Each time needed (if the access token expired) access token is retrieved and used to access APIs.

But sometimes (thus far only two times for more than 6 months) I've experienced strange behaviour:

Requests to Google APIs return Invalid Credentials (401) error.
Refreshing the access token (using the stored refresh token) does not help.

Here is some structured output I've got when testing this issue:

    + ------------------------------------------------------------------------- +
    | 1.TRYING TO REFRESH THE TOKEN.                                            |
    | 2.DONE REFRESHING THE TOKEN.                                              |
    + ------------------------------------------------------------------------- +
    |    access:           **************************************************** |
    |   refresh:                  ********************************************* |
    |   expires:                                                           3600 |
    |   created:                                            2013-07-23 13:12:36 |
    + ------------------------------------------------------------------------- +

I've also tried to verify the "fresh" access token by sending requests to
 https://www.googleapis.com/oauth2/v1/tokeninfo

    + ------------------------------------------------------------------------- +
    | 1. TRYING TO CHECK THE TOKEN .                                            |
    | 2. DONE CHECKING THE TOKEN THE TOKEN.                                     |
    + ------------------------------------------------------------------------- +
    |       issued_to:                  ************.apps.googleusercontent.com |
    |        audience:                  ************.apps.googleusercontent.com |
    |         user_id:                                             ************ |
    |      expires_in:                                                     3600 |
    |           email:                                     **********@gmail.com |
    |  verified_email:                                                        1 |
    |     access_type:                                                  offline |
    |         scopes::                                                          |
    + ------------------------------------------------------------------------- +
    | https://www.googleapis.com/auth/userinfo.email                            |
    | https://www.googleapis.com/auth/userinfo.profile                          |
    | https://www.googleapis.com/auth/plus.me                                   |
    | https://www.googleapis.com/auth/drive                                     |
    + ------------------------------------------------------------------------- +

But when I try to access drive feed the response is:

    Error calling GET https://www.googleapis.com/drive/v2/files (401) Invalid Credentials

    domain:         global
    reason:         authError
    message:        Invalid Credentials
    locationType:   header
    location:       Authorization

We also experienced the same issue with calendars.
So:

Token was valid before (everything worked).

Refreshing token still works.

Requesting a feed responds with "Invalid Credentials" error.

All the other tokens are still working great, meaning that the code is valid.

Normally when the token is revoked "invalid_grant" error is returned when trying to refresh the token.

Questions

What can be the reason for this behaviour? If the refresh token was revoked or got invalid in some other way, should the request for new access token produce error?

Is there a way to validate the refresh token?


问:
How to use loop and range function in python to visualize plot?
Im trying to understand How to use loop and range function in python( matplotlib package ) to visualize the cdf of the Poisson distribution in a single density plot??

 = 3,4,5,6,7

```<code>import numpy as np
import matplotlib.pyplot as plt

plt.gcf().set_size_inches(12,6)

for l in range(3,8,1):
   seq = np.arrange(0,20)
</code>```

How can i build the rest of the code ?

答:
import numpy as np
You define the range of values to calculate the cdf outside the loop, and for every iteration, you have the values as x, and the cdf as y:

```<code>import matplotlib.pyplot as plt
from scipy.stats import poisson

Seq = np.arange(0,20)
plt.gcf().set_size_inches(12,6)

for l in range(3,8,1):
    plt.plot(Seq,poisson.cdf(Seq,l),label=l)
plt.legend(loc="lower right")
</code>```

Body:
Im trying to understand How to use loop and range function in python( matplotlib package ) to visualize the cdf of the Poisson distribution in a single density plot??

 = 3,4,5,6,7

import numpy as np
import matplotlib.pyplot as plt

plt.gcf().set_size_inches(12,6)

for l in range(3,8,1):
   seq = np.arrange(0,20)

How can i build the rest of the code ?

Body:
import numpy as np
You define the range of values to calculate the cdf outside the loop, and for every iteration, you have the values as x, and the cdf as y:

import matplotlib.pyplot as plt
from scipy.stats import poisson

Seq = np.arange(0,20)
plt.gcf().set_size_inches(12,6)

for l in range(3,8,1):
    plt.plot(Seq,poisson.cdf(Seq,l),label=l)
plt.legend(loc="lower right")


问:
Duplication of Comments in my database, how can I fix it?
I have some problem that every time I refresh the page it duplicates the last comment. I tried with redirecting command:

```<code>header("location:../../index.php");
</code>```

but it gives me this error:

Warning: Cannot modify header information - headers already sent by
  (output started at
  /home/timpovodnik/gymshark.timpovodnik.xyz/header.php:87) in
  /home/timpovodnik/gymshark.timpovodnik.xyz/PHP/comments.php on line
  9'.

This is my code:

```<code><?php
    function setComments($conn) { // Funkcija, ki jo kasneje kličem v LoseFat in GainMuscles datoteki //zraven dodamo se spremenljivko $conn, ki je iz datoteke baza.php
        if(isset($_POST['commentSubmit'])) { // Če kliknemo na gumb zažene kodo
            $uid = $_POST['uid'];
            $date = $_POST['date'];
            $message = $_POST['message'];
            $sql = "INSERT INTO komentarji (uime, sporocilo, datum, uporabnik_id, program_id, objava_id) VALUES ('$uid', '$message', '$date', '1', '1', '1')";
            $result = mysqli_query($conn, $sql); // IZVEDE v BAZI
            header("location:../index.php");
            exit();
        }
    }

    function getComments($conn) {
        $sql = "SELECT * FROM komentarji";
        $result = mysqli_query($conn, $sql); // IZVEDE v BAZI
        while ($row = mysqli_fetch_assoc($result)) { // da v tabelo in jo shrani v $row
            echo "<div class='row'>";
                echo "<div class='comment-box'>";
                    echo $row['uime']."<br>";
                    echo $row['datum']."<br>";
                    echo nl2br($row['sporocilo']);
                echo "</div>";
            echo "</div>";
        }
    }
?>
</code>```

答:
I fixed it and also added Mysqli functions to it.

Thank you for all of the suggestions.

```<code><?php
include 'baza.php';

    if(isset($_POST['commentSubmit'])) { // Če kliknemo na gumb zažene kodo
        $uid = $_POST['uid'];
        $date = $_POST['date'];
        $message = $_POST['message'];

        $sql = "INSERT INTO komentarji (uime, sporocilo, datum) VALUES (?, ?, ?);";
        $stmt = mysqli_stmt_init($conn);

        if (!mysqli_stmt_prepare($stmt, $sql)) {
                    header("Location: ../loseFat.php?error=sqlerror"); // Če stavek ne dela
                    exit();
            }
            else {
            mysqli_stmt_bind_param($stmt, "sss", $uid, $message, $date);
            mysqli_stmt_execute($stmt); // Executa stavek v DB

            header("Location: ../loseFat.php?comment=success");
            exit();
        }
    }

function getComments($conn) {
    $sql = "SELECT * FROM komentarji";
    $result = mysqli_query($conn, $sql); // IZVEDE v BAZI
    while ($row = mysqli_fetch_assoc($result)) { // da v tabelo in jo shrani v $row
        echo "<div class='row'>";
            echo "<div class='comment-box'>";
                echo $row['uime']."<br>";
                echo $row['datum']."<br>";
                echo nl2br($row['sporocilo']);
            echo "</div>";
        echo "</div>";
    }
}
</code>```

?>

Body:
I have some problem that every time I refresh the page it duplicates the last comment. I tried with redirecting command:

header("location:../../index.php");

but it gives me this error:

Warning: Cannot modify header information - headers already sent by
  (output started at
  /home/timpovodnik/gymshark.timpovodnik.xyz/header.php:87) in
  /home/timpovodnik/gymshark.timpovodnik.xyz/PHP/comments.php on line
  9'.

This is my code:

<?php
    function setComments($conn) { // Funkcija, ki jo kasneje kličem v LoseFat in GainMuscles datoteki //zraven dodamo se spremenljivko $conn, ki je iz datoteke baza.php
        if(isset($_POST['commentSubmit'])) { // Če kliknemo na gumb zažene kodo
            $uid = $_POST['uid'];
            $date = $_POST['date'];
            $message = $_POST['message'];
            $sql = "INSERT INTO komentarji (uime, sporocilo, datum, uporabnik_id, program_id, objava_id) VALUES ('$uid', '$message', '$date', '1', '1', '1')";
            $result = mysqli_query($conn, $sql); // IZVEDE v BAZI
            header("location:../index.php");
            exit();
        }
    }

    function getComments($conn) {
        $sql = "SELECT * FROM komentarji";
        $result = mysqli_query($conn, $sql); // IZVEDE v BAZI
        while ($row = mysqli_fetch_assoc($result)) { // da v tabelo in jo shrani v $row
            echo "
";
                echo "
";
                    echo $row['uime']."
";
                    echo $row['datum']."
";
                    echo nl2br($row['sporocilo']);
                echo "
";
            echo "
";
        }
    }
?>

Body:
I fixed it and also added Mysqli functions to it.

Thank you for all of the suggestions.

<?php
include 'baza.php';

    if(isset($_POST['commentSubmit'])) { // Če kliknemo na gumb zažene kodo
        $uid = $_POST['uid'];
        $date = $_POST['date'];
        $message = $_POST['message'];

        $sql = "INSERT INTO komentarji (uime, sporocilo, datum) VALUES (?, ?, ?);";
        $stmt = mysqli_stmt_init($conn);

        if (!mysqli_stmt_prepare($stmt, $sql)) {
                    header("Location: ../loseFat.php?error=sqlerror"); // Če stavek ne dela
                    exit();
            }
            else {
            mysqli_stmt_bind_param($stmt, "sss", $uid, $message, $date);
            mysqli_stmt_execute($stmt); // Executa stavek v DB

            header("Location: ../loseFat.php?comment=success");
            exit();
        }
    }

function getComments($conn) {
    $sql = "SELECT * FROM komentarji";
    $result = mysqli_query($conn, $sql); // IZVEDE v BAZI
    while ($row = mysqli_fetch_assoc($result)) { // da v tabelo in jo shrani v $row
        echo "<div class='row'>";
            echo "<div class='comment-box'>";
                echo $row['uime']."<br>";
                echo $row['datum']."<br>";
                echo nl2br($row['sporocilo']);
            echo "</div>";
        echo "</div>";
    }
}

?>


问:
Inserting bulk data into odoo.com. using python
hello i am new to odoo platform.

I have few scripts which extracting data from some websites and i want to modify all by adding functionality that data will be directly uploaded to odoo shop or odoo website.
i want to know that is there any way by which i can upload bulk data into odoo platform using python programming.

I have few scripts which are xtracting information from ecommerce websites and using python scrapy for that. now need some solution to upload this data to odoo.

答:
Since Odoo 12.0, the create method supports batch creation like so:

```<code>vals_list = [{'name': 'john doe'}, {'name': 'alan turing'}, ...]
self.env['model.name'].create(vals_list)
</code>```

The ORM will take care of writing the SQL INSERT to do this.

Body:
Since Odoo 12.0, the create method supports batch creation like so:

vals_list = [{'name': 'john doe'}, {'name': 'alan turing'}, ...]
self.env['model.name'].create(vals_list)

The ORM will take care of writing the SQL INSERT to do this.


问:
Magnify.exe command line args
Does anyone know if there is any command line args that i could pass to the windows magnifier (magnify.exe) so it would open using the Lens view.

Or maybe some other way, I tried opening and sending a keyboard input using the shortcut to change the view, but often it blinks before changing the view! =/

答:
This is a great case for the UNIX "strings" utility, of which there is a Sysinternals version here

It takes some digging and testing, but I found these options:

wait (doesn't magnify until you hit a key)

noutilman

hardwarebuttonlaunch

fullscreen

lens

docked

hilight

globalhotkey

Title: Magnify.exe command line args


问:
Is there a default C++ comparator for user defined structure?
```<code>#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
    map<TreeNode*,int> mp;
    TreeNode* x=new TreeNode(4);
    TreeNode* y=new TreeNode(5);
    TreeNode* z=new TreeNode(6);
    mp[x]=1;
    mp[y]=2;
    mp[z]=3;

    cout<<mp[x]<<endl;

    return 0;
}
</code>```

The above code compiles and gives the desired outut but why don't we need to define a custom comparator to create the map mp; Does C++ does it itself? Same with unordered_map the code works fine.

答:
Is there a default C++ comparator for user defined structure?

Not implicitly and not until C++20.

Since C++20, it is possible to define default comparison operators like this:

```<code>struct T {
    auto operator<=>(const T&) const = default;
};
</code>```

why don't we need to define a custom comparator to create the map mp;

The keys of the map are pointers. Pointers are not user defined types, and they are comparable.

Body:
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
    map<TreeNode*,int> mp;
    TreeNode* x=new TreeNode(4);
    TreeNode* y=new TreeNode(5);
    TreeNode* z=new TreeNode(6);
    mp[x]=1;
    mp[y]=2;
    mp[z]=3;

    cout<<mp[x]<<endl;

    return 0;
}

The above code compiles and gives the desired outut but why don't we need to define a custom comparator to create the map mp; Does C++ does it itself? Same with unordered_map the code works fine.

Body:
Is there a default C++ comparator for user defined structure?

Not implicitly and not until C++20.

Since C++20, it is possible to define default comparison operators like this:

struct T {
    auto operator<=>(const T&) const = default;
};

why don't we need to define a custom comparator to create the map mp;

The keys of the map are pointers. Pointers are not user defined types, and they are comparable.


问:
DynamoDB: ComparisonOperator "IN" doesn't work
JavaScript SDK

I am trying to use ComparisonOperator "IN" in KeyConditions of my query

```<code>var params = {
            TableName: 'xxxxx',
            KeyConditions: {
                'uuid': {
                  ComparisonOperator: 'IN',  /* required */
                  AttributeValueList: [
                    "abc", "def", "ghi"
                  ]
                }              }

        };
var dynamoQueryPromise = dynamoClient.query(params).promise();
...
</code>```

But I received error:

ValidationException: Attempted conditional constraint is not an
  indexable operation

does operation "IN" not available?

Any advice is appreciated.

****UPDATE*****

I followed a potential suggestion from duplicated question link

It suggested to use the "IN" operation in FilterExpression not KeyConditionExpression

I updated my code:

create index 'my-index' with PK = 'staff'

```<code>var keyExpr = "#staff = :staff";
var filterExpr = " #phone IN :phone"

var attributeNames = new Object();
attributeNames["#staff"] = 'staff';
attributeNames["#phone"] = 'phone';

var attributeValues = new Object();
attributeValues[":staff"] = 'A1';
attributeValues[":phone"] = ['0012341', '12342134', '214234124'];
var params = {
      TableName: 'xxxxxx',
      IndexName: 'my-index',
      KeyConditionExpression: keyExpr,
      FilterExpression: filterExpr,
      ExpressionAttributeNames: attributeNames,
      ExpressionAttributeValues: attributeValues
}
...
</code>```

Results: error

ValidationException: Invalid FilterExpression: Syntax error; token:
  ":phone", near: "IN:phone"

答:
Based on the information posted, couldn't figure out whether "phone" is your sort key. However DynamoDB query operator IN is not supported for indexed keys.

For non-indexed keys make sure your AttributeNames list & AttributeValues are declared properly.

Adding a link here for your reference: Dynamo DB filter expression using IN operator with numeric array variable

Body:
JavaScript SDK

I am trying to use ComparisonOperator "IN" in KeyConditions of my query

var params = {
            TableName: 'xxxxx',
            KeyConditions: {
                'uuid': {
                  ComparisonOperator: 'IN',  /* required */
                  AttributeValueList: [
                    "abc", "def", "ghi"
                  ]
                }              }

        };
var dynamoQueryPromise = dynamoClient.query(params).promise();
...

But I received error:

ValidationException: Attempted conditional constraint is not an
  indexable operation

does operation "IN" not available?

Any advice is appreciated.

****UPDATE*****

I followed a potential suggestion from duplicated question link

It suggested to use the "IN" operation in FilterExpression not KeyConditionExpression

I updated my code:

create index 'my-index' with PK = 'staff'

var keyExpr = "#staff = :staff";
var filterExpr = " #phone IN :phone"

var attributeNames = new Object();
attributeNames["#staff"] = 'staff';
attributeNames["#phone"] = 'phone';

var attributeValues = new Object();
attributeValues[":staff"] = 'A1';
attributeValues[":phone"] = ['0012341', '12342134', '214234124'];
var params = {
      TableName: 'xxxxxx',
      IndexName: 'my-index',
      KeyConditionExpression: keyExpr,
      FilterExpression: filterExpr,
      ExpressionAttributeNames: attributeNames,
      ExpressionAttributeValues: attributeValues
}
...

Results: error

ValidationException: Invalid FilterExpression: Syntax error; token:
  ":phone", near: "IN:phone"