问:
Transport scheme NOT recognized: [nsp]
I am trying to connect to a SoftwareAg's Universal Messaging queue in a Spring application. This is my Config class.

@Configuration
@EnableJms
public class Config {

    @Bean
    public ActiveMQConnectionFactory receiverActiveMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();

        var properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
        properties.setProperty(Context.PROVIDER_URL, "nsp://localhost:9200");
        activeMQConnectionFactory.buildFromProperties(properties);

        return activeMQConnectionFactory;
    }

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
        var factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(receiverActiveMQConnectionFactory());
        factory.setConcurrency("3-10");
        return factory;
    }

}
```

<p>This is the part of my pom.xml</p>

<pre class="lang-xml prettyprint-override"><code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-broker</artifactId>
</dependency>
<dependency>
    <groupId>com.pcbsys.nirvana</groupId>
    <artifactId>nClient</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.pcbsys.nirvana</groupId>
    <artifactId>nJMS</artifactId>
    <version>1.0</version>
</dependency>
</code>```

However, I get the following exception when I try to connect to the queue:

```<code>Caused by: org.springframework.jms.UncategorizedJmsException: Uncategorized exception occurred during JMS processing; nested exception is javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:311) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:185) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:507) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:584) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.convertAndSend(JmsTemplate.java:661) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at id.mandiri.co.id.um.Main.lambda$runner$0(Main.java:21) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    ... 5 common frames omitted
Caused by: javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:36) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:333) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:346) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:304) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:244) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.springframework.jms.support.JmsAccessor.createConnection(JmsAccessor.java:196) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:494) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    ... 9 common frames omitted
Caused by: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.apache.activemq.util.IOExceptionSupport.create(IOExceptionSupport.java:28) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:185) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.connect(TransportFactory.java:64) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:331) ~[activemq-client-5.15.10.jar:5.15.10]
    ... 14 common frames omitted
Caused by: java.io.IOException: Could not find factory class for resource: META-INF/services/org/apache/activemq/transport/nsp
    at org.apache.activemq.util.FactoryFinder$StandaloneObjectFactory.loadProperties(FactoryFinder.java:98) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.util.FactoryFinder$StandaloneObjectFactory.create(FactoryFinder.java:60) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.util.FactoryFinder.newInstance(FactoryFinder.java:148) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:182) ~[activemq-client-5.15.10.jar:5.15.10]
    ... 16 common frames omitted
</code>```

It says here:

UM can be used with Spring. In general, the Spring XML that works for ActiveMQ should work for UM with only the connection factory class and URL changed accordingly.

What am I missing?

Edit:

var properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
properties.setProperty(Context.PROVIDER_URL, "nsp://localhost:9200");

Context ctx = new InitialContext(properties);
return (ConnectionFactory) ctx.lookup("local_um"); // THIS?
```

答:
I finally managed to solve it. This is what worked for me:

@Configuration
@EnableJms
public class Config {

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
        var factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(cachingConnectionFactory());
        factory.setConcurrency("3-10");
        return factory;
    }

    @Bean
    @Primary
    public CachingConnectionFactory cachingConnectionFactory() {
        final CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setSessionCacheSize(200);
        cachingConnectionFactory.setTargetConnectionFactory((ConnectionFactory) jndiObjectFactoryBean().getObject());

        return cachingConnectionFactory;
    }

    @Bean
    public JndiTemplate jndiTemplate() {
        final Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
        properties.setProperty(Context.PROVIDER_URL, "nsp://local-dev:9200");

        final JndiTemplate jndiTemplate = new JndiTemplate();
        jndiTemplate.setEnvironment(properties);

        return jndiTemplate;
    }

    @Bean
    public JndiObjectFactoryBean jndiObjectFactoryBean() {
        final JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiTemplate(jndiTemplate());
        jndiObjectFactoryBean.setJndiName("jndi_key");
        return jndiObjectFactoryBean;
    }

}
```

I hope it helps someone. Don't forget to add nClient.jar and nJMS.jar to your classpath. You can find them in the UM install lib directory.

Title: Transport scheme NOT recognized: [nsp]

Body:
I am trying to connect to a SoftwareAg's Universal Messaging queue in a Spring application. This is my Config class.

@Configuration
@EnableJms
public class Config {

    @Bean
    public ActiveMQConnectionFactory receiverActiveMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();

        var properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
        properties.setProperty(Context.PROVIDER_URL, "nsp://localhost:9200");
        activeMQConnectionFactory.buildFromProperties(properties);

        return activeMQConnectionFactory;
    }

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
        var factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(receiverActiveMQConnectionFactory());
        factory.setConcurrency("3-10");
        return factory;
    }

}

This is the part of my pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-broker</artifactId>
</dependency>
<dependency>
    <groupId>com.pcbsys.nirvana</groupId>
    <artifactId>nClient</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.pcbsys.nirvana</groupId>
    <artifactId>nJMS</artifactId>
    <version>1.0</version>
</dependency>

However, I get the following exception when I try to connect to the queue:

Caused by: org.springframework.jms.UncategorizedJmsException: Uncategorized exception occurred during JMS processing; nested exception is javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:311) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:185) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:507) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:584) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.convertAndSend(JmsTemplate.java:661) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at id.mandiri.co.id.um.Main.lambda$runner$0(Main.java:21) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    ... 5 common frames omitted
Caused by: javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:36) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:333) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:346) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:304) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:244) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.springframework.jms.support.JmsAccessor.createConnection(JmsAccessor.java:196) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:494) ~[spring-jms-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    ... 9 common frames omitted
Caused by: java.io.IOException: Transport scheme NOT recognized: [nsp]
    at org.apache.activemq.util.IOExceptionSupport.create(IOExceptionSupport.java:28) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:185) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.connect(TransportFactory.java:64) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:331) ~[activemq-client-5.15.10.jar:5.15.10]
    ... 14 common frames omitted
Caused by: java.io.IOException: Could not find factory class for resource: META-INF/services/org/apache/activemq/transport/nsp
    at org.apache.activemq.util.FactoryFinder$StandaloneObjectFactory.loadProperties(FactoryFinder.java:98) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.util.FactoryFinder$StandaloneObjectFactory.create(FactoryFinder.java:60) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.util.FactoryFinder.newInstance(FactoryFinder.java:148) ~[activemq-client-5.15.10.jar:5.15.10]
    at org.apache.activemq.transport.TransportFactory.findTransportFactory(TransportFactory.java:182) ~[activemq-client-5.15.10.jar:5.15.10]
    ... 16 common frames omitted

It says here:

UM can be used with Spring. In general, the Spring XML that works for ActiveMQ should work for UM with only the connection factory class and URL changed accordingly.

What am I missing?

Edit:

var properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
properties.setProperty(Context.PROVIDER_URL, "nsp://localhost:9200");

Context ctx = new InitialContext(properties);
return (ConnectionFactory) ctx.lookup("local_um"); // THIS?

Body:
I finally managed to solve it. This is what worked for me:

@Configuration
@EnableJms
public class Config {

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
        var factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(cachingConnectionFactory());
        factory.setConcurrency("3-10");
        return factory;
    }

    @Bean
    @Primary
    public CachingConnectionFactory cachingConnectionFactory() {
        final CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setSessionCacheSize(200);
        cachingConnectionFactory.setTargetConnectionFactory((ConnectionFactory) jndiObjectFactoryBean().getObject());

        return cachingConnectionFactory;
    }

    @Bean
    public JndiTemplate jndiTemplate() {
        final Properties properties = new Properties();
        properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.pcbsys.nirvana.nSpace.NirvanaContextFactory");
        properties.setProperty(Context.PROVIDER_URL, "nsp://local-dev:9200");

        final JndiTemplate jndiTemplate = new JndiTemplate();
        jndiTemplate.setEnvironment(properties);

        return jndiTemplate;
    }

    @Bean
    public JndiObjectFactoryBean jndiObjectFactoryBean() {
        final JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiTemplate(jndiTemplate());
        jndiObjectFactoryBean.setJndiName("jndi_key");
        return jndiObjectFactoryBean;
    }

}

I hope it helps someone. Don't forget to add nClient.jar and nJMS.jar to your classpath. You can find them in the UM install lib directory.


来源: stackexchange

问:
Background-clip does not work in google sites

    Eli's Opinion Website

```

The part that wont work is the clip part. Everything else works. I just need the background of the text to end when the text ends.

答:
Based on your description, you might find display:inline helpful.

.header {
  display: inline;
  background: lightblue;
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="header">
  Eli's Opinion Website
</h1></code>```

inline

  The element generates one or more inline element boxes that do not generate line breaks before or after themselves. In normal flow, the next element will be on the same line if there is space. -- display

Depending on your context, you might consider display:inline-block instead.

Also see What is the difference between display: inline and display: inline-block?

inline-block (legacy)

  The element generates a block element box that will be flowed with surrounding content as if it were a single inline box (behaving much like a replaced element would).

ContentLicense: CC BY-SA 4.0

Body:
    Eli's Opinion Website

The part that wont work is the clip part. Everything else works. I just need the background of the text to end when the text ends.

Body:
Based on your description, you might find display:inline helpful.

.header {
  display: inline;
  background: lightblue;
  color: blue;
}

<h1 class="header">
  Eli's Opinion Website
</h1>

inline

  The element generates one or more inline element boxes that do not generate line breaks before or after themselves. In normal flow, the next element will be on the same line if there is space. -- display

Depending on your context, you might consider display:inline-block instead.

Also see What is the difference between display: inline and display: inline-block?

inline-block (legacy)

  The element generates a block element box that will be flowed with surrounding content as if it were a single inline box (behaving much like a replaced element would).


问:
Liquibase maven multimodule
I'm trying to get liquibase to generate changesets based on Hibernate entities.
We have a multi-module maven project, with persisted objects sprinkled around the different modules.
When I run mvn liquibase:generateChangeLog, it executes for every module, repeating same output over and over in the generated changelog file</p>

答:
Figured out the solution to this:
so we have a bunch of core maven modules and a set of modules with customizations for specific customers.
Ultimately the customer modules are "top level" modules, and when application is packaged, it's packaged for the specific top-level customer module.

So solution was to add the following to all but the "top level" customer modules

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>3.9.0</version>
            <configuration>
                <skip>true</skip>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

Title: Liquibase maven multimodule

Body:
Figured out the solution to this:
so we have a bunch of core maven modules and a set of modules with customizations for specific customers.
Ultimately the customer modules are "top level" modules, and when application is packaged, it's packaged for the specific top-level customer module.

So solution was to add the following to all but the "top level" customer modules

<build>
    <plugins>
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>3.9.0</version>
            <configuration>
                <skip>true</skip>
            </configuration>
        </plugin>
    </plugins>
</build>


问:
Selenium Javascript Executor Click() searches for element on page before actually clicking on the page
I am automating a website with Selenium, however click() is not working. It returns an element that can not be scrolled into view.

I used Javascript Executor to invoke click(), the code is written to find an element on the page clicked on after click(). However, Selenium attempts to find the element before it clicks on the website.

I checked the website while the script was running, and it attempts to find the element and then clicks on the page it's on. How do I fix this?

(code below)

I have tried waiting for the element to be clickable using WebDriver. However, it times out every time, so I am out of ideas. Any help is appreciated.

```<code>  Find_Section = Driver.find_element_by_xpath('//div[contains(text()="Text"]')
  Driver.execute_script("arguments[0].click();", Find_Section)
  Tester = Driver.find_element_by_partial_link_text('Test19')
  Tester.click()
</code>```

Edit:

I believe i have figured out what the problem is according to WebDriver click() vs JavaScript click()
click() behaves like a actual user does and execute_script does not and just calls the event so what i believe is happening is the execute_script is clicking on the event but not doing the same as click() so it isn't loading the page correctly.

The reason why i am using execute_script is because the click() method is throwing can not scroll element into view each time.

I may be wrong about the reason why i think it is not working if so correct me

答:
I finally figured it out since no one here would help me for anyone interested you need to insert a wait statement before the next element for example</p>

```<code>try:
    time.sleep(2) # Could be WebDriverWait
    Find_Example = driver.find_element_by_partial_link_text('Example')
    time.sleep(2) # Try to make bot less noticeable
    Find_Example.click()
except InvalidElement: # Defined in the import section
   # Syntax may be wrong i wrote this by hand in this little text window
   print("\033[31m Could Not Find The Desired Element [STATUS] \033[31m")
   exit()

</code>```

Body:
I am automating a website with Selenium, however click() is not working. It returns an element that can not be scrolled into view.

I used Javascript Executor to invoke click(), the code is written to find an element on the page clicked on after click(). However, Selenium attempts to find the element before it clicks on the website.

I checked the website while the script was running, and it attempts to find the element and then clicks on the page it's on. How do I fix this?

(code below)

I have tried waiting for the element to be clickable using WebDriver. However, it times out every time, so I am out of ideas. Any help is appreciated.

  Find_Section = Driver.find_element_by_xpath('//div[contains(text()="Text"]')
  Driver.execute_script("arguments[0].click();", Find_Section)
  Tester = Driver.find_element_by_partial_link_text('Test19')
  Tester.click()

Edit:

I believe i have figured out what the problem is according to WebDriver click() vs JavaScript click()
click() behaves like a actual user does and execute_script does not and just calls the event so what i believe is happening is the execute_script is clicking on the event but not doing the same as click() so it isn't loading the page correctly.

The reason why i am using execute_script is because the click() method is throwing can not scroll element into view each time.

I may be wrong about the reason why i think it is not working if so correct me

Body:
I finally figured it out since no one here would help me for anyone interested you need to insert a wait statement before the next element for example

try:
    time.sleep(2) # Could be WebDriverWait
    Find_Example = driver.find_element_by_partial_link_text('Example')
    time.sleep(2) # Try to make bot less noticeable
    Find_Example.click()
except InvalidElement: # Defined in the import section
   # Syntax may be wrong i wrote this by hand in this little text window
   print("\033[31m Could Not Find The Desired Element [STATUS] \033[31m")
   exit()


问:
Unable to start debugging : The value of miDebuggerPath is invalid
I recently started working on vscode. I wanted to debug my C code. But the moment I am launching the debugger getting Error : Unable to start debugging. The value of miDebuggerPath is invalid.

I have my gdb installed on wsl . It's path is /usr/bin/gdb. I have copied same path to launch.json in miDebuggerPath.

Here is my launch.json :

```<code>{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

    {
        "name": "(gdb) Launch",
        "type": "cppdbg",
        "request": "launch",
        "program": "${workspaceFolder}/bin/main",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": true,
        "MIMode": "gdb",
        "miDebuggerPath": "/usr/bin/gdb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ]
    }
]
</code>```

}

It should not throw the error and I should able to launch my debugger.

答:
I had the same problem, my solution was:

1. Change this section in launch.json

```<code>"miDebuggerPath": "/usr/bin/gdb",
</code>```

for:

```<code>"miDebuggerPath": "C:/MinGW/bin/gdb.exe",
</code>```

2. Do you need to install in your PC  MinGW, this is the link:

https://osdn.net/projects/mingw/downloads/68260/mingw-get-setup.exe/

3. Next, open the MinGW then you install in the URL "C:/MinGW/bin" the gdb (select)

```<code>mingw32-gdb-bin
</code>```

4. Enjoy the vs-code

Body:
I recently started working on vscode. I wanted to debug my C code. But the moment I am launching the debugger getting Error : Unable to start debugging. The value of miDebuggerPath is invalid.

I have my gdb installed on wsl . It's path is /usr/bin/gdb. I have copied same path to launch.json in miDebuggerPath.

Here is my launch.json :

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

    {
        "name": "(gdb) Launch",
        "type": "cppdbg",
        "request": "launch",
        "program": "${workspaceFolder}/bin/main",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": true,
        "MIMode": "gdb",
        "miDebuggerPath": "/usr/bin/gdb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ]
    }
]

}

It should not throw the error and I should able to launch my debugger.

Body:
I had the same problem, my solution was:

1. Change this section in launch.json

"miDebuggerPath": "/usr/bin/gdb",

for:

"miDebuggerPath": "C:/MinGW/bin/gdb.exe",

2. Do you need to install in your PC  MinGW, this is the link:

https://osdn.net/projects/mingw/downloads/68260/mingw-get-setup.exe/

3. Next, open the MinGW then you install in the URL "C:/MinGW/bin" the gdb (select)

mingw32-gdb-bin

4. Enjoy the vs-code


问:
How to select some characters in value of a column and create a new column with this value
I have a csv as below:

```
Date        File Name
11/05/2018  CFL200_ABCD
11/06/2018  CFL203_DFSA
```

I would like to create a new column with values are characters before "_" in the File Name column

```
Date        File Name        ID
11/05/2018  CFL200_ABCD      CFL200
11/06/2018  CFL203_DFSA      CFL203
```

How could I do that? Thanks.

答:
Use first split to split string into sub-string and then get item through index

```<code>df["ID"] = df["File Name"].str.split('_').str[0]
df
         Date    File Name      ID
0  11/05/2018  CFL200_ABCD  CFL200
1  11/06/2018  CFL203_DFSA  CFL203
</code>```

Body:
I have a csv as below:

Date        File Name
11/05/2018  CFL200_ABCD
11/06/2018  CFL203_DFSA

I would like to create a new column with values are characters before "_" in the File Name column

Date        File Name        ID
11/05/2018  CFL200_ABCD      CFL200
11/06/2018  CFL203_DFSA      CFL203

How could I do that? Thanks.

Body:
Use first split to split string into sub-string and then get item through index

df["ID"] = df["File Name"].str.split('_').str[0]
df
         Date    File Name      ID
0  11/05/2018  CFL200_ABCD  CFL200
1  11/06/2018  CFL203_DFSA  CFL203


问:
Problem mapping multiple relations using Entity Framework code-first

Scenario

I have a model that has the following setup:

A member can be member of multiple memberlists. A memberlist can have multiple members. I also defined that a memberlist can have a seperate set of optional members. Basically I have a double n-m relationship between member and memberlist. What's more, a memberlist is always owned by a member, the one person that created the memberlist that is.

Problem

Entity framework code-first is unable to map this relationship correctly eventhough I tell it how to map the relationships. I get the following error when I try to use the DbContext the first time

```<code>Schema specified is not valid. Errors:
(32,6) : error 0040: Type MemberList_Members is not defined in namespace NerdCooking.Models (Alias=Self).
(33,6) : error 0040: Type MemberList_OptionalMembers is not defined in namespace NerdCooking.Models (Alias=Self).
</code>```

What I have tried

The first attempt to use the model in the scenario fails, because it's clear EF doesn't know how to map the n-m relationships. So I told the framework explicitly how to fix the situation.

```<code>// Map the relation between members of a memberlist and the memberlist
// to a Membership table
modelBuilder.Entity<MemberList>().HasMany(memberList => memberList.Members)
    .WithMany(member => member.MemberLists)
    .Map(mapping => mapping.MapLeftKey("MemberId")
        .MapRightKey("MemberListId").ToTable("Membership"));

// Map the relation between optional members of a memberlist and the memberlist
// to a separate table
modelBuilder.Entity<MemberList>().HasMany(memberList => memberList.OptionalMembers)
    .WithMany(member => member.MemberLists)
    .Map(mapping => mapping.MapLeftKey("MemberId")
        .MapRightKey("MemberListId").ToTable("OptionalMembership"));

// Map the relationship between the owner and the memberlist
modelBuilder.Entity<MemberList>().HasRequired(memberList => memberList.Owner)
    .WithMany(member => member.MemberLists).WillCascadeOnDelete(true);
</code>```

My question

Is this scenario possible with Entity framework 4.1 code-first? And if so, what's the best way to fix the mapping issue I'm experiencing?

I can always change the model so that it features a Membership entity that links a member to a memberlist. It makes the whole thing a bit more explicit and I can then add a property to that entity to mark it as optional.

I think however that this is a scenario that should have worked, so I hope someone did this before and knows what the trick is to get it working correctly.

答: All your mappings contain .WithMany(member => member.MemberLists). That is incorrect. You need separate navigation property for each relation = you can use each navigation property only for one relation mapping.

ContentLicense: CC BY-SA 3.0

Body:
Scenario

I have a model that has the following setup:

A member can be member of multiple memberlists. A memberlist can have multiple members. I also defined that a memberlist can have a seperate set of optional members. Basically I have a double n-m relationship between member and memberlist. What's more, a memberlist is always owned by a member, the one person that created the memberlist that is.

Problem

Entity framework code-first is unable to map this relationship correctly eventhough I tell it how to map the relationships. I get the following error when I try to use the DbContext the first time

Schema specified is not valid. Errors:
(32,6) : error 0040: Type MemberList_Members is not defined in namespace NerdCooking.Models (Alias=Self).
(33,6) : error 0040: Type MemberList_OptionalMembers is not defined in namespace NerdCooking.Models (Alias=Self).

What I have tried

The first attempt to use the model in the scenario fails, because it's clear EF doesn't know how to map the n-m relationships. So I told the framework explicitly how to fix the situation.

// Map the relation between members of a memberlist and the memberlist
// to a Membership table
modelBuilder.Entity<MemberList>().HasMany(memberList => memberList.Members)
    .WithMany(member => member.MemberLists)
    .Map(mapping => mapping.MapLeftKey("MemberId")
        .MapRightKey("MemberListId").ToTable("Membership"));

// Map the relation between optional members of a memberlist and the memberlist
// to a separate table
modelBuilder.Entity<MemberList>().HasMany(memberList => memberList.OptionalMembers)
    .WithMany(member => member.MemberLists)
    .Map(mapping => mapping.MapLeftKey("MemberId")
        .MapRightKey("MemberListId").ToTable("OptionalMembership"));

// Map the relationship between the owner and the memberlist
modelBuilder.Entity<MemberList>().HasRequired(memberList => memberList.Owner)
    .WithMany(member => member.MemberLists).WillCascadeOnDelete(true);

My question

Is this scenario possible with Entity framework 4.1 code-first? And if so, what's the best way to fix the mapping issue I'm experiencing?

I can always change the model so that it features a Membership entity that links a member to a memberlist. It makes the whole thing a bit more explicit and I can then add a property to that entity to mark it as optional.

I think however that this is a scenario that should have worked, so I hope someone did this before and knows what the trick is to get it working correctly.


问:
No exact matches in call to instance method error message in Swift
I never get this before, What is the meaning of this error message in Swift:

No exact matches in call to instance method 'dataTask(with:completionHandler:)'

Here is my code block:

```<code>var request: NSMutableURLRequest? = nil
let task = URLSession.shared.dataTask(
            with: request,
            completionHandler: { data, response, error in
                DispatchQueue.main.async(execute: {
                  /// ...
                })
            })
task.resume()
</code>```

Bug Report

Reported via feedbackassistant.apple.com: FB7717686

Note: The Error still exists in the Xcode Version 14.3 on 2023, May 1

答:
Why Xcode Yelling?

Maybe the message text seems a little bit self-explanatory but because Xcode does not precisely point to the parameter itself, a little bit hard to figure out the first time.

Xcode is yelling because the method wants to see exact parameter types on the method call, that is easy.

Solution for the Question:

```<code>var request: URLRequest? = nil

let task = URLSession.shared.dataTask(
            with: request!,
            completionHandler: { data, response, error in
                DispatchQueue.main.async(execute: {

                })
            })
task.resume()
</code>```

Just used the URLRequest instead of the NSMutableURLRequest.

A SwiftUI Case

Let's assume this is your UI:

```<code>        ZStack() {
            Image(systemName: "photo")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .background(Color.green)
                .foregroundColor(Color.white)
                .cornerRadius(12)
            Text(getToday())
                .font(.headline)
            }
        }
</code>```

And this is the method that you're calling in the Text(...):

```<code>    func getToday() -> Any?
    {
        let now = Date()
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day], from: now)
        return components.day

    }
</code>```

Solution

In the example above solution would be changing the Any? to a String type.

A NSURL Case

```<code>if let url = NSURL(String: "http://example-url.com/picture.png") {
  // ...
}
</code>```

Solution

```<code>if let url = URL(String: "http://example-url.com/picture.png") {
  // ...
}
</code>```

ℹ No exact matches in call to instance method '* * *'

This is a general error message for using the wrong type in the method calls. That's why I added here to help others.

I hope this answer will help some of you guys.

Best.

Body:
I never get this before, What is the meaning of this error message in Swift:

No exact matches in call to instance method 'dataTask(with:completionHandler:)'

Here is my code block:

var request: NSMutableURLRequest? = nil
let task = URLSession.shared.dataTask(
            with: request,
            completionHandler: { data, response, error in
                DispatchQueue.main.async(execute: {
                  /// ...
                })
            })
task.resume()

Bug Report

Reported via feedbackassistant.apple.com: FB7717686

Note: The Error still exists in the Xcode Version 14.3 on 2023, May 1

Body:
Why Xcode Yelling?

Maybe the message text seems a little bit self-explanatory but because Xcode does not precisely point to the parameter itself, a little bit hard to figure out the first time.

Xcode is yelling because the method wants to see exact parameter types on the method call, that is easy.

Solution for the Question:

var request: URLRequest? = nil

let task = URLSession.shared.dataTask(
            with: request!,
            completionHandler: { data, response, error in
                DispatchQueue.main.async(execute: {

                })
            })
task.resume()

Just used the URLRequest instead of the NSMutableURLRequest.

A SwiftUI Case

Let's assume this is your UI:

        ZStack() {
            Image(systemName: "photo")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .background(Color.green)
                .foregroundColor(Color.white)
                .cornerRadius(12)
            Text(getToday())
                .font(.headline)
            }
        }

And this is the method that you're calling in the Text(...):

    func getToday() -> Any?
    {
        let now = Date()
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day], from: now)
        return components.day

    }

Solution

In the example above solution would be changing the Any? to a String type.

A NSURL Case

if let url = NSURL(String: "http://example-url.com/picture.png") {
  // ...
}

Solution

if let url = URL(String: "http://example-url.com/picture.png") {
  // ...
}

ℹ No exact matches in call to instance method '* * *'

This is a general error message for using the wrong type in the method calls. That's why I added here to help others.

I hope this answer will help some of you guys.

Best.


问:
How to Check if Timer is Active Before Creating a New One
I came across this code for a timer on another thread. When you press the RaisedButton multiple times concurrently it adds a -1 second for every click thus increasing the rate of decrease.

Any ideas for the easiest way to check if the timer is already active and if it is to not let the RaisedButton create a new one. Thanks!

```<code>import 'dart:async';

[...]

Timer _timer;
int _start = 10;

void startTimer() {
  const oneSec = const Duration(seconds: 1);
  _timer = new Timer.periodic(
    oneSec,
    (Timer timer) => setState(
      () {
        if (_start < 1) {
          timer.cancel();
        } else {
          _start = _start - 1;
        }
      },
    ),
  );
}

@override
void dispose() {
  _timer.cancel();
  super.dispose();
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_start")
      ],
    ),
  );
}
</code>```

答:
Add a check to see if _timer is already active using the isActive property of Timers. If it's already active, it won't create a new one.

Example:

```<code>void startTimer() {
  const oneSec = const Duration(seconds: 1);
  if(!_timer?.isActive) {
    _timer = new Timer.periodic(
      oneSec,
      (Timer timer) => setState(
        () {
          if (_start < 1) {
            timer.cancel();
          } else {
            _start = _start - 1;
          }
        },
      ),
    );
  }
}
</code>```

Body:
I came across this code for a timer on another thread. When you press the RaisedButton multiple times concurrently it adds a -1 second for every click thus increasing the rate of decrease.

Any ideas for the easiest way to check if the timer is already active and if it is to not let the RaisedButton create a new one. Thanks!

import 'dart:async';

[...]

Timer _timer;
int _start = 10;

void startTimer() {
  const oneSec = const Duration(seconds: 1);
  _timer = new Timer.periodic(
    oneSec,
    (Timer timer) => setState(
      () {
        if (_start < 1) {
          timer.cancel();
        } else {
          _start = _start - 1;
        }
      },
    ),
  );
}

@override
void dispose() {
  _timer.cancel();
  super.dispose();
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_start")
      ],
    ),
  );
}

Body:
Add a check to see if _timer is already active using the isActive property of Timers. If it's already active, it won't create a new one.

Example:

void startTimer() {
  const oneSec = const Duration(seconds: 1);
  if(!_timer?.isActive) {
    _timer = new Timer.periodic(
      oneSec,
      (Timer timer) => setState(
        () {
          if (_start < 1) {
            timer.cancel();
          } else {
            _start = _start - 1;
          }
        },
      ),
    );
  }
}


问:
Copy data in array of a nested array of an object
So guys, I don't how to give a topic to this one. I'm having trouble to copy data from array of Object to another newly created array.

For example, I want to copy and create a new array that contain all category of animals of every person in my database.

```<code> people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]
</code>```

So, I created a new array named animalCategory to hold every category available.

```<code> // declare new array to hold category of animals
 let animalCategory = []
</code>```

This is the logic I came up with:-

```<code>// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            // loop and check existing animal categories in animalCategory array
            animalCategory.forEach(category => {
                // check if MATCH?
                if(category === animal.category) {
                    break // or just continue or will NOT BE SAVE
                }

                // if NOT MATCH, then
                else {
                    // SAVE new category
                    animalCategory.push(animal.category)
                }
            })
        }
    })
})

// see result
console.log(animalCategory.length)
</code>```

But unfortunately I got like a very big array of animalCategory as a result. And a lot of repetative animals category. (like shown below)

UPDATED: the output I want to seek is:-

```<code>animalCategory: [ 'cat', 'dog', 'iguana', 'fish']
</code>```

How should I change my logic then? And is there any other way I can do this?

答:
That's another solution.</p>

```<code>people.forEach(people => {
   if (people.animals && people.animals.length) {
       people.animals.forEach(categories => {
           if (animalCategories.indexOf(categories.category) === -1) {
               animalCategories.push(categories.category);
           }
       });
   }
});
</code>```

Body:
So guys, I don't how to give a topic to this one. I'm having trouble to copy data from array of Object to another newly created array.

For example, I want to copy and create a new array that contain all category of animals of every person in my database.

 people = [
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

So, I created a new array named animalCategory to hold every category available.

 // declare new array to hold category of animals
 let animalCategory = []

This is the logic I came up with:-

// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            // loop and check existing animal categories in animalCategory array
            animalCategory.forEach(category => {
                // check if MATCH?
                if(category === animal.category) {
                    break // or just continue or will NOT BE SAVE
                }

                // if NOT MATCH, then
                else {
                    // SAVE new category
                    animalCategory.push(animal.category)
                }
            })
        }
    })
})

// see result
console.log(animalCategory.length)

But unfortunately I got like a very big array of animalCategory as a result. And a lot of repetative animals category. (like shown below)

UPDATED: the output I want to seek is:-

animalCategory: [ 'cat', 'dog', 'iguana', 'fish']

How should I change my logic then? And is there any other way I can do this?

Body:
That's another solution.

people.forEach(people => {
   if (people.animals && people.animals.length) {
       people.animals.forEach(categories => {
           if (animalCategories.indexOf(categories.category) === -1) {
               animalCategories.push(categories.category);
           }
       });
   }
});


问:
Get
 value and assign to url parameter in iframe using jquery onclick
It's a question related to this.

From

```<code><ul id="myid">
    <li value="VALUE1">featured</li>
    <li value="VALUE2">hey</li>
    <li value="VALUE3">wish</li>
<ul>
<iframe src="" id="myiframe" width="460" height="300"></iframe>
</code>```

To

```<code><iframe src="http://example.com/test?=VALUE1 or VALUE2 or VALUE3" id="myiframe" width="460" height="300"></iframe>
</code>```

onclick

答:
Try this</p>

```<code><ul id="myid">
    <li onclick="myFunction('VALUE1')" value="VALUE1">featured</li>
    <li onclick="myFunction('VALUE2')" value="VALUE2">hey</li>
    <li onclick="myFunction('VALUE1')" value="VALUE3">wish</li>
</ul>
<iframe src="" id="myiframe" width="460" height="300"></iframe>

<script>
    var myURL = 'http://example.com/';

    function myFunction(value) {
        document.getElementById("myiframe").src = myURL + "test?=" + value;
    }
</script>

</code>```

Title: Get <li> value and assign to url parameter in iframe using jquery onclick

Body:
It's a question related to this.

From

featured

hey

wish

To

onclick

Body:
Try this

<ul id="myid">
    <li onclick="myFunction('VALUE1')" value="VALUE1">featured</li>
    <li onclick="myFunction('VALUE2')" value="VALUE2">hey</li>
    <li onclick="myFunction('VALUE1')" value="VALUE3">wish</li>
</ul>
<iframe src="" id="myiframe" width="460" height="300"></iframe>

<script>
    var myURL = 'http://example.com/';

    function myFunction(value) {
        document.getElementById("myiframe").src = myURL + "test?=" + value;
    }
</script>


问:
Is there an alternative for positive & negative lookahead and negative lookbehind for my REGEX that would work in Safari?
I have a REGEX to check the validity of a username which looks like this:

/^(?=.{5,30}$)(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9._-]+(?<![_.-])$/

Basically, my username has the following constraints:

it should be 5-30 characters long,

it can contain any alphanumeric [a-z A-Z 0-9] characters,

it could contain symbols like _.-

it can't start or end with these symbols

the symbols can't be adjacent to each other

This REGEX works perfectly in Chrome, but as we all know, Safari doesn't support lookbehind in REGEX. However, I am not sure if they do support lookahead.

My question is, is there a way to convert this REGEX into something that Safari understands?

Thanks in advance!

答:
You may rephrase your regex as:

```<code>/^(?=.{5,30}$)(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9._-]*[a-zA-Z0-9]$/
                                                     ^^^ change is here
</code>```

The logic I am using relies on that the only purpose of the negative lookbehind at the end of the pattern was to assert that the final character is not dot, underscore, or hyphen.  We can instead just use a character class to handle this.  Note that as a side-effect, the immediately previous character class becomes zero or more times, since now the one or more requirement would always be met by the final character.

Body:
You may rephrase your regex as:

/^(?=.{5,30}$)(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9._-]*[a-zA-Z0-9]$/
                                                     ^^^ change is here

The logic I am using relies on that the only purpose of the negative lookbehind at the end of the pattern was to assert that the final character is not dot, underscore, or hyphen.  We can instead just use a character class to handle this.  Note that as a side-effect, the immediately previous character class becomes zero or more times, since now the one or more requirement would always be met by the final character.


问:
Assign NaN to a column based on another column
The title may be off a little. I will explain this properly. I will receive a DataFrame df with unexpected format of one of the column called marker.

Sometimes, I will marker, mixed of single marker or range marker :

```<code>marker             place1       place2
45                  PQR           STU
145.0-100           ABC           DEF
267.0-175.8         GHI           KLM
</code>```

During transformation, I need to split marker that contains - and becomes like this :

```<code>marker        firstkm    lastkm    place1       place2
45             45         NaN       PQR           STU
145.0-100      145.0      100       ABC           DEF
267.0-175.8    267.0      175.8     GHI           KLM
</code>```

I can also get the following DataFrame where all marker are not a range.

```<code>marker    place1       place2
145.0      ABC           DEF
267.0      GHI           KLM
</code>```

With this piece of code:

```<code>    #Split marker to temporary dataframe , split_m
    split_m = df.marker.str.split('-', expand=True)
    split_m.columns=['firstkm', 'lastkm'] #hitting error here
    split_m = split_km[['firstkm', 'lastkm']].replace([None], np.nan)
</code>```

I can achieve the result I wanted if the DataFrame is like the first example I showed above. However, I am not able to achieve the result if the DataFrame is like the second example I showed. I am getting error :

ValueError: Length mismatch: Expected axis has 1 elements, new values
  have 2 elements

I understand the error is caused by, the DataFrame unable to put any value in lastkm. But I don't know how to handle this..

If I print split_m for the second DataFrame, I will get this :

```<code>marker     firstkm
145.0       145.0
267.0       267.0
</code>```

How can I assign np.nan immediately to lastkm to produce the following result:

```<code>marker     firstkm   lastkm
145.0       145.0     NaN
267.0       267.0     NaN
</code>```

EDIT

Another pattern I encounter :

```<code>marker        firstkm      lastkm    place1       place2
45             45           NaN       PQR           STU
145.0-100      145.0        100       ABC           DEF
267.0-175.8    267.0        175.8     GHI           KLM
18.1J          18.1J        Nan       GHI           KLM
P7.991-54.3    P7.991       54.3      GHI           KLM
UPM Ex 0.5     UPM Ex 0.5   NaN       PPP           SSS
</code>```

UPMEx0.5 is stil acceptable. Case insensitive.

答:
You can try this:

```<code># create a copy of the original df, split_m
split_m = df.copy()

# create the additional required columns with default 'NaN' values
split_m.insert(1, 'firstkm', np.nan)
split_m.insert(2, 'lastkm', np.nan)

# unpack the splitted values to the columns. If nothing to unpack
# for 'lastkm', it will become None
split_m[['firstkm', 'lastkm']] = df.marker.str.split('-', expand=True)
# fill None values with np.nan
split_m.fillna(np.nan, inplace=True)

print(split_m)
</code>```

Output:

```<code>        marker firstkm lastkm place1 place2
0           45      45    NaN    PQR    STU
1    145.0-100   145.0    100    ABC    DEF
2  267.0-175.8   267.0  175.8    GHI    KLM
3        145.0   145.0    NaN    ABC    DEF
4        267.0   267.0    NaN    GHI    KLM
</code>```

New scenario with changed input:

```<code># tab separated data for read_clipboard()
# please make sure that you source data
# has a separator other than space.
'''
marker  place1  place2
45  PQR STU
145.0-100   ABC DEF
267.0-175.8 GHI KLM
145.0   ABC DEF
267.0   GHI KLM
P7.991-54.3 GHI KLM
UPM Ex 0.5  PPP SSS
'''

import pandas as pd
import numpy as np

df = pd.read_clipboard()

# #Split marker to temporary dataframe , split_m
split_m = df.copy()

# create the additional required columns with default 'NaN' values
split_m.insert(1, 'firstkm', np.nan)
split_m.insert(2, 'lastkm', np.nan)

# unpack the splitted values to the columns. If nothing to unpack
# for 'lastkm', it will become None
split_m[['firstkm', 'lastkm']] = df.marker.str.split('-', expand=True)
split_m.fillna(np.nan, inplace=True)

print(split_m)
</code>```

Output:

```<code>        marker     firstkm lastkm place1 place2
0           45          45    NaN    PQR    STU
1    145.0-100       145.0    100    ABC    DEF
2  267.0-175.8       267.0  175.8    GHI    KLM
3        145.0       145.0    NaN    ABC    DEF
4        267.0       267.0    NaN    GHI    KLM
5  P7.991-54.3      P7.991   54.3    GHI    KLM
6   UPM Ex 0.5  UPM Ex 0.5    NaN    PPP    SSS
</code>```

Body:
The title may be off a little. I will explain this properly. I will receive a DataFrame df with unexpected format of one of the column called marker.

Sometimes, I will marker, mixed of single marker or range marker :

marker             place1       place2
45                  PQR           STU
145.0-100           ABC           DEF
267.0-175.8         GHI           KLM

During transformation, I need to split marker that contains - and becomes like this :

marker        firstkm    lastkm    place1       place2
45             45         NaN       PQR           STU
145.0-100      145.0      100       ABC           DEF
267.0-175.8    267.0      175.8     GHI           KLM

I can also get the following DataFrame where all marker are not a range.

marker    place1       place2
145.0      ABC           DEF
267.0      GHI           KLM

With this piece of code:

    #Split marker to temporary dataframe , split_m
    split_m = df.marker.str.split('-', expand=True)
    split_m.columns=['firstkm', 'lastkm'] #hitting error here
    split_m = split_km[['firstkm', 'lastkm']].replace([None], np.nan)

I can achieve the result I wanted if the DataFrame is like the first example I showed above. However, I am not able to achieve the result if the DataFrame is like the second example I showed. I am getting error :

ValueError: Length mismatch: Expected axis has 1 elements, new values
  have 2 elements

I understand the error is caused by, the DataFrame unable to put any value in lastkm. But I don't know how to handle this..

If I print split_m for the second DataFrame, I will get this :

marker     firstkm
145.0       145.0
267.0       267.0

How can I assign np.nan immediately to lastkm to produce the following result:

marker     firstkm   lastkm
145.0       145.0     NaN
267.0       267.0     NaN

EDIT

Another pattern I encounter :

marker        firstkm      lastkm    place1       place2
45             45           NaN       PQR           STU
145.0-100      145.0        100       ABC           DEF
267.0-175.8    267.0        175.8     GHI           KLM
18.1J          18.1J        Nan       GHI           KLM
P7.991-54.3    P7.991       54.3      GHI           KLM
UPM Ex 0.5     UPM Ex 0.5   NaN       PPP           SSS

UPMEx0.5 is stil acceptable. Case insensitive.

Body:
You can try this:

# create a copy of the original df, split_m
split_m = df.copy()

# create the additional required columns with default 'NaN' values
split_m.insert(1, 'firstkm', np.nan)
split_m.insert(2, 'lastkm', np.nan)

# unpack the splitted values to the columns. If nothing to unpack
# for 'lastkm', it will become None
split_m[['firstkm', 'lastkm']] = df.marker.str.split('-', expand=True)
# fill None values with np.nan
split_m.fillna(np.nan, inplace=True)

print(split_m)

Output:

        marker firstkm lastkm place1 place2
0           45      45    NaN    PQR    STU
1    145.0-100   145.0    100    ABC    DEF
2  267.0-175.8   267.0  175.8    GHI    KLM
3        145.0   145.0    NaN    ABC    DEF
4        267.0   267.0    NaN    GHI    KLM

New scenario with changed input:

# tab separated data for read_clipboard()
# please make sure that you source data
# has a separator other than space.
'''
marker  place1  place2
45  PQR STU
145.0-100   ABC DEF
267.0-175.8 GHI KLM
145.0   ABC DEF
267.0   GHI KLM
P7.991-54.3 GHI KLM
UPM Ex 0.5  PPP SSS
'''

import pandas as pd
import numpy as np

df = pd.read_clipboard()

# #Split marker to temporary dataframe , split_m
split_m = df.copy()

# create the additional required columns with default 'NaN' values
split_m.insert(1, 'firstkm', np.nan)
split_m.insert(2, 'lastkm', np.nan)

# unpack the splitted values to the columns. If nothing to unpack
# for 'lastkm', it will become None
split_m[['firstkm', 'lastkm']] = df.marker.str.split('-', expand=True)
split_m.fillna(np.nan, inplace=True)

print(split_m)

Output:

        marker     firstkm lastkm place1 place2
0           45          45    NaN    PQR    STU
1    145.0-100       145.0    100    ABC    DEF
2  267.0-175.8       267.0  175.8    GHI    KLM
3        145.0       145.0    NaN    ABC    DEF
4        267.0       267.0    NaN    GHI    KLM
5  P7.991-54.3      P7.991   54.3    GHI    KLM
6   UPM Ex 0.5  UPM Ex 0.5    NaN    PPP    SSS


问:
Android How Do I Place ICON (ie Search Icon) inside content area of EditText or AutoCompleteTextView
Thats it how do I place an icon inside text area as background of EditText or AutoCompleteTextView?   </p>

Body: android:drawableRight="@drawable/somedrawable"


问:
Karate framework for larger data load porcess using post soap service
I have a requirement in which 10,000 plus rows of data needs to be mapped for a SOAP xml post service using karate's feature file examples table. Since data maintenance is easy using csv file, I used below code (copied only relevant code, xml is embedded in feature file) for scenario outline,

def csvData = read('test.csv')
Examples:
| csvData |
Execution hits performance issue, after 800 transactions and test fails.
Please advise, if there is any way to achieve this large data load process using Karate and web services post.

答:
Don't use the CSV / Dynamic Scenario Outline because it would have to load all the rows into memory.

Use karate.repeat() https://github.com/intuit/karate#loops - and use a second feature to make the final request, similar to data-driven testing: https://github.com/intuit/karate#data-driven-features

In the loop you can get the current index, and write some function to get that particular data, it can be from a CSV or even a database.


问:
Print an array in the range of a user input
Below is my code:

```<code> n = int(input())

 for i in range(n):

    d = int(input())

    for i in range(d):
        a = list(map(int,input().split()))
    print(a)
</code>```

But I want my code to do this, for example:
Suppose d = 4 is my user input
Now, I want (random example) a = [1, 4 , 8, 19]. That too from user input.
This is an example of the output of. I am not able to frame the question properly. So, here is the  desired output:

3 #input for n

2 #input for d

[4,6] #output for a

5 #input for 2nd d

[4,2,1,4,7] #output for a, 5 elements as d = 5

2 #input for last d, as 'n' was 3

[1,9] #(the last array a)

答:
Problems with your code

you are using same i variable in both for loop

a = list(map(int,input().split())) scans whole line, so no need of for loop

Solution

n = int(input())

for i in range(n):

    d = int(input())

    a = list(map(int,input().split()))
    print(a)
```

<h2>Output</h2>

<pre class="lang-sh prettyprint-override"><code>2
5
1 2 3 4 5
[1, 2, 3, 4, 5]  # Output
2
1 2
[1, 2]  # output
</code>```

If you got your answer please accept it else comment What's the problem?

Body:
Below is my code:

 n = int(input())

 for i in range(n):

    d = int(input())

    for i in range(d):
        a = list(map(int,input().split()))
    print(a)

But I want my code to do this, for example:
Suppose d = 4 is my user input
Now, I want (random example) a = [1, 4 , 8, 19]. That too from user input.
This is an example of the output of. I am not able to frame the question properly. So, here is the  desired output:

3 #input for n

2 #input for d

[4,6] #output for a

5 #input for 2nd d

[4,2,1,4,7] #output for a, 5 elements as d = 5

2 #input for last d, as 'n' was 3

[1,9] #(the last array a)

Body:
Problems with your code

you are using same i variable in both for loop

a = list(map(int,input().split())) scans whole line, so no need of for loop

Solution

n = int(input())

for i in range(n):

    d = int(input())

    a = list(map(int,input().split()))
    print(a)

Output

2
5
1 2 3 4 5
[1, 2, 3, 4, 5]  # Output
2
1 2
[1, 2]  # output

If you got your answer please accept it else comment What's the problem?


答:
```<code>you can use like this
<ul id="myid">
  <li class ="get" value="VALUE1">featured</li>
  <li class ="get" value="VALUE2">hey</li>
  <li class ="get" value="VALUE3">wish</li>
<ul>
</code>```

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
   $(".get").click(function(){
    data = $(this).attr('value');
    url = "http://example.com/test?=";
    $('#myiframe').attr('src', url+data);
  });
});
</script>
</code>```

Body:
you can use like this
<ul id="myid">
  <li class ="get" value="VALUE1">featured</li>
  <li class ="get" value="VALUE2">hey</li>
  <li class ="get" value="VALUE3">wish</li>
<ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
   $(".get").click(function(){
    data = $(this).attr('value');
    url = "http://example.com/test?=";
    $('#myiframe').attr('src', url+data);
  });
});
</script>


问:
How do I reference a textarea value in another table cell?
I want to reference the content of a text area, but I keep getting undefined:

```<code>$(".send-comment").click(function(e) {
    e.preventDefault();
    var data = $(this).siblings(".comment-text").val();
    alert(data);
});

<tr>
    <td>#textAreaTag(label=false, name="comment[text]", class="comment-text")#</td>
    <td>#submitTag(value="Send", class="send-comment")#</td>
</tr>
</code>```

I suspect it might be because the send button has no siblings (it's alone in a td)... but surely, there has to be a better way to get the value than using this.parent().sibling().child()...

I'm using classes because I have several comment forms on the same page that belong to different posts.

FYI, the generated source from my framework is as expected...

答:
The text area is not a sibling of the submit button (according to your code). The submit button's parent's (parent td) sibling's (td) child is submit tag.

so your code should be:

```<code>var data = $(this).parent().prev().find(".comment-text").val();
</code>```

Body:
I want to reference the content of a text area, but I keep getting undefined:

$(".send-comment").click(function(e) {
    e.preventDefault();
    var data = $(this).siblings(".comment-text").val();
    alert(data);
});

    #textAreaTag(label=false, name="comment[text]", class="comment-text")#
    #submitTag(value="Send", class="send-comment")#

I suspect it might be because the send button has no siblings (it's alone in a td)... but surely, there has to be a better way to get the value than using this.parent().sibling().child()...

I'm using classes because I have several comment forms on the same page that belong to different posts.

FYI, the generated source from my framework is as expected...

Body:
The text area is not a sibling of the submit button (according to your code). The submit button's parent's (parent td) sibling's (td) child is submit tag.

so your code should be:

var data = $(this).parent().prev().find(".comment-text").val();


问:
I am losing data when going from constructor to main method in a different class. What is happening?
```<code>```
  public class tuna
  {
     private int hour;
     private int minute;
     private int second;

     // Constructor with 0 passed arguments
     public tuna()
     {
        this(0,0,0);
     }

     // Constructor with 1 passed arguments
     public tuna(int h)
     {
        this(h,0,0);
     }

     // Constructor with 2 passed arguments
     public tuna(int h, int m)
     {
        this(h,m,0);
     }

     // Constructor with 3 passed arguments
     public tuna(int h, int m, int s)
     {
        setTime(h,m,s);
     }

     // setTime method
     public void setTime(int h, int m, int s)
     {
        setHour(h);
        setMinute(m);
        setSecond(s);
     }

     /*----------Set methods----------*/
     public void setHour(int h) {hour = ( (h>=0 && h<24)?h : 0);}
     public void setMinute(int m) {hour = ( (m>=0 && m<60)?m : 0);}
     public void setSecond(int s) {hour = ( (s>=0 && s<60)?s : 0);}

     /*----------Get methods----------*/
     public int getHour() {
        return hour;}
     public int getMinute() {
        return minute;}
     public int getSecond() {
        return second;}

     public String toMilitary()
     {
        return String.format("%02d:%02d:%02d", getHour(), getMinute(), getSecond());
     }
  }
```
</code>```

Above is the class containing the constructors and methods and below is the class with the main function that actually calls on the constructors and methods.

I was making this simple program that displays the time and the exercise was showing that you can have multiple constructors with different amounts of parameters.  The only problem is when I am at the step of the constructor all the information is correct but when the debugger jumps from the constructor to the class it is being used in all the information is gone except this one line.  I think it has something to do with the way I set the constructors up but I can not figure out what I did wrong. Any help would be great. Thank you!

Here is the output that I get:

The desired output:

And in case any of you recognize this exercise it is one of Bucky's Tutorials.
P.S. I normally would not post all the code but I literally have no idea what may or may not be pertinent to my problem.

```<code>
class apples
{
   public static void main(String[] args)
   {
      tuna obj1 = new tuna(); // No parameter constructor
      tuna obj2 = new tuna(5); // 1 parameter constructor
      tuna obj3 = new tuna(5,13); // 2 parameter constructor
      tuna obj4 = new tuna(5,13,43); // 3 parameter constructor

      System.out.printf("%s\n", obj1.toMilitary());
      System.out.printf("%s\n", obj2.toMilitary());
      System.out.printf("%s\n", obj3.toMilitary());
      System.out.printf("%s\n", obj4.toMilitary());
   }
}
</code>```

答:
You are assigning hour in all setters, while you should be setting hour, minute and second:

```<code>/*----------Set methods----------*/
public void setHour(int h) {hour = ( (h>=0 && h<24)?h : 0);}
public void setMinute(int m) {minute = ( (m>=0 && m<60)?m : 0);}
public void setSecond(int s) {second = ( (s>=0 && s<60)?s : 0);}
</code>```

Body:
```
  public class tuna
  {
     private int hour;
     private int minute;
     private int second;

     // Constructor with 0 passed arguments
     public tuna()
     {
        this(0,0,0);
     }

     // Constructor with 1 passed arguments
     public tuna(int h)
     {
        this(h,0,0);
     }

     // Constructor with 2 passed arguments
     public tuna(int h, int m)
     {
        this(h,m,0);
     }

     // Constructor with 3 passed arguments
     public tuna(int h, int m, int s)
     {
        setTime(h,m,s);
     }

     // setTime method
     public void setTime(int h, int m, int s)
     {
        setHour(h);
        setMinute(m);
        setSecond(s);
     }

     /*----------Set methods----------*/
     public void setHour(int h) {hour = ( (h>=0 && h<24)?h : 0);}
     public void setMinute(int m) {hour = ( (m>=0 && m<60)?m : 0);}
     public void setSecond(int s) {hour = ( (s>=0 && s<60)?s : 0);}

     /*----------Get methods----------*/
     public int getHour() {
        return hour;}
     public int getMinute() {
        return minute;}
     public int getSecond() {
        return second;}

     public String toMilitary()
     {
        return String.format("%02d:%02d:%02d", getHour(), getMinute(), getSecond());
     }
  }
```

Above is the class containing the constructors and methods and below is the class with the main function that actually calls on the constructors and methods.

I was making this simple program that displays the time and the exercise was showing that you can have multiple constructors with different amounts of parameters.  The only problem is when I am at the step of the constructor all the information is correct but when the debugger jumps from the constructor to the class it is being used in all the information is gone except this one line.  I think it has something to do with the way I set the constructors up but I can not figure out what I did wrong. Any help would be great. Thank you!

Here is the output that I get:

The desired output:

And in case any of you recognize this exercise it is one of Bucky's Tutorials.
P.S. I normally would not post all the code but I literally have no idea what may or may not be pertinent to my problem.

class apples
{
   public static void main(String[] args)
   {
      tuna obj1 = new tuna(); // No parameter constructor
      tuna obj2 = new tuna(5); // 1 parameter constructor
      tuna obj3 = new tuna(5,13); // 2 parameter constructor
      tuna obj4 = new tuna(5,13,43); // 3 parameter constructor

      System.out.printf("%s\n", obj1.toMilitary());
      System.out.printf("%s\n", obj2.toMilitary());
      System.out.printf("%s\n", obj3.toMilitary());
      System.out.printf("%s\n", obj4.toMilitary());
   }
}

Body:
You are assigning hour in all setters, while you should be setting hour, minute and second:

/*----------Set methods----------*/
public void setHour(int h) {hour = ( (h>=0 && h<24)?h : 0);}
public void setMinute(int m) {minute = ( (m>=0 && m<60)?m : 0);}
public void setSecond(int s) {second = ( (s>=0 && s<60)?s : 0);}


问:
Chrome opening every webpage inside iframe
I don't know what is happening with my PC and my Google Chrome browser. It is opening every webpage inside a iframe. I dont know why. I have tried resetting all the chrome settings and I even have tried deleting all the data ( deleted all folders related to chrome ) and re installing chrome over 10 times and still the same problem. It is really giving me pain.

You can clearly see that I am on the startup page of chrome and its showing me view frame source and reload frame. I searched it on google found 0 solutions or even 0 topics about this kind of issues. So I am really begging for a solution here..

答:
There is no actual frame, it's just an UI issue. There is a Chrome bug report about it here: https://bugs.chromium.org/p/chromium/issues/detail?id=1085040

Let's hope it will be resolved in an upcoming update.


问:
Codenameone - When to use callSerially with Dialogs?
In the answer here and in section 7.2.1 of the Codenameone Developer Guide, it is suggested that dialogs should be called using callSerially.  I assume that means instead of this:

```<code>                    dlg.showDialog();
</code>```

we should use:

```<code>                Display.getInstance().callSerially(() -> {
                    dlg.showDialog();
                });
</code>```

But I notice in various other parts of Codenameone code that Dialog.shows() are not wrapped in callSerially, for example ConnectionRequest.java, NetworkManager.java and XFClient.java.  Should those be using callSerially as suggested?  If not, what is the criteria to decide when to use callSerially for Dialogs and when to not?

Background:  I’m asking this question because after implementing the networking retry logic discussed here  my users are having some intermittent (and so far impossible to reliably replicate) app lock ups which I suspect may be related to conflict between my Yes/No dialog and a custom network issues dialog in XFClient (see below) that may happen concurrently.  I am wondering if I should always be using callSerially for these dialogs.

```<code>protected void setupConnection(ConnectionRequest req) {
        if (timeout > 0) {
            req.setTimeout(timeout);
        }
        if (readTimeout > 0) {
            req.setReadTimeout(readTimeout);
        }

        // remainder is custom code I added..

        if (silentRetryCount > 0) {
            req.setSilentRetryCount(silentRetryCount);
        }
        req.addExceptionListener(evt -> {
            if (evt != null) {
                if (req.getSilentRetryCount() > 0) {
                    //  silentRetryCount--;
                    req.setSilentRetryCount(req.getSilentRetryCount() - 1);
                    //  NetworkManager.getInstance().resetAPN();      // private, not sure if we need this?
                    req.retry();
                    return;
                }
                Exception exc = evt.getError();
                Log.e(exc);
                if (Display.isInitialized() && !Display.getInstance().isMinimized()
                        //                        && Dialog.show("Exception", exc.toString() + ": for URL " + url + "\n" + exc.getMessage(), "Retry", "Cancel")) {
                        && Dialog.show("Network Issue", "Hopefully it is just a bump in the road.  Suggest you retry...", "Retry", "Cancel")) {
                    req.retry();
                }
                // note: ConnectionRequest.handleException has an else block here setting retrying= false and killed=true

            }
        });
    }
</code>```

Note: The added code is modelled after the handleException method in ConnectionRequest.java.  I couldn't figure out how to add the resetAPN and else block so left those out.  Not sure if that was a mistake?

Any help appreciated.

答:
callSerially for dialogs should be used under two circumstances:

You're off the EDT - this is required

You're in an event chain and want the current event to flush. This is a complex edge case. I won't get into it since it doesn't apply for this case

Initially when the network manager logic was implemented we wrote the retry code. We didn't notice the EDT violation back then and it didn't manifest as much. Unfortunately as is the case with many bugs of this sort it's hard to get rid of it now.

There are other solutions for this but one of the better solutions is to use the network error handler globally which is far closer to what you want. Thisquestion covers the current usage for it: Distinguish between server-side errors and connection problems

Body:
In the answer here and in section 7.2.1 of the Codenameone Developer Guide, it is suggested that dialogs should be called using callSerially.  I assume that means instead of this:

                    dlg.showDialog();

we should use:

                Display.getInstance().callSerially(() -> {
                    dlg.showDialog();
                });

But I notice in various other parts of Codenameone code that Dialog.shows() are not wrapped in callSerially, for example ConnectionRequest.java, NetworkManager.java and XFClient.java.  Should those be using callSerially as suggested?  If not, what is the criteria to decide when to use callSerially for Dialogs and when to not?

Background:  I’m asking this question because after implementing the networking retry logic discussed here  my users are having some intermittent (and so far impossible to reliably replicate) app lock ups which I suspect may be related to conflict between my Yes/No dialog and a custom network issues dialog in XFClient (see below) that may happen concurrently.  I am wondering if I should always be using callSerially for these dialogs.

protected void setupConnection(ConnectionRequest req) {
        if (timeout > 0) {
            req.setTimeout(timeout);
        }
        if (readTimeout > 0) {
            req.setReadTimeout(readTimeout);
        }

        // remainder is custom code I added..

        if (silentRetryCount > 0) {
            req.setSilentRetryCount(silentRetryCount);
        }
        req.addExceptionListener(evt -> {
            if (evt != null) {
                if (req.getSilentRetryCount() > 0) {
                    //  silentRetryCount--;
                    req.setSilentRetryCount(req.getSilentRetryCount() - 1);
                    //  NetworkManager.getInstance().resetAPN();      // private, not sure if we need this?
                    req.retry();
                    return;
                }
                Exception exc = evt.getError();
                Log.e(exc);
                if (Display.isInitialized() && !Display.getInstance().isMinimized()
                        //                        && Dialog.show("Exception", exc.toString() + ": for URL " + url + "\n" + exc.getMessage(), "Retry", "Cancel")) {
                        && Dialog.show("Network Issue", "Hopefully it is just a bump in the road.  Suggest you retry...", "Retry", "Cancel")) {
                    req.retry();
                }
                // note: ConnectionRequest.handleException has an else block here setting retrying= false and killed=true

            }
        });
    }

Note: The added code is modelled after the handleException method in ConnectionRequest.java.  I couldn't figure out how to add the resetAPN and else block so left those out.  Not sure if that was a mistake?

Any help appreciated.


问:
Operator overloading Kotlin
I'm new to kotlin and I'm working on operators overloading for a custom class I defined. The class is called "Rational" and represents a rational number, like for example 117/1098. Class is defined as below and I have overloaded a bunch of operators, like plus, minus, times and so on. However I'm uncertain about what I have to do to overload "in" operator.

Here is my class:

data class Rational(val rational: String) {
    private val numerator: BigInteger
    private val denominator: BigInteger

    init {
        val splitted = rational.split("/")
        numerator = splitted[0].toBigInteger()
        denominator = when (splitted[1]) {
            "0" -> throw Exception("not allowed")
            else -> splitted[1].toBigInteger()
        }
    }

    operator fun plus(number: Rational): Rational {
        val gcm = denominator * number.denominator
        val numerator = (gcm / denominator) * numerator + (gcm / number.denominator) * number.numerator
        return Rational("$numerator/$gcm")
    }

    operator fun minus(number: Rational): Rational {
        val gcm = denominator * number.denominator
        val numerator = (gcm / denominator) * numerator - (gcm / number.denominator) * number.numerator
        return Rational("$numerator/$gcm")
    }

    operator fun times(number: Rational): Rational {
        val numerator = numerator * number.numerator
        val denominator = denominator * number.denominator
        return Rational("$numerator/$denominator")
    }

    operator fun div(number: Rational): Rational {
        val numerator = numerator * number.denominator
        val denominator = denominator * number.numerator
        return Rational("$numerator/$denominator")
    }

    operator fun compareTo(number: Rational): Int {
        val ratio = this.numerator.toFloat() / this.denominator.toFloat()
        val numberRatio = number.numerator.toFloat() / number.denominator.toFloat()
        if (ratio > numberRatio) {
            return 1
        } else if (ratio == numberRatio) {
            return 0
        }
        return -1
    }

    operator fun unaryMinus(): Rational {
        val inverseNumerator = -numerator
        return Rational("$inverseNumerator/$denominator")
    }

    operator fun unaryPlus(): Rational {
        return Rational("$numerator/$denominator")
    }

    operator fun rangeTo(end: Rational): Any {
        var range: MutableList<Rational> = arrayListOf()
        val startNumerator = this.numerator.toInt()
        val endNumerator = end.numerator.toInt()
        var index = 0
        if (this.denominator == end.denominator) {
            for (i in startNumerator..endNumerator) {
                range.add(index, Rational("$i/$denominator"))
            }
        }
        return range
    }

    operator fun contains(number: Rational): Boolean {
        if (this.denominator % number.denominator == 0.toBigInteger()
                && this.numerator <= number.numerator) {
            return true
        }
        return false
    }

    override fun toString(): String {
        val gcd = numerator.gcd(denominator)
        return if (gcd != null) {
            val newNumerator = numerator / gcd
            val newDenominator = denominator / gcd
            "$newNumerator/$newDenominator"
        } else {
            "$numerator/$denominator"
        }
    }
}
```

<pre class="lang-kotlin prettyprint-override"><code>infix fun Int.divBy(denominator: Int): Rational {
    if (denominator == 0) {
        throw Exception("denominator 0 not allowed")
    }

    return Rational("$this/$denominator")
}

infix fun Long.divBy(denominator: Long): Rational {
    if (denominator == 0L) {
        throw Exception("denominator 0 not allowed")
    }
    return Rational("$this/$denominator")
}

infix fun BigInteger.divBy(denominator: BigInteger): Rational {
    if (denominator == 0.toBigInteger()) {
        throw Exception("denominator 0 not allowed")
    }
    return Rational("$this/$denominator")
}

fun String.toRational(): Rational {
    return Rational(this)
}
</code>```

And here is my main body that obviously still doesn't compile:

fun main() {
    val half = 1 divBy 2
    val third = 1 divBy 3
    val twoThirds = 2 divBy 3

    println(half in third..twoThirds) // this line does not compile beacause in operator is not defined for the class
}
```

I guess I have to override "rangeTo" operator but I'm uncertain about the operator prototype. I there somebody that can please help me to get to the right track?

答:
A straightforward solution is to implement the Comparable Interface in your class.

data class Rational(val rational: String) : Comparable<Rational>

Then implement the compareTo() function, with your comparison logic.

```<code>override fun compareTo(other: Rational): Int {
    //Normalize the numerators of each rational
    val thisNumerator = this.numerator * other.denominator
    val otherNumerator = other.numerator * this.denominator
    //Then compare them
    return when{
        thisNumerator > otherNumerator -> 1
        thisNumerator < otherNumerator -> -1
        else -> 0
    }
}
</code>```

This will resolve the compile error without you needing to override the rangeTo() function with custom logic.

Title: Operator overloading Kotlin

Body:
I'm new to kotlin and I'm working on operators overloading for a custom class I defined. The class is called "Rational" and represents a rational number, like for example 117/1098. Class is defined as below and I have overloaded a bunch of operators, like plus, minus, times and so on. However I'm uncertain about what I have to do to overload "in" operator.

Here is my class:

data class Rational(val rational: String) {
    private val numerator: BigInteger
    private val denominator: BigInteger

    init {
        val splitted = rational.split("/")
        numerator = splitted[0].toBigInteger()
        denominator = when (splitted[1]) {
            "0" -> throw Exception("not allowed")
            else -> splitted[1].toBigInteger()
        }
    }

    operator fun plus(number: Rational): Rational {
        val gcm = denominator * number.denominator
        val numerator = (gcm / denominator) * numerator + (gcm / number.denominator) * number.numerator
        return Rational("$numerator/$gcm")
    }

    operator fun minus(number: Rational): Rational {
        val gcm = denominator * number.denominator
        val numerator = (gcm / denominator) * numerator - (gcm / number.denominator) * number.numerator
        return Rational("$numerator/$gcm")
    }

    operator fun times(number: Rational): Rational {
        val numerator = numerator * number.numerator
        val denominator = denominator * number.denominator
        return Rational("$numerator/$denominator")
    }

    operator fun div(number: Rational): Rational {
        val numerator = numerator * number.denominator
        val denominator = denominator * number.numerator
        return Rational("$numerator/$denominator")
    }

    operator fun compareTo(number: Rational): Int {
        val ratio = this.numerator.toFloat() / this.denominator.toFloat()
        val numberRatio = number.numerator.toFloat() / number.denominator.toFloat()
        if (ratio > numberRatio) {
            return 1
        } else if (ratio == numberRatio) {
            return 0
        }
        return -1
    }

    operator fun unaryMinus(): Rational {
        val inverseNumerator = -numerator
        return Rational("$inverseNumerator/$denominator")
    }

    operator fun unaryPlus(): Rational {
        return Rational("$numerator/$denominator")
    }

    operator fun rangeTo(end: Rational): Any {
        var range: MutableList<Rational> = arrayListOf()
        val startNumerator = this.numerator.toInt()
        val endNumerator = end.numerator.toInt()
        var index = 0
        if (this.denominator == end.denominator) {
            for (i in startNumerator..endNumerator) {
                range.add(index, Rational("$i/$denominator"))
            }
        }
        return range
    }

    operator fun contains(number: Rational): Boolean {
        if (this.denominator % number.denominator == 0.toBigInteger()
                && this.numerator <= number.numerator) {
            return true
        }
        return false
    }

    override fun toString(): String {
        val gcd = numerator.gcd(denominator)
        return if (gcd != null) {
            val newNumerator = numerator / gcd
            val newDenominator = denominator / gcd
            "$newNumerator/$newDenominator"
        } else {
            "$numerator/$denominator"
        }
    }
}

infix fun Int.divBy(denominator: Int): Rational {
    if (denominator == 0) {
        throw Exception("denominator 0 not allowed")
    }

    return Rational("$this/$denominator")
}

infix fun Long.divBy(denominator: Long): Rational {
    if (denominator == 0L) {
        throw Exception("denominator 0 not allowed")
    }
    return Rational("$this/$denominator")
}

infix fun BigInteger.divBy(denominator: BigInteger): Rational {
    if (denominator == 0.toBigInteger()) {
        throw Exception("denominator 0 not allowed")
    }
    return Rational("$this/$denominator")
}

fun String.toRational(): Rational {
    return Rational(this)
}

And here is my main body that obviously still doesn't compile:

fun main() {
    val half = 1 divBy 2
    val third = 1 divBy 3
    val twoThirds = 2 divBy 3

    println(half in third..twoThirds) // this line does not compile beacause in operator is not defined for the class
}

I guess I have to override "rangeTo" operator but I'm uncertain about the operator prototype. I there somebody that can please help me to get to the right track?

Body:
A straightforward solution is to implement the Comparable Interface in your class.

data class Rational(val rational: String) : Comparable<Rational>

Then implement the compareTo() function, with your comparison logic.

override fun compareTo(other: Rational): Int {
    //Normalize the numerators of each rational
    val thisNumerator = this.numerator * other.denominator
    val otherNumerator = other.numerator * this.denominator
    //Then compare them
    return when{
        thisNumerator > otherNumerator -> 1
        thisNumerator < otherNumerator -> -1
        else -> 0
    }
}

This will resolve the compile error without you needing to override the rangeTo() function with custom logic.


问:
Angular 8 Typescript How to set value of export const from another component?
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

```<code>var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];
</code>```

答:
You just need to export it, then import it in the component that you want to change it.

Declaration:

```<code>export let bdg_m_1:string = "10" ;
</code>```

Other component:

```<code>import bdg_m_1 from 'nav.ts';

bdg_m_1 = '11';
</code>```

EDIT:   The above "solution" is actually wrong.  However I am leaving it in place because it is instructive about something that is counter-intuitive on how Typescript import/export works.

See this explanation for a good explanation of what is going on.

The upshot is that in the importing module, the big_m_1 actually is a binding, not a variable.  So in effect it is read-only.

What you apparently can do is this:

```<code>import thing = require('./nav.ts');
thing.bdg_m_1 = '11';
</code>```

Good luck.

Body:
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];

Body:
You just need to export it, then import it in the component that you want to change it.

Declaration:

export let bdg_m_1:string = "10" ;

Other component:

import bdg_m_1 from 'nav.ts';

bdg_m_1 = '11';

EDIT:   The above "solution" is actually wrong.  However I am leaving it in place because it is instructive about something that is counter-intuitive on how Typescript import/export works.

See this explanation for a good explanation of what is going on.

The upshot is that in the importing module, the big_m_1 actually is a binding, not a variable.  So in effect it is read-only.

What you apparently can do is this:

import thing = require('./nav.ts');
thing.bdg_m_1 = '11';

Good luck.


问:
How to show the data of prev observable till the time new observable emit the value
In my html i am using async pipe to subscribe the observable like shown below.

```<code><button  (click)="getData(1)" >getUser1</button>
<button style="margin:50px;" (click)="getData(2)" >getUser2</button>
<div>------------------------------------------</div>
<div *ngIf="userData$ |async as user">
data is{{  user | json}}</div>
</code>```

and this userData$ observable become new each time user click on button1 or 2.

```<code>  getData(id) {

   this.userData$ = this.getDataFromBackend(id);
  }

 getDataFromBackend(id) {
    //delay added to simulate network delay
    // fake backend call but i have to use real one in actual project
  return of(this.dataSource[id]).pipe(delay(1000));
  }
</code>```

now whenever user change from user1 to user2 the new observable is assigned. and since this new observable takes some time to get data for that time being it shows empty.

can we do something so that till the time the new observable data is not return we can show the previous data.

```<code>  I can not user loader here meanwhile.
  I know i can do something like
  let subject = new Subject();
  let userObservable$ = subject.asObservable()
  and use this observable in the html
  and the subscribe to these observable form getDataFromBackend() here in the class and from
  subscription do the subject.next() and it will send the updated value
  but this does not seem the best way as it do the manual subscription in the component
</code>```

below is the linke for stackblitz showing the problem.

https://stackblitz.com/edit/angular-ivy-d9nsxu?file=src%2Fapp%2Fapp.component.ts

答:
I would use one of two options:

Option 1

You create an another Observable (loading$ or state$) on your DataSource (Service, I presume?) that provides either a boolean indication if it's loading or not, or (even better) a "state" (enum) able to indicate if it's "in initial state", "loaded", "loading" etc.

Option 2

You can change the content that's flowing through your userData$ Observable. I would suggest that the Observable would that mediate a following data structure:

```<code>{
  user: { ... }, // Containing the user data that has been loaded
  state: "Loaded",
}
</code>```

(when user data is loaded), and:

```<code>{
  user: { ... }, // Containing the previously loaded user's data
  state: "Loading",
}
</code>```

(when user data is loading)

Well, to honest - I'd most likely be using a redux-like state management system such as:

NgRx: https://ngrx.io/

NgXs: https://www.ngxs.io/

Akita: https://github.com/datorama/akita

But that's another story

Body:
In my html i am using async pipe to subscribe the observable like shown below.

<button  (click)="getData(1)" >getUser1</button>
<button style="margin:50px;" (click)="getData(2)" >getUser2</button>

------------------------------------------

data is{{  user | json}}

and this userData$ observable become new each time user click on button1 or 2.

  getData(id) {

   this.userData$ = this.getDataFromBackend(id);
  }

 getDataFromBackend(id) {
    //delay added to simulate network delay
    // fake backend call but i have to use real one in actual project
  return of(this.dataSource[id]).pipe(delay(1000));
  }

now whenever user change from user1 to user2 the new observable is assigned. and since this new observable takes some time to get data for that time being it shows empty.

can we do something so that till the time the new observable data is not return we can show the previous data.

  I can not user loader here meanwhile.
  I know i can do something like
  let subject = new Subject();
  let userObservable$ = subject.asObservable()
  and use this observable in the html
  and the subscribe to these observable form getDataFromBackend() here in the class and from
  subscription do the subject.next() and it will send the updated value
  but this does not seem the best way as it do the manual subscription in the component

below is the linke for stackblitz showing the problem.

https://stackblitz.com/edit/angular-ivy-d9nsxu?file=src%2Fapp%2Fapp.component.ts

Body:
I would use one of two options:

Option 1

You create an another Observable (loading$ or state$) on your DataSource (Service, I presume?) that provides either a boolean indication if it's loading or not, or (even better) a "state" (enum) able to indicate if it's "in initial state", "loaded", "loading" etc.

Option 2

You can change the content that's flowing through your userData$ Observable. I would suggest that the Observable would that mediate a following data structure:

{
  user: { ... }, // Containing the user data that has been loaded
  state: "Loaded",
}

(when user data is loaded), and:

{
  user: { ... }, // Containing the previously loaded user's data
  state: "Loading",
}

(when user data is loading)

Well, to honest - I'd most likely be using a redux-like state management system such as:

NgRx: https://ngrx.io/

NgXs: https://www.ngxs.io/

Akita: https://github.com/datorama/akita

But that's another story


问:
AWS -SES: Adding link in my email template
I have to send an email using template through AWS SES.

```<code>{
"Template": {
"TemplateName": "resetPasswordEmailTemplate",
"SubjectPart": "FBO Hangars- Recover Password",
"HtmlPart": "Hi {{name}},\r\n Please click on the below link to recover your password.<b> <a href="">{{link}}</a> <b> The link will be valid for 24 hours. <b> Thank you for using ,Team",
}
}
</code>```

This is my template. issue is the link is not clickable. Also when i inspect the DOM, href attribute is not there in the  tag. Is this something related to configurations? Or the issue with my template

答:
I think your link should have the following form:</p>

```<code><a href="{{link}}">{{link}}</a>
</code>```

Body:
I have to send an email using template through AWS SES.

{
"Template": {
"TemplateName": "resetPasswordEmailTemplate",
"SubjectPart": "FBO Hangars- Recover Password",
"HtmlPart": "Hi {{name}},\r\n Please click on the below link to recover your password. {{link}}  The link will be valid for 24 hours.  Thank you for using ,Team",
}
}

This is my template. issue is the link is not clickable. Also when i inspect the DOM, href attribute is not there in the  tag. Is this something related to configurations? Or the issue with my template

Body:
I think your link should have the following form:

<a href="{{link}}">{{link}}</a>