问:
fade in/out highlight to zebra striped table
I have a table with a number of data rows, which is zebra striped using the following CSS:

```<code>#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}
</code>```

The data in the table is continually updated via ajax calls, and I want to add a temporary highlight to particular rows where data has changed.

I want this new colour (red if the data value has decreased, green if the data value has increased), to nicely fade in, stay for a second or two, then fade back out to the original row colour again.

I have this working just now using jQuery and CSS;

```<code>$('#row_id').addClass("temphighlight");
setTimeout(clearHighlighting, 3000);

function clearHighlighting(){
$("#row_id").removeClass("temphighlight");
}

#datatable tr.temphighlight {
background-color: #c6efce;
transition: background 1.0s ease;
}
</code>```

This works for the fade in, but after the delay, the CSS class is removed immediately and there is no fade out.

How can I get this highlighting to have a better effect, where it fades in and also fades out?

I have checked several similar SO questions, but the answers either don't work or don't apply - such as suggestions that you animate a fade to white, which doesn't work for me because my rows are alternatively coloured differently due to the row striping.

答:
How's this? You can change the class to be added to either pulseUp or pulseDown dependent on if the value is going up or down.

Try clicking an element in the example provided.

$("td").click(function() {
 var element = this;
  $(element).addClass("pulseUp");
  setTimeout(function () {
       $(element).removeClass("pulseUp");
  },500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}

.pulseUp{
  animation-name: pulseUp;
  animation-duration: 0.5s;
  animation-timing-function: ease;
}

.pulseDown {
  animation-name: pulseDown;
  animation-duration: 0.5s;
  animation-timing-function: ease;
}

@keyframes pulseUp {
  50% {
    background-color: green;
  }
}

@keyframes pulseDown {
  50% {
    background-color: red;
  }
}</code>```

    1
    2
    3

    hello
    mr
    Smith

    Goodbye
    Sir
    Smith

```

Body:
I have a table with a number of data rows, which is zebra striped using the following CSS:

#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}

The data in the table is continually updated via ajax calls, and I want to add a temporary highlight to particular rows where data has changed.

I want this new colour (red if the data value has decreased, green if the data value has increased), to nicely fade in, stay for a second or two, then fade back out to the original row colour again.

I have this working just now using jQuery and CSS;

$('#row_id').addClass("temphighlight");
setTimeout(clearHighlighting, 3000);

function clearHighlighting(){
$("#row_id").removeClass("temphighlight");
}

#datatable tr.temphighlight {
background-color: #c6efce;
transition: background 1.0s ease;
}

This works for the fade in, but after the delay, the CSS class is removed immediately and there is no fade out.

How can I get this highlighting to have a better effect, where it fades in and also fades out?

I have checked several similar SO questions, but the answers either don't work or don't apply - such as suggestions that you animate a fade to white, which doesn't work for me because my rows are alternatively coloured differently due to the row striping.

Body:
How's this? You can change the class to be added to either pulseUp or pulseDown dependent on if the value is going up or down.

Try clicking an element in the example provided.

$("td").click(function() {
 var element = this;
  $(element).addClass("pulseUp");
  setTimeout(function () {
       $(element).removeClass("pulseUp");
  },500);
});

#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}

.pulseUp{
  animation-name: pulseUp;
  animation-duration: 0.5s;
  animation-timing-function: ease;
}

.pulseDown {
  animation-name: pulseDown;
  animation-duration: 0.5s;
  animation-timing-function: ease;
}

@keyframes pulseUp {
  50% {
    background-color: green;
  }
}

@keyframes pulseDown {
  50% {
    background-color: red;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="datatable">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
    <tr>
    <td>hello</td>
    <td>mr</td>
    <td>Smith</td>
  </tr>
    <tr>
    <td>Goodbye</td>
    <td>Sir</td>
    <td>Smith</td>
  </tr>
</table>


来源: stackexchange

问:
MSSQL select customers with same products
Hello I would like to SELECT the name of the customer who ordered this set of products like the Brazilian customers from Northwind database. I did brazilian products here:

```<code>select [ProductName]
from [dbo].[Products] join [dbo].[Order Details] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
join [dbo].[Orders] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Customers] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
where [Country] = 'Brazil'
</code>```

but what now? How I can find them? I tried to do:

```<code>select [CompanyName], [ProductName]
from [dbo].[Customers] join [dbo].[Orders] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
join [dbo].[Order Details] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Products] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
where  [ProductName] in  (
select [ProductName]
from [dbo].[Products] join [dbo].[Order Details] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
join [dbo].[Orders] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Customers] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
where [Country] = 'Brazil')
</code>```

but this also doesn't work :/

答:
if I understand your question (which is phrased not clearly), all you need to do is to add [Customer] to your select statement, instead of running nested queries. Your question asks to select the name of the customer, so it is select [Customer], not [Company], [Product].

Hope that helps.

ContentLicense: CC BY-SA 3.0

Body:
Hello I would like to SELECT the name of the customer who ordered this set of products like the Brazilian customers from Northwind database. I did brazilian products here:

select [ProductName]
from [dbo].[Products] join [dbo].[Order Details] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
join [dbo].[Orders] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Customers] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
where [Country] = 'Brazil'

but what now? How I can find them? I tried to do:

select [CompanyName], [ProductName]
from [dbo].[Customers] join [dbo].[Orders] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
join [dbo].[Order Details] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Products] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
where  [ProductName] in  (
select [ProductName]
from [dbo].[Products] join [dbo].[Order Details] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
join [dbo].[Orders] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Customers] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
where [Country] = 'Brazil')

but this also doesn't work :/


问:
python async that doesn't always await
I have a python async function:

```<code>async def exampleAsync(self,check):
   # normal blocking code

   if check:
      x = await asynch_func()
      # some other code
</code>```

If i run obj.exampleAsync(False) and I know this function isn't going to ever call await. Is it wrong to still call this function like:

```<code>   await obj.exampleAsync(False)
</code>```

I guess it's the right thing to do since I don't know in the code if this function will await or not.

I guess my question is do async function always have to await()?

答:
Here is await for new programmers: "await pause the code running here until this call is finished, and while you pause here you can run async code elsewhere" So yes.

I think you have misunderstood await. Await is not a call. And yes, passing false will make this just like a non asynchronous program. You never give the eventloop a change to do something else.

Title: python async that doesn't always await

Body:
I have a python async function:

async def exampleAsync(self,check):
   # normal blocking code

   if check:
      x = await asynch_func()
      # some other code

If i run obj.exampleAsync(False) and I know this function isn't going to ever call await. Is it wrong to still call this function like:

   await obj.exampleAsync(False)

I guess it's the right thing to do since I don't know in the code if this function will await or not.

I guess my question is do async function always have to await()?


问:
Unresolved reference: SpringExtension using @ExtendWith annotation
I'm using trying to use Junit 5 within SpringBoot in order to take advantage of a number of new features that it provides. The basic setup works and I can use the new annotations such as @BeforeAll and @AfterAll however, I believe that because I cannot resolve the @ExtendWith(SpringExtension::class) I am not able to initialise my Test class to make use of injected resources. I have tried adding required dependencies to my build.gradle file but I assume I'm missing a key dependency:

```<code>buildscript {

ext.dokka_version = '0.9.15'
ext.dockerVersion = '1.2'
ext.junit4Version = '4.12'
ext.junitVintageVersion = '4.12.2'
ext.junitPlatformVersion = '1.0.2'
ext.junitJupiterVersion = '5.0.2'
ext.kotlin_version = '1.1.60'
ext.log4jVersion = '2.9.0'
ext.springVersion = '1.5.8.RELEASE'

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    // Needed for the 'kotlin' plugin
    classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}")
    // Needed for the 'org.springframework.boot' plugin
    classpath("org.springframework.boot:spring-boot-gradle-plugin:${springVersion}")
    // Needed for the 'kotlin-spring' plugin
    classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlin_version}")
    //Needed for 'docker' plugin
    classpath("se.transmode.gradle:gradle-docker:${dockerVersion}")
    //Needed for 'dokka' plugin
    classpath("org.jetbrains.dokka:dokka-gradle-plugin:${dokka_version}")
    // Needed for Junit 5
    classpath("org.junit.platform:junit-platform-gradle-plugin:${junitPlatformVersion}")
}

}

// Allows us to compile Kotlin files
apply plugin: 'kotlin'
// Does some extra work to set up Spring Boot.
// Specifically this gives us the "bootRun" task we will be using
apply plugin: 'org.springframework.boot'
// Allows for improved interoperability between Kotlin and Spring
apply plugin: 'kotlin-spring'
// Allows us to create docker image
apply plugin: 'docker'
//Allows us to create API documentation
apply plugin: 'org.jetbrains.dokka'

apply plugin: 'idea'

apply plugin: 'java'

apply plugin: 'org.junit.platform.gradle.plugin'

junitPlatform {
    // platformVersion '1.0.2'
    filters {
        engines {
            // include 'junit-jupiter', 'junit-vintage'
            // exclude 'custom-engine'
        }
        tags {
            // include 'fast'
            exclude 'slow'
        }
        // includeClassNamePattern '.*Test'
    }
    // enableStandardTestTask true
    // reportsDir file('build/test-results/junit-platform') // this is the default
    //logManager 'org.apache.logging.log4j.jul.LogManager'
}

task buildDocker(type: Docker, dependsOn: [build, dokka]) {
    applicationName = jar.baseName
    dockerfile = file('Dockerfile')
    doFirst {
        copy {
            from jar
            into stageDir
        }
    }
}

dokka {
    outputFormat = 'html'
    outputDirectory = $buildDir / doc
}

repositories {
    mavenCentral()
}

compileJava {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}

compileTestJava {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    options.compilerArgs += '-parameters'
}

dependencies {
// JPA and H2
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2")

compile "org.hibernate:hibernate-entitymanager:5.2.10.Final"
compile "org.hibernate:hibernate-core:5.2.10.Final"

compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"

compile "org.slf4j:slf4j-api:1.7.25"

// Kotlin Dependencies
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"

testCompile "org.springframework.boot:spring-boot-starter-test"
//testCompile "org.springframework.boot:spring-boot-starter-test" {
//    exclude(module = "junit")
//}
// Mockito
//testCompile "org.mockito:mockito-core:2.11.0"
//testCompile "com.nhaarman:mockito-kotlin-kt1.1:1.5.0"

//AssertJ
testCompile 'org.assertj:assertj-core:3.8.0'

// JUnit Jupiter API and TestEngine implementation
testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
testCompile("org.junit.platform:juint-platform-runner:${junitPlatformVersion}")
testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")

// Only needed to run tests in an (IntelliJ) IDE(A) that bundles an older version
testRuntime("org.junit.platform:junit-platform-launcher:${junitPlatformVersion}")

// If you also want to support JUnit 3 and JUnit 4 tests
//testCompile ("junit:junit:${junit4Version}")
//testRuntime ("org.junit.vintage:junit-vintage-engine:${junitVintageVersion}")

// To avoid compiler warnings about @API annotations in JUnit code
testCompileOnly("org.apiguardian:apiguardian-api:1.0.0")

// Spring Dependencies
compile("org.springframework.boot:spring-boot-starter-web") {
    exclude module: "spring-boot-starter-tomcat"
}
compile "org.springframework.boot:spring-boot-starter-jetty"
compile "org.springframework.boot:spring-boot-starter-actuator"

// Jackson Dependencies
compile "com.fasterxml.jackson.core:jackson-annotations"
compile "com.fasterxml.jackson.core:jackson-core"
compile "com.fasterxml.jackson.core:jackson-databind"
runtime "com.fasterxml.jackson.datatype:jackson-datatype-jdk8"
runtime "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
runtime "com.fasterxml.jackson.module:jackson-module-kotlin"
}

configurations.all {
    exclude group: "org.slf4j", module: "slf4j-log4j12"
    exclude group: "log4j", module: "log4j"
}

task wrapper(type: Wrapper) {
    gradleVersion = "4.3"
}
</code>```

答:
I don't see the spring-test-junit5 dependency declared anywhere in your build.gradle. According to the docs for the JUnit 5 Spring extension:

If you'd like to build against a release tag for spring-test-junit5, you may be interested in using JitPack. For example, to build against the 1.0.2 tag, the following Maven coordinates will work.

```<code>Group ID: com.github.sbrannen
Artifact ID: spring-test-junit5
Version: 1.0.2
</code>```

JitPack with Gradle

```<code>repositories {
    mavenCentral()
    maven { url 'https://jitpack.io' }
}

// ...

dependencies {
    // ...
    testCompile('com.github.sbrannen:spring-test-junit5:1.0.2')
    // ...
}
</code>```

Update:

Extracted from the comments below (provided by the author of the JUnit5 Spring Extension):

If you are using spring-test from Spring Framework 5.x, you do not need the spring-test-junit5 artifact (which is only for Spring Framework 4.3.x)

Body:
I'm using trying to use Junit 5 within SpringBoot in order to take advantage of a number of new features that it provides. The basic setup works and I can use the new annotations such as @BeforeAll and @AfterAll however, I believe that because I cannot resolve the @ExtendWith(SpringExtension::class) I am not able to initialise my Test class to make use of injected resources. I have tried adding required dependencies to my build.gradle file but I assume I'm missing a key dependency:

buildscript {

ext.dokka_version = '0.9.15'
ext.dockerVersion = '1.2'
ext.junit4Version = '4.12'
ext.junitVintageVersion = '4.12.2'
ext.junitPlatformVersion = '1.0.2'
ext.junitJupiterVersion = '5.0.2'
ext.kotlin_version = '1.1.60'
ext.log4jVersion = '2.9.0'
ext.springVersion = '1.5.8.RELEASE'

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    // Needed for the 'kotlin' plugin
    classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}")
    // Needed for the 'org.springframework.boot' plugin
    classpath("org.springframework.boot:spring-boot-gradle-plugin:${springVersion}")
    // Needed for the 'kotlin-spring' plugin
    classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlin_version}")
    //Needed for 'docker' plugin
    classpath("se.transmode.gradle:gradle-docker:${dockerVersion}")
    //Needed for 'dokka' plugin
    classpath("org.jetbrains.dokka:dokka-gradle-plugin:${dokka_version}")
    // Needed for Junit 5
    classpath("org.junit.platform:junit-platform-gradle-plugin:${junitPlatformVersion}")
}

}

// Allows us to compile Kotlin files
apply plugin: 'kotlin'
// Does some extra work to set up Spring Boot.
// Specifically this gives us the "bootRun" task we will be using
apply plugin: 'org.springframework.boot'
// Allows for improved interoperability between Kotlin and Spring
apply plugin: 'kotlin-spring'
// Allows us to create docker image
apply plugin: 'docker'
//Allows us to create API documentation
apply plugin: 'org.jetbrains.dokka'

apply plugin: 'idea'

apply plugin: 'java'

apply plugin: 'org.junit.platform.gradle.plugin'

junitPlatform {
    // platformVersion '1.0.2'
    filters {
        engines {
            // include 'junit-jupiter', 'junit-vintage'
            // exclude 'custom-engine'
        }
        tags {
            // include 'fast'
            exclude 'slow'
        }
        // includeClassNamePattern '.*Test'
    }
    // enableStandardTestTask true
    // reportsDir file('build/test-results/junit-platform') // this is the default
    //logManager 'org.apache.logging.log4j.jul.LogManager'
}

task buildDocker(type: Docker, dependsOn: [build, dokka]) {
    applicationName = jar.baseName
    dockerfile = file('Dockerfile')
    doFirst {
        copy {
            from jar
            into stageDir
        }
    }
}

dokka {
    outputFormat = 'html'
    outputDirectory = $buildDir / doc
}

repositories {
    mavenCentral()
}

compileJava {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}

compileTestJava {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    options.compilerArgs += '-parameters'
}

dependencies {
// JPA and H2
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2")

compile "org.hibernate:hibernate-entitymanager:5.2.10.Final"
compile "org.hibernate:hibernate-core:5.2.10.Final"

compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"

compile "org.slf4j:slf4j-api:1.7.25"

// Kotlin Dependencies
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"

testCompile "org.springframework.boot:spring-boot-starter-test"
//testCompile "org.springframework.boot:spring-boot-starter-test" {
//    exclude(module = "junit")
//}
// Mockito
//testCompile "org.mockito:mockito-core:2.11.0"
//testCompile "com.nhaarman:mockito-kotlin-kt1.1:1.5.0"

//AssertJ
testCompile 'org.assertj:assertj-core:3.8.0'

// JUnit Jupiter API and TestEngine implementation
testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
testCompile("org.junit.platform:juint-platform-runner:${junitPlatformVersion}")
testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")

// Only needed to run tests in an (IntelliJ) IDE(A) that bundles an older version
testRuntime("org.junit.platform:junit-platform-launcher:${junitPlatformVersion}")

// If you also want to support JUnit 3 and JUnit 4 tests
//testCompile ("junit:junit:${junit4Version}")
//testRuntime ("org.junit.vintage:junit-vintage-engine:${junitVintageVersion}")

// To avoid compiler warnings about @API annotations in JUnit code
testCompileOnly("org.apiguardian:apiguardian-api:1.0.0")

// Spring Dependencies
compile("org.springframework.boot:spring-boot-starter-web") {
    exclude module: "spring-boot-starter-tomcat"
}
compile "org.springframework.boot:spring-boot-starter-jetty"
compile "org.springframework.boot:spring-boot-starter-actuator"

// Jackson Dependencies
compile "com.fasterxml.jackson.core:jackson-annotations"
compile "com.fasterxml.jackson.core:jackson-core"
compile "com.fasterxml.jackson.core:jackson-databind"
runtime "com.fasterxml.jackson.datatype:jackson-datatype-jdk8"
runtime "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
runtime "com.fasterxml.jackson.module:jackson-module-kotlin"
}

configurations.all {
    exclude group: "org.slf4j", module: "slf4j-log4j12"
    exclude group: "log4j", module: "log4j"
}

task wrapper(type: Wrapper) {
    gradleVersion = "4.3"
}

Body:
I don't see the spring-test-junit5 dependency declared anywhere in your build.gradle. According to the docs for the JUnit 5 Spring extension:

If you'd like to build against a release tag for spring-test-junit5, you may be interested in using JitPack. For example, to build against the 1.0.2 tag, the following Maven coordinates will work.

Group ID: com.github.sbrannen
Artifact ID: spring-test-junit5
Version: 1.0.2

JitPack with Gradle

repositories {
    mavenCentral()
    maven { url 'https://jitpack.io' }
}

// ...

dependencies {
    // ...
    testCompile('com.github.sbrannen:spring-test-junit5:1.0.2')
    // ...
}

Update:

Extracted from the comments below (provided by the author of the JUnit5 Spring Extension):

If you are using spring-test from Spring Framework 5.x, you do not need the spring-test-junit5 artifact (which is only for Spring Framework 4.3.x)


问:
Replace a text with \n character only at a particular line of the text with escape identifier
I have tried sed and perl commands to replace the text but I didn't get expected results.
For Example :
I want to replace

```<code>ABC"\
}
else {
....
</code>```

with:

```<code>ABC"\
} else {
....
</code>```

How can I do this?
Challenges faced are as follows:

As it contains escape identifier and \n I am unable to search the pattern also.

It is not the beginning or end of the file to truncate the particular line and replace.

Tried to change with respect to a line number in a file but my requirement is to do for multiple files hence, line number is not constant.

Though I can search for else. I'm unable to replace the \n

I have tried the inputs given in Removing new line after a particular text via bash/awk/sed/perl
but they do not serve my purpose.

Please give your inputs and help me if there is any other approach for this.

答:
Tcl solution:

```<code>set text [string map [list "\\\n}\nelse {" "\\\n} else {"] $text]
</code>```

Replaces all occurrences. Does not write back to variable: you need to assign back as in the example above.

Documentation:
string

Body:
I have tried sed and perl commands to replace the text but I didn't get expected results.
For Example :
I want to replace

ABC"\
}
else {
....

with:

ABC"\
} else {
....

How can I do this?
Challenges faced are as follows:

As it contains escape identifier and \n I am unable to search the pattern also.

It is not the beginning or end of the file to truncate the particular line and replace.

Tried to change with respect to a line number in a file but my requirement is to do for multiple files hence, line number is not constant.

Though I can search for else. I'm unable to replace the \n

I have tried the inputs given in Removing new line after a particular text via bash/awk/sed/perl
but they do not serve my purpose.

Please give your inputs and help me if there is any other approach for this.

Body:
Tcl solution:

set text [string map [list "\\\n}\nelse {" "\\\n} else {"] $text]

Replaces all occurrences. Does not write back to variable: you need to assign back as in the example above.

Documentation:
string


问:
Why shortcuts don't work in rubymine IDE
No quick button does not work. The reason? Already search the entire Internet and found nothing. I was told that perhaps the problem in Ubuntu. We all know it works, but I have not. Who knows what?</p>

答:
This code helped me:</p>

```<code>sudo add-apt-repository ppa:attente/java-non-latin-shortcuts
sudo apt-get update
sudo apt-get dist-upgrade
restart unity-settings-daemon
</code>```

Body:
This code helped me:

sudo add-apt-repository ppa:attente/java-non-latin-shortcuts
sudo apt-get update
sudo apt-get dist-upgrade
restart unity-settings-daemon


问:
Continuous listening to TCP port
I've made a code which is able to receive data from the port over TCP protocol. I receive data from ESP8266 every 15 minutes, and then ESP goes to a deepSleep mode. How to change it to make it work continuosly? I wanted to create a new connection in while loop, but it doesn't work.

My code

```<code>import sys
import socket

TCP_IP = '192.168.42.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []
i=0

#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind((TCP_IP,TCP_PORT))
#s.listen(1)

#print 'Listening for client...'

#conn, addr = s.accept()
#print 'Connection address:', addr
while 1:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP,TCP_PORT))
    s.listen(1)

    print 'Listening for client...'
    conn, addr = s.accept()
    print 'Connection address:', addr
    data = conn.recv(BUFFER_SIZE)
    if data == ";" :
            conn.close()
            print "Received all the data"
            i=0
            for x in param:
                    print x
            #break
    elif data:
            print "received data: ", data
            param.insert(i,data)
            i+=1
            #print "End of transmission"
</code>```

EDIT:

My code after modification.

```<code>import sys
import socket

TCP_IP = '192.168.42.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []
i=0

#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind((TCP_IP,TCP_PORT))
#s.listen(1)

#print 'Listening for client...'

#conn, addr = s.accept()
#print 'Connection address:', addr
while 1:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP,TCP_PORT))
    s.listen(1)
    while 1:
            print 'Listening for client...'
            conn, addr = s.accept()
            print 'Connection address:', addr
            data = conn.recv(BUFFER_SIZE)
            if data == ";" :
                    conn.close()
                    print "Received all the data"
                    i=0
                    for x in param:
                            print x
                    #break
            elif data:
                    print "received data: ", data
                    param.insert(i,data)
                    i+=1
                    #print "End of transmission"
    s.close()
</code>```

I created second while loop. I can listen continuously now, but I receive only one packet from the ESP (ESP send 9 packets). How to solve that issue?

答:
If you want to continuously listen for connections and data from your remote end, you can achieve this using select()

A modified version of your code that uses select() is shown below. This will also handle the remote end closing the connection:

```<code>import sys
import socket
import select

TCP_IP = '127.0.0.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []

print 'Listening for client...'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((TCP_IP,TCP_PORT))
server.listen(1)
rxset = [server]
txset = []

while 1:
    rxfds, txfds, exfds = select.select(rxset, txset, rxset)
    for sock in rxfds:
        if sock is server:
            conn, addr = server.accept()
            conn.setblocking(0)
            rxset.append(conn)
            print 'Connection from address:', addr
        else:
            try:
                data = sock.recv(BUFFER_SIZE)
                if data == ";" :
                    print "Received all the data"
                    for x in param:
                        print x
                    param = []
                    rxset.remove(sock)
                    sock.close()
                else:
                    print "received data: ", data
                    param.append(data)
            except:
                print "Connection closed by remote end"
                param = []
                rxset.remove(sock)
                sock.close()
</code>```

NB I've replaced your IP address with the loopback but you get the idea.

Hope this may be helpful.

Title: Continuous listening to TCP port

Body:
I've made a code which is able to receive data from the port over TCP protocol. I receive data from ESP8266 every 15 minutes, and then ESP goes to a deepSleep mode. How to change it to make it work continuosly? I wanted to create a new connection in while loop, but it doesn't work.

My code

import sys
import socket

TCP_IP = '192.168.42.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []
i=0

#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind((TCP_IP,TCP_PORT))
#s.listen(1)

#print 'Listening for client...'

#conn, addr = s.accept()
#print 'Connection address:', addr
while 1:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP,TCP_PORT))
    s.listen(1)

    print 'Listening for client...'
    conn, addr = s.accept()
    print 'Connection address:', addr
    data = conn.recv(BUFFER_SIZE)
    if data == ";" :
            conn.close()
            print "Received all the data"
            i=0
            for x in param:
                    print x
            #break
    elif data:
            print "received data: ", data
            param.insert(i,data)
            i+=1
            #print "End of transmission"

EDIT:

My code after modification.

import sys
import socket

TCP_IP = '192.168.42.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []
i=0

#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind((TCP_IP,TCP_PORT))
#s.listen(1)

#print 'Listening for client...'

#conn, addr = s.accept()
#print 'Connection address:', addr
while 1:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP,TCP_PORT))
    s.listen(1)
    while 1:
            print 'Listening for client...'
            conn, addr = s.accept()
            print 'Connection address:', addr
            data = conn.recv(BUFFER_SIZE)
            if data == ";" :
                    conn.close()
                    print "Received all the data"
                    i=0
                    for x in param:
                            print x
                    #break
            elif data:
                    print "received data: ", data
                    param.insert(i,data)
                    i+=1
                    #print "End of transmission"
    s.close()

I created second while loop. I can listen continuously now, but I receive only one packet from the ESP (ESP send 9 packets). How to solve that issue?

Body:
If you want to continuously listen for connections and data from your remote end, you can achieve this using select()

A modified version of your code that uses select() is shown below. This will also handle the remote end closing the connection:

import sys
import socket
import select

TCP_IP = '127.0.0.1'
TCP_PORT = 8888
BUFFER_SIZE = 1024
param = []

print 'Listening for client...'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((TCP_IP,TCP_PORT))
server.listen(1)
rxset = [server]
txset = []

while 1:
    rxfds, txfds, exfds = select.select(rxset, txset, rxset)
    for sock in rxfds:
        if sock is server:
            conn, addr = server.accept()
            conn.setblocking(0)
            rxset.append(conn)
            print 'Connection from address:', addr
        else:
            try:
                data = sock.recv(BUFFER_SIZE)
                if data == ";" :
                    print "Received all the data"
                    for x in param:
                        print x
                    param = []
                    rxset.remove(sock)
                    sock.close()
                else:
                    print "received data: ", data
                    param.append(data)
            except:
                print "Connection closed by remote end"
                param = []
                rxset.remove(sock)
                sock.close()

NB I've replaced your IP address with the loopback but you get the idea.

Hope this may be helpful.


问:
Why does it keep freezing
I have tried switching the defines to consts but it doesn't seem to work either</p>

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

#define TIMES 5/9
#define MINUS 32
int main()
{
    int temp_fahr = 0;
    printf("Enter the temperature in fahrenheit\n");
    scanf("%d\n",temp_fahr);
    printf("The temperature in celcious is: %.3f\n",(temp_fahr-MINUS)*TIMES);
    return 0;
}
</code>```

答:
Your problem is the line

```<code>scanf("%d\n",temp_fahr);
</code>```

As the compiler warnings will tell you, it expects an input of type int * but receives an integer instead. So, it tries to write into the address temp_fahr points to which causes a segmentation fault.

Second, if you fix it by supplying a pointer to temp_fahr, scanf keeps waiting for the newline which gets trimmed from standard input, so it gets stuck there. So, the correct line is

```<code>scanf("%d",&temp_fahr);
</code>```

You'll also notice that the %fformat expects an argument of type double and receives an integer instead, so you'll want to cast the result to double at some point before passing it to printf.

Title: Why does it keep freezing

Body:
I have tried switching the defines to consts but it doesn't seem to work either

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

#define TIMES 5/9
#define MINUS 32
int main()
{
    int temp_fahr = 0;
    printf("Enter the temperature in fahrenheit\n");
    scanf("%d\n",temp_fahr);
    printf("The temperature in celcious is: %.3f\n",(temp_fahr-MINUS)*TIMES);
    return 0;
}

Body:
Your problem is the line

scanf("%d\n",temp_fahr);

As the compiler warnings will tell you, it expects an input of type int * but receives an integer instead. So, it tries to write into the address temp_fahr points to which causes a segmentation fault.

Second, if you fix it by supplying a pointer to temp_fahr, scanf keeps waiting for the newline which gets trimmed from standard input, so it gets stuck there. So, the correct line is

scanf("%d",&temp_fahr);

You'll also notice that the %fformat expects an argument of type double and receives an integer instead, so you'll want to cast the result to double at some point before passing it to printf.


问:
Procedure for debugging glReadPixels
So my glReadPixel call:

```<code>  glPixelStorei(GL_PACK_ALIGNMENT, 1);
  GLfloat lebuf[128 * 128 * 4];
  glReadPixels(0, 0, 128, 128, GL_RGBA, GL_FLOAT, lebuf);
</code>```

just puts 1.0 values in the lebuf array. This is just after finishing drawing the page, and the resultant result is a "white" image.

checking the GL errors indicate that there's nothing wrong.

what could have possibly gone wrong?

答:
Make sure glReadBuffer(GL_FRONT) is set before glReadPixels. If it is not, you could be reading from a different buffer, such as the back buffer when double buffering.

And of course, ensure that your capture area - 128x128 - is not all white.

ContentLicense: CC BY-SA 2.5

Title: Procedure for debugging glReadPixels

Body:
So my glReadPixel call:

  glPixelStorei(GL_PACK_ALIGNMENT, 1);
  GLfloat lebuf[128 * 128 * 4];
  glReadPixels(0, 0, 128, 128, GL_RGBA, GL_FLOAT, lebuf);

just puts 1.0 values in the lebuf array. This is just after finishing drawing the page, and the resultant result is a "white" image.

checking the GL errors indicate that there's nothing wrong.

what could have possibly gone wrong?


问:
Powerquery- 2 tables, all rows, choose columns to append to and new columns to add
i have two tables. Some fields match, some do not. I want to combine them such that the result has the number of rows equal to the sum of rows in table 1 and table 2.

Is there a way to specify which columns to combine from the two tables and which columns to create a new column for? For Access users, it's kind of like the query editor Append Query where the user can select which columns to append a table to.

I guess I can change the headers to match manually (it just occurred to me), is there a more expedient way?

答:
Two tables:

Say I want to append the columns Column1 and Column3 from Table1 and Column2 from Table2, to get this:

Here's one way to do it.

First, connect both tables Table1 and Table2 to Power Query as sources. Once connected as sources, you'll see them listed on the left of your Power Query screen, under Queries.

Then, start a new blank query: Home -> New Source -> Other Sources -> Blank Query, and type = Table.Combine({Table.FromColumns({Table1[Column1], Table1[Column3]},{"Table1 Column1","Table1 Column3"}), Table.FromColumns({Table2[Column2]}, {"Table2 Column2"})})into the formula bar. Then enter.

To learn about the functions I used, see Microsoft's info on Table.FromColumns and Table.Combine. Basically, this code creates two tables...one from Table1 Column1 and Table1 Column3, and one from Table2 Column2...then it combines (appends) those two freshly created tables together.


问:
Entity Framework is being restored via .NetFramework and not Core V2.0 which is my projects framework
When downloading Entity Framework I am getting the error

Package 'EntityFramework 6.2.0' was restored using '.NetFramework,
  version=v4.6.1' instead of the project target framework ".NETCoreApp,
  Version=v2.0' This package may not be fully compatible with your
  project

The reason this is an issue is because when I try to enable migration it gives the following error which I think is linked back to this.

Exception calling "SetData" with "2" argument(s)

答:
I ran into this today too. The solution is here: https://blogs.msdn.microsoft.com/dotnet/2017/08/14/announcing-entity-framework-core-2-0/

Specifically:

You can start using EF Core 2.0 today by installing an EF Core
  2.0-compatible database provider NuGet package in your applications.

The key is "EF Core 2.0-compatible", which means you have to install one of the Microsoft.EntityFrameworkCore packages from NuGet.

So if you're using SQL Server, you'll install Microsoft.EntityFrameworkCore.SqlServer.


问:
Firebase database cannot getValue
Data trying to access:

If I select values for "Bloating" and "Diarrhea" in my app, then it should show me the "Cramps" and "Uncontrollable Bowel Syndrome" as an output in a textView. Function that is getting the values for such case is readDataListenerForTwo(). How can I correct the code?

SymptomActivity.java

```<code>package com.example.nishantsikri.microdoctor;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.security.SecurityPermission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SymptomActivity extends AppCompatActivity {

static boolean calledAlready = false;
Integer i = 2;
private DatabaseReference mFirebaseDatabase, spinnerDatabase;
private FirebaseDatabase mFirebaseInstance;
Button button,add_button,sub_button;
TextView textView,symptom1,symptom2,symptom3;
Spinner spinner,spinner2,spinner3;
String textSymptom1,textSymptom2,textSymptom3;

@Override
public void onBackPressed() {
    startActivity(new Intent(getApplicationContext(),NavigationActivity.class));
    finish();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_symptom);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    button = (Button) findViewById(R.id.button8);
    add_button = (Button) findViewById(R.id.add_button);
    sub_button = (Button) findViewById(R.id.sub_button);
    textView = (TextView) findViewById(R.id.textView2);

    symptom1 = (TextView) findViewById(R.id.symptom1);
    symptom2 = (TextView) findViewById(R.id.symptom2);
    symptom3 = (TextView) findViewById(R.id.symptom3);
    spinner = (Spinner) findViewById(R.id.spinner1);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    spinner3 = (Spinner) findViewById(R.id.spinner3);

    spinner3.setEnabled(false);
    spinner3.setVisibility(View.GONE);
    symptom3.setVisibility(View.GONE);
    sub_button.setEnabled(false);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    if (!calledAlready)
    {
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        calledAlready = true;
    }

    // Write a message to the database
    mFirebaseInstance = FirebaseDatabase.getInstance();
    // store app title to 'app_title' node
    mFirebaseInstance.getReference("app_title").setValue("microDoctor");
    mFirebaseDatabase = mFirebaseInstance.getReference("symptomList");
    spinnerDatabase = mFirebaseInstance.getReference("symptomView");
    //mFirebaseDatabase.child("Headache").child("Some Value").setValue("Head");
    //mFirebaseDatabase.setValue("Headache");

    spinnerData();
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            textSymptom1 = spinner.getItemAtPosition(i).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
    spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            textSymptom2 = spinner2.getItemAtPosition(i).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
    spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            textSymptom3 = spinner3.getItemAtPosition(i).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(i == 3)
                readDataListener();
            else
                readDataListenerForTwo();
        }
    });
    add_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            spinner3.setEnabled(true);
            spinner3.setVisibility(View.VISIBLE);
            symptom3.setVisibility(View.VISIBLE);
            add_button.setEnabled(false);
            sub_button.setEnabled(true);
            i++;
            Log.e("Value i","Value of i: "+i);
        }
    });
    sub_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            spinner3.setEnabled(false);
            spinner3.setVisibility(View.GONE);
            symptom3.setVisibility(View.GONE);
            add_button.setEnabled(true);
            sub_button.setEnabled(false);
            i--;
            Log.e("Value i","Value of i: "+i);
        }
    });

}

private void readDataListener() {
      mFirebaseDatabase.child(textSymptom1).child(textSymptom2).child(textSymptom3).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String symptom = dataSnapshot.child("disease").getValue(String.class);

            // Check for null
            if (symptom == null) {
                Log.e("Data", "Symptom data is null!");
                return;
            }

            Log.e("Symptom Data", "User data is changed!"+symptom);

            // Display newly updated name and email
            textView.setText(symptom+"\n"+dataSnapshot.getKey());
            Intent intent = new Intent(getApplicationContext(),DiseaseActivity.class);
            intent.putExtra("key", symptom);
            startActivity(intent);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Error", "Failed to read user", error.toException());
        }
    });
}
private void readDataListenerForTwo(){
        mFirebaseDatabase.child(textSymptom1).child(textSymptom2).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String symptom = dataSnapshot.getValue(String.class);

            // Check for null
            if (symptom == null) {
                Log.e("Data", "Symptom data is null!");
                Log.e("Chutiya","Haila! Chutiya run ho ra hai! ._.");
                return;
            }

            Log.e("Symptom Data", "User data is changed!"+symptom);

            // Display newly updated name and email
//                textView.setText(symptom+"\n"+dataSnapshot.getKey());
//                Intent intent = new Intent(getApplicationContext(),DiseaseActivity.class);
//                intent.putExtra("key", symptom);
//                startActivity(intent);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Error", "Failed to read user", error.toException());
        }
    });
}
private void spinnerData() {
    spinnerDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Log.e("Spinner Data", "Spinner data is changed!");

            //DataSnapshot data = dataSnapshot;
            Iterable<DataSnapshot> temp = dataSnapshot.getChildren();
            ArrayList<String> list = new ArrayList<>();
//                list.add(dataSnapshot.getValue().toString());
//                showDataInSpinner(list);
            for (DataSnapshot lists : temp){
                Log.d("ddd","Array List: "+lists.getValue().toString());
                list.add(lists.getValue().toString());
                textView.setText(lists.getValue().toString());
            }
            showDataInSpinner(list);

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Error", "Failed to read user", error.toException());
        }
    });
}
public void showDataInSpinner(ArrayList<String> data) {
    ArrayAdapter<String> adapter = new ArrayAdapter<>(
            this, android.R.layout.simple_spinner_item, data
    ); //Create the Adapter to set the data
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);     //Set the layout resource to create the drop down views.
    spinner.setAdapter(adapter); //Set the data to your spinner
    spinner2.setAdapter(adapter);
    spinner3.setAdapter(adapter);
}
}
</code>```

Gradle Error

```<code>11-16 01:02:13.816 22912-22912/com.example.nishantsikri.microdoctor E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.nishantsikri.microdoctor, PID: 22912
                                                                                com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
                                                                                at com.google.android.gms.internal.zzekp.zzb(Unknown Source)
                                                                                at com.google.android.gms.internal.zzekp.zza(Unknown Source)
                                                                                at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                                                at com.example.nishantsikri.microdoctor.SymptomActivity$9.onDataChange(SymptomActivity.java:204)
                                                                                at com.google.android.gms.internal.zzeex.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzegs.zzbwg(Unknown Source)
                                                                                at com.google.android.gms.internal.zzegy.run(Unknown Source)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6236)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
</code>```

答:
To get those names under Diarrhea, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference diarrheaRef = rootRef.child("symptomList").child("Bloating").child("Diarrhea");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.getKey();
            Log.d("TAG", name);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
diarrheaRef.addListenerForSingleValueEvent(eventListener);
</code>```

Your output will be:

```<code>Cramps
Uncontrollable Bowel Syndrome
</code>```

Title: Firebase database cannot getValue

Body:
Data trying to access:

If I select values for "Bloating" and "Diarrhea" in my app, then it should show me the "Cramps" and "Uncontrollable Bowel Syndrome" as an output in a textView. Function that is getting the values for such case is readDataListenerForTwo(). How can I correct the code?

SymptomActivity.java

package com.example.nishantsikri.microdoctor;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.security.SecurityPermission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SymptomActivity extends AppCompatActivity {

static boolean calledAlready = false;
Integer i = 2;
private DatabaseReference mFirebaseDatabase, spinnerDatabase;
private FirebaseDatabase mFirebaseInstance;
Button button,add_button,sub_button;
TextView textView,symptom1,symptom2,symptom3;
Spinner spinner,spinner2,spinner3;
String textSymptom1,textSymptom2,textSymptom3;

@Override
public void onBackPressed() {
    startActivity(new Intent(getApplicationContext(),NavigationActivity.class));
    finish();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_symptom);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    button = (Button) findViewById(R.id.button8);
    add_button = (Button) findViewById(R.id.add_button);
    sub_button = (Button) findViewById(R.id.sub_button);
    textView = (TextView) findViewById(R.id.textView2);

    symptom1 = (TextView) findViewById(R.id.symptom1);
    symptom2 = (TextView) findViewById(R.id.symptom2);
    symptom3 = (TextView) findViewById(R.id.symptom3);
    spinner = (Spinner) findViewById(R.id.spinner1);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    spinner3 = (Spinner) findViewById(R.id.spinner3);

    spinner3.setEnabled(false);
    spinner3.setVisibility(View.GONE);
    symptom3.setVisibility(View.GONE);
    sub_button.setEnabled(false);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    if (!calledAlready)
    {
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        calledAlready = true;
    }

    // Write a message to the database
    mFirebaseInstance = FirebaseDatabase.getInstance();
    // store app title to 'app_title' node
    mFirebaseInstance.getReference("app_title").setValue("microDoctor");
    mFirebaseDatabase = mFirebaseInstance.getReference("symptomList");
    spinnerDatabase = mFirebaseInstance.getReference("symptomView");
    //mFirebaseDatabase.child("Headache").child("Some Value").setValue("Head");
    //mFirebaseDatabase.setValue("Headache");

    spinnerData();
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            textSymptom1 = spinner.getItemAtPosition(i).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
    spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            textSymptom2 = spinner2.getItemAtPosition(i).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
    spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            textSymptom3 = spinner3.getItemAtPosition(i).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(i == 3)
                readDataListener();
            else
                readDataListenerForTwo();
        }
    });
    add_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            spinner3.setEnabled(true);
            spinner3.setVisibility(View.VISIBLE);
            symptom3.setVisibility(View.VISIBLE);
            add_button.setEnabled(false);
            sub_button.setEnabled(true);
            i++;
            Log.e("Value i","Value of i: "+i);
        }
    });
    sub_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            spinner3.setEnabled(false);
            spinner3.setVisibility(View.GONE);
            symptom3.setVisibility(View.GONE);
            add_button.setEnabled(true);
            sub_button.setEnabled(false);
            i--;
            Log.e("Value i","Value of i: "+i);
        }
    });

}

private void readDataListener() {
      mFirebaseDatabase.child(textSymptom1).child(textSymptom2).child(textSymptom3).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String symptom = dataSnapshot.child("disease").getValue(String.class);

            // Check for null
            if (symptom == null) {
                Log.e("Data", "Symptom data is null!");
                return;
            }

            Log.e("Symptom Data", "User data is changed!"+symptom);

            // Display newly updated name and email
            textView.setText(symptom+"\n"+dataSnapshot.getKey());
            Intent intent = new Intent(getApplicationContext(),DiseaseActivity.class);
            intent.putExtra("key", symptom);
            startActivity(intent);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Error", "Failed to read user", error.toException());
        }
    });
}
private void readDataListenerForTwo(){
        mFirebaseDatabase.child(textSymptom1).child(textSymptom2).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String symptom = dataSnapshot.getValue(String.class);

            // Check for null
            if (symptom == null) {
                Log.e("Data", "Symptom data is null!");
                Log.e("Chutiya","Haila! Chutiya run ho ra hai! ._.");
                return;
            }

            Log.e("Symptom Data", "User data is changed!"+symptom);

            // Display newly updated name and email
//                textView.setText(symptom+"\n"+dataSnapshot.getKey());
//                Intent intent = new Intent(getApplicationContext(),DiseaseActivity.class);
//                intent.putExtra("key", symptom);
//                startActivity(intent);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Error", "Failed to read user", error.toException());
        }
    });
}
private void spinnerData() {
    spinnerDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Log.e("Spinner Data", "Spinner data is changed!");

            //DataSnapshot data = dataSnapshot;
            Iterable<DataSnapshot> temp = dataSnapshot.getChildren();
            ArrayList<String> list = new ArrayList<>();
//                list.add(dataSnapshot.getValue().toString());
//                showDataInSpinner(list);
            for (DataSnapshot lists : temp){
                Log.d("ddd","Array List: "+lists.getValue().toString());
                list.add(lists.getValue().toString());
                textView.setText(lists.getValue().toString());
            }
            showDataInSpinner(list);

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.e("Error", "Failed to read user", error.toException());
        }
    });
}
public void showDataInSpinner(ArrayList<String> data) {
    ArrayAdapter<String> adapter = new ArrayAdapter<>(
            this, android.R.layout.simple_spinner_item, data
    ); //Create the Adapter to set the data
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);     //Set the layout resource to create the drop down views.
    spinner.setAdapter(adapter); //Set the data to your spinner
    spinner2.setAdapter(adapter);
    spinner3.setAdapter(adapter);
}
}

Gradle Error

11-16 01:02:13.816 22912-22912/com.example.nishantsikri.microdoctor E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.nishantsikri.microdoctor, PID: 22912
                                                                                com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
                                                                                at com.google.android.gms.internal.zzekp.zzb(Unknown Source)
                                                                                at com.google.android.gms.internal.zzekp.zza(Unknown Source)
                                                                                at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                                                at com.example.nishantsikri.microdoctor.SymptomActivity$9.onDataChange(SymptomActivity.java:204)
                                                                                at com.google.android.gms.internal.zzeex.zza(Unknown Source)
                                                                                at com.google.android.gms.internal.zzegs.zzbwg(Unknown Source)
                                                                                at com.google.android.gms.internal.zzegy.run(Unknown Source)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6236)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)

Body:
To get those names under Diarrhea, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference diarrheaRef = rootRef.child("symptomList").child("Bloating").child("Diarrhea");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.getKey();
            Log.d("TAG", name);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
diarrheaRef.addListenerForSingleValueEvent(eventListener);

Your output will be:

Cramps
Uncontrollable Bowel Syndrome


问:
Connect to signalr core server from signalr 4.6 client
Situation:

50% of our applications are currently running on .net4.6

Other 50% is written in .net core

Currently we're creating a SignalR service which will then be used by both the .net4.6 and .net core applications

The SignalR service is a new feature, thus we want to write this in .net core. The SignalR service is up and running and we can connect from our core projects as follows (simplified console app):

```<code>Console.WriteLine("Hello World!");
var connection = new HubConnectionBuilder()
    .WithUrl("http://localhost:5123/myhub")
    .WithConsoleLogger()
    .Build();

connection.StartAsync().Wait();

connection.On<string>("send", data =>
{
    Console.WriteLine($"Received: {data}");
});

Console.ReadLine();

connection.DisposeAsync().Wait();
</code>```

As long as we're staying in the .net core world, there is no problem. The problem occurs when we're trying to connect from our .net4.6 applications.

Example (also simplified console app):

```<code>var connection = new HubConnection("http://localhost:5123/myhub");
var hub = connection.CreateHubProxy("myhub");

connection.Start().ContinueWith(task =>
{
    if (task.IsFaulted)
    {
        Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
    }
    else
    {
        Console.WriteLine("Connected");
    }
});

hub.On<string>("send", result =>
{
    Console.WriteLine(result);
});

Console.Read();
connection.Stop();
</code>```

Here we're getting a 404 not found error, using the exact same URL:

```<code>There was an error opening the connection: Microsoft.AspNet.SignalR.Client.HttpClientException: StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcZ29ldGVsZW5kclxzb3VyY2VccmVwb3NcU2lnbmFsUlN0YXJ0ZXJcU2lnbmFsUlN0YXJ0ZXIuQVBJXG15aHViXHNpZ25hbHJcbmVnb3RpYXRl?=
  Date: Wed, 15 Nov 2017 12:16:02 GMT
  Server: Kestrel
  X-Powered-By: ASP.NET
  Content-Length: 0
}
   at Microsoft.AspNet.SignalR.Client.Http.DefaultHttpClient.<>c__DisplayClass5_0.<Get>b__1(HttpResponseMessage responseMessage)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.<>c__DisplayClass31_0`2.<Then>b__0(Task`1 t)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.TaskRunners`2.<>c__DisplayClass3_0.<RunTask>b__0(Task`1 t)
</code>```

The main question is if it is possible to connect from .net 4.6 to .net core signalR hubs?

答: The previous version of SignalR is not compatible with the Asp.NET Core version of SignalR. This means that you won't be able to use old client with the new server or vice versa. The new client targets netstandard 2.0 meaning you can use it in applications running on full .NET Framework as long as you are running .NET Framework 4.6.1.</p>

Body:
Situation:

50% of our applications are currently running on .net4.6

Other 50% is written in .net core

Currently we're creating a SignalR service which will then be used by both the .net4.6 and .net core applications

The SignalR service is a new feature, thus we want to write this in .net core. The SignalR service is up and running and we can connect from our core projects as follows (simplified console app):

Console.WriteLine("Hello World!");
var connection = new HubConnectionBuilder()
    .WithUrl("http://localhost:5123/myhub")
    .WithConsoleLogger()
    .Build();

connection.StartAsync().Wait();

connection.On<string>("send", data =>
{
    Console.WriteLine($"Received: {data}");
});

Console.ReadLine();

connection.DisposeAsync().Wait();

As long as we're staying in the .net core world, there is no problem. The problem occurs when we're trying to connect from our .net4.6 applications.

Example (also simplified console app):

var connection = new HubConnection("http://localhost:5123/myhub");
var hub = connection.CreateHubProxy("myhub");

connection.Start().ContinueWith(task =>
{
    if (task.IsFaulted)
    {
        Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
    }
    else
    {
        Console.WriteLine("Connected");
    }
});

hub.On<string>("send", result =>
{
    Console.WriteLine(result);
});

Console.Read();
connection.Stop();

Here we're getting a 404 not found error, using the exact same URL:

There was an error opening the connection: Microsoft.AspNet.SignalR.Client.HttpClientException: StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcZ29ldGVsZW5kclxzb3VyY2VccmVwb3NcU2lnbmFsUlN0YXJ0ZXJcU2lnbmFsUlN0YXJ0ZXIuQVBJXG15aHViXHNpZ25hbHJcbmVnb3RpYXRl?=
  Date: Wed, 15 Nov 2017 12:16:02 GMT
  Server: Kestrel
  X-Powered-By: ASP.NET
  Content-Length: 0
}
   at Microsoft.AspNet.SignalR.Client.Http.DefaultHttpClient.<>c__DisplayClass5_0.<Get>b__1(HttpResponseMessage responseMessage)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.<>c__DisplayClass31_0`2.<Then>b__0(Task`1 t)
   at Microsoft.AspNet.SignalR.TaskAsyncHelper.TaskRunners`2.<>c__DisplayClass3_0.<RunTask>b__0(Task`1 t)

The main question is if it is possible to connect from .net 4.6 to .net core signalR hubs?


问:
Erlang Universal Binary Format? Anyone using it?
I recently stumbled upon this 2002 conference paper (Getting Erlang to talk to the outside world by Joe Armstrong) and I was wondering whether this is a standard that was ignored or if there was any adoption?

Should I focus on Apache Thrift for inter-platform communication? (whatever solution I choose will involve at least Erlang)

答:
UBF never really caught on. Here's what Armstrong had to say in 2008. As you look into Thrift you might also look into Protocol Buffers. You can find an Erlang implementation here.

Hope this helps.


问:
How to filter dimension from another dimension in tableau
Question in Tableau:

I have a list of products and category and subcategory, what i need is: show sales by products of a subcategory, while the product is selected from a parameters which has list of products.

I want to add this parameter as a master filter for my dashboard where i can show the current Qtr sales for the product, in another chart i want to show the trend of products in the subcategory.

Currently when i try to do a filter from dashboard, the second chart with trend shows up only for the selected product not its class of product.

Thanks in Advance!

答:
You can define the specific sheets that are affected from dashboard filter actions.
http://onlinehelp.tableau.com/current/pro/desktop/en-us/actions_filter.html

If you are not using a dashboard action, you can also configure which sheets a filter applies to.
http://onlinehelp.tableau.com/current/pro/desktop/en-us/filtering_global.html


问:
iOS 11 navigation bar transparent with large titles
I have default preferences for uinavigationbar:

```<code>UINavigationBar.appearance().barTintColor = .red
        UINavigationBar.appearance().titleTextAttributes = [ NSAttributedStringKey.foregroundColor:#colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)]
        if #available(iOS 11.0, *) {
            UINavigationBar.appearance().largeTitleTextAttributes = [ NSAttributedStringKey.foregroundColor:#colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)]
        }
        UINavigationBar.appearance().isTranslucent = false
        UINavigationBar.appearance().tintColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)
</code>```

Structure: UINaviagtionController -> PostsTableViewController -> PostTableViewController.

I want to have large navigation bar on PostsViewController (with opaque background color) and transparent navigation bar on PostViewController.

In PostTableViewController i add:

```<code>self.navigationController?.navigationBar.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.barTintColor = .clear

        self.automaticallyAdjustsScrollViewInsets = false
        //self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        //self.navigationController?.navigationBar.shadowImage = UIImage()
        if #available(iOS 11.0, *) {
            print("asd")
            self.tableView.insetsContentViewsToSafeArea = false
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
</code>```

Navigation bar is BLACK. I dont understand how make it transparent...

UPDATE:

git hub repository: https://github.com/Mazorati/testnavbar

i set isTranslucent = true, but large navigation becomes also transparent. Only default navigation is ok.

But i want navigationbar color to be opaque, so:

```<code>self.navigationController?.view.backgroundColor = .red
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .automatic
</code>```

As the result:

3D layers:

答:
Try this, this make your navigation bar transparent.</p>

```<code>    let img = UIImage()
    navigationController?.navigationBar.shadowImage = img
    navigationController?.navigationBar.setBackgroundImage(img, for: .default)
</code>```

Body:
I have default preferences for uinavigationbar:

UINavigationBar.appearance().barTintColor = .red
        UINavigationBar.appearance().titleTextAttributes = [ NSAttributedStringKey.foregroundColor:#colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)]
        if #available(iOS 11.0, *) {
            UINavigationBar.appearance().largeTitleTextAttributes = [ NSAttributedStringKey.foregroundColor:#colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)]
        }
        UINavigationBar.appearance().isTranslucent = false
        UINavigationBar.appearance().tintColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 1)

Structure: UINaviagtionController -> PostsTableViewController -> PostTableViewController.

I want to have large navigation bar on PostsViewController (with opaque background color) and transparent navigation bar on PostViewController.

In PostTableViewController i add:

self.navigationController?.navigationBar.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.barTintColor = .clear

        self.automaticallyAdjustsScrollViewInsets = false
        //self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        //self.navigationController?.navigationBar.shadowImage = UIImage()
        if #available(iOS 11.0, *) {
            print("asd")
            self.tableView.insetsContentViewsToSafeArea = false
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }

Navigation bar is BLACK. I dont understand how make it transparent...

UPDATE:

git hub repository: https://github.com/Mazorati/testnavbar

i set isTranslucent = true, but large navigation becomes also transparent. Only default navigation is ok.

But i want navigationbar color to be opaque, so:

self.navigationController?.view.backgroundColor = .red
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .automatic

As the result:

3D layers:

Body:
Try this, this make your navigation bar transparent.

    let img = UIImage()
    navigationController?.navigationBar.shadowImage = img
    navigationController?.navigationBar.setBackgroundImage(img, for: .default)


问:
Javascript delay between turns
I'm trying to make a turn-based battle system in a RPG I'm building. I want the player to be able to see (through CSS) how his own and enemy's life lowers throughout the fight.
This is my current code:

```<code>// Defining the variables globally for accessibility.
var enemy_max_hp = 0;
var enemy_hp = 0;
var enemy_atk_dmg = 0;
var enemy_def_pwr = 0;
var enemy_crit_chance = 0;
var enemy_crit_pwr = 0.0;

function battle() {
    while(current_hp > 0 || enemy_current_hp <= 0){
        //setTimeout(function(){
            current_hp -= enemy_atk_dmg*enemy_crit_pwr*crit_chance/100 + def_pwr/2;
            enemy_hp -= attack_dmg*crit_power*crit_chance/100 - enemy_def_pwr/2;

            if(current_hp < 0){ current_hp = 0; }
            if(enemy_hp < 0){ enemy_hp = 0; }

            if (current_hp == 0){
                // Die
            }

            if (enemy_current_hp == 0){
                // Win battle, proceed.
                    spawnenemy();
            }
        //}, 1000);
    }
}

function spawnenemy() {
    enemy_max_hp = 150;
    enemy_hp = 150;
    enemy_atk_dmg = 5;
    enemy_def_pwr = 3;
    enemy_crit_chance = 0;
    enemy_crit_pwr = 0;
}
</code>```

I'm updating the user's data via another script:

```<code>var max_hp = 100;
var current_hp = 100;
var attack_dmg = 5;
var defense_power = 4;
var crit_chance = 0;
var crit_power = 0.0;

function showStats(){
    document.getElementById("max_hp").innerHTML = max_hp;
    document.getElementById("current_hp").innerHTML = current_hp;
    document.getElementById("attack_dmg").innerHTML = attack_dmg;
    document.getElementById("defense_power").innerHTML = defense_power;
    document.getElementById("crit_chance").innerHTML = crit_chance + '%';
    document.getElementById("crit_power").innerHTML = crit_power;
}
setInterval(showStats, 5);
</code>```

If I run the code, as is, the battle ends in matter of an eyeblink, and health runs from 100 to 0 in an instance. I figured adding the setTimeout() function would work, but it just crashes the webpage. What should I do?

Also, the battle function is called (per now) via a button onclick call. I tried making a turn() function, but I miserably failed.

On a side note, I try to avoid any use of external packages. I have never touched jQuery or Angular2, and per now I won't use it. If any of you know a solution using it, though, feel free to share it. I don't care much about backwards-compatibility, either, tbh.

答:
Change your battle function to the following:

```<code>function battle() {
    var t = setInterval(function() {
        if(current_hp > 0 || enemy_current_hp <= 0) {

            // code to update battle stats

        } else {
            clearInterval(t);
        }
    }, 1000);
}
</code>```

The problem with your code is that setTimeout and setInterval are asynchronous functions -- i.e., JavaScript will not wait for the them to finish, and thus your while loop is creating an infinite number of them and crashing your program. because it is halting for the timeouts to finish.

This modified program will instead run the code inside the setInterval block every second without creating an infinite loop. Once the battle is ended, it will clear the setInterval.

Title: Javascript delay between turns

Body:
I'm trying to make a turn-based battle system in a RPG I'm building. I want the player to be able to see (through CSS) how his own and enemy's life lowers throughout the fight.
This is my current code:

// Defining the variables globally for accessibility.
var enemy_max_hp = 0;
var enemy_hp = 0;
var enemy_atk_dmg = 0;
var enemy_def_pwr = 0;
var enemy_crit_chance = 0;
var enemy_crit_pwr = 0.0;

function battle() {
    while(current_hp > 0 || enemy_current_hp <= 0){
        //setTimeout(function(){
            current_hp -= enemy_atk_dmg*enemy_crit_pwr*crit_chance/100 + def_pwr/2;
            enemy_hp -= attack_dmg*crit_power*crit_chance/100 - enemy_def_pwr/2;

            if(current_hp < 0){ current_hp = 0; }
            if(enemy_hp < 0){ enemy_hp = 0; }

            if (current_hp == 0){
                // Die
            }

            if (enemy_current_hp == 0){
                // Win battle, proceed.
                    spawnenemy();
            }
        //}, 1000);
    }
}

function spawnenemy() {
    enemy_max_hp = 150;
    enemy_hp = 150;
    enemy_atk_dmg = 5;
    enemy_def_pwr = 3;
    enemy_crit_chance = 0;
    enemy_crit_pwr = 0;
}

I'm updating the user's data via another script:

var max_hp = 100;
var current_hp = 100;
var attack_dmg = 5;
var defense_power = 4;
var crit_chance = 0;
var crit_power = 0.0;

function showStats(){
    document.getElementById("max_hp").innerHTML = max_hp;
    document.getElementById("current_hp").innerHTML = current_hp;
    document.getElementById("attack_dmg").innerHTML = attack_dmg;
    document.getElementById("defense_power").innerHTML = defense_power;
    document.getElementById("crit_chance").innerHTML = crit_chance + '%';
    document.getElementById("crit_power").innerHTML = crit_power;
}
setInterval(showStats, 5);

If I run the code, as is, the battle ends in matter of an eyeblink, and health runs from 100 to 0 in an instance. I figured adding the setTimeout() function would work, but it just crashes the webpage. What should I do?

Also, the battle function is called (per now) via a button onclick call. I tried making a turn() function, but I miserably failed.

On a side note, I try to avoid any use of external packages. I have never touched jQuery or Angular2, and per now I won't use it. If any of you know a solution using it, though, feel free to share it. I don't care much about backwards-compatibility, either, tbh.

Body:
Change your battle function to the following:

function battle() {
    var t = setInterval(function() {
        if(current_hp > 0 || enemy_current_hp <= 0) {

            // code to update battle stats

        } else {
            clearInterval(t);
        }
    }, 1000);
}

The problem with your code is that setTimeout and setInterval are asynchronous functions -- i.e., JavaScript will not wait for the them to finish, and thus your while loop is creating an infinite number of them and crashing your program. because it is halting for the timeouts to finish.

This modified program will instead run the code inside the setInterval block every second without creating an infinite loop. Once the battle is ended, it will clear the setInterval.


问:
how to only use pyflakes checks with pep8 (never style checks)?
I'm migrating from pyflakes to flake8 to get the # noqa line ignore feature.  To ease the migration, I'd like to start with only checking whatever pyflakes was previously checking, and I like pyflakes simple promise to "will never complain about style".  Can I just use flake8 --select F to start with whatever was reported by pyflakes?

flake8 allows selecting or disabling specific error codes like F401 "module imported but unused".  What does F stand for?

The flake8 error-code documentation doesn't list all error codes.

答:
Yes, to only use pyflakes:

```<code>flake8 --select F
</code>```

flake8 documents the F and C "classes" on the pyflakes glossary:

F: pyflakes lint checks; some documented by flake8

C: mccabe complexity, currently only C901

W and E: pep8 violations documented by pycodestyle

E999 is not a pep error; "We report E999 when we fail to compile a file into an Abstract Syntax Tree for the plugins that require it"

Body:
Yes, to only use pyflakes:

flake8 --select F

flake8 documents the F and C "classes" on the pyflakes glossary:

F: pyflakes lint checks; some documented by flake8

C: mccabe complexity, currently only C901

W and E: pep8 violations documented by pycodestyle

E999 is not a pep error; "We report E999 when we fail to compile a file into an Abstract Syntax Tree for the plugins that require it"


问:
Choose two different years joined employees from table
In oracle for informatica, I am using the condition to_char(hiredate, 'YYYY')=1981 and it is showing me all 1981 employees, if I want to see 1981 and 1982 employees together, which code is required?

答:
you could use a IN clause</p>

```<code>where to_char(hiredate, 'YYYY') IN ( '1981', '1982')
</code>```

Body:
you could use a IN clause

where to_char(hiredate, 'YYYY') IN ( '1981', '1982')


问:
How to write a bash script to give another program response
I have a bash script that does several tasks, including python manage.py syncdb on a fresh database. This command asks for input, like the login info for the admin. Currently, I just type this into the command line every time. Is there a way I can automatically provide these replies as part of the bash script?

Thanks, I don't really know anything about bash.

I'm using Ubuntu 10.10.

答:
You can give defaults values to the variables. In line 4 and 5, if the variables RSRC and LOCAL aren't set, they are set to those default values. This way you can give the options to your script or use the default ones</p>

```<code>#!/bin/bash
RSRC=$1
LOCAL=$2
: ${RSRC:="/var/www"}
: ${LOCAL:="/disk2/backup/remote/hot"}
rsync -avz -e 'ssh ' user@myserver:$RSRC $LOCAL
</code>```

Body:
You can give defaults values to the variables. In line 4 and 5, if the variables RSRC and LOCAL aren't set, they are set to those default values. This way you can give the options to your script or use the default ones

#!/bin/bash
RSRC=$1
LOCAL=$2
: ${RSRC:="/var/www"}
: ${LOCAL:="/disk2/backup/remote/hot"}
rsync -avz -e 'ssh ' user@myserver:$RSRC $LOCAL


问:
Drupal folders within docker
I succesfully installed drupal 7 with docker.

Using docker4drupal, now my question when I start editing my drupal site is, where are the folders containing drupal?

Let's say I installed a new theme and want to swap the images for the banner, how do I access the drupal folder containing the images, or would it be preciser to ask : Where does Docker storage them?

My docker compose line is :

-codebase : /var/www/html

I know that installing it using :

./:/var/www/html

Would install drupal in the same directory my docker-compose.yml is, but for some reason it doesn't work and still doesn't show me where the files are.

Any help is welcome!

答:
If you are not using volumes to mount your existing code, the code resides inside the docker container. You can access it only by getting inside the container using docker exec.   If you are using the default docker-compose.yml that came with the repo, then the name of the container will be "docker4drupal_nginx_1" (since nginx is the default).

Run this code to get inside the container:

```<code>docker exec -it docker4drupal_nginx_1 /bin/bash
</code>```

exec allows you to execute commands inside the container.

-it allows you to start an interactive terminal

/bin/bash allows you to start the bash terminal inside the container

Once you are inside container run ls and you will see drupal files including "web".

MORE USEFUL

However, this is not a useful way if you want to work on the files and probably use an editor. Instead, mount a directory on host machine.  First make a new directory where your docker-compose.yml file is with the name "codebase".

Then, update the docker-compose.yml so that:

```<code>- codebase:/var/www/html
</code>```

becomes

```<code>- ./codebase:/var/www/html
</code>```

Do this in both php and nginx service definisions. Of course, you should do this after you run docker-compose down with your previous set up. Then restart containers using docker-compose up -d.

Then, you will notice that the Drupal files are present in the codebase directory.

If you see at the bottom of the yml file, you will see that "codebase" is defined as a Docker volume. This implies the storage is managed by Docker and it will get stored somewhere in /var/lib/docker/ along with the container itself.

Hope this helps.

Title: Drupal folders within docker

Body:
If you are not using volumes to mount your existing code, the code resides inside the docker container. You can access it only by getting inside the container using docker exec.   If you are using the default docker-compose.yml that came with the repo, then the name of the container will be "docker4drupal_nginx_1" (since nginx is the default).

Run this code to get inside the container:

docker exec -it docker4drupal_nginx_1 /bin/bash

exec allows you to execute commands inside the container.

-it allows you to start an interactive terminal

/bin/bash allows you to start the bash terminal inside the container

Once you are inside container run ls and you will see drupal files including "web".

MORE USEFUL

However, this is not a useful way if you want to work on the files and probably use an editor. Instead, mount a directory on host machine.  First make a new directory where your docker-compose.yml file is with the name "codebase".

Then, update the docker-compose.yml so that:

- codebase:/var/www/html

becomes

- ./codebase:/var/www/html

Do this in both php and nginx service definisions. Of course, you should do this after you run docker-compose down with your previous set up. Then restart containers using docker-compose up -d.

Then, you will notice that the Drupal files are present in the codebase directory.

If you see at the bottom of the yml file, you will see that "codebase" is defined as a Docker volume. This implies the storage is managed by Docker and it will get stored somewhere in /var/lib/docker/ along with the container itself.

Hope this helps.


问:
Return Empty column if column does not exist in dataframe
I created a dataframe df as below:

```<code>Type = ['A', 'B', 'C', 'D']
Size = [72,23,66,12]
df = pd.DataFrame({'Type': Type, 'Size': Size})
</code>```

I can extract any existing column using:

```<code>df_count = df['Size']
</code>```

However, if a data frame is too big, and I don't know if the column exist in df or not. In such if I call a column e.g. df['Shape'] as below:

```<code>df_null = df['Shape']
</code>```

It raises a KeyError. However I want that df_null should get an empty column with name "Shape".

答:
Use DataFrame.get in a pattern similar to:

```<code>In [3]: df.get('Size', pd.Series(index=df.index, name='Size'))
Out[3]:
0    72
1    23
2    66
3    12
Name: Size, dtype: int64

In [4]: df.get('Shape', pd.Series(index=df.index, name='Shape'))
Out[4]:
0   NaN
1   NaN
2   NaN
3   NaN
Name: Shape, dtype: float64
</code>```

Or generalize by creating a function to abstract this:

```<code>In [5]: get_column = lambda df, col: df.get(col, pd.Series(index=df.index, name=col))

In [6]: get_column(df, 'Size')
Out[6]:
0    72
1    23
2    66
3    12
Name: Size, dtype: int64

In [7]: get_column(df, 'Shape')
Out[7]:
0   NaN
1   NaN
2   NaN
3   NaN
Name: Shape, dtype: float64
</code>```

Another alternative could be to use reindex and squeeze:

```<code>In [8]: df.reindex(columns=['Size']).squeeze()
Out[8]:
0    72
1    23
2    66
3    12
Name: Size, dtype: int64

In [9]: df.reindex(columns=['Shape']).squeeze()
Out[9]:
0   NaN
1   NaN
2   NaN
3   NaN
Name: Shape, dtype: float64
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a dataframe df as below:

Type = ['A', 'B', 'C', 'D']
Size = [72,23,66,12]
df = pd.DataFrame({'Type': Type, 'Size': Size})

I can extract any existing column using:

df_count = df['Size']

However, if a data frame is too big, and I don't know if the column exist in df or not. In such if I call a column e.g. df['Shape'] as below:

df_null = df['Shape']

It raises a KeyError. However I want that df_null should get an empty column with name "Shape".

Body:
Use DataFrame.get in a pattern similar to:

In [3]: df.get('Size', pd.Series(index=df.index, name='Size'))
Out[3]:
0    72
1    23
2    66
3    12
Name: Size, dtype: int64

In [4]: df.get('Shape', pd.Series(index=df.index, name='Shape'))
Out[4]:
0   NaN
1   NaN
2   NaN
3   NaN
Name: Shape, dtype: float64

Or generalize by creating a function to abstract this:

In [5]: get_column = lambda df, col: df.get(col, pd.Series(index=df.index, name=col))

In [6]: get_column(df, 'Size')
Out[6]:
0    72
1    23
2    66
3    12
Name: Size, dtype: int64

In [7]: get_column(df, 'Shape')
Out[7]:
0   NaN
1   NaN
2   NaN
3   NaN
Name: Shape, dtype: float64

Another alternative could be to use reindex and squeeze:

In [8]: df.reindex(columns=['Size']).squeeze()
Out[8]:
0    72
1    23
2    66
3    12
Name: Size, dtype: int64

In [9]: df.reindex(columns=['Shape']).squeeze()
Out[9]:
0   NaN
1   NaN
2   NaN
3   NaN
Name: Shape, dtype: float64


答:
SetTimeout (kindof) spawns a separate process, which starts life of it's own. The code, where this is called doesn't stop.

You should do something like this:

```<code>function battle(){

    if(current_hp > 0 || enemy_current_hp <= 0){

        // do your win thing

    } else {

        // do your fight thing

        // next round in 1 second
        setTimeout(battle, 1000);

    }

}
</code>```

Using setTimeout for such purposes is better idea than setInterval, as you don't have to clear them and they won't get crowded - if your fight takes longer than period, then this won't run into next fight.

About jQuery, instead of long js selectors like this:

```<code>document.getElementById("max_hp").innerHTML = max_hp;
</code>```

in jQuery you can write:

```<code>$('#max_hp').html(max_hp);
</code>```

Additionally, setInterval with 5 millisecond period is kind of dangerous, especially on slower computers. Use at least 17 ms interval, or even 100ms. Normal human beings won't see updates less than 100 ms anyway.

Title: Javascript delay between turns

Body:
SetTimeout (kindof) spawns a separate process, which starts life of it's own. The code, where this is called doesn't stop.

You should do something like this:

function battle(){

    if(current_hp > 0 || enemy_current_hp <= 0){

        // do your win thing

    } else {

        // do your fight thing

        // next round in 1 second
        setTimeout(battle, 1000);

    }

}

Using setTimeout for such purposes is better idea than setInterval, as you don't have to clear them and they won't get crowded - if your fight takes longer than period, then this won't run into next fight.

About jQuery, instead of long js selectors like this:

document.getElementById("max_hp").innerHTML = max_hp;

in jQuery you can write:

$('#max_hp').html(max_hp);

Additionally, setInterval with 5 millisecond period is kind of dangerous, especially on slower computers. Use at least 17 ms interval, or even 100ms. Normal human beings won't see updates less than 100 ms anyway.


问:
predict after multiple imputation in R
I used the mice package in R to perform multiple imputation for my data:

```<code>### multiple inputation by chained equations
imp.data <- mice(data, maxit = 5, m = 5, seed = 92385, print = F)
</code>```

I want to run a logistic regression model after the MI, and predict the outcome based on the model:

```<code>model <- with(imp.data, glm(died ~ agecat + female_1 + insurance + mech + transfer +
                          iss + mxaisbr1 + maxais + cm_chf_1 + cm_mets_1 + cm_liver_1 +
                          cm_htn_c_1 + cm_bldloss_1 + state, family = binomial))
</code>```

However, the predict command does not work:

```<code>predict(pool(model), type = c('response'))
</code>```

It would be much simpler if I have the data with imputed values, but the imputation got 5 imputed data sets, making the post estimation complicated.
Any idea ?

Thanks!!

答:
I'm not sure if the imputed models are saved as a data.frame or a matrix..

But, if you convert the model to a data.frame you can plug on the columns of interest to your original frame.

```<code>imp.data <- data.frame(imp.data)
original.df$NewImputtedColumn <- imp.data[, 1] # Assuming you want column 1
</code>```

Now, you can easily keep the copies of the imputted models and still only work with a single data.frame in your predictive models.

This is what I tend to do anyway, might not be the standard way (I'm not sure).

You are only taking the inputted values from 1 of the imputed models, right?

Title: predict after multiple imputation in R

Body:
I used the mice package in R to perform multiple imputation for my data:

### multiple inputation by chained equations
imp.data <- mice(data, maxit = 5, m = 5, seed = 92385, print = F)

I want to run a logistic regression model after the MI, and predict the outcome based on the model:

model <- with(imp.data, glm(died ~ agecat + female_1 + insurance + mech + transfer +
                          iss + mxaisbr1 + maxais + cm_chf_1 + cm_mets_1 + cm_liver_1 +
                          cm_htn_c_1 + cm_bldloss_1 + state, family = binomial))

However, the predict command does not work:

predict(pool(model), type = c('response'))

It would be much simpler if I have the data with imputed values, but the imputation got 5 imputed data sets, making the post estimation complicated.
Any idea ?

Thanks!!

Body:
I'm not sure if the imputed models are saved as a data.frame or a matrix..

But, if you convert the model to a data.frame you can plug on the columns of interest to your original frame.

imp.data <- data.frame(imp.data)
original.df$NewImputtedColumn <- imp.data[, 1] # Assuming you want column 1

Now, you can easily keep the copies of the imputted models and still only work with a single data.frame in your predictive models.

This is what I tend to do anyway, might not be the standard way (I'm not sure).

You are only taking the inputted values from 1 of the imputed models, right?