问:
Cancel firebase function
Is it possible to cancel Firebase HTTPS Callable function during it's request?
I have a function with some predictive search. It is called each time when user inputs a character in a search field.

Code:

```<code>func startSearch(_ query: String, completion: @escaping (_ results: [SearcheResults]) -> Void) {

    let data = [
        "query": query
    ]

    functions.httpsCallable("startSearch").call(data) { (result, error) in

        if error != nil {
          completion([])
      } else if let data = result?.data {
            // some data manipulations
            completion(elements)
        }
    }
}
</code>```

Or maybe somehow dismiss earlier completions? Because for now, if user is very rapid and enter text, for example "Berlin" - completion will fire 6 times. I'd like to have a way to cancel a function or cancel previous completions.

Thanks in advance.

答: Once you invoke a callable function, it can't be canceled. The function will run to completion or timeout.  You will need to be sure on the client that you really want to invoke the function.  You are by no means obliged to consume the result (you can ignore it if you want), but the transaction will complete, unless the client app dies in the process.  In that case, the function on the backend will still complete, but it will just not be able to deliver the response.

Title: Cancel firebase function

Body:
Is it possible to cancel Firebase HTTPS Callable function during it's request?
I have a function with some predictive search. It is called each time when user inputs a character in a search field.

Code:

func startSearch(_ query: String, completion: @escaping (_ results: [SearcheResults]) -> Void) {

    let data = [
        "query": query
    ]

    functions.httpsCallable("startSearch").call(data) { (result, error) in

        if error != nil {
          completion([])
      } else if let data = result?.data {
            // some data manipulations
            completion(elements)
        }
    }
}

Or maybe somehow dismiss earlier completions? Because for now, if user is very rapid and enter text, for example "Berlin" - completion will fire 6 times. I'd like to have a way to cancel a function or cancel previous completions.

Thanks in advance.


来源: stackexchange

问:
How to concatenate indefinite number of arrays of Javascript objects
I have an array of Groups s.t. each Group has many Users

I want to return all (unique) Users for a given array of Groups.

So far, I have

```<code>  let actor = await User.query().findById(req.user.id).eager('groups') // find the actor requesting

let actor_groups = actor.groups // find all groups of actor

  if (actor_groups.length > 1)
    var actor_groups_users = actor_groups[0].user
    for (let i = 0; i < actor_groups.length; i++) {
      const actor_groups_users = actor_groups_users.concat(actor_groups[i]);
    }
    console.log('actor groups users is', actor_groups_users);
  else
    // return users from the first (only) group
</code>```

which returns the error: actor_groups_users is not defined

Feels like a roundabout way to do this. Is there a way to just combine actor_groups into a single combined group?

答:
You can simply do this:

```<code>const allGroupsArrs = actor_groups.map(({ user }) => user);
const actor_groups_users = [].concat(...allGroupArrs);
</code>```

Or, you could simply use the .flat() method, which is not yet officially part of the ES standard, but is on its way there and has browser support outside of IE:

```<code>const allGroupsArrs = actor_groups.map(({ user }) => user);
const actor_groups_users = allGroupArrs.flat();
</code>```

Also, the above would result in duplicate values in actor_groups_users if there are people who are in multiple groups. You can remedy this (assuming the array elements are primitive values) using a Set:

```<code>const unique_users = [...new Set(actor_groups_users)];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array of Groups s.t. each Group has many Users

I want to return all (unique) Users for a given array of Groups.

So far, I have

  let actor = await User.query().findById(req.user.id).eager('groups') // find the actor requesting

let actor_groups = actor.groups // find all groups of actor

  if (actor_groups.length > 1)
    var actor_groups_users = actor_groups[0].user
    for (let i = 0; i < actor_groups.length; i++) {
      const actor_groups_users = actor_groups_users.concat(actor_groups[i]);
    }
    console.log('actor groups users is', actor_groups_users);
  else
    // return users from the first (only) group

which returns the error: actor_groups_users is not defined

Feels like a roundabout way to do this. Is there a way to just combine actor_groups into a single combined group?

Body:
You can simply do this:

const allGroupsArrs = actor_groups.map(({ user }) => user);
const actor_groups_users = [].concat(...allGroupArrs);

Or, you could simply use the .flat() method, which is not yet officially part of the ES standard, but is on its way there and has browser support outside of IE:

const allGroupsArrs = actor_groups.map(({ user }) => user);
const actor_groups_users = allGroupArrs.flat();

Also, the above would result in duplicate values in actor_groups_users if there are people who are in multiple groups. You can remedy this (assuming the array elements are primitive values) using a Set:

const unique_users = [...new Set(actor_groups_users)];


问:
finding div height problem and changing margins commensurately
The various content DIVs show up in a slideshow style (I'm using Malsup's Cycle plugin) a single one at a time, but have differing heights (individually, and at different times the largest height may be different). The news div has the height of the highest content DIV. I would like to center the content DIVs vertically within the news DIV. Is there a simple way to do this with CSS? Or should I use jquery to calculate the height of newsWrapper, subtract the newsNav heights, and news from it, halve that and then add it as margin-top for each of the content DIVs?

```<code><div id="newsWrapper">
  <div id="newsNavTop">
  </div>
  <div id="news">
    <div>Content1</div>
    <div>Content2</div>
    <div>Content etc...</div>
  </div>
  <div id="newsNavBottom">
  </div>
</div>
</code>```

答:
"Or should I use jquery to calculate the height of newsWrapper, subtract the newsNav heights, and news from it, halve that and then add it as margin-top for each of the content DIVs?"

This.  Padding-top works too.

ContentLicense: CC BY-SA 3.0

Body:
The various content DIVs show up in a slideshow style (I'm using Malsup's Cycle plugin) a single one at a time, but have differing heights (individually, and at different times the largest height may be different). The news div has the height of the highest content DIV. I would like to center the content DIVs vertically within the news DIV. Is there a simple way to do this with CSS? Or should I use jquery to calculate the height of newsWrapper, subtract the newsNav heights, and news from it, halve that and then add it as margin-top for each of the content DIVs?

Content1

Content2

Content etc...


问:
Connecting PostgreSQL installed in docker inside Hyper-V Ubuntu from Windows 10 PgAdmin
I need help in connecting PostgreSQL which is installed in Docker inside HyperV ubuntu 18.4 from Windows 10 PgAdmin. So far I tried the following

Step 1: Install Postgres in Docker (Ubuntu running on Hyper-V)

```<code>sudo docker run -p 5432:5432 --name pg_test -e POSTGRES_PASSWORD=admin -d postgres
</code>```

Step 2: Create a database

```<code>docker exec -it pg_test bash
psql -U postgres
create database mytestdb
</code>```

Step 3: Get the ip address

```<code>sudo docker inspect pg_test | grep IPAddress
//returned with 172.17.0.2
</code>```

Step 4: pg_hba.conf

```<code>host    all             all             0.0.0.0/0               md5
</code>```

Step 5: When I try to connect from Windows PgAdmin 4, I get this below error -
Note: I have also tried using UBUNTU VM IP address, but no luck

答: You don't need container IP. Since you have mapped container port to host machine (Ubuntu) anyone outsider just needs the Ubuntu machine IP, and on Ubuntu itself you can use localhost.

Body:
I need help in connecting PostgreSQL which is installed in Docker inside HyperV ubuntu 18.4 from Windows 10 PgAdmin. So far I tried the following

Step 1: Install Postgres in Docker (Ubuntu running on Hyper-V)

sudo docker run -p 5432:5432 --name pg_test -e POSTGRES_PASSWORD=admin -d postgres

Step 2: Create a database

docker exec -it pg_test bash
psql -U postgres
create database mytestdb

Step 3: Get the ip address

sudo docker inspect pg_test | grep IPAddress
//returned with 172.17.0.2

Step 4: pg_hba.conf

host    all             all             0.0.0.0/0               md5

Step 5: When I try to connect from Windows PgAdmin 4, I get this below error -
Note: I have also tried using UBUNTU VM IP address, but no luck


问:
UPDATE statement pyodbc set NULL value (instead of None) in sql server
I have code where I want to update certain entries in a database.
Some attributes can have a NULL value.

Let's look at following situation:

```<code>new_doc_name = doc_name (can be None or string value)

sql = UPDATE Documents SET DocName = new_doc_name WHERE DocID = doc_id
cursor.execute(sql);
cursor.commit()
</code>```

When new_doc_name is None, the value in the database is set as None, but I want it to be set as NULL.

When doing the same for INSERT, the values are set as NULL instead of None, which I want. I can't, however, replicate this with the UPDATE statement.

答:
You'll want to use a parameterized query:</p>

```<code>sql = "UPDATE Documents SET DocName = ? WHERE DocID = ?"
cursor.execute(sql, new_doc_name, doc_id);
</code>```

Body:
I have code where I want to update certain entries in a database.
Some attributes can have a NULL value.

Let's look at following situation:

new_doc_name = doc_name (can be None or string value)

sql = UPDATE Documents SET DocName = new_doc_name WHERE DocID = doc_id
cursor.execute(sql);
cursor.commit()

When new_doc_name is None, the value in the database is set as None, but I want it to be set as NULL.

When doing the same for INSERT, the values are set as NULL instead of None, which I want. I can't, however, replicate this with the UPDATE statement.

Body:
You'll want to use a parameterized query:

sql = "UPDATE Documents SET DocName = ? WHERE DocID = ?"
cursor.execute(sql, new_doc_name, doc_id);


问:
SQLite query with 3 entities in Hibernate 4 (nested join?)
I have the following tables in my database (SQLite):

```<code>CREATE TABLE product (
    id INTEGER NOT NULL,
    name TEXT,
    PRIMARY KEY (id)
)

CREATE TABLE feedback(
  product INTEGER PRIMARY KEY,
  score NUMERIC,
  textnote VARCHAR(255),
  FOREIGN KEY(product) REFERENCES product(id)
)

CREATE TABLE product_detail (
    id INTEGER NOT NULL,
    product INTEGER,
    description TEXT,
    url VARCHAR,
    PRIMARY KEY (id),
    FOREIGN KEY(product) REFERENCES product (id),
)
</code>```

So feedback is in a one-to-one relationship with product and product_detail is in a many-to-one relationship with product.

I am trying to write a SQLite query for Hibernate 4 that will give me all the attributes from the 3 tables in one single table. All I came with by far is this:

```<code>String hql = "SELECT p.id, p.name, d.id, d.description, d.url " +
            "FROM ProductDetail d INNER JOIN d.product AS p";
</code>```

I'm correctly obtaining the values I want from product and product_detail. How can I add to the query also the information in feedback? I know all products have at least one product detail, but I can't say the same about feedback: most of the products don't have a feedback. I think I should use a LEFT JOIN but I can't figure out how...
Note that as I'm using Hibernate I have all classes relative to the tables in my application (Feedback, ProductDetail and Product).

答:
You must also join feedback:

```<code>SELECT
  p.id, p.name,
  f.score, f.textxnote,
  d.id, d.description, d.url
FROM product p
INNER JOIN feedback f ON f.product = p.id
INNER JOIN ProductDetail d ON d.product = p.id
</code>```

You may change to LEFT the joins if there is a case that a product does not have a row in either of the tables feedback and ProductDetail.

Body:
I have the following tables in my database (SQLite):

CREATE TABLE product (
    id INTEGER NOT NULL,
    name TEXT,
    PRIMARY KEY (id)
)

CREATE TABLE feedback(
  product INTEGER PRIMARY KEY,
  score NUMERIC,
  textnote VARCHAR(255),
  FOREIGN KEY(product) REFERENCES product(id)
)

CREATE TABLE product_detail (
    id INTEGER NOT NULL,
    product INTEGER,
    description TEXT,
    url VARCHAR,
    PRIMARY KEY (id),
    FOREIGN KEY(product) REFERENCES product (id),
)

So feedback is in a one-to-one relationship with product and product_detail is in a many-to-one relationship with product.

I am trying to write a SQLite query for Hibernate 4 that will give me all the attributes from the 3 tables in one single table. All I came with by far is this:

String hql = "SELECT p.id, p.name, d.id, d.description, d.url " +
            "FROM ProductDetail d INNER JOIN d.product AS p";

I'm correctly obtaining the values I want from product and product_detail. How can I add to the query also the information in feedback? I know all products have at least one product detail, but I can't say the same about feedback: most of the products don't have a feedback. I think I should use a LEFT JOIN but I can't figure out how...
Note that as I'm using Hibernate I have all classes relative to the tables in my application (Feedback, ProductDetail and Product).

Body:
You must also join feedback:

SELECT
  p.id, p.name,
  f.score, f.textxnote,
  d.id, d.description, d.url
FROM product p
INNER JOIN feedback f ON f.product = p.id
INNER JOIN ProductDetail d ON d.product = p.id

You may change to LEFT the joins if there is a case that a product does not have a row in either of the tables feedback and ProductDetail.


问:
Can not change timezone for kubernetes pod
I am trying to modify the config file of a pod to use local time, but it show invalid when saving. Do you know what's wrong ?

In volumeMounts section: I added below lines:

```<code>- mountPath: /etc/localtime
      name: tz-config
</code>```

In volumes setion: I added below lines:

```<code>- name: tz-config
        hostPath:
          path: /usr/share/zoneinfo/Asia/Ho_Chi_Minh
</code>```

Here is my yaml file:

```<code>apiVersion: v1
kind: Pod
metadata:
  .....
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-jgznd
      readOnly: true
    - mountPath: /etc/localtime
      name: tz-config
  dnsPolicy: ClusterFirst
  .....
  volumes:
  - name: default-token-jgznd
    secret:
      defaultMode: 420
      secretName: default-token-jgznd
  - name: tz-config
    hostPath:
      path: /usr/share/zoneinfo/Asia/Ho_Chi_Minh
</code>```

UPDATE: Below are error detail

```<code># pods "hello-75fdf45c64-w7xm8" was not valid:
# * spec: Forbidden: pod updates may not change fields other than `spec.containers[*].image`, `spec.initContainers[*].image`, `spec.activeDeadlineSeconds` or `spec.tolerations` (only additions to existing tolerations)
#   core.PodSpec{
#       Volumes: []core.Volume{
#               {Name: "default-token-wcf8m", VolumeSource: core.VolumeSource{Secret: &core.SecretVolumeSource{SecretName: "default-token-wcf8m", DefaultMode: &420}}},
# -             {
# -                     Name: "tz-config",
# -                     VolumeSource: core.VolumeSource{
# -                             HostPath: &core.HostPathVolumeSource{Path: "/usr/share/zoneinfo/Asia/Ho_Chi_Minh", Type: &""},
# -                     },
# -             },
#       },
#       InitContainers: nil,
</code>```

答:
I resolved my problem by adding mountPath to the file deployment yaml as below. Many thanks @Shawlz for help:</p>

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2020-02-14T15:59:50Z"
  generation: 1
  labels:
    run: hello
  name: hello
  namespace: default
  resourceVersion: "523908"
  selfLink: /apis/apps/v1/namespaces/default/deployments/hello
  uid: 43196302-0176-4ce2-9d10-c8fefcc6c316
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      run: hello
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: hello
    spec:
      containers:
      - image: hello-microservice
        imagePullPolicy: Never
        name: hello
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
          - name: tz-config
            mountPath: /etc/localtime
      volumes:
        - name: tz-config
          hostPath:
            path: /usr/share/zoneinfo/Asia/Ho_Chi_Minh
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
</code>```

Body:
I am trying to modify the config file of a pod to use local time, but it show invalid when saving. Do you know what's wrong ?

In volumeMounts section: I added below lines:

- mountPath: /etc/localtime
      name: tz-config

In volumes setion: I added below lines:

- name: tz-config
        hostPath:
          path: /usr/share/zoneinfo/Asia/Ho_Chi_Minh

Here is my yaml file:

apiVersion: v1
kind: Pod
metadata:
  .....
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-jgznd
      readOnly: true
    - mountPath: /etc/localtime
      name: tz-config
  dnsPolicy: ClusterFirst
  .....
  volumes:
  - name: default-token-jgznd
    secret:
      defaultMode: 420
      secretName: default-token-jgznd
  - name: tz-config
    hostPath:
      path: /usr/share/zoneinfo/Asia/Ho_Chi_Minh

UPDATE: Below are error detail

# pods "hello-75fdf45c64-w7xm8" was not valid:
# * spec: Forbidden: pod updates may not change fields other than `spec.containers[*].image`, `spec.initContainers[*].image`, `spec.activeDeadlineSeconds` or `spec.tolerations` (only additions to existing tolerations)
#   core.PodSpec{
#       Volumes: []core.Volume{
#               {Name: "default-token-wcf8m", VolumeSource: core.VolumeSource{Secret: &core.SecretVolumeSource{SecretName: "default-token-wcf8m", DefaultMode: &420}}},
# -             {
# -                     Name: "tz-config",
# -                     VolumeSource: core.VolumeSource{
# -                             HostPath: &core.HostPathVolumeSource{Path: "/usr/share/zoneinfo/Asia/Ho_Chi_Minh", Type: &""},
# -                     },
# -             },
#       },
#       InitContainers: nil,

Body:
I resolved my problem by adding mountPath to the file deployment yaml as below. Many thanks @Shawlz for help:

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2020-02-14T15:59:50Z"
  generation: 1
  labels:
    run: hello
  name: hello
  namespace: default
  resourceVersion: "523908"
  selfLink: /apis/apps/v1/namespaces/default/deployments/hello
  uid: 43196302-0176-4ce2-9d10-c8fefcc6c316
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      run: hello
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: hello
    spec:
      containers:
      - image: hello-microservice
        imagePullPolicy: Never
        name: hello
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
          - name: tz-config
            mountPath: /etc/localtime
      volumes:
        - name: tz-config
          hostPath:
            path: /usr/share/zoneinfo/Asia/Ho_Chi_Minh
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}


问:
WF4 Workflow persistence store: Is the XAML definition stored along with the instance data?
Environment: Workflow Foundation 4, SQL persistence  store.

Requirement: I have a bookmark which has to be resumed with the same XAML which was used to initialize the instance.

I vaguely remember reading about it a while back somewhere, but I am not sure anymore. Is the XAML definition stored along with the instance data in the persistence store? Or is it our responsibility to maintain multiple XAML versions as part of deployment? This is in the context of workflow version maintenance. My line of thought: assuming the Activity binaries remain the same, it might probably be easier to resume a persisted workflow if the XAML definition is also available in the persistence database! One manual workaround: store the version number of the XAML file in the database and the corresponding versioned XAML file in the deployment folder.

Any other alternatives?

答: No the XAML contents are not stored along with the workflow state and you have to take care of that.</p>


问:
Center values under others
I have tried to center the value (number + %) under the "Battery L" and "Battery R".
For example:

```<code>Battery L    Battery R
  100%         100%
</code>```

Do you know how can I do?

```<code><View style={{ alignItems: "center" }}>
  <View style={{ flex: 1, flexDirection: "row" }}>
    <View style={{ justifyContent: "flex-end", alignItems: "flex-end", marginRight: 20 }}>
      <Text style={{}}>{"Battery R"}</Text>
    </View>
    <View style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
      <Text style={{}}>{"Battery L"}</Text>
    </View>
  </View>

  <View style={{ flex: 1, flexDirection: "row" }}>
    <View style={{ justifyContent: "flex-end", alignItems: "flex-end" }}>
      <Text>{"100" + " %"}</Text>
    </View>
    <View style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
      <Text>{"100" + " %"}</Text>
    </View>
  </View>
</View>
</code>```

Link

答:
try flex:auto
you might find more here: https://css-tricks.com/almanac/properties/f/flex/</p>

Title: Center values under others

Body:
I have tried to center the value (number + %) under the "Battery L" and "Battery R".
For example:

Battery L    Battery R
  100%         100%

Do you know how can I do?

<View style={{ alignItems: "center" }}>
  <View style={{ flex: 1, flexDirection: "row" }}>
    <View style={{ justifyContent: "flex-end", alignItems: "flex-end", marginRight: 20 }}>
      <Text style={{}}>{"Battery R"}</Text>
    </View>
    <View style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
      <Text style={{}}>{"Battery L"}</Text>
    </View>
  </View>

  <View style={{ flex: 1, flexDirection: "row" }}>
    <View style={{ justifyContent: "flex-end", alignItems: "flex-end" }}>
      <Text>{"100" + " %"}</Text>
    </View>
    <View style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
      <Text>{"100" + " %"}</Text>
    </View>
  </View>
</View>

Link


问:
Options page not showing up
I cant see this menu names in admin menu list.
This plugin just show me Custom fields on the menu.
Whats wrong on this code ?

What I have in functions.php file

```<code>if( function_exists('acf_add_options_page') ) {

    acf_add_options_page(array(
        'page_title'    => 'Site Ayarları',
        'menu_title'    => 'Site Ayarları',
        'menu_slug'     => 'site-ayarlari',
        'capability'    => 'manage_options',
        'redirect'      => false
    ));

    acf_add_options_page(array(
        'page_title'    => 'Ana Sayfa Ayarları',
        'menu_title'    => 'Ana Sayfa Ayarları',
        'menu_slug'     => 'anasayfa-ayarlari',
        'parent_slug'   => 'site-ayarlari',
        'capability'    => 'manage_options',
        'redirect'      => false
    ));

}
</code>```

答:
```if( function_exists('acf_add_options_page') ) {
// add parent
$parent = acf_add_options_page(array('page_title' => 'Theme Settings','menu_title' => 'Theme Settings',
'redirect' => false ));
}```

Try like this

Title: Options page not showing up

Body:
I cant see this menu names in admin menu list.
This plugin just show me Custom fields on the menu.
Whats wrong on this code ?

What I have in functions.php file

if( function_exists('acf_add_options_page') ) {

    acf_add_options_page(array(
        'page_title'    => 'Site Ayarları',
        'menu_title'    => 'Site Ayarları',
        'menu_slug'     => 'site-ayarlari',
        'capability'    => 'manage_options',
        'redirect'      => false
    ));

    acf_add_options_page(array(
        'page_title'    => 'Ana Sayfa Ayarları',
        'menu_title'    => 'Ana Sayfa Ayarları',
        'menu_slug'     => 'anasayfa-ayarlari',
        'parent_slug'   => 'site-ayarlari',
        'capability'    => 'manage_options',
        'redirect'      => false
    ));

}

Body:
if( function_exists('acf_add_options_page') ) {
// add parent
$parent = acf_add_options_page(array('page_title' => 'Theme Settings','menu_title' => 'Theme Settings',
'redirect' => false ));
}

Try like this


问:
How to keep/assign row & column names when combining 2 vectors into a matrix in R
Hello, I'm fairly new to R programming so please don't judge if this seems pretty straightforward.

I was wondering if there is a way to do the following: I want to combine 2 vectors into an array but keep/assign their column and row names.

My code:

library(ISLR)

mean = sapply(Auto[, 1:3], mean)
sd = sapply(Auto[, 1:3], sd)

mean_sd = matrix(
   data = c(mean, sd),
   nrow = 2, ncol = 3, byrow = TRUE
)
```

<p>Printing these individually prints them with their column names as intended.</p>

```mean
 mpg           cylinders        weight
 23.445918     104.469388       2977.584184
```

```sd
 mpg           cylinders        weight
 7.805007      1.705783         849.402560
```

<p>but printing them combined I get indices and not names.</p>

```mean_sd
          [,1]     [,2]      [,3]
[1,] 23.445918 5.471939 2977.5842
[2,]  7.805007 1.705783  849.4026
```

<p>Is there a way to get the following:</p>

```mean_sd
              mpg   cylinders       weight
mean    23.445918    5.471939    2977.5842
sd       7.805007    1.705783     849.4026
```

I searched around a bit and found that I should be using dimnames(data) but I couldn't understand how to apply it to my code.

答:
You just need to use data.frame() instead of matrix()

```<code>mean_sd = data.frame(
  mean = sapply(mtcars[, 1:3], mean),
  sd = sapply(mtcars[, 1:3], sd)
)
</code>```

Body:
Hello, I'm fairly new to R programming so please don't judge if this seems pretty straightforward.

I was wondering if there is a way to do the following: I want to combine 2 vectors into an array but keep/assign their column and row names.

My code:

library(ISLR)

mean = sapply(Auto[, 1:3], mean)
sd = sapply(Auto[, 1:3], sd)

mean_sd = matrix(
   data = c(mean, sd),
   nrow = 2, ncol = 3, byrow = TRUE
)

Printing these individually prints them with their column names as intended.

mean
 mpg           cylinders        weight
 23.445918     104.469388       2977.584184

sd
 mpg           cylinders        weight
 7.805007      1.705783         849.402560

but printing them combined I get indices and not names.

mean_sd
          [,1]     [,2]      [,3]
[1,] 23.445918 5.471939 2977.5842
[2,]  7.805007 1.705783  849.4026

Is there a way to get the following:

mean_sd
              mpg   cylinders       weight
mean    23.445918    5.471939    2977.5842
sd       7.805007    1.705783     849.4026

I searched around a bit and found that I should be using dimnames(data) but I couldn't understand how to apply it to my code.

Body:
You just need to use data.frame() instead of matrix()

mean_sd = data.frame(
  mean = sapply(mtcars[, 1:3], mean),
  sd = sapply(mtcars[, 1:3], sd)
)


问:
Micronaut data and Enum fields in Entities
Does micronaut-data support enum fields?

I tried creating enum field resulted in error. Added type converter using Micronaut TypeConverter framework but still same error that it states

java.lang.NoSuchMethodError: 'void company.SyncRun.setStatus(java.lang.String)' where SyncRun.status is enum field which has converter like below.

@Factory
class TypeConverters {

  @Singleton
  fun syncStatusToString(): TypeConverter<SyncStatus, String> {
    return TypeConverter { value, targetType, context -> Optional.of(value.name) }
  }

  @Singleton
  fun stringToSyncStatus(): TypeConverter<String, SyncStatus> {
    return TypeConverter { value, targetType, context -> Optional.of(SyncStatus.valueOf(value)) }
  }
}

```

答:
With JPA you should simply annotate the enum property with @Enumerated(EnumType.STRING).

With JDBC it is working out of the box.


问:
Why arent the "selected" classes not being set for ASP Menu control?
I'm a frontend developer working with a seemingly incompetant .NET dev that cant seem to resolve why the ASP Menu control is not showing the selected menu item. The .NET developer sent me the following code. Is there some rules missing here that are need to enable the CSS?

Thanks in advance

Controller config

```<code> <asp:Menu ID="mnuMaster"
                          runat="server"
                          DataSourceID="sitemapMaster"
                          StaticDisplayLevels="1"
                          MaximumDynamicDisplayLevels="0"
                          Orientation="Horizontal"
                          StaticEnableDefaultPopOutImage="False"
                          CssSelectorClass="TopMainMenu" onmenuitemdatabound="mnuMaster_MenuItemDataBound"
                          StaticBottomSeparatorImageUrl="~/App_Themes/PCTools/Images/top_menu_separator.gif"
                          ></asp:Menu>
</code>```

CSS selected classes

```<code>    .TopMainMenu .AspNet-Menu li a:active, .TopMainMenu li.AspNet-Menu-Selected a,.TopMainMenu li.AspNet-Menu-ChildSelected a,.TopMainMenu li.AspNet-Menu-ParentSelected a {
    background:url(Images/navbg.gif) repeat-x 0 -86px;
}
</code>```

答:
We normally use a standard UL group in ordinary HTML that a designer provides and then make them into HTML Server Tags.

There may be other  solutions but the solution we usually do is this.

First each top level menu item needs an ID.

If the menu is on a masterpage (im going to assume it is)

in the masterpage code behind you can place code like this.

```<code>//Discover currently navigated page TYPE
if (this.Page is `pagetype of the current page`)
    //add a CSS class to the top level menu item
    miFirstMenuItem.Attributes["class"] += " highlightedMenuItemCSSClass";
</code>```

Then the HTML Output would append an additional CSS class to that menu item which you apply your specific style

Heres a real life example
Node you would have to change the type in the SetActiveTab method to the correct type for the MenuItem

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bool homeVisited        = Page is Default;
            bool productsVisited    = Page is Products_List;
            bool demoVisited        = Page is Demonstrations;
            bool contactVisited     = Page is Contact;

            if (homeVisited)
                SetActivePage(hlHome, ButtonSide.Left);
            if (productsVisited)
                SetActivePage(hlProducts, ButtonSide.Middle);
            if (demoVisited)
                SetActivePage(hlDemo, ButtonSide.Middle);
            if (contactVisited)
                SetActivePage(hlContact, ButtonSide.Right);

        }
    }
</code>```

This shows a different way than I described above but you can replace it with link.Attributes["class"] += " cssClass";   Notice the space after the first ".

Also ButtonSide is an enum I added since all the middle menuitems would have the same CSS  class in my particular case and left and right ones as well.

```<code>    private void SetActivePage(HyperLink link, ButtonSide side)
    {
        if (side == ButtonSide.Left)
            link.CssClass = "currentleft";
        if (side == ButtonSide.Middle)
            link.CssClass = "currentmiddle";
        if (side == ButtonSide.Right)
            link.CssClass = "currentright";
    }
</code>```

Body:
I'm a frontend developer working with a seemingly incompetant .NET dev that cant seem to resolve why the ASP Menu control is not showing the selected menu item. The .NET developer sent me the following code. Is there some rules missing here that are need to enable the CSS?

Thanks in advance

Controller config

 <asp:Menu ID="mnuMaster"
                          runat="server"
                          DataSourceID="sitemapMaster"
                          StaticDisplayLevels="1"
                          MaximumDynamicDisplayLevels="0"
                          Orientation="Horizontal"
                          StaticEnableDefaultPopOutImage="False"
                          CssSelectorClass="TopMainMenu" onmenuitemdatabound="mnuMaster_MenuItemDataBound"
                          StaticBottomSeparatorImageUrl="~/App_Themes/PCTools/Images/top_menu_separator.gif"
                          ></asp:Menu>

CSS selected classes

    .TopMainMenu .AspNet-Menu li a:active, .TopMainMenu li.AspNet-Menu-Selected a,.TopMainMenu li.AspNet-Menu-ChildSelected a,.TopMainMenu li.AspNet-Menu-ParentSelected a {
    background:url(Images/navbg.gif) repeat-x 0 -86px;
}

Body:
We normally use a standard UL group in ordinary HTML that a designer provides and then make them into HTML Server Tags.

There may be other  solutions but the solution we usually do is this.

First each top level menu item needs an ID.

If the menu is on a masterpage (im going to assume it is)

in the masterpage code behind you can place code like this.

//Discover currently navigated page TYPE
if (this.Page is `pagetype of the current page`)
    //add a CSS class to the top level menu item
    miFirstMenuItem.Attributes["class"] += " highlightedMenuItemCSSClass";

Then the HTML Output would append an additional CSS class to that menu item which you apply your specific style

Heres a real life example
Node you would have to change the type in the SetActiveTab method to the correct type for the MenuItem

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bool homeVisited        = Page is Default;
            bool productsVisited    = Page is Products_List;
            bool demoVisited        = Page is Demonstrations;
            bool contactVisited     = Page is Contact;

            if (homeVisited)
                SetActivePage(hlHome, ButtonSide.Left);
            if (productsVisited)
                SetActivePage(hlProducts, ButtonSide.Middle);
            if (demoVisited)
                SetActivePage(hlDemo, ButtonSide.Middle);
            if (contactVisited)
                SetActivePage(hlContact, ButtonSide.Right);

        }
    }

This shows a different way than I described above but you can replace it with link.Attributes["class"] += " cssClass";   Notice the space after the first ".

Also ButtonSide is an enum I added since all the middle menuitems would have the same CSS  class in my particular case and left and right ones as well.

    private void SetActivePage(HyperLink link, ButtonSide side)
    {
        if (side == ButtonSide.Left)
            link.CssClass = "currentleft";
        if (side == ButtonSide.Middle)
            link.CssClass = "currentmiddle";
        if (side == ButtonSide.Right)
            link.CssClass = "currentright";
    }


问:
Azure DevOps - compare two commits right in the web UI?
This is surely something simple I'm overlooking. In the Azure DevOps web interface (not integrated as part of an IDE), I see how to compare any commit to its parent, but I can't figure out how to compare it to an arbitrary commit.

ie, I'm looking for the equivalent of GitHub's compare/hash1..hash2 functionality.

The appeal is that the web UI is a view/tool common to everyone, and presumably I could get a link to the specific diff I'm interested in and share it with colleagues.

The web UI suggests it might be possible because when viewing the changes for a particular commit it has text Diff to Parent 1 - <my commit hash> but I haven't figured out how to change Parent 1.

答:
If you go to the list of branches for a repository, you can click on ... (More Actions) on one of the branches and choose Compare branches

This will take you to a URL in the form:
https://dev.azure.com/{organisation}/{project}/_git/{repository}/branches?baseVersion=GB{baseBranch}&targetVersion=GB{targetBranch}&_a=files

You can then change the baseVersion and targetVersion parameters in the query string. These can take the following forms, and can be mixed and matched:

GB{branchName}

GC{commitHash}

GT{tagName}

Just in case that link gets broken, clicking "View Merge Changes" on a pull request takes you to the same page but with a slightly different URL https://dev.azure.com/{organisation}/{project}/_git/{repository}/branchCompare?baseVersion=GC{baseCommit}&targetVersion=GC{targetCommit}&_a=files

I'm not sure if there's a nicer way of comparing commits from the UI, as it only shows branches and tags, but if you do it this way you don't have to temporarily tag commits or create temporary branches just to get a diff that shows all of the changed files.


问:
why is the address of a c++ function always True?
well why would,

```<code>#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}
</code>```

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

答:
There cannot be an overload  for function pointers for the iostream << operator, as there are an infinite number of possible function pointer types. So the function pointer gets a conversion applied, in this case to bool. Try:

```<code>cout << (void *) afunction << endl;
</code>```

Which will give you the address in hex - for me the result was:

```<code>0x401344
</code>```

Body:
well why would,

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

Body:
There cannot be an overload  for function pointers for the iostream << operator, as there are an infinite number of possible function pointer types. So the function pointer gets a conversion applied, in this case to bool. Try:

cout << (void *) afunction << endl;

Which will give you the address in hex - for me the result was:

0x401344


问:
Oracle SQL - creating "unstored" procedure
I have this SQL query

```<code>SELECT ACCBAL_DATE, ACCBAL_AMOUNT
FROM ACCOUNT_BALANCES t
WHERE ACC_KEY = '964570223'
AND ACCBAL_KEY = '16'
ORDER BY ACCBAL_DATE DESC
FETCH FIRST 1 ROWS ONLY;
</code>```

It returns one row but I need to use this query for many ACC_KEYS (about 600).

So first way to do that is to run this query about 600x with different ACC_KEY parameter.

The second one is creating a procedure I think.

Procedure which will use variable acc_key and move it to WHERE statement.
Issue is that I can't create procedure stored on server because of permissions.

Is there some way to solve it without storing procedure on server?

EDIT: I know the IN clause but that is not what I need. I need something which will run the query about 600x, each execution with another ACC_KEY in WHERE clause and the output should be 600 rows.

答:
when I used them in clause IN, then it will still return only one row. I want to return only one row because without limitations it returns about 100 rows, so I want only the first row which has needed data. For each ACC_KEY it should return only one row

You can still do that with an IN() clause listing all 600 key values:

```<code>select acc_key,
  max(accbal_date) as accbal_date,
  max(accbal_amount) keep (dense_rank last order by accbal_date) as accbal_amount
from account_balances t
where acc_key in ('964570223', '964570224', ...) -- up to 1000 allowed
and accbal_key = '16'
group by acc_key
order by acc_key;
</code>```

This is using aggregate functions and grouping by the key, so you will get one row per key, with the data for the most recent date.

Read more about keep/last.

It would still be better to use a collection or a table - maybe an external table loaded from your Excel sheet, saved as a CSV; not least because you can only supply 1000 entries to a single IN() clause - or any expression list - but also for performance and readability/maintenance reasons.

Body:
I have this SQL query

SELECT ACCBAL_DATE, ACCBAL_AMOUNT
FROM ACCOUNT_BALANCES t
WHERE ACC_KEY = '964570223'
AND ACCBAL_KEY = '16'
ORDER BY ACCBAL_DATE DESC
FETCH FIRST 1 ROWS ONLY;

It returns one row but I need to use this query for many ACC_KEYS (about 600).

So first way to do that is to run this query about 600x with different ACC_KEY parameter.

The second one is creating a procedure I think.

Procedure which will use variable acc_key and move it to WHERE statement.
Issue is that I can't create procedure stored on server because of permissions.

Is there some way to solve it without storing procedure on server?

EDIT: I know the IN clause but that is not what I need. I need something which will run the query about 600x, each execution with another ACC_KEY in WHERE clause and the output should be 600 rows.

Body:
when I used them in clause IN, then it will still return only one row. I want to return only one row because without limitations it returns about 100 rows, so I want only the first row which has needed data. For each ACC_KEY it should return only one row

You can still do that with an IN() clause listing all 600 key values:

select acc_key,
  max(accbal_date) as accbal_date,
  max(accbal_amount) keep (dense_rank last order by accbal_date) as accbal_amount
from account_balances t
where acc_key in ('964570223', '964570224', ...) -- up to 1000 allowed
and accbal_key = '16'
group by acc_key
order by acc_key;

This is using aggregate functions and grouping by the key, so you will get one row per key, with the data for the most recent date.

Read more about keep/last.

It would still be better to use a collection or a table - maybe an external table loaded from your Excel sheet, saved as a CSV; not least because you can only supply 1000 entries to a single IN() clause - or any expression list - but also for performance and readability/maintenance reasons.


问:
Ghostscript with LaTeX and rotate page
I am using this command with gs 9.5 for LaTeX pdfs

```<code>gswin64c -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dNOPAUSE -dQUIET -dBATCH -dPrinted=false -sOutputFile=foo-compressed.pdf foo.pdf
</code>```

All works well, except that single pages I rotated in LaTeX from Landscape to Portrait (e.g. wide Tables) appear in the GS output again in Landscape format. The original LaTeX PDF looks fine, the PDF file output of LaTeX is simply too large (over 100MB)

Is there a way to stop gs rotating single pages?

答: Check the documentation on AutoRotatePages.</p>

Title: Ghostscript with LaTeX and rotate page

Body:
I am using this command with gs 9.5 for LaTeX pdfs

gswin64c -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dNOPAUSE -dQUIET -dBATCH -dPrinted=false -sOutputFile=foo-compressed.pdf foo.pdf

All works well, except that single pages I rotated in LaTeX from Landscape to Portrait (e.g. wide Tables) appear in the GS output again in Landscape format. The original LaTeX PDF looks fine, the PDF file output of LaTeX is simply too large (over 100MB)

Is there a way to stop gs rotating single pages?


问:
keytool -storepass option - Is this a password I create? Or a password provided to me with the certificate?
I was told recently to use the following command to import a SSL certificate onto our weblogic server

```<code>keytool -import -file <ssl certificate filename> -alias alias name -keystore <keystorename> -storepass <password>
</code>```

I was reading up on the options for this keytool command and am a bit confused by the -storepass option.

We currently do not use SSL on the server, and am switching over - So for the [-storepass] option is this a password that should be PROVIDED to me along WITH the certificate? Or is this going to be a password I am CREATING for the newly imported certificate?

答:
In order to add support to SSL to your weblogic server you need to import the SSL/TLS certificate to a keystore that will be used by the server. The attribute -storepass is related to the keystore passphrase, it was configured at the moment you generate the keystore.

The bellow command shows how to import a credentials into your keystore, pay attention in the fields you need to replace

```<code>keytool -v -importkeystore -srckeystore *yourkeystorePath* -srcstoretype *yourKeystoreType* -srcstorepass *yourKeystorePassword* -destkeystore *yourtargetKeystore* -deststoretype *yourTargetKeystoreType* -deststorepass *yourTargetKeyStorePass*
</code>```

Body:
I was told recently to use the following command to import a SSL certificate onto our weblogic server

keytool -import -file <ssl certificate filename> -alias alias name -keystore <keystorename> -storepass <password>

I was reading up on the options for this keytool command and am a bit confused by the -storepass option.

We currently do not use SSL on the server, and am switching over - So for the [-storepass] option is this a password that should be PROVIDED to me along WITH the certificate? Or is this going to be a password I am CREATING for the newly imported certificate?

Body:
In order to add support to SSL to your weblogic server you need to import the SSL/TLS certificate to a keystore that will be used by the server. The attribute -storepass is related to the keystore passphrase, it was configured at the moment you generate the keystore.

The bellow command shows how to import a credentials into your keystore, pay attention in the fields you need to replace

keytool -v -importkeystore -srckeystore *yourkeystorePath* -srcstoretype *yourKeystoreType* -srcstorepass *yourKeystorePassword* -destkeystore *yourtargetKeystore* -deststoretype *yourTargetKeystoreType* -deststorepass *yourTargetKeyStorePass*


问:
How to make an element in a page the same visual width as another element exactly?
I'm trying to make it so that element A's width is equal to B's width so that they both visually appear to be the same.

I tried to do:

$('#A').css('max-width', $('#B').css('width'));
```

But this doesn't work the way I want it to, because B's width is 83%, so A's max width becomes 83%.

This doesn't make A visually the same as it just becomes 83% of its parent element, which makes it appear bigger on the page.

Is there a way to calculate the visual width of B so I can use that as A's max-width, using jQuery?

EDIT: I can't edit the document structure.

答:
You need to be setting width, not max-width.

```<code>$('#A').css('width', $('#B').width() )
</code>```

https://codepen.io/doughballs/pen/zYGrMoK

Max-width restricts how wide an element can be - if it isn't already at the width you set as max width, then max-width won't have any effect. Width tells an element how wide it should be.

Body:
I'm trying to make it so that element A's width is equal to B's width so that they both visually appear to be the same.

I tried to do:

$('#A').css('max-width', $('#B').css('width'));

But this doesn't work the way I want it to, because B's width is 83%, so A's max width becomes 83%.

This doesn't make A visually the same as it just becomes 83% of its parent element, which makes it appear bigger on the page.

Is there a way to calculate the visual width of B so I can use that as A's max-width, using jQuery?

EDIT: I can't edit the document structure.

Body:
You need to be setting width, not max-width.

$('#A').css('width', $('#B').width() )

https://codepen.io/doughballs/pen/zYGrMoK

Max-width restricts how wide an element can be - if it isn't already at the width you set as max width, then max-width won't have any effect. Width tells an element how wide it should be.


问:
Match index two column criteria and one row criteria in google sheets
I have a data set where I want to create a search based on SKU and PO (two columns) and either online or store (one row).  Usually I can do a simple index(match()) function with one criteria of each, but it becomes complicated when adding a second column to search.

Body:
try:

=FILTER(IF(F2=C1, C:C, D:D), A:A=G2, B:B=H2)


问:
Impossible to set the Cloud Firebase daily spending limit
I just purchased a Firebase blaze plan (unlimited) but I tried to setup the daily quota as suggested in their documentation:
https://firebase.google.com/docs/firestore/quotas#set_spending_limits

The problem is that I can't find this option on my own console, there is no "Set budget" section:

I really need to setup this daily alert to avoid any bad surprises.
Why am I not seeing this option? Thanks

答:
Well it seems they removed the possibility...

The documentation page (https://firebase.google.com/docs/firestore/quotas#set_spending_limits) has been updated and they explained:

Important: Cloud Firestore no longer supports new App Engine spending limits. After December 12, 2019, you cannot apply new App Engine spending limits. Spending limits set before December 12 still apply.

Now there is only the monthly budget left to use.

The budget on the Firebase Blaze plan is unlimited and there is not a single way to supervize it on a daily basis...


问:
Hibernate Criteria, createAlias() If Alias is Null
In the code below..
There are two Alias as Entity Object  Reference.
Sometimes "caseStage" as stage can be null in Database.
When "caseStage" is null I want stage.name value as an empty String or something customized like "---" etc.

```<code>session.createCriteria(CaseMasterPO.class)
       .createAlias("branch", "br")     // BranchPO.class
       .createAlias("caseStage", "stage") // CaseStagePO.class
       .setProjection(Projections.projectionList()
          .add(Projections.property("caseCode"))
          .add(Projections.property("br.zoneCode"))
          .add(Projections.property("stage.name")) // Problem, when stage == null
       )
       .add(Restrictions.eq("caseCode", caseCode)).uniqueResult();
</code>```

答:
@Koti Eswar answer is right, but it's deprecated now.

It's should be done like this:

```<code>        join('branch', JoinType.LEFT)
        createAlias('branch', 'br')
</code>```

Tested in Grails 3.3.5

Body:
In the code below..
There are two Alias as Entity Object  Reference.
Sometimes "caseStage" as stage can be null in Database.
When "caseStage" is null I want stage.name value as an empty String or something customized like "---" etc.

session.createCriteria(CaseMasterPO.class)
       .createAlias("branch", "br")     // BranchPO.class
       .createAlias("caseStage", "stage") // CaseStagePO.class
       .setProjection(Projections.projectionList()
          .add(Projections.property("caseCode"))
          .add(Projections.property("br.zoneCode"))
          .add(Projections.property("stage.name")) // Problem, when stage == null
       )
       .add(Restrictions.eq("caseCode", caseCode)).uniqueResult();

Body:
@Koti Eswar answer is right, but it's deprecated now.

It's should be done like this:

        join('branch', JoinType.LEFT)
        createAlias('branch', 'br')

Tested in Grails 3.3.5


问:
Entity Framework Core with WPF Core - Cannot add migrations
Recently I migrated my WPF app (.NET 4.7) to .Net Core 3.1. Most of it works fine except for me not being able to generate/add EF Core migrations.

I integrated my dbContext / EF Core with help of the following post(s) using Dependency Injection:

https://marcominerva.wordpress.com/2019/03/06/using-net-core-3-0-dependency-injection-and-service-provider-with-wpf/

https://marcominerva.wordpress.com/2019/03/19/using-entity-framework-core-with-wpf-on-net-core-3-0/

The database connects and is working properly. However when I try to add migrations by typing in the following command: Add-Migration InitialMigration I keep getting the following error:

Unable to create an object of type 'MyDBContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

In web applications this seems to be a common/known issue and is fixable by changing CreateHostBuilder to BuildWebHost in the program class; https://stackoverflow.com/questions/57745481/unable-to-create-an-object-of-type-mycontext-for-the-different-patterns-suppo

I also found some other posts by adding MigrationsAssembly in options.UseSqlServer.

Long story short, I tried all these solutions but none of them seem to work. Probably because my application is not a web application (no program class e.g. BuildWebHost) but a WPF (Core) application.

My initializing code for the WPF app looks as following:

App.xaml.cs

```<code>public partial class App : Application
{
    private readonly IHost host;
    public IServiceProvider ServiceProvider { get; private set; }
    public IConfiguration Configuration { get; private set; }

    public App()
    {
        host = Host.CreateDefaultBuilder()
               .ConfigureServices((context, services) =>
               {
                   ConfigureServices(services);
               }).Build();
    }

    private void ConfigureServices(IServiceCollection services)
    {
        // services for DI...

        services.AddDbContext<MyDbContext>
            (options =>
                options.UseSqlServer(
                        Configuration.GetConnectionString("SqlConnection")));

        services.AddTransient<MainWindow>();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        Configuration = builder.Build();

        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        ServiceProvider = serviceCollection.BuildServiceProvider();

        var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
        mainWindow.Show();
    }

    protected override async void OnExit(ExitEventArgs e)
    {
        using (host)
        {
            await host.StopAsync(TimeSpan.FromSeconds(5));
        }

        base.OnExit(e);
    }
}
</code>```

MyDbContext.cs

```<code>public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
        Database.Migrate();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Zonnescherm Model
        modelBuilder.Entity<Zonneschermen>().Property(e => e.BreedteZonnescherm).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<Zonneschermen>().Property(e => e.UitvalDoek).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<Zonneschermen>().Property(e => e.ArmLengte).HasColumnType("decimal(17,2)");

        // ScreenRegels Model
        modelBuilder.Entity<ScreenRegels>().Property(e => e.Breedte).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<ScreenRegels>().Property(e => e.Hoogte).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<ScreenRegels>().Property(e => e.DraaistangLengte).HasColumnType("decimal(17,2)");

        // Seed
        modelBuilder.Entity<Instellingen>().HasData(
            // seeding...

        );

        // Seed
        modelBuilder.Entity<ZonneschermInstellingen>().HasData(
            // seeding...
        );

        // Seed
        modelBuilder.Entity<ScreenInstellingen>().HasData(
            // seeding...
        );
    }

    public DbSet<Lamellen> Lamellen { get; set; }
    public DbSet<LamellenRegels> LamellenRegels { get; set; }
    public DbSet<Zonneschermen> Zonneschermen { get; set; }
    public DbSet<ZonneschermInstellingen> ZonneschermInstellingen { get; set; }
    public DbSet<Screens> Screens { get; set; }
    public DbSet<ScreenRegels> ScreenRegels { get; set; }
    public DbSet<ScreenInstellingen> ScreenInstellingen { get; set; }
    public DbSet<Instellingen> Instellingen { get; set; }
}
</code>```

Any clues where it goes wrong?

答:
Just came across this post: WPF with entity framework on net core - unable to create and object of type AppDbContext

which addresses the same issue.

Body:
Recently I migrated my WPF app (.NET 4.7) to .Net Core 3.1. Most of it works fine except for me not being able to generate/add EF Core migrations.

I integrated my dbContext / EF Core with help of the following post(s) using Dependency Injection:

https://marcominerva.wordpress.com/2019/03/06/using-net-core-3-0-dependency-injection-and-service-provider-with-wpf/

https://marcominerva.wordpress.com/2019/03/19/using-entity-framework-core-with-wpf-on-net-core-3-0/

The database connects and is working properly. However when I try to add migrations by typing in the following command: Add-Migration InitialMigration I keep getting the following error:

Unable to create an object of type 'MyDBContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

In web applications this seems to be a common/known issue and is fixable by changing CreateHostBuilder to BuildWebHost in the program class; https://stackoverflow.com/questions/57745481/unable-to-create-an-object-of-type-mycontext-for-the-different-patterns-suppo

I also found some other posts by adding MigrationsAssembly in options.UseSqlServer.

Long story short, I tried all these solutions but none of them seem to work. Probably because my application is not a web application (no program class e.g. BuildWebHost) but a WPF (Core) application.

My initializing code for the WPF app looks as following:

App.xaml.cs

public partial class App : Application
{
    private readonly IHost host;
    public IServiceProvider ServiceProvider { get; private set; }
    public IConfiguration Configuration { get; private set; }

    public App()
    {
        host = Host.CreateDefaultBuilder()
               .ConfigureServices((context, services) =>
               {
                   ConfigureServices(services);
               }).Build();
    }

    private void ConfigureServices(IServiceCollection services)
    {
        // services for DI...

        services.AddDbContext<MyDbContext>
            (options =>
                options.UseSqlServer(
                        Configuration.GetConnectionString("SqlConnection")));

        services.AddTransient<MainWindow>();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        Configuration = builder.Build();

        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        ServiceProvider = serviceCollection.BuildServiceProvider();

        var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
        mainWindow.Show();
    }

    protected override async void OnExit(ExitEventArgs e)
    {
        using (host)
        {
            await host.StopAsync(TimeSpan.FromSeconds(5));
        }

        base.OnExit(e);
    }
}

MyDbContext.cs

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
        Database.Migrate();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Zonnescherm Model
        modelBuilder.Entity<Zonneschermen>().Property(e => e.BreedteZonnescherm).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<Zonneschermen>().Property(e => e.UitvalDoek).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<Zonneschermen>().Property(e => e.ArmLengte).HasColumnType("decimal(17,2)");

        // ScreenRegels Model
        modelBuilder.Entity<ScreenRegels>().Property(e => e.Breedte).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<ScreenRegels>().Property(e => e.Hoogte).HasColumnType("decimal(17,2)");
        modelBuilder.Entity<ScreenRegels>().Property(e => e.DraaistangLengte).HasColumnType("decimal(17,2)");

        // Seed
        modelBuilder.Entity<Instellingen>().HasData(
            // seeding...

        );

        // Seed
        modelBuilder.Entity<ZonneschermInstellingen>().HasData(
            // seeding...
        );

        // Seed
        modelBuilder.Entity<ScreenInstellingen>().HasData(
            // seeding...
        );
    }

    public DbSet<Lamellen> Lamellen { get; set; }
    public DbSet<LamellenRegels> LamellenRegels { get; set; }
    public DbSet<Zonneschermen> Zonneschermen { get; set; }
    public DbSet<ZonneschermInstellingen> ZonneschermInstellingen { get; set; }
    public DbSet<Screens> Screens { get; set; }
    public DbSet<ScreenRegels> ScreenRegels { get; set; }
    public DbSet<ScreenInstellingen> ScreenInstellingen { get; set; }
    public DbSet<Instellingen> Instellingen { get; set; }
}

Any clues where it goes wrong?


问:
Pandas DataFrame: replace all values in a column, based on condition
I have a simple DataFrame like the following:

Team
First Season
Total Games

0
Dallas Cowboys
1960
894

1
Chicago Bears
1920
1357

2
Green Bay Packers
1921
1339

3
Miami Dolphins
1966
792

4
Baltimore Ravens
1996
326

5
San Francisco 49ers
1950
1003

I want to select all values from the First Season column and replace those that are over 1990 by 1. In this example, only Baltimore Ravens would have the 1996 replaced by 1 (keeping the rest of the data intact).

I have used the following:

```<code>df.loc[(df['First Season'] > 1990)] = 1
</code>```

But, it replaces all the values in that row by 1, not just the values in the 'First Season' column.

How can I replace just the values from that column?

答:
df['First Season'].loc[(df['First Season'] > 1990)] = 1
```

strange that nobody has this answer, the only missing part of your code is the ['First Season'] right after df and just remove your curly brackets inside.

Body:
I have a simple DataFrame like the following:

Team
First Season
Total Games

0
Dallas Cowboys
1960
894

1
Chicago Bears
1920
1357

2
Green Bay Packers
1921
1339

3
Miami Dolphins
1966
792

4
Baltimore Ravens
1996
326

5
San Francisco 49ers
1950
1003

I want to select all values from the First Season column and replace those that are over 1990 by 1. In this example, only Baltimore Ravens would have the 1996 replaced by 1 (keeping the rest of the data intact).

I have used the following:

df.loc[(df['First Season'] > 1990)] = 1

But, it replaces all the values in that row by 1, not just the values in the 'First Season' column.

How can I replace just the values from that column?

Body:
df['First Season'].loc[(df['First Season'] > 1990)] = 1

strange that nobody has this answer, the only missing part of your code is the ['First Season'] right after df and just remove your curly brackets inside.


问:
Need emergency help with dw20.exe process?
recently I have deployed asp.net application to production windows server 2008.

after 10-20 min, starts dw20.exe process (Microsoft.net error reporting shim), which takes almost all CPU available which cause to very slow response of my application.

No error no exception in Event Viewer.

I right clicked on the dw20.exe process and created the dump file to analyze what causing the issue.

Then I opened this file in WidDbg. run command .loadby sos mscorwks and get Unable to find module 'mscorwks'

It looks like I'm missing something or doing it wrong.

How to determine what cause an exception in application? how to analyze DMP file created?

Is it possible to stop this service?

答: Try adding ELMAH (http://code.google.com/p/elmah/) to the project so that you can grab the error info in an easier fashion.</p>


问:
scroll to element on reload page react
I'm trying to figure out how to scroll to the element after page reloads. I'm trying to ref the element and scroll to it after page reloads.

My current example will just scroll to the end of the page

```<code>const transactionRef = useRef(null)
const scrollToElemet = () => {
    transactionRef.current.scrollIntoView({ block: 'end', behavior: 'smooth' });
  }

  useEffect(scrollToElemet)

return (
  <div ref={transactionRef}></div>
)
</code>```

How can I calculate the position of the element and scroll to it on page reload? Thanks

答:
I would say, add an element at the bottom of your page and then use that element to scroll. Here is a sample

https://codesandbox.io/s/jolly-dhawan-k7q8b?fontsize=14&hidenavigation=1&theme=dark

Also, you need to pass [] as second argument so it only scroll on first mount otherwise it will keep on scrolling down to bottom on every change or on every render.

function App() {
  const [checked, setChecked] = useState(false);
  useEffect(() => {
    document.getElementById("footer").scrollIntoView();
  }, []);
  return (

Hello CodeSandbox

       setChecked(v => !v)}>{checked ? "Enable" : "Disable"}

Start editing to see some magic happen!

Main

        Footer

  );
}```

Title: scroll to element on reload page react

Body:
I'm trying to figure out how to scroll to the element after page reloads. I'm trying to ref the element and scroll to it after page reloads.

My current example will just scroll to the end of the page

const transactionRef = useRef(null)
const scrollToElemet = () => {
    transactionRef.current.scrollIntoView({ block: 'end', behavior: 'smooth' });
  }

  useEffect(scrollToElemet)

return (

)

How can I calculate the position of the element and scroll to it on page reload? Thanks

Body:
I would say, add an element at the bottom of your page and then use that element to scroll. Here is a sample

https://codesandbox.io/s/jolly-dhawan-k7q8b?fontsize=14&hidenavigation=1&theme=dark

Also, you need to pass [] as second argument so it only scroll on first mount otherwise it will keep on scrolling down to bottom on every change or on every render.

function App() {
  const [checked, setChecked] = useState(false);
  useEffect(() => {
    document.getElementById("footer").scrollIntoView();
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <span onClick={() => setChecked(v => !v)}>{checked ? "Enable" : "Disable"}</span>
      <h2>Start editing to see some magic happen!</h2>
      <div className="main">Main</div>
      <div id="footer" className="footer">
        Footer
      </div>
    </div>
  );
}


问:
How to calculate the SUM of rows values for one column of a table created using TCPDF?
Please could you help me to calculate and display the SUM VALUE of the rows of a column named "prime" in my table which is created in a PDF report using TCPDF (the data is being extracted from my database).
Thank you in advance. I would be very grateful if you could help me.
A better description of my result table in this link
The main part of my code is this:

```<code>    <?php
set_time_limit(0);
tcpdf();

 // create new PDF document
$pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// set default monospaced font
//$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
//$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';

// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);

// ---------------------------------------------------------

// add a page
$pdf->AddPage();

$pdf->SetXY(16, 10);

// set document information
$pdf->SetCreator(PDF_CREATOR);
//$pdf->SetAuthor('Nicola Asuni');
//$pdf->SetSubject('TCPDF Tutorial');
//$pdf->SetKeywords('TCPDF, PDF, example, navettes, guide');
// set default header data
//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.'', PDF_HEADER_STRING);
 $pdf->setPrintHeader(false);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

$pdf->setRTL(true);

$pdf->SetFont('xzar', '', 10);

    $sql= "SELECT * FROM nav_agent WHERE matricule='$mat'";
    $query = $this->db->query($sql);

$saut=0;
$tbl = '<table cellspacing="0" cellpadding="1" border="1">
   <thead>
        <tr>
            <th style="border: 1px double #000000; text-align:center;"  colspan="2">الإذن </th>
            <th style="border: 1px double #000000; text-align:center;"  colspan="2">التنقل</th>
            <th style="border: 1px double #000000; text-align:center;"  colspan="2">التوقيت</th>
            <th style="border: 1px double #000000; text-align:center;"  colspan="4"> </th>
       </tr>

<tr>
<td style="border: 1px double #000000; text-align:center;">العدد</td>
<td style="border: 1px double #000000; text-align:center;">التاريخ</td>
<td style="border: 1px double #000000; text-align:center;">من</td>
<td style="border: 1px double #000000; text-align:center;">إلى</td>
<td style="border: 1px double #000000; text-align:center;">الإنطلاق</td>
<td style="border: 1px double #000000; text-align:center;">الرجوع</td>
<td style="border: 1px double #000000; text-align:center;">المدة المقضاة (بالساعة)</td>
<td style="border: 1px double #000000; text-align:center;"> مبلغ منحة التنقل </td>
<td style="border: 1px double #000000; text-align:center;">رقم السيارة</td>
</tr>
';

$prime=0;
foreach ($query->result() as $row){

 $sql1 = "SELECT * FROM fiche_nav WHERE id_navette='$row->id_navette'";

  $query1 = $this->db->query($sql1);
foreach ($query1->result() as $row1){

$delai = strtotime($row1->heureret) - strtotime($row1->heuredep);
$time_h = ($delai/60)/60;

if ($val_grade == 'A1' or   $val_grade == 'A2')
    $montant1 = 15.000;
    else
        if ($val_grade == 'A3' or   $val_grade == 'B'
         or     $val_grade =='ouv cat 8' or $val_grade =='ouv cat 9' or $val_grade =='ouv cat 10')

    $montant1 = 9.000;
    else
        if ($val_grade == 'C' or    $val_grade == 'D'
         or     $val_grade =='ouv cat 1' or $val_grade =='ouv cat 2' or $val_grade =='ouv cat 3'
         or $val_grade =='ouv cat 4' or $val_grade =='ouv cat 5' or $val_grade =='ouv cat 6' or $val_grade =='ouv cat 7')

    $montant1 = 6.750;

if ($val_grade == 'A1' or   $val_grade == 'A2')
    $montant2 = 35.000;
    else
        if ($val_grade == 'A3' or   $val_grade == 'B'
         or     $val_grade =='ouv cat 8' or $val_grade =='ouv cat 9' or $val_grade =='ouv cat 10')

    $montant2 = 25.000;
    else
        if ($val_grade == 'C' or    $val_grade == 'D'
         or     $val_grade =='ouv cat 1' or $val_grade =='ouv cat 2' or $val_grade =='ouv cat 3'
         or $val_grade =='ouv cat 4' or $val_grade =='ouv cat 5' or $val_grade =='ouv cat 6' or $val_grade =='ouv cat 7')

    $montant2 = 18.000;

if ( $time_h <= 7 )
$prime = 0;
else

    if ( $time_h >7 && $time_h <= 14 )
$prime = 0.5 * $montant1;

else

    if ( $time_h >14 && $time_h < 24 )
$prime = $montant1;

else

    if ( $time_h >=24 )
$prime = $montant2;

$tbl=$tbl. '<tr>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->datedep .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->lieudep .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->destination .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->heuredep .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->heureret .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $time_h .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $prime .'</td>
<td style="border: 0px solid #000000; text-align:center;"> '.$row1->matriculevoiture .' </td>

<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center"></td>
</tr>
' ;

}

}

$tbl=$tbl.' </thead></table> ';

$pdf->writeHTML($tbl, true, false, false, false, '');

  // WHAT SHALL I ADD HERE TO CALCULATE the TOTAL VALUE i.e SUM OF "$PRIME" ROWS?

// close and output PDF document
 $date_auj=date('dmY',NOW());
    $strr = "Rapport-".$date_auj.".pdf";
$pdf->Output($strr, 'I');
//ob_end_clean();
//$pdf->Output($strr, 'I');

//============================================================+
// END OF FILE
//============================================================+
?>
</code>```

答:
you can declare a variable before $prime variable

```<code>$grandPrime=0;
$prime=0;
foreach ($query->result() as $row){
</code>```

initialize it here

```<code>$grandPrime+=$prime;
$tbl=$tbl. '<tr>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->datedep .'</td>
</code>```

and use it after your loop end.

Body:
Please could you help me to calculate and display the SUM VALUE of the rows of a column named "prime" in my table which is created in a PDF report using TCPDF (the data is being extracted from my database).
Thank you in advance. I would be very grateful if you could help me.
A better description of my result table in this link
The main part of my code is this:

    <?php
set_time_limit(0);
tcpdf();

 // create new PDF document
$pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// set default monospaced font
//$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
//$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';

// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);

// ---------------------------------------------------------

// add a page
$pdf->AddPage();

$pdf->SetXY(16, 10);

// set document information
$pdf->SetCreator(PDF_CREATOR);
//$pdf->SetAuthor('Nicola Asuni');
//$pdf->SetSubject('TCPDF Tutorial');
//$pdf->SetKeywords('TCPDF, PDF, example, navettes, guide');
// set default header data
//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.'', PDF_HEADER_STRING);
 $pdf->setPrintHeader(false);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

$pdf->setRTL(true);

$pdf->SetFont('xzar', '', 10);

    $sql= "SELECT * FROM nav_agent WHERE matricule='$mat'";
    $query = $this->db->query($sql);

$saut=0;
$tbl = '

            الإذن
            التنقل
            التوقيت

العدد
التاريخ
من
إلى
الإنطلاق
الرجوع
المدة المقضاة (بالساعة)
 مبلغ منحة التنقل
رقم السيارة

';

$prime=0;
foreach ($query->result() as $row){

 $sql1 = "SELECT * FROM fiche_nav WHERE id_navette='$row->id_navette'";

  $query1 = $this->db->query($sql1);
foreach ($query1->result() as $row1){

$delai = strtotime($row1->heureret) - strtotime($row1->heuredep);
$time_h = ($delai/60)/60;

if ($val_grade == 'A1' or   $val_grade == 'A2')
    $montant1 = 15.000;
    else
        if ($val_grade == 'A3' or   $val_grade == 'B'
         or     $val_grade =='ouv cat 8' or $val_grade =='ouv cat 9' or $val_grade =='ouv cat 10')

    $montant1 = 9.000;
    else
        if ($val_grade == 'C' or    $val_grade == 'D'
         or     $val_grade =='ouv cat 1' or $val_grade =='ouv cat 2' or $val_grade =='ouv cat 3'
         or $val_grade =='ouv cat 4' or $val_grade =='ouv cat 5' or $val_grade =='ouv cat 6' or $val_grade =='ouv cat 7')

    $montant1 = 6.750;

if ($val_grade == 'A1' or   $val_grade == 'A2')
    $montant2 = 35.000;
    else
        if ($val_grade == 'A3' or   $val_grade == 'B'
         or     $val_grade =='ouv cat 8' or $val_grade =='ouv cat 9' or $val_grade =='ouv cat 10')

    $montant2 = 25.000;
    else
        if ($val_grade == 'C' or    $val_grade == 'D'
         or     $val_grade =='ouv cat 1' or $val_grade =='ouv cat 2' or $val_grade =='ouv cat 3'
         or $val_grade =='ouv cat 4' or $val_grade =='ouv cat 5' or $val_grade =='ouv cat 6' or $val_grade =='ouv cat 7')

    $montant2 = 18.000;

if ( $time_h <= 7 )
$prime = 0;
else

    if ( $time_h >7 && $time_h <= 14 )
$prime = 0.5 * $montant1;

else

    if ( $time_h >14 && $time_h < 24 )
$prime = $montant1;

else

    if ( $time_h >=24 )
$prime = $montant2;

$tbl=$tbl. '

'. $row1->datedep .'
'. $row1->lieudep .'
'. $row1->destination .'
'. $row1->heuredep .'
'. $row1->heureret .'
'. $time_h .'
'. $prime .'
 '.$row1->matriculevoiture .'

' ;

}

}

$tbl=$tbl.'

 ';

$pdf->writeHTML($tbl, true, false, false, false, '');

  // WHAT SHALL I ADD HERE TO CALCULATE the TOTAL VALUE i.e SUM OF "$PRIME" ROWS?

// close and output PDF document
 $date_auj=date('dmY',NOW());
    $strr = "Rapport-".$date_auj.".pdf";
$pdf->Output($strr, 'I');
//ob_end_clean();
//$pdf->Output($strr, 'I');

//============================================================+
// END OF FILE
//============================================================+
?>

Body:
you can declare a variable before $prime variable

$grandPrime=0;
$prime=0;
foreach ($query->result() as $row){

initialize it here

$grandPrime+=$prime;
$tbl=$tbl. '<tr>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->datedep .'</td>

and use it after your loop end.


问:
StringWriter or StringBuilder
What is the difference between StringWriter and StringBuilder and when should I use one or the other?

答: The StringBuilder class is basically a mutable string, a helper class to construct an immutable string. The StringWriter is built on top to add more convenience functions for string formatting.

OwnerDisplayName: MAC

Title: StringWriter or StringBuilder

OwnerDisplayName: Konrad Rudolph

ContentLicense: CC BY-SA 2.5


问:
Get output from the search with PHP
I would like to get the output of my search from "https://login.ku.edu.tr/eGuide/servlet/eGuide" which is my university's eguide. However it is only accessible with in campus or the vpn.

My aim is, writing the php code which gets the output of the field "Location" in any search. But it is also ok if the code only works in the in campus or the computers who are login in the vpn servers.

How can I get this value from the search ?

Thanks.

答: that depends entirely on the format of the content retrieved by that search. without seeing any code, or resultant HTML, we can't provide any real advice for extracting the data. basically, you probably want to do some research on page scraping.</p>

Title: Get output from the search with PHP


问:
Git wrongly mark a file as deleted instead of rewritten
I'm doing several refactors on a project. So sometimes I need to rename the file extension, for example index.js -> index.ts, and change many lines on this file.

Because that git wrongly mark index.js as deleted and index.ts as a new file, that could be bad on code review and logs.

Is there some way to explicitly say to git "hey, I renamed index.js to index.ts"?

Edit

The approach using git add / git rm / git mv didn't work, because git still say that I created a new file and removed other.

Also I should not use two commits to that (one for rename and one for update its content), because the first commit will be broken, since the build steps for a .js file is different than a .ts file

答:
Git will usually notice if you moved the file, if you didn't muck around with the internals of the file too much. Either way, this is a bad practice and you should endeavor to always explicity move the file with git itself.

```<code>git mv index.js index.ts
</code>```

Typically I strongly prefer that the move and file alterations be done as separate commits.

If the damage is already done in that regard... it may be helpful to copy out the file you've changed, and revert the repo back. Then you can rename the file, and copy the alterations on top of it.

Body:
Git will usually notice if you moved the file, if you didn't muck around with the internals of the file too much. Either way, this is a bad practice and you should endeavor to always explicity move the file with git itself.

git mv index.js index.ts

Typically I strongly prefer that the move and file alterations be done as separate commits.

If the damage is already done in that regard... it may be helpful to copy out the file you've changed, and revert the repo back. Then you can rename the file, and copy the alterations on top of it.


问:
Using Azure Data Factory to ingest incoming data from a REST API
Is there a way to create an Azure ADF Pipeline to ingest the incoming POST requests? I have this gateway app (outside Azure) that is able to publish data via REST as it arrives from the application and this data needs to be ingested into a Data Lake. I am utilizing the REST calls from another pipeline to pull the data but this basically needs to do the reverse - the data will be pushed and i need to be constantly 'listening' to those calls...

Is this something an ADF pipeline should do or maybe there are any other Azure components able to do it?

答:
Previous comment is right and is one of the approach to get it working but would need bit of coding (for azure function).

There could also be an alternate solution to cater to your requirement is with Azure Logic Apps and Azure data factory.

Step 1:  Create a HTTP triggered logic app which would be invoked by your gateway app and data will be posted to this REST callable endpoint.

Step 2: Create ADF pipeline with a parameter, this parameter holds the data that needs to be pushed to the data lake. It could be raw data and can be transformed as a step within the pipeline before pushing it to the data lake.

Step 3: Once logic app is triggered, you can simply use Azure data factory actions to invoke the data factory pipeline created in step 2 and pass the posted data as a pipeline parameter to your ADF pipeline.

This should be it, with this - you can spin up your code-less solution.


问:
Adding elements to a form from another runspace
I have a form in which as soon as ready several elements will be added (for example, a list). It may take some time to add them (from fractions of a second to several minutes). Therefore, I want to add processing to a separate thread (child). The number of elements is not known in advance (for example, how many files are in the folder), so they are created in the child stream. When the processing in the child stream ends, I want to display these elements on the main form (before that the form did not have these elements and performed other tasks).

However, I am faced with the fact that I cannot add these elements to the main form from the child stream. I will give a simple example as an example. It certainly works:

```<code>$Main = New-Object System.Windows.Forms.Form

$Run = {

    # The form is busy while adding elements (buttons here)

    $Top = 0
    1..5 | % {

        $Button = New-Object System.Windows.Forms.Button
        $Button.Top = $Top
        $Main.Controls.Add($Button)
        $Top += 30
        Sleep 1
    }
}

$Main.Add_Shown($Run)

# Adding and performing other tasks on the form here

[void]$Main.ShowDialog()
</code>```

But, adding the same thing to the child stream I did not get the button to display on the main form. I do not understand why.

```<code>$Main = New-Object System.Windows.Forms.Form

$Run = {

    $RS = [Runspacefactory]::CreateRunspace()
    $RS.Open()
    $RS.SessionStateProxy.SetVariable('Main', $Main)
    $PS = [PowerShell]::Create().AddScript({

        # Many items will be added here. Their number and processing time are unknown in advance
        # Now an example with the addition of five buttons.

        $Top = 0
        1..5 | % {

            $Button = New-Object System.Windows.Forms.Button
            $Button.Top = $Top
            $Main.Controls.Add($Button)
            $Top += 30
            Sleep 1
        }
    })

    $PS.Runspace = $RS; $Null = $PS.BeginInvoke()
}

$Main.Add_Shown($Run)

[void]$Main.ShowDialog()
</code>```

How can I add elements to the main form that are created in the child stream? thanks

答:
While you can create controls on thread B, you cannot add them to a control that was created in thread A from thread B.

If you attempt that, you'll get the following exception:

Controls created on one thread cannot be parented to a control on a different thread.
```

<p><em>Parenting to</em> means calling the <code>.Add()</code> or <code>.AddRange()</code> method on a control (form) to add other controls as child controls.</p>

<p>In other words: <strong>In order to add controls to your <code>$Main</code> form, which is created and later displayed in the <em>original</em> thread (PowerShell runspace), the <code>$Main.Controls.Add()</code> call <em>must</em> occur in that same thread.</strong></p>

<p>Similarly, you should <strong>always attach <em>event delegates</em> (event-handler script blocks) in that same thread too.</strong></p>

<p>While your own answer attempts to ensure adding the buttons to the form in the original runspace, it doesn't work as written - see the bottom section.</p>

<p>I suggest a simpler approach:</p>

<ul>
<li><p>Use a <em>thread job</em> to create the controls in the background, via <code>Start-ThreadJob</code>.</p>

<ul>
<li><code>Start-ThreadJob</code> is part of the the <code>ThreadJob</code> module that offers a lightweight, <em>thread</em>-based alternative to the child-process-based regular background jobs and is also a more convenient alternative to creating runspaces via the PowerShell SDK.
It comes with PowerShell [Core] v6+ and in Windows PowerShell can be installed on demand with, e.g., <code>Install-Module ThreadJob -Scope CurrentUser</code>.
In most cases, thread jobs are the better choice, both for performance and type fidelity - see the bottom section of this answer for why.</li>
</ul></li>
<li><p>Show your form <em>non-modally</em> (<code>.Show()</code> rather than <code>.ShowDialog()</code>) and process GUI events in a <code>[System.Windows.Forms.Application]::DoEvents()</code> loop.</p>

<ul>
<li>Note: <code>[System.Windows.Forms.Application]::DoEvents()</code> can be problematic in general (it is essentially what the blocking <code>.ShowDialog()</code> call does behind the scenes), but in this constrained scenario (assuming only <em>one</em> form is to be shown) it should be fine. See this answer for background information.</li>
</ul></li>
<li><p>In the loop, check for newly created buttons as output by the thread job, attach an event handler, and add them to your form.</p></li>
</ul>

<p>Here is a working example that adds 3 buttons to the form after making it visible, one after the other while sleeping in between:</p>

```Add-Type -ea Stop -Assembly System.Windows.Forms

$Main = New-Object System.Windows.Forms.Form

# Start a thread job that will create the buttons.
$job = Start-ThreadJob {
    $top = 0
    1..3 | % {
        # Create and output a button object.
        ($btn = [System.Windows.Forms.Button] @{
            Name = "Button$_"
            Text = "Button$_"
            Top = $top
        })
        Start-Sleep 1
        $top += $btn.Height
    }
}

# Show the form asynchronously
$Main.Show()

# Process GUI events in a loop, and add
# buttons to the form as they're being created
# by the thread job.
while ($Main.Visible) {
    [System.Windows.Forms.Application]::DoEvents()
    if ($button = Receive-Job -Job $job) {
        # Add an event handler...
        $button.add_Click({ Write-Host "Button clicked: $($this.Name)" })
        # .. and it to the form.
        $Main.Controls.AddRange($button)
    }
}

# Clean up.
$Main.Dispose()
Remove-Job -Job $job -Force

'Done'
```

As of this writing, your own answer tries to achieve adding the controls to the form in the original runspace by using Register-ObjectEvent to subscribe to the other thread's (runspace's) events, given that the -Action script block used for event handling runs (in a dynamic module inside) the original thread (runspace), but there are two problems with that:

Unlike your answer suggests, the -Action script block neither directly sees the $Main variable from the original runspace, nor the other runspace's variables - these problems can be overcome, however, by passing $Main to Register-ObjectEvent via -MessageData and accessing it via $Event.MessageData in the script block, and by accessing the other runspace's variables via $Sender.Runspace.SessionStateProxy.GetVariable() calls.

More importantly, however, the .ShowDialog() call will block further processing; that is, your events won't fire and therefore your -Action script block won't be invoked until after the form closes.

Update: You mention a workaround in order to get PowerShell's events to fire while the form is being displayed:

Subscribe to the MouseMove event with a dummy event handler whose invocation gives PowerShell a chance to fire its own events while the form is being displayed modally; e.g.: $Main.Add_MouseMove({ Out-Host }); note that this workaround is only effective if the script block
calls a command, such as Out-Host in this example (which is effectively a no-op); a mere expression or .NET method call is not enough.

However, this workaround is suboptimal in that it relies on the user (continually) mousing over the form for the PowerShell events to fire; also, it is somewhat obscure and inefficient.

Body:
I have a form in which as soon as ready several elements will be added (for example, a list). It may take some time to add them (from fractions of a second to several minutes). Therefore, I want to add processing to a separate thread (child). The number of elements is not known in advance (for example, how many files are in the folder), so they are created in the child stream. When the processing in the child stream ends, I want to display these elements on the main form (before that the form did not have these elements and performed other tasks).

However, I am faced with the fact that I cannot add these elements to the main form from the child stream. I will give a simple example as an example. It certainly works:

$Main = New-Object System.Windows.Forms.Form

$Run = {

    # The form is busy while adding elements (buttons here)

    $Top = 0
    1..5 | % {

        $Button = New-Object System.Windows.Forms.Button
        $Button.Top = $Top
        $Main.Controls.Add($Button)
        $Top += 30
        Sleep 1
    }
}

$Main.Add_Shown($Run)

# Adding and performing other tasks on the form here

[void]$Main.ShowDialog()

But, adding the same thing to the child stream I did not get the button to display on the main form. I do not understand why.

$Main = New-Object System.Windows.Forms.Form

$Run = {

    $RS = [Runspacefactory]::CreateRunspace()
    $RS.Open()
    $RS.SessionStateProxy.SetVariable('Main', $Main)
    $PS = [PowerShell]::Create().AddScript({

        # Many items will be added here. Their number and processing time are unknown in advance
        # Now an example with the addition of five buttons.

        $Top = 0
        1..5 | % {

            $Button = New-Object System.Windows.Forms.Button
            $Button.Top = $Top
            $Main.Controls.Add($Button)
            $Top += 30
            Sleep 1
        }
    })

    $PS.Runspace = $RS; $Null = $PS.BeginInvoke()
}

$Main.Add_Shown($Run)

[void]$Main.ShowDialog()

How can I add elements to the main form that are created in the child stream? thanks

Body:
While you can create controls on thread B, you cannot add them to a control that was created in thread A from thread B.

If you attempt that, you'll get the following exception:

Controls created on one thread cannot be parented to a control on a different thread.

Parenting to means calling the .Add() or .AddRange() method on a control (form) to add other controls as child controls.

In other words: In order to add controls to your $Main form, which is created and later displayed in the original thread (PowerShell runspace), the $Main.Controls.Add() call must occur in that same thread.

Similarly, you should always attach event delegates (event-handler script blocks) in that same thread too.

While your own answer attempts to ensure adding the buttons to the form in the original runspace, it doesn't work as written - see the bottom section.

I suggest a simpler approach:

Use a thread job to create the controls in the background, via Start-ThreadJob.

Start-ThreadJob is part of the the ThreadJob module that offers a lightweight, thread-based alternative to the child-process-based regular background jobs and is also a more convenient alternative to creating runspaces via the PowerShell SDK.
It comes with PowerShell [Core] v6+ and in Windows PowerShell can be installed on demand with, e.g., Install-Module ThreadJob -Scope CurrentUser.
In most cases, thread jobs are the better choice, both for performance and type fidelity - see the bottom section of this answer for why.

Show your form non-modally (.Show() rather than .ShowDialog()) and process GUI events in a [System.Windows.Forms.Application]::DoEvents() loop.

Note: [System.Windows.Forms.Application]::DoEvents() can be problematic in general (it is essentially what the blocking .ShowDialog() call does behind the scenes), but in this constrained scenario (assuming only one form is to be shown) it should be fine. See this answer for background information.

In the loop, check for newly created buttons as output by the thread job, attach an event handler, and add them to your form.

Here is a working example that adds 3 buttons to the form after making it visible, one after the other while sleeping in between:

Add-Type -ea Stop -Assembly System.Windows.Forms

$Main = New-Object System.Windows.Forms.Form

# Start a thread job that will create the buttons.
$job = Start-ThreadJob {
    $top = 0
    1..3 | % {
        # Create and output a button object.
        ($btn = [System.Windows.Forms.Button] @{
            Name = "Button$_"
            Text = "Button$_"
            Top = $top
        })
        Start-Sleep 1
        $top += $btn.Height
    }
}

# Show the form asynchronously
$Main.Show()

# Process GUI events in a loop, and add
# buttons to the form as they're being created
# by the thread job.
while ($Main.Visible) {
    [System.Windows.Forms.Application]::DoEvents()
    if ($button = Receive-Job -Job $job) {
        # Add an event handler...
        $button.add_Click({ Write-Host "Button clicked: $($this.Name)" })
        # .. and it to the form.
        $Main.Controls.AddRange($button)
    }
}

# Clean up.
$Main.Dispose()
Remove-Job -Job $job -Force

'Done'

As of this writing, your own answer tries to achieve adding the controls to the form in the original runspace by using Register-ObjectEvent to subscribe to the other thread's (runspace's) events, given that the -Action script block used for event handling runs (in a dynamic module inside) the original thread (runspace), but there are two problems with that:

Unlike your answer suggests, the -Action script block neither directly sees the $Main variable from the original runspace, nor the other runspace's variables - these problems can be overcome, however, by passing $Main to Register-ObjectEvent via -MessageData and accessing it via $Event.MessageData in the script block, and by accessing the other runspace's variables via $Sender.Runspace.SessionStateProxy.GetVariable() calls.

More importantly, however, the .ShowDialog() call will block further processing; that is, your events won't fire and therefore your -Action script block won't be invoked until after the form closes.

Update: You mention a workaround in order to get PowerShell's events to fire while the form is being displayed:

Subscribe to the MouseMove event with a dummy event handler whose invocation gives PowerShell a chance to fire its own events while the form is being displayed modally; e.g.: $Main.Add_MouseMove({ Out-Host }); note that this workaround is only effective if the script block
calls a command, such as Out-Host in this example (which is effectively a no-op); a mere expression or .NET method call is not enough.

However, this workaround is suboptimal in that it relies on the user (continually) mousing over the form for the PowerShell events to fire; also, it is somewhat obscure and inefficient.


问:
Difference between InnoDB and MyISAM?

Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

```<code>$q = ("SELECT * ... );
$r = mysql_query($q);
</code>```

答:
Generally I go with InnoDB if my table will have more updates/inserts/delete statements then select statements or I want relational database with foreign keys, if not I stick with MyISAM. If you go with InnoDB you will give up select statement performance and the ability to do full text search indexes.

The MyISAM storage engine.

The InnoDB storage engine.

Title: Difference between InnoDB and MyISAM?

Body:
Possible Duplicate:

  MyISAM versus InnoDB

Ok I read this information of Wikipedia and InnoDB seems better. Here is my question would it be OK to use InnoDB instead of MyISAM for selecting user data from the database? Or would it be better to stay with MyISAM for this.

And if I would to change to Inno would PDO still work with it and some old style query's?

$q = ("SELECT * ... );
$r = mysql_query($q);