问:
How to select one and remove correlated features from a long format correlation dataframe directly?
I have a long format pandas dataframe containing feature correlation pairs (with duplicate pairs). I want to select one out of every correlated pair from this long table (100s of feature). Is their a pythonic way to do this without transforming this table into a matrix? Ideally in this example, we need to keep only feature a, since it is correlated to both b and c. In this example, I'm considering the threshold 0.95.

feature1
feature2
corr

a
b
0.96

b
a
0.96

a
c
0.95

c
a
0.95

b
c
0.94

c
b
0.94

Reproduce this dataframe using

```<code>import pandas as pd
df = pd.DataFrame({'feature1': ['a', 'b', 'a', 'c', 'b', 'c'],
                   'feature2': ['a', 'b', 'a', 'c', 'b', 'c'],
                   'corr': [0.96, 0.96, 0.95, 0.95, 0.94, 0.94]})
</code>```

答:
Solved this by lexicographical sorting the rows and then removing everything from feature2 column.

```<code>features_list = ['a', 'b', 'c']

def custom_sort(x):
    min_val = min(x["feature1"], x["feature2"])
    max_val = max(x["feature1"], x["feature2"])
    x["feature1"] = min_val
    x["feature2"] = max_val
    return x

drop_features_list = list(df.apply(custom_sort, axis=1)["feature2"].drop_duplicates())
drop_features_list

selected_features = list(set(features_list) - set(drop_features_list))
selected_features
> ['a']
</code>```

Body:
I have a long format pandas dataframe containing feature correlation pairs (with duplicate pairs). I want to select one out of every correlated pair from this long table (100s of feature). Is their a pythonic way to do this without transforming this table into a matrix? Ideally in this example, we need to keep only feature a, since it is correlated to both b and c. In this example, I'm considering the threshold 0.95.

feature1
feature2
corr

a
b
0.96

b
a
0.96

a
c
0.95

c
a
0.95

b
c
0.94

c
b
0.94

Reproduce this dataframe using

import pandas as pd
df = pd.DataFrame({'feature1': ['a', 'b', 'a', 'c', 'b', 'c'],
                   'feature2': ['a', 'b', 'a', 'c', 'b', 'c'],
                   'corr': [0.96, 0.96, 0.95, 0.95, 0.94, 0.94]})

Body:
Solved this by lexicographical sorting the rows and then removing everything from feature2 column.

features_list = ['a', 'b', 'c']

def custom_sort(x):
    min_val = min(x["feature1"], x["feature2"])
    max_val = max(x["feature1"], x["feature2"])
    x["feature1"] = min_val
    x["feature2"] = max_val
    return x

drop_features_list = list(df.apply(custom_sort, axis=1)["feature2"].drop_duplicates())
drop_features_list

selected_features = list(set(features_list) - set(drop_features_list))
selected_features
> ['a']


来源: stackexchange

问:
Setting up sharepoint rest api as backend in Azure APIM
We are trying to setup sharepoint rest api in Azure apim backend. We set up the following apim policy. It is receiving the client token, but , not able to successfully execute rest call in the sharepoint. I am not sure whether we are on the right track. Any input is greatly appreciated. Thank you.</p>
```<code>    <send-request ignore-error="true" timeout="20" response-variable-name="bearerToken" mode="new">
        <set-url>{{authorizationServer}}</set-url>
        <set-method>POST</set-method>
        <set-header name="Content-Type" exists-action="override">
            <value>application/x-www-form-urlencoded</value>
        </set-header>
        <set-body>@{
          return "client_id={{clientId}}&scope={{scope}}&client_secret={{clientSecret}}&grant_type=client_credentials";

          // For Azure AD v1, try return statement below
          // return "client_id={{clientId}}&resource={{scope}}&client_secret={{clientSecret}}&grant_type=client_credentials";
      }</set-body>
    </send-request>
    <set-header name="Authorization" exists-action="override">
        <value>@("Bearer " + (String)((IResponse)context.Variables["bearerToken"]).Body.As<JObject>()["access_token"])</value>
    </set-header>
    <!--  Don't expose APIM subscription key to the backend. -->
    <set-header name="Ocp-Apim-Subscription-Key" exists-action="delete" />
</code>```

答:
Before calling backend services we need to initiate a request for which APIM provides send request where you can use that in your policy along with the C# expression.

Also, you can go through this document which has details about Access tokens.

As you have already generated token just check the app is granted through enough permissions

For complete details about SharePoint Rest API go through this document and this MS Q&A discussion.

ContentLicense: CC BY-SA 4.0

Body:
We are trying to setup sharepoint rest api in Azure apim backend. We set up the following apim policy. It is receiving the client token, but , not able to successfully execute rest call in the sharepoint. I am not sure whether we are on the right track. Any input is greatly appreciated. Thank you.

    <send-request ignore-error="true" timeout="20" response-variable-name="bearerToken" mode="new">
        <set-url>{{authorizationServer}}</set-url>
        <set-method>POST</set-method>
        <set-header name="Content-Type" exists-action="override">
            <value>application/x-www-form-urlencoded</value>
        </set-header>
        <set-body>@{
          return "client_id={{clientId}}&scope={{scope}}&client_secret={{clientSecret}}&grant_type=client_credentials";

          // For Azure AD v1, try return statement below
          // return "client_id={{clientId}}&resource={{scope}}&client_secret={{clientSecret}}&grant_type=client_credentials";
      }</set-body>
    </send-request>
    <set-header name="Authorization" exists-action="override">
        <value>@("Bearer " + (String)((IResponse)context.Variables["bearerToken"]).Body.As<JObject>()["access_token"])</value>
    </set-header>

    <set-header name="Ocp-Apim-Subscription-Key" exists-action="delete" />


问:
Grafana and Influx time since last measurement
I want to show time since last measurement from influxDB in grafana. I can't find solution to do that in grafana (because since grafana 7 "Singlestat panel" is deprehended).
I've also tried to calculate difference between last measurement and "now()" in influx, just like below:

```<code>from(bucket: "bucket")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "measurement")
  |> filter(fn: (r) => r["_field"] == "field")
  |> group()
  |> first()
  |> map(fn: (r) => ({ time: uint(v: now()) - uint(v: r._time)}))
</code>```

Unfortunately this is also wrong. Result of that calculation is something like 2112-3-21 18:23:33 and what I'm expecting is 20 min for example.

Do you know any solution?

答: I was trying to do the same thing and found the problem. When you convert time to uint this return nanosecond epoch timestamp. You must divide the result you obtained by 10E9 to obtain the time in seconds</p>

Body:
I want to show time since last measurement from influxDB in grafana. I can't find solution to do that in grafana (because since grafana 7 "Singlestat panel" is deprehended).
I've also tried to calculate difference between last measurement and "now()" in influx, just like below:

from(bucket: "bucket")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "measurement")
  |> filter(fn: (r) => r["_field"] == "field")
  |> group()
  |> first()
  |> map(fn: (r) => ({ time: uint(v: now()) - uint(v: r._time)}))

Unfortunately this is also wrong. Result of that calculation is something like 2112-3-21 18:23:33 and what I'm expecting is 20 min for example.

Do you know any solution?


问:
Theorem euclid_gcd , proving that forall a b z, euclid a b z -> gcd a b z. using coq
i am trying to prove euclid_gcd Theorem but i get stack in the first case !! some help please  :)</p>
```<code>Inductive euclid : nat -> nat -> nat -> Prop :=
| stop : forall z, euclid z z z
| step_a : forall a b z, a > b -> euclid (a - b) b z -> euclid a b z
| step_b : forall a b z, a < b -> euclid a (b - a) z -> euclid a b z.

Inductive gcd : nat -> nat -> nat -> Prop :=
| base : forall z, gcd z z z
| step_a' : forall a b z, gcd a b z -> gcd (a + b) b z
| step_b' : forall a b z, gcd a b z -> gcd a (a + b) z.

Theorem euclid_gcd : forall a b z, euclid a b z -> gcd a b z.
Proof.
intros a b z H.
induction a.
....`
</code>```

答:
I find out how to prove this Theorem . The induction must be at H So we have something to work with  ,</p>
```<code>Theorem euclid_gcd : forall a b z, euclid a b z -> gcd a b z.
Proof.
intros a b z H.
induction H.
 - apply base.
 - apply step_a' in ....
</code>```

Body:
i am trying to prove euclid_gcd Theorem but i get stack in the first case !! some help please  :)

Inductive euclid : nat -> nat -> nat -> Prop :=
| stop : forall z, euclid z z z
| step_a : forall a b z, a > b -> euclid (a - b) b z -> euclid a b z
| step_b : forall a b z, a  euclid a (b - a) z -> euclid a b z.

Inductive gcd : nat -> nat -> nat -> Prop :=
| base : forall z, gcd z z z
| step_a' : forall a b z, gcd a b z -> gcd (a + b) b z
| step_b' : forall a b z, gcd a b z -> gcd a (a + b) z.

Theorem euclid_gcd : forall a b z, euclid a b z -> gcd a b z.
Proof.
intros a b z H.
induction a.
....`

Body:
I find out how to prove this Theorem . The induction must be at H So we have something to work with  ,

Theorem euclid_gcd : forall a b z, euclid a b z -> gcd a b z.
Proof.
intros a b z H.
induction H.
 - apply base.
 - apply step_a' in ....


问:
Apache / PHP Docker containers are just serving the PHP source files and not executing the PHP files correctly
I'm trying to run a Laravel app in my local environment via Docker. I want to setup separate containers for each service i.e. Apache, PHP, MySQL. I also want to keep Composer, Artisan and PHPUnit in separate containers as well. This is more for neatness than anything else.

All the containers spin up with no issues and I can access each one no problems via the 'docker-compose exec [container name] /bin/sh' command.

The problem I'm having is that the index.php in the public folder is not being executed correctly. Apache is just serving up the file contents.

I can't figure out what I'm doing wrong. I've tried using an Nginx container instead of Apache but I get the same issue. I'm guessing my Apache container does not recognize my PHP container.

Is there anything I'm doing wrong below?

My docker-compose.yml file is as follows:

```<code>version: '3.8'

networks:
  cpw:
    name: cpw_network

services:
  apache:
    build:
      context: .
      dockerfile: apache.dockerfile
    container_name: cpw_apache
    depends_on:
      - php
      - mysql
    ports:
      - 8080:80
      - 8443:443
    volumes:
      - ./:/var/www/html
    networks:
      - cpw

  php:
    build:
      context: .
      dockerfile: php.dockerfile
    container_name: cpw_php
    volumes:
      - ./:/var/www/html
    networks:
      - cpw

  mysql:
    image: mysql:5.7.32
    container_name: cpw_mysql
    environment:
      MYSQL_DATABASE: cpw
      MYSQL_USER: laravel
      MYSQL_PASSWORD: secret
      MYSQL_ROOT_PASSWORD: secret
    networks:
      - cpw

  composer:
    image: composer:latest
    container_name: cpw_composer
    volumes:
      - ./:/var/www/html
    working_dir: /var/www/html
    networks:
      - cpw

  artisan:
    build:
      context: .
      dockerfile: php.dockerfile
    container_name: cpw_artisan
    volumes:
      - ./:/var/www/html
    working_dir: /var/www/html
    entrypoint: [ "php", "artisan" ]
    networks:
      - cpw

  phpunit:
    build:
      context: .
      dockerfile: php.dockerfile
    container_name: cpw_phpunit
    volumes:
      - ./:/var/www/html
    working_dir: /var/www/html
    entrypoint: [ "/var/www/html/vendor/bin/phpunit" ]
    networks:
      - cpw
</code>```

My apache.dockerfile is as follows:

```<code>FROM httpd:alpine

ADD ./apache/httpd-vhosts.conf /usr/local/apache2/conf/extra/httpd-vhosts.conf

RUN sed -i 's,#Include conf/extra/httpd-vhosts.conf,Include conf/extra/httpd-vhosts.conf,g' /usr/local/apache2/conf/httpd.conf

RUN mkdir -p /var/www/html
</code>```

My php.dockerfile is as follows:

```<code>FROM php:7.4.12-fpm-alpine

RUN mkdir -p /var/www/html

RUN apk --no-cache add shadow && usermod -u 1000 www-data

RUN docker-php-ext-install pdo pdo_mysql
</code>```

My httpd-vhosts.conf is as follows:

```<code><VirtualHost *:80>
    ServerAdmin email@email.com
    DocumentRoot /var/www/html/public
    ServerName localhost
    ServerAlias localhost
    ErrorLog logs/localhost-error_log
    CustomLog logs/localhost-access_log common

    <Directory /var/www/html/public>
        AllowOverride All
        DirectoryIndex index.php index.php
        Options -Indexes
        Require all granted
    </Directory>
</VirtualHost>
</code>```

Any help appreciated.

Regards,
Stephen

答:
This might also fix:</p>
```<code><FilesMatch \.(?i:php)$>
    SetHandler application/x-httpd-php
</FilesMatch>
</code>```

Body:
I'm trying to run a Laravel app in my local environment via Docker. I want to setup separate containers for each service i.e. Apache, PHP, MySQL. I also want to keep Composer, Artisan and PHPUnit in separate containers as well. This is more for neatness than anything else.

All the containers spin up with no issues and I can access each one no problems via the 'docker-compose exec [container name] /bin/sh' command.

The problem I'm having is that the index.php in the public folder is not being executed correctly. Apache is just serving up the file contents.

I can't figure out what I'm doing wrong. I've tried using an Nginx container instead of Apache but I get the same issue. I'm guessing my Apache container does not recognize my PHP container.

Is there anything I'm doing wrong below?

My docker-compose.yml file is as follows:

version: '3.8'

networks:
  cpw:
    name: cpw_network

services:
  apache:
    build:
      context: .
      dockerfile: apache.dockerfile
    container_name: cpw_apache
    depends_on:
      - php
      - mysql
    ports:
      - 8080:80
      - 8443:443
    volumes:
      - ./:/var/www/html
    networks:
      - cpw

  php:
    build:
      context: .
      dockerfile: php.dockerfile
    container_name: cpw_php
    volumes:
      - ./:/var/www/html
    networks:
      - cpw

  mysql:
    image: mysql:5.7.32
    container_name: cpw_mysql
    environment:
      MYSQL_DATABASE: cpw
      MYSQL_USER: laravel
      MYSQL_PASSWORD: secret
      MYSQL_ROOT_PASSWORD: secret
    networks:
      - cpw

  composer:
    image: composer:latest
    container_name: cpw_composer
    volumes:
      - ./:/var/www/html
    working_dir: /var/www/html
    networks:
      - cpw

  artisan:
    build:
      context: .
      dockerfile: php.dockerfile
    container_name: cpw_artisan
    volumes:
      - ./:/var/www/html
    working_dir: /var/www/html
    entrypoint: [ "php", "artisan" ]
    networks:
      - cpw

  phpunit:
    build:
      context: .
      dockerfile: php.dockerfile
    container_name: cpw_phpunit
    volumes:
      - ./:/var/www/html
    working_dir: /var/www/html
    entrypoint: [ "/var/www/html/vendor/bin/phpunit" ]
    networks:
      - cpw

My apache.dockerfile is as follows:

FROM httpd:alpine

ADD ./apache/httpd-vhosts.conf /usr/local/apache2/conf/extra/httpd-vhosts.conf

RUN sed -i 's,#Include conf/extra/httpd-vhosts.conf,Include conf/extra/httpd-vhosts.conf,g' /usr/local/apache2/conf/httpd.conf

RUN mkdir -p /var/www/html

My php.dockerfile is as follows:

FROM php:7.4.12-fpm-alpine

RUN mkdir -p /var/www/html

RUN apk --no-cache add shadow && usermod -u 1000 www-data

RUN docker-php-ext-install pdo pdo_mysql

My httpd-vhosts.conf is as follows:

<VirtualHost *:80>
    ServerAdmin email@email.com
    DocumentRoot /var/www/html/public
    ServerName localhost
    ServerAlias localhost
    ErrorLog logs/localhost-error_log
    CustomLog logs/localhost-access_log common

    <Directory /var/www/html/public>
        AllowOverride All
        DirectoryIndex index.php index.php
        Options -Indexes
        Require all granted
    </Directory>
</VirtualHost>

Any help appreciated.

Regards,
Stephen

Body:
This might also fix:

<FilesMatch \.(?i:php)$>
    SetHandler application/x-httpd-php
</FilesMatch>


问:
left Join with right table filtered for every rows
I have two tables:

Customer: customer_id

Order: order_id, customer_id, createdAt

I want to retry for every customer the only last order.

I tried to do this:

```<code>    SELECT C.customer_id, ORD.*
    FROM "Customer" as C
    LEFT JOIN (
            SELECT "Order".customer_id, "Order".order_id, "Order"."createdAt"
            FROM "Order", "Customer"
            WHERE "Order".customer_id = "Customer".customer_id
            ORDER BY "Order"."createdAt" DESC limit 1
    ) ORD ON C.customer_id = ORD.customer_id
</code>```

but the result is:

Customer.customer_id
Order.order_id
createdAt

1
null
null

2
null
null

3
123
2022-03-04

The result is correct only for a customer. I lose the information of the others.

I also tried to do this:

```<code>    SELECT  C.customer_id, ORD.*
    FROM    "Customer" as C
    LEFT JOIN "Order" as ORD
    ON ORD.customer_id = (
                    SELECT  ORD.customer_id
                    FROM    "Order" as ORD
                    WHERE   ORD.customer_id = C.customer_id
                    ORDER BY
                                    ORD."createdAt" DESC limit 1
                    )
</code>```

the result in this case is:

Customer.customer_id
Order.order_id
createdAt

1
119
2022-01-04

2
120
2022-01-04

3
123
2022-03-04

3
121
2022-02-04

I have more information about customer 3, when I just need the row where order_id is 123.

I've been working on it for a couple of days, could someone help me? Thanks so much.

答:
You want the most recent order for each customer. But the LIMIT 1 in your subquery means you only get the single most recent order (for any customer).

Let's work out a subquery to get the most recent order for each customer. Start with the date of each customer's most recent order.

            SELECT customer_id, MAX(createdAt) createdAt
              FROM ORD
             GROUP BY customer_id
```
<p>Then let's do an inner join to that subquery. This should get us the detail of the latest order for each customer. Test it to convince yourself it works properly.</p>
<pre class="lang-sql prettyprint-override"><code>        SELECT ORD.*
          FROM ORD
          JOIN (
                SELECT customer_id, MAX(createdAt) createdAt
                  FROM ORD
                 GROUP BY customer_id
               ) latest ON ORD.customer_id = latest.customer_id
                       AND ORD.createdAt = latest.createdAt
</code>```

That's the subquery to use in place of the one you have.

SELECT C.customer_id, ORD.*
FROM "Customer" as C
LEFT JOIN (
        SELECT ORD.*
          FROM ORD
          JOIN (
                SELECT customer_id, MAX(createdAt) createdAt
                  FROM ORD
                 GROUP BY customer_id
               ) latest ON ORD.customer_id = latest.customer_id
                       AND ORD.createdAt = latest.createdAt
    ) ORD ON C.customer_id = ORD.customer_id
```

This sort of thing probably works on multiple database vendors.

Body:
I have two tables:

Customer: customer_id

Order: order_id, customer_id, createdAt

I want to retry for every customer the only last order.

I tried to do this:

    SELECT C.customer_id, ORD.*
    FROM "Customer" as C
    LEFT JOIN (
            SELECT "Order".customer_id, "Order".order_id, "Order"."createdAt"
            FROM "Order", "Customer"
            WHERE "Order".customer_id = "Customer".customer_id
            ORDER BY "Order"."createdAt" DESC limit 1
    ) ORD ON C.customer_id = ORD.customer_id

but the result is:

Customer.customer_id
Order.order_id
createdAt

1
null
null

2
null
null

3
123
2022-03-04

The result is correct only for a customer. I lose the information of the others.

I also tried to do this:

    SELECT  C.customer_id, ORD.*
    FROM    "Customer" as C
    LEFT JOIN "Order" as ORD
    ON ORD.customer_id = (
                    SELECT  ORD.customer_id
                    FROM    "Order" as ORD
                    WHERE   ORD.customer_id = C.customer_id
                    ORDER BY
                                    ORD."createdAt" DESC limit 1
                    )

the result in this case is:

Customer.customer_id
Order.order_id
createdAt

1
119
2022-01-04

2
120
2022-01-04

3
123
2022-03-04

3
121
2022-02-04

I have more information about customer 3, when I just need the row where order_id is 123.

I've been working on it for a couple of days, could someone help me? Thanks so much.

Body:
You want the most recent order for each customer. But the LIMIT 1 in your subquery means you only get the single most recent order (for any customer).

Let's work out a subquery to get the most recent order for each customer. Start with the date of each customer's most recent order.

            SELECT customer_id, MAX(createdAt) createdAt
              FROM ORD
             GROUP BY customer_id

Then let's do an inner join to that subquery. This should get us the detail of the latest order for each customer. Test it to convince yourself it works properly.

        SELECT ORD.*
          FROM ORD
          JOIN (
                SELECT customer_id, MAX(createdAt) createdAt
                  FROM ORD
                 GROUP BY customer_id
               ) latest ON ORD.customer_id = latest.customer_id
                       AND ORD.createdAt = latest.createdAt

That's the subquery to use in place of the one you have.

SELECT C.customer_id, ORD.*
FROM "Customer" as C
LEFT JOIN (
        SELECT ORD.*
          FROM ORD
          JOIN (
                SELECT customer_id, MAX(createdAt) createdAt
                  FROM ORD
                 GROUP BY customer_id
               ) latest ON ORD.customer_id = latest.customer_id
                       AND ORD.createdAt = latest.createdAt
    ) ORD ON C.customer_id = ORD.customer_id

This sort of thing probably works on multiple database vendors.


问:
Apply a function that takes two vectors as input to two matrices across their corresponding columns (in R)
I have a function in R that takes two vectors and an integer like this:

```<code>MyFunction<-function(MyLoot, DungeonLoot, DungeonOrder)
{

  # Perfect Match
  PerfectMatch = MyLoot[1]==DungeonLoot[1]

  # Group Match
  GroupandClassMatch = (MyLoot[2]==DungeonLoot[2])&(MyLoot[3]>=DungeonLoot[3])

  # Order Match
  OrderMatch = MyLoot[5]==DungeonOrder

  # Order Match +1
  OrderMatchPlusOne = (OrderMatch)&(MyLoot[8]==1)

  # Final Score
  Score = PerfectMatch*1 + GroupandClassMatch*1 + OrderMatch*2 + OrderMatchPlusOne*1

  return(Score)
}
</code>```

Now I want to apply MyFunction to two matrices Matrix1 and Matrix2 across their rows so that I have a vector that looks something like:

```<code>c(MyFunction(Matrix1[1,],Matrix2[1,],12),MyFunction(Matrix1[2,],Matrix2[2,],12),...,MyFunction[Matrix1[n,],Matrix2[n,],12)
</code>```

What is the best (and most efficient) way of doing this? I could use a for loop but wondering if there is a better way e.g. using one of apply, sapply, mapply, lappy functions

答:
Your newly posted function is still easily vectorized:</p>
```<code>MyFunction <- function(MyLoot, DungeonLoot, DungeonOrder) {
  # Perfect Match
  PerfectMatch <- MyLoot[1,] == DungeonLoot[1,]

  # Group Match
  GroupandClassMatch <- (MyLoot[2,] == DungeonLoot[2,]) & (MyLoot[3,] >= DungeonLoot[3,])

  # Order Match
  OrderMatch <- MyLoot[5,] == DungeonOrder

  # Order Match +1
  OrderMatchPlusOne <- OrderMatch & (MyLoot[8,] == 1)

  # Final Score
  Score <- PerfectMatch + GroupandClassMatch + OrderMatch*2 + OrderMatchPlusOne

  return(Score)
}

MyFunction(Matrix1, Matrix2, 12)
</code>```

Body:
I have a function in R that takes two vectors and an integer like this:

MyFunction<-function(MyLoot, DungeonLoot, DungeonOrder)
{

  # Perfect Match
  PerfectMatch = MyLoot[1]==DungeonLoot[1]

  # Group Match
  GroupandClassMatch = (MyLoot[2]==DungeonLoot[2])&(MyLoot[3]>=DungeonLoot[3])

  # Order Match
  OrderMatch = MyLoot[5]==DungeonOrder

  # Order Match +1
  OrderMatchPlusOne = (OrderMatch)&(MyLoot[8]==1)

  # Final Score
  Score = PerfectMatch*1 + GroupandClassMatch*1 + OrderMatch*2 + OrderMatchPlusOne*1

  return(Score)
}

Now I want to apply MyFunction to two matrices Matrix1 and Matrix2 across their rows so that I have a vector that looks something like:

c(MyFunction(Matrix1[1,],Matrix2[1,],12),MyFunction(Matrix1[2,],Matrix2[2,],12),...,MyFunction[Matrix1[n,],Matrix2[n,],12)

What is the best (and most efficient) way of doing this? I could use a for loop but wondering if there is a better way e.g. using one of apply, sapply, mapply, lappy functions

Body:
Your newly posted function is still easily vectorized:

MyFunction <- function(MyLoot, DungeonLoot, DungeonOrder) {
  # Perfect Match
  PerfectMatch <- MyLoot[1,] == DungeonLoot[1,]

  # Group Match
  GroupandClassMatch <- (MyLoot[2,] == DungeonLoot[2,]) & (MyLoot[3,] >= DungeonLoot[3,])

  # Order Match
  OrderMatch <- MyLoot[5,] == DungeonOrder

  # Order Match +1
  OrderMatchPlusOne <- OrderMatch & (MyLoot[8,] == 1)

  # Final Score
  Score <- PerfectMatch + GroupandClassMatch + OrderMatch*2 + OrderMatchPlusOne

  return(Score)
}

MyFunction(Matrix1, Matrix2, 12)


问:
Flutter : i want to pass (title,details,content) to details page display it in vertically in top of the details page?
eg: details about the questions ......................................................when i click to a gridview item i want to pass (title,details,content) to details page display in vertically in top of the details page but when i am pass the data not able to fetch the data in details page i created a constrctor in details page not able to set the data in text and image.</p>
```<code>Home Page
----------

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'DetailsPage.dart';
var paddingBottom = 48.0;

class HomePage extends StatelessWidget {
  final String apiUrl = "https://www.sofikart.com/MobileApi/banners";
  final String apiUrl1 =
      "https://wayindia.net/indigo/odia_rashifal/rasifhala.php";

  Future<List<dynamic>> fetchUsers() async {
    var result = await http.get(Uri.parse(apiUrl1));
    return json.decode(result.body)['data'];
  }

  String id(dynamic user) {
    return user['id'];
  }

  String title(dynamic user) {
    return user['title'];
  }

  String content(dynamic user) {
    return user['content'];
  }

  String eng_title(dynamic user) {
    return user['eng_title'];
  }

  String main_img(dynamic user) {
    return user['main_img'];
  }

  String image_2(dynamic user) {
    return user['image_2'];
  }

  String image_3(dynamic user) {
    return user['image_3'];
  }

  String image_4(dynamic user) {
    return user['image_4'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ଆଜିର ରାଶିଫଳ'),
        centerTitle: true,
      ),
      body: Container(
        child: FutureBuilder<List<dynamic>>(
          future: fetchUsers(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              print(id(snapshot.data[0]));

              return GridView.builder(
                itemCount: snapshot.data.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 20,
                  mainAxisSpacing: 25,
                ),
                padding: EdgeInsets.all(13),
                shrinkWrap: true,
                itemBuilder: (ctx, index) {
                  return InkWell(
                    child: Container(
                      decoration: BoxDecoration(
                          color: Colors.transparent,
                          borderRadius: BorderRadius.all(Radius.circular(12))),
                      child: Column(
                        children: [
                          Expanded(
                            flex: 9,
                            child: ClipRRect(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(12)),
                                child: Image.network(
                                    snapshot.data[index]['main_img'],
                                    fit: BoxFit.fill)),
                          ),
                          Expanded(
                              flex: 2,
                              child: Text(
                                title(snapshot.data[index]),
                                style: TextStyle(
                                    color: Colors.black, fontSize: 17),
                              )),
                        ],
                      ),
                    ),
                    onTap: () {
                      print("Click event on Container");
                      Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(builder: (context) => DetailsPage()), (route) => false);
                    },
                  );
                },
              );
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}

Details Page
------------

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:odia_rasiphala/HomePage.dart';
import 'dart:convert';

class DetailsPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return WillPopScope(
        onWillPop: () async => false,
        child: new Scaffold(
          appBar: new AppBar(
            title: new Text('ଆଜିର ରାଶିଫଳ'),
            leading: new IconButton(
              icon: new Icon(Icons.arrow_back_outlined),
              onPressed: () => Navigator.pushReplacement(context,
                  new MaterialPageRoute(builder: (context) => HomePage())),
            ),
            actions: [
              IconButton(
                onPressed: () {},
                icon: Icon(Icons.share),
              ),
            ],
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Image.network(
                '',
                width: 200.0,
                height: 200.0,
              ),
              new Center(
                child: new Text('',style: TextStyle(
                    color: Colors.black,fontSize: 17
                )),
              )
            ],
          ),
        ));
  }
}
</code>```

答:
I am guessing you want to pass "eng_title" and "main_img" to details screen.

To do that first make a constructor in your details pages. Example:

```<code>class DetailScreen extends StatelessWidget {
  // In the constructor, require a Todo.
  const DetailScreen({Key? key, required this.eng_title, required this.main_img}) : super(key: key);

  // Declare a field that holds the strings passed to this class.
  final String eng_title;
  final String main_img;

  @override
  Widget build(BuildContext context) {
    // Use the final parameters to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text(eng.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(main_img),
      ),
    );
  }
}
</code>```

on your OnTap function, when you click an item on the list, just pass the required parameters like this

```<code>onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => DetailScreen(eng_title: snapshot.data[index]['eng_title'], main_img: snapshot.data[index]['main_img']),
          ),
        );
      },
</code>```

This way you can pass data from onescreen to another. Do not use push and remove until, if you want the user to go back to the list in homepage.

For more info about passing data read the following article by flutter:
https://docs.flutter.dev/cookbook/navigation/passing-data

Body:
eg: details about the questions ......................................................when i click to a gridview item i want to pass (title,details,content) to details page display in vertically in top of the details page but when i am pass the data not able to fetch the data in details page i created a constrctor in details page not able to set the data in text and image.

Home Page
----------

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'DetailsPage.dart';
var paddingBottom = 48.0;

class HomePage extends StatelessWidget {
  final String apiUrl = "https://www.sofikart.com/MobileApi/banners";
  final String apiUrl1 =
      "https://wayindia.net/indigo/odia_rashifal/rasifhala.php";

  Future<List<dynamic>> fetchUsers() async {
    var result = await http.get(Uri.parse(apiUrl1));
    return json.decode(result.body)['data'];
  }

  String id(dynamic user) {
    return user['id'];
  }

  String title(dynamic user) {
    return user['title'];
  }

  String content(dynamic user) {
    return user['content'];
  }

  String eng_title(dynamic user) {
    return user['eng_title'];
  }

  String main_img(dynamic user) {
    return user['main_img'];
  }

  String image_2(dynamic user) {
    return user['image_2'];
  }

  String image_3(dynamic user) {
    return user['image_3'];
  }

  String image_4(dynamic user) {
    return user['image_4'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ଆଜିର ରାଶିଫଳ'),
        centerTitle: true,
      ),
      body: Container(
        child: FutureBuilder<List<dynamic>>(
          future: fetchUsers(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              print(id(snapshot.data[0]));

              return GridView.builder(
                itemCount: snapshot.data.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 20,
                  mainAxisSpacing: 25,
                ),
                padding: EdgeInsets.all(13),
                shrinkWrap: true,
                itemBuilder: (ctx, index) {
                  return InkWell(
                    child: Container(
                      decoration: BoxDecoration(
                          color: Colors.transparent,
                          borderRadius: BorderRadius.all(Radius.circular(12))),
                      child: Column(
                        children: [
                          Expanded(
                            flex: 9,
                            child: ClipRRect(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(12)),
                                child: Image.network(
                                    snapshot.data[index]['main_img'],
                                    fit: BoxFit.fill)),
                          ),
                          Expanded(
                              flex: 2,
                              child: Text(
                                title(snapshot.data[index]),
                                style: TextStyle(
                                    color: Colors.black, fontSize: 17),
                              )),
                        ],
                      ),
                    ),
                    onTap: () {
                      print("Click event on Container");
                      Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(builder: (context) => DetailsPage()), (route) => false);
                    },
                  );
                },
              );
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}

Details Page
------------

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:odia_rasiphala/HomePage.dart';
import 'dart:convert';

class DetailsPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return WillPopScope(
        onWillPop: () async => false,
        child: new Scaffold(
          appBar: new AppBar(
            title: new Text('ଆଜିର ରାଶିଫଳ'),
            leading: new IconButton(
              icon: new Icon(Icons.arrow_back_outlined),
              onPressed: () => Navigator.pushReplacement(context,
                  new MaterialPageRoute(builder: (context) => HomePage())),
            ),
            actions: [
              IconButton(
                onPressed: () {},
                icon: Icon(Icons.share),
              ),
            ],
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Image.network(
                '',
                width: 200.0,
                height: 200.0,
              ),
              new Center(
                child: new Text('',style: TextStyle(
                    color: Colors.black,fontSize: 17
                )),
              )
            ],
          ),
        ));
  }
}

Body:
I am guessing you want to pass "eng_title" and "main_img" to details screen.

To do that first make a constructor in your details pages. Example:

class DetailScreen extends StatelessWidget {
  // In the constructor, require a Todo.
  const DetailScreen({Key? key, required this.eng_title, required this.main_img}) : super(key: key);

  // Declare a field that holds the strings passed to this class.
  final String eng_title;
  final String main_img;

  @override
  Widget build(BuildContext context) {
    // Use the final parameters to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text(eng.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(main_img),
      ),
    );
  }
}

on your OnTap function, when you click an item on the list, just pass the required parameters like this

onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => DetailScreen(eng_title: snapshot.data[index]['eng_title'], main_img: snapshot.data[index]['main_img']),
          ),
        );
      },

This way you can pass data from onescreen to another. Do not use push and remove until, if you want the user to go back to the list in homepage.

For more info about passing data read the following article by flutter:
https://docs.flutter.dev/cookbook/navigation/passing-data


问:
How to handle multiple instances of input to one field
I want to add a line in a multiline textbox after every information that the user enters in the TextBox in Windows form. I wont be able to determine the point to draw line as I wont know how long the user will enter information. So I am thinking of adding a  string "_______" after a button click in the code. Is there a better way? </p>

答:
You might consider writing a custom control.

You could either paint the control yourself, or use an autosized label and the control's scollbars.

OwnerDisplayName: LearnOneTime

LastEditorDisplayName: Keltex

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: John Gietzen

ContentLicense: CC BY-SA 2.5


问:
how to import JQuery to another html file
I have a html file and in that i have some html and jquery i want to import the jquery to another html file this is my html code ↓↓↓

```<code> <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Register Form Test JQuery</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        var data = "";
        let arr = [];

        $(document).ready(function() {
            var skills = [];
            var subjects = [];

            $("button").click(function() {
                $.each($("input[name='subject']:checked"), function() {
                    subjects.push($(this).val());

                });

                $.each($("input[name='skill']:checked"), function() {
                    skills.push($(this).val());
                });

                var email = $("#email").val();
                var password = $("#password").val();
                var dob = $("#dob").val();
                var gender = $("#gender").val();
                var address = $("#address").val();
                var city = $("#city").val();
                var telephone = $("#telephone").val();
                var aadhaar = $("#aadhaar").val();
                var role = $("#role").val();

                data = "Email: " + email + ", " + "Password: " + password + ", " + "Date Of Birth: " + dob + ", " + "Gender: " + gender + ", " + "Address: " + address + ", " + "City: " + city + ", " + "Subjects: " + subjects.join(", ") + ", " + "Skills: " + skills.join(", ") + ", " + "Telephone Number: " + telephone + ", " + "Aadhaar Number: " + aadhaar + ", " + "Role: " + role;
                arr.push(data);
                console.log(data)
            });
        });
    </script>
</head>

<body>
    <form>
        <label>Email:</label><br>
        <input id="email" type="email" required><br>
        <label>Date Of Birth:</label><br>
        <input id="dob" type="date" required><br>
        <label>Role:</label><br>
        <select id="role" required>
    <option>Learner</option>
    <option>Educator</option>
    <option>Both</option>
    </select><br>
        <label>Gender:</label><br>
        <select id="gender" required>
      <option>Male</option>
      <option>Female</option>
      <option>other</option>
    </select><br>
        <label>Address:</label><br/>
        <input id="address" type="text" required><br/>
        <label>City:</label><br>
        <input id="city" type="text" required><br>
        <label>Subject/s</label><br>
        <label><input type="checkbox" value="Math" name="subject"> Math</label>
        <label><input type="checkbox" value="Science" name="subject"> Science</label>
        <label><input type="checkbox" value="SST" name="subject"> SST</label>
        <label><input type="checkbox" value="English" name="subject"> English</label>
        <label><input type="checkbox" value="Computer Science" name="subject"> Computer Science</label>
        <label><input type="checkbox" value="Kannada" name="subject"> Kannada</label><br>
        <label><input type="checkbox" value="Hindi" name="subject"> Hindi</label><br>
        <label>Skill/s</label>
        <BR>
        <label><input type="checkbox" value="Drawing/Doodling" name="skill"> Drawing/Doodling</label>
        <label><input type="checkbox" value="Instrument Playing" name="skill"> Instrument Playing</label>
        <label><input type="checkbox" value="Dance and/or Music" name="skill"> Dance and/or Music</label>
        <label><input type="checkbox" value="sports (any)" name="skill"> sports (any)</label><br>
        <label>Telephone Number:</label><br>
        <input type="tel" id="telephone" placeholder="1234-567890" pattern="[0-9]{4}-[0-9]{6}"><br>
        <label>Aadhaar Number (if available):</label><br>
        <input id="aadhaar" placeholder="1234-5678-9000" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}"><br>
        <label>Password:</label><br>
        <input type="password" id="password" required><br><br>
        <button type="button" value="submit">Submit</button>
    </form>
</body>

</html>
</code>```

How do i import the jquery script which is in this html file to another html file which also contains jquery? Is there any code which i need to input in my other file or do i need to link it in this html file?

Thanks for your help!

答:
Just copy CDN scripts to bottom of your body or in head of your HTML tag and that's it.
You can find links here:
https://releases.jquery.com/</p>

Body:
I have a html file and in that i have some html and jquery i want to import the jquery to another html file this is my html code ↓↓↓

 <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Register Form Test JQuery</title>

    <form>
        Email:

        <input id="email" type="email" required>

        Date Of Birth:

        <input id="dob" type="date" required>

        Role:

        <select id="role" required>
    <option>Learner</option>
    <option>Educator</option>
    <option>Both</option>
    </select>

        Gender:

        <select id="gender" required>
      <option>Male</option>
      <option>Female</option>
      <option>other</option>
    </select>

        Address:

        <input id="address" type="text" required>

        City:

        <input id="city" type="text" required>

        Subject/s

        <input type="checkbox" value="Math" name="subject"> Math
        <input type="checkbox" value="Science" name="subject"> Science
        <input type="checkbox" value="SST" name="subject"> SST
        <input type="checkbox" value="English" name="subject"> English
        <input type="checkbox" value="Computer Science" name="subject"> Computer Science
        <input type="checkbox" value="Kannada" name="subject"> Kannada

        <input type="checkbox" value="Hindi" name="subject"> Hindi

        Skill/s

        <input type="checkbox" value="Drawing/Doodling" name="skill"> Drawing/Doodling
        <input type="checkbox" value="Instrument Playing" name="skill"> Instrument Playing
        <input type="checkbox" value="Dance and/or Music" name="skill"> Dance and/or Music
        <input type="checkbox" value="sports (any)" name="skill"> sports (any)

        Telephone Number:

        <input type="tel" id="telephone" placeholder="1234-567890" pattern="[0-9]{4}-[0-9]{6}">

        Aadhaar Number (if available):

        <input id="aadhaar" placeholder="1234-5678-9000" pattern="[0-9]{4}-[0-9]{4}-[0-9]{4}">

        Password:

        <input type="password" id="password" required>

        <button type="button" value="submit">Submit</button>
    </form>

How do i import the jquery script which is in this html file to another html file which also contains jquery? Is there any code which i need to input in my other file or do i need to link it in this html file?

Thanks for your help!


问:
What is the use-case for `CancellationTokenSource.TryReset`?
CancellationTokenSource has a TryReset() member.  The documentation appears so strict as to make me wonder why it exists.

It will only work if no-one has already called Cancel() on it.

It is only valid to use when any previous asynchronous operations issued with its token have completed, which means (I think) that I would need to hang on to my Task object to track whether it is still running

It is not safe to call when someone else is trying to cancel the operation, requiring

So why would people bother with TryReset?  Why not simply create a brand new CancellationTokenSource for every asynchronous operation and then throw it away after the operation completes and cancellation is no longer needed?  Is CancellationTokenSource a terribly expensive object to create?

答:
Here you can find the original issue

Here you can find the related pull request

Let me quote here the Background and Motivation section of the issue

When a library or framework exposes a CancellationToken that usually does not get canceled (e.g. HttpContext.RequestAborted) they often still need to dispose the backing CancellationTokenSource (CTS) after an operation completes rather than reusing it in order to account for callers that might never dispose their registrations.

To use the RequestAborted example, Kestrel disposes the backing CTS after every request where the RequestAborted token is accessed. If Kestrel attempted to reuse the CTS backing the RequestAborted token for future requests in order to reduce allocations, it would risk leaking any undisposed registrations and triggering the undisposed registrations when unrelated requests are aborted.

Another scenario where people want to be able to "reset" a CTS is after calling CancelAfter(). This can already be achieved by calling CancelAfter(Timeout.Infinite), but that's not necessarily obvious unless you read the docs. TryReset() is something that would immediately make sense in this scenario when looking at intellisense completions.

Another benefit is that it's immediately obvious if resetting failed. If you try resetting a timeout with CancelAfter(), you have to check after the call to verify their was no cancellation before or during the call causing CancelAfter() to no-op. This is demonstrated in the second HttpClient usage example.


问:
Why programmable interval timer cannot work while other device work?
My OS can properly handle keyboard and mouse interrupt, but PIT cannot work at all.

void int_handler_32() {
    PIC_send_EOI(0);
    term_printf("-");
    kPrintf("!");
}

void timer_init() {
    kPrintf("!");
    cli();
    uint16_t hz = TIMER_IN_HZ / TIMER_TARGET_HZ;
    outb(0x43, 0x34);
    outb(0x40, hz & 0xFF);
    outb(0x40, hz >> 8);
    // sti();
}

/**************************/

void idt_init() {
    pic_init();
    // PIC_remap(0x20, 0x28);

    idtr.base = (uint32_t)idt;
    idtr.limit = sizeof(idt_entry_t) * 256 - 1;

    for (uint16_t i = 0; i < 256; i++) {
        idt_set_descriptor(i, 0, 0, 0);
    }

#define ADD_INT(n) \
    void isr_wrapper_##n(); \
    idt_set_descriptor(n, 0x08, isr_wrapper_##n, 0x8E)

    ADD_INT(32); // timer
    ADD_INT(33); // keyboard
    ADD_INT(44); // mouse
    ADD_INT(128);// custom

    asm volatile ("lidt %0":: "m" (idtr));

    asm volatile ("sti");
    IRQ_set_mask(0x20);
    IRQ_set_mask(0x21);
    IRQ_set_mask(0x2C);
}

/**************************/

static Queue qKeyboard;
static Queue qMouse;

void int_handler_33() {
    PIC_send_EOI(1);
    uint8_t ch = inb(0x60);
    queue_push(&qKeyboard, &ch);
    // kPrintf("+K %d\n", ch);
}

void int_handler_44() {
    PIC_send_EOI(12);
    uint8_t ch = inb(0x60);
    queue_push(&qMouse, &ch);
    // kPrintf("+M %xb\n", ch);
}
```
<pre class="lang-sh prettyprint-override"><code># codes generate a .s file
for i in 32 33 44 128; do
    cat << EOF
.global isr_wrapper_$i
.type isr_wrapper_$i, @function
isr_wrapper_$i:
    pusha
    cld
    call int_handler_$i
    popa
    iret
EOF
done
</code>```

I've just have no idea now. By outputting to qemu's port 0x3F8, I've confirmed that isr_wrapper 33, 44 are called but 32 aren't.

Can anyone gives some suggestions? I've read the I Can't Get Interrupts Working article on osdev, but cannot find any clue.

After debugging with bochs, the logs shows that IRQ0 is changed but it doesn't signal me.

```<code>01399359954d[PIC   ] IRQ line 0 now high
01399399946d[PIC   ] IRQ line 0 now low
01399399950d[PIC   ] IRQ line 0 now high
01399421000d[PIC   ] IRQ line 1 now high
01399421000d[PIC   ] signalling IRQ #1
01399421032d[PIC   ] IO write to 0x0020 = 0x20
01399421051d[PIC   ] IRQ line 1 now low
01399439946d[PIC   ] IRQ line 0 now low
01399439950d[PIC   ] IRQ line 0 now high
01399479942d[PIC   ] IRQ line 0 now low
01399479946d[PIC   ] IRQ line 0 now high
</code>```

Comparing to line 1(keyboard), it should signal IRQ #0 but it doesn't.
I've searched this question which is quite similar to my problem. His problem is that he doesn't set IF bit with sti, but in my case this couldn't happen as keyboard works.

答:
After carefully checking my code, I've find the reason!

I used to set IMR before the main loop like below (for keyboard and mouse message handling) and have forgotten that (I think I set this mask right after idt_init).

void input_start() {
    outb(0x21, 0xF9);
    outb(0xA1, 0xEF);
}
```

I hard-coded the mask which set the bit zero which make PIC ignore the timer. After remove this function, timer works.

Body:
My OS can properly handle keyboard and mouse interrupt, but PIT cannot work at all.

void int_handler_32() {
    PIC_send_EOI(0);
    term_printf("-");
    kPrintf("!");
}

void timer_init() {
    kPrintf("!");
    cli();
    uint16_t hz = TIMER_IN_HZ / TIMER_TARGET_HZ;
    outb(0x43, 0x34);
    outb(0x40, hz & 0xFF);
    outb(0x40, hz >> 8);
    // sti();
}

/**************************/

void idt_init() {
    pic_init();
    // PIC_remap(0x20, 0x28);

    idtr.base = (uint32_t)idt;
    idtr.limit = sizeof(idt_entry_t) * 256 - 1;

    for (uint16_t i = 0; i < 256; i++) {
        idt_set_descriptor(i, 0, 0, 0);
    }

#define ADD_INT(n) \
    void isr_wrapper_##n(); \
    idt_set_descriptor(n, 0x08, isr_wrapper_##n, 0x8E)

    ADD_INT(32); // timer
    ADD_INT(33); // keyboard
    ADD_INT(44); // mouse
    ADD_INT(128);// custom

    asm volatile ("lidt %0":: "m" (idtr));

    asm volatile ("sti");
    IRQ_set_mask(0x20);
    IRQ_set_mask(0x21);
    IRQ_set_mask(0x2C);
}

/**************************/

static Queue qKeyboard;
static Queue qMouse;

void int_handler_33() {
    PIC_send_EOI(1);
    uint8_t ch = inb(0x60);
    queue_push(&qKeyboard, &ch);
    // kPrintf("+K %d\n", ch);
}

void int_handler_44() {
    PIC_send_EOI(12);
    uint8_t ch = inb(0x60);
    queue_push(&qMouse, &ch);
    // kPrintf("+M %xb\n", ch);
}

# codes generate a .s file
for i in 32 33 44 128; do
    cat << EOF
.global isr_wrapper_$i
.type isr_wrapper_$i, @function
isr_wrapper_$i:
    pusha
    cld
    call int_handler_$i
    popa
    iret
EOF
done

I've just have no idea now. By outputting to qemu's port 0x3F8, I've confirmed that isr_wrapper 33, 44 are called but 32 aren't.

Can anyone gives some suggestions? I've read the I Can't Get Interrupts Working article on osdev, but cannot find any clue.

After debugging with bochs, the logs shows that IRQ0 is changed but it doesn't signal me.

01399359954d[PIC   ] IRQ line 0 now high
01399399946d[PIC   ] IRQ line 0 now low
01399399950d[PIC   ] IRQ line 0 now high
01399421000d[PIC   ] IRQ line 1 now high
01399421000d[PIC   ] signalling IRQ #1
01399421032d[PIC   ] IO write to 0x0020 = 0x20
01399421051d[PIC   ] IRQ line 1 now low
01399439946d[PIC   ] IRQ line 0 now low
01399439950d[PIC   ] IRQ line 0 now high
01399479942d[PIC   ] IRQ line 0 now low
01399479946d[PIC   ] IRQ line 0 now high

Comparing to line 1(keyboard), it should signal IRQ #0 but it doesn't.
I've searched this question which is quite similar to my problem. His problem is that he doesn't set IF bit with sti, but in my case this couldn't happen as keyboard works.

Body:
After carefully checking my code, I've find the reason!

I used to set IMR before the main loop like below (for keyboard and mouse message handling) and have forgotten that (I think I set this mask right after idt_init).

void input_start() {
    outb(0x21, 0xF9);
    outb(0xA1, 0xEF);
}

I hard-coded the mask which set the bit zero which make PIC ignore the timer. After remove this function, timer works.


问:
Change the default folder structure in Azure Function project with Python
I'd like to create a Python project using Azure Functions. When creating, files are allocated into the default layout (as recommended in documentation), so currently my project has the following structure:

```<code>root
 | - function_1
 | | - __init__.py
 | | - function.json
 | - function_2
 | | - __init__.py
 | | - function.json
 | - function_N
 | | - __init__.py
 | | - function.json
 | - src
 | | - __init__.py
 | | - logic
 | - host.json
 | - local.settings.json
 | - requirements.txt
 | - tests
</code>```

The problem is that N might be relatively big (>=10), so in this way the project will become messy very quickly. I'd like the project to be of the following format, with functions being grouped into folders (eg for versioning purpose and just to keep them separately from the code):

```<code>root
 | - v0
 | | - function_1
 | | | - __init__.py
 | | | - function.json
 | | - function_N
 | | | - __init__.py
 | | | - function.json
 | - v1
 | | - function_1
 | | | - __init__.py
 | | | - function.json
 | | - function_M
 | | | - __init__.py
 | | | - function.json
 | - src
 | | - __init__.py
 | | - logic
 | - host.json
 | - local.settings.json
 | - requirements.txt
 | - tests
</code>```

or something close to it, the main aim is to separate functions into separate folders.

However when I'm trying to run a project with such a layout, I get message saying that "No job functions found", or "Unable to find project root. Expecting to find one of host.json, local.settings.json in project root.", if I move host.json to functions folder.

Is there a way to configure project to work with this custom layout, so that functions are discoverable from their grouping directories?

All my functions are HttpTriggers.

I'm using Python3.9.7 and Visual Studio Code Version: 1.63.2 with Azure Functions extension for Visual Studio Code v1.6.0

答:
One of the workaround I did to change the folder structure of the Azure Functions project is:

- Created the Azure Functions Project of1 Http Trigger and 1 Queue Trigger in a separate folder called QueueTriggerFuncs.

- When I Published this Azure Functions Project, got the same default folder structure shown in Microsoft documentation.

- I tried to create a folder manually in the wwwroot folder but it gave me an error called:

409 Conflict: Cannot delete directory. It is either not empty or access is not allowed. in Azure kudu
```
<p><em><strong>So, While publishing the project I unchecked the <code>Run from package</code> setting in Visual Studio Publish Profile:</strong></em></p>
<p><img src="https://i.imgur.com/jzJHiC7.png" alt="enter image description here" /></p>
<p><em><strong>And then published to Azure Function App.</strong></em></p>
<p><em><strong>- Going to Kudu Console (CMD) - seen the same folder structure but this time I'm able to create the folders manually without any error.</strong></em></p>
<p><img src="https://i.imgur.com/TnhluzZ.png" alt="enter image description here" /></p>
<p><em><strong>- Created the new folder as <code>QueueTriggerFuncs</code>.</strong></em>
<em><strong>- Used this command to move my Queue Trigger Functions to the the specific folder created.</strong></em></p>
```mv FunctionsQ QueueTriggerFuncs
```
<p>its kind of format</p>
```mv FunctionFolderName DestinationFolderName
```

And Now this is the modified folder structure as expected:

Where my QueueTriggerFuncs Folder contains only specific functions like Queue Trigger related functions.

Body:
I'd like to create a Python project using Azure Functions. When creating, files are allocated into the default layout (as recommended in documentation), so currently my project has the following structure:

root
 | - function_1
 | | - __init__.py
 | | - function.json
 | - function_2
 | | - __init__.py
 | | - function.json
 | - function_N
 | | - __init__.py
 | | - function.json
 | - src
 | | - __init__.py
 | | - logic
 | - host.json
 | - local.settings.json
 | - requirements.txt
 | - tests

The problem is that N might be relatively big (>=10), so in this way the project will become messy very quickly. I'd like the project to be of the following format, with functions being grouped into folders (eg for versioning purpose and just to keep them separately from the code):

root
 | - v0
 | | - function_1
 | | | - __init__.py
 | | | - function.json
 | | - function_N
 | | | - __init__.py
 | | | - function.json
 | - v1
 | | - function_1
 | | | - __init__.py
 | | | - function.json
 | | - function_M
 | | | - __init__.py
 | | | - function.json
 | - src
 | | - __init__.py
 | | - logic
 | - host.json
 | - local.settings.json
 | - requirements.txt
 | - tests

or something close to it, the main aim is to separate functions into separate folders.

However when I'm trying to run a project with such a layout, I get message saying that "No job functions found", or "Unable to find project root. Expecting to find one of host.json, local.settings.json in project root.", if I move host.json to functions folder.

Is there a way to configure project to work with this custom layout, so that functions are discoverable from their grouping directories?

All my functions are HttpTriggers.

I'm using Python3.9.7 and Visual Studio Code Version: 1.63.2 with Azure Functions extension for Visual Studio Code v1.6.0

Body:
One of the workaround I did to change the folder structure of the Azure Functions project is:

- Created the Azure Functions Project of1 Http Trigger and 1 Queue Trigger in a separate folder called QueueTriggerFuncs.

- When I Published this Azure Functions Project, got the same default folder structure shown in Microsoft documentation.

- I tried to create a folder manually in the wwwroot folder but it gave me an error called:

409 Conflict: Cannot delete directory. It is either not empty or access is not allowed. in Azure kudu

So, While publishing the project I unchecked the Run from package setting in Visual Studio Publish Profile:

And then published to Azure Function App.

- Going to Kudu Console (CMD) - seen the same folder structure but this time I'm able to create the folders manually without any error.

- Created the new folder as QueueTriggerFuncs.
- Used this command to move my Queue Trigger Functions to the the specific folder created.

mv FunctionsQ QueueTriggerFuncs

its kind of format

mv FunctionFolderName DestinationFolderName

And Now this is the modified folder structure as expected:

Where my QueueTriggerFuncs Folder contains only specific functions like Queue Trigger related functions.


问:
Is it possible to have different access privileges on different folders in a GitHub Repository?
I have a GitHub repository with two folders, A and B. The first Folder A needs to require a Pull Requests to commit a change to the code so that I can implement a peer review process. Folder B I would like to be open, where users can commit changes freely, without requiring a Pull Request. Is this something that is possible? Any suggestions of how I could implement this?

答:
No this isn't possible. A pull-request policy is set at the branch level and there is no exclusion option for specific folders. You can use the CODE OWNERS feature to assign required reviewers to the parts that require review and then let people complete their own pull requests if no required reviewers are assigned.

See:

https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners

https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/about-protected-branches#require-pull-request-reviews-before-merging

An other option would be to have people commit changes to FolderB on a separate branch without protection and let GitHub actions merge the changes into target branch while bypassing protections. You'll need to use a Personal Access Token of a repository administrator to bypass the protections.


问:
Forcing a deadlock with MySQL transactions
I'm trying to force a deadlock for a demonstration and with Oracle, it seems to be working, but in MySQL, for some reason, the query goes through...

Why is my example not causing a deadlock??

```<code>@EventListener(ApplicationReadyEvent.class)
public void executeStartupTask() throws Exception {
    LOGGER.info("Connecting to MySQL via: " + databaseUrl);
    LOGGER.info("Seeding database...");
    seedDatabase();

    Thread providerResetThread = new Thread(() -> {
        try {
            Connection connection = getMySQLDataSource().getConnection();
            connection.setAutoCommit(false);

            // 1st device model always GMETER
            updateDeviceModel("E000000001", "GMETER", connection);

            LOGGER.info("Sleep for " + genericTimeoutLength + "  milliseconds");
            Thread.sleep(Integer.parseInt(genericTimeoutLength));

            // 2st device model always EMETER
            updateDeviceModel("E000000002", "EMETER",  connection);

            connection.commit();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    });

    providerResetThread.start();

    // Resetting the model type
    try {
        Connection connection = getMySQLDataSource().getConnection();
        connection.setAutoCommit(false);

        Statement statement = connection.createStatement();

        updateDeviceModel("E000000002", "NONE", connection);
        updateDeviceModel("E000000001", "NONE", connection);

        connection.commit();
    }
    catch(Exception e) {
        e.printStackTrace();
    }

    providerResetThread.join();
    LOGGER.info("EXECUTION SUCCESSFUL!");
}

public void updateDeviceModel(String deviceId, String model, Connection connection) throws SQLException {
    LOGGER.info("Updating model for device " + deviceId);
    PreparedStatement statement = connection.prepareStatement("UPDATE device_entity SET model = '" + model + "' WHERE deviceId = '" + deviceId + "'");
    statement.execute();
}
</code>```

The log goes as following:

```<code>2022-02-08 09:59:32,950 INFO  method: [Thread-2] interview.InterviewApplication (InterviewApplication.java:126) - Updating model for device E000000001
2022-02-08 09:59:32,950 INFO  method: [main] interview.InterviewApplication (InterviewApplication.java:126) - Updating model for device E000000002
2022-02-08 09:59:32,955 INFO  method: [Thread-2] interview.InterviewApplication (InterviewApplication.java:56) - Sleep for 5000  milliseconds
2022-02-08 09:59:37,965 INFO  method: [Thread-2] interview.InterviewApplication (InterviewApplication.java:126) - Updating model for device E000000002
2022-02-08 09:59:37,975 INFO  method: [main] interview.InterviewApplication (InterviewApplication.java:126) - Updating model for device E000000001
2022-02-08 09:59:43,046 INFO  method: [main] interview.InterviewApplication (InterviewApplication.java:92) - EXECUTION SUCCESSFUL!

</code>```

答:
Using your code in the repository that you indicted, I have the expected behaviour as you can see in the following image:

I've used MySQL 5.6 (also in the latest version the same occurs).

Also the code in the repository is not the same you posted here. When using the code you posted here the behaviour does not occur.

If you observe closely:

```<code>updateDeviceModel("E000000001", "GMETER", connection);

updateDeviceModel("E000000001", "NONE", connection);
</code>```

Is using Ids that do not exist in database.

Your seed database uses IDs "E1" and "E2".
In practice you are updating nothing.

Changing your execute statement to

```<code>final int update = statement.executeUpdate();
</code>```

You can see how many records were affected (zero).

So no deadlock occurs.

In your repository code, if you do the same, you will see that one record was updated in each call.

Body:
I'm trying to force a deadlock for a demonstration and with Oracle, it seems to be working, but in MySQL, for some reason, the query goes through...

Why is my example not causing a deadlock??

@EventListener(ApplicationReadyEvent.class)
public void executeStartupTask() throws Exception {
    LOGGER.info("Connecting to MySQL via: " + databaseUrl);
    LOGGER.info("Seeding database...");
    seedDatabase();

    Thread providerResetThread = new Thread(() -> {
        try {
            Connection connection = getMySQLDataSource().getConnection();
            connection.setAutoCommit(false);

            // 1st device model always GMETER
            updateDeviceModel("E000000001", "GMETER", connection);

            LOGGER.info("Sleep for " + genericTimeoutLength + "  milliseconds");
            Thread.sleep(Integer.parseInt(genericTimeoutLength));

            // 2st device model always EMETER
            updateDeviceModel("E000000002", "EMETER",  connection);

            connection.commit();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    });

    providerResetThread.start();

    // Resetting the model type
    try {
        Connection connection = getMySQLDataSource().getConnection();
        connection.setAutoCommit(false);

        Statement statement = connection.createStatement();

        updateDeviceModel("E000000002", "NONE", connection);
        updateDeviceModel("E000000001", "NONE", connection);

        connection.commit();
    }
    catch(Exception e) {
        e.printStackTrace();
    }

    providerResetThread.join();
    LOGGER.info("EXECUTION SUCCESSFUL!");
}

public void updateDeviceModel(String deviceId, String model, Connection connection) throws SQLException {
    LOGGER.info("Updating model for device " + deviceId);
    PreparedStatement statement = connection.prepareStatement("UPDATE device_entity SET model = '" + model + "' WHERE deviceId = '" + deviceId + "'");
    statement.execute();
}

The log goes as following:

2022-02-08 09:59:32,950 INFO  method: [Thread-2] interview.InterviewApplication (InterviewApplication.java:126) - Updating model for device E000000001
2022-02-08 09:59:32,950 INFO  method: [main] interview.InterviewApplication (InterviewApplication.java:126) - Updating model for device E000000002
2022-02-08 09:59:32,955 INFO  method: [Thread-2] interview.InterviewApplication (InterviewApplication.java:56) - Sleep for 5000  milliseconds
2022-02-08 09:59:37,965 INFO  method: [Thread-2] interview.InterviewApplication (InterviewApplication.java:126) - Updating model for device E000000002
2022-02-08 09:59:37,975 INFO  method: [main] interview.InterviewApplication (InterviewApplication.java:126) - Updating model for device E000000001
2022-02-08 09:59:43,046 INFO  method: [main] interview.InterviewApplication (InterviewApplication.java:92) - EXECUTION SUCCESSFUL!

Body:
Using your code in the repository that you indicted, I have the expected behaviour as you can see in the following image:

I've used MySQL 5.6 (also in the latest version the same occurs).

Also the code in the repository is not the same you posted here. When using the code you posted here the behaviour does not occur.

If you observe closely:

updateDeviceModel("E000000001", "GMETER", connection);

updateDeviceModel("E000000001", "NONE", connection);

Is using Ids that do not exist in database.

Your seed database uses IDs "E1" and "E2".
In practice you are updating nothing.

Changing your execute statement to

final int update = statement.executeUpdate();

You can see how many records were affected (zero).

So no deadlock occurs.

In your repository code, if you do the same, you will see that one record was updated in each call.


问:
How to custom sort a pandas dataframe per row by comparing values in columns?
I have a pandas dataframe like this

```<code>import pandas as pd
df = pd.DataFrame({'feature1': ['a', 'b', 'a', 'c', 'b', 'c'],
                   'feature2': ['b', 'a', 'c', 'a', 'c', 'a'],
                   'val': [0.96, 0.96, 0.95, 0.95, 0.94, 0.94]})
df
    feature1    feature2    corr
0   a   b   0.96
1   b   a   0.96
2   a   c   0.95
3   c   a   0.95
4   b   c   0.94
5   c   a   0.94
</code>```

I want to sort individual rows by taking the lexicographical minimum value in feature1 and maximum value in feature2. The resultant dataframe will look like this

```<code>    feature1    feature2    corr
0   a   b   0.96
1   a   b   0.96
2   a   c   0.95
3   a   c   0.95
4   b   c   0.94
5   a   c   0.94
</code>```

答:
You can sort per rows:

```<code>df[['feature1','feature2']] = np.sort(df[['feature1','feature2']], axis=1)
print (df)
  feature1 feature2   val
0        a        b  0.96
1        a        b  0.96
2        a        c  0.95
3        a        c  0.95
4        b        c  0.94
5        a        c  0.94
</code>```

Or filter feature columns and get minimal and maximal values:

```<code>df[['feature1','feature2']] = df.filter(like='feature').agg(['min','max'], axis=1)
</code>```

Body:
I have a pandas dataframe like this

import pandas as pd
df = pd.DataFrame({'feature1': ['a', 'b', 'a', 'c', 'b', 'c'],
                   'feature2': ['b', 'a', 'c', 'a', 'c', 'a'],
                   'val': [0.96, 0.96, 0.95, 0.95, 0.94, 0.94]})
df
    feature1    feature2    corr
0   a   b   0.96
1   b   a   0.96
2   a   c   0.95
3   c   a   0.95
4   b   c   0.94
5   c   a   0.94

I want to sort individual rows by taking the lexicographical minimum value in feature1 and maximum value in feature2. The resultant dataframe will look like this

    feature1    feature2    corr
0   a   b   0.96
1   a   b   0.96
2   a   c   0.95
3   a   c   0.95
4   b   c   0.94
5   a   c   0.94

Body:
You can sort per rows:

df[['feature1','feature2']] = np.sort(df[['feature1','feature2']], axis=1)
print (df)
  feature1 feature2   val
0        a        b  0.96
1        a        b  0.96
2        a        c  0.95
3        a        c  0.95
4        b        c  0.94
5        a        c  0.94

Or filter feature columns and get minimal and maximal values:

df[['feature1','feature2']] = df.filter(like='feature').agg(['min','max'], axis=1)


问:
How do I see previously installed versions of Flutter?
I updated flutter, and it screwed everything up. There's lots of info out there on how to downgrade, but I'm not sure what I need to downgrade to.</p>

答:
in your pubspec.yaml file, search for below line. your number might be different.

```<code>environment:
  sdk: ">=2.16.0 <3.0.0"
</code>```

the first number is your Dart version when you created your project if you didn't change it. for exp my dart version is 2.16.0.

Go to Flutter release notes page. go to announcement of every flutter version and see which flutter version use your Dart version.

Body:
in your pubspec.yaml file, search for below line. your number might be different.

environment:
  sdk: ">=2.16.0 <3.0.0"

the first number is your Dart version when you created your project if you didn't change it. for exp my dart version is 2.16.0.

Go to Flutter release notes page. go to announcement of every flutter version and see which flutter version use your Dart version.


问:
Private API for native application
Is it possible to make a private API to communicate from a native application to a web application ?
Because as the application is installed in the client side, the user can the HTTP request and so he can see the application private key and build a new application based on this key...

Tank you,
Sébastien

答: Limit his private API key just to one application, if it's used from another one, deny access to your API</p>

Title: Private API for native application


问:
Java GWT Image.onErrorHandler is not triggering
I have a image loading problem on GWT.

On server side:

I have a HttpServlet that creates and transfers Captcha images using "https://github.com/chintanbuch/simplecaptcha".

On the client side:

I am calling this servlet by puting a new url to a GWT Image object.

However, even I am using localhost, somethimes the image does not shown. And it never triggers "onError", always "onLoad".

How should I debug it? Please help.

```<code>tbCaptcha = new TextBox();

imgCaptcha = new Image();
imgCaptcha.addErrorHandler(new ErrorHandler() {
    public void onError(ErrorEvent event) {
        d.ce("onCaptcha", "onError", System.currentTimeMillis());
        onCaptcha.execute();
    }
});
imgCaptcha.addLoadHandler(new LoadHandler() {
    public void onLoad(LoadEvent event) {
        d.cr("onCaptcha", "onLoad", System.currentTimeMillis());
    }
});

var login = TGS_LibScaleServletUtils.login();
var newUrl = TGC_CaptchaUtils.newUrl(login.domain, login.port, login.spi);
imgCaptcha.setUrl(newUrl);
</code>```

And yes, I am creating a new URL with a random parameter and using Image.prefetch as below:

```<code>public static String newUrl(CharSequence domain, Integer port, CharSequence spi) {
    var newUrlCaptcha = TGS_UrlBuilderUtils.https()
            .domain(domain).port(port).directory(spi)
            .fileOrServlet(TGS_SURLUtils.LOC_NAME)
            .parameter(TGS_SURLUtils.PARAM_NAME, TGS_CaptchaUtils.SERVLET_REFRESH())
            .parameterRandom("r", 10).toString();
    Image.prefetch(newUrlCaptcha);
    return newUrlCaptcha;
}
</code>```

Client side console:

see the api code in github github

答:
Change to Light browser theme from Dark Dark Theme.
As captcha image is transparent having black colored text, which matches with black background.</p>

Body:
I have a image loading problem on GWT.

On server side:

I have a HttpServlet that creates and transfers Captcha images using "https://github.com/chintanbuch/simplecaptcha".

On the client side:

I am calling this servlet by puting a new url to a GWT Image object.

However, even I am using localhost, somethimes the image does not shown. And it never triggers "onError", always "onLoad".

How should I debug it? Please help.

tbCaptcha = new TextBox();

imgCaptcha = new Image();
imgCaptcha.addErrorHandler(new ErrorHandler() {
    public void onError(ErrorEvent event) {
        d.ce("onCaptcha", "onError", System.currentTimeMillis());
        onCaptcha.execute();
    }
});
imgCaptcha.addLoadHandler(new LoadHandler() {
    public void onLoad(LoadEvent event) {
        d.cr("onCaptcha", "onLoad", System.currentTimeMillis());
    }
});

var login = TGS_LibScaleServletUtils.login();
var newUrl = TGC_CaptchaUtils.newUrl(login.domain, login.port, login.spi);
imgCaptcha.setUrl(newUrl);

And yes, I am creating a new URL with a random parameter and using Image.prefetch as below:

public static String newUrl(CharSequence domain, Integer port, CharSequence spi) {
    var newUrlCaptcha = TGS_UrlBuilderUtils.https()
            .domain(domain).port(port).directory(spi)
            .fileOrServlet(TGS_SURLUtils.LOC_NAME)
            .parameter(TGS_SURLUtils.PARAM_NAME, TGS_CaptchaUtils.SERVLET_REFRESH())
            .parameterRandom("r", 10).toString();
    Image.prefetch(newUrlCaptcha);
    return newUrlCaptcha;
}

Client side console:

see the api code in github github


问:
Altium Designer - Reserve Old Reference Designators
I have a design I am looking to iterate on. I would look to delete some components and add some new ones. How can I configure Altium Designer so that when the new components are annotated they do not acquire a reference designator that formerly belonged to a now-deleted component?</p>

答: You could copy, paste and quickly annotate new component. You can delete the older one in a second moment.</p>


问:
Can Postman render a file from a base64 string?
One of my server responses is returning a PDF as a base 64 encoded string.

E.g.

```<code>{
    "fileName": "my-file.pdf",
    "base64EncodedFileContent": "JVBERi0xLjcKJeLjz9MNCj...
</code>```

Is it possible to render this 64 bit string as a PDF inside my Postman collection?

I've looked at decoding the string into an environment variable using CryptoJS.enc.Base64.parse

I've also looked at https://docs.postman-echo.com/ to perhaps send the bytes back to me with a content type of application/pdf, however it nests any body you send inside a JSON object.

Note:  This is just a tool of convenience to prevent people using the collection from having to use an external base64 -> PDF converter

答:
You shouldn't need to import CryptoJS to decode base64... you could use something like this;

```<code>const response = pm.response.json().base64EncodedFileContent;
var decodedMessage = atob(response);
console.log(decodedMessage);
</code>```

This might also help with 'vizualising' PDF's in Postman
https://community.postman.com/t/visualize-pdf-on-postman-v8-4-0/23856

Body:
One of my server responses is returning a PDF as a base 64 encoded string.

E.g.

{
    "fileName": "my-file.pdf",
    "base64EncodedFileContent": "JVBERi0xLjcKJeLjz9MNCj...

Is it possible to render this 64 bit string as a PDF inside my Postman collection?

I've looked at decoding the string into an environment variable using CryptoJS.enc.Base64.parse

I've also looked at https://docs.postman-echo.com/ to perhaps send the bytes back to me with a content type of application/pdf, however it nests any body you send inside a JSON object.

Note:  This is just a tool of convenience to prevent people using the collection from having to use an external base64 -> PDF converter

Body:
You shouldn't need to import CryptoJS to decode base64... you could use something like this;

const response = pm.response.json().base64EncodedFileContent;
var decodedMessage = atob(response);
console.log(decodedMessage);

This might also help with 'vizualising' PDF's in Postman
https://community.postman.com/t/visualize-pdf-on-postman-v8-4-0/23856


问:
making reference to file two by two in a bash command
I have this list of file that I have to analyse by pair (the a_1 with a_2, b_1 with b_2 and so on)

```<code>a_1.fq
a_2.fq
b_1.fq
b_2.fq
c_1.fq
...
</code>```

I want to set a for loop to make reference to these pairs of file in a command, bellow
this is just an example of what I want to do (with a false syntax) :

```<code>$ for File1 File2 in *1.fq *2.fq; do STAR --readFilein File1 File2 ; done
</code>```

Thank you a lot for your help

答:
You can iterate over just one type of the files and use parameter expansion to device the second one:

for file1 in *1.fq; do
    file2=${file1%1.fq}2.fq
    ...
```
<p>The <code>%pattern</code> removes the pattern from the end of the variable's value.</p>
<p>You might want to check for the file2's existence before running the command.</p>
<p>Or, if you can get the files listed in the way the pairs are adjacent, you can populate <code>$@</code> with them and <code>shift</code> the parameters by two:</p>
<pre class="lang-sh prettyprint-override"><code>set -- [a-z]_[12].fq
while (( $# )) ; do
    file1=$1
    file2=$2
    shift 2
    ...
done
</code>```

Body:
I have this list of file that I have to analyse by pair (the a_1 with a_2, b_1 with b_2 and so on)

a_1.fq
a_2.fq
b_1.fq
b_2.fq
c_1.fq
...

I want to set a for loop to make reference to these pairs of file in a command, bellow
this is just an example of what I want to do (with a false syntax) :

$ for File1 File2 in *1.fq *2.fq; do STAR --readFilein File1 File2 ; done

Thank you a lot for your help

Body:
You can iterate over just one type of the files and use parameter expansion to device the second one:

for file1 in *1.fq; do
    file2=${file1%1.fq}2.fq
    ...

The %pattern removes the pattern from the end of the variable's value.

You might want to check for the file2's existence before running the command.

Or, if you can get the files listed in the way the pairs are adjacent, you can populate $@ with them and shift the parameters by two:

set -- [a-z]_[12].fq
while (( $# )) ; do
    file1=$1
    file2=$2
    shift 2
    ...
done


问:
Apollo Client Error: Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>
I am new to do this Apollo.

I am currently trying to get create an app with React and Apollo.

When I start my application, I am getting the following error:

Could not find "client" in the context or passed in as an option. Wrap the root component in an , or pass an ApolloClient instance in via options.

```<code>Here is my RegisterController -> index.tsx

import * as React from "react";
import { ChildMutateProps, graphql } from 'react-apollo';
import gql from 'graphql-tag';

interface Props {
  children: (
    data: { submit: (values: any) => Promise<null> }
  ) => JSX.Element | null;
}

class C extends React.PureComponent<ChildMutateProps<Props, any, any>> {
  submit = async (values: any) => {
    console.log(values);

    const response = await this.props.mutate({
      variables: values
    });

    console.log('response: ', response);

    return null;
  };

  render() {
    return this.props.children({ submit: this.submit });
  }
}

const registerMutation = gql`
  mutation($email: String!, $password: String!) {
    register(email: $email, password: $password) {
      path
      message
    }
  }
`;

export const RegisterController = graphql(registerMutation)(C);
</code>```

Here is my main index.tsx

```<code>import React from 'react';
import ReactDOM from 'react-dom';

import reportWebVitals from './reportWebVitals';
import { ApolloProvider } from 'react-apollo';
import { client } from './apollo';
import { Routes } from './routes';
import "./index.css";

ReactDOM.render(
  <ApolloProvider client={client}>
    <React.StrictMode>
      <Routes />
    </React.StrictMode>
  </ApolloProvider>,
  document.getElementById('root')
);
</code>```

Finally, here is my package.json

```<code>{
  "name": "@abb/controller",
  "version": "1.0.0",
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
  "license": "MIT",
  "scripts": {
    "build": "rm -rf ./dist && tsc"
  },
  "dependencies": {
    "graphql": "^15.4.0",
    "graphql-tag": "^2.11.0",
    "react": "^17.0.1",
    "react-apollo": "^3.1.5",
    "react-dom": "^17.0.1"
  },
  "devDependencies": {
    "@types/node": "^14.14.20",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "tslint": "^6.1.3",
    "tslint-config-prettier": "^1.18.0",
    "typescript": "^4.1.3"
  }
}
</code>```

As you can see in my index.tsx, it is wrapped with ApolloProvider with the client passing in there.
Why I am getting this error?
Could anyone please help me with this issue?

Thank you.

答:
I had luck with downgrading @apollo/client from v3.5.x to v3.4.17, and my tests (which is where I got this error) started passing again.

npm i @apollo/client@3.4.17

Body:
I am new to do this Apollo.

I am currently trying to get create an app with React and Apollo.

When I start my application, I am getting the following error:

Could not find "client" in the context or passed in as an option. Wrap the root component in an , or pass an ApolloClient instance in via options.

Here is my RegisterController -> index.tsx

import * as React from "react";
import { ChildMutateProps, graphql } from 'react-apollo';
import gql from 'graphql-tag';

interface Props {
  children: (
    data: { submit: (values: any) => Promise<null> }
  ) => JSX.Element | null;
}

class C extends React.PureComponent<ChildMutateProps<Props, any, any>> {
  submit = async (values: any) => {
    console.log(values);

    const response = await this.props.mutate({
      variables: values
    });

    console.log('response: ', response);

    return null;
  };

  render() {
    return this.props.children({ submit: this.submit });
  }
}

const registerMutation = gql`
  mutation($email: String!, $password: String!) {
    register(email: $email, password: $password) {
      path
      message
    }
  }
`;

export const RegisterController = graphql(registerMutation)(C);

Here is my main index.tsx

import React from 'react';
import ReactDOM from 'react-dom';

import reportWebVitals from './reportWebVitals';
import { ApolloProvider } from 'react-apollo';
import { client } from './apollo';
import { Routes } from './routes';
import "./index.css";

ReactDOM.render(
  <ApolloProvider client={client}>
    <React.StrictMode>
      <Routes />
    </React.StrictMode>
  </ApolloProvider>,
  document.getElementById('root')
);

Finally, here is my package.json

{
  "name": "@abb/controller",
  "version": "1.0.0",
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
  "license": "MIT",
  "scripts": {
    "build": "rm -rf ./dist && tsc"
  },
  "dependencies": {
    "graphql": "^15.4.0",
    "graphql-tag": "^2.11.0",
    "react": "^17.0.1",
    "react-apollo": "^3.1.5",
    "react-dom": "^17.0.1"
  },
  "devDependencies": {
    "@types/node": "^14.14.20",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "tslint": "^6.1.3",
    "tslint-config-prettier": "^1.18.0",
    "typescript": "^4.1.3"
  }
}

As you can see in my index.tsx, it is wrapped with ApolloProvider with the client passing in there.
Why I am getting this error?
Could anyone please help me with this issue?

Thank you.


问:
Is it possible to show a UIImagePickerController at full screen in iPad?
I'm currently working on the iPad version of an app, where I used UIImagePickerController to let the user pick a photo from their library.

In the iPad an error message suggests using a popover, but I can't show my imagepicker at fullscreen. Is it possible?

I'm being told that it can be done using presentModalViewController. If so can anyone point me to a tutorial?

答:
It is possible!

Just remove this:

```<code>UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:picker];
[popoverController presentPopoverFromRect:frame
                                   inView:self.view
                 permittedArrowDirections:UIPopoverArrowDirectionAny
                                 animated:YES];
</code>```

And use this instead:

```<code>[self presentModalViewController:picker animated:YES];
</code>```

Where picker is your UIImagePickerController.

Body:
It is possible!

Just remove this:

UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:picker];
[popoverController presentPopoverFromRect:frame
                                   inView:self.view
                 permittedArrowDirections:UIPopoverArrowDirectionAny
                                 animated:YES];

And use this instead:

[self presentModalViewController:picker animated:YES];

Where picker is your UIImagePickerController.


问:
c# Convert struct to another struct
Is there any way, how to convert this:

```<code>namespace Library
{
    public struct Content
    {
        int a;
        int b;
    }
}
</code>```

I have struct in Library2.Content that has data defined same way
({ int a; int b; }), but different methods.

Is there a way to convert a struct instance from Library.Content to Library2.Content?  Something like:

```<code>Library.Content c1 = new Library.Content(10, 11);
Library2.Content c2 = (Libary2.Content)(c1); //this doesn't work
</code>```

答:
A bit late to the game. But if the structs match I used this in the past

```<code>public static object CastTo(ref object obj, Type type)
{
    var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type));
    try
    {
        Marshal.StructureToPtr(obj, ptr, false);
        return Marshal.PtrToStructure(ptr, type);
    }
    finally
    {
        Marshal.FreeHGlobal(ptr);
    }
}
</code>```

Thanks to @avi_sweden for pointing out that the allocated memory should be freed

Title: c# Convert struct to another struct

Body:
Is there any way, how to convert this:

namespace Library
{
    public struct Content
    {
        int a;
        int b;
    }
}

I have struct in Library2.Content that has data defined same way
({ int a; int b; }), but different methods.

Is there a way to convert a struct instance from Library.Content to Library2.Content?  Something like:

Library.Content c1 = new Library.Content(10, 11);
Library2.Content c2 = (Libary2.Content)(c1); //this doesn't work

Body:
A bit late to the game. But if the structs match I used this in the past

public static object CastTo(ref object obj, Type type)
{
    var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type));
    try
    {
        Marshal.StructureToPtr(obj, ptr, false);
        return Marshal.PtrToStructure(ptr, type);
    }
    finally
    {
        Marshal.FreeHGlobal(ptr);
    }
}

Thanks to @avi_sweden for pointing out that the allocated memory should be freed


问:
SwiftUI customButton / view alignement issue in HStack
I have a row of custom buttons displayed in a VStack and a HStack, strangely the 2 rows are not aligning - see the example for the best I could achieve.
I suspect that it is due to the different content (text or SFSymbol) but the buttons "look" the same size.
To get this I had to have different spacing within the HStacks which.

Thanks

```<code>import Foundation
import SwiftUI

struct MyRoundButton: ButtonStyle {

    var color: Color = .purple

    func makeBody(configuration: Configuration) -> some View {

        configuration

            .label
            .frame(height: 30)
            .font(Font.system(size: 25, weight: .semibold))
            .foregroundColor(configuration.isPressed ? .white : color)
            .padding(23)
            .background(
                Circle()
                    .fill(configuration.isPressed ? color : color.opacity(0.25)))

    }
}

import SwiftUI

struct ContentView: View {

    var body: some View {

        VStack(spacing: 30) {

            HStack(alignment: .center, spacing: 23) {
                Group {
                    Button {

                        print ("didTap roundButton")

                    } label: {
                        Image(systemName: "camera.fill")
                    }

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Image(systemName: "photo.fill.on.rectangle.fill")
                    }

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Image(systemName: "folder.fill")
                    }

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Image(systemName: "trash.fill")

                    }.buttonStyle(MyRoundButton(color: .red))

                }.buttonStyle(MyRoundButton())
            }

            HStack(alignment: .center, spacing: 27) {

                Group {
                    Button {

                        print ("didTap roundButton")

                    } label: {

                        Text("Ja")

                    }.buttonStyle(MyRoundButton(color: .green))

                    Button {
                        print ("didTap roundButton")
                    } label: {
                        Text("Ja")

                    }.buttonStyle(MyRoundButton(color: .blue))

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Text("Ja")
                    }.buttonStyle(MyRoundButton(color: .orange))

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Text("Ja")

                    }.buttonStyle(MyRoundButton(color: .yellow))

                }.buttonStyle(MyRoundButton())
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

答:
Fixed size worked as suggested, thanks.</p>
```<code>   import Foundation
   import SwiftUI

       struct MyRoundButton: ButtonStyle {

            var color: Color = .purple

            func makeBody(configuration: Configuration) -> some View {

                configuration
                    .label
                    .frame(width: 30, height: 30, alignment: .center)
                    .font(Font.system(size: 25, weight: .semibold))
                    .foregroundColor(configuration.isPressed ? .white : color)
                    .padding(23)
                    .background(
                        Circle()
                            .fill(configuration.isPressed ? color : color.opacity(0.25)))
            }
        }
</code>```

Body:
I have a row of custom buttons displayed in a VStack and a HStack, strangely the 2 rows are not aligning - see the example for the best I could achieve.
I suspect that it is due to the different content (text or SFSymbol) but the buttons "look" the same size.
To get this I had to have different spacing within the HStacks which.

Thanks

import Foundation
import SwiftUI

struct MyRoundButton: ButtonStyle {

    var color: Color = .purple

    func makeBody(configuration: Configuration) -> some View {

        configuration

            .label
            .frame(height: 30)
            .font(Font.system(size: 25, weight: .semibold))
            .foregroundColor(configuration.isPressed ? .white : color)
            .padding(23)
            .background(
                Circle()
                    .fill(configuration.isPressed ? color : color.opacity(0.25)))

    }
}

import SwiftUI

struct ContentView: View {

    var body: some View {

        VStack(spacing: 30) {

            HStack(alignment: .center, spacing: 23) {
                Group {
                    Button {

                        print ("didTap roundButton")

                    } label: {
                        Image(systemName: "camera.fill")
                    }

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Image(systemName: "photo.fill.on.rectangle.fill")
                    }

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Image(systemName: "folder.fill")
                    }

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Image(systemName: "trash.fill")

                    }.buttonStyle(MyRoundButton(color: .red))

                }.buttonStyle(MyRoundButton())
            }

            HStack(alignment: .center, spacing: 27) {

                Group {
                    Button {

                        print ("didTap roundButton")

                    } label: {

                        Text("Ja")

                    }.buttonStyle(MyRoundButton(color: .green))

                    Button {
                        print ("didTap roundButton")
                    } label: {
                        Text("Ja")

                    }.buttonStyle(MyRoundButton(color: .blue))

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Text("Ja")
                    }.buttonStyle(MyRoundButton(color: .orange))

                    Button {
                        print ("didTap roundButton")

                    } label: {
                        Text("Ja")

                    }.buttonStyle(MyRoundButton(color: .yellow))

                }.buttonStyle(MyRoundButton())
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Body:
Fixed size worked as suggested, thanks.

   import Foundation
   import SwiftUI

       struct MyRoundButton: ButtonStyle {

            var color: Color = .purple

            func makeBody(configuration: Configuration) -> some View {

                configuration
                    .label
                    .frame(width: 30, height: 30, alignment: .center)
                    .font(Font.system(size: 25, weight: .semibold))
                    .foregroundColor(configuration.isPressed ? .white : color)
                    .padding(23)
                    .background(
                        Circle()
                            .fill(configuration.isPressed ? color : color.opacity(0.25)))
            }
        }