问:
Java Beans from xml returns null pointer exception
Hi i got a little problem with my app.
I'm trying to get bean data from xml.

beans.xml

```<code>        <bean id="s3Bean" class="com.example.demo.controller.S3Bean">
            <property name="s3Host" value="${s3.host}" />
            <property name="s3AccessKey" value="${s3.accessKey}"/>
            <property name="s3SecretKey" value="${s3.secretKey}"/>
            <property name="s3Bucket" value="${s3.bucket}"/>
        </bean>
</code>```

S3Bean.java

```<code>@ImportResource("classpath:beans.xml")
public class S3Bean {

    private String s3Host;
    private String s3AccessKey;
    private String s3SecretKey;
    private String s3Bucket;

    public void setS3AccessKey(String s3AccessKey) {
        this.s3AccessKey = s3AccessKey;
    }

    public void setS3SecretKey(String s3SecretKey) {
        this.s3SecretKey = s3SecretKey;
    }

    public void setS3Bucket(String s3Bucket) {
        this.s3Bucket = s3Bucket;
    }

    public void sets3Host(String s3Host) {
        this.s3Host = s3Host;
    }
}
</code>```

Class also have getters.
In my controller im trying to get bean like that.

```<code>    public S3Bean getS3Bean() {return S3Bean;}
    public void setS3Bean(S3Bean s3Bean) {S3Bean = s3Bean;}
    private S3Bean S3Bean;
...
    S3Bean.getS3Host();
</code>```

This get returns null pointer.
When im geting bean from application context it prints fine.

```<code>            ApplicationContext ctx = new ClassPathXmlApplicationContext("/beans.xml");
            S3Bean bean = ctx.getBean(S3Bean.class);
            System.out.println(bean.toString());
</code>```

Could you explain why the first way of getting property dosent working?

StackTrace

```<code>java.lang.NullPointerException: null
    at com.example.demo.controller.hello.sayHello(hello.java:27) ~[classes/:na]
</code>```

27 line is S3Bean.getS3Host();

答:
I found out what was the problem. I didnt declared S3Bean in beans.xml.</p>
```<code>        <bean id="springBean.Impl" class="com.example.demo.controller.Impl">
            <property name="S3Bean" ref="springBean.S3Bean"/>
        </bean>
</code>```

Body:
Hi i got a little problem with my app.
I'm trying to get bean data from xml.

beans.xml

        <bean id="s3Bean" class="com.example.demo.controller.S3Bean">
            <property name="s3Host" value="${s3.host}" />
            <property name="s3AccessKey" value="${s3.accessKey}"/>
            <property name="s3SecretKey" value="${s3.secretKey}"/>
            <property name="s3Bucket" value="${s3.bucket}"/>
        </bean>

S3Bean.java

@ImportResource("classpath:beans.xml")
public class S3Bean {

    private String s3Host;
    private String s3AccessKey;
    private String s3SecretKey;
    private String s3Bucket;

    public void setS3AccessKey(String s3AccessKey) {
        this.s3AccessKey = s3AccessKey;
    }

    public void setS3SecretKey(String s3SecretKey) {
        this.s3SecretKey = s3SecretKey;
    }

    public void setS3Bucket(String s3Bucket) {
        this.s3Bucket = s3Bucket;
    }

    public void sets3Host(String s3Host) {
        this.s3Host = s3Host;
    }
}

Class also have getters.
In my controller im trying to get bean like that.

    public S3Bean getS3Bean() {return S3Bean;}
    public void setS3Bean(S3Bean s3Bean) {S3Bean = s3Bean;}
    private S3Bean S3Bean;
...
    S3Bean.getS3Host();

This get returns null pointer.
When im geting bean from application context it prints fine.

            ApplicationContext ctx = new ClassPathXmlApplicationContext("/beans.xml");
            S3Bean bean = ctx.getBean(S3Bean.class);
            System.out.println(bean.toString());

Could you explain why the first way of getting property dosent working?

StackTrace

java.lang.NullPointerException: null
    at com.example.demo.controller.hello.sayHello(hello.java:27) ~[classes/:na]

27 line is S3Bean.getS3Host();

Body:
I found out what was the problem. I didnt declared S3Bean in beans.xml.

        <bean id="springBean.Impl" class="com.example.demo.controller.Impl">
            <property name="S3Bean" ref="springBean.S3Bean"/>
        </bean>


来源: stackexchange

问:
Width and precision format specifiers for printf
According to https://cplusplus.com/reference/cstdio/printf/ the printf format specifier follows this prototype:

```<code>%[flags][width][.precision][length]specifier
</code>```

Regarding width the above-mentioned web page states:

Minimum number of characters to be printed. If the value to be printed
is shorter than this number, the result is padded with blank spaces.
The value is not truncated even if the result is larger.

In the sample source code, as shown below, I have specified a width of 4 and a precision of 2, for printing the value of PI.  I was expecting the output to be padded by a single blank space, to meet the field width constraint of 4, since the precision is 2.  However, I am finding that the output is not padded by a single blank space.

```<code>#include <stdio.h>
#include <math.h>

int main()
{
   printf ("PI:%4.2f\n", M_PI);
   // Outputs PI:3.14, and not
   // PI: 3.14

   return 0;
}
</code>```

答:
Minimum number of characters to be printed

3.14 was printed - that's 4 characters 3 . 1 4. If you want to print an additional space, that would be 5 characters   3 . 1 4 - so width 5.

ContentLicense: CC BY-SA 4.0

Body:
According to https://cplusplus.com/reference/cstdio/printf/ the printf format specifier follows this prototype:

%[flags][width][.precision][length]specifier

Regarding width the above-mentioned web page states:

Minimum number of characters to be printed. If the value to be printed
is shorter than this number, the result is padded with blank spaces.
The value is not truncated even if the result is larger.

In the sample source code, as shown below, I have specified a width of 4 and a precision of 2, for printing the value of PI.  I was expecting the output to be padded by a single blank space, to meet the field width constraint of 4, since the precision is 2.  However, I am finding that the output is not padded by a single blank space.

#include <stdio.h>
#include <math.h>

int main()
{
   printf ("PI:%4.2f\n", M_PI);
   // Outputs PI:3.14, and not
   // PI: 3.14

   return 0;
}


问:
MySQL Create View Tables names from Schema and Count in loop
i need some ideas to create a MySQL View.

The base query collect all table names with prefix _dynamicgroup.

```<code>SELECT table_name AS tname FROM information_schema.tables where TABLE_NAME LIKE "%_dynamicgroup%"');
</code>```

As a next step I would like to have the number of individual fields of each table. In each table there is a column "ID".

```<code>SELECT count(id) FROM 10_dynamicgroup
</code>```

The view should then look like this:

IDcount
tname

23
10_dynamicgroup

17
33_dynamicgroup

27
3_dynamicgroup

1
56_dynamicgroup

110
18_dynamicgroup

Thank you for your ideas

答:
you can use.

SELECT ...
FROM ...
GROUP BY ...

</code

Body:
i need some ideas to create a MySQL View.

The base query collect all table names with prefix _dynamicgroup.

SELECT table_name AS tname FROM information_schema.tables where TABLE_NAME LIKE "%_dynamicgroup%"');

As a next step I would like to have the number of individual fields of each table. In each table there is a column "ID".

SELECT count(id) FROM 10_dynamicgroup

The view should then look like this:

IDcount
tname

23
10_dynamicgroup

17
33_dynamicgroup

27
3_dynamicgroup

1
56_dynamicgroup

110
18_dynamicgroup

Thank you for your ideas


问:
Pandas DataFrame conditional forward filling based on first row values
I have the following DataFrame:

import pandas as pd
df = pd.DataFrame({
    'col1':['A',pd.NA,pd.NA,pd.NA,pd.NA, 'B', pd.NA, pd.NA],
    'col2':[9.5, 6,24,8, 30, 7, 6, 8],
    })
print(df)
```
<p>Giving:</p>
```   col1  col2
0     A   9.5
1  <NA>   6.0
2  <NA>  24.0
3  <NA>   8.0
4  <NA>  30.0
5     B   7.0
6  <NA>   6.0
7  <NA>   8.0
```
<p>What I'd like to achieve is to forward fill col1, but not in rows where the value in col2 is greater than the col2 value of the row I'm forward filling from. Like so:</p>
```   col1  col2
0     A   9.5
1     A   6.0
2  <NA>  24.0
3     A   8.0
4  <NA>  30.0
5     B   7.0
6     B   6.0
7  <NA>   8.0
```
<p>Here, index 1 and 3 are forward filled, but index 2 and 4 are not, as the col2 values (24, 30) are greater than the initial row's col2 value (9.5)</p>
<p>I can achieve the desired result by iterating through the df, like so:</p>
<pre class="lang-py prettyprint-override"><code>val2 = -1
for i, r in df.iterrows():
    if not pd.isnull(r['col1']):
        val1 = r['col1']
        val2 = r['col2']
    else:
        if r['col2']<val2:
            df.loc[i, 'col1'] = val1
print(df)
</code>```

Is there a way to achieve this without using iterrows()?

答:
You can forward filling missing values to helper Series s and then compare groups by this Series - first value by all values and if values are not greater replace values in numpy.where:

```<code>s = df['col1'].ffill()

df['col1'] = np.where(df.groupby(s)['col2'].transform('first').gt(df['col2']),s,df['col1'])
print (df)
   col1  col2
0     A   9.5
1     A   6.0
2  <NA>  24.0
3     A   8.0
4  <NA>  30.0
5     B   7.0
6     B   6.0
7  <NA>   8.0
</code>```

Body:
I have the following DataFrame:

import pandas as pd
df = pd.DataFrame({
    'col1':['A',pd.NA,pd.NA,pd.NA,pd.NA, 'B', pd.NA, pd.NA],
    'col2':[9.5, 6,24,8, 30, 7, 6, 8],
    })
print(df)

Giving:

   col1  col2
0     A   9.5
1  <NA>   6.0
2  <NA>  24.0
3  <NA>   8.0
4  <NA>  30.0
5     B   7.0
6  <NA>   6.0
7  <NA>   8.0

What I'd like to achieve is to forward fill col1, but not in rows where the value in col2 is greater than the col2 value of the row I'm forward filling from. Like so:

   col1  col2
0     A   9.5
1     A   6.0
2  <NA>  24.0
3     A   8.0
4  <NA>  30.0
5     B   7.0
6     B   6.0
7  <NA>   8.0

Here, index 1 and 3 are forward filled, but index 2 and 4 are not, as the col2 values (24, 30) are greater than the initial row's col2 value (9.5)

I can achieve the desired result by iterating through the df, like so:

val2 = -1
for i, r in df.iterrows():
    if not pd.isnull(r['col1']):
        val1 = r['col1']
        val2 = r['col2']
    else:
        if r['col2']<val2:
            df.loc[i, 'col1'] = val1
print(df)

Is there a way to achieve this without using iterrows()?

Body:
You can forward filling missing values to helper Series s and then compare groups by this Series - first value by all values and if values are not greater replace values in numpy.where:

s = df['col1'].ffill()

df['col1'] = np.where(df.groupby(s)['col2'].transform('first').gt(df['col2']),s,df['col1'])
print (df)
   col1  col2
0     A   9.5
1     A   6.0
2  <NA>  24.0
3     A   8.0
4  <NA>  30.0
5     B   7.0
6     B   6.0
7  <NA>   8.0


问:
Neo4j - Architecture, Java API & Persistence
I just loved the concept of Graph Based Databases, specifically Neo4j. I have some queries:

Is there any Architecture document on Neo4j? I specifically want to know, suppose if I use Java API how the graph would persist in memory? I mean to say I want to create the graph once and then search multiple times however when we work on NEo4j Java API when the program terminates everything is lost, so how to persist it in memory. Where are the data files stored on disk?

Is there any way to create database from the Java API but use the http://localhost:7474/db/ interface to see the nodes graphically?

Thanks. Eagerly waiting for replies as I have gone crazy over Neo4j to solve one of my problem.

Thanks,
Yavar

答:
Data is persisted to disk when the transaction is marked as successful and finished. You can read more about transactions here:

manual

apidocs

code examples

Yes, have a look at Using the server with an embedded database!

ContentLicense: CC BY-SA 3.0


问:
Adding an association ( HasManyAddAssociationMixin ) after deleting it with { paranoid: true }
I have a user orm associated with a party orm that has something like this

```<code>  public getParties!: HasManyGetAssociationsMixin<Party>;
  public addParty!: HasManyAddAssociationMixin<Party, number>;
  public hasParty!: HasManyHasAssociationMixin<Party, number>;
  public countParties!: HasManyCountAssociationsMixin;
  public removeParty!: HasManyRemoveAssociationMixin<Party, number>;
</code>```

The association looks like this

```<code>User.belongsToMany(Party, { through: { model: 'UserParties', paranoid: true }, as: 'Parties' });
</code>```

and it works perfectly when I want to addParty or removeParty, But, If I try adding a party after having removed it, it doesn't work.

This, doesn't work

```<code>user.addParty(party) // works
user.removeParty(party) // works
user.addParty(party) // Doesn't work
</code>```

I got this error:

```<code>ERROR:  duplicate key value violates unique constraint "UserParties_pkey"
DETAIL:  Key ("UserId", "PartyId")=(1, 1) already exists.
</code>```

I know why I got this error, but how I can I make it so it overrides it, in the case it exists but has a deleted_at ?

答:
There are two ways:

don't use paranoid mode

include deletedAt to an unique constraint/index with all three fields: UserId, PartyId and deletedAt

Sequelize does not support a composite PK in associations. You need to add a separate autogenerated field as a PK

Body:
I have a user orm associated with a party orm that has something like this

  public getParties!: HasManyGetAssociationsMixin<Party>;
  public addParty!: HasManyAddAssociationMixin<Party, number>;
  public hasParty!: HasManyHasAssociationMixin<Party, number>;
  public countParties!: HasManyCountAssociationsMixin;
  public removeParty!: HasManyRemoveAssociationMixin<Party, number>;

The association looks like this

User.belongsToMany(Party, { through: { model: 'UserParties', paranoid: true }, as: 'Parties' });

and it works perfectly when I want to addParty or removeParty, But, If I try adding a party after having removed it, it doesn't work.

This, doesn't work

user.addParty(party) // works
user.removeParty(party) // works
user.addParty(party) // Doesn't work

I got this error:

ERROR:  duplicate key value violates unique constraint "UserParties_pkey"
DETAIL:  Key ("UserId", "PartyId")=(1, 1) already exists.

I know why I got this error, but how I can I make it so it overrides it, in the case it exists but has a deleted_at ?


问:
How to receive one variable from another widget in flutter?
*this is statefulWidget 1

```<code>class DiceRoll extends StatefulWidget {
  const DiceRoll({Key? key}) : super(key: key);

  @override
  _DiceRollState createState() => _DiceRollState();
}

class _DiceRollState extends State<DiceRoll> {

  int randomTime = 1;

  update(BuildContext context) {
    setState(() {

      randomTime = Random().nextInt(120) + 1;
    });
  }

 @override
  Widget build(BuildContext context) {
    return Container(

Text(randomTime),

    );
  }

</code>```

*this is statefulWidget 2

```<code>class demoTwo extends StatefulWidget {
  const ({ Key? key }) : super(key: key);

  @override
  _StatedemoTwo createState() => _StatedemoTwo();
}

class _StatedemoTwo extends State<demoTwo> {

int timerSet = time;
// I want to receive the random time from the first statefulWidget widget  here.. How to get the time here.

Timer? timer;

startTimer(BuildContext context) {
    timer = Timer.periodic(
      const Duration(seconds: 1),
      (_) {
        if (timerSet > 0) {
          if (mounted) {
            setState(() {
              timerSet--;
            });
          }
        } else {
          stopTimer();
          goBackHome();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }
}

</code>```

答:
Just copy the randomTime variable from widget 1 to widget 2.

Widget 1

```<code>class DiceRoll extends StatefulWidget {
  const DiceRoll({Key? key}) : super(key: key);

  @override
  _DiceRollState createState() => _DiceRollState();
}

class _DiceRollState extends State<DiceRoll> {

  int randomTime = 1;

  update(BuildContext context) {
    setState(() {

      randomTime = Random().nextInt(120) + 1;
    });
  }

 @override
  Widget build(BuildContext context) {
    return Column(
        children: <Widget>[
        Text(randomTime),
        //copy with constructor
        demoTwo(time: randomTime),
       ],
    );
  }
</code>```

Widget 2

```<code>class demoTwo extends StatefulWidget {
  int? time;

  demoTwo({this.time});

  @override
  _StatedemoTwo createState() => _StatedemoTwo();
}

class _StatedemoTwo extends State<demoTwo> {

int timerSet = widget.time;
// I want to receive the random time from the first statefulWidget widget  here.. How to get the time here.

Timer? timer;

startTimer(BuildContext context) {
    timer = Timer.periodic(
      const Duration(seconds: 1),
      (_) {
        if (timerSet > 0) {
          if (mounted) {
            setState(() {
              timerSet--;
            });
          }
        } else {
          stopTimer();
          goBackHome();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }
}
</code>```

Alternatively, use the Provider package to update and manage state.
https://pub.dev/packages/provider

Body:
*this is statefulWidget 1

class DiceRoll extends StatefulWidget {
  const DiceRoll({Key? key}) : super(key: key);

  @override
  _DiceRollState createState() => _DiceRollState();
}

class _DiceRollState extends State<DiceRoll> {

  int randomTime = 1;

  update(BuildContext context) {
    setState(() {

      randomTime = Random().nextInt(120) + 1;
    });
  }

 @override
  Widget build(BuildContext context) {
    return Container(

Text(randomTime),

    );
  }

*this is statefulWidget 2

class demoTwo extends StatefulWidget {
  const ({ Key? key }) : super(key: key);

  @override
  _StatedemoTwo createState() => _StatedemoTwo();
}

class _StatedemoTwo extends State<demoTwo> {

int timerSet = time;
// I want to receive the random time from the first statefulWidget widget  here.. How to get the time here.

Timer? timer;

startTimer(BuildContext context) {
    timer = Timer.periodic(
      const Duration(seconds: 1),
      (_) {
        if (timerSet > 0) {
          if (mounted) {
            setState(() {
              timerSet--;
            });
          }
        } else {
          stopTimer();
          goBackHome();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }
}

Body:
Just copy the randomTime variable from widget 1 to widget 2.

Widget 1

class DiceRoll extends StatefulWidget {
  const DiceRoll({Key? key}) : super(key: key);

  @override
  _DiceRollState createState() => _DiceRollState();
}

class _DiceRollState extends State<DiceRoll> {

  int randomTime = 1;

  update(BuildContext context) {
    setState(() {

      randomTime = Random().nextInt(120) + 1;
    });
  }

 @override
  Widget build(BuildContext context) {
    return Column(
        children: <Widget>[
        Text(randomTime),
        //copy with constructor
        demoTwo(time: randomTime),
       ],
    );
  }

Widget 2

class demoTwo extends StatefulWidget {
  int? time;

  demoTwo({this.time});

  @override
  _StatedemoTwo createState() => _StatedemoTwo();
}

class _StatedemoTwo extends State<demoTwo> {

int timerSet = widget.time;
// I want to receive the random time from the first statefulWidget widget  here.. How to get the time here.

Timer? timer;

startTimer(BuildContext context) {
    timer = Timer.periodic(
      const Duration(seconds: 1),
      (_) {
        if (timerSet > 0) {
          if (mounted) {
            setState(() {
              timerSet--;
            });
          }
        } else {
          stopTimer();
          goBackHome();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }
}

Alternatively, use the Provider package to update and manage state.
https://pub.dev/packages/provider


问:
semantic-release does not update package.json of my Angular library
I have this Angular library uploaded to a package registry that I created on Gitlab. I've already been able to upload my library successfully to this registry using the CI. I now want to implement semantic versionning to this library, but I'm not quite sure how to do it... The version of my library does not seem to update. Here is my current Gitlab CI config :

```<code>default:
  image: node:16
  before_script:
    - npm ci --cache node_modules --prefer-offline
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - node_modules/

stages:
  - build
  - semver-check
  - deploy

build:
  only:
    - main
  stage: build
  script:
    - npm install
    - npm run build-lib
  artifacts:
    paths:
      - dist/

semver-check:
  stage: semver-check
  only:
    refs:
    - main
    - alpha
    - /^(([0-9]+)\.)?([0-9]+)\.x/
    - /^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$/
  script:
    - cd $CI_PROJECT_DIR/dist/my-compiled-lib
    - cat package.json
    - npm install @semantic-release/gitlab
    - npx semantic-release
    - cat package.json

deploy:
  only:
    - main
  stage: deploy
  script:
    - cd $CI_PROJECT_DIR/dist/my-compiled-lib
    - cat package.json
    - echo "@my-group:registry https://${CI_SERVER_HOST}/api/v4/packages/npm/">.npmrc
    - echo "//${CI_SERVER_HOST}/api/v4/packages/npm/:_authToken=${CI_JOB_TOKEN}">>.npmrc
    - echo "//${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}">>.npmrc
    - npm publish
  dependencies:
    - build
</code>```

Library package.json

```<code>{
  "name": "@my-group/angular-lib",
  "version": "1.0.6",
  "publishConfig": {
    "@my-group:registry": "https://gitlab.com/api/v4/projects/XXXXXXX/packages/npm/"
  },
  "scripts": {
    "build-lib": "ng build lib-angular",
    "semantic-release": "semantic-release"
  },
  "peerDependencies": {
    "@angular/cdk": "^13.0.0",
    "@angular/common": "^13.1.0",
    "@angular/core": "^13.1.0",
    "@angular/material": "^13.2.0",
    "ngx-bootstrap": "^8.0.0",
    "rxjs": "~7.4.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "devDependencies": {
    "@semantic-release/gitlab": "^7.0.4",
    "semantic-release": "^19.0.2"
  }
}
</code>```

.releaserc.yml

```<code>{
  "branches": ["main"],
  "plugins": [
    "@semantic-release/commit-analyzer",
    "@semantic-release/release-notes-generator",
    [
      "@semantic-release/gitlab",
      {
        "gitlabUrl": "https://gitlab.com",
        "gitlabApiPathPrefix": "/api/v4",
        "verifyConditions": []
      }
    ],
    ["@semantic-release/npm", {
      "npmPublish": false,
      "tarballDir": "dist"
    }],
    [
      "@semantic-release/git",
      {
        "assets": ["dist/my-compiled-lib/package.json"],
        "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
      }
    ]
  ]
}
</code>```

答: The problem was that I was not triggering a release with my commit messages. Once that was sorted out, the package.json updated normally.</p>

Body:
I have this Angular library uploaded to a package registry that I created on Gitlab. I've already been able to upload my library successfully to this registry using the CI. I now want to implement semantic versionning to this library, but I'm not quite sure how to do it... The version of my library does not seem to update. Here is my current Gitlab CI config :

default:
  image: node:16
  before_script:
    - npm ci --cache node_modules --prefer-offline
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - node_modules/

stages:
  - build
  - semver-check
  - deploy

build:
  only:
    - main
  stage: build
  script:
    - npm install
    - npm run build-lib
  artifacts:
    paths:
      - dist/

semver-check:
  stage: semver-check
  only:
    refs:
    - main
    - alpha
    - /^(([0-9]+)\.)?([0-9]+)\.x/
    - /^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$/
  script:
    - cd $CI_PROJECT_DIR/dist/my-compiled-lib
    - cat package.json
    - npm install @semantic-release/gitlab
    - npx semantic-release
    - cat package.json

deploy:
  only:
    - main
  stage: deploy
  script:
    - cd $CI_PROJECT_DIR/dist/my-compiled-lib
    - cat package.json
    - echo "@my-group:registry https://${CI_SERVER_HOST}/api/v4/packages/npm/">.npmrc
    - echo "//${CI_SERVER_HOST}/api/v4/packages/npm/:_authToken=${CI_JOB_TOKEN}">>.npmrc
    - echo "//${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}">>.npmrc
    - npm publish
  dependencies:
    - build

Library package.json

{
  "name": "@my-group/angular-lib",
  "version": "1.0.6",
  "publishConfig": {
    "@my-group:registry": "https://gitlab.com/api/v4/projects/XXXXXXX/packages/npm/"
  },
  "scripts": {
    "build-lib": "ng build lib-angular",
    "semantic-release": "semantic-release"
  },
  "peerDependencies": {
    "@angular/cdk": "^13.0.0",
    "@angular/common": "^13.1.0",
    "@angular/core": "^13.1.0",
    "@angular/material": "^13.2.0",
    "ngx-bootstrap": "^8.0.0",
    "rxjs": "~7.4.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "devDependencies": {
    "@semantic-release/gitlab": "^7.0.4",
    "semantic-release": "^19.0.2"
  }
}

.releaserc.yml

{
  "branches": ["main"],
  "plugins": [
    "@semantic-release/commit-analyzer",
    "@semantic-release/release-notes-generator",
    [
      "@semantic-release/gitlab",
      {
        "gitlabUrl": "https://gitlab.com",
        "gitlabApiPathPrefix": "/api/v4",
        "verifyConditions": []
      }
    ],
    ["@semantic-release/npm", {
      "npmPublish": false,
      "tarballDir": "dist"
    }],
    [
      "@semantic-release/git",
      {
        "assets": ["dist/my-compiled-lib/package.json"],
        "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
      }
    ]
  ]
}


问:
NaCl OpenGL example
Now that nacl is about to be on by default in chrome I'd like to try writing an opengl game. It seems that this is possible because there is a working quake port, but I can't find any documentation about this. Does anyone have a minimal example? </p>

<p>Bonus question: can I do any kind of networking from nacl? E.g. web sockets? </p>

答:
I was trying to find the answer for this one a few days ago.

Here is a working NaCl OpenGL cube webpage

Here is the code for the sample you can compile "out of the box" like the other NaCl SDK samples:

BTW: I renamed the .nexe files to .n - to stop an annoying Chrome warning about the files.

Title: NaCl OpenGL example

Body:
Now that nacl is about to be on by default in chrome I'd like to try writing an opengl game. It seems that this is possible because there is a working quake port, but I can't find any documentation about this. Does anyone have a minimal example?

Bonus question: can I do any kind of networking from nacl? E.g. web sockets?


问:
Cannot read property 'setData' of undefined - React touch event
My touch function definition is

```<code>onDragStart(ev,id) {
    console.log('dragstart: ',id)
    ev.dataTransfer.setData("id",id)
}
onTouchStart(ev,id) {
    console.log('touchstart: ',id)
    ev.dataTransfer.setData("id",id)
}
</code>```

Here the console gives touchstart: 9824357 correctly, but the next line gives Cannot read property 'setData' of undefined. This codes works fine for onDragStart.

My div is

```<code><div
    onDragStart={(e)=>this.onDragStart(e, id)}
    onTouchStart={(e)=>this.onTouchStart(e, id)}
    draggable
    className="draggable">
</div>
</code>```

How can I fix this? Should I add or declare anything more for touch events?

答:
As has been told, dataTransfer is not a property for touch events.

Instead you can use ev.target for extracting the info of the touched element and then point to the property you want to transfer (in your case the id)
In your example:

In HTML just add an id to your draggable element:

```<code><div class="draggable" id="_draggable">
</div>
</code>```

In JS:

```<code>let box = document.querySelector(".draggable");

box.addEventListener('touchmove', (e) => {
    //Gets movement in px of the touch movement
    let touchLocation = e.targetTouches[0];
    //Gets element data
    currentElement = e.target;
    //Gets element id
    currentElementId = currentElement.id;

    //Moves element
    box.style.left = touchLocation.pageX + 'px';
    box.style.top = touchLocation.pageY + 'px';
})

box.addEventListener('touchend', (e) => {
    //Picks up the id of the dragged element
    console.log(currentElementId)

    //Picks up the new element position
    let x = parseInt(box.style.left);
    let y = parseInt(box.style.top);

})
</code>```

Also remember that the element to be dragged must have position: absolute;

Body:
My touch function definition is

onDragStart(ev,id) {
    console.log('dragstart: ',id)
    ev.dataTransfer.setData("id",id)
}
onTouchStart(ev,id) {
    console.log('touchstart: ',id)
    ev.dataTransfer.setData("id",id)
}

Here the console gives touchstart: 9824357 correctly, but the next line gives Cannot read property 'setData' of undefined. This codes works fine for onDragStart.

My div is

this.onDragStart(e, id)}
    onTouchStart={(e)=>this.onTouchStart(e, id)}
    draggable
    className="draggable">

How can I fix this? Should I add or declare anything more for touch events?

Body:
As has been told, dataTransfer is not a property for touch events.

Instead you can use ev.target for extracting the info of the touched element and then point to the property you want to transfer (in your case the id)
In your example:

In HTML just add an id to your draggable element:

<div class="draggable" id="_draggable">
</div>

In JS:

let box = document.querySelector(".draggable");

box.addEventListener('touchmove', (e) => {
    //Gets movement in px of the touch movement
    let touchLocation = e.targetTouches[0];
    //Gets element data
    currentElement = e.target;
    //Gets element id
    currentElementId = currentElement.id;

    //Moves element
    box.style.left = touchLocation.pageX + 'px';
    box.style.top = touchLocation.pageY + 'px';
})

box.addEventListener('touchend', (e) => {
    //Picks up the id of the dragged element
    console.log(currentElementId)

    //Picks up the new element position
    let x = parseInt(box.style.left);
    let y = parseInt(box.style.top);

})

Also remember that the element to be dragged must have position: absolute;


问:
Filter mongo document in django
The project stack is Django + MongoDB (djongo library).

I have product table with data structure like this

```<code>{
  _id:"qwer1234",
  organization:{...},
  service:{
      "id":1,
      ...

  }
}
</code>```

How can I get all documents where service.id will be in array of id ([1,2,3])?

答:
Simply use $in like this:

```<code>db.collection.find({
  "service.id": {
    "$in": yourArray
  }
})
</code>```

Check this example

Title: Filter mongo document in django

Body:
The project stack is Django + MongoDB (djongo library).

I have product table with data structure like this

{
  _id:"qwer1234",
  organization:{...},
  service:{
      "id":1,
      ...

  }
}

How can I get all documents where service.id will be in array of id ([1,2,3])?

Body:
Simply use $in like this:

db.collection.find({
  "service.id": {
    "$in": yourArray
  }
})

Check this example


问:
I am actually working on an ML problem and I have some date columns that contains just dates in plain integer format and I want to convert it
I am actually working on an ML problem and I have some date columns that contain just dates in plain integer format and I want to convert it.
Like: 20200225 into a date_time format...2020-02-25
I am using python
Any suggestions on how to work my way out.</p>

答:
I think this should be good for what your asking</p>
```<code>import datetime
today=datetime.datetime.today()
print(today)
</code>```

Body:
I think this should be good for what your asking

import datetime
today=datetime.datetime.today()
print(today)


问:
Error 302 when executing AT+CMGL="ALL"
I'm programming a modem using AT commands. When I execute AT+CMGL="ALL", I get an inconsistent result. Most of the time, it returned Error 302 (operation not allowed). At other times, it returns the list of messages. I'm using Multitech MTCBA-G-U.FA. This inconsistency makes it difficult to know what is happening.

I get the same behaviour when using putty as well. In all instances where AT+CMGL fails, AT always works returning OK.

regards

答:
Did you register with the GSM network via AT+COPS?

You can check via AT+COPS?.

Title: Error 302 when executing AT+CMGL="ALL"


问:
Repeated 'Too many certificates already issued for exact set of domains' error with GreenLock package
I have already checked this post. But even though I tried that method, it didn't work, so I open a new issue.

I use AWS EC2 server and deploy with aws pipeline. So When I push to github repository, it will automatically build and deploy to production server.

At first it's works fine, and there are no errors in the console.

But one day an error began to occur. So when I checked the console, there was an error as below.

[Error Message in console]

```<code>set greenlockOptions.notify to override the default logger
certificate_order (more info available: account subject altnames challengeTypes)
Error cert_issue:
[acme-v2.js] authorizations were not fetched for 'mydomain.com':
{"type":"urn:ietf:params:acme:error:rateLimited","detail":"Error creating new order :: too many certificates already issued for exact set of domains: mydomain.com: see https://letsencrypt.org/docs/rate-limits/","status":429,"_identifiers":[{"type":"dns","value":"mydomain.com"}]}
Error: [acme-v2.js] authorizations were not fetched for 'mydomain.com':
{"type":"urn:ietf:params:acme:error:rateLimited","detail":"Error creating new order :: too many certificates already issued for exact set of domains: mydomain.com: see https://letsencrypt.org/docs/rate-limits/","status":429,"_identifiers":[{"type":"dns","value":"mydomain.com"}]}
    at Object.E.NO_AUTHORIZATIONS (/home/project/build/node_modules/@root/acme/errors.js:75:9)
    at /home/project/build/node_modules/@root/acme/acme.js:1198:11
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
Error cert_issue:
[acme-v2.js] authorizations were not fetched for 'mydomain.com':
</code>```

In my opinion, I think there was a limit to the process of reissuing the certificate every time I push the code, but I don't know where the problem occurred even if I check the code.

My code structure is written as below and developed with Express.

[server.js]

```<code>"use strict";

const app = require("./app.js");

require("greenlock-express")
    .init({
        packageRoot: __dirname,
        configDir: "./greenlock.d",

        // contact for security and critical bug notices
        maintainerEmail: process.env.EMAIL,

        // whether or not to run at cloudscale
        cluster: false
    })
    // Serves on 80 and 443
    // Get's SSL certificates magically!
    .serve(app);
</code>```

[greenlock.d/config.json]

```<code>{ "sites": [{ "subject": "mydomain.com", "altnames": ["mydomain.com"] }] }
</code>```

[.greenlockrc]

```<code>{"configDir":"./greenlock.d"}
</code>```

[package.json (scripts.start line)]

```<code> "scripts": {
    "start": "node server.js"
  },
</code>```

I am aware of the seven-day limit from Let's Encrypt. So I want to find a way to solve this problem.

答:
in my express folder, I do

```<code>sudo chmod 775 ./greenlock.d
</code>```

then I delete greenlock.d(one time) and npm start

I dont have issue since

Body:
I have already checked this post. But even though I tried that method, it didn't work, so I open a new issue.

I use AWS EC2 server and deploy with aws pipeline. So When I push to github repository, it will automatically build and deploy to production server.

At first it's works fine, and there are no errors in the console.

But one day an error began to occur. So when I checked the console, there was an error as below.

[Error Message in console]

set greenlockOptions.notify to override the default logger
certificate_order (more info available: account subject altnames challengeTypes)
Error cert_issue:
[acme-v2.js] authorizations were not fetched for 'mydomain.com':
{"type":"urn:ietf:params:acme:error:rateLimited","detail":"Error creating new order :: too many certificates already issued for exact set of domains: mydomain.com: see https://letsencrypt.org/docs/rate-limits/","status":429,"_identifiers":[{"type":"dns","value":"mydomain.com"}]}
Error: [acme-v2.js] authorizations were not fetched for 'mydomain.com':
{"type":"urn:ietf:params:acme:error:rateLimited","detail":"Error creating new order :: too many certificates already issued for exact set of domains: mydomain.com: see https://letsencrypt.org/docs/rate-limits/","status":429,"_identifiers":[{"type":"dns","value":"mydomain.com"}]}
    at Object.E.NO_AUTHORIZATIONS (/home/project/build/node_modules/@root/acme/errors.js:75:9)
    at /home/project/build/node_modules/@root/acme/acme.js:1198:11
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
Error cert_issue:
[acme-v2.js] authorizations were not fetched for 'mydomain.com':

In my opinion, I think there was a limit to the process of reissuing the certificate every time I push the code, but I don't know where the problem occurred even if I check the code.

My code structure is written as below and developed with Express.

[server.js]

"use strict";

const app = require("./app.js");

require("greenlock-express")
    .init({
        packageRoot: __dirname,
        configDir: "./greenlock.d",

        // contact for security and critical bug notices
        maintainerEmail: process.env.EMAIL,

        // whether or not to run at cloudscale
        cluster: false
    })
    // Serves on 80 and 443
    // Get's SSL certificates magically!
    .serve(app);

[greenlock.d/config.json]

{ "sites": [{ "subject": "mydomain.com", "altnames": ["mydomain.com"] }] }

[.greenlockrc]

{"configDir":"./greenlock.d"}

[package.json (scripts.start line)]

 "scripts": {
    "start": "node server.js"
  },

I am aware of the seven-day limit from Let's Encrypt. So I want to find a way to solve this problem.

Body:
in my express folder, I do

sudo chmod 775 ./greenlock.d

then I delete greenlock.d(one time) and npm start

I dont have issue since


问:
UIDatePicker Month/Year Blank On Load
I have an almost working datepicker with the following settings:

Preferred Style: Automatic

Mode: Date

Locale: Default

Date: Current Date

My problem is the current month and year name do not appear on load. Instead, the right arrow icon is in its place, and the month and year name only show after I've selected a day from the calendar.

I've tried .setDate on the datePicker in viewDidLayoutSubviews() as a try, but still seeing the same result. Any guidance would be appreciated as I could not find any existing solution online.

I created the datePicker through storyboard, but here is the remaining code as it pertains to the datePicker onLoad:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    calendarDatePicker.preferredDatePickerStyle = .inline
    calendarDatePicker.overrideUserInterfaceStyle = .dark
    calendarDatePicker.date = //current date
    calendarDatePickerContainerView.layer.cornerRadius = 8
    calendarDatePickerContainerView.layer.masksToBounds = true
    calendarDatePickerContainerViewBottomConstraint.constant -= self.view.bounds.size.height
    self.view.layoutIfNeeded()
}
</code>```

```<code>override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    guard let current = currentDate else { return }
    calendarDatePicker.setDate(current, animated: true)
}
</code>```

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    DispatchQueue.main.async {
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseIn, animations: {
            self.calendarDatePickerContainerViewBottomConstraint.constant = 0
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}
</code>```

答:
the reason is that your device is in dark mode.
in night mode, default label color is white.
so if UI background is white, it looks like the labels-month/year/day is hidden.
you can see the UIDatePicker label color or you can change the dark to light mode.

Title: UIDatePicker Month/Year Blank On Load

Body:
I have an almost working datepicker with the following settings:

Preferred Style: Automatic

Mode: Date

Locale: Default

Date: Current Date

My problem is the current month and year name do not appear on load. Instead, the right arrow icon is in its place, and the month and year name only show after I've selected a day from the calendar.

I've tried .setDate on the datePicker in viewDidLayoutSubviews() as a try, but still seeing the same result. Any guidance would be appreciated as I could not find any existing solution online.

I created the datePicker through storyboard, but here is the remaining code as it pertains to the datePicker onLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    calendarDatePicker.preferredDatePickerStyle = .inline
    calendarDatePicker.overrideUserInterfaceStyle = .dark
    calendarDatePicker.date = //current date
    calendarDatePickerContainerView.layer.cornerRadius = 8
    calendarDatePickerContainerView.layer.masksToBounds = true
    calendarDatePickerContainerViewBottomConstraint.constant -= self.view.bounds.size.height
    self.view.layoutIfNeeded()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    guard let current = currentDate else { return }
    calendarDatePicker.setDate(current, animated: true)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    DispatchQueue.main.async {
        UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .curveEaseIn, animations: {
            self.calendarDatePickerContainerViewBottomConstraint.constant = 0
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}


问:
Using DISTINCT in Excel Data Model
I am using Excel Data Model where I have imported some data from an SQL Query. I am trying to do the excel equivalent of removing duplicates in a column.

So I saw the DISTINCT function exists and says: "Returns a one column table that contains the distinct (unique) values in a column, for a column argument."

That is exactly what I need, I have a column which has 2million rows but only about 4k distinct values/rows.

However when I go into the Calculation area and create the measure_distinct:=DISTINCT(TABLE_NAME[COLUMN_NAME]) it gives the following error: "Calculation error in measure 'TABLE_NAME'[measure_distinct]: A table of multiple values was supplied where a single value was expected"

I get that what I am trying to get is not a measure, it's a one column table and I probably shouldn't be using the DISTINCT function in the Calculation area. But I cannot figure out where or how to use it in order to get that column with unique values.

The objective is to import that column of distinct values into the Excel sheet.

Any help is greatly appreciated

Cheers

答:
As I said in my comments, this should really be done in Power Query. However, it can also be done using DAX.

You need to import a random table using Data/Existing Connections and then selecting one of the available tables, choosing 'Table' in the Import Dialog box.

Then, right-click in this table, select 'Table/Edit DAX', then 'DAX' in the Command Type dropdown and type this in the Expression box:

EVALUATE DISTINCT(TABLE_NAME[COLUMN_NAME])

Title: Using DISTINCT in Excel Data Model


问:
Does Common Lisp have any syntactic sugar for a while True, i.e. infinite, loop?
Common Lisp's LOOP macro has made it notorious for having everything and the kitchen sink when it comes to looping. Despite this, while loops are a bit difficult. Is the special case of while true, i.e. infinite loops, an exception? That is, does Common Lisp offer any syntactic sugar for infinite loops?

My attempts to find anything like this online have failed. This cookbook suggests making a circular list and then telling the LOOP macro to do something for each element in that infinite list. This clearly works, but it's not any sort of syntactic sugar. For comparison, the R language lets users write while(TRUE){...} as repeat{...}. This is the sort of syntactic sugar that I have in mind.

Note: As much as I love seeing Lisp macros, I'm not asking for anyone to implement repeat in Common Lisp. I want to know what is already in the language from the get go.

答:
Endless loop:

```<code>(loop while t
      do ...)
</code>```

above can be written shorter:

```<code>(loop do ...)
</code>```

above can be written shorter:

```<code>(loop ...)
</code>```

That's because LOOP already loops indefinitely by default.

Body:
Endless loop:

(loop while t
      do ...)

above can be written shorter:

(loop do ...)

above can be written shorter:

(loop ...)

That's because LOOP already loops indefinitely by default.


问:
Unable to sync new data and update the duplicate one with new data
I get updated and new products which i have to save in my db. The data which i recieve should be like if there is a new SKU it gets added and if there is an SKU whose details are updated then it should be updated. For eg if there is no SKU then it gets deleted in db as well

The for loop which i use below gives me updated products but it donot delete the pervious one for eg i there is and sku name ABC and i rename it to DEF then both the entries remain in my db, i want DEF to replcace ABC

In mappedProducts i get all the products

```<code>let updatedProducts = mappedProducts.filter(p => savedSKUs.indexOf(p.sku) != -1);
let newProducts = mappedProducts.filter(p => savedSKUs.indexOf(p.sku) == -1);
await dbProducts.insertMany(newProducts);

                for(let i= 0; i< updatedProducts.length; ++i){
                    let currentData = updatedProducts[i];
                    let operatingSKU = currentData.sku;
                    //await dbProducts.findOneAndDelete({sku: currentData.sku});
                    await dbProducts.findOneAndUpdate({
                        SGID: req.decoded.SGID,
                        sku: operatingSKU
                    },{$set: currentData})
                }
</code>```

答:
it's your filter that blocks the update because it has both values so it can't find the object to update.
Your filter should only contain the SGID value and the update one the sku value

Body:
I get updated and new products which i have to save in my db. The data which i recieve should be like if there is a new SKU it gets added and if there is an SKU whose details are updated then it should be updated. For eg if there is no SKU then it gets deleted in db as well

The for loop which i use below gives me updated products but it donot delete the pervious one for eg i there is and sku name ABC and i rename it to DEF then both the entries remain in my db, i want DEF to replcace ABC

In mappedProducts i get all the products

let updatedProducts = mappedProducts.filter(p => savedSKUs.indexOf(p.sku) != -1);
let newProducts = mappedProducts.filter(p => savedSKUs.indexOf(p.sku) == -1);
await dbProducts.insertMany(newProducts);

                for(let i= 0; i< updatedProducts.length; ++i){
                    let currentData = updatedProducts[i];
                    let operatingSKU = currentData.sku;
                    //await dbProducts.findOneAndDelete({sku: currentData.sku});
                    await dbProducts.findOneAndUpdate({
                        SGID: req.decoded.SGID,
                        sku: operatingSKU
                    },{$set: currentData})
                }


问:
How to obtain Pair Distance column in summary (MatchIt)
I'm trying to compare different CEM matchings, unfortunately the MatchIt package does not have the L statistic therefore I wanted to compare the Pair Distance conlumn that can be obained with the summary function

How can I print only that column? (Since I apply several trials in the original dataset and the variables are a lot I would like to avoid copy and paste)

```<code>library(tidyverse)
library(MatchIt)

data(lalonde)

cem1 <- matchit(treat ~ age + re74 + re75, data = lalonde,
                 method = "cem")

cem2 <- matchit(treat ~ age + re74 + re75, data = lalonde,
               method = "cem",
               cutpoints= list(age = c(20.5, 25.5, 30.5,35.5,40.5))
               )

summary(cem1, un=TRUE)
summary(cem2, un=TRUE)
</code>```

resutls I get

```<code>Call:
matchit(formula = treat ~ age + re74 + re75, data = lalonde,
    method = "cem", cutpoints = list(age = c(20.5, 25.5, 30.5,
        35.5, 40.5)))

Summary of Balance for All Data:
     Means Treated Means Control Std. Mean Diff. Var. Ratio eCDF Mean eCDF Max
age        25.8162       28.0303         -0.3094     0.4400    0.0813   0.1577
re74     2095.5737     5619.2365         -0.7211     0.5181    0.2248   0.4470
re75     1532.0553     2466.4844         -0.2903     0.9563    0.1342   0.2876

Summary of Balance for Matched Data:
    Means Treated Means Control Std. Mean Diff. Var. Ratio eCDF Mean eCDF Max Std. Pair
                                                                                Dist.
age        25.6286       25.8312         -0.0283     0.6863    0.0222   0.0619     0.2364
re74     1299.0813     1755.5500         -0.0934     1.1026    0.0672   0.3764     0.1321
re75     1016.9323     1228.5970         -0.0657     1.0062    0.0471   0.1852     0.1617

Percent Balance Improvement:
     Std. Mean Diff. Var. Ratio eCDF Mean eCDF Max
age             90.8       54.1      72.7     60.8
re74            87.0       85.1      70.1     15.8
re75            77.3       86.2      64.9     35.6

Sample Sizes:
              Control Treated
All            429.       185
Matched (ESS)  169.79     175
Matched        288.       175
Unmatched      141.        10
Discarded        0.         0
</code>```

what I would like to get a table like this one more or less

```<code>       cem1          cem2
       Pair. Dist.   Pair. Dist.
age    0.1616        0.2364
re74   0.1289        0.1321
re75   0.1671        0.1617
</code>```

答:
The summary() output is just a list. You can look at its details using str().

To get just the columns of interest, use the following:

```<code>cbind(
  summary(cem1)$sum.matched[,"Std. Pair Dist."],
  summary(cem2)$sum.matched[,"Std. Pair Dist."]
)
</code>```

Body:
I'm trying to compare different CEM matchings, unfortunately the MatchIt package does not have the L statistic therefore I wanted to compare the Pair Distance conlumn that can be obained with the summary function

How can I print only that column? (Since I apply several trials in the original dataset and the variables are a lot I would like to avoid copy and paste)

library(tidyverse)
library(MatchIt)

data(lalonde)

cem1 <- matchit(treat ~ age + re74 + re75, data = lalonde,
                 method = "cem")

cem2 <- matchit(treat ~ age + re74 + re75, data = lalonde,
               method = "cem",
               cutpoints= list(age = c(20.5, 25.5, 30.5,35.5,40.5))
               )

summary(cem1, un=TRUE)
summary(cem2, un=TRUE)

resutls I get

Call:
matchit(formula = treat ~ age + re74 + re75, data = lalonde,
    method = "cem", cutpoints = list(age = c(20.5, 25.5, 30.5,
        35.5, 40.5)))

Summary of Balance for All Data:
     Means Treated Means Control Std. Mean Diff. Var. Ratio eCDF Mean eCDF Max
age        25.8162       28.0303         -0.3094     0.4400    0.0813   0.1577
re74     2095.5737     5619.2365         -0.7211     0.5181    0.2248   0.4470
re75     1532.0553     2466.4844         -0.2903     0.9563    0.1342   0.2876

Summary of Balance for Matched Data:
    Means Treated Means Control Std. Mean Diff. Var. Ratio eCDF Mean eCDF Max Std. Pair
                                                                                Dist.
age        25.6286       25.8312         -0.0283     0.6863    0.0222   0.0619     0.2364
re74     1299.0813     1755.5500         -0.0934     1.1026    0.0672   0.3764     0.1321
re75     1016.9323     1228.5970         -0.0657     1.0062    0.0471   0.1852     0.1617

Percent Balance Improvement:
     Std. Mean Diff. Var. Ratio eCDF Mean eCDF Max
age             90.8       54.1      72.7     60.8
re74            87.0       85.1      70.1     15.8
re75            77.3       86.2      64.9     35.6

Sample Sizes:
              Control Treated
All            429.       185
Matched (ESS)  169.79     175
Matched        288.       175
Unmatched      141.        10
Discarded        0.         0

what I would like to get a table like this one more or less

       cem1          cem2
       Pair. Dist.   Pair. Dist.
age    0.1616        0.2364
re74   0.1289        0.1321
re75   0.1671        0.1617

Body:
The summary() output is just a list. You can look at its details using str().

To get just the columns of interest, use the following:

cbind(
  summary(cem1)$sum.matched[,"Std. Pair Dist."],
  summary(cem2)$sum.matched[,"Std. Pair Dist."]
)


问:
How can I convert some variables into numeric while keeping other variables same in R
Here I use this code to convert the factors to numeric variables:

```<code>Table1_2[] <- lapply(Table1_2, function(x) as.numeric(as.character(x)))
</code>```

But It converts all the variables so I cant use The FIRM variable anymore in the below plot.
My question is how can I change only the variables I want into numeric while keeping some of them in their original version?

```<code>install.packages('remotes')

remotes::install_github("brunoruas2/gujarati",force = TRUE)

library(gujarati)

library(ggplot2)

Table1_2[] <- lapply(Table1_2, function(x) as.numeric(as.character(x)))

ggplot(Table1_2, aes(Table1_2$C.1, Table1_2$I) +geom_point() + facet_wrap(~Table1_2$FIRM)+theme(legend.position = "none",
        panel.grid = element_blank(),
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.background = element_blank())
</code>```

答:
You can perform operations on subsets of dataframes (in your case only a few Cols) by restricting the Input and the overwritten variable of your cols. Lets say you want every column to be numeric except for  the column named FIRM:

col_is_not_FIRM <- colnames(Table1_2) != "FIRM"
Table1_2[col_is_not_FIRM] <- lapply(Table1_2 [col_is_not_FIRM], function(x) as.numeric(as.character(x)))
```

col_is_not_FIRM in this case is a logical vector, telling the subsetting operation, which columns to select. You can find a few ways for subsetting in dataframes here: https://www.statology.org/subset-data-frame-in-r/

Note that you have to subset on the left side of <- as well as on the right side. Else R will attempt to cram a larger dataframe into a smaller one or vise versa.

Body:
Here I use this code to convert the factors to numeric variables:

Table1_2[] <- lapply(Table1_2, function(x) as.numeric(as.character(x)))

But It converts all the variables so I cant use The FIRM variable anymore in the below plot.
My question is how can I change only the variables I want into numeric while keeping some of them in their original version?

install.packages('remotes')

remotes::install_github("brunoruas2/gujarati",force = TRUE)

library(gujarati)

library(ggplot2)

Table1_2[] <- lapply(Table1_2, function(x) as.numeric(as.character(x)))

ggplot(Table1_2, aes(Table1_2$C.1, Table1_2$I) +geom_point() + facet_wrap(~Table1_2$FIRM)+theme(legend.position = "none",
        panel.grid = element_blank(),
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        panel.background = element_blank())

Body:
You can perform operations on subsets of dataframes (in your case only a few Cols) by restricting the Input and the overwritten variable of your cols. Lets say you want every column to be numeric except for  the column named FIRM:

col_is_not_FIRM <- colnames(Table1_2) != "FIRM"
Table1_2[col_is_not_FIRM] <- lapply(Table1_2 [col_is_not_FIRM], function(x) as.numeric(as.character(x)))

col_is_not_FIRM in this case is a logical vector, telling the subsetting operation, which columns to select. You can find a few ways for subsetting in dataframes here: https://www.statology.org/subset-data-frame-in-r/

Note that you have to subset on the left side of <- as well as on the right side. Else R will attempt to cram a larger dataframe into a smaller one or vise versa.


问:
QWidget::repaint: Recursive repaint detected on Windows in Debug without creation of new threads
The following code sometimes failes on Windows x64 in DEBUG: I close the _mainView and see the empty white form of _loginView and then the program just crashes with QWidget::repaint: Recursive repaint detected message. I do not create any threads myself in my application.

void GuiLauncher::handleOnLogin()
{
    _loginView->hide();
    _loginView.reset();

    _mainView.reset(new MainView{});

    CONNECT(*_mainView, onLogout(), *this, handleOnLogout());

    _mainView->show();
}

void GuiLauncher::handleOnLogout()
{
    _mainView->hide();
    _mainView.reset();

    _loginView.reset(new LoginView{});

    CONNECT(*_loginView, onLogin(), *this, handleOnLogin());

    _loginView->show();
}
```
<p>In debugger in vscode I get:</p>
```Debug Assertion Failed!

Program: C:\Qt\5.12.12\msvc2017_64\bin\Qt5Widgetsd.dll
File: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\vector
Line: 208

Expression: vector iterator range transposed

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)
Loaded 'C:\Windows\System32\TextShaping.dll'.
Second Chance Assertion Failed: File C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\vector, Line 208
```

Is anything wrong with my code at the first glance? Thank  you for attention.

答:
It turned out that the crash (on Windows in DEBUG mode) is due the fact that auto-generated ui file contained:

```<code>       <widget class="QToolButton" name="button_logout">
       </widget>
</code>```

which would generate the code

        QToolButton *button_logout;
        button_logout = new QToolButton(widget_session_list);
        button_logout->setObjectName(QString::fromUtf8("button_logout"));
        header_layout->addWidget(button_logout);
```
<p>So having a clicked event due to this connection:</p>
<pre class="lang-cpp prettyprint-override"><code>...
    connect(_ui->button_logout, &QToolButton::clicked, this, &ViewImpl::performLogout);
...

void ViewImpl::performLogout()
{
    emit onLogout();
}
</code>```

led to the crash after the window would be hidden and deleted as a reaction on the signal onLogout().

So I have asked the next question: QToolButton crashes on clicked and window initialization.

Body:
The following code sometimes failes on Windows x64 in DEBUG: I close the _mainView and see the empty white form of _loginView and then the program just crashes with QWidget::repaint: Recursive repaint detected message. I do not create any threads myself in my application.

void GuiLauncher::handleOnLogin()
{
    _loginView->hide();
    _loginView.reset();

    _mainView.reset(new MainView{});

    CONNECT(*_mainView, onLogout(), *this, handleOnLogout());

    _mainView->show();
}

void GuiLauncher::handleOnLogout()
{
    _mainView->hide();
    _mainView.reset();

    _loginView.reset(new LoginView{});

    CONNECT(*_loginView, onLogin(), *this, handleOnLogin());

    _loginView->show();
}

In debugger in vscode I get:

Debug Assertion Failed!

Program: C:\Qt\5.12.12\msvc2017_64\bin\Qt5Widgetsd.dll
File: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\vector
Line: 208

Expression: vector iterator range transposed

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)
Loaded 'C:\Windows\System32\TextShaping.dll'.
Second Chance Assertion Failed: File C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\vector, Line 208

Is anything wrong with my code at the first glance? Thank  you for attention.

Body:
It turned out that the crash (on Windows in DEBUG mode) is due the fact that auto-generated ui file contained:

       <widget class="QToolButton" name="button_logout">
       </widget>

which would generate the code

        QToolButton *button_logout;
        button_logout = new QToolButton(widget_session_list);
        button_logout->setObjectName(QString::fromUtf8("button_logout"));
        header_layout->addWidget(button_logout);

So having a clicked event due to this connection:

...
    connect(_ui->button_logout, &QToolButton::clicked, this, &ViewImpl::performLogout);
...

void ViewImpl::performLogout()
{
    emit onLogout();
}

led to the crash after the window would be hidden and deleted as a reaction on the signal onLogout().

So I have asked the next question: QToolButton crashes on clicked and window initialization.


问:
Swapping between subclasses of an Abstract Class
I want to make an abstract class, A that will be subclassed by Class B and Class C such that they will all use the same methods in the defined abstract class (B and C are A-able classes).

I have another class, Z, that will contain an array of A-able classes. I would like for it to have a function that allows it to swap between B and C in that array (ie. calling initializer/member function with an argument).

The below example, while not being exactly like what I'm describing above (not using abstract classes), showcases the same issue I'm running into: I'm unable to set the array to the correct subclass, since it's complaining that it was initialized as the parent class.

However, this should be possible to do right? What am I missing here?

```<code>#include <iostream>
#include <array>

class BaseItem {
protected:
    std::string name;
    BaseItem(const std::string & name) : name(name) {};
    virtual void printName();
    virtual ~BaseItem() = default;
};

class Item1: public BaseItem {
public:
    using BaseItem::name;
    Item1() : BaseItem("Book1") {}
    void printName() {
        std::cout << "1" << name;
    }
};

class Item2: public BaseItem {
public:
    using BaseItem::name;
    Item2() : BaseItem("Book2") {}
    void printName() {
        std::cout << "2" << name;
    }
};

class Library {
  public:
    std::array<BaseItem, 2> books;
    void setToItem2() {
        for (size_t i = 0; i < books.size(); i++) {
            books[i] = new Item2();
        }
    }
    void setToItem1() {
        for (size_t i = 0; i < books.size(); i++) {
            books[i] = new Item1();
        }
    }
    void printBooks() {
        for (auto& entry: books) {
            entry->printName();
        }
    }
};

int main() {
    Library a;
    a.setToItem1();
    a.printBooks();
    a.setToItem2();
    a.printBooks();
    return 0;
}
</code>```

Edit: Cleaned up a bit, also adding error message below:

```<code>prog.cpp: In member function ‘void Library::setToItem2()’:
prog.cpp:36:31: error: no match for ‘operator=’ (operand types are ‘std::array<BaseItem, 2>::value_type’ {aka ‘BaseItem’} and ‘Item2*’)
</code>```

Edit2: Made the example code more representative of what I want to implement, utilizing code help from some of the existing answers.

Current potential solutions:

Evict books and pass in the correct subclass. This is currently what I'm going with. Just don't know if there is anything that can make this look cleaner (ie. all the casting looks a bit messy).

Make books a variant. The code looks cleaner here, but if I'm to extend to Item3, Item4, etc. I'll have to increase the variant to include all those subtypes, which IMHO defeats part of the purpose of making this "interface" (of course, we still get to inherit some shared things, but I'd like to not have to keep adding new classes into variant).

For now, I'm going to just do 1. But please let me know if there is something better.

答:
Like other comments, if you store a vector of superclass by value, say vector, as the vector allocates the memory, in addition to other information that vector stores, it will allocate sizeof(A)*NumOfElement(vector) for storage. As subclasses, say B need more space than A, object slicing will occur. My suggestion is, instead of storing the class as value, store those as reference. ex)vector<shared_ptr>. As the size of the pointer is same, this will allow to store A's subclasses. Oh, do not forget to define its virtual destructor!

Suggested code:

```<code>#include <iostream>
#include <vector>
#include <memory>

class Item {
public:
    Item() : name("Book1") {}
    std::string name;
    virtual void f1() {/* Your Implementation here or make it pure virtual */};
    virtual ~Item() = 0;
};

class Item2 : public Item {
public:
    Item2() { name = "Book2"; }
    //std::string name; //Hides base class name
    void f1() override {/* Your Implementation here */};
    ~Item2() = default;
};

class Library {
public:
    std::vector<std::shared_ptr<Item>> books;
    void setToItem2() {
        books.emplace_back(std::dynamic_pointer_cast<Item>(std::shared_ptr<Item2>(new Item2()))); //If you wish, use loop here
        books.emplace_back(std::dynamic_pointer_cast<Item>(std::shared_ptr<Item2>(new Item2())));
    }
    void printBooks() {
        for (auto& entry : books) {
            std::cout << entry->name;
        }
    }
};

int main() {
    Library a;
    a.printBooks();
    return 0;
}
</code>```

Body:
I want to make an abstract class, A that will be subclassed by Class B and Class C such that they will all use the same methods in the defined abstract class (B and C are A-able classes).

I have another class, Z, that will contain an array of A-able classes. I would like for it to have a function that allows it to swap between B and C in that array (ie. calling initializer/member function with an argument).

The below example, while not being exactly like what I'm describing above (not using abstract classes), showcases the same issue I'm running into: I'm unable to set the array to the correct subclass, since it's complaining that it was initialized as the parent class.

However, this should be possible to do right? What am I missing here?

#include <iostream>
#include <array>

class BaseItem {
protected:
    std::string name;
    BaseItem(const std::string & name) : name(name) {};
    virtual void printName();
    virtual ~BaseItem() = default;
};

class Item1: public BaseItem {
public:
    using BaseItem::name;
    Item1() : BaseItem("Book1") {}
    void printName() {
        std::cout << "1" << name;
    }
};

class Item2: public BaseItem {
public:
    using BaseItem::name;
    Item2() : BaseItem("Book2") {}
    void printName() {
        std::cout << "2" << name;
    }
};

class Library {
  public:
    std::array<BaseItem, 2> books;
    void setToItem2() {
        for (size_t i = 0; i < books.size(); i++) {
            books[i] = new Item2();
        }
    }
    void setToItem1() {
        for (size_t i = 0; i < books.size(); i++) {
            books[i] = new Item1();
        }
    }
    void printBooks() {
        for (auto& entry: books) {
            entry->printName();
        }
    }
};

int main() {
    Library a;
    a.setToItem1();
    a.printBooks();
    a.setToItem2();
    a.printBooks();
    return 0;
}

Edit: Cleaned up a bit, also adding error message below:

prog.cpp: In member function ‘void Library::setToItem2()’:
prog.cpp:36:31: error: no match for ‘operator=’ (operand types are ‘std::array<BaseItem, 2>::value_type’ {aka ‘BaseItem’} and ‘Item2*’)

Edit2: Made the example code more representative of what I want to implement, utilizing code help from some of the existing answers.

Current potential solutions:

Evict books and pass in the correct subclass. This is currently what I'm going with. Just don't know if there is anything that can make this look cleaner (ie. all the casting looks a bit messy).

Make books a variant. The code looks cleaner here, but if I'm to extend to Item3, Item4, etc. I'll have to increase the variant to include all those subtypes, which IMHO defeats part of the purpose of making this "interface" (of course, we still get to inherit some shared things, but I'd like to not have to keep adding new classes into variant).

For now, I'm going to just do 1. But please let me know if there is something better.

Body:
Like other comments, if you store a vector of superclass by value, say vector<A>, as the vector allocates the memory, in addition to other information that vector stores, it will allocate sizeof(A)*NumOfElement(vector<A>) for storage. As subclasses, say B need more space than A, object slicing will occur. My suggestion is, instead of storing the class as value, store those as reference. ex)vector<shared_ptr<A>>. As the size of the pointer is same, this will allow to store A's subclasses. Oh, do not forget to define its virtual destructor!

Suggested code:

#include <iostream>
#include <vector>
#include <memory>

class Item {
public:
    Item() : name("Book1") {}
    std::string name;
    virtual void f1() {/* Your Implementation here or make it pure virtual */};
    virtual ~Item() = 0;
};

class Item2 : public Item {
public:
    Item2() { name = "Book2"; }
    //std::string name; //Hides base class name
    void f1() override {/* Your Implementation here */};
    ~Item2() = default;
};

class Library {
public:
    std::vector<std::shared_ptr<Item>> books;
    void setToItem2() {
        books.emplace_back(std::dynamic_pointer_cast<Item>(std::shared_ptr<Item2>(new Item2()))); //If you wish, use loop here
        books.emplace_back(std::dynamic_pointer_cast<Item>(std::shared_ptr<Item2>(new Item2())));
    }
    void printBooks() {
        for (auto& entry : books) {
            std::cout << entry->name;
        }
    }
};

int main() {
    Library a;
    a.printBooks();
    return 0;
}


问:
I want to define a variable with superglobal scope in php
I want to define a variable in php with in a global scope. That variable should be accessible for each user, so it should not depend on the session.

I want to do something like the following: I have a php script, and that script usually takes about 5 to 15 minutes to execute, but it can take more than one hour in some special cases. This script is being run using a cron job with a 15 minutes interval. This script can also be run manually by any user.

Now it's possible to run any number of scripts at the same time. I want to limit this number of scripts.

So, I want a variable to store the number of currently executing scripts. I don't want to use a DB or files to store a single value.

Thanks in advance.

答:
Writing the variables to a specific memory address and reading and writing to/from that address with information such as a count might work.

An (old) article on IPC (inter process communication) might help you

http://zez.org/article/articleview/46/

Out of interest why is it you don't want to use files or a database?

Another solution (despite more than likely technically using files or a database) would be to force the script to use a specific session ID.

```<code><?php

$maximum = 1;

session_id(md5('myscript'));
session_start();

if( !isset( $_SESSION['count'] ) ) {
    $_SESSION['count'] = 1;
} else {
    if( $_SESSION['count'] >= $maximum ) {
        die( "too many processes running" );
    } else {
        $_SESSION['count']++;
    }
}

session_write_close();

// simulate running something
sleep(10);

session_id(md5('myscript'));
session_start();

$_SESSION['count']--;

session_write_close();

echo "<br />executed";

?>
</code>```

Note in the example above, the call to session_write_close() is important because the execution of the script will prevent the counter being incremented until it finishes otherwise. And then as it closes it, it needs reopening to decrement the counter.

Obviously because of the session reopening, any output from the script would need to be buffered (see http://www.php.net/ob_start) to prevent headers already sent errors

Body:
Writing the variables to a specific memory address and reading and writing to/from that address with information such as a count might work.

An (old) article on IPC (inter process communication) might help you

http://zez.org/article/articleview/46/

Out of interest why is it you don't want to use files or a database?

Another solution (despite more than likely technically using files or a database) would be to force the script to use a specific session ID.

<?php

$maximum = 1;

session_id(md5('myscript'));
session_start();

if( !isset( $_SESSION['count'] ) ) {
    $_SESSION['count'] = 1;
} else {
    if( $_SESSION['count'] >= $maximum ) {
        die( "too many processes running" );
    } else {
        $_SESSION['count']++;
    }
}

session_write_close();

// simulate running something
sleep(10);

session_id(md5('myscript'));
session_start();

$_SESSION['count']--;

session_write_close();

echo "<br />executed";

?>

Note in the example above, the call to session_write_close() is important because the execution of the script will prevent the counter being incremented until it finishes otherwise. And then as it closes it, it needs reopening to decrement the counter.

Obviously because of the session reopening, any output from the script would need to be buffered (see http://www.php.net/ob_start) to prevent headers already sent errors


问:
DTS task failed, DTS-077100: Record Replicator error in table asyncprocess.outgoing_bot. cause by jdbc Operation failed
I'm doing real-time replication between two SQL Server using Data Transmission Service (DTS) which provided by Alibaba Cloud. And after the full data migration completed, the task was suspended during incremental data migration.

Then I checked task details, it says:

"DTS task failed
Region: Malaysia (Kuala Lumpur)

Task ID/Name: dts-task-id-string / dts-task-name

DTS-077100: Record Replicator error in table asyncprocess.outgoing bot. cause by
[com.microsoft.sqlserver.jdbc.SQLServerException:Operationfailed.Theindexentryof
length 1910 bytes for the index ' WA Sys 00000004 3D2915A8' exceeds the maximum
length of 1700 bytes for nonclustered indexes.]

Also, I refer the related document as below, nothing found similar to my case.
https://www.alibabacloud.com/blog/solving-the-dts-077100-error-during-data-synchronization_598444

答:
In this case, the structure of the table mentioned in the output may not meet the requirements. Check data schema, be sure the table has primary key or at least has a unique non-null index.

Reference:
https://www.alibabacloud.com/help/doc-detail/34357.htm

All prerequisites for SQL Server incremental migration using DTS


问:
MySQL Create View Tables names from Schema and Count in loop
i need some ideas to create a MySQL View.

The base query collect all table names with prefix _dynamicgroup.

```<code>SELECT table_name AS tname FROM information_schema.tables where TABLE_NAME LIKE "%_dynamicgroup%"');
</code>```

As a next step I would like to have the number of individual fields of each table. In each table there is a column "ID".

```<code>SELECT count(id) FROM 10_dynamicgroup
</code>```

The view should then look like this:

IDcount
tname

23
10_dynamicgroup

17
33_dynamicgroup

27
3_dynamicgroup

1
56_dynamicgroup

110
18_dynamicgroup

Thank you for your ideas

答:
You should be querying the information_schema.COLUMNS table:

SELECT COUNT(*) AS IDcount, TABLE_NAME AS name
FROM information_schema.COLUMNS
WHERE TABLE_NAME LIKE '%_dynamicgroup%'
GROUP BY TABLE_NAME;
```

Body:
i need some ideas to create a MySQL View.

The base query collect all table names with prefix _dynamicgroup.

SELECT table_name AS tname FROM information_schema.tables where TABLE_NAME LIKE "%_dynamicgroup%"');

As a next step I would like to have the number of individual fields of each table. In each table there is a column "ID".

SELECT count(id) FROM 10_dynamicgroup

The view should then look like this:

IDcount
tname

23
10_dynamicgroup

17
33_dynamicgroup

27
3_dynamicgroup

1
56_dynamicgroup

110
18_dynamicgroup

Thank you for your ideas


问:
Azure B2C Custom Policy: How do you reset the TOTP settings in the event that a user lost access to there authenticator app?
In my custom policy I used the example here: https://github.com/azure-ad-b2c/samples/tree/master/policies/totp

I have TOTP working, but I want to make sure I will be able to reset it if a user doesn't have access to their authenticator app anymore.

NOTE: This is NOT using Azure B2C's built-in flows where you can enable TOTP in the settings.

答:
This seems like an Admin controlled operation. In which case

List the softwareOathMethods for the user, here.

Delete the softwareOathMethod for the user, here.

The B2C policy will then ask the user to re-enrol an authenticator device on next sign-in.


问:
How to animate line in scatter plot using plotly express?
Consider official example for scatter plot animation

```<code>import plotly.express as px
df = px.data.gapminder()
px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])
</code>```

this results in a plot in which markers are getting animated. However, I want to animate the connecting lines too which is not directly possible. I tried to update mode and marker properties for the frames like fig.frames.data[n].mode=markers+lines but still no luck. Could someone let me know where I am going wrong.

Cheers,
DD

答:
If you by animate the connecting lines means connecting, for example, all markers illustrating Asia etc in the example above, then adding the following to your code will produce the plot below.

```<code>fig.for_each_trace(lambda t: t.update(mode = 'lines+markers'))
for fr in fig.frames:
    for d in fr.data:
        d.update(mode='markers+lines')
</code>```

Plot:

Complete code:

```<code>import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90],
           # mode = 'markers+lines'
           height = 600, width = 1000
          )

# lineas and markers on first display
fig.for_each_trace(lambda t: t.update(mode = 'lines+markers'))

# lineas and markers on animation frames
for fr in fig.frames:
    for d in fr.data:
        d.update(mode='markers+lines')

fig.show()
</code>```

Body:
Consider official example for scatter plot animation

import plotly.express as px
df = px.data.gapminder()
px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])

this results in a plot in which markers are getting animated. However, I want to animate the connecting lines too which is not directly possible. I tried to update mode and marker properties for the frames like fig.frames.data[n].mode=markers+lines but still no luck. Could someone let me know where I am going wrong.

Cheers,
DD

Body:
If you by animate the connecting lines means connecting, for example, all markers illustrating Asia etc in the example above, then adding the following to your code will produce the plot below.

fig.for_each_trace(lambda t: t.update(mode = 'lines+markers'))
for fr in fig.frames:
    for d in fr.data:
        d.update(mode='markers+lines')

Plot:

Complete code:

import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90],
           # mode = 'markers+lines'
           height = 600, width = 1000
          )

# lineas and markers on first display
fig.for_each_trace(lambda t: t.update(mode = 'lines+markers'))

# lineas and markers on animation frames
for fr in fig.frames:
    for d in fr.data:
        d.update(mode='markers+lines')

fig.show()


问:
Stop Tkinter window taking focus when created
I want the tkinter window i'm creating to stop taking the program focus when it is opened but still stay on top and 'lifted' the program is simple however I cant seem to find a solution to make the window open but not take focus as im not even sure thats possible.</p>
```<code>from tkinter import *

Window = Tk()

champ_text = Label(Window, text='hello', font="arial, 100",)
champ_text.pack()

Window.wm_attributes('-disabled', False)
Window.lift()
Window.wm_attributes("-topmost", True)

#Window.overrideredirect(True)

Window.mainloop()

</code>```

答:
Foreground = focus. In my head.

You can however decide where you want the window to open on the screen:

```<code>Window.geometry('200x200+400+400')
</code>```

"200x200" is the size of the window that you open.
"+400+400" is the placement on the screen for the window.

Open the window in the foreground on the side of the screen will make it not so much in focus?

Body:
I want the tkinter window i'm creating to stop taking the program focus when it is opened but still stay on top and 'lifted' the program is simple however I cant seem to find a solution to make the window open but not take focus as im not even sure thats possible.

from tkinter import *

Window = Tk()

champ_text = Label(Window, text='hello', font="arial, 100",)
champ_text.pack()

Window.wm_attributes('-disabled', False)
Window.lift()
Window.wm_attributes("-topmost", True)

#Window.overrideredirect(True)

Window.mainloop()

Body:
Foreground = focus. In my head.

You can however decide where you want the window to open on the screen:

Window.geometry('200x200+400+400')

"200x200" is the size of the window that you open.
"+400+400" is the placement on the screen for the window.

Open the window in the foreground on the side of the screen will make it not so much in focus?


问:
What is the simplest way to add Facebook Connect to a PHP web site?

Facebook Connect

I have spent a few weeks putting together a basic web site which uses Facebook connect as authentication.

I have studied 'theRunAround', the provided example application. However the code is convoluted and uses a large number of files and classes, most of which have a lot of functionality that I have no need for. I have also had a good read of the documentation.

My code works almost all the time. However, occasionally I receive strange, unpredictable errors.

Required Features

Check if user is already logged in to Facebook, if so, retrieve the fb_uid, name, profile pic

Return a list of friends which have also connected to this application

Are there any tutorials, better than the ones provided by Facebook regarding such simple functionality?

答:
I wrote my own library to work with Facebook Connect as I found the one provided to be very lacking.

I can't provide the code as it is company code, but here's a breakdown of what I needed to do.  Hopefully you can use it and fill in the blanks easily yourself.

In your application settings, configure the "Connect" tab.  The "Connect URL" in my case is the root folder where my xd_receiver.htm file is.  Also, under "Advanced" I marked my app as a Web Application.

Put your xd_receiver.htm file in the root folder specified above.  There is a ton of documentation on xd_receiver.htm out there.  This is what facebook hits when the user logs in.  It will write cookies to their browser which your application can read in later to do authentication.

The cookies Facebook sets are in the format of _ where APIKEY is your apps API key and  is the name of the cookie.  You'll need the _session_key cookie to make further API calls.  If this cookie is not set, you need to show the login button as desscribed in steps 4 - 6.  Otherwise skip to step 7.

You need to load in the Facebook javascript file on your page that you will have the FB login button.  ==> http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php

To show the FB login button, use:

The Facebook JS will automatically render a facebook login button for you.  It will trigger the "facebook_onlogin" method that you shall define once the user is logged in so you can do something after they login.

Right below the above markup, you need to call the FB init javascript to have it render the button:

FB.init('YOUR API KEY HERE', 'ABSOLUTE PATH TO YOUR XD_RECEIVER.HTM FILE HERE');

Use the session_key  as set in the cookie to make any API calls.  How to make API calls is well documented.

Hope this helps.

OwnerDisplayName: Jon

ContentLicense: CC BY-SA 2.5