问:
Base10 encryption for a String
I am trying to find a way to obtain a base10 value for a String. This is easily achievable with the hash code function as shown. But I've noticed the values turns up sequential or close to it. Example below.

I am not dealing with a secure password or anything here, just wanting to be able to convert a String to base10 value and always get the same value when I do that.

May be bit over kill but looked at existing hashing options such as MessageDigest. But they are all Base64 (more or less) but none for Base10 which is expected considering that is not secure to begin with.

One possible option I am thinking is to use MessageDigest, get a base64 value and regex it to only extract out all the numbers. Meaning every time I encode via message digest and regex to get only Base10 values, I should always get same value.

My question is, is there a better way to do this? Instead of complicating it with encryptions which is not really needed in my case.

I just want to convert example as follows:

```<code>String s1 = "Sample00000000001";
// after encoding, getting Base10 value like -> 8725342728354

String s2 = "Sample00000000002";
// after encoding, getting Base10 value like -> 11576232138652 (random, not sequential even though only 1 character changed).
</code>```

Trying with Base64 from Java Util which produces results in sequence (or close) thus not what I want. Will still need to regex out the Base10 values from here.

```<code>public static void main(String[] args) {
    String salt = "Sample";
    String num = "00000000001";
    Base64.Encoder encoder = Base64.getEncoder();
    Base64.Decoder decoder = Base64.getDecoder();
    String value  = salt + num;
    String encoded = encoder.encodeToString(value.getBytes());
    String decoded = new String(decoder.decode(encoded));
    // 00000000001 gives U2FtcGxlMDAwMDAwMDAwMDE=
    // 00000000002 gives U2FtcGxlMDAwMDAwMDAwMDI=
}
</code>```

Using hashcode which again ends up sequential or close

```<code>public static void main(String[] args) {

    String salt = "Sample";
    String num = "00000000002";

    String v = salt+num;
    int hash = v.hashCode();
    System.out.println(hash);
}
</code>```

Last option I am looking at, using libraries like Bouncy castle or in built MessageDigest.

Assuming the encoding is done and I have assigned that to variable 'value' below. I could pull out only Base10 values from it via regex as follows.

```<code>String value = "HASDJHSDGF3423HIHGH234565BJB666";
long result =  Long.valueOf(value.replaceAll("\\D+",""));
System.out.println(result); // end up with 3423234565666 as expected.
</code>```

I am currently leaning towards this last option to possibly use MessageDigest but looking for advice / options for a better way to do this. Appreciate any help. Thanks.

答:
Purpose of method hashCode is for searching objects in data structures such as HashMap. Standard implementation is based on address in memory, not content of a string, so for your case it is useless.

Base64 is not an encryption and also not a hash function. It only converts binary data so it can be stored as text, so small changes in input will make small changes in output.

What you need is to use some real hash function like SHA and convert result for your format.

Title: Base10 encryption for a String

Body:
I am trying to find a way to obtain a base10 value for a String. This is easily achievable with the hash code function as shown. But I've noticed the values turns up sequential or close to it. Example below.

I am not dealing with a secure password or anything here, just wanting to be able to convert a String to base10 value and always get the same value when I do that.

May be bit over kill but looked at existing hashing options such as MessageDigest. But they are all Base64 (more or less) but none for Base10 which is expected considering that is not secure to begin with.

One possible option I am thinking is to use MessageDigest, get a base64 value and regex it to only extract out all the numbers. Meaning every time I encode via message digest and regex to get only Base10 values, I should always get same value.

My question is, is there a better way to do this? Instead of complicating it with encryptions which is not really needed in my case.

I just want to convert example as follows:

String s1 = "Sample00000000001";
// after encoding, getting Base10 value like -> 8725342728354

String s2 = "Sample00000000002";
// after encoding, getting Base10 value like -> 11576232138652 (random, not sequential even though only 1 character changed).

Trying with Base64 from Java Util which produces results in sequence (or close) thus not what I want. Will still need to regex out the Base10 values from here.

public static void main(String[] args) {
    String salt = "Sample";
    String num = "00000000001";
    Base64.Encoder encoder = Base64.getEncoder();
    Base64.Decoder decoder = Base64.getDecoder();
    String value  = salt + num;
    String encoded = encoder.encodeToString(value.getBytes());
    String decoded = new String(decoder.decode(encoded));
    // 00000000001 gives U2FtcGxlMDAwMDAwMDAwMDE=
    // 00000000002 gives U2FtcGxlMDAwMDAwMDAwMDI=
}

Using hashcode which again ends up sequential or close

public static void main(String[] args) {

    String salt = "Sample";
    String num = "00000000002";

    String v = salt+num;
    int hash = v.hashCode();
    System.out.println(hash);
}

Last option I am looking at, using libraries like Bouncy castle or in built MessageDigest.

Assuming the encoding is done and I have assigned that to variable 'value' below. I could pull out only Base10 values from it via regex as follows.

String value = "HASDJHSDGF3423HIHGH234565BJB666";
long result =  Long.valueOf(value.replaceAll("\\D+",""));
System.out.println(result); // end up with 3423234565666 as expected.

I am currently leaning towards this last option to possibly use MessageDigest but looking for advice / options for a better way to do this. Appreciate any help. Thanks.


来源: stackexchange

问:
A function passes all these unit tests, why is it failing in its actual context with the same parameters?
I'm making a simple API to cipher text through the Caesar cipher, on Javascript with Express.js. Testing the output with Jest, it appears to pass all the tests (and a console.log of the output indeed shows that the output string matches the expected string). However, when testing the relevant endpoint with Postman, the output doesn't match the expected string. I don't even know where to start digging, honestly.

Here is the route:

```<code>  const plaintext = req.body.text
  const factor = req.body.factor
  if (/^[a-zA-Z\s]*$/.test(plaintext) === false) {
    res.json({
      error: 'Your text contains forbidden characters! Please use only letters from A to Z',
    })
  } else {
    res.json({ message: caesar(plaintext, factor) })
  }
})
</code>```

Here's the function:

```<code>const max = 'Z'.charCodeAt(0)
const lowerMin = 'a'.charCodeAt(0)
const lowerMax = 'z'.charCodeAt(0)

module.exports = {
  caesar: (plaintext, factor) => {
    let cipher = ''
    for (let i = 0; i < plaintext.length; i++) {
      plaintext.charCodeAt(i) >= 65 && plaintext.charCodeAt(i) <= 90
        ? (cipher += String.fromCharCode(
            ((plaintext.charCodeAt(i) - min + factor) % (max - min + 1)) + min
          ))
        : plaintext.charCodeAt(i) >= 97 && plaintext.charCodeAt(i) <= 122
        ? (cipher += String.fromCharCode(
            ((plaintext.charCodeAt(i) - lowerMin + factor) % (lowerMax - lowerMin + 1)) + lowerMin
          ))
        : (cipher += plaintext[i])
    }
    return cipher
  },
}
</code>```

The tests:

```<code>
test('Ciphers the whole alphabet to ROT13, equalling "NOPQRSTUVWXYZABCDEFGHIJKLM"', () => {
  expect(caesar('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 13)).toBe('NOPQRSTUVWXYZABCDEFGHIJKLM')
})

test('Ciphers "ABCXYZ" to ROT13, equalling "NOPKLM"', () => {
  expect(caesar('ABCXYZ', 13)).toBe('NOPKLM')
})

test('Ciphers "Lorem Ipsum Dolor Sit Amet" to "Yberz Vcfhz Qbybe Fvg Nzrg" on ROT13', () => {
  expect(caesar('Lorem Ipsum Dolor Sit Amet', 13)).toBe('Yberz Vcfhz Qbybe Fvg Nzrg')
})

test('Ciphers "Lorem Ipsum Dolor Sit Amet" to "Twzmu Qxacu Lwtwz Aqb Iumb" on ROT8', () => {
  expect(caesar('Lorem Ipsum Dolor Sit Amet', 8)).toBe('Twzmu Qxacu Lwtwz Aqb Iumb')
})
</code>```

And the output of some queries:

Text: Lorem Ipsum Dolor Sit Amet |
Factor: 13 |
Output:

```<code>    "message": "Vjxxr Hftlr Bjvjx Thp Nrxp"
}
</code>```

Text: ABCDEFGHIJKLMNOPQRSTUVWXYZ |
Factor: 13 |
Output:

```<code>{
    "message": "NJFBXTPLHDZVRNJFBXTPLHDZVR"
}
</code>```

答:
The difference between test cases and API route is that factor isn't parsed and thus is allowed to be a string.

Type coercion makes this line

```<code>((plaintext.charCodeAt(i) - lowerMin + factor) % (lowerMax - lowerMin + 1)) + lowerMin
</code>```

concatenate plaintext.charCodeAt(i) - lowerMin and factor strings, the result is converted to a number.

It should be:

```<code>const factor = +req.body.factor
</code>```

factor can be additionally validated to be positive integer.

ContentLicense: CC BY-SA 4.0

Body:
I'm making a simple API to cipher text through the Caesar cipher, on Javascript with Express.js. Testing the output with Jest, it appears to pass all the tests (and a console.log of the output indeed shows that the output string matches the expected string). However, when testing the relevant endpoint with Postman, the output doesn't match the expected string. I don't even know where to start digging, honestly.

Here is the route:

  const plaintext = req.body.text
  const factor = req.body.factor
  if (/^[a-zA-Z\s]*$/.test(plaintext) === false) {
    res.json({
      error: 'Your text contains forbidden characters! Please use only letters from A to Z',
    })
  } else {
    res.json({ message: caesar(plaintext, factor) })
  }
})

Here's the function:

const max = 'Z'.charCodeAt(0)
const lowerMin = 'a'.charCodeAt(0)
const lowerMax = 'z'.charCodeAt(0)

module.exports = {
  caesar: (plaintext, factor) => {
    let cipher = ''
    for (let i = 0; i < plaintext.length; i++) {
      plaintext.charCodeAt(i) >= 65 && plaintext.charCodeAt(i) <= 90
        ? (cipher += String.fromCharCode(
            ((plaintext.charCodeAt(i) - min + factor) % (max - min + 1)) + min
          ))
        : plaintext.charCodeAt(i) >= 97 && plaintext.charCodeAt(i) <= 122
        ? (cipher += String.fromCharCode(
            ((plaintext.charCodeAt(i) - lowerMin + factor) % (lowerMax - lowerMin + 1)) + lowerMin
          ))
        : (cipher += plaintext[i])
    }
    return cipher
  },
}

The tests:

test('Ciphers the whole alphabet to ROT13, equalling "NOPQRSTUVWXYZABCDEFGHIJKLM"', () => {
  expect(caesar('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 13)).toBe('NOPQRSTUVWXYZABCDEFGHIJKLM')
})

test('Ciphers "ABCXYZ" to ROT13, equalling "NOPKLM"', () => {
  expect(caesar('ABCXYZ', 13)).toBe('NOPKLM')
})

test('Ciphers "Lorem Ipsum Dolor Sit Amet" to "Yberz Vcfhz Qbybe Fvg Nzrg" on ROT13', () => {
  expect(caesar('Lorem Ipsum Dolor Sit Amet', 13)).toBe('Yberz Vcfhz Qbybe Fvg Nzrg')
})

test('Ciphers "Lorem Ipsum Dolor Sit Amet" to "Twzmu Qxacu Lwtwz Aqb Iumb" on ROT8', () => {
  expect(caesar('Lorem Ipsum Dolor Sit Amet', 8)).toBe('Twzmu Qxacu Lwtwz Aqb Iumb')
})

And the output of some queries:

Text: Lorem Ipsum Dolor Sit Amet |
Factor: 13 |
Output:

    "message": "Vjxxr Hftlr Bjvjx Thp Nrxp"
}

Text: ABCDEFGHIJKLMNOPQRSTUVWXYZ |
Factor: 13 |
Output:

{
    "message": "NJFBXTPLHDZVRNJFBXTPLHDZVR"
}

Body:
The difference between test cases and API route is that factor isn't parsed and thus is allowed to be a string.

Type coercion makes this line

((plaintext.charCodeAt(i) - lowerMin + factor) % (lowerMax - lowerMin + 1)) + lowerMin

concatenate plaintext.charCodeAt(i) - lowerMin and factor strings, the result is converted to a number.

It should be:

const factor = +req.body.factor

factor can be additionally validated to be positive integer.


问:
chrome 83 started crashing since upgrade
Since the upgrade my angular e2e tests started failing with following message.

I am using directConnect: true and all my tests are using async/await.
It looks it is crashing and does not always crash at the same point in my tests - and I do have some test running successfully. Disabled sharding as well.

- Failed: unknown error: session deleted because of page crash
           from unknown error: cannot determine loading status
           from tab crashed
             (Session info: headless chrome=83.0.4103.61)
             (Driver info: chromedriver=83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}),platform=Linux 3.10.0-1127.el7.x86_64 x86_64)

UPDATE: 6/1/2020
After adding more shared memory (finding CI runners that have more memory) this problem is gone. Still leaves the problem in a "mystery mode".

Update 6/2/2020:

Chrome Flags

```<code>    'headless',
    'verbose',
    'w3c=false',
    'disable-infobars',
    'window-size=1440x1080',
    'disable-dev-shm-usage',
    'disable-gpu',
    'incognito',
    'disable-extensions',
    'disable-plugins',
    'no-sandbox'
</code>```

答:
I'm using chrome headless in podman and I've run into the same issue, here's what seems to work for me:

increase /dev/shm

remove "disable-dev-shm-usage" option

I needed the option in the past because it was impossible to change default /dev/shm size in a proprietary cloud software I'm using, looks like it's broken in the last chrome release.
The funny thing is - chrome also runs much faster after the changes

Body:
Since the upgrade my angular e2e tests started failing with following message.

I am using directConnect: true and all my tests are using async/await.
It looks it is crashing and does not always crash at the same point in my tests - and I do have some test running successfully. Disabled sharding as well.

- Failed: unknown error: session deleted because of page crash
           from unknown error: cannot determine loading status
           from tab crashed
             (Session info: headless chrome=83.0.4103.61)
             (Driver info: chromedriver=83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}),platform=Linux 3.10.0-1127.el7.x86_64 x86_64)

UPDATE: 6/1/2020
After adding more shared memory (finding CI runners that have more memory) this problem is gone. Still leaves the problem in a "mystery mode".

Update 6/2/2020:

Chrome Flags

    'headless',
    'verbose',
    'w3c=false',
    'disable-infobars',
    'window-size=1440x1080',
    'disable-dev-shm-usage',
    'disable-gpu',
    'incognito',
    'disable-extensions',
    'disable-plugins',
    'no-sandbox'


问:
buildSrc: Could not get unknown property for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler
I am trying to reorganize this Android (Java based) library to use the buildSrc folder to define all versions and dependencies as described in this article.

I already set this successfully up for several times for Kotlin bases projects. This time the project is pure Java.

In the buildSrc folder I created the following buildSrc/src/main/java/org/ligi/snackengage/Dependencies.java file:

```<code>package org.ligi.snackengage;

public class Dependencies {

    public static class Android { /* ... */ }

    public static class GradlePlugins {
        public static final String ANDROID = "com.android.tools.build:gradle:3.6.3";
        // ...
    }

    public static class Libs { /* ... */ }

}
</code>```

Then I refer to the definitions in the project root build.gradle among others:

```<code>import org.ligi.snackengage.Dependencies.GradlePlugins

apply plugin: "com.github.ben-manes.versions"

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath GradlePlugins.ANDROID
        classpath GradlePlugins.MAVEN
        classpath GradlePlugins.VERSIONS
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}
</code>```

Here is the work in progress branch. When I build the project then the following error occurs:

* Where:
Build file 'SnackEngage/build.gradle' line: 12

* What went wrong:
A problem occurred evaluating root project 'SnackEngage'.
> Could not get unknown property 'GradlePlugins' for object of type
  org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
```

Here is the build log.

答:
You need to define variable GradlePlugins with def (in Gradle) or public class GradlePlugins (in Java), before attempting to access it. Kotlin class GradlePlugins should also work.

```<code>dependencies {
    classpath GradlePlugins.ANDROID
    classpath GradlePlugins.MAVEN
    classpath GradlePlugins.VERSIONS
}
</code>```

And I think the buildSrc directory belongs into the module directory, as the Gradle manual shows.

Body:
I am trying to reorganize this Android (Java based) library to use the buildSrc folder to define all versions and dependencies as described in this article.

I already set this successfully up for several times for Kotlin bases projects. This time the project is pure Java.

In the buildSrc folder I created the following buildSrc/src/main/java/org/ligi/snackengage/Dependencies.java file:

package org.ligi.snackengage;

public class Dependencies {

    public static class Android { /* ... */ }

    public static class GradlePlugins {
        public static final String ANDROID = "com.android.tools.build:gradle:3.6.3";
        // ...
    }

    public static class Libs { /* ... */ }

}

Then I refer to the definitions in the project root build.gradle among others:

import org.ligi.snackengage.Dependencies.GradlePlugins

apply plugin: "com.github.ben-manes.versions"

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath GradlePlugins.ANDROID
        classpath GradlePlugins.MAVEN
        classpath GradlePlugins.VERSIONS
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Here is the work in progress branch. When I build the project then the following error occurs:

* Where:
Build file 'SnackEngage/build.gradle' line: 12

* What went wrong:
A problem occurred evaluating root project 'SnackEngage'.
> Could not get unknown property 'GradlePlugins' for object of type
  org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Here is the build log.

Body:
You need to define variable GradlePlugins with def (in Gradle) or public class GradlePlugins (in Java), before attempting to access it. Kotlin class GradlePlugins should also work.

dependencies {
    classpath GradlePlugins.ANDROID
    classpath GradlePlugins.MAVEN
    classpath GradlePlugins.VERSIONS
}

And I think the buildSrc directory belongs into the module directory, as the Gradle manual shows.


问:
Necessary to check for empty variable after validation and before saving data?
Is it still necessary to check for empty variable after validation a form and before saving a data?

This step is somewhat unnecessary because if a user does not enter any input, the validation rule would definitely trigger an error.

However, I've seen comments from others saying that if user input gets sanitized it might return an empty variable. But how often do we get user who will enter pure XSS script that will only return an empty variable?

Anyone has any opinions on this? Thanks in advance.

答:
Having a sanitized return value that is empty and having an empty value sent is not the same thing.

Consider a simpe logon script: User does not input username & password.  Would you still validate his input? Obviously, no. You would have a check for $_POST['username'] and $_POST['pw'] to make sure they have a value before passing those off to validation. This is the only way you have control on what is wrong ( and why it is wrong).  You can then give the user a message that username & password is needed to log on. Of course, many validation libraries do that step themselves but it is important that the validation library you use tells you why the validation failed so you can act accordingly, ie: To message the user, or log malicious attempts for example.

Hope that helps, happy conding

ContentLicense: CC BY-SA 3.0


问:
How to write Inline/Lambda for appending or not appending to a list
I feel this a noob question but I haven't used lambda functions that much and I couldn't find what I needed online.
I wanted to write a lambda function which takes a series as an input, and returns a list without any 'None's in it
Basically I want a lambda function for the followinf function:

```<code>def get_path(x):
  toRet = []
  for item in x.tolist():
    if item is not None:
      toret.append(item)
  return toRet
</code>```

Is it possible to get an inline lambda function which does what get_path() does.
Yes I do know that I can do the following:

```<code>lambda x: get_path(x)
</code>```

It solves the problem but I would really love to know how to make an inline function for this.

答:
```<code>get_path = lambda x: [ elem for elem in x.tolist() if not elem]
</code>```

Body:
I feel this a noob question but I haven't used lambda functions that much and I couldn't find what I needed online.
I wanted to write a lambda function which takes a series as an input, and returns a list without any 'None's in it
Basically I want a lambda function for the followinf function:

def get_path(x):
  toRet = []
  for item in x.tolist():
    if item is not None:
      toret.append(item)
  return toRet

Is it possible to get an inline lambda function which does what get_path() does.
Yes I do know that I can do the following:

lambda x: get_path(x)

It solves the problem but I would really love to know how to make an inline function for this.


问:
token exchange endpoint not called after authorization endpoint redirect
I have created my first Google Smart Home project and implemented the two endpoints for account linking. The authorization endpoint is called and my code respond by redirecting (302) to the redirect_uri providing an authorization code, however the token exchange endpoint is never called.
The account linking is triggered from the Google Assistant UI, when linking a device. It goes into "Manage Accounts". I click my [test] display name, it goes to my account linking site, then goes back to the "Manage Accounts" screen. The token exchange endpoint is not called and, of course, no SYNC happens.
What I may be doing wrong? How can I debug the flow? I get no error anywhere...
Thanks in advance for any hints or help.</p>

答: I was facing the same problem. I resolved it by uninstalling my Chrome browser on the phone. It seems that the login authentication process was initiated in the browser and the browser was not able to redirect to the com.google.android.apps.gsa.gdi: protocol. After uninstalling the browser, the login authentication was done by Google Home and it was able to recognize the protocol and call token exchange.</p>


答:
You don't even need lambda functions here.

```<code>toRet = [item for item in x.tolist() if item is not None]
</code>```

You can also use filter for example, which looks neater

```<code>toRet = list(filter(None, x.tolist()))
</code>```

Title: How to write Inline/Lambda for appending or not appending to a list

Body:
You don't even need lambda functions here.

toRet = [item for item in x.tolist() if item is not None]

You can also use filter for example, which looks neater

toRet = list(filter(None, x.tolist()))


问:
Setting up Reverse DNS Records
This question is not directly programming related but I need my Server to pass Spam filters for my app to work properly. I talked to my ISP about rDNS and the guy from tech-support told me if I write an email with what they should add to my DNS record they would do that. My question:

What should I tell him to add if my hostname is "http://niklasfi.de" and my is 78.31.67.216?

Thanks für the answers. I tried searching on the Web but i only very specific anwers concerning a single ISP.

答:
Just to clarify. http://niklasfi.de is not a host name. It's a URI or URL. A host name would be mail.niklausfi.de for example.

I looked it up using one of the many service on the web (search for "reverse DNS lookup"). The mentioned IP address has already an IN-ADDR record. It's 216-67-31-78-rb1.sit.dsl.dynamic.acsalaska.net.

OwnerDisplayName: niklasfi

ContentLicense: CC BY-SA 2.5

Title: Setting up Reverse DNS Records

OwnerDisplayName: splattne


问:
Java to HTML Parser / State Machine
I wish to create a app that translates input java code into HTML formatted java code,

For example:

```<code>public class ReadWithScanner
</code>```

Would become

```<code><span class="public">public</span> <span class="class">class</span> ReadWithScanner
</code>```

However it gets quite complicated when it comes to parameters and regular expressions. Now I have a bit of time on my hands, and I wish to write my own code parser.

How would I start this? and is there any tutorials or online content to not only help me write this, but understand it.

Thanks

答:
For help with the complexity of parsing, you'll need to rely on the Java Language Specification.

As I seem to recall, Java is an LL(k) language (see here, for instance). However, the Java language, despite all attempts to keep it "compact", is still quite large and complex. The grammar is spread out over the entire document. This is not a project for the faint at heart. You might consider using a Java parsing tool (like Java-front).

Title: Java to HTML Parser / State Machine

Body:
I wish to create a app that translates input java code into HTML formatted java code,

For example:

public class ReadWithScanner

Would become

public class ReadWithScanner

However it gets quite complicated when it comes to parameters and regular expressions. Now I have a bit of time on my hands, and I wish to write my own code parser.

How would I start this? and is there any tutorials or online content to not only help me write this, but understand it.

Thanks


问:
SEQUELIZE: hasMany is not a function
I'm totally newbie with Sequelize and I'm getting the next error when I run my application and sync my tables:

```<code>TypeError: UserModel.hasMany is not a function
    at Object.<anonymous> (/home/josecarlos/Workspace/nodejs/remote-roofing/src/server/models/users.js:46:11)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Module._compile (/home/josecarlos/Workspace/nodejs/remote-roofing/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Object.newLoader [as .js] (/home/josecarlos/Workspace/nodejs/remote-roofing/node_modules/pirates/lib/index.js:104:7)
</code>```

I've got two tables only, so I have defined two models. One for each one and try to relationship between them.

user.js

```<code>import ProjectModel from "./projects";

const UserModel = (sequelize, type) => {
    return sequelize.define("user", {
        id: {
            type: type.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false,
        },
        email: {
            type: type.STRING,
            allowNull: false,
            isEmail: {
                msg: "The format of the e-mail is not correct"
            },
            validate: {
                notNull: {
                    msg: "E-mail cannot be empty"
                }
            }
        },
        name: {
            type: type.STRING,
            is: /^[a-zA-Z ]+$/i,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Name cannot be empty"
                }
            }
        },
        surname: {
            type: type.STRING,
            is: /^[a-zA-Z ]+$/i,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Surname cannot be empty"
                }
            }
        }
    })
};

UserModel.hasMany(ProjectModel, { foreingKey: "userID", sourceKey: "id"});
ProjectModel.belongsTo(UserModel, { foreingKey: "userID", sourceKey: "id"});

module.exports.UserModel = UserModel;
</code>```

project.js

```<code>import UserModel from "./users";

const ProjectModel = (sequelize, type) => {
    return sequelize.define("project", {
        id: {
            type: type.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false,
        },
        name: {
            type: type.STRING,
            is: /^[a-zA-Z ]+$/i,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Name cannot be empty"
                }
            }
        },
        body: {
            type: type.TEXT,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Body cannot be empty"
                }
            }
        },
        status: {
            type: type.ENUM("active", "inactive", "declined", "completed"),
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Status cannot be empty"
                }
            }
        },
        userID: {
            type: type.INTEGER,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "userID cannot be empty"
                }
            }
        }
    })
};

module.exports.ProjectModel = ProjectModel;
</code>```

This two models are create from db.js:

```<code>import Sequelize from "sequelize";
import UserModel from "./models/users";
import ProjectModel from "./models/projects";
//It's mandatory to import dotenv in each file where we can use enviroment variables
import config from "dotenv";
config.config();

const sequelize = new Sequelize(process.env.DDBB_NAME, process.env.DDBB_USER,process.env.DDBB_PSWD, {
        host: process.env.DDBB_HOST,
        port: process.env.DDBB_PORT,
        define: {
            //freezeTableName: true, /**Don't add 's to the end of each table/model */
            //timestamps: false,  /**Don't add fields createdAt and updatedAt */
        },
        dialect: "postgres",
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    }
);

const User = UserModel(sequelize, Sequelize);
const Project = ProjectModel(sequelize, Sequelize);

sequelize.sync({force: false}).then(() => {
    console.log("Tables syncronized!!!")
})

module.exports = {
    User,
    Project
};
</code>```

This file is required when I run the application. And I've got the error that I have showned before.

What am I doing wrong?

Edit I:

I have modified db.js file and it doesn't work to me. I've got the same error. I don't know how been called the models :(((((

```<code>import Sequelize from "sequelize";
import UserModel from "./models/users";
import ProjectModel from "./models/projects";
import fs from "fs";
import path from "path";
//It's mandatory to import dotenv in each file where we can use enviroment variables
import config from "dotenv";
config.config();

const sequelize = new Sequelize(process.env.DDBB_NAME, process.env.DDBB_USER,process.env.DDBB_PSWD, {
        host: process.env.DDBB_HOST,
        port: process.env.DDBB_PORT,
        define: {
            //freezeTableName: true, /**Don't add 's to the end of each table/model */
            //timestamps: false,  /**Don't add fields createdAt and updatedAt */
        },
        dialect: "postgres",
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    }
);

let db = {
    sequelize,
    Sequelize,
    models: {}
}

//Register Models
const models = path.join(__dirname, "models");
fs
  .readdirSync(models)
  .filter(function (file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
  })
  .forEach(function (file) {
    var model = sequelize['import'](path.join(models, file))
    db[model.name] = model
  })

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.sequelize.sync({force: false}).then(() => {
    console.log("Tables syncronized!!!")
})

module.exports.db = db;
</code>```

Edit II:

Now, I've got this error:

```<code>/home/josecarlos/Workspace/nodejs/remote-roofing/src/server/models/users.js:9
var UserModel = _db["default"].sequelize.define("user", {
                                         ^

TypeError: Cannot read property 'define' of undefined
    at Object.<anonymous> (/home/josecarlos/Workspace/nodejs/remote-roofing/src/server/models/users.js:4:32)
</code>```

db.js

```<code>import Sequelize from "sequelize";
import UserModel from "./models/users";
import ProjectModel from "./models/projects";
import fs from "fs";
import path from "path";
//It's mandatory to import dotenv in each file where we can use enviroment variables
import config from "dotenv";
config.config();

const sequelize = new Sequelize(process.env.DDBB_NAME, process.env.DDBB_USER,process.env.DDBB_PSWD, {
        host: process.env.DDBB_HOST,
        port: process.env.DDBB_PORT,
        define: {
            //freezeTableName: true, /**Don't add 's to the end of each table/model */
            //timestamps: false,  /**Don't add fields createdAt and updatedAt */
        },
        dialect: "postgres",
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    }
);

let db = {
    sequelize: sequelize,
    Sequelize: Sequelize,
    models: {}
}

//Register Models
const models = path.join(__dirname, "models");
fs
  .readdirSync(models)
  .filter(function (file) {
      console.log("file: " + file);
    return (file.indexOf('.') !== 0) && (file.slice(-3) === '.js')
  })
  .forEach(function (file) {
    var model = sequelize['import'](path.join(models, file))
    db[model.name] = model
  })

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.sequelize.sync({force: false}).then(() => {
    console.log("Tables syncronized!!!")
})

module.exports.db = db;
</code>```

users.js

```<code>import Sequelize from "sequelize";
import db from "../db";

const UserModel = db.sequelize.define("user", {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
    },
    email: {
        type: Sequelize.STRING,
        allowNull: false,
        isEmail: {
            msg: "The format of the e-mail is not correct"
        },
        validate: {
            notNull: {
                msg: "E-mail cannot be empty"
            }
        }
    },
    name: {
        type: Sequelize.STRING,
        is: /^[a-zA-Z ]+$/i,
        allowNull: false,
        validate: {
            notNull: {
                msg: "Name cannot be empty"
            }
        }
    },
    surname: {
        type: Sequelize.STRING,
        is: /^[a-zA-Z ]+$/i,
        allowNull: false,
        validate: {
            notNull: {
                msg: "Surname cannot be empty"
            }
        }
    }
})

UserModel.associate = (models) => {
    UserModel.hasMany(models.ProjectModel, {
        foreignKey: "userID"
    })
}

module.exports.UserModel = UserModel;
</code>```

project.js

```<code>import Sequelize from "sequelize";
import db from "../db";

const ProjectModel = db.sequelize.define("project", {
    id: {
        type: type.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
    },
    name: {
        type: type.STRING,
        is: /^[a-zA-Z ]+$/i,
        allowNull: false,
        validate: {
            notNull: {
                msg: "Name cannot be empty"
            }
        }
    },
    body: {
        type: type.TEXT,
        allowNull: false,
        validate: {
            notNull: {
                msg: "Body cannot be empty"
            }
        }
    },
    status: {
        type: type.ENUM("active", "inactive", "declined", "completed"),
        allowNull: false,
        validate: {
            notNull: {
                msg: "Status cannot be empty"
            }
        }
    },
    userID: {
        type: type.INTEGER,
        allowNull: false,
        validate: {
            notNull: {
                msg: "userID cannot be empty"
            }
        }
    }
});

ProjectModel.associate = (models) => {
    ProjectModel.belongsTo(models.UserModel, {
        foreignKey: "userID"
    })
}

module.exports.ProjectModel = ProjectModel;
</code>```

Sorry, but I don't understand anything ... :((

Edit III:

I have checked the keys of db in user.js and I've got nothing, so it's right that I've got thi error, but ... Why have db nothing?

```<code>[nodemon] starting `babel-node src/server/server.js`
db:
</code>```

答:
Your issue is that UserModel in user.js is as a function that returns a sequalize definition.

In the same file you are trying to call UserModel.hasMany on the function that returns your model object instead of on the model object itself.

You probably just want to remove the wrapping function and assign the sequalize object to UserModel directly.

```<code>const UserModel = sequelize.define("user", {
...
</code>```

or move the calls on UserModel into the function.

```<code>    const model = sequelize.define("user", {
    ...
    });
    model.hasMany(ProjectModel, { foreingKey: "userID", sourceKey: "id"});
    model.belongsTo(UserModel, { foreingKey: "userID", sourceKey: "id"});
    return model;
};
module.exports.UserModel = UserModel;
</code>```

Title: SEQUELIZE: hasMany is not a function

Body:
I'm totally newbie with Sequelize and I'm getting the next error when I run my application and sync my tables:

TypeError: UserModel.hasMany is not a function
    at Object.<anonymous> (/home/josecarlos/Workspace/nodejs/remote-roofing/src/server/models/users.js:46:11)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Module._compile (/home/josecarlos/Workspace/nodejs/remote-roofing/node_modules/pirates/lib/index.js:99:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Object.newLoader [as .js] (/home/josecarlos/Workspace/nodejs/remote-roofing/node_modules/pirates/lib/index.js:104:7)

I've got two tables only, so I have defined two models. One for each one and try to relationship between them.

user.js

import ProjectModel from "./projects";

const UserModel = (sequelize, type) => {
    return sequelize.define("user", {
        id: {
            type: type.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false,
        },
        email: {
            type: type.STRING,
            allowNull: false,
            isEmail: {
                msg: "The format of the e-mail is not correct"
            },
            validate: {
                notNull: {
                    msg: "E-mail cannot be empty"
                }
            }
        },
        name: {
            type: type.STRING,
            is: /^[a-zA-Z ]+$/i,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Name cannot be empty"
                }
            }
        },
        surname: {
            type: type.STRING,
            is: /^[a-zA-Z ]+$/i,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Surname cannot be empty"
                }
            }
        }
    })
};

UserModel.hasMany(ProjectModel, { foreingKey: "userID", sourceKey: "id"});
ProjectModel.belongsTo(UserModel, { foreingKey: "userID", sourceKey: "id"});

module.exports.UserModel = UserModel;

project.js

import UserModel from "./users";

const ProjectModel = (sequelize, type) => {
    return sequelize.define("project", {
        id: {
            type: type.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: false,
        },
        name: {
            type: type.STRING,
            is: /^[a-zA-Z ]+$/i,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Name cannot be empty"
                }
            }
        },
        body: {
            type: type.TEXT,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Body cannot be empty"
                }
            }
        },
        status: {
            type: type.ENUM("active", "inactive", "declined", "completed"),
            allowNull: false,
            validate: {
                notNull: {
                    msg: "Status cannot be empty"
                }
            }
        },
        userID: {
            type: type.INTEGER,
            allowNull: false,
            validate: {
                notNull: {
                    msg: "userID cannot be empty"
                }
            }
        }
    })
};

module.exports.ProjectModel = ProjectModel;

This two models are create from db.js:

import Sequelize from "sequelize";
import UserModel from "./models/users";
import ProjectModel from "./models/projects";
//It's mandatory to import dotenv in each file where we can use enviroment variables
import config from "dotenv";
config.config();

const sequelize = new Sequelize(process.env.DDBB_NAME, process.env.DDBB_USER,process.env.DDBB_PSWD, {
        host: process.env.DDBB_HOST,
        port: process.env.DDBB_PORT,
        define: {
            //freezeTableName: true, /**Don't add 's to the end of each table/model */
            //timestamps: false,  /**Don't add fields createdAt and updatedAt */
        },
        dialect: "postgres",
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    }
);

const User = UserModel(sequelize, Sequelize);
const Project = ProjectModel(sequelize, Sequelize);

sequelize.sync({force: false}).then(() => {
    console.log("Tables syncronized!!!")
})

module.exports = {
    User,
    Project
};

This file is required when I run the application. And I've got the error that I have showned before.

What am I doing wrong?

Edit I:

I have modified db.js file and it doesn't work to me. I've got the same error. I don't know how been called the models :(((((

import Sequelize from "sequelize";
import UserModel from "./models/users";
import ProjectModel from "./models/projects";
import fs from "fs";
import path from "path";
//It's mandatory to import dotenv in each file where we can use enviroment variables
import config from "dotenv";
config.config();

const sequelize = new Sequelize(process.env.DDBB_NAME, process.env.DDBB_USER,process.env.DDBB_PSWD, {
        host: process.env.DDBB_HOST,
        port: process.env.DDBB_PORT,
        define: {
            //freezeTableName: true, /**Don't add 's to the end of each table/model */
            //timestamps: false,  /**Don't add fields createdAt and updatedAt */
        },
        dialect: "postgres",
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    }
);

let db = {
    sequelize,
    Sequelize,
    models: {}
}

//Register Models
const models = path.join(__dirname, "models");
fs
  .readdirSync(models)
  .filter(function (file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
  })
  .forEach(function (file) {
    var model = sequelize['import'](path.join(models, file))
    db[model.name] = model
  })

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.sequelize.sync({force: false}).then(() => {
    console.log("Tables syncronized!!!")
})

module.exports.db = db;

Edit II:

Now, I've got this error:

/home/josecarlos/Workspace/nodejs/remote-roofing/src/server/models/users.js:9
var UserModel = _db["default"].sequelize.define("user", {
                                         ^

TypeError: Cannot read property 'define' of undefined
    at Object.<anonymous> (/home/josecarlos/Workspace/nodejs/remote-roofing/src/server/models/users.js:4:32)

db.js

import Sequelize from "sequelize";
import UserModel from "./models/users";
import ProjectModel from "./models/projects";
import fs from "fs";
import path from "path";
//It's mandatory to import dotenv in each file where we can use enviroment variables
import config from "dotenv";
config.config();

const sequelize = new Sequelize(process.env.DDBB_NAME, process.env.DDBB_USER,process.env.DDBB_PSWD, {
        host: process.env.DDBB_HOST,
        port: process.env.DDBB_PORT,
        define: {
            //freezeTableName: true, /**Don't add 's to the end of each table/model */
            //timestamps: false,  /**Don't add fields createdAt and updatedAt */
        },
        dialect: "postgres",
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    }
);

let db = {
    sequelize: sequelize,
    Sequelize: Sequelize,
    models: {}
}

//Register Models
const models = path.join(__dirname, "models");
fs
  .readdirSync(models)
  .filter(function (file) {
      console.log("file: " + file);
    return (file.indexOf('.') !== 0) && (file.slice(-3) === '.js')
  })
  .forEach(function (file) {
    var model = sequelize['import'](path.join(models, file))
    db[model.name] = model
  })

Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.sequelize.sync({force: false}).then(() => {
    console.log("Tables syncronized!!!")
})

module.exports.db = db;

users.js

import Sequelize from "sequelize";
import db from "../db";

const UserModel = db.sequelize.define("user", {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
    },
    email: {
        type: Sequelize.STRING,
        allowNull: false,
        isEmail: {
            msg: "The format of the e-mail is not correct"
        },
        validate: {
            notNull: {
                msg: "E-mail cannot be empty"
            }
        }
    },
    name: {
        type: Sequelize.STRING,
        is: /^[a-zA-Z ]+$/i,
        allowNull: false,
        validate: {
            notNull: {
                msg: "Name cannot be empty"
            }
        }
    },
    surname: {
        type: Sequelize.STRING,
        is: /^[a-zA-Z ]+$/i,
        allowNull: false,
        validate: {
            notNull: {
                msg: "Surname cannot be empty"
            }
        }
    }
})

UserModel.associate = (models) => {
    UserModel.hasMany(models.ProjectModel, {
        foreignKey: "userID"
    })
}

module.exports.UserModel = UserModel;

project.js

import Sequelize from "sequelize";
import db from "../db";

const ProjectModel = db.sequelize.define("project", {
    id: {
        type: type.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
    },
    name: {
        type: type.STRING,
        is: /^[a-zA-Z ]+$/i,
        allowNull: false,
        validate: {
            notNull: {
                msg: "Name cannot be empty"
            }
        }
    },
    body: {
        type: type.TEXT,
        allowNull: false,
        validate: {
            notNull: {
                msg: "Body cannot be empty"
            }
        }
    },
    status: {
        type: type.ENUM("active", "inactive", "declined", "completed"),
        allowNull: false,
        validate: {
            notNull: {
                msg: "Status cannot be empty"
            }
        }
    },
    userID: {
        type: type.INTEGER,
        allowNull: false,
        validate: {
            notNull: {
                msg: "userID cannot be empty"
            }
        }
    }
});

ProjectModel.associate = (models) => {
    ProjectModel.belongsTo(models.UserModel, {
        foreignKey: "userID"
    })
}

module.exports.ProjectModel = ProjectModel;

Sorry, but I don't understand anything ... :((

Edit III:

I have checked the keys of db in user.js and I've got nothing, so it's right that I've got thi error, but ... Why have db nothing?

[nodemon] starting `babel-node src/server/server.js`
db:

Body:
Your issue is that UserModel in user.js is as a function that returns a sequalize definition.

In the same file you are trying to call UserModel.hasMany on the function that returns your model object instead of on the model object itself.

You probably just want to remove the wrapping function and assign the sequalize object to UserModel directly.

const UserModel = sequelize.define("user", {
...

or move the calls on UserModel into the function.

    const model = sequelize.define("user", {
    ...
    });
    model.hasMany(ProjectModel, { foreingKey: "userID", sourceKey: "id"});
    model.belongsTo(UserModel, { foreingKey: "userID", sourceKey: "id"});
    return model;
};
module.exports.UserModel = UserModel;


Title: Data frame multiple columns splitting

Body:
I have a pandas dataframe of the following format.

0     06-10-2000 Deposit $40.00
1  09-12-2002 Withdraw $1000.00
2     27-06-2001 Deposit $47.00
3   07-12-2021 Withdraw $100.00
4    06-10-2022 Deposit $120.00
5     06-10-2000 Deposit $40.00
6    09-12-2024 Withdraw $50.00

How do I split each row in to 3 columns.
Ideal output wanted:

      Date       Status   Amount
0     06-10-2000 Deposit $40.00
1  09-12-2002 Withdraw $1000.00
2     27-06-2001 Deposit $47.00
3   07-12-2021 Withdraw $100.00
4    06-10-2022 Deposit $120.00
5     06-10-2000 Deposit $40.00
6    09-12-2024 Withdraw $50.00

Body:
You can use named groups and extract:

df[1].str.extract('(?P<Date>.*) (?P<Status>.*) (?P<Amount>.*)')

Output:

         Date    Status    Amount
0  06-10-2000   Deposit    $40.00
1  09-12-2002  Withdraw  $1000.00
2  27-06-2001   Deposit    $47.00
3  07-12-2021  Withdraw   $100.00
4  06-10-2022   Deposit   $120.00
5  06-10-2000   Deposit    $40.00
6  09-12-2024  Withdraw    $50.00


问:
Passing results of queries in promises
I am using node-postgres for a database connection. For that I have APIs like that:

```<code>app.post('/api/insert', urlEncodedParser, function(req, res) {
    // do stuff
})
</code>```

Now I need synchron steps:

Select specific id from table user

Check if id from table user already exists in table list
3a) if id in table list does not exist, then insert data in table list
3b) if id in table list exists, then update data in table list

So I have following code:

```<code>var userid = 0;
var listEntry = 0;

client
.query('SELECT "ID" FROM "User" WHERE "PW" = $1 AND "Name" = $2', [req.body.pw, req.body.name])
.then(res => userid = res.rows[0])
.catch(e => console.error(e.stack))
.query('SELECT " FROM "List" WHERE "UserID" = $1', [userid])
.then(res => listEntry = res.rows[0])
.catch(e => console.error(e.stack))
.query('INSERT INTO "List" ("UserID", "LastDate")', [userid, req.body.date])
.then(res => userid = res.rows[0])
.catch(e => console.error(e.stack))
.query('UPDATE "List" SET "LastDate" = $1', [req.body.date])
.then(res => userid = res.rows[0])
.catch(e => console.error(e.stack))
.finally(() { client.end()
});
</code>```

What do I need to change that I can have this synchron steps as listed above? Sorry, I am new to javascript and node-postgres.

答:
Whatever you return in one then ends up in the following then. For example:

client.query("SELECT...")
    .then((result) => {
        // do something with the result
        return 42;
    })
    .then((result) => console.log(result))
    .then((result) => console.log(result))
```

<p>The first log prints 42 because the previous <code>then</code> returned 42 and the second prints <code>undefined</code> because the previous <code>then</code> returned nothing = <code>undefined</code>. So you actually want something like this:</p>

<pre class="lang-js prettyprint-override"><code>client.query('SELECT "ID" FROM "User" WHERE "PW" = $1 AND "Name" = $2', [req.body.pw, req.body.name])
    .then((res) => {
        const userid = res.rows[0];
        return client.query('SELECT " FROM "List" WHERE "UserID" = $1', [userid]).then(() => {
            return client.query('INSERT INTO "List" ("UserID", "LastDate")', [userid, req.body.date]);
        });
    })
    .then(() => {
        return client.query('UPDATE "List" SET "LastDate" = $1', [req.body.date])
    })
    .catch(error => console.error(error))
    .finally(() => client.end());
</code>```

This was you don't even need the semi-global variables userid and listEntry. This is generally a good thing.

The code can be more simplified when using async/await.

If you don't want to execute the following queries because there are no rows in the first response you can do something like this:

client.query('SELECT "ID" FROM "User" WHERE "PW" = $1 AND "Name" = $2', [req.body.pw, req.body.name])
    .then((res) => {
        if (res.rows.length > 0) {
            const userid = res.rows[0];
            return client.query('SELECT " FROM "List" WHERE "UserID" = $1', [userid]).then(() => {
                return client.query('INSERT INTO "List" ("UserID", "LastDate")', [userid, req.body.date]);
            }).then(() => {
                return client.query('UPDATE "List" SET "LastDate" = $1', [req.body.date])
            })
        }
    })
    .catch(error => console.error(error))
    .finally(() => client.end());
```

Title: Passing results of queries in promises

Body:
I am using node-postgres for a database connection. For that I have APIs like that:

app.post('/api/insert', urlEncodedParser, function(req, res) {
    // do stuff
})

Now I need synchron steps:

Select specific id from table user

Check if id from table user already exists in table list
3a) if id in table list does not exist, then insert data in table list
3b) if id in table list exists, then update data in table list

So I have following code:

var userid = 0;
var listEntry = 0;

client
.query('SELECT "ID" FROM "User" WHERE "PW" = $1 AND "Name" = $2', [req.body.pw, req.body.name])
.then(res => userid = res.rows[0])
.catch(e => console.error(e.stack))
.query('SELECT " FROM "List" WHERE "UserID" = $1', [userid])
.then(res => listEntry = res.rows[0])
.catch(e => console.error(e.stack))
.query('INSERT INTO "List" ("UserID", "LastDate")', [userid, req.body.date])
.then(res => userid = res.rows[0])
.catch(e => console.error(e.stack))
.query('UPDATE "List" SET "LastDate" = $1', [req.body.date])
.then(res => userid = res.rows[0])
.catch(e => console.error(e.stack))
.finally(() { client.end()
});

What do I need to change that I can have this synchron steps as listed above? Sorry, I am new to javascript and node-postgres.

Body:
Whatever you return in one then ends up in the following then. For example:

client.query("SELECT...")
    .then((result) => {
        // do something with the result
        return 42;
    })
    .then((result) => console.log(result))
    .then((result) => console.log(result))

The first log prints 42 because the previous then returned 42 and the second prints undefined because the previous then returned nothing = undefined. So you actually want something like this:

client.query('SELECT "ID" FROM "User" WHERE "PW" = $1 AND "Name" = $2', [req.body.pw, req.body.name])
    .then((res) => {
        const userid = res.rows[0];
        return client.query('SELECT " FROM "List" WHERE "UserID" = $1', [userid]).then(() => {
            return client.query('INSERT INTO "List" ("UserID", "LastDate")', [userid, req.body.date]);
        });
    })
    .then(() => {
        return client.query('UPDATE "List" SET "LastDate" = $1', [req.body.date])
    })
    .catch(error => console.error(error))
    .finally(() => client.end());

This was you don't even need the semi-global variables userid and listEntry. This is generally a good thing.

The code can be more simplified when using async/await.

If you don't want to execute the following queries because there are no rows in the first response you can do something like this:

client.query('SELECT "ID" FROM "User" WHERE "PW" = $1 AND "Name" = $2', [req.body.pw, req.body.name])
    .then((res) => {
        if (res.rows.length > 0) {
            const userid = res.rows[0];
            return client.query('SELECT " FROM "List" WHERE "UserID" = $1', [userid]).then(() => {
                return client.query('INSERT INTO "List" ("UserID", "LastDate")', [userid, req.body.date]);
            }).then(() => {
                return client.query('UPDATE "List" SET "LastDate" = $1', [req.body.date])
            })
        }
    })
    .catch(error => console.error(error))
    .finally(() => client.end());


问:
How to make cells in UITableView not turn blue?
I am using a UITableView and the cells I am using in this view should do nothing when I click them. I can't turn off UserInteraction though because then I am not able to click on the accessory (detailDisclosureButton). So how can I make them stop turning blue and still allow them to click on the accessory?</p>

答:
Use the UITabelViewCell selectionStyle property.

```<code>myCell.selectionStyle = UITableViewCellSelectionStyleNone;
</code>```

Body:
Use the UITabelViewCell selectionStyle property.

myCell.selectionStyle = UITableViewCellSelectionStyleNone;


问:
Spring REST - Is there a way to override the character Spring uses to separate a query parameter into a list of values?
I'm writing a REST API using Spring and have certain clients to the service that cannot or will not change how they call my service.

Normally when sending a query param with a list of values you would just comma delimit the parameter and Spring will do the rest
curl http://host.com/api/endpoint?listParam=1,2,3

And the controller

@GetMapping("/api/endpoint")
public ResponseEntity endpoint(@RequestParam("listParam" List<String> listParam){
    // Here, listParam is populated with 1,2,3
}
```

<p>Unfortunately my clients are going to be passing lists with the bar <code>|</code> delimiter and it simply isn't possible to get them to change that.<br>
<strong>Example:</strong> <code>curl http://host.com/api/endpoint?listParam=1%7C2%7C3%7C</code></p>

<p>I would still like to use Spring to break these calls out into lists so I don't have to clutter my code with manual <code>String.split()</code> calls.</p>

<p><strong>What I've already tried:</strong><br>
I found the <code>@InitBinder</code> annotation and wrote the following</p>

<pre class="lang-java prettyprint-override"><code>@InitBinder
public void initBinder(WebDataBinder dataBinder){
    dataBinder.registerCustomEditor(String[].class, new StringArrayPropertyEditor("|"));
}
</code>```

However, this code doesn't seem to ever be called (watching with breakpoints) and requests using the bar as the delimiter fail with a 400 BAD REQUEST.

Any suggestions would be much appreciated, thanks!

答:
404 is coming due to URL encoding issue.

You need to encode | then it will work, but it will create another problem, params would not be split.

To work around this you need to create a custom conversion that can convert String to Collection. For the custom conversion, you can check the StringToCollectionConverter class. Once you have custom conversion then you can register that service, in any of the configuration classes add following function

  @Autowired
  void conversionService(GenericConversionService genericConversionService) {
    genericConversionService.addConverter(myStringToCollectionConvert());
  }

  @Bean
  public MyStringToCollectionConvert myStringToCollectionConvert() {
    return new MyStringToCollectionConvert();
  }

```

In this MyStringToCollectionConvert is class that will parse String and converts to a collection of Strings.

Body:
I'm writing a REST API using Spring and have certain clients to the service that cannot or will not change how they call my service.

Normally when sending a query param with a list of values you would just comma delimit the parameter and Spring will do the rest
curl http://host.com/api/endpoint?listParam=1,2,3

And the controller

@GetMapping("/api/endpoint")
public ResponseEntity endpoint(@RequestParam("listParam" List<String> listParam){
    // Here, listParam is populated with 1,2,3
}

Unfortunately my clients are going to be passing lists with the bar | delimiter and it simply isn't possible to get them to change that.

Example: curl http://host.com/api/endpoint?listParam=1%7C2%7C3%7C

I would still like to use Spring to break these calls out into lists so I don't have to clutter my code with manual String.split() calls.

What I've already tried:

I found the @InitBinder annotation and wrote the following

@InitBinder
public void initBinder(WebDataBinder dataBinder){
    dataBinder.registerCustomEditor(String[].class, new StringArrayPropertyEditor("|"));
}

However, this code doesn't seem to ever be called (watching with breakpoints) and requests using the bar as the delimiter fail with a 400 BAD REQUEST.

Any suggestions would be much appreciated, thanks!

Body:
404 is coming due to URL encoding issue.

You need to encode | then it will work, but it will create another problem, params would not be split.

To work around this you need to create a custom conversion that can convert String to Collection. For the custom conversion, you can check the StringToCollectionConverter class. Once you have custom conversion then you can register that service, in any of the configuration classes add following function

  @Autowired
  void conversionService(GenericConversionService genericConversionService) {
    genericConversionService.addConverter(myStringToCollectionConvert());
  }

  @Bean
  public MyStringToCollectionConvert myStringToCollectionConvert() {
    return new MyStringToCollectionConvert();
  }

In this MyStringToCollectionConvert is class that will parse String and converts to a collection of Strings.


问:
How to complete remove eslint in vue cli 3 generated project?
I am not interested in the stupid lint, which is not workable at all. It can do nothing but waste of my time. </p>

<p>I need a way to remove it and make sure ESLint will never appear again. What should I do? Please don't tell me to put a comment in my code to disable one warning. I need a solution to completely get rid of ESLint in vue cli 3 generated project. </p>

答:
If Vue generated a config file for your project, you can look inside the config\index.js file and change useEslint to be false, as such:
useEslint: false

Body:
I am not interested in the stupid lint, which is not workable at all. It can do nothing but waste of my time.

I need a way to remove it and make sure ESLint will never appear again. What should I do? Please don't tell me to put a comment in my code to disable one warning. I need a solution to completely get rid of ESLint in vue cli 3 generated project.


问:
Win32 API - HWND "{unused = ???} Unable to read memory" error
My project is C++ Windows Desktop Wizard AKA Win32 API project.

In function WinMain(...) I'm creating my window:

```<code>hWnd = CreateWindowEx(NULL, _T("DesktopApp"), _T("Hi, I'm window"), WS_OVERLAPPEDWINDOW,
    CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL);
</code>```

And after that for some reason my window has status "unable to read memory" (therefore I can't create GUIs without this issue). I checked even 2nd page of Google to find a resolve of this problem. Microsoft's documentation didn't help: I checked the implementation and it fits with mine. I can't fix it for a long time, mb I'm blind and I wrote smth wrong before, despite I've created 2 working projects before (comparison didn't give any results).

Here goes the whole code:

```<code>#include <windows.h>
#include <stdlib.h>
#include <string>
#include <tchar.h>
#include <shellapi.h>
#include <ctime>

HWND hWnd;
HINSTANCE hInst;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow)
{
    WNDCLASSEX wcex;

    ZeroMemory(&wcex, sizeof(wcex));
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = szWindowClass;
    wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);

    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Windows Desktop Guided Tour"),
            NULL);
        return 1;
    }

    hInst = hInstance;

    hWnd = CreateWindowEx(NULL, _T("DesktopApp"), _T("Hi, I'm window"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL);
    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Windows Desktop Guided Tour"),
            NULL);
        return 1;
    }

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int)msg.wParam;
}
</code>```

>how it looks in debugger<

Thanks in advance for help.

答:
When STRICT Type Checking is enabled during compiling, HWND is a typedef for HWND__*, where HWND__ is a struct with an unused data member (only because a struct can't legally be empty in C, but it can in C++), eg:

winnt.h:

#ifdef STRICT
typedef void *HANDLE;
#if 0 && (_MSC_VER > 1000)
#define DECLARE_HANDLE(name) struct name##__; typedef struct name##__ *name
#else
#define DECLARE_HANDLE(name) struct name##__{int unused;}; typedef struct name##__ *name
#endif
#else
typedef PVOID HANDLE;
#define DECLARE_HANDLE(name) typedef HANDLE name
#endif
```

<p>windef:</p>

<pre class="lang-c prettyprint-override"><code>DECLARE_HANDLE            (HWND);
</code>```

So, when STRICT is defined, HWND is an alias for struct HWND__*, otherwise it is an alias for PVOID (void*).  Same with MANY other handle types (HHOOK, HEVENT, HGDIOBJ, HBITMAP, etc).

For your debugger to be showing you the unused member when viewing an HWND, that means you are compiling with STRICT defined (which is a good thing, you should be).  The debugger sees a pointer to a type, and tries to display the data that type contains.

However, an HWND is not REALLY a pointer to a struct HWND__ in memory.  It is actually just an opaque value provided by the kernel.  What an HWND actually refers to is private to the kernel, a user-mode debugger has no way of knowing what that really is.

STRICT handling is merely provided for compile-time type safety, so that user code can't accidentally pass other handle types where an HWND is expected, and vice versa.

In your case, your HWND has a value of 0x00170344, which means CreateWindowEx() is not failing, the HWND itself is valid.  But 0x00170344 is not a valid memory address in your app's address space, so when the debugger tries to access the unused member at that address, it fails with "unable to read memory". The unused member will NEVER be valid in a user-mode debugger (that is why it is "unused").  The only thing that is important is whether the value of the HWND itself is 0 or not.

Body:
My project is C++ Windows Desktop Wizard AKA Win32 API project.

In function WinMain(...) I'm creating my window:

hWnd = CreateWindowEx(NULL, _T("DesktopApp"), _T("Hi, I'm window"), WS_OVERLAPPEDWINDOW,
    CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL);

And after that for some reason my window has status "unable to read memory" (therefore I can't create GUIs without this issue). I checked even 2nd page of Google to find a resolve of this problem. Microsoft's documentation didn't help: I checked the implementation and it fits with mine. I can't fix it for a long time, mb I'm blind and I wrote smth wrong before, despite I've created 2 working projects before (comparison didn't give any results).

Here goes the whole code:

#include <windows.h>
#include <stdlib.h>
#include <string>
#include <tchar.h>
#include <shellapi.h>
#include <ctime>

HWND hWnd;
HINSTANCE hInst;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow)
{
    WNDCLASSEX wcex;

    ZeroMemory(&wcex, sizeof(wcex));
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = szWindowClass;
    wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);

    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Windows Desktop Guided Tour"),
            NULL);
        return 1;
    }

    hInst = hInstance;

    hWnd = CreateWindowEx(NULL, _T("DesktopApp"), _T("Hi, I'm window"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL);
    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Windows Desktop Guided Tour"),
            NULL);
        return 1;
    }

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int)msg.wParam;
}

>how it looks in debugger<

Thanks in advance for help.

Body:
When STRICT Type Checking is enabled during compiling, HWND is a typedef for HWND__*, where HWND__ is a struct with an unused data member (only because a struct can't legally be empty in C, but it can in C++), eg:

winnt.h:

#ifdef STRICT
typedef void *HANDLE;
#if 0 && (_MSC_VER > 1000)
#define DECLARE_HANDLE(name) struct name##__; typedef struct name##__ *name
#else
#define DECLARE_HANDLE(name) struct name##__{int unused;}; typedef struct name##__ *name
#endif
#else
typedef PVOID HANDLE;
#define DECLARE_HANDLE(name) typedef HANDLE name
#endif

windef:

DECLARE_HANDLE            (HWND);

So, when STRICT is defined, HWND is an alias for struct HWND__*, otherwise it is an alias for PVOID (void*).  Same with MANY other handle types (HHOOK, HEVENT, HGDIOBJ, HBITMAP, etc).

For your debugger to be showing you the unused member when viewing an HWND, that means you are compiling with STRICT defined (which is a good thing, you should be).  The debugger sees a pointer to a type, and tries to display the data that type contains.

However, an HWND is not REALLY a pointer to a struct HWND__ in memory.  It is actually just an opaque value provided by the kernel.  What an HWND actually refers to is private to the kernel, a user-mode debugger has no way of knowing what that really is.

STRICT handling is merely provided for compile-time type safety, so that user code can't accidentally pass other handle types where an HWND is expected, and vice versa.

In your case, your HWND has a value of 0x00170344, which means CreateWindowEx() is not failing, the HWND itself is valid.  But 0x00170344 is not a valid memory address in your app's address space, so when the debugger tries to access the unused member at that address, it fails with "unable to read memory". The unused member will NEVER be valid in a user-mode debugger (that is why it is "unused").  The only thing that is important is whether the value of the HWND itself is 0 or not.


问:
MongoDB findOne funtion returns null when comparing with id
I am using the following code to get the details of a user when I pass their id as a parameter:

```<code>   server.get("/users/:id", (req, res) => {
        const itemId = req.params.id;

        dbCollection.findOne({ _id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            res.json(result);
        });
    });
</code>```

However, this doesn't seem to work, as whenever I run the code, I get returned with a null value.
My question is not the same as many previously asked questions because I have ObjectId('randomId') as my id, and not a string. How can I fix my code?

答:
As others already said, MongoDB expects _id to be an ObjectID. But if you are searching for ONE item, instead of using findOne use findById, which accepts id as a string.

const { Model } = require('./models'); // Model is your Mongoose Schema

server.get("/users/:id", async (req, res) => {
   const { id } = req.params;

   // This is the same as Model.findOne({ _id: new ObjectId(id) });
   const item = await Model.findById(id);

   return res.json(item);
});
```

Body:
I am using the following code to get the details of a user when I pass their id as a parameter:

   server.get("/users/:id", (req, res) => {
        const itemId = req.params.id;

        dbCollection.findOne({ _id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            res.json(result);
        });
    });

However, this doesn't seem to work, as whenever I run the code, I get returned with a null value.
My question is not the same as many previously asked questions because I have ObjectId('randomId') as my id, and not a string. How can I fix my code?


问:
Expected to decode Dictionary<String, Any> but found an array instead JSON SwiftUI
I'm getting an error while trying to decode JSON with SwiftUI.

typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "platforms", intValue: nil)], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))

I believe that it has to do with finding an empty array with platforms but I've tried to figure out how to call that information and then show it in the content view.

I think that it’s because I'm using fields in the getGames webservice, I may be messing up how I'm pulling the API. I also can't figure out where to print the JSON so I can see what is actually being pulled.

The JSON I'm trying to decode is:

```<code>{
    "id": 22636,
    "name": "Call of Duty: Black Ops - Annihilation",
    "platforms": [
      {
        "id": 6,
        "name": "PC (Microsoft Windows)"
      },
      {
        "id": 9,
        "name": "PlayStation 3"
      },
      {
        "id": 12,
        "name": "Xbox 360"
      }
    ]
}
</code>```

My Game Struct Looks like:

```<code>Game.swift
struct Game: Codable, Identifiable {
    let id: Int
    let name: String
    let summary: String?
    let platforms: Platforms
}

struct Platforms: Codable, Identifiable {
    let id: Int
    let name: String

}
</code>```

My Webservice is using fields to get only specific parts of the API:

```<code>GameService.swift
public class GameService: ObservableObject {

    @Published var games = [Game]()

    init(){
        getGames()
    }

    func getGames() {

        let parameters = "fields name, summary, platforms.name; where platforms = (48,6,49); limit 10;"
        let postData = parameters.data(using: .utf8)

        let url = URL(string: "https://api-v3.igdb.com/games/")!

        var request = URLRequest(url: url)
        request.addValue("HIDDEN", forHTTPHeaderField: "user-key")
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = postData

        URLSession.shared.dataTask(with: request) { data, response, error in
            do {
                if let d = data {
// DO I NEED TO ADJUST THE JSONDecoder to Array<Game>.self?
                    let decodedLists = try JSONDecoder().decode([Game].self, from: d)
                    DispatchQueue.main.async {
                        self.games = decodedLists
                    }
                } else {
                    print("No data in response: \(error?.localizedDescription ?? "Unknown Error").")
                }
            } catch {
                print("\(error)")
            }
        }.resume()
    }
}
</code>```

答:
You’re receiving in your JSON an array of Platforms, so you have to update your Game struct to be able to parse it:

```<code>struct Game: Codable, Identifiable {
    let id: Int
    let name: String
    let summary: String?
    let platforms: [Platforms]
}
</code>```

And to use it, for example:

```<code>List {
    ForEach(game.platforms) { platform in
        Text(platform.name)
    }
}
</code>```

Body:
I'm getting an error while trying to decode JSON with SwiftUI.

typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "platforms", intValue: nil)], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))

I believe that it has to do with finding an empty array with platforms but I've tried to figure out how to call that information and then show it in the content view.

I think that it’s because I'm using fields in the getGames webservice, I may be messing up how I'm pulling the API. I also can't figure out where to print the JSON so I can see what is actually being pulled.

The JSON I'm trying to decode is:

{
    "id": 22636,
    "name": "Call of Duty: Black Ops - Annihilation",
    "platforms": [
      {
        "id": 6,
        "name": "PC (Microsoft Windows)"
      },
      {
        "id": 9,
        "name": "PlayStation 3"
      },
      {
        "id": 12,
        "name": "Xbox 360"
      }
    ]
}

My Game Struct Looks like:

Game.swift
struct Game: Codable, Identifiable {
    let id: Int
    let name: String
    let summary: String?
    let platforms: Platforms
}

struct Platforms: Codable, Identifiable {
    let id: Int
    let name: String

}

My Webservice is using fields to get only specific parts of the API:

GameService.swift
public class GameService: ObservableObject {

    @Published var games = [Game]()

    init(){
        getGames()
    }

    func getGames() {

        let parameters = "fields name, summary, platforms.name; where platforms = (48,6,49); limit 10;"
        let postData = parameters.data(using: .utf8)

        let url = URL(string: "https://api-v3.igdb.com/games/")!

        var request = URLRequest(url: url)
        request.addValue("HIDDEN", forHTTPHeaderField: "user-key")
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = postData

        URLSession.shared.dataTask(with: request) { data, response, error in
            do {
                if let d = data {
// DO I NEED TO ADJUST THE JSONDecoder to Array<Game>.self?
                    let decodedLists = try JSONDecoder().decode([Game].self, from: d)
                    DispatchQueue.main.async {
                        self.games = decodedLists
                    }
                } else {
                    print("No data in response: \(error?.localizedDescription ?? "Unknown Error").")
                }
            } catch {
                print("\(error)")
            }
        }.resume()
    }
}

Body:
You’re receiving in your JSON an array of Platforms, so you have to update your Game struct to be able to parse it:

struct Game: Codable, Identifiable {
    let id: Int
    let name: String
    let summary: String?
    let platforms: [Platforms]
}

And to use it, for example:

List {
    ForEach(game.platforms) { platform in
        Text(platform.name)
    }
}


问:
Invalid command name in Tcl when using format
I'm running the following commands

```<code>set full_pin_name [format "%s %s" $top_cell $encoded_name]
puts "full_pin_name is $full_pin_name"
</code>```

and I get the following error:

```<code>full_pin_name is invalid command name "A" B
</code>```

when top_cell equals A and encoded_name equals B.

Why is this happening?

答:
I suspect the problem is with your $top_cell variable, which has the value invalid command name "A". To check, try the following line before your format line:

```<code>puts ">$top_cell<"
</code>```

If indeed, $top_cell value has a problem, you can then trace back to the last set command. Let us know if it fixes your problem, or we might try some other approaches.

Body:
I'm running the following commands

set full_pin_name [format "%s %s" $top_cell $encoded_name]
puts "full_pin_name is $full_pin_name"

and I get the following error:

full_pin_name is invalid command name "A" B

when top_cell equals A and encoded_name equals B.

Why is this happening?

Body:
I suspect the problem is with your $top_cell variable, which has the value invalid command name "A". To check, try the following line before your format line:

puts ">$top_cell<"

If indeed, $top_cell value has a problem, you can then trace back to the last set command. Let us know if it fixes your problem, or we might try some other approaches.


问:
pydantic BaseModel not found in Fastapi
I have python3 3.6.9 on Kubuntu 18.04. I have installed fastapi using pip3 install fastapi. I'm trying to test drive the framework through its official documentation and I'm in the relational database section of its guide.

In schemas.py:

```<code>from typing import List

from pydantic import BaseModel

class VerseBase(BaseModel):
    AyahText: str
    NormalText: str

class Verse(VerseBase):
    id: int

    class Config:
        orm_mode = True
</code>```

VS code highlights an error in from pydantic import BaseModel and it tells that: No name 'BaseModel' in module 'pydantic'. Additionally, when I try to run uvicorn main:app reload  I have gotten the following error:

```<code>File "./main.py", line 6, in <module>
   from . import crud, models, schemas
ImportError: attempted relative import with no known parent package
</code>```

I have tried to renstall pydantic using pip3 but it tells me that:

```<code>Requirement already satisfied: dataclasses>=0.6; python_version < "3.7" in ./.local/lib/python3.6/site-packages (from pydantic) (0.7)
</code>```

答:
The problem of highlighting in VS code may be a problem due to the fact that you did not open the folder. It's quite annoying as it happens often to me as well (and I have basically your same config).

Regarding the second problem you mention, it is probably due to the fact that the folder in which the script lays, does not have a __init__.py file. If you add it, it should work since python will interpret the folder as a module.

As an alternative, you could try to import with the full path from the top folder (e.g. from app.module.main import app).

For more information about modules see the following links:

Python 3.8 Modules

Real Python

Title: pydantic BaseModel not found in Fastapi

Body:
I have python3 3.6.9 on Kubuntu 18.04. I have installed fastapi using pip3 install fastapi. I'm trying to test drive the framework through its official documentation and I'm in the relational database section of its guide.

In schemas.py:

from typing import List

from pydantic import BaseModel

class VerseBase(BaseModel):
    AyahText: str
    NormalText: str

class Verse(VerseBase):
    id: int

    class Config:
        orm_mode = True

VS code highlights an error in from pydantic import BaseModel and it tells that: No name 'BaseModel' in module 'pydantic'. Additionally, when I try to run uvicorn main:app reload  I have gotten the following error:

File "./main.py", line 6, in <module>
   from . import crud, models, schemas
ImportError: attempted relative import with no known parent package

I have tried to renstall pydantic using pip3 but it tells me that:

Requirement already satisfied: dataclasses>=0.6; python_version < "3.7" in ./.local/lib/python3.6/site-packages (from pydantic) (0.7)


问:
Scrape with bs4 two values for one variable, how can i use just one?
Im trying to get the price of different amazon pages. The problem is that when the product is "amazon choice" the price is in different "div", so... how can i check if the price is in one tag or another and then, save that value as price. Then give to that value price a int format, ready to be save to one cell on xlsx file. I have this code without error, but i cant delete the option None of the print result. If i try replace gimme error, if i use get_text gimme error. So... i dont know what else to do. Im in blank.</p>
```<code>URL = 'https://www.amazon.com.mx/dp/B07MJP47M5'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}

page = requests.get(URL, headers=headers)
scrape = soup(page.content, 'html.parser')

price_1 = scrape.find(id='priceblock_ourprice')
if price_1 != None:
    price_1 = scrape.find(id='priceblock_ourprice').get_text()

price_2 = scrape.find(id='priceblock_saleprice')
if price_2 != None:
    price_2 = scrape.find(id='priceblock_saleprice').get_text()

price = (price_1, price_2)
print(price)
</code>```

答:
I already solver this problem.</p>
```<code>URL = 'https://www.amazon.com.mx/dp/B07T514NTL'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}

page = requests.get(URL, headers=headers)
scrape = soup(page.content, 'html.parser')

# se extrae el precio y se le da formato, se quita la coma, y las decimales y el simbolo

price_1 = scrape.find(id='priceblock_ourprice')
if price_1 is None:
    price_1 = scrape.find(id='priceblock_saleprice')

price_4 = price_1.get_text()

verted_price = price_4[1:10]
onverted_price = verted_price.replace(',','')
sep = '.'
converted_price = onverted_price.split(sep, 1)[0]

print(converted_price)
</code>```

Body:
Im trying to get the price of different amazon pages. The problem is that when the product is "amazon choice" the price is in different "div", so... how can i check if the price is in one tag or another and then, save that value as price. Then give to that value price a int format, ready to be save to one cell on xlsx file. I have this code without error, but i cant delete the option None of the print result. If i try replace gimme error, if i use get_text gimme error. So... i dont know what else to do. Im in blank.

URL = 'https://www.amazon.com.mx/dp/B07MJP47M5'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}

page = requests.get(URL, headers=headers)
scrape = soup(page.content, 'html.parser')

price_1 = scrape.find(id='priceblock_ourprice')
if price_1 != None:
    price_1 = scrape.find(id='priceblock_ourprice').get_text()

price_2 = scrape.find(id='priceblock_saleprice')
if price_2 != None:
    price_2 = scrape.find(id='priceblock_saleprice').get_text()

price = (price_1, price_2)
print(price)

Body:
I already solver this problem.

URL = 'https://www.amazon.com.mx/dp/B07T514NTL'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}

page = requests.get(URL, headers=headers)
scrape = soup(page.content, 'html.parser')

# se extrae el precio y se le da formato, se quita la coma, y las decimales y el simbolo

price_1 = scrape.find(id='priceblock_ourprice')
if price_1 is None:
    price_1 = scrape.find(id='priceblock_saleprice')

price_4 = price_1.get_text()

verted_price = price_4[1:10]
onverted_price = verted_price.replace(',','')
sep = '.'
converted_price = onverted_price.split(sep, 1)[0]

print(converted_price)


问:
Renaming multiple columns using their index
How can i rename multiple columns of a dataframe using their index?
For example i want to rename the columns at positions 5,6,7,8 to 'five','six','seven','eight' respectively. I don't want to enter the keys in the dictionary individually.</p>

答:
If you don't want to use rename with a dict, as you mentioned, you could also try renaming the columns this way:

column_names = list(df.columns)
column_names[4:8] = ['five', 'six', 'seven', 'eight']
df.columns = column_names
```

<p>As has already been mentioned though, you don't have to rename one column at a time with the <code>dict</code>. You can do them all at once:</p>

<pre class="lang-py prettyprint-override"><code>my_dict = {5: 'five', 6: 'six', 7: 'seven'} # etc.
df.rename(columns = my_dict, inplace = True)
</code>```

Body:
If you don't want to use rename with a dict, as you mentioned, you could also try renaming the columns this way:

column_names = list(df.columns)
column_names[4:8] = ['five', 'six', 'seven', 'eight']
df.columns = column_names

As has already been mentioned though, you don't have to rename one column at a time with the dict. You can do them all at once:

my_dict = {5: 'five', 6: 'six', 7: 'seven'} # etc.
df.rename(columns = my_dict, inplace = True)


问:
Bash doesn't create all files and directories with loop
I'm trying to create a directory with list of directories with list of files.
Could you explain me, why this script doesn't work properly?

createapp() {
    local folders=('graphql' 'migrations' 'models' 'tests')
    local files=('__init__.py' 'admin.py' 'apps.py' 'views.py')

    cd backend/apps
    mkdir $COMMAND2
    cd $COMMAND2

    for folder in $folders
        do mkdir $folder && cd $folder
        for file in $files
            do touch $file && cd ..
        done
    done
}
```

It creates a graphql directory, and an __init__.py file in it, but that's all.

答:
If you want to get fancy, you can do all of this with zero loops and a combination of bash brace and array expansions:

```<code>#!/bin/bash

createapp() {
    local folders=('graphql' 'migrations' 'models' 'tests')
    local files=('__init__.py' 'admin.py' 'apps.py' 'views.py')

    IFS=,
    eval mkdir -p "{${folders[*]}}"
    eval touch "{${folders[*]}}/{${files[*]}}"
}
</code>```

Note that the use of eval can be dangerous, but it's pretty limited in this implementation as the two arrays are local and not using user-defined input.  If this was zsh, you could embed brace and array expansion without the need for eval

Body:
I'm trying to create a directory with list of directories with list of files.
Could you explain me, why this script doesn't work properly?

createapp() {
    local folders=('graphql' 'migrations' 'models' 'tests')
    local files=('__init__.py' 'admin.py' 'apps.py' 'views.py')

    cd backend/apps
    mkdir $COMMAND2
    cd $COMMAND2

    for folder in $folders
        do mkdir $folder && cd $folder
        for file in $files
            do touch $file && cd ..
        done
    done
}

It creates a graphql directory, and an __init__.py file in it, but that's all.

Body:
If you want to get fancy, you can do all of this with zero loops and a combination of bash brace and array expansions:

#!/bin/bash

createapp() {
    local folders=('graphql' 'migrations' 'models' 'tests')
    local files=('__init__.py' 'admin.py' 'apps.py' 'views.py')

    IFS=,
    eval mkdir -p "{${folders[*]}}"
    eval touch "{${folders[*]}}/{${files[*]}}"
}

Note that the use of eval can be dangerous, but it's pretty limited in this implementation as the two arrays are local and not using user-defined input.  If this was zsh, you could embed brace and array expansion without the need for eval


问:
How to center a string using String.format?
```<code>public class Divers {
  public static void main(String args[]){

     String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
     System.out.format(format, "FirstName", "Init.", "LastName");
     System.out.format(format, "Real", "", "Gagnon");
     System.out.format(format, "John", "D", "Doe");

     String ex[] = { "John", "F.", "Kennedy" };

     System.out.format(String.format(format, (Object[])ex));
  }
}
</code>```

output:

```<code>|FirstName |Init.     |LastName            |
|Real      |          |Gagnon              |
|John      |D         |Doe                 |
|John      |F.        |Kennedy             |
</code>```

I want the output to be centered. If I do not use '-' flag the output will be aligned to the right.

I did not find a flag to center text in the API.

This article has some information about format, but nothing on centre justify.

答:
```<code>int spaceSize = n - s.length();
int prefixSize = spaceSize / 2;
int suffixSize = (spaceSize + 1) / 2
</code>```

"one-liner" since Java 11

```<code>return n > s.length()
     ? " ".repeat(prefixSize) + s + " ".repeat(suffixSize)
     : s;
</code>```

Inlining the above vars into one return we can get:

return n > s.length()
? " ".repeat((n - s.length()) / 2) + s + " ".repeat((n - s.length() + 1) / 2**)**
: s;

since Java 8

Java 8 has no " ".repeat(10) method. So

just replace the " ".repeat(10) with Java 8 analog. See https://stackoverflow.com/a/57514604/601844, and

use the same (as Java 11 ☝) alg:

```<code>  int spaceSize = n - s.length();
  int prefixSize = spaceSize / 2;
  int suffixSize = (spaceSize + 1) / 2
  return n > s.length()
       ? space(prefixSize) + s + space(suffixSize)
       : s;

private String space(int spaceSize) {
  return generate(() -> " ").limit(spaceSize).collect(joining());
}
</code>```

Body:
public class Divers {
  public static void main(String args[]){

     String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
     System.out.format(format, "FirstName", "Init.", "LastName");
     System.out.format(format, "Real", "", "Gagnon");
     System.out.format(format, "John", "D", "Doe");

     String ex[] = { "John", "F.", "Kennedy" };

     System.out.format(String.format(format, (Object[])ex));
  }
}

output:

|FirstName |Init.     |LastName            |
|Real      |          |Gagnon              |
|John      |D         |Doe                 |
|John      |F.        |Kennedy             |

I want the output to be centered. If I do not use '-' flag the output will be aligned to the right.

I did not find a flag to center text in the API.

This article has some information about format, but nothing on centre justify.

Body:
int spaceSize = n - s.length();
int prefixSize = spaceSize / 2;
int suffixSize = (spaceSize + 1) / 2

"one-liner" since Java 11

return n > s.length()
     ? " ".repeat(prefixSize) + s + " ".repeat(suffixSize)
     : s;

Inlining the above vars into one return we can get:

return n > s.length()
? " ".repeat((n - s.length()) / 2) + s + " ".repeat((n - s.length() + 1) / 2**)**
: s;

since Java 8

Java 8 has no " ".repeat(10) method. So

just replace the " ".repeat(10) with Java 8 analog. See https://stackoverflow.com/a/57514604/601844, and

use the same (as Java 11 ☝) alg:

  int spaceSize = n - s.length();
  int prefixSize = spaceSize / 2;
  int suffixSize = (spaceSize + 1) / 2
  return n > s.length()
       ? space(prefixSize) + s + space(suffixSize)
       : s;

private String space(int spaceSize) {
  return generate(() -> " ").limit(spaceSize).collect(joining());
}


问:
The webpage cannot be found - HTTP 404 JSP page
Experts,

My dynamic web project having 3 JSP page and 3 servlets .. and everthing was working fine till date.

when i executed the same project today, it was showing this below message.

The webpage cannot be found - HTTP 404

I deleted the whole project after trying multiple checks... now in web.xml if i remove the servlets section, its displaying the jsp content. but if i add the servlet back its throwing same page cannot be found :(

no error in project and i dont see any logs in eclipse... can someone please tel me why this is happening?
Appreciate your input. Thanks

答:
Below are a few general suggestions on debugging web apps:

3 and 4 would be the first checks for 404.

Try to start the web app in the debug mode, and place the break point in the servlet method: any hit? (or just put a System.out.println in the Servlet);

Check the structure of the dynamic web project in Eclipse: are the compiled java classes of the servlets in there?

Check the context path (url) of the dynamic web project in eclipse project config: not accidentally changed?

Check the log files of the tomcat (access logs and catalina logs) your dynamic web project is associated with.