问:
Why it's throwing error while setting up Eureka configuration in application.yml?
I am new to microservices where I have to use two services (which I have made in separate projects). And now I am trying to set up Eureka configuration in my application.yml file :

But it's throwing errors as can be seen in the screenshot above:

```<code>Nested mappings are not allowed in compact mapping
</code>```

and

```<code>Multiple markers at this line:
- Nested mappings are not allowed in compact mapping
- Implicit keys need to be on a single line
</code>```

Additionally, I tried with

I am sharing my EServerApplication.java code below:

```<code>package com.eserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EServerApplication {

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

}
</code>```

and below is my pom.xml file contents:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.eserver</groupId>
    <artifactId>e_server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>e_server</name>
    <description>This is a microservice for eureka server</description>
    <properties>
        <java.version>11</java.version>
        <spring-cloud.version>2021.0.0</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

But, when I do configure the same thing in application.properties file, it works well.

and below is the console output:

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.3)

2022-01-27 14:52:11.965  INFO 14444 --- [           main] com.eserver.EServerApplication           : Starting EServerApplication using Java 17.0.1 on SHAHFAISALKHAN with PID 14444 (C:\Users\shahf\Documents\workspace-spring-tool-suite-4-4.13.0.RELEASE\e_server\target\classes started by shahf in C:\Users\shahf\Documents\workspace-spring-tool-suite-4-4.13.0.RELEASE\e_server)
2022-01-27 14:52:11.970  INFO 14444 --- [           main] com.eserver.EServerApplication           : No active profile set, falling back to default profiles: default
2022-01-27 14:52:13.550  INFO 14444 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=0f4543fa-8866-3a60-8d6e-f4ead7a36662
2022-01-27 14:52:13.981  INFO 14444 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8761 (http)
2022-01-27 14:52:13.993  INFO 14444 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-01-27 14:52:13.993  INFO 14444 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-01-27 14:52:14.275  INFO 14444 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-01-27 14:52:14.275  INFO 14444 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2203 ms
2022-01-27 14:52:15.013  INFO 14444 --- [           main] c.s.j.s.i.a.WebApplicationImpl           : Initiating Jersey application, version 'Jersey: 1.19.4 05/24/2017 03:20 PM'
2022-01-27 14:52:15.089  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2022-01-27 14:52:15.091  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2022-01-27 14:52:15.299  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2022-01-27 14:52:15.300  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2022-01-27 14:52:19.162  INFO 14444 --- [           main] DiscoveryClientOptionalArgsConfiguration : Eureka HTTP Client uses Jersey
2022-01-27 14:52:19.326  WARN 14444 --- [           main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with the default cache. You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
2022-01-27 14:52:19.393  INFO 14444 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2022-01-27 14:52:19.494  INFO 14444 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2022-01-27 14:52:19.495  INFO 14444 --- [           main] com.netflix.discovery.DiscoveryClient    : Client configured to neither register nor query for data.
2022-01-27 14:52:19.525  INFO 14444 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1643275339522 with initial instances count: 0
2022-01-27 14:52:19.657  INFO 14444 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initializing ...
2022-01-27 14:52:19.665  INFO 14444 --- [           main] c.n.eureka.cluster.PeerEurekaNodes       : Adding new peer nodes [http://localhost:8761/eureka/]
2022-01-27 14:52:20.036  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2022-01-27 14:52:20.036  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2022-01-27 14:52:20.036  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2022-01-27 14:52:20.036  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2022-01-27 14:52:20.177  INFO 14444 --- [on(3)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-27 14:52:20.178  INFO 14444 --- [on(3)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-01-27 14:52:20.333  INFO 14444 --- [           main] c.n.eureka.cluster.PeerEurekaNodes       : Replica node URL:  http://localhost:8761/eureka/
2022-01-27 14:52:20.377  INFO 14444 --- [           main] c.n.e.registry.AbstractInstanceRegistry  : Finished initializing remote region registries. All known remote regions: []
2022-01-27 14:52:20.386  INFO 14444 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initialized
2022-01-27 14:52:20.396  INFO 14444 --- [on(3)-127.0.0.1] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2022-01-27 14:52:20.408  INFO 14444 --- [on(3)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 230 ms
2022-01-27 14:52:20.547  INFO 14444 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application UNKNOWN with eureka with status UP
2022-01-27 14:52:20.551  INFO 14444 --- [       Thread-9] o.s.c.n.e.server.EurekaServerBootstrap   : Setting the eureka configuration..
2022-01-27 14:52:20.567  INFO 14444 --- [       Thread-9] o.s.c.n.e.server.EurekaServerBootstrap   : isAws returned false
2022-01-27 14:52:20.568  INFO 14444 --- [       Thread-9] o.s.c.n.e.server.EurekaServerBootstrap   : Initialized server context
2022-01-27 14:52:20.568  INFO 14444 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Got 1 instances from neighboring DS node
2022-01-27 14:52:20.569  INFO 14444 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Renew threshold is: 1
2022-01-27 14:52:20.570  INFO 14444 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Changing status to UP
2022-01-27 14:52:20.606  INFO 14444 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8761 (http) with context path ''
2022-01-27 14:52:20.607  INFO 14444 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8761
2022-01-27 14:52:20.692  INFO 14444 --- [       Thread-9] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2022-01-27 14:52:21.438  INFO 14444 --- [           main] com.eserver.EServerApplication           : Started EServerApplication in 11.215 seconds (JVM running for 12.441)
2022-01-27 14:53:20.580  INFO 14444 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
2022-01-27 14:54:20.579  INFO 14444 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
</code>```

Please guide me how can I can I fix the application.yml error.

EDIT: [SOLVED]

I found that this yml configuration file is sensitive to white-space of each components and hence I corrected it in my program. Closing the thread now!

答:
yaml files follow a different naming convention. The following properties should resolve your issue.</p>
```<code>eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
  server:
    wait-time-in-ms-when-sync-empty: 0
</code>```

Body:
I am new to microservices where I have to use two services (which I have made in separate projects). And now I am trying to set up Eureka configuration in my application.yml file :

But it's throwing errors as can be seen in the screenshot above:

Nested mappings are not allowed in compact mapping

and

Multiple markers at this line:
- Nested mappings are not allowed in compact mapping
- Implicit keys need to be on a single line

Additionally, I tried with

I am sharing my EServerApplication.java code below:

package com.eserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EServerApplication {

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

}

and below is my pom.xml file contents:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/>
    </parent>
    <groupId>com.eserver</groupId>
    <artifactId>e_server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>e_server</name>
    <description>This is a microservice for eureka server</description>
    <properties>
        <java.version>11</java.version>
        <spring-cloud.version>2021.0.0</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

But, when I do configure the same thing in application.properties file, it works well.

and below is the console output:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.3)

2022-01-27 14:52:11.965  INFO 14444 --- [           main] com.eserver.EServerApplication           : Starting EServerApplication using Java 17.0.1 on SHAHFAISALKHAN with PID 14444 (C:\Users\shahf\Documents\workspace-spring-tool-suite-4-4.13.0.RELEASE\e_server\target\classes started by shahf in C:\Users\shahf\Documents\workspace-spring-tool-suite-4-4.13.0.RELEASE\e_server)
2022-01-27 14:52:11.970  INFO 14444 --- [           main] com.eserver.EServerApplication           : No active profile set, falling back to default profiles: default
2022-01-27 14:52:13.550  INFO 14444 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=0f4543fa-8866-3a60-8d6e-f4ead7a36662
2022-01-27 14:52:13.981  INFO 14444 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8761 (http)
2022-01-27 14:52:13.993  INFO 14444 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-01-27 14:52:13.993  INFO 14444 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-01-27 14:52:14.275  INFO 14444 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-01-27 14:52:14.275  INFO 14444 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2203 ms
2022-01-27 14:52:15.013  INFO 14444 --- [           main] c.s.j.s.i.a.WebApplicationImpl           : Initiating Jersey application, version 'Jersey: 1.19.4 05/24/2017 03:20 PM'
2022-01-27 14:52:15.089  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2022-01-27 14:52:15.091  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2022-01-27 14:52:15.299  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2022-01-27 14:52:15.300  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2022-01-27 14:52:19.162  INFO 14444 --- [           main] DiscoveryClientOptionalArgsConfiguration : Eureka HTTP Client uses Jersey
2022-01-27 14:52:19.326  WARN 14444 --- [           main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with the default cache. You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
2022-01-27 14:52:19.393  INFO 14444 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2022-01-27 14:52:19.494  INFO 14444 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2022-01-27 14:52:19.495  INFO 14444 --- [           main] com.netflix.discovery.DiscoveryClient    : Client configured to neither register nor query for data.
2022-01-27 14:52:19.525  INFO 14444 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1643275339522 with initial instances count: 0
2022-01-27 14:52:19.657  INFO 14444 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initializing ...
2022-01-27 14:52:19.665  INFO 14444 --- [           main] c.n.eureka.cluster.PeerEurekaNodes       : Adding new peer nodes [http://localhost:8761/eureka/]
2022-01-27 14:52:20.036  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2022-01-27 14:52:20.036  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2022-01-27 14:52:20.036  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2022-01-27 14:52:20.036  INFO 14444 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2022-01-27 14:52:20.177  INFO 14444 --- [on(3)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-27 14:52:20.178  INFO 14444 --- [on(3)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-01-27 14:52:20.333  INFO 14444 --- [           main] c.n.eureka.cluster.PeerEurekaNodes       : Replica node URL:  http://localhost:8761/eureka/
2022-01-27 14:52:20.377  INFO 14444 --- [           main] c.n.e.registry.AbstractInstanceRegistry  : Finished initializing remote region registries. All known remote regions: []
2022-01-27 14:52:20.386  INFO 14444 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initialized
2022-01-27 14:52:20.396  INFO 14444 --- [on(3)-127.0.0.1] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2022-01-27 14:52:20.408  INFO 14444 --- [on(3)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 230 ms
2022-01-27 14:52:20.547  INFO 14444 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application UNKNOWN with eureka with status UP
2022-01-27 14:52:20.551  INFO 14444 --- [       Thread-9] o.s.c.n.e.server.EurekaServerBootstrap   : Setting the eureka configuration..
2022-01-27 14:52:20.567  INFO 14444 --- [       Thread-9] o.s.c.n.e.server.EurekaServerBootstrap   : isAws returned false
2022-01-27 14:52:20.568  INFO 14444 --- [       Thread-9] o.s.c.n.e.server.EurekaServerBootstrap   : Initialized server context
2022-01-27 14:52:20.568  INFO 14444 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Got 1 instances from neighboring DS node
2022-01-27 14:52:20.569  INFO 14444 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Renew threshold is: 1
2022-01-27 14:52:20.570  INFO 14444 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Changing status to UP
2022-01-27 14:52:20.606  INFO 14444 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8761 (http) with context path ''
2022-01-27 14:52:20.607  INFO 14444 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8761
2022-01-27 14:52:20.692  INFO 14444 --- [       Thread-9] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2022-01-27 14:52:21.438  INFO 14444 --- [           main] com.eserver.EServerApplication           : Started EServerApplication in 11.215 seconds (JVM running for 12.441)
2022-01-27 14:53:20.580  INFO 14444 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
2022-01-27 14:54:20.579  INFO 14444 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms

Please guide me how can I can I fix the application.yml error.

EDIT: [SOLVED]

I found that this yml configuration file is sensitive to white-space of each components and hence I corrected it in my program. Closing the thread now!

Body:
yaml files follow a different naming convention. The following properties should resolve your issue.

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
  server:
    wait-time-in-ms-when-sync-empty: 0


来源: stackexchange

问:
"itemSlotRectTransform" is a variable but is used like a type?
I'm following a tutorial to make an inventory (this one to be exact link to video)
a line in the code goes as follows:

```<code>RectTransform itemSlotRectTransform = Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<itemSlotRectTransform>();
</code>```

i get the error

```<code>"itemSlotRectTransform" is a variable
but is used like a type.
</code>```

nobody else seems to get this error.

For reference, here is the full bloc of code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InventoryUI : MonoBehaviour
{
    private Inventory inventory;
    private Transform itemSlotContainer;
    private Transform itemSlotTemplate;

    private void Awake()
    {
        itemSlotContainer = transform.Find("itemSlotContainer");
        itemSlotTemplate = transform.Find("itemSlotTemplate");
    }

    public void SetInventory(Inventory inventory)
    {
        this.inventory = inventory;
        RefreshInventoryItems();
    }

    private void RefreshInventoryItems()
    {
        int x = 0;
        int y = 0;
        float itemSlotCellSize = 30f;
        foreach (Item item in inventory.GetItemList())
        {
            RectTransform itemSlotRectTransform =
                Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<itemSlotRectTransform>();

            itemSlotRectTransform.gameObject.SetActive(true);

            itemSlotRectTransform.anchoredPosition =
                new Vector2(x * itemSlotCellSize, y * itemSlotCellSize);
            x++;
            if(x > 4)
            {
                x = 0;
                y++;
            }
        }
    }
}
</code>```

if you could help I'd much appreciate!

答:
Generic arguments must be types whereas you specified an instance of a type.

Try this instead:

Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<RectTransform>()

Notice the argument in angle brackets.

ContentLicense: CC BY-SA 4.0

Body:
I'm following a tutorial to make an inventory (this one to be exact link to video)
a line in the code goes as follows:

RectTransform itemSlotRectTransform = Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<itemSlotRectTransform>();

i get the error

"itemSlotRectTransform" is a variable
but is used like a type.

nobody else seems to get this error.

For reference, here is the full bloc of code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InventoryUI : MonoBehaviour
{
    private Inventory inventory;
    private Transform itemSlotContainer;
    private Transform itemSlotTemplate;

    private void Awake()
    {
        itemSlotContainer = transform.Find("itemSlotContainer");
        itemSlotTemplate = transform.Find("itemSlotTemplate");
    }

    public void SetInventory(Inventory inventory)
    {
        this.inventory = inventory;
        RefreshInventoryItems();
    }

    private void RefreshInventoryItems()
    {
        int x = 0;
        int y = 0;
        float itemSlotCellSize = 30f;
        foreach (Item item in inventory.GetItemList())
        {
            RectTransform itemSlotRectTransform =
                Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<itemSlotRectTransform>();

            itemSlotRectTransform.gameObject.SetActive(true);

            itemSlotRectTransform.anchoredPosition =
                new Vector2(x * itemSlotCellSize, y * itemSlotCellSize);
            x++;
            if(x > 4)
            {
                x = 0;
                y++;
            }
        }
    }
}

if you could help I'd much appreciate!


问:
How to join same table on multiple columns?
What would be the best way to JOIN a table based on whether join column is NULL or not.

I need to JOIN table #main with table #sub.

For example:

if ID column in table #main is NULL then join on column LocationID = #sub.LocationID

if ID and LocationID columns in table #main is NULLs then join on column UserID = #sub.UserID

```<code>create table #main (ID int, locationID varchar(50), UserID varchar(50))
insert into #main values (1,'Loc1',NULL),
                         (2,NULL,'User1'),
                         (NULL,'Loc1','User1'),
                         (4,'Loc1',NULL),
                         (5,NULL,'User1'),
                         (NULL,'Loc1','User1')
--select * from #main

select *
from #main m
-- if m.ID is not null then join on m.ID
-- OR if m.ID is null then join on m.locationID = s.LocationID
-- OR if m.ID is null and m.LocationID is null then join on  m.UserID = s.UserID
    left join #sub s ON  m.ID = s.ID OR m.locationID = s.LocationID OR m.UserID = s.UserID
</code>```

Thank you

答:
as an alternative to join, this can be done using outer apply with a subquery in which the matching condition is implemented via case when like this:

```<code>Select *
From #main As m Outer Apply
(Select * From #sub As s
 Where 1 = Case When m.ID Is Not Null And m.ID=s.ID Then 1
                When m.ID Is Null And m.LocationID Is Not Null And m.locationID=s.locationID Then 1
                When m.ID Is Null And m.LocationID Is Null And m.UserID Is Not Null And m.UserID=s.UserID Then 1
                Else 0
           End) As t
Order by m.ID, m.locationID, m.UserID
</code>```

Body:
What would be the best way to JOIN a table based on whether join column is NULL or not.

I need to JOIN table #main with table #sub.

For example:

if ID column in table #main is NULL then join on column LocationID = #sub.LocationID

if ID and LocationID columns in table #main is NULLs then join on column UserID = #sub.UserID

create table #main (ID int, locationID varchar(50), UserID varchar(50))
insert into #main values (1,'Loc1',NULL),
                         (2,NULL,'User1'),
                         (NULL,'Loc1','User1'),
                         (4,'Loc1',NULL),
                         (5,NULL,'User1'),
                         (NULL,'Loc1','User1')
--select * from #main

select *
from #main m
-- if m.ID is not null then join on m.ID
-- OR if m.ID is null then join on m.locationID = s.LocationID
-- OR if m.ID is null and m.LocationID is null then join on  m.UserID = s.UserID
    left join #sub s ON  m.ID = s.ID OR m.locationID = s.LocationID OR m.UserID = s.UserID

Thank you

Body:
as an alternative to join, this can be done using outer apply with a subquery in which the matching condition is implemented via case when like this:

Select *
From #main As m Outer Apply
(Select * From #sub As s
 Where 1 = Case When m.ID Is Not Null And m.ID=s.ID Then 1
                When m.ID Is Null And m.LocationID Is Not Null And m.locationID=s.locationID Then 1
                When m.ID Is Null And m.LocationID Is Null And m.UserID Is Not Null And m.UserID=s.UserID Then 1
                Else 0
           End) As t
Order by m.ID, m.locationID, m.UserID


问:
Performance of SQL inserts with Liquibase
In our project we are using Liquibase 4.6.1 and install the cumulative (initial) state of DB and test data within SQL scripts with many INSERTs.
We do an installation for MySQL and for Oracle, for MySQL it is Okay, we use multiple inserts like:

```<code>INSERT INTO `${schema-user.name}`.`TABLE`
( `FIELD_1`, ...,  `FIELD_N` )
VALUES
( 0, ..., 0 ),
( 99, ..., 99 );
</code>```

That is why an installation of a schema A is about 5 seconds on local PC with MySQL instance in a docker container.

However, there is no multiple insert command for Oracle, so generally we just do inserting one by one. And that is quite painful: on the same PC, with an Oracle instance inside a container it's about 30 secs.

From what I have tried:

INSERT ALL

```<code>INSERT ALL
    INTO "${schema-user.name}".TABLE (FIELD_1,..., FIELD_N)
    VALUES (1, .., N)
    ...
    INTO "${schema-user.name}".TABLE (FIELD_1,..., FIELD_N)
    VALUES (1, .., N)
SELECT 1 FROM DUAL
/
</code>```

SELECT WITH:

```<code>insert /*+ APPEND NOLOGGING */ into "${schema-user.name}".TABLE (FIELD_1,..., FIELD_N)
with vals as (
    select 1, .., N from dual union all
    select 1, .., N from dual
    )
select * from vals
/
</code>```

The approaches above do not give any improvement.

The specific of schema A is what tables mostly have no any indexes/constrains except PK and there are no triggers on the tables. So I don't see here a problem of many indexes/triggers which could impact the performance.

From Liquibase's logs I see, that LB reads SQL file and does something quite long before it start to apply those particular INSERTs like the following:

```<code>[2022-02-10 17:56:03] FINE [liquibase.changelog] Reading ChangeSet: cumulative/cumulative.root.yml::1643287602-install-test-data-schema-a::ppraulov
[2022-02-10 17:56:03] FINE [liquibase.resource] Closing duplicate stream for file:/home/ppraulov/path/schema-a.test-data.sql
[2022-02-10 17:56:03] FINE [liquibase.configuration] No configuration value for liquibase.fileEncoding found
[2022-02-10 17:56:03] FINE [liquibase.configuration] Configuration liquibase.fileEncoding is using the default value of UTF-8
<pause some seconds>
[2022-02-10 17:53:44] FINE [liquibase.executor] Executing with the 'jdbc' executor
[2022-02-10 17:53:44] FINE [liquibase.executor] 1 row(s) affected
[2022-02-10 17:53:44] FINE [liquibase.database] Executing Statement: INSERT INTO "schema-a"."TABLE"
...
</code>```

As the last measure we have an option of installation of test data from CSV files, which is faster, however, it is still far from the desirable level of 5 secs, which we have for MySQL installation.

So my question is what would be possible ways to improve performance of installation on Oracle using SQL scripts?

答:
If you want to use Liquibase in the Oracle toolkit, e.g. SQLcl, we allow you to batchload rows to your table in a changeLog using a LOAD command, that rips through a csv file.

I talk about this in detail here

Concepts: SQLcl is free. We have taken the community edition of Liquibase, and enhanced the Oracle support. It's using the 4.6.x library, but also has access to ALL of our features in SQLcl, a more modern take on SQLPlus.

SO if you wanted to use the SQLcl (from SQL Developer) features...like generating DDL, loading rows to a table...that would look like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:n0="http://www.oracle.com/xml/ns/dbchangelog-ext"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
        http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.6.xsd">
        <changeSet id="abcd1234567890" author="Generated" failOnError="false"   runAlways="true" >
                <n0:runOracleScript objectName="MY_SCRIPT" objectType="SCRIPT" ownerName="FUNKY" sourceType="STRING" replaceIfExists="false">
                        <n0:source><![CDATA[
cd C:\liquibase\load_table
set sqlformat csv
set feedback off
spool locations.csv
select * from hr.locations;
spool off
create table locations as select * from hr.locations where 1=2;
load locations locations.csv
commit;
                        ]]></n0:source>
                </n0:runOracleScript>
        </changeSet>
</databaseChangeLog>
</code>```

And it's batching the rows via JDBC, will be MUCH faster than row-by-row inserts.

Disclaimer: I'm a product manager at Oracle and SQLcl is one of my products.

Body:
In our project we are using Liquibase 4.6.1 and install the cumulative (initial) state of DB and test data within SQL scripts with many INSERTs.
We do an installation for MySQL and for Oracle, for MySQL it is Okay, we use multiple inserts like:

INSERT INTO `${schema-user.name}`.`TABLE`
( `FIELD_1`, ...,  `FIELD_N` )
VALUES
( 0, ..., 0 ),
( 99, ..., 99 );

That is why an installation of a schema A is about 5 seconds on local PC with MySQL instance in a docker container.

However, there is no multiple insert command for Oracle, so generally we just do inserting one by one. And that is quite painful: on the same PC, with an Oracle instance inside a container it's about 30 secs.

From what I have tried:

INSERT ALL

INSERT ALL
    INTO "${schema-user.name}".TABLE (FIELD_1,..., FIELD_N)
    VALUES (1, .., N)
    ...
    INTO "${schema-user.name}".TABLE (FIELD_1,..., FIELD_N)
    VALUES (1, .., N)
SELECT 1 FROM DUAL
/

SELECT WITH:

insert /*+ APPEND NOLOGGING */ into "${schema-user.name}".TABLE (FIELD_1,..., FIELD_N)
with vals as (
    select 1, .., N from dual union all
    select 1, .., N from dual
    )
select * from vals
/

The approaches above do not give any improvement.

The specific of schema A is what tables mostly have no any indexes/constrains except PK and there are no triggers on the tables. So I don't see here a problem of many indexes/triggers which could impact the performance.

From Liquibase's logs I see, that LB reads SQL file and does something quite long before it start to apply those particular INSERTs like the following:

[2022-02-10 17:56:03] FINE [liquibase.changelog] Reading ChangeSet: cumulative/cumulative.root.yml::1643287602-install-test-data-schema-a::ppraulov
[2022-02-10 17:56:03] FINE [liquibase.resource] Closing duplicate stream for file:/home/ppraulov/path/schema-a.test-data.sql
[2022-02-10 17:56:03] FINE [liquibase.configuration] No configuration value for liquibase.fileEncoding found
[2022-02-10 17:56:03] FINE [liquibase.configuration] Configuration liquibase.fileEncoding is using the default value of UTF-8
<pause some seconds>
[2022-02-10 17:53:44] FINE [liquibase.executor] Executing with the 'jdbc' executor
[2022-02-10 17:53:44] FINE [liquibase.executor] 1 row(s) affected
[2022-02-10 17:53:44] FINE [liquibase.database] Executing Statement: INSERT INTO "schema-a"."TABLE"
...

As the last measure we have an option of installation of test data from CSV files, which is faster, however, it is still far from the desirable level of 5 secs, which we have for MySQL installation.

So my question is what would be possible ways to improve performance of installation on Oracle using SQL scripts?

Body:
If you want to use Liquibase in the Oracle toolkit, e.g. SQLcl, we allow you to batchload rows to your table in a changeLog using a LOAD command, that rips through a csv file.

I talk about this in detail here

Concepts: SQLcl is free. We have taken the community edition of Liquibase, and enhanced the Oracle support. It's using the 4.6.x library, but also has access to ALL of our features in SQLcl, a more modern take on SQLPlus.

SO if you wanted to use the SQLcl (from SQL Developer) features...like generating DDL, loading rows to a table...that would look like this:

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:n0="http://www.oracle.com/xml/ns/dbchangelog-ext"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
        http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.6.xsd">
        <changeSet id="abcd1234567890" author="Generated" failOnError="false"   runAlways="true" >
                <n0:runOracleScript objectName="MY_SCRIPT" objectType="SCRIPT" ownerName="FUNKY" sourceType="STRING" replaceIfExists="false">
                        <n0:source><![CDATA[
cd C:\liquibase\load_table
set sqlformat csv
set feedback off
spool locations.csv
select * from hr.locations;
spool off
create table locations as select * from hr.locations where 1=2;
load locations locations.csv
commit;
                        ]]></n0:source>
                </n0:runOracleScript>
        </changeSet>
</databaseChangeLog>

And it's batching the rows via JDBC, will be MUCH faster than row-by-row inserts.

Disclaimer: I'm a product manager at Oracle and SQLcl is one of my products.


问:
Pandas Drop Rows when Exactly Matching Items from a List
I'm trying to drop rows in a pandas dataframe on an exact match. My code nearly works, but it currently drops rows which match partially (which I don't want).

The code below will drop the name 'Krish' from the dataframe because it partially matches to 'kris'.

```<code>import pandas as pd

# list of strings to drop in an exact match
drop_list = ["nick", "kris"]

# initialize data of lists.
data = {'Name': ['Tom', 'nick', 'krish', 'jack'],
        'Age': [20, 21, 19, 18]}

# Create DataFrame
df = pd.DataFrame(data)

df = df[~df['Name'].str.contains("|".join(drop_list))]

# print dataframe.
print(df)
</code>```

Current Output:

```<code>   Name  Age
0   Tom   20
3  jack   18
</code>```

Desired Output:

```<code>    Name  Age
0    Tom   20
2  krish   19
3   jack   18
</code>```

答:
Use isin:

```<code>df = df[~df['Name'].isin(drop_list)]
</code>```

Output:

```<code>>>> df
    Name  Age
0    Tom   20
2  krish   19
3   jack   18
</code>```

Body:
I'm trying to drop rows in a pandas dataframe on an exact match. My code nearly works, but it currently drops rows which match partially (which I don't want).

The code below will drop the name 'Krish' from the dataframe because it partially matches to 'kris'.

import pandas as pd

# list of strings to drop in an exact match
drop_list = ["nick", "kris"]

# initialize data of lists.
data = {'Name': ['Tom', 'nick', 'krish', 'jack'],
        'Age': [20, 21, 19, 18]}

# Create DataFrame
df = pd.DataFrame(data)

df = df[~df['Name'].str.contains("|".join(drop_list))]

# print dataframe.
print(df)

Current Output:

   Name  Age
0   Tom   20
3  jack   18

Desired Output:

    Name  Age
0    Tom   20
2  krish   19
3   jack   18

Body:
Use isin:

df = df[~df['Name'].isin(drop_list)]

Output:

>>> df
    Name  Age
0    Tom   20
2  krish   19
3   jack   18


问:
select * only return one value
I want select multiple (all) values from table Account.

```<code>string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();
</code>```

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

答:
You need to loop, something like this:

```<code>SqlDataReader reader = command.ExecuteReader();

// Call Read before accessing data.
while (reader.Read())
{
    Console.WriteLine(String.Format("{0}, {1}",
        reader[0], reader[1]));
}
</code>```

There is an example in the MSDN docs:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx

ContentLicense: CC BY-SA 3.0

Title: select * only return one value

Body:
I want select multiple (all) values from table Account.

string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

Body:
You need to loop, something like this:

SqlDataReader reader = command.ExecuteReader();

// Call Read before accessing data.
while (reader.Read())
{
    Console.WriteLine(String.Format("{0}, {1}",
        reader[0], reader[1]));
}

There is an example in the MSDN docs:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx


问:
How do I find image base address of a process from a crash dump in Windbg
I have a memory crash dump, and I can list processes with !process 0 0

What I want to do is find the Image Base Address of calc.exe and get its contents from the memory. Potentially saving it into a file.

what do I need to do to achieve that?

Edit: the type of dump I have is "automatic dump" but I would like to know the technique for other types such as full core dump

答:
a dump can be of several types
what is the type of dump is it user mode or kernel mode  ?
it is mindump of full dump ?

in many cases the pages may not be present either being paged out or intentionally discarded init section of modules

anyway
if user mode try !vadump or !address to locate the module of interest find its start address and end address and try dumping in page size increments (0x1000 bytes )using .writemem

in kmode use !vad

and follow both commands by lm or !dh to get the module information in both user mode and kernelmode

here is an user mode dump !address info

```<code>F:\caldump>cdb -c "!address calculator;q" -z calc.dmp | awk "/Reading/,/quit/"

0:023> cdb: Reading initial command '!address calculator;q'

Usage:                  Image
Base Address:           00007ff7`04a30000
End Address:            00007ff7`04a31000
Region Size:            00000000`00001000 (   4.000 kB)
State:                  00001000          MEM_COMMIT
Protect:                00000002          PAGE_READONLY
Type:                   01000000          MEM_IMAGE
Allocation Base:        00007ff7`04a30000
Allocation Protect:     00000080          PAGE_EXECUTE_WRITECOPY
Image Path:             C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.1906.55.0_x64__8wekyb3d8bbwe\Calculator.exe
Module Name:            Calculator
Loaded Image Name:
Mapped Image Name:
More info:              lmv m Calculator
More info:              !lmi Calculator
More info:              ln 0x7ff704a30000
More info:              !dh 0x7ff704a30000
</code>```

Body:
a dump can be of several types
what is the type of dump is it user mode or kernel mode  ?
it is mindump of full dump ?

in many cases the pages may not be present either being paged out or intentionally discarded init section of modules

anyway
if user mode try !vadump or !address to locate the module of interest find its start address and end address and try dumping in page size increments (0x1000 bytes )using .writemem

in kmode use !vad

and follow both commands by lm or !dh to get the module information in both user mode and kernelmode

here is an user mode dump !address info

F:\caldump>cdb -c "!address calculator;q" -z calc.dmp | awk "/Reading/,/quit/"

0:023> cdb: Reading initial command '!address calculator;q'

Usage:                  Image
Base Address:           00007ff7`04a30000
End Address:            00007ff7`04a31000
Region Size:            00000000`00001000 (   4.000 kB)
State:                  00001000          MEM_COMMIT
Protect:                00000002          PAGE_READONLY
Type:                   01000000          MEM_IMAGE
Allocation Base:        00007ff7`04a30000
Allocation Protect:     00000080          PAGE_EXECUTE_WRITECOPY
Image Path:             C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.1906.55.0_x64__8wekyb3d8bbwe\Calculator.exe
Module Name:            Calculator
Loaded Image Name:
Mapped Image Name:
More info:              lmv m Calculator
More info:              !lmi Calculator
More info:              ln 0x7ff704a30000
More info:              !dh 0x7ff704a30000


问:
Why does "Get-PowerBIDataset" Powershell command gives me all the datasets in the Workspace?
I am working on some automation. I am using command Power BI Powershell commands. One of the Powershell commands I am using is "Get-PowerBIDataset". It's supposed to return Dataset ID (i.e. GUID) when Dataset name provided but it gives me all the datasets under that workspace.

Below is the pseudo code as I am working on client machine. The workspace is say "WS - ABC" and the Dataset under it are "DS-XYZ", "DS-XYZ1" and "DS-XYZ2". I only want Id for Dataset name provided in the command.

```<code>#Connect using Service Principal
Connect-PowerBIServiceAccount -ServicePrincipal ####

#Get Workspace details
$Workspace = Get-PowerBIWorkspace -Name 'WS - ABC'
Write-Output $Workspace.Id ## Works correctly and gives me GUID only for 'WS - ABC'

#Get Dataset details
$Dataset = Get-PowerBIDataset -Name 'DS-XYZ' -WorkspaceId $Workspace.Id
Write-Output $Dataset.Id ## Works incorrectly and gives me GUIDs for all the 3 Datasets in the Workspace.
</code>```

Any idea what I am missing here?

答:
You need to use Where-Object:</p>
```<code>$Dataset = Get-PowerBIDataset -WorkspaceId $Workspace.Id | Where-Object {$_.name -eq 'DS-XYZ'}
</code>```

Body:
I am working on some automation. I am using command Power BI Powershell commands. One of the Powershell commands I am using is "Get-PowerBIDataset". It's supposed to return Dataset ID (i.e. GUID) when Dataset name provided but it gives me all the datasets under that workspace.

Below is the pseudo code as I am working on client machine. The workspace is say "WS - ABC" and the Dataset under it are "DS-XYZ", "DS-XYZ1" and "DS-XYZ2". I only want Id for Dataset name provided in the command.

#Connect using Service Principal
Connect-PowerBIServiceAccount -ServicePrincipal ####

#Get Workspace details
$Workspace = Get-PowerBIWorkspace -Name 'WS - ABC'
Write-Output $Workspace.Id ## Works correctly and gives me GUID only for 'WS - ABC'

#Get Dataset details
$Dataset = Get-PowerBIDataset -Name 'DS-XYZ' -WorkspaceId $Workspace.Id
Write-Output $Dataset.Id ## Works incorrectly and gives me GUIDs for all the 3 Datasets in the Workspace.

Any idea what I am missing here?

Body:
You need to use Where-Object:

$Dataset = Get-PowerBIDataset -WorkspaceId $Workspace.Id | Where-Object {$_.name -eq 'DS-XYZ'}


问:
Permission error when creating Flutter project
I am new to Flutter, and after installing it, I got this error when I tried to create a project.

```<code>[hello_world] flutter create --ios-language swift --android-language kotlin .
Failed to open or create the artifact cache lockfile: "FileSystemException: Cannot open file, path = '/home/raphael/flutter/flutter/bin/cache/lockfile' (OS Error: Permission denied, errno = 13)"
Please ensure you have permissions to create or open /home/raphael/flutter/flutter/bin/cache/lockfile
Failed to open or create the lockfile
exit code 1
</code>```

I can't find any way to fix this, so I'd be glad if someone helps me :)

Thank you!

答:
```<code>$ sudo chown -R <username> /Users/<username>/.config
</code>```

or this one work for me

```<code>$ sudo chmod 775 <username> /Users/<username>/.config
</code>```

For full right

```<code>$ sudo chmod 777 <username> /Users/<username>/.config
</code>```

Body:
I am new to Flutter, and after installing it, I got this error when I tried to create a project.

[hello_world] flutter create --ios-language swift --android-language kotlin .
Failed to open or create the artifact cache lockfile: "FileSystemException: Cannot open file, path = '/home/raphael/flutter/flutter/bin/cache/lockfile' (OS Error: Permission denied, errno = 13)"
Please ensure you have permissions to create or open /home/raphael/flutter/flutter/bin/cache/lockfile
Failed to open or create the lockfile
exit code 1

I can't find any way to fix this, so I'd be glad if someone helps me :)

Thank you!

Body:
$ sudo chown -R <username> /Users/<username>/.config

or this one work for me

$ sudo chmod 775 <username> /Users/<username>/.config

For full right

$ sudo chmod 777 <username> /Users/<username>/.config


问:
Importing a module which have the same name with a system module
My situation is similar to one in this question... The difference is,

In our python/django project, we have a directory called utils, which keeps basic functions...

Sometimes, we need to test some modules by running thm from console like

```<code>python myproject/some_module.py
</code>```

It is all good, until python tries to import something from our utils directory...

```<code>from utils.custom_modules import some_function
ImportError: No module named custom_modules
</code>```

I check my python path, and our project is on the list, each folder under the project file has __init__.py files, and when i run ipython within project directory... Everything is ok, otherwise, python imports from its own utils directory...

My collegues use the sama method without any problem, but it throws ImportError on my environment... What could be the problem that all of us was missing?

UPDATE: My project directory, and each sub-drectory have __init__.py file, and i can import other modules from my project without any problem... When i am in a diffrent folder than my procekt and i run ipython, a such import have no problem...

```<code>from someothermodule.submodule imprort blahblahblah
</code>```

But, when it comes to importing utils, it fails...

UPATE 2: What caused the problem was the utils directory under django folder, which is also in the python path...

答:
I'm not going to bother telling you to try and make sure you don't name your own modules after the stdlib modules;

If you want to leave the name like this, you'll have to use something like this in everything that imports your own utils module:

```<code>import sys, imp

utils = sys.modules.get('utils')
if not utils: utils = imp.load_module('utils',*imp.find_module('utils/utils'))
</code>```

However, unless there's a lot of stuff that you'd have to change after renaming it, I'd suggest you rename it.

Body:
My situation is similar to one in this question... The difference is,

In our python/django project, we have a directory called utils, which keeps basic functions...

Sometimes, we need to test some modules by running thm from console like

python myproject/some_module.py

It is all good, until python tries to import something from our utils directory...

from utils.custom_modules import some_function
ImportError: No module named custom_modules

I check my python path, and our project is on the list, each folder under the project file has __init__.py files, and when i run ipython within project directory... Everything is ok, otherwise, python imports from its own utils directory...

My collegues use the sama method without any problem, but it throws ImportError on my environment... What could be the problem that all of us was missing?

UPDATE: My project directory, and each sub-drectory have __init__.py file, and i can import other modules from my project without any problem... When i am in a diffrent folder than my procekt and i run ipython, a such import have no problem...

from someothermodule.submodule imprort blahblahblah

But, when it comes to importing utils, it fails...

UPATE 2: What caused the problem was the utils directory under django folder, which is also in the python path...

Body:
I'm not going to bother telling you to try and make sure you don't name your own modules after the stdlib modules;

If you want to leave the name like this, you'll have to use something like this in everything that imports your own utils module:

import sys, imp

utils = sys.modules.get('utils')
if not utils: utils = imp.load_module('utils',*imp.find_module('utils/utils'))

However, unless there's a lot of stuff that you'd have to change after renaming it, I'd suggest you rename it.


问:
Simple connectivity to a Gremlin DB via a Javascript Appliaction
I apologies for such a basic question, but I can't seem to figure out how to do this and the docs are all very specific.

I'm just trying to connect to a standard Gremlin DB (Cosmos) using gremlin. It works great from the server, but when I connect from the browser, I get this error:

```<code>Error: ws does not work in the browser. Browser clients must use the native WebSocket object
</code>```

Nothing terribly complicated, and the error seems to be pretty clear.

Here is the code:

```<code>     constructor() {
        var authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(`/dbs/${config.database}/colls/${config.collection}`, config.primaryKey);
        this.gremlin_config_options = {
            authenticator,
            traversalsource: "g",
            rejectUnauthorized: true,
            mimeType: "application/vnd.gremlin-v2.0+json"
        }

       var DriverRemoteConnection = Gremlin.driver.DriverRemoteConnection;
        this.Graph = Gremlin.structure.Graph;

        var dc = new DriverRemoteConnection(this.gremlin_websocket,this.gremlin_config_options);

        this.graph = new this.Graph();
        this.g = this.graph.traversal().withRemote(this.gremlin_websocket);
      };

</code>```

When I do the following code, it completes without the Javascript error.

```<code>    constructor() {
        var authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(`/dbs/${config.database}/colls/${config.collection}`, config.primaryKey);
        this.gremlin_config_options = {
            authenticator,
            traversalsource: "g",
            rejectUnauthorized: true,
            mimeType: "application/vnd.gremlin-v2.0+json"
        }

        this.Graph = Gremlin.structure.Graph;

        this.gremlin_websocket = new WebSocket('ws://test_db.gremlin.cosmos.azure.com:8182/')

        this.graph = new this.Graph();
        this.g = this.graph.traversal().withRemote(this.gremlin_websocket);
      };

</code>```

However, I need to pass along authentication and collection information (currently in the authenticator object). But WebSocket doesn't seem to support it, and Driver Remote Connection doesn't seem to natively take the websocket. What should I do?

答: Check out gremlin-browser, a JavaScript Gremlin Language Variant for the Browser based on version gremlin-js v3.5.2 and isomorphic-ws v4.0.1. Tested using Azure Cosmos DB Gremlin API 2022 :)</p>

Body:
I apologies for such a basic question, but I can't seem to figure out how to do this and the docs are all very specific.

I'm just trying to connect to a standard Gremlin DB (Cosmos) using gremlin. It works great from the server, but when I connect from the browser, I get this error:

Error: ws does not work in the browser. Browser clients must use the native WebSocket object

Nothing terribly complicated, and the error seems to be pretty clear.

Here is the code:

     constructor() {
        var authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(`/dbs/${config.database}/colls/${config.collection}`, config.primaryKey);
        this.gremlin_config_options = {
            authenticator,
            traversalsource: "g",
            rejectUnauthorized: true,
            mimeType: "application/vnd.gremlin-v2.0+json"
        }

       var DriverRemoteConnection = Gremlin.driver.DriverRemoteConnection;
        this.Graph = Gremlin.structure.Graph;

        var dc = new DriverRemoteConnection(this.gremlin_websocket,this.gremlin_config_options);

        this.graph = new this.Graph();
        this.g = this.graph.traversal().withRemote(this.gremlin_websocket);
      };

When I do the following code, it completes without the Javascript error.

    constructor() {
        var authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(`/dbs/${config.database}/colls/${config.collection}`, config.primaryKey);
        this.gremlin_config_options = {
            authenticator,
            traversalsource: "g",
            rejectUnauthorized: true,
            mimeType: "application/vnd.gremlin-v2.0+json"
        }

        this.Graph = Gremlin.structure.Graph;

        this.gremlin_websocket = new WebSocket('ws://test_db.gremlin.cosmos.azure.com:8182/')

        this.graph = new this.Graph();
        this.g = this.graph.traversal().withRemote(this.gremlin_websocket);
      };

However, I need to pass along authentication and collection information (currently in the authenticator object). But WebSocket doesn't seem to support it, and Driver Remote Connection doesn't seem to natively take the websocket. What should I do?


问:
How do I check if a string is an integer?
This is my code:</p>
```<code>lowMess=input('A\n')
if 'dice(' in lowMess:
  diceLen = len(lowMess)
  dice = []
  for x in range (5,diceLen):
    if x.isnumeric():
      dice.append(x)
print(dice)
</code>```

答:
Your x is an integer (taken from range(5, diceLen)) and has nothing to do with the input, other than that it could be used as an index in the input string. So you would want to make that access in the input string:

```<code>digit = lowMess[x]
</code>```

Then continue with the check. As noted in comments, for checking whether a character is a digit, isnumeric is not the right tool. Use isdecimal:

```<code>if digit.isdecimal():
</code>```

...and convert to integer:

```<code>  dice.append(int(digit))
</code>```

All this can be done with list comprehension:

```<code>dice = [int(digit) for digit in lowMess if digit.isdecimal()]
</code>```

Body:
This is my code:

lowMess=input('A\n')
if 'dice(' in lowMess:
  diceLen = len(lowMess)
  dice = []
  for x in range (5,diceLen):
    if x.isnumeric():
      dice.append(x)
print(dice)

Body:
Your x is an integer (taken from range(5, diceLen)) and has nothing to do with the input, other than that it could be used as an index in the input string. So you would want to make that access in the input string:

digit = lowMess[x]

Then continue with the check. As noted in comments, for checking whether a character is a digit, isnumeric is not the right tool. Use isdecimal:

if digit.isdecimal():

...and convert to integer:

  dice.append(int(digit))

All this can be done with list comprehension:

dice = [int(digit) for digit in lowMess if digit.isdecimal()]


问:
failed to copy what appear into the terminal during script execution into file
I have a script that do many action, and echo information.
I want to have a "duplicate" of all what is printed to the terminal into a file, and I want to add some information into it as well.

Problem : i can't simply piping every echo into tee because some printing are done by function that are sourced from another source file, and I can't modify them.

So I searched and I found this
redirect COPY of stdout to log file from within bash script itself

So based on that, i do the following script

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

strReportingFilepath="./reporting.log"

echo "[1] stdout : This text will not appear in the reporting file"
echo "[2] stderr : Neither this one" >&2

# We dup stdour and stderr into the reporting file (reporting fiel emptied)
exec > >(tee -i "$strReportingFilepath") 2>&1

echo "[3] stdout : This text will be on both the terminal and the reporting file"
echo "[4] stderr : This one too :)" >&2
echo "[5] stdout : Last case : this text should only appear into the reporting file" >> "$strReportingFilepath"

exit 0
</code>```

When I run this script, I have this on my terminal

```<code>(terminal info) # ./my_script.sh
[1] stdout : This text will not appear in the reporting file
[2] stderr : Neither this one
(terminal info) # [3] stdout : This text will be on both the terminal and the reporting file
[4] stderr : This one too :)
</code>```

and this into my file

```<code>(terminal info) # cat reporting.log
[3] stdout : This text will be on both the terminal and the reporting file
[4] stderr : This one too :)
</code>```

I have 2 problem :

First, for an unknow reason (I suspect that I use exec/named pipe/tee in a sloppy way), my script actually wait at the end. I have to press enter key in order to terminate the script.

Secondly, the [5] echo doesn't appear into the file.

I'm pretty sure that I mess something up with the exec line, but I can't understand what and I don't know what to do.

I added a "sync" call after the [5] echo, but it didn't work.

Well, I think I finally managed to do what I wanted.

What I want :

Having everything printed onto the screen terminal (stdout, stderr, stdin) to be "logged" into a file

Having the possibility to add text into this logging file without displaying it onto the terminal screen.

I stopped using tee, and I found a link talking about "script(8)".
After tinkering around, I ended up with this script :

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

strReportingFilepath="./reporting.log"

# Part that will do the script reporting
if [ -z "$SCRIPT" ]; then
    export SCRIPT="$0"

    # Creation of the string bash command
    strCommand="$0"
    strSearch="'"
    strReplace="'\''"
    for strArgument in "$@"; do
        strCommand+=" '${strArgument//$strSearch/$strReplace}'"
    done

    # Execution of the script
    /usr/bin/script --return --quiet --flush --append "$strReportingFilepath" --command "$strCommand"
    # We get the return
    intScriptReturnValue="$?"

    # The line automaticly added by /usr/bin/script is something that I don't want
    strTemporaryFilepath="$(mktemp)"
    grep -v '^Script started on ' "$strReportingFilepath" > "$strTemporaryFilepath"
    mv "$strTemporaryFilepath" "$strReportingFilepath"

    exit "$intScriptReturnValue"
fi

# "Start" of the script that I want "supervised"

sync
echo "[0  ] directly" >> "$strReportingFilepath"

echo "[1. ] out"

sync
echo "[1.5] directly" >> "$strReportingFilepath"

echo "[2  ] out"
echo "[3. ] err" >&2

sync
echo "[3.5] directly" >> "$strReportingFilepath"

echo "[4  ] err" >&2
echo -n "[5  ] input : "
read

echo "[6  ] out"
echo "[7  ] err" >&2
echo "      End :)"

exit 5
</code>```

Now, there are still some problem :

I really don't know what I have done, so if you're thinking about using this code as it, think about it twice.
I just know that for my case, it "seem to work" (yeepee !)

Each time I want to write something directly into the logging file, I have to call "sync" before. Without it, the line aren't in order. Please note that "sync" doesn't garanty that it's instantaneous. In the doc, they say that command like "halt" do a "sleep" after a sync in order to be sure, so it's still possible to have race condition resulting in wrong line order.

It seem that "script" doesn't work on some case, like when stdin is not a terminal. See "script(8)".

Well, sorry for this strange question, I would have bet that what I wanted to do was simple and common, turn out not really.

答:
You have a race condition; everything sent via tee is just getting buffered, and only gets written (to the terminal and disk) after the script has actually finished. Note: sync doesn't affect this, since it flushes the operating system's buffers, but tail's.

That's why you're getting a terminal prompt before line [3]:

```<code>(terminal info) # [3] stdout : This text will be on both the terminal and the reporting file
</code>```

...your shell sends the prompt for the next command (after running the script), then tee flushes everything in its buffers, so you see lines [3] and [4] after the prompt. Pressing enter after this doesn't terminate the script (it ended a while ago), it just gets you a clean shell prompt that isn't mixed up with the output.

Something similar happens with the reporting.log file. Line [5] gets written into it, and then a moment later tee writes lines [3] and [4] into  it, but since tee's output pointer is set to write to it starting at the beginning of the file, it overwrites line [5].

Body:
I have a script that do many action, and echo information.
I want to have a "duplicate" of all what is printed to the terminal into a file, and I want to add some information into it as well.

Problem : i can't simply piping every echo into tee because some printing are done by function that are sourced from another source file, and I can't modify them.

So I searched and I found this
redirect COPY of stdout to log file from within bash script itself

So based on that, i do the following script

#!/bin/bash

strReportingFilepath="./reporting.log"

echo "[1] stdout : This text will not appear in the reporting file"
echo "[2] stderr : Neither this one" >&2

# We dup stdour and stderr into the reporting file (reporting fiel emptied)
exec > >(tee -i "$strReportingFilepath") 2>&1

echo "[3] stdout : This text will be on both the terminal and the reporting file"
echo "[4] stderr : This one too :)" >&2
echo "[5] stdout : Last case : this text should only appear into the reporting file" >> "$strReportingFilepath"

exit 0

When I run this script, I have this on my terminal

(terminal info) # ./my_script.sh
[1] stdout : This text will not appear in the reporting file
[2] stderr : Neither this one
(terminal info) # [3] stdout : This text will be on both the terminal and the reporting file
[4] stderr : This one too :)

and this into my file

(terminal info) # cat reporting.log
[3] stdout : This text will be on both the terminal and the reporting file
[4] stderr : This one too :)

I have 2 problem :

First, for an unknow reason (I suspect that I use exec/named pipe/tee in a sloppy way), my script actually wait at the end. I have to press enter key in order to terminate the script.

Secondly, the [5] echo doesn't appear into the file.

I'm pretty sure that I mess something up with the exec line, but I can't understand what and I don't know what to do.

I added a "sync" call after the [5] echo, but it didn't work.

Well, I think I finally managed to do what I wanted.

What I want :

Having everything printed onto the screen terminal (stdout, stderr, stdin) to be "logged" into a file

Having the possibility to add text into this logging file without displaying it onto the terminal screen.

I stopped using tee, and I found a link talking about "script(8)".
After tinkering around, I ended up with this script :

#!/bin/bash

strReportingFilepath="./reporting.log"

# Part that will do the script reporting
if [ -z "$SCRIPT" ]; then
    export SCRIPT="$0"

    # Creation of the string bash command
    strCommand="$0"
    strSearch="'"
    strReplace="'\''"
    for strArgument in "$@"; do
        strCommand+=" '${strArgument//$strSearch/$strReplace}'"
    done

    # Execution of the script
    /usr/bin/script --return --quiet --flush --append "$strReportingFilepath" --command "$strCommand"
    # We get the return
    intScriptReturnValue="$?"

    # The line automaticly added by /usr/bin/script is something that I don't want
    strTemporaryFilepath="$(mktemp)"
    grep -v '^Script started on ' "$strReportingFilepath" > "$strTemporaryFilepath"
    mv "$strTemporaryFilepath" "$strReportingFilepath"

    exit "$intScriptReturnValue"
fi

# "Start" of the script that I want "supervised"

sync
echo "[0  ] directly" >> "$strReportingFilepath"

echo "[1. ] out"

sync
echo "[1.5] directly" >> "$strReportingFilepath"

echo "[2  ] out"
echo "[3. ] err" >&2

sync
echo "[3.5] directly" >> "$strReportingFilepath"

echo "[4  ] err" >&2
echo -n "[5  ] input : "
read

echo "[6  ] out"
echo "[7  ] err" >&2
echo "      End :)"

exit 5

Now, there are still some problem :

I really don't know what I have done, so if you're thinking about using this code as it, think about it twice.
I just know that for my case, it "seem to work" (yeepee !)

Each time I want to write something directly into the logging file, I have to call "sync" before. Without it, the line aren't in order. Please note that "sync" doesn't garanty that it's instantaneous. In the doc, they say that command like "halt" do a "sleep" after a sync in order to be sure, so it's still possible to have race condition resulting in wrong line order.

It seem that "script" doesn't work on some case, like when stdin is not a terminal. See "script(8)".

Well, sorry for this strange question, I would have bet that what I wanted to do was simple and common, turn out not really.

Body:
You have a race condition; everything sent via tee is just getting buffered, and only gets written (to the terminal and disk) after the script has actually finished. Note: sync doesn't affect this, since it flushes the operating system's buffers, but tail's.

That's why you're getting a terminal prompt before line [3]:

(terminal info) # [3] stdout : This text will be on both the terminal and the reporting file

...your shell sends the prompt for the next command (after running the script), then tee flushes everything in its buffers, so you see lines [3] and [4] after the prompt. Pressing enter after this doesn't terminate the script (it ended a while ago), it just gets you a clean shell prompt that isn't mixed up with the output.

Something similar happens with the reporting.log file. Line [5] gets written into it, and then a moment later tee writes lines [3] and [4] into  it, but since tee's output pointer is set to write to it starting at the beginning of the file, it overwrites line [5].


问:
Are PUT and DELETE requests supported by Azure Static web apps CLI on local environment?
Does the Azure Static web apps CLI(Github link) support other HTTP methods than GET and POST? I'm trying to set up Azure Static web apps CLI on my local environment, and GET and POST requests to port 4280 works fine, but PUT and DELETE requests fails with the error:

UnhandledPromiseRejectionWarning: SyntaxError: Invalid regular
expression: /^*$/: Nothing to repeat.

For testing I'm calling the endpoints from Postman, and if I try directly on the Azure function (running on the default port 7071), these work as expected. Is there some configuration I need to add to ensure SWA CLI forwards my PUT and DELETE requests to the Azure Functions?

Sample function.json that works on port 7071, but not through 4280:

```<code>{   "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": ["put"],
      "route": "project/{id}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }   ] }
</code>```

答:
Turns out the solution is adding a staticwebapp.config.json file (sample allowing any user to run PUT and DELETE calls, even when not authenticated):</p>
```<code>{
  "routes": [
    {
      "route": "/api/*",
      "methods": ["GET", "POST", "PUT", "DELETE"]
    }
  ]
}
</code>```

Body:
Does the Azure Static web apps CLI(Github link) support other HTTP methods than GET and POST? I'm trying to set up Azure Static web apps CLI on my local environment, and GET and POST requests to port 4280 works fine, but PUT and DELETE requests fails with the error:

UnhandledPromiseRejectionWarning: SyntaxError: Invalid regular
expression: /^*$/: Nothing to repeat.

For testing I'm calling the endpoints from Postman, and if I try directly on the Azure function (running on the default port 7071), these work as expected. Is there some configuration I need to add to ensure SWA CLI forwards my PUT and DELETE requests to the Azure Functions?

Sample function.json that works on port 7071, but not through 4280:

{   "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": ["put"],
      "route": "project/{id}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }   ] }

Body:
Turns out the solution is adding a staticwebapp.config.json file (sample allowing any user to run PUT and DELETE calls, even when not authenticated):

{
  "routes": [
    {
      "route": "/api/*",
      "methods": ["GET", "POST", "PUT", "DELETE"]
    }
  ]
}


问:
Discord bot is not responding to commands
I started to make a bot for my Discord server, but I'm completely new to it (I have programming skills, but in web development). I made an application on the Discord developer portal, I made a folder on my PC, I created a package.json file, a main.js file, installed node.js, installed discord.js, I deployed my bot on a test server, etc. (not in this order but whatever).

Then, following a tutorial from a site, I made this in the index.js file:

```<code>const Discord = require('discord.js');
const client = new Discord.Client();

client.once('ready', () => {
    console.log('Ready!');
});

client.on('message', message => {
    if (message.content === '!ping') {
        message.channel.send('Pong.');
    }
});

client.login(' I PUTTED MY TOCKEN HERE ');
</code>```

When I put the command !ping on the test server I created, the bot remains offline and I don't receive Pong...

Can you please help me, please?

答:
Make sure that your bot is allowed to recieve messages (discord.com/developers > your bot > bot > the two intent-switches).

Then add this into the brackets of new Discord.Client();
{ partials: ['MESSAGE', 'CHANNEL', 'REACTION', 'USER', 'GUILD_MEMBER']} (you can remove some of those parameters but message will be needed).

Sorry for bad English...

Body:
I started to make a bot for my Discord server, but I'm completely new to it (I have programming skills, but in web development). I made an application on the Discord developer portal, I made a folder on my PC, I created a package.json file, a main.js file, installed node.js, installed discord.js, I deployed my bot on a test server, etc. (not in this order but whatever).

Then, following a tutorial from a site, I made this in the index.js file:

const Discord = require('discord.js');
const client = new Discord.Client();

client.once('ready', () => {
    console.log('Ready!');
});

client.on('message', message => {
    if (message.content === '!ping') {
        message.channel.send('Pong.');
    }
});

client.login(' I PUTTED MY TOCKEN HERE ');

When I put the command !ping on the test server I created, the bot remains offline and I don't receive Pong...

Can you please help me, please?


问:
Many Senders Sending Multiple Packets to Many Receivers Concurrently
I would like to extend VeinsInetSampleApplication to make node[0] and node[1] send packets to node[2] concurrently.

I tried to comment the if-condition at L46. However, this did not work.

How to achieve that? I would like to have a scalable solution (e.g., in case I want many senders sending multiple packets to many receivers).

答: Please find if MAC layer is wired or wireless. If MAC is wireless then concurrent transmissions are possible between adjacent nodes bounded by transmission range. It may result in collision at the receiver if the medum is broadcasting.</p>


问:
Google One Tap Login with custom term of use
I am using google one-tap login for my web application.

Reference: https://developers.google.com/identity/sign-in/web/sign-in

This one-tap login is replacing the custom sign-up form I used to have.

While the concept is a "one-tap" login, it is missing the term of use agreement.

The old sign-up form contained validation of the term-of-use agreement.

Now I wonder if I can move to google one-tap login with my custom term-of-use.

Thanks.

答:
Found that on the on-tap login popup, there is a link to the /policy route of your web application.

The policy / term of use can be displayed on this route.


问:
Exclude from file one the lines in common with file two and preserve line order
one

```<code>pl
a
ff
c
b
nn
</code>```

two

```<code>b
a
z
k
c
d
</code>```

I want to remove from the first file all lines that are also in the second (common lines). And I want to maintain the file_one lines order.

It's possible to work in a line by line check mode, something like:

```<code>while read line; do
  if ! grep $line two; then
    echo $line >> one_only
  fi
done < one
</code>```

But it likely isn't the best option for a fast check.
An other way would be using "comm" command on the files previously sorted:

```<code>comm -1 -2 <(sort one) <(sort two) \
  | tr '\n' '\|' \
  | sed 's/|/\\|/g;s/\\|$/\n/' \
  > common_lines

grep -v "$(cat common_lines)" one
</code>```

first command creates a "logical OR pattern":

```<code>a\|b\|c
</code>```

which can be reuse with grep to exclude common lines from the "one" file. In this way the original order of "one" lines is preserved. And the result will be:

```<code>pl
ff
nn
</code>```

Can you suggest any other idea to minimize compute time even more?

Real input files are much more populated and contain short names (software names):

```<code>blender
gimp
vim
emacs
mozilla-firefox
google-earth
</code>```

and so on...

答:
```<code>awk 'NR==FNR{a[$0]; next} !($0 in a)' two one
</code>```

Regarding the  while read loop in your question, please read why-is-using-a-shell-loop-to-process-text-considered-bad-practice

Body:
one

pl
a
ff
c
b
nn

two

b
a
z
k
c
d

I want to remove from the first file all lines that are also in the second (common lines). And I want to maintain the file_one lines order.

It's possible to work in a line by line check mode, something like:

while read line; do
  if ! grep $line two; then
    echo $line >> one_only
  fi
done < one

But it likely isn't the best option for a fast check.
An other way would be using "comm" command on the files previously sorted:

comm -1 -2 <(sort one) <(sort two) \
  | tr '\n' '\|' \
  | sed 's/|/\\|/g;s/\\|$/\n/' \
  > common_lines

grep -v "$(cat common_lines)" one

first command creates a "logical OR pattern":

a\|b\|c

which can be reuse with grep to exclude common lines from the "one" file. In this way the original order of "one" lines is preserved. And the result will be:

pl
ff
nn

Can you suggest any other idea to minimize compute time even more?

Real input files are much more populated and contain short names (software names):

blender
gimp
vim
emacs
mozilla-firefox
google-earth

and so on...

Body:
awk 'NR==FNR{a[$0]; next} !($0 in a)' two one

Regarding the  while read loop in your question, please read why-is-using-a-shell-loop-to-process-text-considered-bad-practice


问:
Is there a way you can produce an output like this in T-SQL
I have a column which I translate the values using a case statements and I get numbers like this below. There are multiple columns I need to produce the result like this and this is just one column.

How do you produce the output  as a whole like this below.
The 12 is the total numbers counting from top to bottom
49 is the Average.
4.08 is the division 49/12.
1 is how many 1's are there in the output list above. As you can see there is only one 1 in the output above
8.33% is the division and percentage comes from 1/12 * 100
and so on. Is there a way to produce this output below?

```<code>drop table test111
create table test111
(
Q1 nvarchar(max)
);

INSERT INTO TEST111(Q1)
VALUES('Strongly Agree')
,('Agree')
,('Disagree')
,('Strongly Disagree')
,('Strongly Agree')
,('Agree')
,('Disagree')
,('Neutral');

SELECT
CASE WHEN [Q1] = 'Strongly Agree' THEN 5
WHEN [Q1] = 'Agree' THEN 4
WHEN [Q1] = 'Neutral' THEN 3
WHEN [Q1] = 'Disagree' THEN 2
WHEN [Q1] = 'Strongly Disagree' THEN 1
END AS 'Test Q1'
FROM test111
</code>```

答:
I have to make a few assumptions here, but it looks like you want to treat an output column like a column in a spreadsheet. You have 12 numbers. You then have a blank "separator" row. Then a row with the number 12 (which is the count of how many numbers you have). Then a row with the number 49, which is the sum of those 12 numbers. Then the 4.08 row, which is rougly the average, and so on.

Some of these outputs can be provided by cube or rollup, but neither is a complete solution.

If you wanted to produce this output directly from TSQL, you would need to have multiple select statements and combine the results of all of those statements using union all. First you would have a select just to get the numbers. Then you would have a second select which outputs a "blank". Then another select which is providing a count. Then another select which is providing a sum. And so on.

You would also no longer be able to output actual numbers, since a "blank" is not a number. Visually it's best represented as an empty string. But now your output column has to be of datatype char or varchar.

You also have to make sure rows come out in the correct order for presentation. So you need a column to order by. You would have to add some kind of ordering column "manually" to each of the select statements, so when you union them all together you can tell SQL in what order the output should be provided.

So the answer to "can it be done?" is technically "yes". But if you think seems like a whole lot of laborious and inefficient TSQL work, you'd be right.

The real solution here is to change your approach. SQL should not be concerned with "output formatting". What you should do is just return the actual data (your 12 numbers) from SQL, and then do all of the additional presentation (like adding a blank row, adding a count row, etc), in the code of the program that is calling SQL to get that data.

Body:
I have a column which I translate the values using a case statements and I get numbers like this below. There are multiple columns I need to produce the result like this and this is just one column.

How do you produce the output  as a whole like this below.
The 12 is the total numbers counting from top to bottom
49 is the Average.
4.08 is the division 49/12.
1 is how many 1's are there in the output list above. As you can see there is only one 1 in the output above
8.33% is the division and percentage comes from 1/12 * 100
and so on. Is there a way to produce this output below?

drop table test111
create table test111
(
Q1 nvarchar(max)
);

INSERT INTO TEST111(Q1)
VALUES('Strongly Agree')
,('Agree')
,('Disagree')
,('Strongly Disagree')
,('Strongly Agree')
,('Agree')
,('Disagree')
,('Neutral');

SELECT
CASE WHEN [Q1] = 'Strongly Agree' THEN 5
WHEN [Q1] = 'Agree' THEN 4
WHEN [Q1] = 'Neutral' THEN 3
WHEN [Q1] = 'Disagree' THEN 2
WHEN [Q1] = 'Strongly Disagree' THEN 1
END AS 'Test Q1'
FROM test111


问:
how to find the starting and ending index of a span in a document in spacy
I am doing some NLP work using spacy. I have a sentence and a noun chunk, how to find the starting word index and ending word index of the noun chunk using spacy?
As for instance, If I have "I live in New York City", and the noun chunk is "New York", then I want 3 as the output</p>

答:
```<code>import spacy
nlp = spacy.load("en_core_web_sm")
text="I live in New York City"
doc = nlp(text)

#To find the Noun chunks

Noun_chunks= [chunk.text for chunk in doc.noun_chunks]

#for loop to find the index of noun chunks

for noun in Noun_chunks:
  starting_index = text.index(noun)
  ending_index = text.index(noun) + len(noun) - 1
  print(noun,starting_index,ending_index)

#output
#There are 2 noun_chunks: I and New York City
#I 0 0 (starting at 0 and ending at 0)
#New York City 10 22 (starting at 10 and ending at 22)
</code>```


问:
Left Join of Two Data Table into one two DataTabale
Here is my Scenario

I Have First Datable :TableA

```     **Item**    **Place**

      ItemA      PlaceA
      ItemB      PlaceB
      ItemE      PlaceE
```

I Have Second Datable :TableB

```

  **Item**            **Status**
-------------------------------
   ItemC             Complete

   ItemD             Complete

   ItemE             Complete
```

Output New DataTable Will Look Like This

```
   Item        Place       Status
----------------------------------------------

   ItemA     PlaceA

   ItemB     PlaceB

   ItemC                Complete

   ItemD                Complete

   ItemE     PlaceE     Complete
```

Please give me the Solution in VB.Net

答:
As a quick example:

```<code>    Dim dt As New DataTable()
    dt.Columns.Add("Serial", Type.GetType("System.String"))
    dt.Columns.Add("Item", Type.GetType("System.String"))
    dt.Columns.Add("Place", Type.GetType("System.String"))
    dt.Rows.Add(New String() {"001", "ItemA", "PlaceA"})
    dt.Rows.Add(New String() {"002", "ItemB", "PlaceB"})

    Dim dt1 As New DataTable()
    dt1.Columns.Add("Serial", Type.GetType("System.String"))
    dt1.Columns.Add("Item", Type.GetType("System.String"))
    dt1.Columns.Add("Status", Type.GetType("System.String"))
    dt1.Rows.Add(New String() {"003", "ItemC", "Complete"})
    dt1.Rows.Add(New String() {"003", "ItemD", "Complete"})

    dt.Merge(dt1)
</code>```

The last line is the most important, which merges the contents of one datatable with the contents of another.

Should do the trick!!

Body:
Here is my Scenario

I Have First Datable :TableA

     **Item**    **Place**

      ItemA      PlaceA
      ItemB      PlaceB
      ItemE      PlaceE

I Have Second Datable :TableB

  **Item**            **Status**
-------------------------------
   ItemC             Complete

   ItemD             Complete

   ItemE             Complete

Output New DataTable Will Look Like This

   Item        Place       Status
----------------------------------------------

   ItemA     PlaceA

   ItemB     PlaceB

   ItemC                Complete

   ItemD                Complete

   ItemE     PlaceE     Complete

Please give me the Solution in VB.Net

Body:
As a quick example:

    Dim dt As New DataTable()
    dt.Columns.Add("Serial", Type.GetType("System.String"))
    dt.Columns.Add("Item", Type.GetType("System.String"))
    dt.Columns.Add("Place", Type.GetType("System.String"))
    dt.Rows.Add(New String() {"001", "ItemA", "PlaceA"})
    dt.Rows.Add(New String() {"002", "ItemB", "PlaceB"})

    Dim dt1 As New DataTable()
    dt1.Columns.Add("Serial", Type.GetType("System.String"))
    dt1.Columns.Add("Item", Type.GetType("System.String"))
    dt1.Columns.Add("Status", Type.GetType("System.String"))
    dt1.Rows.Add(New String() {"003", "ItemC", "Complete"})
    dt1.Rows.Add(New String() {"003", "ItemD", "Complete"})

    dt.Merge(dt1)

The last line is the most important, which merges the contents of one datatable with the contents of another.

Should do the trick!!


问:
How to create a deep insert structure using Olingo Client?
How to POST the following JSON structure using Apache OLINGO client? What is the best way to build up this structure? Are there any examples?</p>
```<code>{
"itemNumber": "ITEM1"

"lines": [

    {
        componentNumber":   "COMPONENT1"
    },
    {
        componentNumber":   "COMPONENT2"
    }
]
}
</code>```

答:
You will have to specify the the NavigationPropertyName in the deep part. So for your sample payload it would look like

```<code>{
    "itemNumber": "ITEM1",

    "lines": {
        "componentNumber":"COMPONENT1",
        "componentNumber":"COMPONENT2",

    }
}
</code>```

You can refer to this post in SO to get details about n level nesting

The above answer asuumes that your NavigationProperty is named lines, you can substitute it with the right name by looking at service/$metadata

The answer assumes that you are trying to do deep inserts in a odata2 service, for OData4 the concept remains the same but syntax might vary a bit. Please refer to the payload descripted in documentation in case of OData 4

Body:
How to POST the following JSON structure using Apache OLINGO client? What is the best way to build up this structure? Are there any examples?

{
"itemNumber": "ITEM1"

"lines": [

    {
        componentNumber":   "COMPONENT1"
    },
    {
        componentNumber":   "COMPONENT2"
    }
]
}

Body:
You will have to specify the the NavigationPropertyName in the deep part. So for your sample payload it would look like

{
    "itemNumber": "ITEM1",

    "lines": {
        "componentNumber":"COMPONENT1",
        "componentNumber":"COMPONENT2",

    }
}

You can refer to this post in SO to get details about n level nesting

The above answer asuumes that your NavigationProperty is named lines, you can substitute it with the right name by looking at service/$metadata

The answer assumes that you are trying to do deep inserts in a odata2 service, for OData4 the concept remains the same but syntax might vary a bit. Please refer to the payload descripted in documentation in case of OData 4


问:
Adding space before capital letters in yaml file (flexget config)
I have some problems with the FlexGet Configuration.

I want to rename and move some movies.

Example

For example the movie "ElPatriota" (which currently is unable to rename) can not be found in TheMovieDataBase (tmdb) when searching for this title without spaces.

So I need to rename it first to "El Patriota" before I can look it up at tmdb and move it to his correct directory.

What I researched

I saw this function using a regular-expression but I don't know how to implement it on my config or if it's the correct solution for me.

```<code>re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord")
'Word Word Word'
</code>```

FlexGet Config YAML

This is a part of the related config:

move movies:
    priority: 3
    template:
      - movies-metainfo
      - telegram
    filesystem:
      path: /downloads/
      recursive: yes
      retrieve: files
      regexp: '.*\.(avi|mkv|mp4)$'
    seen: local
    regexp:
      reject:
        - \b(duo|tri|quadri|tetra|penta)logy\b: {from: title}
        - s\d{2}(e\d{2,})?: {from: title}
    require_field:
      - tmdb_name
      - movie_name
    accept_all: yes
    tmdb_lookup:
      language: es
    set:
      title: "{{title|replace('4K','[]')|replace('BD1080','[]')|replace('M1080','[]')}}"
    move:
      to: "/media/Peliculas/"
      rename: "{{tmdb_name|replace('/','_')|replace(':',' -')|replace(',','')|replace('?','')}}"
      along:
        extensions:
          - sub
          - srt
        subdirs:
          - Subs
      clean_source: 50
```

答:
Assumptions on construction of search-terms

From your comment I assume the file-name replacing step as input for the search is:

```<code>    set:
      title: "{{title|replace('4K','[]')|replace('BD1080','[]')|replace('M1080','[]')}}"
</code>```

So the different search-terms (set titles) are alternatives (separated by | like boolean OR):

```<code>title|replace('4K','[]')|replace('BD1080','[]')|replace('M1080','[]')
</code>```

See also FlexGet docs:

series Plugin, Set entry fields

set Plugin

manipulate Plugin

Regex as solution

Assume further that you can use a regular-expression to substitute the title.
Then a regex-substitution adding a space between lower-case and upper-case letters will do:

Step
Value

Input
ElPatriotaM1080.www.url.com.mkv

Wanted
El Patriota M1080.www.url.com.mkv

Regex
substitute ([a-z])([A-Z]) by \1 \2

Output
El Patriota M1080.www.url.com.mkv

Manipulate and replace by regex

Appropriate seems the manipulate Plugin with action replace as sown in Example 4:

You can control how the regex hits are output using \1, \2, etc in format.

manipulate:
  - title:
      replace:
        regexp: '(.*)/(.*)/(.*)'
        format: '\2.\1.\3'
```
</blockquote>
<p><strong>⚠ Caution: Regex matches are ignore-case by default</strong>
Since the regex is case-sensitive (depends on different upper-case and lower-case characters), the default regex-flags of the manipulate replace-by-regex (IGNORE and UNICODE) must be disabled explicitly by surrounding the regex with disabled inline-flag <code>i</code> like <code>(?-i:<regex>)</code>.</p>
<h3>Config snippets</h3>
<p>In this case it could look like separating the lower-case (first group <code>([a-z])</code> and insert by reference <code>\1</code>) from upper-case (second group <code>([A-Z])</code> and insert by reference <code>\2</code>) by a space between.</p>
<p>Additionally disabling the <code>i</code> we need to config: <code>(?-i:([a-z])([A-Z]))</code>.</p>
<pre class="lang-yaml prettyprint-override"><code>manipulate:
  - title:
      replace:
        regexp: '(?-i:([a-z])([A-Z]))'
        format: '\1 \2'
</code>```

or alternatively, without capturing but with a positive look-ahead  as (?=[A-Z]) then inserting a space (with switched-off ignore-case flag):

manipulate:
  - title:
      replace:
        regexp: '(?-i:(?=[A-Z]))'
        format: ' '
```
<h3>Demo in pure Python</h3>
<p>A working demo in pure Python shows how to replace file-names.
It was adapted from How to replace camelCasing in all files in a folder using Python or c#?:</p>
<pre class="lang-py prettyprint-override"><code>import re

old_name = 'ElPatriotaM1080.www.url.com.mkv'
print(f"Given:           '{old_name}'")

flags=re.I  # default for FlexGet's replace-plugin: ignore-case

regex_1           = '(?=[A-Z])'
regex_1_no_ignore = '(?-i:(?=[A-Z]))'

new_name = re.sub(regex_1, ' ', old_name, flags=flags)
print(f"Regex 1 (I on ): '{new_name}'")
new_name = re.sub(regex_1_no_ignore, ' ', old_name, flags=flags)
print(f"Regex 1 (I off): '{new_name}'")

regex_2           = r'([a-z])([A-Z])'
regex_2_no_ignore = r'(?-i:([a-z])([A-Z]))'

new_name = re.sub(regex_2, r'\1 \2', old_name, flags=flags)
print(f"Regex 2 (I on ): '{new_name}'")
new_name = re.sub(regex_2_no_ignore, r'\1 \2', old_name, flags=flags)
print(f"Regex 2 (I off): '{new_name}'")
</code>```

Prints:

```<code>Given:           'ElPatriotaM1080.www.url.com.mkv'
Regex 1 (I on ): ' E l P a t r i o t a M1080. w w w. u r l. c o m. m k v'
Regex 1 (I off): ' El Patriota M1080.www.url.com.mkv'
Regex 2 (I on ): 'E lP at ri ot aM1080.w ww.u rl.c om.m kv'
Regex 2 (I off): 'El Patriota M1080.www.url.com.mkv'
</code>```

Both regex-approaches (1+2) have almost the same effect: space inserted before upper-case letters. However, the ignore-case flag (whether "I on" or "I off") has unexpected impact on the result.

Body:
I have some problems with the FlexGet Configuration.

I want to rename and move some movies.

Example

For example the movie "ElPatriota" (which currently is unable to rename) can not be found in TheMovieDataBase (tmdb) when searching for this title without spaces.

So I need to rename it first to "El Patriota" before I can look it up at tmdb and move it to his correct directory.

What I researched

I saw this function using a regular-expression but I don't know how to implement it on my config or if it's the correct solution for me.

re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord")
'Word Word Word'

FlexGet Config YAML

This is a part of the related config:

move movies:
    priority: 3
    template:
      - movies-metainfo
      - telegram
    filesystem:
      path: /downloads/
      recursive: yes
      retrieve: files
      regexp: '.*\.(avi|mkv|mp4)$'
    seen: local
    regexp:
      reject:
        - \b(duo|tri|quadri|tetra|penta)logy\b: {from: title}
        - s\d{2}(e\d{2,})?: {from: title}
    require_field:
      - tmdb_name
      - movie_name
    accept_all: yes
    tmdb_lookup:
      language: es
    set:
      title: "{{title|replace('4K','[]')|replace('BD1080','[]')|replace('M1080','[]')}}"
    move:
      to: "/media/Peliculas/"
      rename: "{{tmdb_name|replace('/','_')|replace(':',' -')|replace(',','')|replace('?','')}}"
      along:
        extensions:
          - sub
          - srt
        subdirs:
          - Subs
      clean_source: 50

Body:
Assumptions on construction of search-terms

From your comment I assume the file-name replacing step as input for the search is:

    set:
      title: "{{title|replace('4K','[]')|replace('BD1080','[]')|replace('M1080','[]')}}"

So the different search-terms (set titles) are alternatives (separated by | like boolean OR):

title|replace('4K','[]')|replace('BD1080','[]')|replace('M1080','[]')

See also FlexGet docs:

series Plugin, Set entry fields

set Plugin

manipulate Plugin

Regex as solution

Assume further that you can use a regular-expression to substitute the title.
Then a regex-substitution adding a space between lower-case and upper-case letters will do:

Step
Value

Input
ElPatriotaM1080.www.url.com.mkv

Wanted
El Patriota M1080.www.url.com.mkv

Regex
substitute ([a-z])([A-Z]) by \1 \2

Output
El Patriota M1080.www.url.com.mkv

Manipulate and replace by regex

Appropriate seems the manipulate Plugin with action replace as sown in Example 4:

You can control how the regex hits are output using \1, \2, etc in format.

manipulate:
  - title:
      replace:
        regexp: '(.*)/(.*)/(.*)'
        format: '\2.\1.\3'

⚠ Caution: Regex matches are ignore-case by default
Since the regex is case-sensitive (depends on different upper-case and lower-case characters), the default regex-flags of the manipulate replace-by-regex (IGNORE and UNICODE) must be disabled explicitly by surrounding the regex with disabled inline-flag i like (?-i:<regex>).

Config snippets

In this case it could look like separating the lower-case (first group ([a-z]) and insert by reference \1) from upper-case (second group ([A-Z]) and insert by reference \2) by a space between.

Additionally disabling the i we need to config: (?-i:([a-z])([A-Z])).

manipulate:
  - title:
      replace:
        regexp: '(?-i:([a-z])([A-Z]))'
        format: '\1 \2'

or alternatively, without capturing but with a positive look-ahead  as (?=[A-Z]) then inserting a space (with switched-off ignore-case flag):

manipulate:
  - title:
      replace:
        regexp: '(?-i:(?=[A-Z]))'
        format: ' '

Demo in pure Python

A working demo in pure Python shows how to replace file-names.
It was adapted from How to replace camelCasing in all files in a folder using Python or c#?:

import re

old_name = 'ElPatriotaM1080.www.url.com.mkv'
print(f"Given:           '{old_name}'")

flags=re.I  # default for FlexGet's replace-plugin: ignore-case

regex_1           = '(?=[A-Z])'
regex_1_no_ignore = '(?-i:(?=[A-Z]))'

new_name = re.sub(regex_1, ' ', old_name, flags=flags)
print(f"Regex 1 (I on ): '{new_name}'")
new_name = re.sub(regex_1_no_ignore, ' ', old_name, flags=flags)
print(f"Regex 1 (I off): '{new_name}'")

regex_2           = r'([a-z])([A-Z])'
regex_2_no_ignore = r'(?-i:([a-z])([A-Z]))'

new_name = re.sub(regex_2, r'\1 \2', old_name, flags=flags)
print(f"Regex 2 (I on ): '{new_name}'")
new_name = re.sub(regex_2_no_ignore, r'\1 \2', old_name, flags=flags)
print(f"Regex 2 (I off): '{new_name}'")

Prints:

Given:           'ElPatriotaM1080.www.url.com.mkv'
Regex 1 (I on ): ' E l P a t r i o t a M1080. w w w. u r l. c o m. m k v'
Regex 1 (I off): ' El Patriota M1080.www.url.com.mkv'
Regex 2 (I on ): 'E lP at ri ot aM1080.w ww.u rl.c om.m kv'
Regex 2 (I off): 'El Patriota M1080.www.url.com.mkv'

Both regex-approaches (1+2) have almost the same effect: space inserted before upper-case letters. However, the ignore-case flag (whether "I on" or "I off") has unexpected impact on the result.