问:
How to make spring boot, spatial hibernate and postgis work?
I can't start my spring boot(2.6.3) project with hibernate-spatial in create mode.
It tells me that type "geometry does not exist".
The geometry type comes from the hibernate-spatial library.

However, I applied everything necessary:

add hibernate-spatial dependency (my version 5.6.3.Final)

use the org.hibernate.spatial.dialect.postgis.PostgisDialect dialect
Moreover this class is deprecated and the documentation corresponding to the same version, it still indicates to use it, I do not understand anything (https://docs.jboss.org/hibernate/orm/5.6/userguide /html_single/Hibernate_User_Guide.html#spatial)

Use Geometry type from geolatte group or jts group
Despite that I have an error where it cannot create the table because the type "geometry does not exist".

Here are my maven dependencies:

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-spatial</artifactId>
        <version>5.6.3.Final</version>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.3.1</version>
    </dependency>
    <!--<dependency>
        <groupId>org.locationtech.jts</groupId>
        <artifactId>jts-core</artifactId>
        <version>1.18.2</version>
    </dependency>-->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

My properties :

```<code>spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/postgres?currentSchema=hibernatespatial
    username: postgres
    password:
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.spatial.dialect.postgis.PostgisDialect
    open-in-view: false
    database-platform: org.hibernate.spatial.dialect.postgis.PostgisDialect
</code>```

My entity class :

```<code>package org.test.hibernate.spatial;

import org.geolatte.geom.Geometry;

import javax.persistence.*;

@Entity
@Table
public class Person {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    private String lastname;

    private String age;

    private Geometry geom;

    public Geometry getGeom() {
        return geom;
    }

    public void setGeom(Geometry geom) {
        this.geom = geom;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
</code>```

My repository class :

```<code>package org.test.hibernate.spatial;

import org.springframework.data.jpa.repository.JpaRepository;

public interface PersonRepository extends JpaRepository<Person, Long> {

}
</code>```

My boot class :

```<code>package org.test.hibernate.spatial;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableJpaRepositories
@EnableTransactionManagement
public class TestHibernateSpatialApplication  implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(TestHibernateSpatialApplication.class, args);
    }

    public void run(String... args) throws Exception {

    }
}

</code>```

My postgreSQL database is 14 version.
Somebody have any idea what is wrong ?

答:
PostGIS is a Postgres extension, which needs to be enabled for each database:

Once PostGIS is installed, it needs to be enabled (Section 3.3, “Creating spatial databases”) or upgraded (Section 3.4, “Upgrading spatial databases”) in each individual database you want to use it in.

[...]

Run the following SQL snippet in the database you want to enable spatially:

```<code>CREATE EXTENSION IF NOT EXISTS plpgsql;
CREATE EXTENSION postgis;
</code>```

Also be aware that the extension is by default installed to the default schema (e.g. public). So when using the currentSchema option, be sure to not accidentally exclude the schema postgis was installed into. To prevent this, one could either add the postgis schema to the currentSchema (e.g. jdbc:postgresql://localhost:5432/tst?currentSchema=app1,public), or move postgis to the preferred schema.

Body:
I can't start my spring boot(2.6.3) project with hibernate-spatial in create mode.
It tells me that type "geometry does not exist".
The geometry type comes from the hibernate-spatial library.

However, I applied everything necessary:

add hibernate-spatial dependency (my version 5.6.3.Final)

use the org.hibernate.spatial.dialect.postgis.PostgisDialect dialect
Moreover this class is deprecated and the documentation corresponding to the same version, it still indicates to use it, I do not understand anything (https://docs.jboss.org/hibernate/orm/5.6/userguide /html_single/Hibernate_User_Guide.html#spatial)

Use Geometry type from geolatte group or jts group
Despite that I have an error where it cannot create the table because the type "geometry does not exist".

Here are my maven dependencies:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-spatial</artifactId>
        <version>5.6.3.Final</version>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

My properties :

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/postgres?currentSchema=hibernatespatial
    username: postgres
    password:
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.spatial.dialect.postgis.PostgisDialect
    open-in-view: false
    database-platform: org.hibernate.spatial.dialect.postgis.PostgisDialect

My entity class :

package org.test.hibernate.spatial;

import org.geolatte.geom.Geometry;

import javax.persistence.*;

@Entity
@Table
public class Person {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    private String lastname;

    private String age;

    private Geometry geom;

    public Geometry getGeom() {
        return geom;
    }

    public void setGeom(Geometry geom) {
        this.geom = geom;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

My repository class :

package org.test.hibernate.spatial;

import org.springframework.data.jpa.repository.JpaRepository;

public interface PersonRepository extends JpaRepository<Person, Long> {

}

My boot class :

package org.test.hibernate.spatial;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableJpaRepositories
@EnableTransactionManagement
public class TestHibernateSpatialApplication  implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(TestHibernateSpatialApplication.class, args);
    }

    public void run(String... args) throws Exception {

    }
}

My postgreSQL database is 14 version.
Somebody have any idea what is wrong ?

Body:
PostGIS is a Postgres extension, which needs to be enabled for each database:

Once PostGIS is installed, it needs to be enabled (Section 3.3, “Creating spatial databases”) or upgraded (Section 3.4, “Upgrading spatial databases”) in each individual database you want to use it in.

[...]

Run the following SQL snippet in the database you want to enable spatially:

CREATE EXTENSION IF NOT EXISTS plpgsql;
CREATE EXTENSION postgis;

Also be aware that the extension is by default installed to the default schema (e.g. public). So when using the currentSchema option, be sure to not accidentally exclude the schema postgis was installed into. To prevent this, one could either add the postgis schema to the currentSchema (e.g. jdbc:postgresql://localhost:5432/tst?currentSchema=app1,public), or move postgis to the preferred schema.


来源: stackexchange

问:
How to determine the runtime for the two reverse string methods in O() notaion?
I have two queries to reverse a string. Need to compare them:

```<code>public string ReverseD(string text)
{
    return new string(text.ToCharArray().Reverse().ToArray());
}

public string ReverseB(string text)
{
    char[] charArray = text.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}
</code>```

How can I determine the run time for these two algorithms in O() notation? Need to compare.

答:
Both are O(n) - they both go through the full array, which is O(n).

The first algorithm has worse constant factor though since effectively you are "buffering" the full array and then emit it in reverse order (unless Enumerable.Reverse() is optimized for arrays under the hood, don't have Reflector handy right now). Since you are buffering the full array, then emit a new array in reverse order you could say that effort is 2*N, so the constant factor c = 2.

The second algorithm will use array indexes so you are performing n/2 element swaps within the same array - still O(n) but a constant factor c = 0.5.

ContentLicense: CC BY-SA 3.0

Body:
I have two queries to reverse a string. Need to compare them:

public string ReverseD(string text)
{
    return new string(text.ToCharArray().Reverse().ToArray());
}

public string ReverseB(string text)
{
    char[] charArray = text.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}

How can I determine the run time for these two algorithms in O() notation? Need to compare.


问:
Transpose a tibble
I have this tibble:

```<code>tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)
</code>```

I want to transpose it into this tibble:

```<code>tibble(Cor = c("a,b","b,c"),
       Linear = c("x1","x3"),
       Rank = c("x2","x4")
)
</code>```

Is there a tidyverse simple command to do so?

答:
We can do it in two steps with tidyr's pivot_longer and pivot_wider:

```<code>df %>%
  pivot_longer(-Cor) %>%
  pivot_wider(names_from = Cor, values_from = value)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Transpose a tibble

Body:
I have this tibble:

tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)

I want to transpose it into this tibble:

tibble(Cor = c("a,b","b,c"),
       Linear = c("x1","x3"),
       Rank = c("x2","x4")
)

Is there a tidyverse simple command to do so?

Body:
We can do it in two steps with tidyr's pivot_longer and pivot_wider:

df %>%
  pivot_longer(-Cor) %>%
  pivot_wider(names_from = Cor, values_from = value)


问:
Netty HTTP/3 codec dependency giving an error in Gradle
I'm currently working on implementing HTTP3 server using the Gradle version 7.3 on a Ubuntu 20.04 VM. But QUIC codec (0.0.20.Final) and HTTP/3 codec (0.0.11.Final) dependencies produce the following error.

```<code>   Could not find netty-incubator-codec-native-quic-0.0.25.Final-${os.detected.name}-${os.detected.arch}.jar (io.netty.incubator:netty-incubator-codec-native-quic:0.0.25.Final).

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html
</code>```

Following are the dependencies I used

```<code>implementation 'io.netty.incubator:netty-incubator-codec-quic:0.0.20.Final:linux-x86_64'
implementation 'io.netty.incubator:netty-incubator-codec-http3:0.0.11.Final'
</code>```

答:
As a temporary solution I downloaded the jar of the dependency from here and referenced it in the build.gradle file.</p>
```<code>implementation ("io.netty.incubator:netty-incubator-codec-quic:0.0.20.Final:linux-x86_64")
implementation (files("libs/netty-incubator-codec-http3-0.0.11.Final.jar"))
</code>```

Body:
I'm currently working on implementing HTTP3 server using the Gradle version 7.3 on a Ubuntu 20.04 VM. But QUIC codec (0.0.20.Final) and HTTP/3 codec (0.0.11.Final) dependencies produce the following error.

   Could not find netty-incubator-codec-native-quic-0.0.25.Final-${os.detected.name}-${os.detected.arch}.jar (io.netty.incubator:netty-incubator-codec-native-quic:0.0.25.Final).

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

Following are the dependencies I used

implementation 'io.netty.incubator:netty-incubator-codec-quic:0.0.20.Final:linux-x86_64'
implementation 'io.netty.incubator:netty-incubator-codec-http3:0.0.11.Final'

Body:
As a temporary solution I downloaded the jar of the dependency from here and referenced it in the build.gradle file.

implementation ("io.netty.incubator:netty-incubator-codec-quic:0.0.20.Final:linux-x86_64")
implementation (files("libs/netty-incubator-codec-http3-0.0.11.Final.jar"))


问:
Using e.printStackTrace() in Java
This is probably a newbie question, but hope you can help me. :) I have something like this:

```<code>try
{
//try to do something there
}
catch (IOException e)
{
//handle the exception
e.printStackTrace();
}
</code>```

I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line.  When I press Alt+Enter, it says Throwable.printStackTrace() should be removed.  What does this mean?  Could anyone give more insight as what this may mean? Or can I ignore this?

Thanks!

答: It's probably because printStackTrace() doesn't really handle the error as much as it just dumps the stack in the console. It acts as a placeholder until you replace it with proper error handling (if it is needed at all) and replace the output with a logger of some sort.

Title: Using e.printStackTrace() in Java

Body:
This is probably a newbie question, but hope you can help me. :) I have something like this:

try
{
//try to do something there
}
catch (IOException e)
{
//handle the exception
e.printStackTrace();
}

I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line.  When I press Alt+Enter, it says Throwable.printStackTrace() should be removed.  What does this mean?  Could anyone give more insight as what this may mean? Or can I ignore this?

Thanks!


问:
Python(3) - store one specific link of output from soup.find_all in variable
I am working on a web scrapping function.
I want to find the latest download link ending with ".img.html" from:

"https://dl.twrp.me/gauguin/"

and store this link in a variable, not just print it.

My code so far:

```<code>from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://dl.twrp.me/gauguin/"

html_doc = urlopen(url)
# defining html link (twrp...)

soup = BeautifulSoup(html_doc, "html.parser")

for link in soup.find_all('a'):
    links = (link.get('href'))
print(links)
</code>```

My Output:

```<code>https://twrp.me
#
https://twrp.me/about/
https://twrp.me/contactus/
https://twrp.me/Devices/
https://twrp.me/FAQ/
/public.asc
/gauguin/twrp-3.5.2_10-0-gauguin.img.html
/gauguin/twrp-3.5.1_10-0-gauguin.img.html
/gauguin/twrp-3.5.0_10-0-gauguin.img.html
https://twrp.me/terms/termsofservice.html
https://twrp.me/terms/cookiepolicy.html
https://github.com/TeamWin
</code>```

So my goal is to filter this output so I just have those one link (the latest):

```<code>/gauguin/twrp-3.5.2_10-0-gauguin.img.html
</code>```

stored in a variable, so I can call this variable later on or even directly download it with wget for example.

答:
Upon reading your query I understand that you are looking for a method to get the links that end with ".img.html" so that you can use them in the future.
The below code will extract all the target links and store in a python list which can be easily used in future.

You can try this:

```<code>from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://dl.twrp.me/gauguin/"

html_doc = urlopen(url)
# defining html link (twrp...)
soup = BeautifulSoup(html_doc, "html.parser")

links = []

for link in soup.find_all('a'):
    links.append((link.get('href')))

# target strings variable will contain all the links that end with .img.html

target_strings =[]
for i in links:
    if '.img.html' in i:
        target_strings.append(i)

# and if needed in the future you can extract a single element from the list
</code>```

Body:
I am working on a web scrapping function.
I want to find the latest download link ending with ".img.html" from:

"https://dl.twrp.me/gauguin/"

and store this link in a variable, not just print it.

My code so far:

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://dl.twrp.me/gauguin/"

html_doc = urlopen(url)
# defining html link (twrp...)

soup = BeautifulSoup(html_doc, "html.parser")

for link in soup.find_all('a'):
    links = (link.get('href'))
print(links)

My Output:

https://twrp.me
#
https://twrp.me/about/
https://twrp.me/contactus/
https://twrp.me/Devices/
https://twrp.me/FAQ/
/public.asc
/gauguin/twrp-3.5.2_10-0-gauguin.img.html
/gauguin/twrp-3.5.1_10-0-gauguin.img.html
/gauguin/twrp-3.5.0_10-0-gauguin.img.html
https://twrp.me/terms/termsofservice.html
https://twrp.me/terms/cookiepolicy.html
https://github.com/TeamWin

So my goal is to filter this output so I just have those one link (the latest):

/gauguin/twrp-3.5.2_10-0-gauguin.img.html

stored in a variable, so I can call this variable later on or even directly download it with wget for example.

Body:
Upon reading your query I understand that you are looking for a method to get the links that end with ".img.html" so that you can use them in the future.
The below code will extract all the target links and store in a python list which can be easily used in future.

You can try this:

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://dl.twrp.me/gauguin/"

html_doc = urlopen(url)
# defining html link (twrp...)
soup = BeautifulSoup(html_doc, "html.parser")

links = []

for link in soup.find_all('a'):
    links.append((link.get('href')))

# target strings variable will contain all the links that end with .img.html

target_strings =[]
for i in links:
    if '.img.html' in i:
        target_strings.append(i)

# and if needed in the future you can extract a single element from the list


问:
Vue does not return the correct value of the option. It returns the text
I'm starting using Vue.js via CDN.

I have this select element:

```<code><select @change="setValue($event.target.value)">
   <option>Choose</option>
   <option val="1">First</option>
   <option val="2">Second</option>
</select>
</code>```

The problem is that Vue.js calls my setValue function with Choose when the user selects the Choose options. But when he selects the first or the second option, I get the correct value.

What do I do wrong?

答:
The correct syntax for the HTML should be value and not val

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option

<select>
    <option value="">--Please choose an option--</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
</select>
```

Body:
I'm starting using Vue.js via CDN.

I have this select element:

<select @change="setValue($event.target.value)">
   <option>Choose</option>
   <option val="1">First</option>
   <option val="2">Second</option>
</select>

The problem is that Vue.js calls my setValue function with Choose when the user selects the Choose options. But when he selects the first or the second option, I get the correct value.

What do I do wrong?


问:
How to set global.TextDecoder in jest for jsdom if node's util.TextDecoder is type mismatch?
Try to use jsdom with Jest in an NX repo (typescript/angular) and I get the problem that TextEncoder and TextDecoder are not present. I get the same result whether I set the jest testEnvironment to 'jsdom' or 'node' and with versions of node from 10 to 16)

So, following solutions other people posted (thanks!), I imported them in my test-setup.ts from node and set them on the node global object:

```<code>import 'jest-preset-angular/setup-jest'
import { TextEncoder, TextDecoder } from 'util';

global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
</code>```

This seems to work for TextEncoder, but not for TextDecoder:

```<code>   libs/xplat/features/test-setup.ts:10:1 - error TS2322: Type 'typeof TextDecoder' is not assignable to type '{ new (label?: string | undefined, options?: TextDecoderOptions | undefined): TextDecoder; prototype: TextDecoder; }'.
      The types of 'prototype.decode' are incompatible between these types.
        Type '(input?: ArrayBufferView | ArrayBuffer | null | undefined, options?: { stream?: boolean | undefined; } | undefined) => string' is not assignable to type '(input?: BufferSource | undefined, options?: TextDecodeOptions | undefined) => string'.
          Types of parameters 'input' and 'input' are incompatible.
            Type 'BufferSource | undefined' is not assignable to type 'ArrayBufferView | ArrayBuffer | null | undefined'.
              Type 'ArrayBufferView' is not assignable to type 'ArrayBufferView | ArrayBuffer | null | undefined'.
                Type 'ArrayBufferView' is missing the following properties from type 'DataView': getFloat32, getFloat64, getInt8, getInt16, and 17 more.

    10 global.TextDecoder = TextDecoder;
</code>```

Is there a different TextDecoder I should use - in particular, is there one somehow bundled with jest's jsdom which I'm just not seeing how to use?

In case it helps, here some versions (from my most recent package.json):

```<code>"devDependencies": {
    "@angular-devkit/architect": "^0.1301.2",
    "@angular-devkit/build-angular": "<=13.0.2",
    ...
    "@nrwl/angular": "13.4.6",
    "@nrwl/cli": "13.4.6",
    ...
    "@nrwl/jest": "13.4.6",
     ...
    "@types/core-js": "^2.5.5",
    "@types/jest": "^27.0.2",
    "@types/jsdom": "^16.2.14",
    "@types/node": "14.14.33",
    "@types/whatwg-url": "^8.2.1",
    "@typescript-eslint/eslint-plugin": "~5.3.0",
    "@typescript-eslint/parser": "~5.3.0",
   ...
    "jest": "27.2.3",
    "jest-jasmine2": "^27.4.6",
    "jest-preset-angular": "11.0.0",
    "jsdom": "^19.0.0",
    "ng-mocks": "^12.5.1",
    ...
    "ts-jest": "27.0.5",
    "typescript": "~4.4.3",
    "util": "^0.12.4",
    "whatwg-url": "^11.0.0"
  },
</code>```

答:
I managed to get rid of the error by first coercing the global object to any then assigning the TextDecoder:

```<code>import { TextEncoder, TextDecoder } from "util";
(global as any).TextEncoder = TextEncoder;
(global as any).TextDecoder = TextDecoder;
</code>```

I know it is not the best way of accomplishing the desired goal and would generally be considered bad practice but, as this is just for Jest's testing I think it should be ok.

Body:
Try to use jsdom with Jest in an NX repo (typescript/angular) and I get the problem that TextEncoder and TextDecoder are not present. I get the same result whether I set the jest testEnvironment to 'jsdom' or 'node' and with versions of node from 10 to 16)

So, following solutions other people posted (thanks!), I imported them in my test-setup.ts from node and set them on the node global object:

import 'jest-preset-angular/setup-jest'
import { TextEncoder, TextDecoder } from 'util';

global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

This seems to work for TextEncoder, but not for TextDecoder:

   libs/xplat/features/test-setup.ts:10:1 - error TS2322: Type 'typeof TextDecoder' is not assignable to type '{ new (label?: string | undefined, options?: TextDecoderOptions | undefined): TextDecoder; prototype: TextDecoder; }'.
      The types of 'prototype.decode' are incompatible between these types.
        Type '(input?: ArrayBufferView | ArrayBuffer | null | undefined, options?: { stream?: boolean | undefined; } | undefined) => string' is not assignable to type '(input?: BufferSource | undefined, options?: TextDecodeOptions | undefined) => string'.
          Types of parameters 'input' and 'input' are incompatible.
            Type 'BufferSource | undefined' is not assignable to type 'ArrayBufferView | ArrayBuffer | null | undefined'.
              Type 'ArrayBufferView' is not assignable to type 'ArrayBufferView | ArrayBuffer | null | undefined'.
                Type 'ArrayBufferView' is missing the following properties from type 'DataView': getFloat32, getFloat64, getInt8, getInt16, and 17 more.

    10 global.TextDecoder = TextDecoder;

Is there a different TextDecoder I should use - in particular, is there one somehow bundled with jest's jsdom which I'm just not seeing how to use?

In case it helps, here some versions (from my most recent package.json):

"devDependencies": {
    "@angular-devkit/architect": "^0.1301.2",
    "@angular-devkit/build-angular": "<=13.0.2",
    ...
    "@nrwl/angular": "13.4.6",
    "@nrwl/cli": "13.4.6",
    ...
    "@nrwl/jest": "13.4.6",
     ...
    "@types/core-js": "^2.5.5",
    "@types/jest": "^27.0.2",
    "@types/jsdom": "^16.2.14",
    "@types/node": "14.14.33",
    "@types/whatwg-url": "^8.2.1",
    "@typescript-eslint/eslint-plugin": "~5.3.0",
    "@typescript-eslint/parser": "~5.3.0",
   ...
    "jest": "27.2.3",
    "jest-jasmine2": "^27.4.6",
    "jest-preset-angular": "11.0.0",
    "jsdom": "^19.0.0",
    "ng-mocks": "^12.5.1",
    ...
    "ts-jest": "27.0.5",
    "typescript": "~4.4.3",
    "util": "^0.12.4",
    "whatwg-url": "^11.0.0"
  },

Body:
I managed to get rid of the error by first coercing the global object to any then assigning the TextDecoder:

import { TextEncoder, TextDecoder } from "util";
(global as any).TextEncoder = TextEncoder;
(global as any).TextDecoder = TextDecoder;

I know it is not the best way of accomplishing the desired goal and would generally be considered bad practice but, as this is just for Jest's testing I think it should be ok.


答:
e.printStackTrace();

Is not good practice because it prints in the default ErrorStream, which most of the times is the console!

NetBeans should be warning you about that. The good practice about it, is logging the message. Follow same reference:

http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html

EDIT
See first comment bellow to more info.

Title: Using e.printStackTrace() in Java


问:
I am getting an error after the command: make clean. Cleaning the android kernel from garbage
I have the linux kernel sources, but when I try to remove unnecessary garbage (if you follow the video manual), it gives an error:</p>
```<code>make clean
/bin/sh: 1: cd: can't cd to /lib/modules/5.14.0-kali4-amd64/build
</code>```

答:
Problem solved! The problem was the missing build directory. Installation:
apt-get install linux-headers-kernel worked but required a reboot of the device. Setting the kernel package headers can also help.</p>

Body:
I have the linux kernel sources, but when I try to remove unnecessary garbage (if you follow the video manual), it gives an error:

make clean
/bin/sh: 1: cd: can't cd to /lib/modules/5.14.0-kali4-amd64/build


问:
Why this keyof doesn't infer correctly?
I've code like this (TS Playground):

```<code>const createComp = <T extends {
  modifiers:  {
    [key: string]: string;
  };
  defaultMods: keyof T["modifiers"];
}
>(com: T) => com;

const style = createComp({
  modifiers: {
    blue: 'blue',
    red: 'red'
  },
  defaultMods: 'red' // correct. defaultMods type is 'blue' | 'red'
});
</code>```

It infer defaultMods type to 'blue' | 'red' as I expected.

But when I try to extract the extends type to Component type, like this (TS Playground):

```<code>type Component = {
  modifiers:  {
    [key: string]: string;
  };
  defaultMods: keyof Component["modifiers"];
}

const createComp = <T extends Component>(com: T) => com;

const style = createComp({
  modifiers: {
    blue: 'blue',
    red: 'red'
  },
  defaultMods: '' // defaultMods type is string
});
</code>```

It doesn't return defaultMods type as 'blue' | 'red'. Did I miss something?

答:
keyof Component["modifiers"] always resolves to string. You will need an extra type parameter to Component to represent the modifiers, and infer that in your function:

```<code>type Component<TModifiers extends Record<string, string>> = {
  modifiers: TModifiers;
  defaultMods: keyof TModifiers;
}

const createComp = <TModifiers extends Record<string, string>>(com: Component<TModifiers>) => com;

const style = createComp({
  modifiers: {
    blue: 'blue',
    red: 'red'
  },
  defaultMods: '' // it should be 'blue' | 'red'
});
</code>```

Playground Link

Title: Why this keyof doesn't infer correctly?

Body:
I've code like this (TS Playground):

const createComp = <T extends {
  modifiers:  {
    [key: string]: string;
  };
  defaultMods: keyof T["modifiers"];
}
>(com: T) => com;

const style = createComp({
  modifiers: {
    blue: 'blue',
    red: 'red'
  },
  defaultMods: 'red' // correct. defaultMods type is 'blue' | 'red'
});

It infer defaultMods type to 'blue' | 'red' as I expected.

But when I try to extract the extends type to Component type, like this (TS Playground):

type Component = {
  modifiers:  {
    [key: string]: string;
  };
  defaultMods: keyof Component["modifiers"];
}

const createComp = <T extends Component>(com: T) => com;

const style = createComp({
  modifiers: {
    blue: 'blue',
    red: 'red'
  },
  defaultMods: '' // defaultMods type is string
});

It doesn't return defaultMods type as 'blue' | 'red'. Did I miss something?

Body:
keyof Component["modifiers"] always resolves to string. You will need an extra type parameter to Component to represent the modifiers, and infer that in your function:

type Component<TModifiers extends Record<string, string>> = {
  modifiers: TModifiers;
  defaultMods: keyof TModifiers;
}

const createComp = <TModifiers extends Record<string, string>>(com: Component<TModifiers>) => com;

const style = createComp({
  modifiers: {
    blue: 'blue',
    red: 'red'
  },
  defaultMods: '' // it should be 'blue' | 'red'
});

Playground Link


问:
F# cannot post to web api?
I have the following code to post to a web api.

[<CLIMutable>]
type MyModel = { FileName:string; Period:DateTime; DownloadedTime:DateTimeOffset; Url:string; }

let PostDownload (filepath, date, url) =
  async {
    try
        use client = new HttpClient()
        let content = { FileName = filepath; Period = date; DownloadedTime = DateTimeOffset.Now; Url = url }
        let! response = Async.AwaitTask(client.PostAsJsonAsync("http://localhost:5000/api/DownloadedFiles", content))
    with
    | ex -> logger.Error(ex, "Exception: " + ex.Message)
  } |> Async.Start
```

<p>The service has the following code and the debugger shows all the fields of <code>downloadedFile</code> are the default values (nulls or the minimum values for value types). </p>

```    [HttpPost]
    public void Post([FromBody]DownloadedFile downloadedFile)
    {
        try
        {
            _context.DownloadedFile.Add(downloadedFile);
            _context.SaveChanges();
        }
        catch (Exception ex) { ...... }
    }
```

The fiddler shows the F# code (or PostAsJsonAsync cannot handle F# mutable record type?) added @ at the end of field name?

{"FileName@":"test","Period@":"2100-01-01T00:00:00","DownloadedTime@":"2016-08-18T15:50:37.5004391-04:00","Url@":"test"}

答:
I just ran into this issue and lost some hours solving it.
It seems the serializer that is used in HttpClient.PostAsJsonAsync does not handle fsharp types well. The @ symbol issue is also not easily googleable.
Using the following code however seems to work:

task {
  let content = JObject.FromObject({ Id = "foo" }).ToString()
  let! response = client.PostAsync("url", new StringContent(content, Encoding.UTF8, "application/json"))
  return "Hello world"
}

```

Title: F# cannot post to web api?

Body:
I have the following code to post to a web api.

[<CLIMutable>]
type MyModel = { FileName:string; Period:DateTime; DownloadedTime:DateTimeOffset; Url:string; }

let PostDownload (filepath, date, url) =
  async {
    try
        use client = new HttpClient()
        let content = { FileName = filepath; Period = date; DownloadedTime = DateTimeOffset.Now; Url = url }
        let! response = Async.AwaitTask(client.PostAsJsonAsync("http://localhost:5000/api/DownloadedFiles", content))
    with
    | ex -> logger.Error(ex, "Exception: " + ex.Message)
  } |> Async.Start

The service has the following code and the debugger shows all the fields of downloadedFile are the default values (nulls or the minimum values for value types).

    [HttpPost]
    public void Post([FromBody]DownloadedFile downloadedFile)
    {
        try
        {
            _context.DownloadedFile.Add(downloadedFile);
            _context.SaveChanges();
        }
        catch (Exception ex) { ...... }
    }

The fiddler shows the F# code (or PostAsJsonAsync cannot handle F# mutable record type?) added @ at the end of field name?

{"FileName@":"test","Period@":"2100-01-01T00:00:00","DownloadedTime@":"2016-08-18T15:50:37.5004391-04:00","Url@":"test"}


问:
Can I test deadlock in googletest?
I have a small class that creates multiple threads. When I call stop() method, it sets a flag for stopping threads and joins on the thread until they are stopped. Here is the code of stop() method:

```<code>void stop() {
    running_flag_ = false;
    for (auto& th : threads_) {
        if (th.joinable())
            th.join();
    }
}
</code>```

I wonder if there is a way to test if this method works as expected, meaning this method should always return. I don't think dead test is really suitable here. Any idea if there is a way to test this?

答:
When you have a deadlock some threads are waiting on locks until they are released. There is no way to recover process form such state, without adding extra code.

The only way to overcome this problem is to detect timeout and crash unit test application when timeout accrues. Some times ago I used this code to detect issue so build machine do not hang to long:

class TerminateOnDeadlockGuard final
{
public:
    using Clock = std::chrono::system_clock;
    using Duration = Clock::duration;

    explicit TerminateOnDeadlockGuard(Duration timeout = std::chrono::seconds{30});

    ~TerminateOnDeadlockGuard();

private:
    void waitForCompletion();

private:
    const Duration m_timeout;
    std::mutex m_mutex;
    std::condition_variable m_wasCompleted;
    std::condition_variable m_guardStarted;
    std::thread m_guardThread;
};
//---------
TerminateOnDeadlockGuard::TerminateOnDeadlockGuard(Duration timeout) : m_timeout{timeout}
{
    m_guardThread = std::thread(&TerminateOnDeadlockGuard::waitForCompletion, this);
    std::unique_lock lock{m_mutex};
    m_guardStarted.wait(lock);
}

TerminateOnDeadlockGuard::~TerminateOnDeadlockGuard()
{
    m_wasCompleted.notify_one();
    m_guardThread.join();
}

void TerminateOnDeadlockGuard::waitForCompletion()
{
    std::unique_lock lock{m_mutex};
    m_guardStarted.notify_one();
    if (std::cv_status::timeout == m_wasCompleted.wait_for(lock, m_timeout))
    {
        std::cerr << "Test timeout!!!" << std::endl;
        std::exit(-1); // you can use `abort` here to create crash log.
    }
}
```
<p>Usage:</p>
<pre class="lang-cpp prettyprint-override"><code>TEST(SomeTestSuite, myTest)
{
    TerminateOnDeadlockGuard guardDeadLock;

    // test code here
}
</code>```

Now there is google death test which could come to the rescue.
This forks process at let child process to terminate.

using namespace std::chrono_literals;

class NoDeadLockTest : public ::testing::Test
{
public:
    void someTest()
    {
        TerminateOnDeadlockGuard guardDeadLock{5s};
        actualTest();
        std::exit(::testing::Test::HasFailure() ? 2 : 0);
    }

    void actualTest()
    {
#if VERSION == 0
        ASSERT_TRUE(true);
#elif VERSION == 1
        ASSERT_TRUE(false);
#elif VERSION == 2
        std::this_thread::sleep_for(10s);
#endif
    }
};

TEST_F(NoDeadLockTest, myTest)
{
    EXPECT_EXIT(someTest(), testing::ExitedWithCode(0), "");
}
```

I've checked this on godbolt and it is far from perfect: https://godbolt.org/z/nasros577 but shows there is hope if some extra effort is done.

I relay recommend to use some tool to detect the dead locks and fix code. I used thread sanitizer - I've tried it and it is very effective.

Title: Can I test deadlock in googletest?

Body:
I have a small class that creates multiple threads. When I call stop() method, it sets a flag for stopping threads and joins on the thread until they are stopped. Here is the code of stop() method:

void stop() {
    running_flag_ = false;
    for (auto& th : threads_) {
        if (th.joinable())
            th.join();
    }
}

I wonder if there is a way to test if this method works as expected, meaning this method should always return. I don't think dead test is really suitable here. Any idea if there is a way to test this?

Body:
When you have a deadlock some threads are waiting on locks until they are released. There is no way to recover process form such state, without adding extra code.

The only way to overcome this problem is to detect timeout and crash unit test application when timeout accrues. Some times ago I used this code to detect issue so build machine do not hang to long:

class TerminateOnDeadlockGuard final
{
public:
    using Clock = std::chrono::system_clock;
    using Duration = Clock::duration;

    explicit TerminateOnDeadlockGuard(Duration timeout = std::chrono::seconds{30});

    ~TerminateOnDeadlockGuard();

private:
    void waitForCompletion();

private:
    const Duration m_timeout;
    std::mutex m_mutex;
    std::condition_variable m_wasCompleted;
    std::condition_variable m_guardStarted;
    std::thread m_guardThread;
};
//---------
TerminateOnDeadlockGuard::TerminateOnDeadlockGuard(Duration timeout) : m_timeout{timeout}
{
    m_guardThread = std::thread(&TerminateOnDeadlockGuard::waitForCompletion, this);
    std::unique_lock lock{m_mutex};
    m_guardStarted.wait(lock);
}

TerminateOnDeadlockGuard::~TerminateOnDeadlockGuard()
{
    m_wasCompleted.notify_one();
    m_guardThread.join();
}

void TerminateOnDeadlockGuard::waitForCompletion()
{
    std::unique_lock lock{m_mutex};
    m_guardStarted.notify_one();
    if (std::cv_status::timeout == m_wasCompleted.wait_for(lock, m_timeout))
    {
        std::cerr << "Test timeout!!!" << std::endl;
        std::exit(-1); // you can use `abort` here to create crash log.
    }
}

Usage:

TEST(SomeTestSuite, myTest)
{
    TerminateOnDeadlockGuard guardDeadLock;

    // test code here
}

Now there is google death test which could come to the rescue.
This forks process at let child process to terminate.

using namespace std::chrono_literals;

class NoDeadLockTest : public ::testing::Test
{
public:
    void someTest()
    {
        TerminateOnDeadlockGuard guardDeadLock{5s};
        actualTest();
        std::exit(::testing::Test::HasFailure() ? 2 : 0);
    }

    void actualTest()
    {
#if VERSION == 0
        ASSERT_TRUE(true);
#elif VERSION == 1
        ASSERT_TRUE(false);
#elif VERSION == 2
        std::this_thread::sleep_for(10s);
#endif
    }
};

TEST_F(NoDeadLockTest, myTest)
{
    EXPECT_EXIT(someTest(), testing::ExitedWithCode(0), "");
}

I've checked this on godbolt and it is far from perfect: https://godbolt.org/z/nasros577 but shows there is hope if some extra effort is done.

I relay recommend to use some tool to detect the dead locks and fix code. I used thread sanitizer - I've tried it and it is very effective.


问:
Inventor Design Automation with Modelstates not working
I had a bug today with an assembly that is using model states. It is handled by the design automation. So I just did a simple example.

There is a Quader, a cylinder and a sphere.
sample bg

With the help of modelstates and iLogic only one of them is shown. There is a parameter that has three options:

parameter

Depending on what is selected the model state switches. This works by using some iLogic:

```<code>If Config = "Quader" Then
    ThisDoc.ActiveModelState = "Quader"
Else If Config = "Cylinder" Then
    ThisDoc.ActiveModelState = "Cylinder"
Else If Config = "Kugel" Then
    ThisDoc.ActiveModelState = "Kugel"
End If
</code>```

This works locally but not when using it with forge design automation. Im happy to show you a sample but if you want to have a look at this video :
https://youtu.be/a9YQxsZuobo

in a more complex sample there seams to be much more things not working like parameter values not updating or position of model is wrong.

答:
After watching your video, it is understood that you are looking for assembly configurator using model states.

Now, forge sample code and testing assembly are prepared to find out the workaround. Finally, the workaround is to add one more extra parameter 'None' to assembly and save assembly with 'None' parameter as default parameter. Whenever the other 3 parameters are changed, it triggers event triggers. Which in turn executes iLogic rule to change the model state of assembly.

To demonstrate the same screencast is prepared and uploaded to below link.

https://autode.sk/3J6BjMq

Forge sample code and testing assembly used in above video are uploaded to this  link. Access to this link has been given to tobias.wiesendanger@mum.ch

Thanks and regards,

Chandra shekar G

Body:
I had a bug today with an assembly that is using model states. It is handled by the design automation. So I just did a simple example.

There is a Quader, a cylinder and a sphere.
sample bg

With the help of modelstates and iLogic only one of them is shown. There is a parameter that has three options:

parameter

Depending on what is selected the model state switches. This works by using some iLogic:

If Config = "Quader" Then
    ThisDoc.ActiveModelState = "Quader"
Else If Config = "Cylinder" Then
    ThisDoc.ActiveModelState = "Cylinder"
Else If Config = "Kugel" Then
    ThisDoc.ActiveModelState = "Kugel"
End If

This works locally but not when using it with forge design automation. Im happy to show you a sample but if you want to have a look at this video :
https://youtu.be/a9YQxsZuobo

in a more complex sample there seams to be much more things not working like parameter values not updating or position of model is wrong.


问:
How can I frequently/automatically compare the structure of the same Database?
Does anyone know a tool that automatically compares the structure of a database and gives a report of what was changed?  If it can be integrated into a CruiseControl, even better.

By structure I also mean functions and stored procedures. Which is probably not clear at first sight ;-)

The idea was to integrate that into a cruise control server

答:
SQL Compare by Redgate is purportedly good at this.

Failing that you can get a good idea of a schema compare by comparing the results of queries:

```<code>select * from information_schema.columns
select * from information_schema.tables
</code>```

OwnerDisplayName: Fatboss

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

Body:
SQL Compare by Redgate is purportedly good at this.

Failing that you can get a good idea of a schema compare by comparing the results of queries:

select * from information_schema.columns
select * from information_schema.tables

OwnerDisplayName: Neil Barnwell


问:
Duplicate child entries when saving an entity
I am getting duplicates of child when updating entity.

Submission Code:

```<code>Report report = _ReportService.GetReport(id);

report.AddDocument(
    new Document
    {
        Extension = qqfile.Substring(qqfile.Length - 3),
        Path = g.ToString(),
        Type = TypeHelper.GetDocumentType(report.Status),
        User = MemberFactory.MemberInfo
    }
);

report.Status = (ReportStatus)((int)report.Status + 1);

_reportRepository.SaveOrUpdate(report);

public class Document : BaseModel
{
    public virtual string Path { get; set; }
    public virtual string Extension { get; set; }
    public virtual DocumentType Type { get; set; }
    public virtual User User { get; set; }
    public virtual Report Report { get; set; }
}

public class DocumentMap : ClassMap<Document>
{
    public DocumentMap()
    {
        Id(x=> x.Id);
        Map(x=> x.Extension);
        Map(x => x.Path);
        Map(x => x.CreateDate);
        Map(x => x.LastModified);
        Map(x => x.Type).CustomType<int>();

        References<User>(x => x.User);
        References<Report>(x => x.Report);
    }
}

public class Report : BaseModel
{
    public virtual Patient Patient { get; set; }
    public virtual ReportStatus Status { get; set; }
    public virtual DateTime AppointmentStart { get; set; }
    public virtual DateTime AppointmentEnd { get; set; }
    public virtual ReportType Type { get; set; }
    public virtual IList<Document> Documents { get; set; }
    public virtual long Kareo_Id { get; set; }

    public Report()
    {
        this.Status = ReportStatus.New;
        this.Documents = new List<Document>();
    }

    public virtual void AddDocument(Document document)
    {
        document.Report = this;
        this.Documents.Add(document);
    }
}

public class ReportMap : ClassMap<Report>
{
    public ReportMap()
    {
        Id(x => x.Id);
        Map(x => x.CreateDate);
        Map(x => x.LastModified);
        Map(x => x.AppointmentStart);
        Map(x => x.AppointmentEnd);
        Map(x => x.Type).CustomType<int>();
        Map(x => x.Status).CustomType<int>();
        Map(x => x.Kareo_Id);

        References<Patient>(x => x.Patient);
        HasMany<Document>(x => x.Documents)
            .Inverse()
            .Cascade.All();
    }
}
</code>```

答:
Mapping of an entity i take it as document map:
you should add

```<code>References<User>(x => x.User).Cascade.None();
</code>```

Cascade.None() will stop cascading any changes.

Also you can use intellisense to give you options you can use when you write .Cascade.

Rev 2

this should be for both mappings

References(x => x.User).Cascade.None(); References(x =>
  x.Report).Cascade.None();

Body:
I am getting duplicates of child when updating entity.

Submission Code:

Report report = _ReportService.GetReport(id);

report.AddDocument(
    new Document
    {
        Extension = qqfile.Substring(qqfile.Length - 3),
        Path = g.ToString(),
        Type = TypeHelper.GetDocumentType(report.Status),
        User = MemberFactory.MemberInfo
    }
);

report.Status = (ReportStatus)((int)report.Status + 1);

_reportRepository.SaveOrUpdate(report);

public class Document : BaseModel
{
    public virtual string Path { get; set; }
    public virtual string Extension { get; set; }
    public virtual DocumentType Type { get; set; }
    public virtual User User { get; set; }
    public virtual Report Report { get; set; }
}

public class DocumentMap : ClassMap<Document>
{
    public DocumentMap()
    {
        Id(x=> x.Id);
        Map(x=> x.Extension);
        Map(x => x.Path);
        Map(x => x.CreateDate);
        Map(x => x.LastModified);
        Map(x => x.Type).CustomType<int>();

        References<User>(x => x.User);
        References<Report>(x => x.Report);
    }
}

public class Report : BaseModel
{
    public virtual Patient Patient { get; set; }
    public virtual ReportStatus Status { get; set; }
    public virtual DateTime AppointmentStart { get; set; }
    public virtual DateTime AppointmentEnd { get; set; }
    public virtual ReportType Type { get; set; }
    public virtual IList<Document> Documents { get; set; }
    public virtual long Kareo_Id { get; set; }

    public Report()
    {
        this.Status = ReportStatus.New;
        this.Documents = new List<Document>();
    }

    public virtual void AddDocument(Document document)
    {
        document.Report = this;
        this.Documents.Add(document);
    }
}

public class ReportMap : ClassMap<Report>
{
    public ReportMap()
    {
        Id(x => x.Id);
        Map(x => x.CreateDate);
        Map(x => x.LastModified);
        Map(x => x.AppointmentStart);
        Map(x => x.AppointmentEnd);
        Map(x => x.Type).CustomType<int>();
        Map(x => x.Status).CustomType<int>();
        Map(x => x.Kareo_Id);

        References<Patient>(x => x.Patient);
        HasMany<Document>(x => x.Documents)
            .Inverse()
            .Cascade.All();
    }
}

Body:
Mapping of an entity i take it as document map:
you should add

References<User>(x => x.User).Cascade.None();

Cascade.None() will stop cascading any changes.

Also you can use intellisense to give you options you can use when you write .Cascade.

Rev 2

this should be for both mappings

References(x => x.User).Cascade.None(); References(x =>
  x.Report).Cascade.None();


问:
How to position user typed-in content in search bar input?
I am working on a search bar for my site. It is positioned correctly on the site, it's styled and everything works just fine, I added a placeholder and positioned/styled it inside the search bar as I liked it to fit the rest of my site. If I click inside the search bar and write anything, the written letters appear in the default position of the placeholder (middle of the search bar), but I want them to be positioned differently (more to the left and lower), like the placeholder.
The placeholder looks good but the
typed-in text doesn't.

The HTML looks like this:

```<code><input id="searchbar" type="text" placeholder="Suche..." />
</code>```

The search bar is styled as following:

```<code>#searchbar {
  grid-area: search;
  font-size: max(var(--ändern), 20px);
  font-family: var(--schriftart);
  background-color: var(--hintergrundfarbe);
  color: var(--schriftfarbe);
  border: solid 1px;
  border-radius: 0.75vw;
  border-color: var(--hintergrundfarbe);
  text-align: center;
  width: 15vw;
  height: max(2.5vw, calc(150px / 4));
  margin-left: 1.25vw;
  margin-top: 0.5vw;
  box-sizing: border-box;
}
input:focus {
  outline: none;
}
</code>```

The placeholder is styled as following:

```<code>#searchbar::placeholder {
  color: var(--schriftfarbe);
  filter: opacity(0.5);
  position: absolute;
  left: 20px;
  top: auto;
  bottom: auto;
}
</code>```

I tried to use

```<code>#searchbar:focus {
  position: relative;
  left: 20px;
  top: auto;
  bottom: auto;
}
</code>```

but it shifts the whole search bar, not only the the typed-in content.
I also tried

```<code>text-indent: 40px;
</code>```

but doesn't seem to change anything either. I would be happy for anyone trying to help me :)

答:
try to do like this:</p>
```<code>#searchbar input[type=text]{
/*write your css here*/

  text-indent: 20px;
}
</code>```

Body:
I am working on a search bar for my site. It is positioned correctly on the site, it's styled and everything works just fine, I added a placeholder and positioned/styled it inside the search bar as I liked it to fit the rest of my site. If I click inside the search bar and write anything, the written letters appear in the default position of the placeholder (middle of the search bar), but I want them to be positioned differently (more to the left and lower), like the placeholder.
The placeholder looks good but the
typed-in text doesn't.

The HTML looks like this:

<input id="searchbar" type="text" placeholder="Suche..." />

The search bar is styled as following:

#searchbar {
  grid-area: search;
  font-size: max(var(--ändern), 20px);
  font-family: var(--schriftart);
  background-color: var(--hintergrundfarbe);
  color: var(--schriftfarbe);
  border: solid 1px;
  border-radius: 0.75vw;
  border-color: var(--hintergrundfarbe);
  text-align: center;
  width: 15vw;
  height: max(2.5vw, calc(150px / 4));
  margin-left: 1.25vw;
  margin-top: 0.5vw;
  box-sizing: border-box;
}
input:focus {
  outline: none;
}

The placeholder is styled as following:

#searchbar::placeholder {
  color: var(--schriftfarbe);
  filter: opacity(0.5);
  position: absolute;
  left: 20px;
  top: auto;
  bottom: auto;
}

I tried to use

#searchbar:focus {
  position: relative;
  left: 20px;
  top: auto;
  bottom: auto;
}

but it shifts the whole search bar, not only the the typed-in content.
I also tried

text-indent: 40px;

but doesn't seem to change anything either. I would be happy for anyone trying to help me :)

Body:
try to do like this:

#searchbar input[type=text]{
/*write your css here*/

  text-indent: 20px;
}


问:
How can I use the LIKE operator on a map type in hiveql?
I want to select two columns out of students:

```<code>id_test         int
number  map<string,string>
</code>```

I tried followed command with the LIKE Operator:

```<code>SELECT id_test ,number FROM students WHERE id_test = 123456 AND number LIKE %MOBILE%;
</code>```

And get this error:

```<code>FAILED: SemanticException [Error 10014]: Line 1:82 Wrong arguments ''%MOBILE%'': No
matching method for class org.apache.hadoop.hive.ql.udf.UDFLike with
(map<string,string>, string). Possible choices: _FUNC_(string, string)
</code>```

Code for reproduction:

```<code>CREATE TABLE students(id_test INT, number MAP<STRING, STRING>) ROW FORMAT DELIMITED FIELDS TERMINATED by
'|' COLLECTION ITEMS TERMINATED BY ',' MAP KEYS TERMINATED BY ':';

INSERT INTO TABLE students SELECT 123434, map('MOBILE','918-555-1162') FROM existingtable LIMIT 1;
INSERT INTO TABLE students SELECT 245678, map('WORK','806-555-4722') FROM existingtable LIMIT 1;
</code>```

答:
Explode map, then you can filter keys using LIKE. If you want to get single row per id_test, number even if there are many keys satisfying LIKE condition, use GROUP BY or DISTINCT.

Demo:

```<code>with students as (--one record has many MOBILE* keys in the map
SELECT 123434 id_test , map('MOBILE','918-555-1162', 'OFFICE', '123456', 'MOBILE2', '5678') number union all
SELECT 245678, map('WORK','806-555-4722')
)

select s.id_test, s.number
  from students s
      lateral view explode(number) n as key,value
where n.key like '%MOBILE%'
group by s.id_test, s.number
</code>```

Result:

```<code>123434 {"MOBILE":"918-555-1162","MOBILE2":"5678","OFFICE":"123456"}
</code>```

If you know the key exactly 'MOBILE' then better to filter like this:  where number['MOBILE'] is not null, without explode.

Body:
I want to select two columns out of students:

id_test         int
number  map<string,string>

I tried followed command with the LIKE Operator:

SELECT id_test ,number FROM students WHERE id_test = 123456 AND number LIKE %MOBILE%;

And get this error:

FAILED: SemanticException [Error 10014]: Line 1:82 Wrong arguments ''%MOBILE%'': No
matching method for class org.apache.hadoop.hive.ql.udf.UDFLike with
(map<string,string>, string). Possible choices: _FUNC_(string, string)

Code for reproduction:

CREATE TABLE students(id_test INT, number MAP<STRING, STRING>) ROW FORMAT DELIMITED FIELDS TERMINATED by
'|' COLLECTION ITEMS TERMINATED BY ',' MAP KEYS TERMINATED BY ':';

INSERT INTO TABLE students SELECT 123434, map('MOBILE','918-555-1162') FROM existingtable LIMIT 1;
INSERT INTO TABLE students SELECT 245678, map('WORK','806-555-4722') FROM existingtable LIMIT 1;

Body:
Explode map, then you can filter keys using LIKE. If you want to get single row per id_test, number even if there are many keys satisfying LIKE condition, use GROUP BY or DISTINCT.

Demo:

with students as (--one record has many MOBILE* keys in the map
SELECT 123434 id_test , map('MOBILE','918-555-1162', 'OFFICE', '123456', 'MOBILE2', '5678') number union all
SELECT 245678, map('WORK','806-555-4722')
)

select s.id_test, s.number
  from students s
      lateral view explode(number) n as key,value
where n.key like '%MOBILE%'
group by s.id_test, s.number

Result:

123434 {"MOBILE":"918-555-1162","MOBILE2":"5678","OFFICE":"123456"}

If you know the key exactly 'MOBILE' then better to filter like this:  where number['MOBILE'] is not null, without explode.


问:
So I have a jquery selector and I am chaining many methods as well as using a toggle
```<code>$(document).ready(function(){
    $("header").css({
        "background-color":"#93E9BE",
        "color": "white",
        "text-align": "center",
        "font-size" : "xx-large"
    }).click(function(){
        $(this).toggle(function(){
            $(this).css("background-color","red");
        }, function(){
            $(this).css("background-color", "black");
        }),

    })

});
</code>```

答:
.toggle() is used to display or hide the matched elements. So to just toggle the background, you can try this

$(document).ready(function(){
    var initial = 'rgb(147, 233, 190)';
    var red     = 'rgb(255, 0, 0)';
    var black   = 'rgb(0, 0, 0)';

    $("header").css({
        "background-color": initial,
        "color": "white",
        "text-align": "center",
        "font-size" : "xx-large"
    }).click(function(){
        if( $(this).css('background-color') === initial ){
            $(this).css('background-color', red);
        }else if( $(this).css('background-color') === red ){
            $(this).css('background-color', black);
        }else{
            $(this).css("background-color", initial);
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header style="height:50px;"></header></code>```

Body:
.toggle() is used to display or hide the matched elements. So to just toggle the background, you can try this

$(document).ready(function(){
    var initial = 'rgb(147, 233, 190)';
    var red     = 'rgb(255, 0, 0)';
    var black   = 'rgb(0, 0, 0)';

    $("header").css({
        "background-color": initial,
        "color": "white",
        "text-align": "center",
        "font-size" : "xx-large"
    }).click(function(){
        if( $(this).css('background-color') === initial ){
            $(this).css('background-color', red);
        }else if( $(this).css('background-color') === red ){
            $(this).css('background-color', black);
        }else{
            $(this).css("background-color", initial);
        }
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header style="height:50px;"></header>


问:
Regex to match MySQL comments
I need to find and remove all of the comments from a MySQL query.  The problem I'm having is avoiding comment markers (--, #, /* ... */) that are inside of quotes or backticks.</p>

答:
Unfortunately, what you are trying to do requires a context free grammar and cannot be done with a regular expression.  It's because of the nesting, and in computer science theory, we require a stack to track when you are nested in quotes or what-not.  (Technically this requires a  push down automata instead of a regular language.  Blah blah academia blah...) It isn't hard to implement, but is has to be done procedurally, and honestly, it may require more effort than you want to expend.

If you don't mind cutting and pasting, you can use SQLInform.  The online mode is free and supports comment removal.

UPDATE

Considering the comment I received below, I played around with the MySQL editor.  I was mistaken -- they've actually prohibited nesting anything deeper than one level.  You can no longer nest a comment inside a comment (if you ever could).  At any rate, I'll leave my answer up just for the SQLInform link.

Title: Regex to match MySQL comments


问:
Unity animation not completing
i'm beginner on unity and game development. i'm trying to make a platformer game with unity, and i want to play a animation when the player is moving right or left, but the problem is that the isMoving variable for some reason is true animation is playing for a few moments (less than a second) and then is going to false again and the idle animation is playing.

My Animator (Exit time is disabled for all transitions):

My Movement script:

```<code>public class PlayerMovement : MonoBehaviour
{

    private bool canPlayerJump;
    private float horizontalInput;
    private Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.Space) && canPlayerJump)
        {
            GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
        }

        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.A))
        {
            animator.SetBool("isMoving", true);
        } else
        {
            animator.SetBool("isMoving", false);
        }

        horizontalInput = Input.GetAxis("Horizontal");

    }

    private void FixedUpdate()
    {
        GetComponent<Rigidbody>().velocity = new Vector3(horizontalInput * 5, GetComponent<Rigidbody>().velocity.y, 0);
    }

    private void OnCollisionEnter(Collision collision)
    {
       canPlayerJump = true;
       Debug.Log(collision.gameObject.name);
    }

    private void OnCollisionExit(Collision collision)
    {
        canPlayerJump = false;
    }

}
</code>```

答:
You using Update loop function that means this code will be executed each frame by unity. Similar to FixedUpdate, LateUpdate etc...
You can read more here: HERE
Once you pressing down you IF statement will be executed because you listening for BTN DOWN event. This means that TRUE will be returned only in one frame when you press actually button next frame it will return false. and your animations stops.

Try to change bool to Trigger

Or handle in another way bool var state.

Title: Unity animation not completing

Body:
i'm beginner on unity and game development. i'm trying to make a platformer game with unity, and i want to play a animation when the player is moving right or left, but the problem is that the isMoving variable for some reason is true animation is playing for a few moments (less than a second) and then is going to false again and the idle animation is playing.

My Animator (Exit time is disabled for all transitions):

My Movement script:

public class PlayerMovement : MonoBehaviour
{

    private bool canPlayerJump;
    private float horizontalInput;
    private Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.Space) && canPlayerJump)
        {
            GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
        }

        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.A))
        {
            animator.SetBool("isMoving", true);
        } else
        {
            animator.SetBool("isMoving", false);
        }

        horizontalInput = Input.GetAxis("Horizontal");

    }

    private void FixedUpdate()
    {
        GetComponent<Rigidbody>().velocity = new Vector3(horizontalInput * 5, GetComponent<Rigidbody>().velocity.y, 0);
    }

    private void OnCollisionEnter(Collision collision)
    {
       canPlayerJump = true;
       Debug.Log(collision.gameObject.name);
    }

    private void OnCollisionExit(Collision collision)
    {
        canPlayerJump = false;
    }

}


问:
how to open and edit py file in command prompt windows 10
I'm finding for a syntax equivalent to mac os terminal open filename.py in windows command prompt.
I've search internet to find answer like type in filename (or location) filename.py into command prompt, but that just run a script or even start filename.py doesn't seems to work too. how do i edit get to edit my code via command prompt?

答:
If you have set the environment variable you can type

```<code>python fileName.py
</code>```

Otherwise you will need to put the full path.In my case

```<code>C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.7/ Python 3.7 (64-bit)
</code>```

Body:
If you have set the environment variable you can type

python fileName.py

Otherwise you will need to put the full path.In my case

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.7/ Python 3.7 (64-bit)


问:
Spring boot transaction keeps running after commiting in async method
I have this scenario:

```<code>@Transactional
public void setStopped(Machine machine)
{
    machine.setStatus(StatusType.STOPPED);
    machineRepository.saveAndFlush(machine);
}

@Transactional
public void setRunningAndAvailable(Machine machine)
{
    machine.setStatus(StatusType.RUNNING);
    machine.setAvailable(true);
    machineRepository.saveAndFlush(machine);
}

@Async
public void restart(Machine machine, int bound, int sec)
{
    try
    {
        if(machine.getStatus().equals(StatusType.RUNNING))
        {
            Random random = new Random();
            int number = random.nextInt(bound) * 1000;
            Thread.sleep((sec * 1000L) + number);

            setStopped(machine);

            number = random.nextInt(bound) * 1000;
            Thread.sleep((sec * 1000L) + number);

            setRunningAndAvailable(machine);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
</code>```

I keep getting the following errors:

```<code>org.springframework.orm.ObjectOptimisticLockingFailureException

Caused by:
org.hibernate.StaleObjectStateException: Row was updated or deleted by another
transaction (or unsaved-value mapping was incorrect)
</code>```

The DB doesn't update after the first method ends (setStopped) and I get these errors when I try to saveAndFlush for the second time in (setRunningAndAvailable) which leads me to believe that somehow the first transaction is still ongoing.

I tried to do @Transactional(propagation = Propagation.NESTED) and @Transactional(propagation = Propagation.REQUIRES_NEW) but I got the same errors.

I don't know why this keeps happening, if anyone could help me I would appreciate it a lot.

答:
You need to know that @Transactional works with AOP, so the behaviour (the creation and commit of the transaction) is added before entering your method and right after the return.

The main problem is that your are calling methods from the same bean, so you are not traversing the proxy layer of the bean, and not triggering the @Transactional behaviour..

You need to move the annotated methods in another class, and inject that bean in your class.

Body:
I have this scenario:

@Transactional
public void setStopped(Machine machine)
{
    machine.setStatus(StatusType.STOPPED);
    machineRepository.saveAndFlush(machine);
}

@Transactional
public void setRunningAndAvailable(Machine machine)
{
    machine.setStatus(StatusType.RUNNING);
    machine.setAvailable(true);
    machineRepository.saveAndFlush(machine);
}

@Async
public void restart(Machine machine, int bound, int sec)
{
    try
    {
        if(machine.getStatus().equals(StatusType.RUNNING))
        {
            Random random = new Random();
            int number = random.nextInt(bound) * 1000;
            Thread.sleep((sec * 1000L) + number);

            setStopped(machine);

            number = random.nextInt(bound) * 1000;
            Thread.sleep((sec * 1000L) + number);

            setRunningAndAvailable(machine);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

I keep getting the following errors:

org.springframework.orm.ObjectOptimisticLockingFailureException

Caused by:
org.hibernate.StaleObjectStateException: Row was updated or deleted by another
transaction (or unsaved-value mapping was incorrect)

The DB doesn't update after the first method ends (setStopped) and I get these errors when I try to saveAndFlush for the second time in (setRunningAndAvailable) which leads me to believe that somehow the first transaction is still ongoing.

I tried to do @Transactional(propagation = Propagation.NESTED) and @Transactional(propagation = Propagation.REQUIRES_NEW) but I got the same errors.

I don't know why this keeps happening, if anyone could help me I would appreciate it a lot.


问:
Pandas conditional merge 2 dataframes with one to many relationship
I am trying to merge two pandas DataFrames with one of many relationship. However, there are a couple of caveats. Explanation below.

```<code>import pandas as pd

df1 = pd.DataFrame({'name': ['AA', 'BB', 'CC', 'DD'],
                    'col1': [1, 2, 3, 4],
                    'col2': [1, 2, 3, 4] })

df2 = pd.DataFrame({'name': ['AA', 'AA', 'BB', 'BB', 'CC', 'DD'],
                    'col3': [0, 10, np.nan, 11, 12, np.nan] })
</code>```

I'd like to merge the 2 DataFrames, however, ignore the 0 and np.nan in df2 when joining. I cannot simply filter df2 as there are other columns that I need.

Basically, I'd like to join on rows with one-to-many relationship that are not 0 or NaNs.

Expected output:

答:
how about this :

```<code>merged_Df = df1.merge(df2.sort_values(['name','col3'], ascending=False).groupby(['name']).head(1), on='name')
</code>```

output :

```<code>>>>
  name  col1  col2  col3
0   AA     1     1  10.0
1   BB     2     2  11.0
2   CC     3     3  12.0
3   DD     4     4   NaN
</code>```

Body:
I am trying to merge two pandas DataFrames with one of many relationship. However, there are a couple of caveats. Explanation below.

import pandas as pd

df1 = pd.DataFrame({'name': ['AA', 'BB', 'CC', 'DD'],
                    'col1': [1, 2, 3, 4],
                    'col2': [1, 2, 3, 4] })

df2 = pd.DataFrame({'name': ['AA', 'AA', 'BB', 'BB', 'CC', 'DD'],
                    'col3': [0, 10, np.nan, 11, 12, np.nan] })

I'd like to merge the 2 DataFrames, however, ignore the 0 and np.nan in df2 when joining. I cannot simply filter df2 as there are other columns that I need.

Basically, I'd like to join on rows with one-to-many relationship that are not 0 or NaNs.

Expected output:

Body:
how about this :

merged_Df = df1.merge(df2.sort_values(['name','col3'], ascending=False).groupby(['name']).head(1), on='name')

output :

>>>
  name  col1  col2  col3
0   AA     1     1  10.0
1   BB     2     2  11.0
2   CC     3     3  12.0
3   DD     4     4   NaN


问:
What's the accepted method for deploying a linux application that relies on shared libraries?
I have an application that relies on Qt, GDCM, and VTK, with the main build environment being Qt.  All of these libraries are cross-platform and compile on Windows, Mac, and Linux.  I need to deploy the application to Linux after deploying on Windows.  The versions of vtk and gdcm I'm using are trunk versions from git (about a month old), more recent than what I can get apt-get on Ubuntu 11.04, which is my current (and only) Linux deployment target.

What is the accepted method for deploying an application that relies on these kinds of libraries?

Should I be statically linking here, to avoid LD_LIBRARY_PATH?  I see conflicting reports on LD_LIBRARY_PATH; tutorials like this one suggest that it's the 'right way' to modify the library path to use shared libraries through system reboots.  Others suggest that I should never set LD_LIBRARY_PATH.  In the default version of GDCM, the installation already puts libraries into the /usr/local/lib directory, so those libraries get seen when I run ldd <my program>.  VTK, on the other hand, puts its libraries into /usr/local/lib/vtk-5.9, which is not part of the LD_LIBRARY_PATH on most user's machines, and so is not found unless some change is made to the system.  Copying the VTK files into '/usr/local/lib' does not allow 'ldd' to see the files.

So, how can I make my application see VTK to use the libraries?

On windows, deploying the dlls is very straightforward, because I can just include them in the installer, and the application finds them because they are in the local directory.  That approach does not work in Linux, so I was going to have the users install Qt, GDCM, and VTK from whatever appropriate source and use the default locations, and then have the application point to those default locations.  However, since VTK is putting things into a non-standard location, should I also expect users to modify LD_LIBRARY_PATH?  Should I include the specific versions of the libraries that I want and then figure out how to make the executable look in the local directory for those libraries and ignore the ones it finds in the library path?

答:
In general, you're best off depending on the 'normal' versions of the libraries for whatever distribution you're targetting (and saying you don't support dists that don't support recent enough versions of the lib), but if you REALLY need to depend on a bleeding edge version of some shared lib, you can link your app with -Wl,-rpath,'$ORIGIN' and then install a copy of the exact version you want in the same directory as your executable.

Note that if you use make, you'll need $$ in the makefile to get a single $ into the argument that is actually sent to the linker.  The single qutoes are needed so the shell doesn't munge things...


问:
Rspec feature specs not working with Devise sign up
I want to test that a user can log in and that a visitor can sign up. The log in works well but for sign up it is not working for some reason. This is my feature spec:

```<code>require 'rails_helper'

RSpec.feature "Devise interactions", type: :feature do
    let(:user) { FactoryBot.create(:non_admin_user) }

    scenario "user logs in sucessfully" do
        visit new_user_session_path

        fill_in "Email", with: user.email
        fill_in "Password", with: user.password
        click_button "Log in"

        expect(page).to have_current_path "/"
    end

    scenario "user logs in unsuccesfully" do
        visit new_user_session_path

        fill_in "Password", with: user.password
        click_button "Log in"

        expect(page).to have_text('Invalid Email or password')
    end

    scenario "visitor signs up succesfully", js:true do
        visit new_user_registration_path

        fill_in "Username", with: "josem"
        fill_in "Email", with: "abcd@test.com"
        within ".user_password" do
            fill_in 'Password', with: 'testing'
        end
        within ".user_password_confirmation" do
            fill_in 'Password confirmation', with: 'testing'
        end

        #save_and_open_screenshot

        click_button "Sign up"

        #save_and_open_screenshot

        expect(page).to have_text('Welcome! You have signed up successfully.')
    end

    scenario "visitor signs up unsuccesfully" do
        visit new_user_registration_path

        fill_in "Username", with: "josem"
        fill_in "Email", with: "abcd"
        within ".user_password" do
            fill_in 'Password', with: 'password'
        end
        within ".user_password_confirmation" do
            fill_in 'Password confirmation', with: 'password'
        end
        click_button "Sign up"

        expect(page).to have_text('Email is invalid')
    end
end
</code>```

The third scenario:

```<code>scenario "visitor signs up succesfully", js:true do
        visit new_user_registration_path

        fill_in "Username", with: "josem"
        fill_in "Email", with: "abcd@test.com"
        within ".user_password" do
            fill_in 'Password', with: 'testing'
        end
        within ".user_password_confirmation" do
            fill_in 'Password confirmation', with: 'testing'
        end

        #save_and_open_screenshot

        click_button "Sign up"

        #save_and_open_screenshot

        expect(page).to have_text('Welcome! You have signed up successfully.')
    end
</code>```

Is the one that is not working. Been trying to debug:

Before the Sign up button is clicked, everything is written correctly

After the Sign up button is clicked, I only get an error of Please review the problems below: but it doesn´t say what type of error (there shouldn't be any error since the validations are all successful).

When I go to my Rails app and try to sign up manually, every time I have an error, it will point it out but it doesn't in the spec.

Since the log in is working, I doubt it is an error from the Devise config and I can´t find out why. Any ideas on why is it happening? Thanks!!

答:
I feel the error that you are getting is not from the device. Because devise doesn't have any error with message Please review the problems below. Possibly the error is from the simple_form gem which you might be using(check your Gemfile.lock). simple_form gem has the same error notification which you have mentioned. Please refer to the code Please review the problems below.

Also, you can see the feature test log tail -f log/test.log.

Body:
I want to test that a user can log in and that a visitor can sign up. The log in works well but for sign up it is not working for some reason. This is my feature spec:

require 'rails_helper'

RSpec.feature "Devise interactions", type: :feature do
    let(:user) { FactoryBot.create(:non_admin_user) }

    scenario "user logs in sucessfully" do
        visit new_user_session_path

        fill_in "Email", with: user.email
        fill_in "Password", with: user.password
        click_button "Log in"

        expect(page).to have_current_path "/"
    end

    scenario "user logs in unsuccesfully" do
        visit new_user_session_path

        fill_in "Password", with: user.password
        click_button "Log in"

        expect(page).to have_text('Invalid Email or password')
    end

    scenario "visitor signs up succesfully", js:true do
        visit new_user_registration_path

        fill_in "Username", with: "josem"
        fill_in "Email", with: "abcd@test.com"
        within ".user_password" do
            fill_in 'Password', with: 'testing'
        end
        within ".user_password_confirmation" do
            fill_in 'Password confirmation', with: 'testing'
        end

        #save_and_open_screenshot

        click_button "Sign up"

        #save_and_open_screenshot

        expect(page).to have_text('Welcome! You have signed up successfully.')
    end

    scenario "visitor signs up unsuccesfully" do
        visit new_user_registration_path

        fill_in "Username", with: "josem"
        fill_in "Email", with: "abcd"
        within ".user_password" do
            fill_in 'Password', with: 'password'
        end
        within ".user_password_confirmation" do
            fill_in 'Password confirmation', with: 'password'
        end
        click_button "Sign up"

        expect(page).to have_text('Email is invalid')
    end
end

The third scenario:

scenario "visitor signs up succesfully", js:true do
        visit new_user_registration_path

        fill_in "Username", with: "josem"
        fill_in "Email", with: "abcd@test.com"
        within ".user_password" do
            fill_in 'Password', with: 'testing'
        end
        within ".user_password_confirmation" do
            fill_in 'Password confirmation', with: 'testing'
        end

        #save_and_open_screenshot

        click_button "Sign up"

        #save_and_open_screenshot

        expect(page).to have_text('Welcome! You have signed up successfully.')
    end

Is the one that is not working. Been trying to debug:

Before the Sign up button is clicked, everything is written correctly

After the Sign up button is clicked, I only get an error of Please review the problems below: but it doesn´t say what type of error (there shouldn't be any error since the validations are all successful).

When I go to my Rails app and try to sign up manually, every time I have an error, it will point it out but it doesn't in the spec.

Since the log in is working, I doubt it is an error from the Devise config and I can´t find out why. Any ideas on why is it happening? Thanks!!


问:
What is the deno equivalent of node --check
In node there is a --check option to check if code is valid for execution without actually running it if valid.
I have been looking for an equivalent in deno (deno help, deno run help, deno lint help)

The closest i can figure out is deno lint, but it will happily lint the following typescript code (in test.ts), which deno run subsequently refuses to run (obviously).

What is the canonical deno "dry run"?

test.ts:

```<code>const message = "hello!";
message();
</code>```

答:
check if code is valid for execution

"dry run"

These concepts don't exist. I think what you want is to have your TypeScript code analyzed using static type-checking (without actually running the module). This is called compilation and the Deno subcommand you want in this case is cache:

```<code>deno cache module.ts
</code>```

Re-cache the entrypoint module and all dependencies:

```<code>deno cache --reload module.ts
</code>```

Using your example test.ts:

```<code>% deno cache test.ts
Check file:///Users/deno/test.ts
error: TS2349 [ERROR]: This expression is not callable.
  Type 'String' has no call signatures.
message();
~~~~~~~
    at file:///Users/deno/test.ts:2:1
</code>```

Body:
In node there is a --check option to check if code is valid for execution without actually running it if valid.
I have been looking for an equivalent in deno (deno help, deno run help, deno lint help)

The closest i can figure out is deno lint, but it will happily lint the following typescript code (in test.ts), which deno run subsequently refuses to run (obviously).

What is the canonical deno "dry run"?

test.ts:

const message = "hello!";
message();

Body:
check if code is valid for execution

"dry run"

These concepts don't exist. I think what you want is to have your TypeScript code analyzed using static type-checking (without actually running the module). This is called compilation and the Deno subcommand you want in this case is cache:

deno cache module.ts

Re-cache the entrypoint module and all dependencies:

deno cache --reload module.ts

Using your example test.ts:

% deno cache test.ts
Check file:///Users/deno/test.ts
error: TS2349 [ERROR]: This expression is not callable.
  Type 'String' has no call signatures.
message();
~~~~~~~
    at file:///Users/deno/test.ts:2:1


问:
How can Contract get NFT's metadata?
I have two Token Contracts ("AA" = ERC721, "BB" = ERC20).

I will make "Swap Contract" that can give "BB" differently according to the "AA"'s metadata. (e.g. "level").

How do I make the "Swap Contract" for this function to work?

Any example plz.

答:
If you are hosting the metadata outside the blockchain you can't do that.
You need to use an oracle. Read more.</p>

Title: How can Contract get NFT's metadata?


问:
Frequency counts with a "multiple selection" variable
I have a dataframe with three variables:

ID

Gender (m,f,d)

Medication (1,2,3,4,5,6,7,8,9,10)

For "Medication" multiple selections were possible in the questionnaire so now there are several numbers in each cell of the dataframe (separated by ";").
Is it possible to create a frequency table that counts each number (1-10) individually  and have it grouped by gender? I need to have "Medication" (1-10) in rows and the counts grouped by gender as columns.

I already tried to split the columns so that each cell is left with only one value. But then I still have the problem to count the values across multiple columns. For each function I tried so far, the variables have been counted separately.

Thank you for your help!

Sorry, I don't know how to do it with dput. Here is a screenshot, I hope that helps! (Geschlecht = gender; Medikament = medication

And this is the expected output but without the combinations like "01;03"

答:
Text parsing like this can be difficult without a specific, reproducible example. However, it sounds as though your data frame looks something like this:

df
#>    ID medication gender
#> 1   1          9      f
#> 2   2      2;1;3      m
#> 3   3        6;2      d
#> 4   4          3      f
#> 5   5    7;8;7;1      f
#> 6   6    6;9;4;6      m
#> 7   7          9      d
#> 8   8      8;6;3      f
#> 9   9        9;7      d
#> 10 10        8;6      m
```
<p>In which case, the pedestrian way to get your result in base R would be something like this:</p>
```meds <- lapply(split(df, df$gender),
               function(x) unlist(strsplit(x$medication, ";\\s?")))

genders <- rep(c("d", "f", "m"), times = lengths(meds))

table(gender = genders, medication = unlist(meds))
#>       medication
#> gender 1 2 3 4 5 6 7 8 9 10
#>      d 0 1 0 0 0 1 1 0 2  0
#>      f 1 0 2 0 0 1 2 2 1  0
#>      m 1 1 1 1 0 3 0 1 1  0
```
<hr />
<p><strong>Reproducible data</strong></p>
<pre class="lang-r prettyprint-override"><code>set.seed(2)

medication <- sapply(rpois(10, 2), function(x) {
  if(x == 0) x <- 1
  x <- sample(1:10, x, TRUE)
  paste(x, collapse = ";")
})

gender <- sample(c("m", "f", "d"), 10, TRUE, prob = c(2, 2, 1))

df <- data.frame(ID = 1:10, medication = medication, gender = gender)
</code>```

Created on 2022-02-06 by the reprex package (v2.0.1)

Body:
Text parsing like this can be difficult without a specific, reproducible example. However, it sounds as though your data frame looks something like this:

df
#>    ID medication gender
#> 1   1          9      f
#> 2   2      2;1;3      m
#> 3   3        6;2      d
#> 4   4          3      f
#> 5   5    7;8;7;1      f
#> 6   6    6;9;4;6      m
#> 7   7          9      d
#> 8   8      8;6;3      f
#> 9   9        9;7      d
#> 10 10        8;6      m

In which case, the pedestrian way to get your result in base R would be something like this:

meds <- lapply(split(df, df$gender),
               function(x) unlist(strsplit(x$medication, ";\\s?")))

genders <- rep(c("d", "f", "m"), times = lengths(meds))

table(gender = genders, medication = unlist(meds))
#>       medication
#> gender 1 2 3 4 5 6 7 8 9 10
#>      d 0 1 0 0 0 1 1 0 2  0
#>      f 1 0 2 0 0 1 2 2 1  0
#>      m 1 1 1 1 0 3 0 1 1  0

Reproducible data

set.seed(2)

medication <- sapply(rpois(10, 2), function(x) {
  if(x == 0) x <- 1
  x <- sample(1:10, x, TRUE)
  paste(x, collapse = ";")
})

gender <- sample(c("m", "f", "d"), 10, TRUE, prob = c(2, 2, 1))

df <- data.frame(ID = 1:10, medication = medication, gender = gender)

Created on 2022-02-06 by the reprex package (v2.0.1)


问:
MPI_Isend/MPI_Recv vs. MPI_Send/MPI_Irecv
For asynchronous communication in MPI which of the following is better (in terms of performance, reliability, readability, etc.):

MPI_Isend with buffer and then MPI_Iprobe & MPI_Recv once the receiver is ready, or

MPI_Irecv with buffer (such that there is always and MPI_Irecv posted with sufficient buffer) and then MPI_Send when the sender is ready?

The communication scenario is that data has to be exchanged asynchronously and the arrival times do not matter and both processes have workload. Only the overall performance (especially no blocking) is considered.

Below is a minimal working example (I did not include workload and the timings are thus probably not meaningful).

```<code>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char const *argv[]) {
  MPI_Init(NULL, NULL);
  int world_size, world_rank;

  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

  if (world_rank == 0 && world_size != 2) {
    fprintf(stderr, "This example requires two MPI processes.\n");
    MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
  }

  /* Non Blocking Send */
  int buf[100] = {0};

  MPI_Barrier(MPI_COMM_WORLD);
  double time = MPI_Wtime();
  if (world_rank == 1) {
    MPI_Request request;
    MPI_Isend(buf, 100, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
    MPI_Wait(&request, MPI_STATUS_IGNORE);
  } else {
    MPI_Recv(buf, 100, MPI_INT, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  }
  time = MPI_Wtime() - time;
  printf("rank = %d, time = %f sec\n", world_rank, time);
  MPI_Barrier(MPI_COMM_WORLD);

  usleep(100);
  if (world_rank == 0) {
    printf("---\n");
  }

  /* Non Blocking Receive */
  MPI_Barrier(MPI_COMM_WORLD);
  time = MPI_Wtime();
  if (world_rank == 1) {
    MPI_Send(buf, 100, MPI_INT, 0, 0, MPI_COMM_WORLD);
  } else {
    MPI_Request request;
    MPI_Irecv(buf, 100, MPI_INT, 1, 0, MPI_COMM_WORLD, &request);
    MPI_Wait(&request, MPI_STATUS_IGNORE);
  }
  time = MPI_Wtime() - time;
  printf("rank = %d, time = %f sec\n", world_rank, time);
  MPI_Barrier(MPI_COMM_WORLD);

  MPI_Finalize();
  return 0;
}
</code>```

On my machine this generates:

```<code>rank = 0, time = 0.000035 sec
rank = 1, time = 0.000036 sec
---
rank = 0, time = 0.000035 sec
rank = 1, time = 0.000026 sec
</code>```

Thank you already for your answers and have a nice day :)

答:
A general rule of thumb is to:

Receive data, in a buffer. This action is quick but you might wait for the message to arrive,

Send some data, in a buffer again; which is a long step.

Doing it the other around is not bad, however, you could overlap the sending and receiving better.

For this reason, one should go for the second case scenario you describe. Also, if you do not use non-blocking communication, be careful of deadlocks. For deadlocks, see MPI Send and receive questions.

Exercise for the reader:

In the following fragments assume that all buffers have been allocated with sufficient size. Moreover, rank and size denote the rank of each process and the total number of MPI processes, respectively.
For each fragment note whether it deadlocks or not and explain why. Report performance issues.

snippet 1:

```<code>int ireq = 0;
for (int p=0; p<size; p++)
if (p!=rank)
MPI_Isend(sbuffers[p],buflen,MPI_INT,p,0,comm,&(reqs[ireq++]));
for (int p=0; p<size; p++)
if (p!=rank)
MPI_Recv(rbuffer,buflen,MPI_INT,p,0,comm,MPI_STATUS_IGNORE);
MPI_Waitall(size-1,reqs,MPI_STATUSES_IGNORE);
</code>```

snippet 2:

```<code>int ireq = 0;
for (int p=0; p<size; p++)
if (p!=rank)
MPI_Irecv(rbuffers[p],buflen,MPI_INT,p,0,comm,&(reqs[ireq++]));
MPI_Waitall(size-1,reqs,MPI_STATUSES_IGNORE);
for (int p=0; p<size; p++)
if (p!=rank)
MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm);
</code>```

Solution:

  The snippet 1 suffers from performance issue, invert recv and send.

  The snippet 2 has a deadlock due to Waitall.

Body:
For asynchronous communication in MPI which of the following is better (in terms of performance, reliability, readability, etc.):

MPI_Isend with buffer and then MPI_Iprobe & MPI_Recv once the receiver is ready, or

MPI_Irecv with buffer (such that there is always and MPI_Irecv posted with sufficient buffer) and then MPI_Send when the sender is ready?

The communication scenario is that data has to be exchanged asynchronously and the arrival times do not matter and both processes have workload. Only the overall performance (especially no blocking) is considered.

Below is a minimal working example (I did not include workload and the timings are thus probably not meaningful).

#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char const *argv[]) {
  MPI_Init(NULL, NULL);
  int world_size, world_rank;

  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

  if (world_rank == 0 && world_size != 2) {
    fprintf(stderr, "This example requires two MPI processes.\n");
    MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
  }

  /* Non Blocking Send */
  int buf[100] = {0};

  MPI_Barrier(MPI_COMM_WORLD);
  double time = MPI_Wtime();
  if (world_rank == 1) {
    MPI_Request request;
    MPI_Isend(buf, 100, MPI_INT, 0, 0, MPI_COMM_WORLD, &request);
    MPI_Wait(&request, MPI_STATUS_IGNORE);
  } else {
    MPI_Recv(buf, 100, MPI_INT, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  }
  time = MPI_Wtime() - time;
  printf("rank = %d, time = %f sec\n", world_rank, time);
  MPI_Barrier(MPI_COMM_WORLD);

  usleep(100);
  if (world_rank == 0) {
    printf("---\n");
  }

  /* Non Blocking Receive */
  MPI_Barrier(MPI_COMM_WORLD);
  time = MPI_Wtime();
  if (world_rank == 1) {
    MPI_Send(buf, 100, MPI_INT, 0, 0, MPI_COMM_WORLD);
  } else {
    MPI_Request request;
    MPI_Irecv(buf, 100, MPI_INT, 1, 0, MPI_COMM_WORLD, &request);
    MPI_Wait(&request, MPI_STATUS_IGNORE);
  }
  time = MPI_Wtime() - time;
  printf("rank = %d, time = %f sec\n", world_rank, time);
  MPI_Barrier(MPI_COMM_WORLD);

  MPI_Finalize();
  return 0;
}

On my machine this generates:

rank = 0, time = 0.000035 sec
rank = 1, time = 0.000036 sec
---
rank = 0, time = 0.000035 sec
rank = 1, time = 0.000026 sec

Thank you already for your answers and have a nice day :)

Body:
A general rule of thumb is to:

Receive data, in a buffer. This action is quick but you might wait for the message to arrive,

Send some data, in a buffer again; which is a long step.

Doing it the other around is not bad, however, you could overlap the sending and receiving better.

For this reason, one should go for the second case scenario you describe. Also, if you do not use non-blocking communication, be careful of deadlocks. For deadlocks, see MPI Send and receive questions.

Exercise for the reader:

In the following fragments assume that all buffers have been allocated with sufficient size. Moreover, rank and size denote the rank of each process and the total number of MPI processes, respectively.
For each fragment note whether it deadlocks or not and explain why. Report performance issues.

snippet 1:

int ireq = 0;
for (int p=0; p<size; p++)
if (p!=rank)
MPI_Isend(sbuffers[p],buflen,MPI_INT,p,0,comm,&(reqs[ireq++]));
for (int p=0; p<size; p++)
if (p!=rank)
MPI_Recv(rbuffer,buflen,MPI_INT,p,0,comm,MPI_STATUS_IGNORE);
MPI_Waitall(size-1,reqs,MPI_STATUSES_IGNORE);

snippet 2:

int ireq = 0;
for (int p=0; p<size; p++)
if (p!=rank)
MPI_Irecv(rbuffers[p],buflen,MPI_INT,p,0,comm,&(reqs[ireq++]));
MPI_Waitall(size-1,reqs,MPI_STATUSES_IGNORE);
for (int p=0; p<size; p++)
if (p!=rank)
MPI_Send(sbuffer,buflen,MPI_INT,p,0,comm);

Solution:

  The snippet 1 suffers from performance issue, invert recv and send.

  The snippet 2 has a deadlock due to Waitall.