问:
returning a java.util.List in a Web Service
I try to create a Bottom up Java bean Web Service in eclipse  and I need to return a java.util.List so I have this on the server

```<code>public class BookStoreWS {
    private Book book1;
    private List<Book> listOfBooks;

    public Book getBook(){
        return  book1;
    }
    public List<Book> getBooks(){
        return  listOfBooks;
    }
}
</code>```

and this on the client

```<code>public static void main(String[] args) {
    BookStoreWSStub stub = new BookStoreWSStub();
    GetBookResponseDocument gbrd = stub.getBook();
    Book book = gbrd.getGetBookResponse().getReturn();//OK

    GetBooksResponseDocument gbrd2 = stub.getBooks();
    XmlObject OMGIAMNOTALIST = gbrd2.getGetBooksResponse().getReturn();//BAD
}
</code>```

So getBook() returns my desired object Book but getBooks() returns XmlObject instead of a List<Book>

Any easy way of getting a List<Book> instead of a XmlObject? Or to transform the XmlObject into a List<Book>?

答:
Is that what you are looking for?

```<code>List<A> OMGIAMALIST = new ArrayList<A>();
OMGIAMALIST.addAll(stub.getAs());

for ( A item : OMGIAMALIST ) {
    XmlObject OMGIAMANITEM = item.getGetAsResponse().getReturn();
}
</code>```

XmlObject (most probably) cannot be an A, but item surely is.

Body:
I try to create a Bottom up Java bean Web Service in eclipse  and I need to return a java.util.List so I have this on the server

public class BookStoreWS {
    private Book book1;
    private List<Book> listOfBooks;

    public Book getBook(){
        return  book1;
    }
    public List<Book> getBooks(){
        return  listOfBooks;
    }
}

and this on the client

public static void main(String[] args) {
    BookStoreWSStub stub = new BookStoreWSStub();
    GetBookResponseDocument gbrd = stub.getBook();
    Book book = gbrd.getGetBookResponse().getReturn();//OK

    GetBooksResponseDocument gbrd2 = stub.getBooks();
    XmlObject OMGIAMNOTALIST = gbrd2.getGetBooksResponse().getReturn();//BAD
}

So getBook() returns my desired object Book but getBooks() returns XmlObject instead of a List<Book>

Any easy way of getting a List<Book> instead of a XmlObject? Or to transform the XmlObject into a List<Book>?

Body:
Is that what you are looking for?

List<A> OMGIAMALIST = new ArrayList<A>();
OMGIAMALIST.addAll(stub.getAs());

for ( A item : OMGIAMALIST ) {
    XmlObject OMGIAMANITEM = item.getGetAsResponse().getReturn();
}

XmlObject (most probably) cannot be an A, but item surely is.


来源: stackexchange

问:
Does memcpy copy bytes in reverse order?
I am little bit confused on usage of memcpy. I though memcpy can be used to copy chunks of binary data to address we desire. I was trying to implement a small logic to directyl convert 2 bytes of hex to 16 bit signed integer without using union.

```<code> #include <stdio.h>
    #include <stdint.h>
    #include <string.h>
    int main()
    {   uint8_t message[2] = {0xfd,0x58};
        // int16_t roll = message[0]<<8;
        // roll|=message[1];
        int16_t roll = 0;
        memcpy((void *)&roll,(void *)&message,2);
        printf("%x",roll);

        return 0;
    }
</code>```

This return 58fd instead of fd58

答:
Does memcpy copy bytes in reverse order?

memcpy does not reverse the order bytes.

This return 58fd instead of fd58

Yes, your computer is little endian, so bytes 0xfd,0x58 in order are interpreted by your computer as the value 0x58fd.

ContentLicense: CC BY-SA 4.0

Body:
I am little bit confused on usage of memcpy. I though memcpy can be used to copy chunks of binary data to address we desire. I was trying to implement a small logic to directyl convert 2 bytes of hex to 16 bit signed integer without using union.

 #include <stdio.h>
    #include <stdint.h>
    #include <string.h>
    int main()
    {   uint8_t message[2] = {0xfd,0x58};
        // int16_t roll = message[0]<<8;
        // roll|=message[1];
        int16_t roll = 0;
        memcpy((void *)&roll,(void *)&message,2);
        printf("%x",roll);

        return 0;
    }

This return 58fd instead of fd58


问:
Pycharm GitHub 'Push failed: fatal: Authentication failed'
Every time I try to push a repository in GitHub with Pycharm the it fails.

```<code>Push failed: fatal: Authentication failed for 'https://github.com/(my github repository)/'
</code>```

In Settings->Version Control->GitHub, I filled the fields Host, Loging and Password (Auth Type: Password).  Testing it: "Connection successful"

In Settings->Version Control->Git, Path to Git executable is seted with the full path, SSH executable: Buil-in

Pycharm version 3.1.1
Git version 1.8.4.msysgit.0
On Win 7.

答:
I am using High Sierra on an old iMac and originally tried to push a new local project to a new remote.

Unable to get authentication working on Terminal I then tried to use PyCharm as a vehicle to save the authentication token from Github.

In the past I was accustomed to the IDE prompting for the use of a token and even suggesting me to open Github.com to generate the appropriate one.

PyCharm was not able to push a new branch but it did not give any such hints for a solution in the error message

```<code>12:56   Push failed
        git@github.com: Permission denied (publickey).
        Could not read from remote repository.

        Please make sure you have the correct access rights
        and the repository exists.
        Show details in console
</code>```

My solution was to go into the settings and there I found the connection to Github unset - and I was able to link a token.

But I also had to set the remote with the HTTPS link. When I tried with the SSH URI it did not work.

ContentLicense: CC BY-SA 3.0

Body:
Every time I try to push a repository in GitHub with Pycharm the it fails.

Push failed: fatal: Authentication failed for 'https://github.com/(my github repository)/'

In Settings->Version Control->GitHub, I filled the fields Host, Loging and Password (Auth Type: Password).  Testing it: "Connection successful"

In Settings->Version Control->Git, Path to Git executable is seted with the full path, SSH executable: Buil-in

Pycharm version 3.1.1
Git version 1.8.4.msysgit.0
On Win 7.

Body:
I am using High Sierra on an old iMac and originally tried to push a new local project to a new remote.

Unable to get authentication working on Terminal I then tried to use PyCharm as a vehicle to save the authentication token from Github.

In the past I was accustomed to the IDE prompting for the use of a token and even suggesting me to open Github.com to generate the appropriate one.

PyCharm was not able to push a new branch but it did not give any such hints for a solution in the error message

12:56   Push failed
        git@github.com: Permission denied (publickey).
        Could not read from remote repository.

        Please make sure you have the correct access rights
        and the repository exists.
        Show details in console

My solution was to go into the settings and there I found the connection to Github unset - and I was able to link a token.

But I also had to set the remote with the HTTPS link. When I tried with the SSH URI it did not work.


问:
Bezier curve : forcing a curve of 4 points to pass through control points in 3D space
I have read the thread to make this happen for 4 points but only in 2D space here .

I have implemented the answer for 3D but only for 3 control points here

I have read this post but don't understand the sudo code or the math

Can anyone simplify in java? I don't want to draw the curve as 2 segments of 3 points

答:
To draw the cubic curve after computing the points p[x][y]:

```<code>public void paint(Graphics g) {
  Graphics2D g2d = (Graphics2D) g;
  CubicCurve2D cubcurve = new CubicCurve2D.Float(p[0][0], p[0][1], p[1][0], p[1][1], p[2][0], p[2][1], p[3][0], p[3][0]);
  g2d.draw(cubcurve);
}
</code>```

(Re: http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/CubicCurve2DFloat.htm)

Body:
To draw the cubic curve after computing the points p[x][y]:

public void paint(Graphics g) {
  Graphics2D g2d = (Graphics2D) g;
  CubicCurve2D cubcurve = new CubicCurve2D.Float(p[0][0], p[0][1], p[1][0], p[1][1], p[2][0], p[2][1], p[3][0], p[3][0]);
  g2d.draw(cubcurve);
}

(Re: http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/CubicCurve2DFloat.htm)


问:
Undefined is not an object (evaluating '_$$_REQUIRE(_dependencyMap[5], "expo-camera").Camera')
I am trying to install the expo camera on my device,
but I keep running into problems. I only did 3 things

expo install expo-camera.

copy the example code to my project.

add expo camera to package.json.

I followed this tutorial: https://docs.expo.dev/versions/latest/sdk/camera/

I think the problem might be: In managed apps, Camera requires Permissions.CAMERA. Video recording requires Permissions.AUDIO_RECORDING.

I have no clue what to do with that.

Good to know:

I also tried to install the react native camera https://react-native-camera.github.io/react-native-camera/docs/installation . with no succes ofcourse :(

Package.json:

```<code>{
  "name": "untitled",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "17.0.2",
    "react-native": "0.67.2"
  },
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/runtime": "^7.16.7",
    "@react-native-community/eslint-config": "^3.0.1",
    "babel-jest": "^27.4.6",
    "eslint": "^7.32.0",
    "jest": "^27.4.7",
    "metro-react-native-babel-preset": "^0.67.0",
    "react-test-renderer": "17.0.2",
    "expo-camera": "~12.0.3"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

Camera.js

```<code>import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import {Camera} from 'expo-camera';

export default function App() {
  const [hasPermission, setHasPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);

  useEffect(() => {
    (async () => {
      const {status} = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }
  return (
    <View style={styles.container}>
      <Camera style={styles.camera} type={type}>
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={styles.button}
            onPress={() => {
              setType(
                type === Camera.Constants.Type.back
                  ? Camera.Constants.Type.front
                  : Camera.Constants.Type.back,
              );
            }}>
            <Text style={styles.text}> Flip </Text>
          </TouchableOpacity>
        </View>
      </Camera>
    </View>
  );
}

const styles = StyleSheet.create({});
</code>```

Errors:

答:
Update

If you want to use any of the expo modules easily, you would need to install "Expo Modules".

If you are migrating from react-native-unimodules
see this: https://expo.fyi/expo-modules-migration/

To Install Expo Modules in your project, run the following command:

```<code>npx install-expo-modules
</code>```

If there is an error follow the manual installation:
https://docs.expo.dev/bare/installing-expo-modules/#manual-installation

Old

I think the problem might be that you have the expo-camera dependency as a development dependency.

You could try moving the

```<code>{
  ...
  devDependencies:{
    "expo-camera": "~12.0.3"
  }
  ...
}
</code>```

to

```<code>{
  ...
  dependencies:{
    "expo-camera": "~12.0.3"
  }
  ...
}
</code>```

Body:
I am trying to install the expo camera on my device,
but I keep running into problems. I only did 3 things

expo install expo-camera.

copy the example code to my project.

add expo camera to package.json.

I followed this tutorial: https://docs.expo.dev/versions/latest/sdk/camera/

I think the problem might be: In managed apps, Camera requires Permissions.CAMERA. Video recording requires Permissions.AUDIO_RECORDING.

I have no clue what to do with that.

Good to know:

I also tried to install the react native camera https://react-native-camera.github.io/react-native-camera/docs/installation . with no succes ofcourse :(

Package.json:

{
  "name": "untitled",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "17.0.2",
    "react-native": "0.67.2"
  },
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/runtime": "^7.16.7",
    "@react-native-community/eslint-config": "^3.0.1",
    "babel-jest": "^27.4.6",
    "eslint": "^7.32.0",
    "jest": "^27.4.7",
    "metro-react-native-babel-preset": "^0.67.0",
    "react-test-renderer": "17.0.2",
    "expo-camera": "~12.0.3"
  },
  "jest": {
    "preset": "react-native"
  }
}

Camera.js

import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import {Camera} from 'expo-camera';

export default function App() {
  const [hasPermission, setHasPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);

  useEffect(() => {
    (async () => {
      const {status} = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }
  return (
    <View style={styles.container}>
      <Camera style={styles.camera} type={type}>
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={styles.button}
            onPress={() => {
              setType(
                type === Camera.Constants.Type.back
                  ? Camera.Constants.Type.front
                  : Camera.Constants.Type.back,
              );
            }}>
            <Text style={styles.text}> Flip </Text>
          </TouchableOpacity>
        </View>
      </Camera>
    </View>
  );
}

const styles = StyleSheet.create({});

Errors:

Body:
Update

If you want to use any of the expo modules easily, you would need to install "Expo Modules".

If you are migrating from react-native-unimodules
see this: https://expo.fyi/expo-modules-migration/

To Install Expo Modules in your project, run the following command:

npx install-expo-modules

If there is an error follow the manual installation:
https://docs.expo.dev/bare/installing-expo-modules/#manual-installation

Old

I think the problem might be that you have the expo-camera dependency as a development dependency.

You could try moving the

{
  ...
  devDependencies:{
    "expo-camera": "~12.0.3"
  }
  ...
}

to

{
  ...
  dependencies:{
    "expo-camera": "~12.0.3"
  }
  ...
}


问:
AWS Lambda : how to handle a code asset defined by an environment variable that does not exist yet?
I (try to) deploy my current application using CDK pipelines.

In doing so, I stumbled across an unexpected behavior (here if interested) which now I am trying to resolve. I have a Lambda function for which the asset is a directory that is dynamically generated during a CodeBuild step. The line is currently defined like this in my CDK stack :

code: lambda.Code.fromAsset(process.env.CODEBUILD_SRC_DIR_BuildLambda || "")
```

The issue is that locally, this triggers the unexpected and undesired behaviour because the environment variable does not exist and therefore goes to the default "".

What is the proper way to avoid this issue?

Thanks!

答:
Option 1: Set the env var locally, pointing to the correct source directory;

CODEBUILD_SRC_DIR_BuildLambda=path/to/lambda && cdk deploy
```
<p><strong>Option 2:</strong> Define a dummy asset if <code>CODEBUILD_SRC_DIR_BuildLambda</code> is undefined</p>
<pre class="lang-js prettyprint-override"><code>code: process.env.CODEBUILD_SRC_DIR_BuildLambda
  ? lambda.Code.fromAsset(process.env.CODEBUILD_SRC_DIR_BuildLambda)
  : new lambda.InlineCode('exports.handler = async () => console.log("NEVER")'),
</code>```

Body:
I (try to) deploy my current application using CDK pipelines.

In doing so, I stumbled across an unexpected behavior (here if interested) which now I am trying to resolve. I have a Lambda function for which the asset is a directory that is dynamically generated during a CodeBuild step. The line is currently defined like this in my CDK stack :

code: lambda.Code.fromAsset(process.env.CODEBUILD_SRC_DIR_BuildLambda || "")

The issue is that locally, this triggers the unexpected and undesired behaviour because the environment variable does not exist and therefore goes to the default "".

What is the proper way to avoid this issue?

Thanks!

Body:
Option 1: Set the env var locally, pointing to the correct source directory;

CODEBUILD_SRC_DIR_BuildLambda=path/to/lambda && cdk deploy

Option 2: Define a dummy asset if CODEBUILD_SRC_DIR_BuildLambda is undefined

code: process.env.CODEBUILD_SRC_DIR_BuildLambda
  ? lambda.Code.fromAsset(process.env.CODEBUILD_SRC_DIR_BuildLambda)
  : new lambda.InlineCode('exports.handler = async () => console.log("NEVER")'),


问:
How To Get Google User Profile Info Using Access Token From OAuth?
I am using ReactJS on the frontend: I successfully retrieved the access token from Google's Oauth service, but it doesn't give me any profile information for the 'current user'.

I tried using the /userInfo endpoint, ?access_token={my_access_token} query str, and some other solutions but I keep getting weird errors.

Currently I have:

```<code>  const { access_token, refresh_token } = res.data; // now I have valid access_token
  let userInfo = await axios.get("https://www.googleapis.com/oauth2/v3/userinfo",
  {
    headers: {
      Authorization: `Bearer ${access_token}`
    }
  }); // ERROR WHEN MAKING THIS CALL.
</code>```

My specific 401 error is as follows:

If there are better ways of getting user info (such as first/last name, email, etc. some sort of unique ID) please let me know.

答:
You shouldnt rely on the user info endpoint to get user profile informaiton.  As long as you are requesting the profile scope from the user, or even email. you should go though the People api.  This will give you access to all of the users profile data.

```<code>GET https://people.googleapis.com/v1/people/me?personFields=names HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json
</code>```

response

```<code>{
  "resourceName": "people/117dd2004755326722775346",
  "etag": "%EgUBAi43PRoEAQIFBddyIMR3BzQkR2cnI1ZGc9",
  "names": [
    {
      "metadata": {
        "primary": true,
        "source": {
          "type": "PROFILE",
          "id": "117200155326727753146"
        }
      },
      "displayName": "Linda Lawton",
      "familyName": "Lawton",
      "givenName": "Linda",
      "displayNameLastFirst": "Lawton, Linda",
      "unstructuredName": "Linda Lawton"
    },
    {
      "metadata": {
        "source": {
          "type": "CONTACT",
          "id": "3faa96eb0118baa4be"
        }
      },
      "displayName": "Linda Lawton",
      "familyName": "Lawton",
      "givenName": "Linda",
      "displayNameLastFirst": "Lawton, Linda",
      "unstructuredName": "Linda Lawton"
    }
  ]
}
</code>```

Body:
I am using ReactJS on the frontend: I successfully retrieved the access token from Google's Oauth service, but it doesn't give me any profile information for the 'current user'.

I tried using the /userInfo endpoint, ?access_token={my_access_token} query str, and some other solutions but I keep getting weird errors.

Currently I have:

  const { access_token, refresh_token } = res.data; // now I have valid access_token
  let userInfo = await axios.get("https://www.googleapis.com/oauth2/v3/userinfo",
  {
    headers: {
      Authorization: `Bearer ${access_token}`
    }
  }); // ERROR WHEN MAKING THIS CALL.

My specific 401 error is as follows:

If there are better ways of getting user info (such as first/last name, email, etc. some sort of unique ID) please let me know.

Body:
You shouldnt rely on the user info endpoint to get user profile informaiton.  As long as you are requesting the profile scope from the user, or even email. you should go though the People api.  This will give you access to all of the users profile data.

GET https://people.googleapis.com/v1/people/me?personFields=names HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json

response

{
  "resourceName": "people/117dd2004755326722775346",
  "etag": "%EgUBAi43PRoEAQIFBddyIMR3BzQkR2cnI1ZGc9",
  "names": [
    {
      "metadata": {
        "primary": true,
        "source": {
          "type": "PROFILE",
          "id": "117200155326727753146"
        }
      },
      "displayName": "Linda Lawton",
      "familyName": "Lawton",
      "givenName": "Linda",
      "displayNameLastFirst": "Lawton, Linda",
      "unstructuredName": "Linda Lawton"
    },
    {
      "metadata": {
        "source": {
          "type": "CONTACT",
          "id": "3faa96eb0118baa4be"
        }
      },
      "displayName": "Linda Lawton",
      "familyName": "Lawton",
      "givenName": "Linda",
      "displayNameLastFirst": "Lawton, Linda",
      "unstructuredName": "Linda Lawton"
    }
  ]
}


问:
Is there a way to reference the function you are inside of in C?
I am writing a function that just looks up values inside of a table. Is it possible to call that function inside of itself? I've seen stuff about this and self and don't really understand it.

答:
Update

Okay, I thought this was about "getting every function value". As other posters said, this is called recursion. A few notes though:

Recursion is faster than iteration (I don't have benchmark results on hand, but I ran them one year ago on an Intel Core i5).

```<code>//Iteration
function do_stuff(i)
{
    //BLABLAH
}

for (i = 0; i <5; i++) {
    do_stuff();
}

//Recursion
function do_stuff(int i)
{
    //BLABLAH
    if (i < 5) {
        do_stuff(i + 1);
    }
}
</code>```

You can recurse multiple times but you have to find a way to make the recursion stop or...

If your recursion goes down too far (think "Inception" times a million...), you run into the risk of overflowing your available stack memory just by entering the same function a millionth time.

Body:
Update

Okay, I thought this was about "getting every function value". As other posters said, this is called recursion. A few notes though:

Recursion is faster than iteration (I don't have benchmark results on hand, but I ran them one year ago on an Intel Core i5).

//Iteration
function do_stuff(i)
{
    //BLABLAH
}

for (i = 0; i <5; i++) {
    do_stuff();
}

//Recursion
function do_stuff(int i)
{
    //BLABLAH
    if (i < 5) {
        do_stuff(i + 1);
    }
}

You can recurse multiple times but you have to find a way to make the recursion stop or...

If your recursion goes down too far (think "Inception" times a million...), you run into the risk of overflowing your available stack memory just by entering the same function a millionth time.


问:
Defer processing in Python
I'm trying to write events in a non-blocking fashion so as not to slow down any of our existing processes.  It seems like the two options available are:

use Twisted's defer object

create a python logging handler

Are there other options.  Anybody have experience with this?

Background: We're planning to write events to Amazon's CloudWatch service and I'm concerned about latency from doing the PUT request. I'm not actually so concerned about losing a few PUTs if that changes the answer (we're writing the events for alerting purposes and they'll all be purged after a week anyway).

答:
If logging fits your application, and it sounds so, it should be simpler than using twisted. You could log to a thread safe queue in memory and have a separate thread (or several) pull from it and push to the cloud.

That said, twisted may be faster or at least more scalable, but, especially if you don't know it, with a steeper learning curve.

If the threads approach hits limits you can always switch your logging handler to use twisted, without changing your interface to the app, so that's how I would start, with a simple approach and bases covered.

Title: Defer processing in Python


问:
Able to run Python code with Unicode string in Eclipse, but getting UnicodeEncodeError when running via command line or Idle.
I've experienced this a lot, where I'll decode/encode some string of Unicode in Eclipse (PyDev), and it runs fine and how I expected, but then when I launch the same script from the command line (for example) instead, I'll get encoding errors.

Is there any simple explanation for this? Is Eclipse doing something to the Unicode/manipulating it in some different way?

EDIT:

Example:

```<code>value = u'\u2019'.decode( 'utf-8', 'ignore' )
return value
</code>```

This works in Eclipse (PyDev) but not if I run it in Idle or on the command line.

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 135: ordinal not in range(128)

答:
Just wanted to add why it worked on PyDev: it has a special sitecustomize that'll customize python through sys.setdefaultencoding to use the encoding of the PyDev console.

Note that the response from bobince is correct, if you have a unicode string, you have to use the encode() method to transform it into a proper string (you'd use decode if you had a string and wanted to transform it into a unicode).

Body:
I've experienced this a lot, where I'll decode/encode some string of Unicode in Eclipse (PyDev), and it runs fine and how I expected, but then when I launch the same script from the command line (for example) instead, I'll get encoding errors.

Is there any simple explanation for this? Is Eclipse doing something to the Unicode/manipulating it in some different way?

EDIT:

Example:

value = u'\u2019'.decode( 'utf-8', 'ignore' )
return value

This works in Eclipse (PyDev) but not if I run it in Idle or on the command line.

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 135: ordinal not in range(128)


问:
create default html opening code in Visual Studio Code
In some html editors when you create a new html file, some default codes as below created automatically:

```<code><!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
</head>
<body>

</body>
</html>
</code>```

how can I enable this feature in VSCode editor?

Thanks.

答: Just give the ! sign and then press Tab.

Body:
In some html editors when you create a new html file, some default codes as below created automatically:

<!DOCTYPE html>

<title></title>
<meta charset="utf-8"/>

how can I enable this feature in VSCode editor?

Thanks.


问:
Initialize class member to different derived classes in a hierarchy
I have a class baseNoCrtpIterator that holds one member baseNoCrtp _base, among others.
Class baseNoCrtp has several simply derived classes derived[n]NoCrtp, where [n] denotes a number 1,2,... These classes do not add any data members to baseNoCrtp, only some functionality.

I want that, during construction of a baseNoCrtpIterator, member _base is assigned one of derived[n]NoCrtp, depending on another value dclass passed to the constructor.

Is that possible?

I tried a constructor like

```<code>baseNoCrtpIterator::baseNoCrtpIterator(const int dclass) :
    _base(dclass)       // Point #8
{
    if (dclass == 0) {
        derived1NoCrtp* d1n = new derived1NoCrtp(0);
        _base = *d1n;        // Point #9
    }
    else if (dclass == 1) {
        derived2NoCrtp* d2n = new derived2NoCrtp(1);
        _base = *d2n;
    } else {
        cout << "Unknown derived class: " << dclass << endl;
        throw runtime_error("Unknown derived class");
    }
};
</code>```

This doesn't work, and I probably have to fix #8 (I guess I have to remove it from the initializer list), and #9, since I don't have operator= (I could write it, but I guess it doesn't solve my problem).

Note:
I guess CRTP might be an alternative.
But I see a couple of problems:

All uses of baseNoCrtpIterator have to be replaced by baseNoCrtpIterator<T>. Thus, downstream, all functions, classes, etc., that use baseNoCrtpIterator will have to be "templetized".
This means huge changes in existing code.

I would not be able to hold all objects of class baseNoCrtp and derived in a single container. That is part of the changes mentioned above.

TL;DR

I have two hierarchies of (base + n simply derived) classes.
One is a "main" hierarchy, and the other is an "iterator" hierarchy, meant to iterate over the main.

The base class for the iterators refers to the base class for the main in #1

```<code>class baseNoCrtpIterator {
public:
    baseNoCrtpIterator(const baseNoCrtp& base, const int dclass);
    virtual ~baseNoCrtpIterator() {};

    const baseNoCrtp& operator*() const { return *operator->(); };
    const baseNoCrtp* operator->() const { return &_base; };
private:
    baseNoCrtp _base;   // Point #1
    int _index;
};
</code>```

and its constructor is

```<code>baseNoCrtpIterator::baseNoCrtpIterator(const structure& s, const int dclass) :
    _base(s, dclass),
    _index(0) { };
</code>```

where dclass indicates the derived class of _base (that is not enough, as will be shown later).
The derived iterator classes are like this (derived1... is associated with dclass=0, and so on)

```<code>class derived1NoCrtpIterator : public baseNoCrtpIterator {         // derived1...
public:
    derived1NoCrtpIterator(const baseNoCrtp& base) : baseNoCrtpIterator(base, 0) {};   // ... dclass=0
    virtual ~derived1NoCrtpIterator() {};

    const derived1NoCrtp& operator*() { return *operator->(); }
    const derived1NoCrtp* operator->() {                             // Point #2
        const baseNoCrtp* bnp = baseNoCrtpIterator::operator->();    // Point #3
        return static_cast<const derived1NoCrtp*>(bnp);              // Point #4
    }
};
</code>```

The problem is when using something like

```<code>for (derived1NoCrtpIterator d1ni(sconst); ...) {
    const derived1NoCrtp& d1nr = *d1ni;   // Point #5
    ...
</code>```

Point #5 leads to #2.
In #3 we extract a pointer to member baseNoCrtp.
But then the static_cast downcast in #4 is undefined behavior.
This could be solved if the constructor baseNoCrtpIterator::baseNoCrtpIterator assigned to baseNoCrtp objects of the derived classes derived1NoCrtpIterator, etc., instead of the base class.

I tried to replace the constructor with something like

```<code>baseNoCrtpIterator::baseNoCrtpIterator(const structure& s, const int dclass) :
    _base(s, dclass),        // Point #8
    _index(0) {
    if (dclass == 0) {
        derived1NoCrtp* d1n = new derived1NoCrtp(s, 0);
        _base = *d1n;        // Point #9
    }
    else if (dclass == 1) {
        derived2NoCrtp* d2n = new derived2NoCrtp(s, 1);
        _base = *d2n;
    } else {
        cout << "Unknown derived class: " << dclass << endl;
        throw runtime_error("Unknown derived class");
    }
};
</code>```

This doesn't work, and I probably have to fix #8 (I guess I have to remove it from the initializer list), and #9, since I don't have operator= (I could write it, but I guess it doesn't solve my problem).

How can I achieve this assignment to _base of objects of derived classes, depending on dclass?

Since this is a boiled down example of a very large code that I have to fix,
I am in principle not interested in other methods that require extensive modifications of the code.
For instance, if CRTP might be a solution, it probably involves huge changes.
I know the current way might be a somewhat contrived form of iterating the main hierarchy, but this is what I received.

The "main" classes are (here it is not relevant what structure is):

```<code>class baseNoCrtp {
public:
    baseNoCrtp(const structure& s, const int dclass) :
        _structure(s), _derivedClass(dclass) { };
    virtual ~baseNoCrtp() {};
public:
    int getDerivedClass() const { return _derivedClass; }
    const structure& getStructure() const { return _structure; };
protected:
    const structure& _structure;
private:
    friend class baseNoCrtpIterator;
    int _derivedClass;
};

class derived1NoCrtp : public baseNoCrtp {
public:
    derived1NoCrtp(const structure& s) : baseNoCrtp(s, 0) {};
    virtual ~derived1NoCrtp() {};
    // Add whatever extra methods
};
</code>```

答:
It seems this is not possible, see also this.

The "workaround" is to change the type of member _base, to baseNoCrtp*, so it can point to objects of any derived class.

Body:
I have a class baseNoCrtpIterator that holds one member baseNoCrtp _base, among others.
Class baseNoCrtp has several simply derived classes derived[n]NoCrtp, where [n] denotes a number 1,2,... These classes do not add any data members to baseNoCrtp, only some functionality.

I want that, during construction of a baseNoCrtpIterator, member _base is assigned one of derived[n]NoCrtp, depending on another value dclass passed to the constructor.

Is that possible?

I tried a constructor like

baseNoCrtpIterator::baseNoCrtpIterator(const int dclass) :
    _base(dclass)       // Point #8
{
    if (dclass == 0) {
        derived1NoCrtp* d1n = new derived1NoCrtp(0);
        _base = *d1n;        // Point #9
    }
    else if (dclass == 1) {
        derived2NoCrtp* d2n = new derived2NoCrtp(1);
        _base = *d2n;
    } else {
        cout << "Unknown derived class: " << dclass << endl;
        throw runtime_error("Unknown derived class");
    }
};

This doesn't work, and I probably have to fix #8 (I guess I have to remove it from the initializer list), and #9, since I don't have operator= (I could write it, but I guess it doesn't solve my problem).

Note:
I guess CRTP might be an alternative.
But I see a couple of problems:

All uses of baseNoCrtpIterator have to be replaced by baseNoCrtpIterator<T>. Thus, downstream, all functions, classes, etc., that use baseNoCrtpIterator will have to be "templetized".
This means huge changes in existing code.

I would not be able to hold all objects of class baseNoCrtp and derived in a single container. That is part of the changes mentioned above.

TL;DR

I have two hierarchies of (base + n simply derived) classes.
One is a "main" hierarchy, and the other is an "iterator" hierarchy, meant to iterate over the main.

The base class for the iterators refers to the base class for the main in #1

class baseNoCrtpIterator {
public:
    baseNoCrtpIterator(const baseNoCrtp& base, const int dclass);
    virtual ~baseNoCrtpIterator() {};

    const baseNoCrtp& operator*() const { return *operator->(); };
    const baseNoCrtp* operator->() const { return &_base; };
private:
    baseNoCrtp _base;   // Point #1
    int _index;
};

and its constructor is

baseNoCrtpIterator::baseNoCrtpIterator(const structure& s, const int dclass) :
    _base(s, dclass),
    _index(0) { };

where dclass indicates the derived class of _base (that is not enough, as will be shown later).
The derived iterator classes are like this (derived1... is associated with dclass=0, and so on)

class derived1NoCrtpIterator : public baseNoCrtpIterator {         // derived1...
public:
    derived1NoCrtpIterator(const baseNoCrtp& base) : baseNoCrtpIterator(base, 0) {};   // ... dclass=0
    virtual ~derived1NoCrtpIterator() {};

    const derived1NoCrtp& operator*() { return *operator->(); }
    const derived1NoCrtp* operator->() {                             // Point #2
        const baseNoCrtp* bnp = baseNoCrtpIterator::operator->();    // Point #3
        return static_cast<const derived1NoCrtp*>(bnp);              // Point #4
    }
};

The problem is when using something like

for (derived1NoCrtpIterator d1ni(sconst); ...) {
    const derived1NoCrtp& d1nr = *d1ni;   // Point #5
    ...

Point #5 leads to #2.
In #3 we extract a pointer to member baseNoCrtp.
But then the static_cast downcast in #4 is undefined behavior.
This could be solved if the constructor baseNoCrtpIterator::baseNoCrtpIterator assigned to baseNoCrtp objects of the derived classes derived1NoCrtpIterator, etc., instead of the base class.

I tried to replace the constructor with something like

baseNoCrtpIterator::baseNoCrtpIterator(const structure& s, const int dclass) :
    _base(s, dclass),        // Point #8
    _index(0) {
    if (dclass == 0) {
        derived1NoCrtp* d1n = new derived1NoCrtp(s, 0);
        _base = *d1n;        // Point #9
    }
    else if (dclass == 1) {
        derived2NoCrtp* d2n = new derived2NoCrtp(s, 1);
        _base = *d2n;
    } else {
        cout << "Unknown derived class: " << dclass << endl;
        throw runtime_error("Unknown derived class");
    }
};

This doesn't work, and I probably have to fix #8 (I guess I have to remove it from the initializer list), and #9, since I don't have operator= (I could write it, but I guess it doesn't solve my problem).

How can I achieve this assignment to _base of objects of derived classes, depending on dclass?

Since this is a boiled down example of a very large code that I have to fix,
I am in principle not interested in other methods that require extensive modifications of the code.
For instance, if CRTP might be a solution, it probably involves huge changes.
I know the current way might be a somewhat contrived form of iterating the main hierarchy, but this is what I received.

The "main" classes are (here it is not relevant what structure is):

class baseNoCrtp {
public:
    baseNoCrtp(const structure& s, const int dclass) :
        _structure(s), _derivedClass(dclass) { };
    virtual ~baseNoCrtp() {};
public:
    int getDerivedClass() const { return _derivedClass; }
    const structure& getStructure() const { return _structure; };
protected:
    const structure& _structure;
private:
    friend class baseNoCrtpIterator;
    int _derivedClass;
};

class derived1NoCrtp : public baseNoCrtp {
public:
    derived1NoCrtp(const structure& s) : baseNoCrtp(s, 0) {};
    virtual ~derived1NoCrtp() {};
    // Add whatever extra methods
};


问:
printing stack with variable names with gdb?
I was just reading this article.
In the article, the author uses gdb to look around in a c executable.

At one point, when a breakpoint is hit, the author says to have a look at the stack, and shows this output:

```<code>STACK:

0x00007fffffffdf40│+0x0000: 0x00007fffffffe058  → 0x00007fffffffe380

0x00007fffffffdf48│+0x0008: 0x0000000100401050

0x00007fffffffdf50│+0x0010: 0x00007fffffffe050  →  0x0000000000000001

0x00007fffffffdf58│+0x0018: 0x0000000000402004  →  “p@ssw0rD”

0x00007fffffffdf60│+0x0020: 0x0000000000000000 ← $rbp

0x00007fffffffdf68│+0x0028: 0x00007ffff7ded0b3  →  <__libc_start_main+243> mov edi, eax

0x00007fffffffdf70│+0x0030: 0x00007ffff7ffc620  →  0x0005043700000000

0x00007fffffffdf78│+0x0038: 0x00007fffffffe058  →  0x00007fffffffe380  →
</code>```

This is nice, but how do I generate this output in gdb?
I've been googling for a while with no luck

Also, in this output there is two different columns of hex adresses, I'm guessing one points to the stack, what is the other one? and which is which?

答:
The author doesn't state it explicitly, but in their gdb output you can see the prompt gef>.  This indicates they are likely making use of the gef addon for gdb.

I have never used this addon myself, but you can see in some of the example output on the gef site that the addon has a stack view identical to the output you gave above.

The gef addon makes use of gdb's Python API to provide additional features for gdb, one of which appears to be the alternative stack view.

Body:
I was just reading this article.
In the article, the author uses gdb to look around in a c executable.

At one point, when a breakpoint is hit, the author says to have a look at the stack, and shows this output:

STACK:

0x00007fffffffdf40│+0x0000: 0x00007fffffffe058  → 0x00007fffffffe380

0x00007fffffffdf48│+0x0008: 0x0000000100401050

0x00007fffffffdf50│+0x0010: 0x00007fffffffe050  →  0x0000000000000001

0x00007fffffffdf58│+0x0018: 0x0000000000402004  →  “p@ssw0rD”

0x00007fffffffdf60│+0x0020: 0x0000000000000000 ← $rbp

0x00007fffffffdf68│+0x0028: 0x00007ffff7ded0b3  →  <__libc_start_main+243> mov edi, eax

0x00007fffffffdf70│+0x0030: 0x00007ffff7ffc620  →  0x0005043700000000

0x00007fffffffdf78│+0x0038: 0x00007fffffffe058  →  0x00007fffffffe380  →

This is nice, but how do I generate this output in gdb?
I've been googling for a while with no luck

Also, in this output there is two different columns of hex adresses, I'm guessing one points to the stack, what is the other one? and which is which?


问:
No such file or directory
I am trying to use Pillow Library in Python. I am writing basic code to open up a picture that I have saved.

But every time I run the code, it says

```<code>"can't open file 'C:\Users\saadn\PycharmProjects\Giraffe\main.py':
[Errno 2] No such file or directory".
</code>```

The path for where the picture is saved is "C:\Users\saadn\PycharmProjects\Giraffe\DirectoryAssign1"

Now I know that in the error it says "Girrafe\main.py". but I don't have a python file named main at all. Someone guide me.

the code I wrote was

```<code>from PIL import Image
img = Image.open("dany.jpg")
img.show()
</code>```

Here is a screenshot for better understanding.

答:
Actually I think there are 2 issues, and not 1.

Error 1 - Wrong File is being tried to run :

In the picture you attached there is an error which means it cannot open main.py (No such file) . You entered a wrong file name, your file name is OpenAndShow.py

How to fix?

Be sure to open the terminal or command prompt and be sure you are in the following directory C:\Users\saadn\PycharmProjects\Giraffe\ and enter the following command as you are a Windows OS User:
py OpenAndShow.py

Fun fact: Of course Python won't search in the whole PC or directory (including folders which are in the directory) , so that's why you need to mention it is in a folder in the Giraffe folder!

Error 2 - Wrong location for the picture

If you had fixed error 1, you will get another error, that dany.jpg is not such file, why ? Because it is in another folder inside the folder your code is located, you can use dany.jpg when they are in the same folder, not in another folder in the same folder, in this case, it is in DirectoryAssign1 which is in Girrafe folder.

How to fix?

To fix it, change the path:

From : The current Path:
dany.jpg

To : The following path below:
DirectoryAssign1\dany.jpg

Title: No such file or directory

Body:
I am trying to use Pillow Library in Python. I am writing basic code to open up a picture that I have saved.

But every time I run the code, it says

"can't open file 'C:\Users\saadn\PycharmProjects\Giraffe\main.py':
[Errno 2] No such file or directory".

The path for where the picture is saved is "C:\Users\saadn\PycharmProjects\Giraffe\DirectoryAssign1"

Now I know that in the error it says "Girrafe\main.py". but I don't have a python file named main at all. Someone guide me.

the code I wrote was

from PIL import Image
img = Image.open("dany.jpg")
img.show()

Here is a screenshot for better understanding.


问:
SwiftUI: Binding on property of struct derived from environment object
I have two structs in my task manager app:

struct Task {
    var identifier: String
    var title: String
    var tags: [String] // Array of tag identifiers
}
struct Tag {
    var identifier: String
    var title: String
}
```
<p>I then have a class to store them:</p>
<pre class="lang-swift prettyprint-override"><code>class TaskStore: ObservableObject {
    @Published var tasks = [String:Task]()
    @Published var tags = [String:Tag]()
}
</code>```

which I pass to my root view as an .environmentObject(taskStore).

Correct me if any of the following is wrong (against bad practices):

In my TaskView I have:

    @EnvironmentObject var taskStore: TaskStore

    var taskIdentifier: String // Passed from parent view

    private var task: Task {
        get {
            return taskStore.tasks[taskIdentifier]! // Looks up the task in the store
        }
    }
    private var tags: [Tag] {
        get {
            return taskStore.tags
        }
    }
```

The issue is, when learning SwiftUI I was told when making certain components (like a picker that let's you alter the tags array in this case) that it should accept a binding to the value/collection, or say I want to make the task title editable, I need a binding to the task.title property, both of which I can't do because (based on the way I'm defining and computing task) I can't get a binding on task.

Am I doing something against best practices here? Or where along this path did I diverge from the right way of storing points of truth in an environment object, and make them editable in sub views.

答:
You are correct to model your data with value types and manage lifecycle and side-effects with a reference type. The bit you are missing is that Task doesn't implement the Identifiable protocol which enables SwiftUI to keep track of the data in a List or ForEach. Implement that as follows:

```<code>struct Task: Identifiable {
    var id: String
    var title: String
    var tags: [String] // Array of tag identifiers
}
</code>```

Then switch to using an array, e.g.

```<code>class TaskStore: ObservableObject {
    @Published var tasks = [Task]()
    @Published var tags = [Tag]()

    // you might find this helper found in Fruta useful
    func task(for identifier: String) -> Task? {
        return tasks.first(where: { $0.id == identifier })
    }
}
</code>```

Now that you have an array of identifiable data it is real simple to get a binding to the task via:

```<code>List($model.tasks) { $task in
    // now you have a binding to the task
}
</code>```

I recommend checking out Apple's Fruta sample for more detail.

Body:
I have two structs in my task manager app:

struct Task {
    var identifier: String
    var title: String
    var tags: [String] // Array of tag identifiers
}
struct Tag {
    var identifier: String
    var title: String
}

I then have a class to store them:

class TaskStore: ObservableObject {
    @Published var tasks = [String:Task]()
    @Published var tags = [String:Tag]()
}

which I pass to my root view as an .environmentObject(taskStore).

Correct me if any of the following is wrong (against bad practices):

In my TaskView I have:

    @EnvironmentObject var taskStore: TaskStore

    var taskIdentifier: String // Passed from parent view

    private var task: Task {
        get {
            return taskStore.tasks[taskIdentifier]! // Looks up the task in the store
        }
    }
    private var tags: [Tag] {
        get {
            return taskStore.tags
        }
    }

The issue is, when learning SwiftUI I was told when making certain components (like a picker that let's you alter the tags array in this case) that it should accept a binding to the value/collection, or say I want to make the task title editable, I need a binding to the task.title property, both of which I can't do because (based on the way I'm defining and computing task) I can't get a binding on task.

Am I doing something against best practices here? Or where along this path did I diverge from the right way of storing points of truth in an environment object, and make them editable in sub views.

Body:
You are correct to model your data with value types and manage lifecycle and side-effects with a reference type. The bit you are missing is that Task doesn't implement the Identifiable protocol which enables SwiftUI to keep track of the data in a List or ForEach. Implement that as follows:

struct Task: Identifiable {
    var id: String
    var title: String
    var tags: [String] // Array of tag identifiers
}

Then switch to using an array, e.g.

class TaskStore: ObservableObject {
    @Published var tasks = [Task]()
    @Published var tags = [Tag]()

    // you might find this helper found in Fruta useful
    func task(for identifier: String) -> Task? {
        return tasks.first(where: { $0.id == identifier })
    }
}

Now that you have an array of identifiable data it is real simple to get a binding to the task via:

List($model.tasks) { $task in
    // now you have a binding to the task
}

I recommend checking out Apple's Fruta sample for more detail.


答:
My solution is similar but maybe easier.

I have this numpy array colvals:

array([[0.90588235, 0.96078431, 1.        , 1.        ],
       [0.81568627, 0.92156863, 1.        , 1.        ],
       [0.64705882, 0.84705882, 1.        , 1.        ],
       [0.45490196, 0.75294118, 0.98823529, 1.        ],
       [0.30196078, 0.67058824, 0.96862745, 1.        ],
       [0.2       , 0.60392157, 0.94117647, 1.        ],
       [0.13333333, 0.54509804, 0.90196078, 1.        ],
       [0.10980392, 0.49411765, 0.83921569, 1.        ],
       [0.09803922, 0.44313725, 0.76078431, 1.        ],
       [0.09411765, 0.39215686, 0.67058824, 1.        ]])
```
<p>It is in rgba format.</p>
<p>Transforming in into colormap looks like:</p>
<pre class="lang-py prettyprint-override"><code>cmp_blue = ListedColormap(colvals)
cmp_blue
</code>```

Now I make it more granular

inbetween_color_amount = 10

# the 10 is from the original 10 colors, the 4 is for R, G, B, A
newcolvals = np.zeros(shape=(10 * (inbetween_color_amount) - (inbetween_color_amount - 1), 4))

# add first one already
newcolvals[0] = colvals[0]

for i, (rgba1, rgba2) in enumerate(zip(colvals[:-1], np.roll(colvals, -1, axis=0)[:-1])):
    for j, (p1, p2) in enumerate(zip(rgba1, rgba2)):
        flow = np.linspace(p1, p2, (inbetween_color_amount + 1))
        # discard first 1 since we already have it from previous iteration
        flow = flow[1:]
        newcolvals[ i * (inbetween_color_amount) + 1 : (i + 1) * (inbetween_color_amount) + 1, j] = flow

newcolvals
```
<p>This time:</p>
<pre class="lang-py prettyprint-override"><code>cmp_blue = ListedColormap(newcolvals)
cmp_blue
</code>```

I get:

Title: How to interpolate colours to double its number in matplotlib

Body:
I have a list of 9 colors like this:

  colors = [
           [0, 82, 246, 255],
           [0, 196, 196, 255],
           [0, 137, 83, 255],
           [1, 233, 11, 255],
           [234, 255, 31, 255],
           [255, 176, 0, 255],
           [247, 19, 0, 255],
           [193, 0, 76, 255],
           [255, 0, 255, 255]]

I want to use matplotlib to double the number of colours with interpolated ones. I have used LinearSegmentedColormap.from_list without success:

  cm = LinearSegmentedColormap.from_list('test', np.array(colors) / 255,
                                         N=len(colors))

  colors = cm(np.linspace(0, 1, 2 * len(colors)))
  colors = (colors * 255).astype('uint8')

However I get the same colours but repeated:

array([[  0,  82, 246, 255],
       [  0,  82, 246, 255],
       [  0, 196, 196, 255],
       [  0, 196, 196, 255],
       [  0, 137,  83, 255],
       [  0, 137,  83, 255],
       [  1, 233,  11, 255],
       [  1, 233,  11, 255],
       [234, 255,  31, 255],
       [234, 255,  31, 255],
       [255, 176,   0, 255],
       [255, 176,   0, 255],
       [247,  18,   0, 255],
       [247,  18,   0, 255],
       [193,   0,  76, 255],
       [193,   0,  76, 255],
       [255,   0, 255, 255],
       [255,   0, 255, 255]], dtype=uint8)

How can I get the expected behaviour, with the colours I originally I had, plus others in the middle?

Body:
My solution is similar but maybe easier.

I have this numpy array colvals:

array([[0.90588235, 0.96078431, 1.        , 1.        ],
       [0.81568627, 0.92156863, 1.        , 1.        ],
       [0.64705882, 0.84705882, 1.        , 1.        ],
       [0.45490196, 0.75294118, 0.98823529, 1.        ],
       [0.30196078, 0.67058824, 0.96862745, 1.        ],
       [0.2       , 0.60392157, 0.94117647, 1.        ],
       [0.13333333, 0.54509804, 0.90196078, 1.        ],
       [0.10980392, 0.49411765, 0.83921569, 1.        ],
       [0.09803922, 0.44313725, 0.76078431, 1.        ],
       [0.09411765, 0.39215686, 0.67058824, 1.        ]])

It is in rgba format.

Transforming in into colormap looks like:

cmp_blue = ListedColormap(colvals)
cmp_blue

Now I make it more granular

inbetween_color_amount = 10

# the 10 is from the original 10 colors, the 4 is for R, G, B, A
newcolvals = np.zeros(shape=(10 * (inbetween_color_amount) - (inbetween_color_amount - 1), 4))

# add first one already
newcolvals[0] = colvals[0]

for i, (rgba1, rgba2) in enumerate(zip(colvals[:-1], np.roll(colvals, -1, axis=0)[:-1])):
    for j, (p1, p2) in enumerate(zip(rgba1, rgba2)):
        flow = np.linspace(p1, p2, (inbetween_color_amount + 1))
        # discard first 1 since we already have it from previous iteration
        flow = flow[1:]
        newcolvals[ i * (inbetween_color_amount) + 1 : (i + 1) * (inbetween_color_amount) + 1, j] = flow

newcolvals

This time:

cmp_blue = ListedColormap(newcolvals)
cmp_blue

I get:


问:
Having trouble loading a javascript (images don't load)
I downloaded a calendar javascript. My working directory is /user. I put the script into /user/js/calendar. In my HTML located at user/, I have...

```<code><script language="JavaScript" src="js/calendar/calendar_us.js"></script>
<link rel="stylesheet" href="js/calendar/calendar.css">
</code>```

The .js and .css load, and I see the calendar form, but the images under user/js/calendar/img do not load when it's displayed on the browser.

The image reference code in the downloaded javascript is below

```<code><img src="' + this.a_tpl.imgpath + 'next_year.gif" />
</code>```

this.a_tpl.imgpath is 'img/'. Is there something I need to add or modify in my HTML or in the .js file to make correct relative reference to the files in user/js/calendar/img?

答:
You can't put javascript string functions directly in your HTML like this:

```<code><img src="' + this.a_tpl.imgpath + 'next_year.gif" />
</code>```

You can use a piece of javascript to document.write() the image tag inline or you can create the tag dynamically in javascript and set the .src property using JS after the document has been loaded.  But, you can't just throw some javascript into the middle of your HTML like this.

For static definitions of image URLs in an HTML file, the paths should either be relative to the page location or they should be relative to the top of your domain or they should be a fully qualified domain/path.

Body:
I downloaded a calendar javascript. My working directory is /user. I put the script into /user/js/calendar. In my HTML located at user/, I have...

<link rel="stylesheet" href="js/calendar/calendar.css">

The .js and .css load, and I see the calendar form, but the images under user/js/calendar/img do not load when it's displayed on the browser.

The image reference code in the downloaded javascript is below

this.a_tpl.imgpath is 'img/'. Is there something I need to add or modify in my HTML or in the .js file to make correct relative reference to the files in user/js/calendar/img?

Body:
You can't put javascript string functions directly in your HTML like this:

<img src="' + this.a_tpl.imgpath + 'next_year.gif" />

You can use a piece of javascript to document.write() the image tag inline or you can create the tag dynamically in javascript and set the .src property using JS after the document has been loaded.  But, you can't just throw some javascript into the middle of your HTML like this.

For static definitions of image URLs in an HTML file, the paths should either be relative to the page location or they should be relative to the top of your domain or they should be a fully qualified domain/path.


问:
scikit-learn kernel PCA explained variance
I have been using the normal PCA from scikit-learn and get the variance ratios for each principal component without any issues.

```<code>pca = sklearn.decomposition.PCA(n_components=3)
pca_transform = pca.fit_transform(feature_vec)
var_values = pca.explained_variance_ratio_
</code>```

I want to explore differnt kernels using kernel PCA and also want the explained variance ratios but I am now seeing it doesn't have this attribute.  Does anyone know how to get these values?

```<code>kpca = sklearn.decomposition.KernelPCA(kernel=kernel, n_components=3)
kpca_transform = pca.fit_transform(feature_vec)
var_values = kpca.explained_variance_ratio_
</code>```

AttributeError: 'KernelPCA' object has no attribute 'explained_variance_ratio_'

答:
Use the eigen values, it gives similar information and intuition you need:</p>
```<code>pca = KernelPCA(n_components=30, kernel="rbf")
pca.fit(x)
var_values = pca.eigenvalues_ / sum(pca.eigenvalues_)
print(sum(var_values))
plt.plot(np.arange(1, pca.n_components + 1), var_values, "+", linewidth=2)
plt.ylabel("PCA explained variance ratio")
plt.show()
</code>```

Body:
I have been using the normal PCA from scikit-learn and get the variance ratios for each principal component without any issues.

pca = sklearn.decomposition.PCA(n_components=3)
pca_transform = pca.fit_transform(feature_vec)
var_values = pca.explained_variance_ratio_

I want to explore differnt kernels using kernel PCA and also want the explained variance ratios but I am now seeing it doesn't have this attribute.  Does anyone know how to get these values?

kpca = sklearn.decomposition.KernelPCA(kernel=kernel, n_components=3)
kpca_transform = pca.fit_transform(feature_vec)
var_values = kpca.explained_variance_ratio_

AttributeError: 'KernelPCA' object has no attribute 'explained_variance_ratio_'

Body:
Use the eigen values, it gives similar information and intuition you need:

pca = KernelPCA(n_components=30, kernel="rbf")
pca.fit(x)
var_values = pca.eigenvalues_ / sum(pca.eigenvalues_)
print(sum(var_values))
plt.plot(np.arange(1, pca.n_components + 1), var_values, "+", linewidth=2)
plt.ylabel("PCA explained variance ratio")
plt.show()


问:
Mat-table Sorting Demo not Working
I am trying to get the mat-table sorting to work locally, and while I can get the data to show up as expected, clicking on the header row does not do the sorting as it does on online examples (nothing happens at all).
I am trying to get this demo working locally:
https://material.angular.io/components/sort/overview
https://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview

I have generated a new project with Angular CLI, then followed these steps:
https://material.angular.io/guide/getting-started

Here are my local files:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSort, MatTableModule } from '@angular/material';

import { AppComponent } from './app.component';
import { TableSortingExample } from './table-sorting-example';

@NgModule({
  declarations: [
    AppComponent,
    TableSortingExample,
    MatSort
  ],
  imports: [
    BrowserModule,
    MatTableModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

<p><strong>app.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}
</code>```

app.component.html

    Welcome to {{title}}!

```

<p><strong>table-sorting-example.html</strong></p>

<pre class="lang-html prettyprint-override"><code><div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource" matSort>

    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

    <!-- ID Column -->
    <ng-container matColumnDef="userId">
      <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
    </ng-container>

    <!-- Progress Column -->
    <ng-container matColumnDef="progress">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Progress </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.progress}}% </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="userName">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

    <!-- Color Column -->
    <ng-container matColumnDef="color">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Color </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.color}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>

<!-- Copyright 2017 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->
</code>```

table-sorting-example.ts

import {Component, ViewChild} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

/**
 * @title Table with sorting
 */
@Component({
  selector: 'table-sorting-example',
  styleUrls: ['table-sorting-example.css'],
  templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample {
  displayedColumns = ['userId', 'userName', 'progress', 'color'];
  exampleDatabase = new ExampleDatabase();
  dataSource: ExampleDataSource | null;

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);
  }
}

/** Constants used to fill up our data base. */
const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

export interface UserData {
  id: string;
  name: string;
  progress: string;
  color: string;
}

/** An example database that the data source uses to retrieve data for the table. */
export class ExampleDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
  get data(): UserData[] { return this.dataChange.value; }

  constructor() {
    // Fill up the database with 100 users.
    for (let i = 0; i < 100; i++) { this.addUser(); }
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }

  /** Builds and returns a new User. */
  private createNewUser() {
    const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
      id: (this.data.length + 1).toString(),
      name: name,
      progress: Math.round(Math.random() * 100).toString(),
      color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
    };
  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDatabase, private _sort: MatSort) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<UserData[]> {
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._sort.sortChange,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      return this.getSortedData();
    });
  }

  disconnect() {}

  /** Returns a sorted copy of the database data. */
  getSortedData(): UserData[] {
    const data = this._exampleDatabase.data.slice();
    if (!this._sort.active || this._sort.direction == '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';

      switch (this._sort.active) {
        case 'userId': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'userName': [propertyA, propertyB] = [a.name, b.name]; break;
        case 'progress': [propertyA, propertyB] = [a.progress, b.progress]; break;
        case 'color': [propertyA, propertyB] = [a.color, b.color]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
    });
  }
}

/**  Copyright 2017 Google Inc. All Rights Reserved.
 Use of this source code is governed by an MIT-style license that
 can be found in the LICENSE file at http://angular.io/license */
```

Does anyone have an idea of why it would show up like the online table but lack the sorting functionality?

答:
changing

```<code>@ViewChild('matsort') sort: MatSort;
</code>```

to

```<code>@ViewChild(matSort) sort: MatSort
</code>```

did it for me must be the same

```<code><table mat-table [dataSource]="dataSource" class="mat-elevation-z8" matSort matSortActive="name" matSortDirection="asc">
</code>```

Title: Mat-table Sorting Demo not Working

Body:
I am trying to get the mat-table sorting to work locally, and while I can get the data to show up as expected, clicking on the header row does not do the sorting as it does on online examples (nothing happens at all).
I am trying to get this demo working locally:
https://material.angular.io/components/sort/overview
https://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview

I have generated a new project with Angular CLI, then followed these steps:
https://material.angular.io/guide/getting-started

Here are my local files:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSort, MatTableModule } from '@angular/material';

import { AppComponent } from './app.component';
import { TableSortingExample } from './table-sorting-example';

@NgModule({
  declarations: [
    AppComponent,
    TableSortingExample,
    MatSort
  ],
  imports: [
    BrowserModule,
    MatTableModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

app.component.html

    Welcome to {{title}}!

table-sorting-example.html

  <mat-table #table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="userId">
      <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="progress">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Progress </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.progress}}% </mat-cell>
    </ng-container>

    <ng-container matColumnDef="userName">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="color">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Color </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.color}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>

table-sorting-example.ts

import {Component, ViewChild} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

/**
 * @title Table with sorting
 */
@Component({
  selector: 'table-sorting-example',
  styleUrls: ['table-sorting-example.css'],
  templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample {
  displayedColumns = ['userId', 'userName', 'progress', 'color'];
  exampleDatabase = new ExampleDatabase();
  dataSource: ExampleDataSource | null;

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);
  }
}

/** Constants used to fill up our data base. */
const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

export interface UserData {
  id: string;
  name: string;
  progress: string;
  color: string;
}

/** An example database that the data source uses to retrieve data for the table. */
export class ExampleDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
  get data(): UserData[] { return this.dataChange.value; }

  constructor() {
    // Fill up the database with 100 users.
    for (let i = 0; i < 100; i++) { this.addUser(); }
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }

  /** Builds and returns a new User. */
  private createNewUser() {
    const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
      id: (this.data.length + 1).toString(),
      name: name,
      progress: Math.round(Math.random() * 100).toString(),
      color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
    };
  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDatabase, private _sort: MatSort) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<UserData[]> {
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._sort.sortChange,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      return this.getSortedData();
    });
  }

  disconnect() {}

  /** Returns a sorted copy of the database data. */
  getSortedData(): UserData[] {
    const data = this._exampleDatabase.data.slice();
    if (!this._sort.active || this._sort.direction == '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';

      switch (this._sort.active) {
        case 'userId': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'userName': [propertyA, propertyB] = [a.name, b.name]; break;
        case 'progress': [propertyA, propertyB] = [a.progress, b.progress]; break;
        case 'color': [propertyA, propertyB] = [a.color, b.color]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
    });
  }
}

/**  Copyright 2017 Google Inc. All Rights Reserved.
 Use of this source code is governed by an MIT-style license that
 can be found in the LICENSE file at http://angular.io/license */

Does anyone have an idea of why it would show up like the online table but lack the sorting functionality?

Body:
changing

@ViewChild('matsort') sort: MatSort;

to

@ViewChild(matSort) sort: MatSort

did it for me must be the same

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8" matSort matSortActive="name" matSortDirection="asc">


问:
Fatal error while creating superuser in Django (django-rest-framework)
I want to make an AbstractUser without a username field so I got this:

```<code>from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator

class CustomUser(AbstractUser):
    email = models.EmailField(max_length=254, unique=True)
    username = None

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    session_token = models.CharField(max_length=10, default=0)

    #Newsletter/Shipment Info (not required)
    newsletter = models.BooleanField(default=False)

    first_name = models.CharField(max_length=35, blank=True, null=True)
    last_name = models.CharField(max_length=35, blank=True, null=True)
    adress = models.CharField(max_length=50, blank=True, null=True)
    city = models.CharField(max_length=50, blank=True, null=True)
    postal_code = models.CharField(max_length=6, blank=True, null=True)
    phone = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{9}$/')], blank=True, null=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

</code>```

I got this migrated into the database and now I need to craete an admin user so I would be able to enter the admin panel. I typed email and both passwords into the comand prompt after python manage.py createsuperuser and I got this error:

```<code>Traceback (most recent call last):
  File "C:\Users\mateu\Documents\meadow\backend\manage.py", line 22, in <module>
    main()
  File "C:\Users\mateu\Documents\meadow\backend\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line
    utility.execute()
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\base.py", line 417, in execute
    output = self.handle(*args, **options)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 195, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'
</code>```

I have no idea how to fix it. Any thoughts?

答:
You have to inherit from AbstractBaseUser not from AbstractUser and add Manager Class to it

from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    is_superuser = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    # Add other fields here

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

class UserManager(BaseUserManager):

    def _create_user(self, email, password, **extra_fields):
        user = self.model(email=self.normalize_email(email), **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password, **extra_fields):
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self._create_user(email, password, **extra_fields)
```
<p>Don't forget</p>
```python manage.py makemigrations

python manage.py migrate
```

I recommend you to take a look at the docs

Body:
I want to make an AbstractUser without a username field so I got this:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator

class CustomUser(AbstractUser):
    email = models.EmailField(max_length=254, unique=True)
    username = None

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    session_token = models.CharField(max_length=10, default=0)

    #Newsletter/Shipment Info (not required)
    newsletter = models.BooleanField(default=False)

    first_name = models.CharField(max_length=35, blank=True, null=True)
    last_name = models.CharField(max_length=35, blank=True, null=True)
    adress = models.CharField(max_length=50, blank=True, null=True)
    city = models.CharField(max_length=50, blank=True, null=True)
    postal_code = models.CharField(max_length=6, blank=True, null=True)
    phone = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{9}$/')], blank=True, null=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

I got this migrated into the database and now I need to craete an admin user so I would be able to enter the admin panel. I typed email and both passwords into the comand prompt after python manage.py createsuperuser and I got this error:

Traceback (most recent call last):
  File "C:\Users\mateu\Documents\meadow\backend\manage.py", line 22, in <module>
    main()
  File "C:\Users\mateu\Documents\meadow\backend\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line
    utility.execute()
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\core\management\base.py", line 417, in execute
    output = self.handle(*args, **options)
  File "C:\Users\mateu\Documents\meadow\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 195, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'

I have no idea how to fix it. Any thoughts?

Body:
You have to inherit from AbstractBaseUser not from AbstractUser and add Manager Class to it

from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    is_superuser = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    # Add other fields here

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

class UserManager(BaseUserManager):

    def _create_user(self, email, password, **extra_fields):
        user = self.model(email=self.normalize_email(email), **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password, **extra_fields):
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self._create_user(email, password, **extra_fields)

Don't forget

python manage.py makemigrations

python manage.py migrate

I recommend you to take a look at the docs


问:
How to define a more customElements for same Class
I jsut tried to define new Custom Elements.

// the class
class MyEl extends HTMLElement {
  constructor() {
    // mandatory super call to upgrade the current context
    super();
    // any other Class/DOM related procedure
    this.setAttribute('custom-attribute', 'value');
this.innerText = 'new element';
  }
}

// its mandatory definition
customElements.define('my-el', MyEl);

// the JS way to create a custom element
const newMe = new MyEl();

document.body.appendChild(newMe);```

Defining a new element of the same class will cause an error:

"Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry':
 this constructor has already been used with this registry"

But i want to define new elements for same class.
Could you suggest a way to display multiple items from the same class (MyEl).

Thank in advance!

答:
Just try with an anonymous constructor and extend your MyEl:

class MyEl extends HTMLElement {
  // your definitions
}

customElements.define("my-better-element", class extends MyEl { })
customElements.define("my-second-element", class extends MyEl { })```

Body:
I jsut tried to define new Custom Elements.

// the class
class MyEl extends HTMLElement {
  constructor() {
    // mandatory super call to upgrade the current context
    super();
    // any other Class/DOM related procedure
    this.setAttribute('custom-attribute', 'value');
this.innerText = 'new element';
  }
}

// its mandatory definition
customElements.define('my-el', MyEl);

// the JS way to create a custom element
const newMe = new MyEl();

document.body.appendChild(newMe);

Defining a new element of the same class will cause an error:

"Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry':
 this constructor has already been used with this registry"

But i want to define new elements for same class.
Could you suggest a way to display multiple items from the same class (MyEl).

Thank in advance!


问:
Mongoose not saving elements in Object Array?
I'm trying to make a RPG Discord Bot, where you can level skills, sell items, etc.
Recently, a friend of mine refactored all the code. Everything is working, besides the start command:

Before the refactor, it'd save everything correctly.
Afterwards, it didn't save the maxLevel property for any skill and began saving ObjectID properties.

Skills/start.js

    await new client.database.user({
      userID: interaction.user.id,
      inventory: [],
      coins: 250,
      skills: [
        {
          name: 'Strength',
          level: 1,
          exp: 0,
          maxLevel: 50,
        },
        {
          name: 'Agility',
          level: 1,
          exp: 0,
          maxLevel: 50,
        },
        {
          name: 'Knowledge',
          level: 1,
          exp: 0,
          maxLevel: 50,
        },
        {
          name: 'Trading',
          level: 1,
          exp: 0,
          maxLevel: 50,
        },
        {
          name: 'Challenge',
          level: 1,
          exp: 0,
          maxLevel: 5,
        },
        {
          name: 'Hunting',
          level: 1,
          exp: 0,
          maxLevel: 50,
        }
      ],
      mobsKilled: 0,
      bossesKilled: 0,
      created: moment().format('DD/MM/YYYY'),
      heavenDifficulty: Math.floor(Math.random() * 9 + 1),
    }).save();
```
<p><code>Schemas/User.js</code></p>
<pre class="lang-js prettyprint-override"><code>import mongoose from 'mongoose';

const userSchema = mongoose.Schema({
  userID: String,
  guild: {
    guildID: String,
    guildName: String,
    position: String
  },
  inventory: [{ name: String, amount: Number }],
  coins: Number,
  skills: [{ name: String, level: Number, exp: Number }],
  mobsKilled: Number,
  bossesKilled: Number,
  created: String,
  heavenDifficulty: Number,
  isPremium: Boolean,
  premium: {
    since: String,
    sinceTS: String, //TS = Timestamp
    tier: String
  }
});

const UserSchema = mongoose.model('users', userSchema);
</code>```

Also, I do know, that the premium properties are empty. This is because I want to add them to the database, when someone becomes a premium member and not when they start their journey.

Edit: This is what it's returning (all undefined properties should be the maxLevel property)
:

答:
"Afterwards, it didn't save the maxLevel property..."

Is the issue occurring because you need to add a maxLevel property to your database schema?

Body:
I'm trying to make a RPG Discord Bot, where you can level skills, sell items, etc.
Recently, a friend of mine refactored all the code. Everything is working, besides the start command:

Before the refactor, it'd save everything correctly.
Afterwards, it didn't save the maxLevel property for any skill and began saving ObjectID properties.

Skills/start.js

    await new client.database.user({
      userID: interaction.user.id,
      inventory: [],
      coins: 250,
      skills: [
        {
          name: 'Strength',
          level: 1,
          exp: 0,
          maxLevel: 50,
        },
        {
          name: 'Agility',
          level: 1,
          exp: 0,
          maxLevel: 50,
        },
        {
          name: 'Knowledge',
          level: 1,
          exp: 0,
          maxLevel: 50,
        },
        {
          name: 'Trading',
          level: 1,
          exp: 0,
          maxLevel: 50,
        },
        {
          name: 'Challenge',
          level: 1,
          exp: 0,
          maxLevel: 5,
        },
        {
          name: 'Hunting',
          level: 1,
          exp: 0,
          maxLevel: 50,
        }
      ],
      mobsKilled: 0,
      bossesKilled: 0,
      created: moment().format('DD/MM/YYYY'),
      heavenDifficulty: Math.floor(Math.random() * 9 + 1),
    }).save();

Schemas/User.js

import mongoose from 'mongoose';

const userSchema = mongoose.Schema({
  userID: String,
  guild: {
    guildID: String,
    guildName: String,
    position: String
  },
  inventory: [{ name: String, amount: Number }],
  coins: Number,
  skills: [{ name: String, level: Number, exp: Number }],
  mobsKilled: Number,
  bossesKilled: Number,
  created: String,
  heavenDifficulty: Number,
  isPremium: Boolean,
  premium: {
    since: String,
    sinceTS: String, //TS = Timestamp
    tier: String
  }
});

const UserSchema = mongoose.model('users', userSchema);

Also, I do know, that the premium properties are empty. This is because I want to add them to the database, when someone becomes a premium member and not when they start their journey.

Edit: This is what it's returning (all undefined properties should be the maxLevel property)
:


问:
how set the windows clock using c++
I'm trying set the windows system clock using C++.
I'm trying with the following code(not working):

```<code>#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {

    SYSTEMTIME st;
    st.wDay = 1;
    st.wMonth = 5;
    st.wYear = 2011;
    st.wHour = 12;
    st.wMinute = 15;
    bool result = SetLocalTime(&st);
    cout << result;
    return 0;
}
</code>```

Can someone point out my error? Thanks in advance.

答:
You need to initialize the parameters you don't need to 0.

Replace:

```<code>SYSTEMTIME st;
</code>```

with:

```<code>SYSTEMTIME st;
ZeroMemory(&st, sizeof(st));
</code>```

Title: how set the windows clock using c++

Body:
I'm trying set the windows system clock using C++.
I'm trying with the following code(not working):

#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {

    SYSTEMTIME st;
    st.wDay = 1;
    st.wMonth = 5;
    st.wYear = 2011;
    st.wHour = 12;
    st.wMinute = 15;
    bool result = SetLocalTime(&st);
    cout << result;
    return 0;
}

Can someone point out my error? Thanks in advance.

Body:
You need to initialize the parameters you don't need to 0.

Replace:

SYSTEMTIME st;

with:

SYSTEMTIME st;
ZeroMemory(&st, sizeof(st));


问:
SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
I am using the SmtpClient library to send emails using the following:

```<code>SmtpClient client = new SmtpClient();
client.Host = "hostname";
client.Port = 465;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User", "Pass);
client.Send("from@hostname", "to@hostname", "Subject", "Body");
</code>```

The code works fine in my test environment, but when I use production SMTP servers, the code fails with an SmtpException "Failure sending mail." with an inner IOException "Unable to read data from the transport connection: net_io_connectionclosed".

I've confirmed that firewalls are not an issue. The port opens just fine between the client and the server. I'm not sure what else could throw this error.

答:
I got the same problem with the .NET smtp client + office 365 mail server: sometimes mails were sent successfully, sometimes not (intermittent sending failures).

The problem was fixed by setting the desired TLS version to 1.2 only. The original code (which started to fail in the middle of the year 2021 - BTW) was allowing TLS 1.0, TLS 1.1 and TLS 1.2.

Code (CLI/C++)

```<code>    int tls12 = 3072; // Tls12 is not defined in the SecurityProtocolType enum in CLI/C++ / ToolsVersion="4.0"
    System::Net::ServicePointManager::SecurityProtocol = (SecurityProtocolType) tls12;
</code>```

(note: the problem was reproduced and fixed on a Win 8.1 machine)

Body:
I am using the SmtpClient library to send emails using the following:

SmtpClient client = new SmtpClient();
client.Host = "hostname";
client.Port = 465;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User", "Pass);
client.Send("from@hostname", "to@hostname", "Subject", "Body");

The code works fine in my test environment, but when I use production SMTP servers, the code fails with an SmtpException "Failure sending mail." with an inner IOException "Unable to read data from the transport connection: net_io_connectionclosed".

I've confirmed that firewalls are not an issue. The port opens just fine between the client and the server. I'm not sure what else could throw this error.

Body:
I got the same problem with the .NET smtp client + office 365 mail server: sometimes mails were sent successfully, sometimes not (intermittent sending failures).

The problem was fixed by setting the desired TLS version to 1.2 only. The original code (which started to fail in the middle of the year 2021 - BTW) was allowing TLS 1.0, TLS 1.1 and TLS 1.2.

Code (CLI/C++)

    int tls12 = 3072; // Tls12 is not defined in the SecurityProtocolType enum in CLI/C++ / ToolsVersion="4.0"
    System::Net::ServicePointManager::SecurityProtocol = (SecurityProtocolType) tls12;

(note: the problem was reproduced and fixed on a Win 8.1 machine)


问:
Python Flask SqlAlchemy Add Database Model Name dynamically in For Loop
I am not that familiar with Python and SQLAlchemy so please be patient :)

I need to capture if, within a FORM that holds multiple ICONS(files), one or more ICONS have been changed when editing the record.
To see which ICONS have been changed I created an Object holding the changes with "Database Model Name" as the "Key" and its "Value"

```<code>{'icon': <FileStorage: 'fire.png' ('image/png')>}
</code>```

key = used as database model name

value = file.filename

now when I try the get the data within a for loop and add this data to the Database model, nothing happens and it looks like I am not really accessing variable "k" in the loop.

```<code>for k, v in notequalat.items():
                    responseteamdata.k = v.filename
</code>```

My question is, how can I combine the Database model class "responseteamdata" and the variable "k" so that I can add the changes to the database model dynamically.

here is the full code:

```<code>if not notequalat:
            try:
                responseteamdata.title = title
                responseteamdata.abbreviation = abbreviation
                responseteamdata.isfireteam = booleanisfireteam
                responseteamdata.iconposition = newlatlng
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
                db.session.close()
                res = make_response(jsonify("message ", "Error Updating the Team"), 500)
                return res
        else:
            responseteamdata.title = title
            responseteamdata.abbreviation = abbreviation
            responseteamdata.isfireteam = booleanisfireteam
            responseteamdata.iconposition = newlatlng

            for k, v in notequalat.items():
                responseteamdata.k = v.filename

            db.session.commit()
            dbevent = "updated"

        db.session.close()
</code>```

答:
To be able to dynamically assign the Table Column Name the following command has been working for me:

```<code>setattr(DB-Object, ColumnName, Value)
</code>```

which means in my case:

```<code>setattr(responseteamdata, k, v.filename)
</code>```

Body:
I am not that familiar with Python and SQLAlchemy so please be patient :)

I need to capture if, within a FORM that holds multiple ICONS(files), one or more ICONS have been changed when editing the record.
To see which ICONS have been changed I created an Object holding the changes with "Database Model Name" as the "Key" and its "Value"

{'icon': <FileStorage: 'fire.png' ('image/png')>}

key = used as database model name

value = file.filename

now when I try the get the data within a for loop and add this data to the Database model, nothing happens and it looks like I am not really accessing variable "k" in the loop.

for k, v in notequalat.items():
                    responseteamdata.k = v.filename

My question is, how can I combine the Database model class "responseteamdata" and the variable "k" so that I can add the changes to the database model dynamically.

here is the full code:

if not notequalat:
            try:
                responseteamdata.title = title
                responseteamdata.abbreviation = abbreviation
                responseteamdata.isfireteam = booleanisfireteam
                responseteamdata.iconposition = newlatlng
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
                db.session.close()
                res = make_response(jsonify("message ", "Error Updating the Team"), 500)
                return res
        else:
            responseteamdata.title = title
            responseteamdata.abbreviation = abbreviation
            responseteamdata.isfireteam = booleanisfireteam
            responseteamdata.iconposition = newlatlng

            for k, v in notequalat.items():
                responseteamdata.k = v.filename

            db.session.commit()
            dbevent = "updated"

        db.session.close()

Body:
To be able to dynamically assign the Table Column Name the following command has been working for me:

setattr(DB-Object, ColumnName, Value)

which means in my case:

setattr(responseteamdata, k, v.filename)


问:
TypeError: string indices must be integers error from api
```<code>import requests
y = requests.get("https://api.pancakeswap.info/api/v2/tokens/0x1f546ad641b56b86fd9dceac473d1c7a357276b7")
print(y["data"]["name"])
</code>```

It's my code. api response is :

```<code>{"updated_at":1644149123565,"data":{"name":"PantherSwap Token","symbol":"PANTHER","price":"0.002859855069251732056933583434307","price_BNB":"0.000006871276102143279917041096829823"}}
</code>```

i want to get only price and name. I mean name = PantherSwap and price = 0.002859855

when i run i have error, error is TypeError: string indices must be integers

答:
```<code>import requests
response = requests.get("https://api.pancakeswap.info/api/v2/tokens/0x1f546ad641b56b86fd9dceac473d1c7a357276b7")
resp_json = response.json()
print(resp_json["data"]["name"])
</code>```

Body:
import requests
y = requests.get("https://api.pancakeswap.info/api/v2/tokens/0x1f546ad641b56b86fd9dceac473d1c7a357276b7")
print(y["data"]["name"])

It's my code. api response is :

{"updated_at":1644149123565,"data":{"name":"PantherSwap Token","symbol":"PANTHER","price":"0.002859855069251732056933583434307","price_BNB":"0.000006871276102143279917041096829823"}}

i want to get only price and name. I mean name = PantherSwap and price = 0.002859855

when i run i have error, error is TypeError: string indices must be integers