问:
Is there a relationship between dollar sign ($) and id function in Haskell?
One of these days I was reading comments on the Monad Challenge (which I highly recommend to any beginner in Haskell, like myself), and I ended up on this thread where I read that ($) = id.

I don't know about scaring people, but many programming languages have concepts that are best demonstrated with small examples that make people say "whoa".

For example, it's amazing that append() in Prolog can be run "backwards" from the concatenated result to yield all the lists that can be concatenated to produce it. Or that the monadic bind operator in Haskell (>>=) can be defined in terms of join and fmap, or that ($) = id.

($) = id !?

< tries it out in Raskell/Ghci >

I see now why it's true, but still... Whoah!! Thanks for that! (...)

I then checked the base-4.10.0.0 code, looking for the definitions of ($) and id, but right at the top I read this:

```NOTA BENE: Do NOT use ($) anywhere in this module! The type of ($) is
slightly magical (it can return unlifted types), and it is wired in.
But, it is also *defined* in this module, with a non-magical type.
GHC gets terribly confused (and *hangs*) if you try to use ($) in this
module, because it has different types in different scenarios.

This is not a problem in general, because the type ($), being wired in, is not
written out to the interface file, so importing files don't get confused.
The problem is only if ($) is used here. So don't!```

And their implementations are:

-- | Identity function.
id                      :: a -> a
id x                    =  x

-- | Application operator.
{-# INLINE ($) #-}
($)                     :: (a -> b) -> a -> b
f $ x                   =  f x
```

I tried swapping one by the other on GHCi and all I got was type errors (as I expected). Now, I have more questions than what I started with:

What do they mean by saying that ($) = id?

In which cases is that statement true? Does that mean I can use one instead of the other?

In the base, what is meant by saying that ($) is "slightly magical (it can return unlifted types)" and "being wired in"?

And what about "different types in different scenarios"? I thought that since Haskell is a strongly typed language, once you define a type signature, that signature is retained until the end of Time. Is that not true? Are there cases where one can change a function's type?

答:
Haskell indeed is strongly typed; the issue is related to some hackery specific to the ($) operator. Unfortunatelly, I have no idea what is it about: hopefully someone will answer your question 3 (and question 4 automatically).

Concerning question 1, look at the types:

```<code>id :: a -> a
($) :: (a -> b) -> (a -> b)
</code>```

Rename c = a -> b and you get ($) :: c -> c, which means that the type of ($) is a specification of the type of id, so that at least types allow us to use id to implement ($).

Now, look at the definition of ($):

```<code>f $ x = f x
</code>```

Let's rewrite it a bit:

```<code>($) f = \x -> f x
</code>```

And apply eta-reduction:

```<code>($) f = f
</code>```

Now it is clearly seen that ($) is just id with a bit more specific type (so that f is always a function).

Note that it doesn't work another way round, since the type of ($) is more restrictive. For example, you can call id 5 and get 5 as a result, but ($) 5 won't typecheck: 5 doesn't have type of the form a -> b.

The point of ($) is that it has very low priority and allows to avoid braces around the arguments of f, and can be used like

```<code>someFunction $ whatever complex computation you dont need braces around
</code>```

Body:
One of these days I was reading comments on the Monad Challenge (which I highly recommend to any beginner in Haskell, like myself), and I ended up on this thread where I read that ($) = id.

I don't know about scaring people, but many programming languages have concepts that are best demonstrated with small examples that make people say "whoa".

For example, it's amazing that append() in Prolog can be run "backwards" from the concatenated result to yield all the lists that can be concatenated to produce it. Or that the monadic bind operator in Haskell (>>=) can be defined in terms of join and fmap, or that ($) = id.

($) = id !?

< tries it out in Raskell/Ghci >

I see now why it's true, but still... Whoah!! Thanks for that! (...)

I then checked the base-4.10.0.0 code, looking for the definitions of ($) and id, but right at the top I read this:

NOTA BENE: Do NOT use ($) anywhere in this module! The type of ($) is
slightly magical (it can return unlifted types), and it is wired in.
But, it is also *defined* in this module, with a non-magical type.
GHC gets terribly confused (and *hangs*) if you try to use ($) in this
module, because it has different types in different scenarios.

This is not a problem in general, because the type ($), being wired in, is not
written out to the interface file, so importing files don't get confused.
The problem is only if ($) is used here. So don't!

And their implementations are:

-- | Identity function.
id                      :: a -> a
id x                    =  x

-- | Application operator.
{-# INLINE ($) #-}
($)                     :: (a -> b) -> a -> b
f $ x                   =  f x

I tried swapping one by the other on GHCi and all I got was type errors (as I expected). Now, I have more questions than what I started with:

What do they mean by saying that ($) = id?

In which cases is that statement true? Does that mean I can use one instead of the other?

In the base, what is meant by saying that ($) is "slightly magical (it can return unlifted types)" and "being wired in"?

And what about "different types in different scenarios"? I thought that since Haskell is a strongly typed language, once you define a type signature, that signature is retained until the end of Time. Is that not true? Are there cases where one can change a function's type?

Body:
Haskell indeed is strongly typed; the issue is related to some hackery specific to the ($) operator. Unfortunatelly, I have no idea what is it about: hopefully someone will answer your question 3 (and question 4 automatically).

Concerning question 1, look at the types:

id :: a -> a
($) :: (a -> b) -> (a -> b)

Rename c = a -> b and you get ($) :: c -> c, which means that the type of ($) is a specification of the type of id, so that at least types allow us to use id to implement ($).

Now, look at the definition of ($):

f $ x = f x

Let's rewrite it a bit:

($) f = \x -> f x

And apply eta-reduction:

($) f = f

Now it is clearly seen that ($) is just id with a bit more specific type (so that f is always a function).

Note that it doesn't work another way round, since the type of ($) is more restrictive. For example, you can call id 5 and get 5 as a result, but ($) 5 won't typecheck: 5 doesn't have type of the form a -> b.

The point of ($) is that it has very low priority and allows to avoid braces around the arguments of f, and can be used like

someFunction $ whatever complex computation you dont need braces around


来源: stackexchange

问:
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 was missing the following dependency:

```<code>dependencies {
    compile 'org.springframework:spring-context:5.0.1.RELEASE'
}
</code>```

Ultimately there were a lot of dependency mismatches due to my build.gradle. Make sure all spring modules are derived from the 5.0.1.RELEASE I found some from previous versions which caused different errors. I ended up defining my versions:

```<code>    ext {
    antJunitVersion = '1.9.7'
    assertjcoreVersion = '3.8.0'
    apiguardianVersion = '1.0.0'
    dokkaVersion = '0.9.15'
    dockerVersion = '1.2'
    h2Version = '1.4.196'
    hibernateVersion = '5.2.12.Final'
    jacksonVersion = '2.9.1'
    junit4Version = '4.12'
    junitVintageVersion = '4.12.2'
    junitPlatformVersion = '1.0.2'
    junitJupiterVersion = '5.0.2'
    kotlinVersion = '1.1.60'
    log4jVersion = '2.9.1'
    springVersion = '5.0.1.RELEASE'
    springBootVersion = '1.5.8.RELEASE'
    slf4jVersion = '1.7.25'
}
</code>```

and then declared them as explicit dependencies

```<code>// Spring Dependencies
compile("org.springframework:spring-webmvc:${springVersion}")
compile("org.springframework:spring-web:${springVersion}")
compile("org.springframework:spring-aspects:${springVersion}")
compile("org.springframework:spring-aop:${springVersion}")
compile("org.springframework:spring-orm:${springVersion}")
compile("org.springframework:spring-jdbc:${springVersion}")
compile("org.springframework:spring-tx:${springVersion}")
compile("org.springframework:spring-beans:${springVersion}")
compile("org.springframework:spring-expression:${springVersion}")
compile("org.springframework:spring-core:${springVersion}")
compile("org.springframework:spring-context:${springVersion}")
compile("org.springframework:spring-test:${springVersion}")
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") {
    exclude module: "spring-boot-starter-tomcat"
}
compile "org.springframework.boot:spring-boot-starter-jetty:${springBootVersion}"
compile "org.springframework.boot:spring-boot-starter-actuator:${springBootVersion}"
</code>```

ContentLicense: CC BY-SA 3.0

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 was missing the following dependency:

dependencies {
    compile 'org.springframework:spring-context:5.0.1.RELEASE'
}

Ultimately there were a lot of dependency mismatches due to my build.gradle. Make sure all spring modules are derived from the 5.0.1.RELEASE I found some from previous versions which caused different errors. I ended up defining my versions:

    ext {
    antJunitVersion = '1.9.7'
    assertjcoreVersion = '3.8.0'
    apiguardianVersion = '1.0.0'
    dokkaVersion = '0.9.15'
    dockerVersion = '1.2'
    h2Version = '1.4.196'
    hibernateVersion = '5.2.12.Final'
    jacksonVersion = '2.9.1'
    junit4Version = '4.12'
    junitVintageVersion = '4.12.2'
    junitPlatformVersion = '1.0.2'
    junitJupiterVersion = '5.0.2'
    kotlinVersion = '1.1.60'
    log4jVersion = '2.9.1'
    springVersion = '5.0.1.RELEASE'
    springBootVersion = '1.5.8.RELEASE'
    slf4jVersion = '1.7.25'
}

and then declared them as explicit dependencies

// Spring Dependencies
compile("org.springframework:spring-webmvc:${springVersion}")
compile("org.springframework:spring-web:${springVersion}")
compile("org.springframework:spring-aspects:${springVersion}")
compile("org.springframework:spring-aop:${springVersion}")
compile("org.springframework:spring-orm:${springVersion}")
compile("org.springframework:spring-jdbc:${springVersion}")
compile("org.springframework:spring-tx:${springVersion}")
compile("org.springframework:spring-beans:${springVersion}")
compile("org.springframework:spring-expression:${springVersion}")
compile("org.springframework:spring-core:${springVersion}")
compile("org.springframework:spring-context:${springVersion}")
compile("org.springframework:spring-test:${springVersion}")
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") {
    exclude module: "spring-boot-starter-tomcat"
}
compile "org.springframework.boot:spring-boot-starter-jetty:${springBootVersion}"
compile "org.springframework.boot:spring-boot-starter-actuator:${springBootVersion}"


问:
Read SharePoint List item using JavaScript
I am wondering if anyone could clarify my confusion on how to use JavaScript to read/filter SharePoint List items, please?
As a code example from MSDN:
https://msdn.microsoft.com/en-us/library/office/hh185007(v=office.14).aspx

In the CAML query XML, what is the FieldRef field in SharePoint List? Is it defined column names/list properties?

When ClientContext object load collListItem, it has a (Include) parameter which includes a bunch of field/property names, what are they? Are they defined column names/list properties as well?

Is there anyway I can know what field names are, so I can use/filter the List?

Thank you.

答:
The FieldRef is the internal field name of the column. Sometimes it's the same as the display name but as the display name can be changed you can't be certain of this. When creating new columns, I find it best to create them WithoutSpacesLikeThis and then replace the spaces once created. This makes it much easier to see what's happening when you're referencing them in code or in a URL etc. The same with Sites,Lists, Libraries etc.

The quickest way to find the internal name is to open the column as if you were going to edit it and then look in the URL and you will find the internal name there.

For example, the internal name of ApprovalStatus is at the end of the below URL after Field=. If the field has been created with a space in the name the space will be replaced by %20. E.g. Approval%20Status.

```<code>_layouts/15/FldEdit.aspx?List=%7BE07BFB18-BBED-4A57-8988-6CAEB47FAA02%7D&Field=ApprovalStatus
</code>```

Another way to see the field names would be to use the REST api. You can do this by adding _api/web/lits/getbytitle('NameOfList')/items to the end of the site collection URL. However, depending on the number of items you have in the list, it might return a lot of data.

```<code>https://tenant.sharepoint.com/sites/app/_api/web/lists/getbytitle('NameOfList)/items
</code>```

When ClientContext object load collListItem, it has a (Include)
  parameter which includes a bunch of field/property names, what are
  they? Are they defined column names/list properties as well?

As far as this part of your question is concerned, can you provide some of the properties to give a better idea of what it is you're talking about, please?

Body:
The FieldRef is the internal field name of the column. Sometimes it's the same as the display name but as the display name can be changed you can't be certain of this. When creating new columns, I find it best to create them WithoutSpacesLikeThis and then replace the spaces once created. This makes it much easier to see what's happening when you're referencing them in code or in a URL etc. The same with Sites,Lists, Libraries etc.

The quickest way to find the internal name is to open the column as if you were going to edit it and then look in the URL and you will find the internal name there.

For example, the internal name of ApprovalStatus is at the end of the below URL after Field=. If the field has been created with a space in the name the space will be replaced by %20. E.g. Approval%20Status.

_layouts/15/FldEdit.aspx?List=%7BE07BFB18-BBED-4A57-8988-6CAEB47FAA02%7D&Field=ApprovalStatus

Another way to see the field names would be to use the REST api. You can do this by adding _api/web/lits/getbytitle('NameOfList')/items to the end of the site collection URL. However, depending on the number of items you have in the list, it might return a lot of data.

https://tenant.sharepoint.com/sites/app/_api/web/lists/getbytitle('NameOfList)/items

When ClientContext object load collListItem, it has a (Include)
  parameter which includes a bunch of field/property names, what are
  they? Are they defined column names/list properties as well?

As far as this part of your question is concerned, can you provide some of the properties to give a better idea of what it is you're talking about, please?


问:
High Sierra issues with unsigned SSL certificate and local curl
For several OSX versions, I've been using these tutorials to set up a local development environment, including SSL.

I've also always been able to create dynamic virtual hosts based on the folder structure like this:

```<code># Auto-VirtualHosts with .dev
<VirtualHost *:8080>
  ServerName dev
  ServerAlias *.dev

  CustomLog "/Users/username/Sites/logs/dev-access_log" combinedmassvhost
  ErrorLog "/Users/username/Sites/logs/dev-error_log"

  VirtualDocumentRoot /Users/username/Sites/%-2+
</VirtualHost>
<VirtualHost *:8443>
  ServerName dev
  ServerAlias *.dev
  Include "/Users/username/Sites/ssl/ssl-shared-cert.inc"

  CustomLog "/Users/username/Sites/logs/dev-access_log" combinedmassvhost
  ErrorLog "/Users/username/Sites/logs/dev-error_log"

  VirtualDocumentRoot /Users/username/Sites/%-2+
</VirtualHost>
</code>```

The included SSL file there is like this:

```<code>SSLEngine On
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
SSLCertificateFile "/usr/local/etc/httpd/server.crt"
SSLCertificateKeyFile "/usr/local/etc/httpd/server.key"
</code>```

And to generate that certificate I run this code:

```<code>$ cd /usr/local/etc/httpd
$ openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout server.key -out server.crt
</code>```

This has always worked okay for me, locally. I can run curl successfully, and especially in WordPress development I can run cron tasks that presumably use curl.

Upon upgrading to High Sierra, I get the following error in WordPress:

There was a problem spawning a call to the WP-Cron system on your site. This means WP-Cron events on your site may not work. The problem was:
  cURL error 60: SSL certificate problem: self signed certificate

And on the command line, when I run curl to a local HTTPS URL, I get this error:

curl: (60) SSL certificate problem: self signed certificate
  More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
  establish a secure connection to it. To learn more about this situation and
  how to fix it, please visit the web page mentioned above.

I've tried reinstalling all the items from the initial tutorial, but so far nothing has helped. I've also tried installing curl from the Homebrew version instead of the built in, but this didn't seem to have any effect. Is there something known about High Sierra that would make it more picky about this? If so, is there anything I can do to bypass this for local development?

答:
You have to add your self-signed certificate to the curl CA certificate store.

First you have to generate the ca bundle by running the perl script stored in:

```<code>/usr/local/Cellar/curl/7.56.1/libexec/mk-ca-bundle.pl
</code>```

Edit the generated file:

```<code>/usr/local/Cellar/curl/7.56.1/libexec/ca-bundle.crt
</code>```

and add your self-signed certificate using the same syntax.

You can obtain the certificate with:

```<code>openssl s_client -showcerts -connect my.server.com:443
</code>```

Copy everything from :

```<code>-----BEGIN CERTIFICATE-----
</code>```

to

```<code>-----END CERTIFICATE-----
</code>```

including the BEGIN and ENDlines.
Create then a file ~/.curlrc containing:

```<code>cacert /usr/local/Cellar/curl/7.56.1/libexec/ca-bundle.crt
</code>```

Body:
For several OSX versions, I've been using these tutorials to set up a local development environment, including SSL.

I've also always been able to create dynamic virtual hosts based on the folder structure like this:

# Auto-VirtualHosts with .dev
<VirtualHost *:8080>
  ServerName dev
  ServerAlias *.dev

  CustomLog "/Users/username/Sites/logs/dev-access_log" combinedmassvhost
  ErrorLog "/Users/username/Sites/logs/dev-error_log"

  VirtualDocumentRoot /Users/username/Sites/%-2+
</VirtualHost>
<VirtualHost *:8443>
  ServerName dev
  ServerAlias *.dev
  Include "/Users/username/Sites/ssl/ssl-shared-cert.inc"

  CustomLog "/Users/username/Sites/logs/dev-access_log" combinedmassvhost
  ErrorLog "/Users/username/Sites/logs/dev-error_log"

  VirtualDocumentRoot /Users/username/Sites/%-2+
</VirtualHost>

The included SSL file there is like this:

SSLEngine On
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
SSLCertificateFile "/usr/local/etc/httpd/server.crt"
SSLCertificateKeyFile "/usr/local/etc/httpd/server.key"

And to generate that certificate I run this code:

$ cd /usr/local/etc/httpd
$ openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout server.key -out server.crt

This has always worked okay for me, locally. I can run curl successfully, and especially in WordPress development I can run cron tasks that presumably use curl.

Upon upgrading to High Sierra, I get the following error in WordPress:

There was a problem spawning a call to the WP-Cron system on your site. This means WP-Cron events on your site may not work. The problem was:
  cURL error 60: SSL certificate problem: self signed certificate

And on the command line, when I run curl to a local HTTPS URL, I get this error:

curl: (60) SSL certificate problem: self signed certificate
  More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
  establish a secure connection to it. To learn more about this situation and
  how to fix it, please visit the web page mentioned above.

I've tried reinstalling all the items from the initial tutorial, but so far nothing has helped. I've also tried installing curl from the Homebrew version instead of the built in, but this didn't seem to have any effect. Is there something known about High Sierra that would make it more picky about this? If so, is there anything I can do to bypass this for local development?

Body:
You have to add your self-signed certificate to the curl CA certificate store.

First you have to generate the ca bundle by running the perl script stored in:

/usr/local/Cellar/curl/7.56.1/libexec/mk-ca-bundle.pl

Edit the generated file:

/usr/local/Cellar/curl/7.56.1/libexec/ca-bundle.crt

and add your self-signed certificate using the same syntax.

You can obtain the certificate with:

openssl s_client -showcerts -connect my.server.com:443

Copy everything from :

-----BEGIN CERTIFICATE-----

to

-----END CERTIFICATE-----

including the BEGIN and ENDlines.
Create then a file ~/.curlrc containing:

cacert /usr/local/Cellar/curl/7.56.1/libexec/ca-bundle.crt


问:
Parallel.ForEach and ListView Control
I am having an issue getting the Parallel.ForEach to work properly. I have a listview control that loads a files contents or mutliple files contents (each file represents a log file) into a richtextbox. Had it all working with a Foreach loop but decided that the parallel operation would cut down on the loadtime when loading 100+ files.

Here is the code block I was using for the foreach loop. How do I get a Parallel.Foreach working?

```<code>//Set cursor to WaitCursor Style
this.Cursor = Cursors.WaitCursor;

//Clear Messages RichTexBox
this.rtbMessages.Clear();

//Loop through each selected file
foreach (ListViewItem Item in lvMessageFiles.Items)
{
    //Check if item is selected in the listview
    if (Item.Selected && rtbMessages.TextLength < rtbMessages.MaxLength)
    {
        //Get Path to message file
        filename = String.Format("{0}\\Data\\Log\\{1}.log", Global.AppPath, Item.SubItems[0].Text);

        //Set Timeline Events calendar to selected items created date
        cvTimeline.ShowDate(Convert.ToDateTime(lvMessageFiles.SelectedItems[0].SubItems[2].Text));

        //Check if file exists
        if (File.Exists(filename))
        {
            //streamreader to read the file
            reader = new StreamReader(filename);

            //to copy the read content in to richtextbox
            string MessageContents = String.Format("{0}\n{1}\n", ("file:///" + filename.Replace(" ", "%20").Replace("\\", "/")), reader.ReadToEnd());
            rtbMessages.Text += MessageContents;

            // closing streamreader
            reader.Close();
        }
    }

}

//Set cursor to WaitCursor Style
this.Cursor = Cursors.Default;
</code>```

答:
2 problems with what you are doing.

1) with this specific code, you are trying to modify UI from a background thread which is not allowed

2) this scenario isn't a good candidate for parallelization anyhow because you're performace is "I/O bound" to a single hard drive.  if you want to speed up load time, split the files onto multiple hard drives and then parallelization may be worthwhile

see Is Parallel File.Read Faster than Sequential Read?

ContentLicense: CC BY-SA 2.5

Title: Parallel.ForEach and ListView Control

Body:
I am having an issue getting the Parallel.ForEach to work properly. I have a listview control that loads a files contents or mutliple files contents (each file represents a log file) into a richtextbox. Had it all working with a Foreach loop but decided that the parallel operation would cut down on the loadtime when loading 100+ files.

Here is the code block I was using for the foreach loop. How do I get a Parallel.Foreach working?

//Set cursor to WaitCursor Style
this.Cursor = Cursors.WaitCursor;

//Clear Messages RichTexBox
this.rtbMessages.Clear();

//Loop through each selected file
foreach (ListViewItem Item in lvMessageFiles.Items)
{
    //Check if item is selected in the listview
    if (Item.Selected && rtbMessages.TextLength < rtbMessages.MaxLength)
    {
        //Get Path to message file
        filename = String.Format("{0}\\Data\\Log\\{1}.log", Global.AppPath, Item.SubItems[0].Text);

        //Set Timeline Events calendar to selected items created date
        cvTimeline.ShowDate(Convert.ToDateTime(lvMessageFiles.SelectedItems[0].SubItems[2].Text));

        //Check if file exists
        if (File.Exists(filename))
        {
            //streamreader to read the file
            reader = new StreamReader(filename);

            //to copy the read content in to richtextbox
            string MessageContents = String.Format("{0}\n{1}\n", ("file:///" + filename.Replace(" ", "%20").Replace("\\", "/")), reader.ReadToEnd());
            rtbMessages.Text += MessageContents;

            // closing streamreader
            reader.Close();
        }
    }

}

//Set cursor to WaitCursor Style
this.Cursor = Cursors.Default;


问:
HTML Anchor Tag Not Working in Outlook
I am making email template in Django to be sent to Outlook and I want to add anchor tag for navigation. However, I found the tags work in html browser but not in Outlook (both 2010 and 2013). Could anyone advise what have gone wrong and how to fix it? Many thanks.

Specifically I want the screen will move to Text1 location by clicking Text in the outlook:

```<code><table><tr><td>
<p><a href="#body204" style="text-decoration:none; color:#0000FF;"> Text </a></p>
</td></tr></table>

<table><tr>
<td name="body204"> Text1</td>
</tr></table>
</code>```

答:
This will work in outlook:  - take the anchor tag and inject it inside (empty value will work).

 Text

 Text1

 ```

Title: HTML Anchor Tag Not Working in Outlook

Body:
I am making email template in Django to be sent to Outlook and I want to add anchor tag for navigation. However, I found the tags work in html browser but not in Outlook (both 2010 and 2013). Could anyone advise what have gone wrong and how to fix it? Many thanks.

Specifically I want the screen will move to Text1 location by clicking Text in the outlook:

 Text

 Text1

Body:
This will work in outlook: <a name="body204"></a> - take the anchor tag and inject it inside (empty value will work).

<table><tr><td>
<p><a href="#body204" style="text-decoration:none; color:#0000FF;"> Text </a></p>
</td></tr></table>

<table><tr>
<td ><a name="body204"></a> Text1</td>
</tr></table>


问:
how can approach to parse huge JSON file in android studio in android java
I'm trying to parse some huge JSON file (like link ) using volley  library.
How can i load and add to RecyclerView.
 would like to know what is the best approch to parse this kind of big file (about 80k lines) and if you may know good API that can help me processing this. </p>

<p>help me ..-> Thanks.  </p>

答:
You should use Flatbuffer library :

- website : https://google.github.io/flatbuffers/

- talk 1 : https://www.youtube.com/watch?v=iQTxMkSJ1dQ

- talk 2 : https://www.youtube.com/watch?v=90ND0yQVYg8

My advice : By experience, Flatbuffer implementation can be complicated, so if your data can be static, use AssetManager to persist your huge JSON File in local application, and load it for use it.

Body:
I'm trying to parse some huge JSON file (like link ) using volley  library.
How can i load and add to RecyclerView.
 would like to know what is the best approch to parse this kind of big file (about 80k lines) and if you may know good API that can help me processing this.

help me ..-> Thanks.


问:
How to save value from System.currentTimeMillis() in android studio
I have this code:

```<code>public class MainActivity extends AppCompatActivity implements SensorEventListener {

    long start_time;
    int record_state;

    @Override
    public void onSensorChanged(SensorEvent event) {
    Long time = System.currentTimeMillis();

    if (record_state == 1)
    {
        start_time = time;
        record_state = 0;
    }

    if(Ax.size() == N_SAMPLES && Ay.size() == N_SAMPLES && Az.size() == N_SAMPLES) //assuming this gets executed
    {
        Toast.makeText(MainActivity.this, "Size of Ax: " + Integer.toString(Ax.size()) +
                    "\nSize of Ay: " + Integer.toString(Ay.size()) +
                    "\nSize of Az: " + Integer.toString(Az.size()) + "\n" + Long.toString((time)) + "\n" + Long.toString((start_time)) + "\nrecord state: " + Integer.toString((record_state)), Toast.LENGTH_LONG).show();
        }
    }
}
</code>```

But it appears that time and start_time always have the same value. I want start_time to record the time at the very beginning (or freeze the value of time at one instant) only. How can I do this? What is wrong with this code?

答:
If the code below does not work as you expected it to, then I suspect, that you have an issue with when and how "record_state" is being set somewhere in your code.

Local values with class wide scope:

```<code>int record_state = 1;
int iterations = 0;
long start_time;
</code>```

When your onSensorChanged triggers call  checkTimeDiff

```<code>private void checkTimeDiff(){
    iterations++;

    long time = SystemClock.elapsedRealtime();
    if (record_state == 1)
    {
        start_time = SystemClock.elapsedRealtime();
        record_state = 0;
    }

    long diff = time - start_time;
    Log.e("My Timer", "Time difference = " + diff + " number of iterations = " + iterations);

    if (diff >= 4000)
    {
        record_start = 1;
        Toast.makeText(MainActivity.this, Long.toString(time) + "\n" + Long.toString(start_time), Toast.LENGTH_SHORT).show();
    }
}
</code>```

It appears as if you are using "record_state" as a digital flag. In that case a boolean would be more elegant. But I will use your code as much as possible.

Body:
I have this code:

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    long start_time;
    int record_state;

    @Override
    public void onSensorChanged(SensorEvent event) {
    Long time = System.currentTimeMillis();

    if (record_state == 1)
    {
        start_time = time;
        record_state = 0;
    }

    if(Ax.size() == N_SAMPLES && Ay.size() == N_SAMPLES && Az.size() == N_SAMPLES) //assuming this gets executed
    {
        Toast.makeText(MainActivity.this, "Size of Ax: " + Integer.toString(Ax.size()) +
                    "\nSize of Ay: " + Integer.toString(Ay.size()) +
                    "\nSize of Az: " + Integer.toString(Az.size()) + "\n" + Long.toString((time)) + "\n" + Long.toString((start_time)) + "\nrecord state: " + Integer.toString((record_state)), Toast.LENGTH_LONG).show();
        }
    }
}

But it appears that time and start_time always have the same value. I want start_time to record the time at the very beginning (or freeze the value of time at one instant) only. How can I do this? What is wrong with this code?

Body:
If the code below does not work as you expected it to, then I suspect, that you have an issue with when and how "record_state" is being set somewhere in your code.

Local values with class wide scope:

int record_state = 1;
int iterations = 0;
long start_time;

When your onSensorChanged triggers call  checkTimeDiff

private void checkTimeDiff(){
    iterations++;

    long time = SystemClock.elapsedRealtime();
    if (record_state == 1)
    {
        start_time = SystemClock.elapsedRealtime();
        record_state = 0;
    }

    long diff = time - start_time;
    Log.e("My Timer", "Time difference = " + diff + " number of iterations = " + iterations);

    if (diff >= 4000)
    {
        record_start = 1;
        Toast.makeText(MainActivity.this, Long.toString(time) + "\n" + Long.toString(start_time), Toast.LENGTH_SHORT).show();
    }
}

It appears as if you are using "record_state" as a digital flag. In that case a boolean would be more elegant. But I will use your code as much as possible.


问:
wxpython add splitter window to notebook page
I have adapted this for my own use:

```<code>import wx
import wx.grid as gridlib

########################################################################
class LeftPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class RightPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title="Splitter Tutorial")

        splitter = wx.SplitterWindow(self)
        leftP = LeftPanel(splitter)
        rightP = RightPanel(splitter)

        # split the window
        splitter.SplitVertically(leftP, rightP)
        splitter.SetMinimumPaneSize(20)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()
</code>```

Now I want to add it as a page in a simple wxNotebook. Normally the notebook page would be set up something like:

```<code>p = wx.Panel(self)
nb = wx.Notebook(p)
page1 = module_name.module_Class(nb)
nb.AddPage(page1, "Tab label")
</code>```

The splitter has two (three in my case) panel Classes but obviously I can't just call one of them. Can someone please explain how I can wrap it all up?
Thanks.

答: Unless I'm missing something, you should just add the splitter itself as a page.</p>

Body:
I have adapted this for my own use:

import wx
import wx.grid as gridlib

########################################################################
class LeftPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class RightPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title="Splitter Tutorial")

        splitter = wx.SplitterWindow(self)
        leftP = LeftPanel(splitter)
        rightP = RightPanel(splitter)

        # split the window
        splitter.SplitVertically(leftP, rightP)
        splitter.SetMinimumPaneSize(20)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

Now I want to add it as a page in a simple wxNotebook. Normally the notebook page would be set up something like:

p = wx.Panel(self)
nb = wx.Notebook(p)
page1 = module_name.module_Class(nb)
nb.AddPage(page1, "Tab label")

The splitter has two (three in my case) panel Classes but obviously I can't just call one of them. Can someone please explain how I can wrap it all up?
Thanks.


问:
Mapping Over a new Array() without populating it returns an empty array. Why?

Riddle me this.

Let's say you new up an array of 1,000 elements and want to assign the index of each element as the element's value using .map(). I would expect it to work like so:

```<code>new Array(1000).map((element, i) => i);
</code>```

Here's the problem: the new array returned, while having the required 1,000 elements, is empty, despite assigning the .map()'s return value to be the array index. This can be remedied by chaining .fill(0) like so:

```<code>new Array(1000).fill(0).map((element, i) => i);
</code>```

But why?

Why do .map or .filter require a populated array to produce a populated array?

答:
To make it working you can use the spread operator in ECMA6

console.log([...new Array(1000)].map((element, i) => i))```

Body:
Riddle me this.

Let's say you new up an array of 1,000 elements and want to assign the index of each element as the element's value using .map(). I would expect it to work like so:

new Array(1000).map((element, i) => i);

Here's the problem: the new array returned, while having the required 1,000 elements, is empty, despite assigning the .map()'s return value to be the array index. This can be remedied by chaining .fill(0) like so:

new Array(1000).fill(0).map((element, i) => i);

But why?

Why do .map or .filter require a populated array to produce a populated array?


答:
You can introduce a variable that will give you the order of the CatId when the result set would have been ordered by CatId and then the 14 last digits of the AllocationId. So in your example this variable would be either 1 or 2.

Once you have that variable value for each record, you can sort by that value first, and then by CatId:

select t.allocationId, CatId
from (
    select  t.*,
            @rn := if(@CatId = CatId, @rn+1, if(@CatId := CatId, 1, 1)) rn
    from (
            SELECT      m.allocationID, mt.CatId,mt.CatSName
            FROM        msttransaction m,
            INNER JOIN  msttemp mt
                    ON  m.allocationID = mt.AllocationId
            WHERE       m.isPending='Y'
            AND         mt.quarterId='010100001'
            ORDER BY CatId, SUBSTRING(m.AllocationId, -14)
         ) t,
         (select @CatId := -1, @rn := -1) init
    ) t
order by rn, CatId;
```

Title: I want to sort my CatId in this order 1 2 3 4 1 2 3 4 but there is a catch that it first check allocationId last 14 digits if catid is same

Body:
My query is this:-

SELECT m.allocationID,mt.CatId,mt.CatSName
FROM msttransaction m,msttemp mt WHERE m.isPending='Y'
AND m.allocationID IN (
    SELECT mt.AllocationId FROM msttemp WHERE mt.quarterId='010100001'
) ORDER BY SUBSTRING(m.AllocationId, -14)

output:-

12980013120170919125006   1   A

12980013320170919125404   3   C

12980013420170919125603   4   D

12980013820170919130113   2   B

12980013920170919130315   3   C

12980014020170919130519   4   D

12980013220170919130613   2   B

12980013720170919130722   1   A

In 129800 series last 14 digits is date and time. First I have to sort my output according to 1 2 3 4 1 2 3 4 but first it check last 14 digits of 129800 of same catId that comes first which comes first.

Expected output

12980013120170919125006 1 A
12980013820170919130113 2 B
12980013320170919125404 3 C
12980013420170919125603 4 D
12980013720170919130722 1 A
12980013220170919130613 2 B
12980013920170919130315 3 C
12980014020170919130519 4 D


问:
how to convert this String to Decimal
i have this String '5666,232343' and i want to convert it to Decimal, i use cast('5666,232343' as decimal(7,5)) but it returns NULL value.
Do you know why it doesn't work with CAST

答:
The problem is probably the comma.  In some databases, some of the functions are not as internationally-sensitive as (I think) they should be.  So try:</p>

```<code>cast(replace('5666,232343', ',', '.') as decimal(7, 5))
</code>```

Title: how to convert this String to Decimal

Body:
The problem is probably the comma.  In some databases, some of the functions are not as internationally-sensitive as (I think) they should be.  So try:

cast(replace('5666,232343', ',', '.') as decimal(7, 5))


问:
Slickgrid: how to get selected rows with new Checkbox Select Column plugin?
I am working with this example:
http://mleibman.github.com/SlickGrid/examples/example-checkbox-row-select.html

Looking inside checkboxselectolumn.js I can see a selectedRows  variable but this is empty to me it seems.

Any tips?

答:
bit of oo magic

grid.getSelectedRows();

Body:
bit of oo magic

grid.getSelectedRows();


问:
UISearchController searchBar disappears on first click
I have implemented a UISearchController in a TableView, pushed by a Navigation Controller.

First my problem was that whenever I click on the SearchBar, it disappears. It works when I enter some text, but it stays completely blank. Then I managed to semi solve the issue using this code:

```<code>- (void)searchForText:(NSString*)searchText
{
    [self.view addSubview:villeSearchController.searchBar];
}
</code>```

Which semi-works because now, when I click on the search bar, it blanks out, but if I enter one character, it appears again, and then it stays there, no matter what. Until I cancel the search, and click on it again, in that case it blanks out.
I have made some tests and this method (searchForText) is called on the very first click, so that isn't the reason.

Does anyone know how I can solve this issue and make the searchbar appear from the very first click?

EDIT:

This is how I initialize the SearchController:

```<code>villeSearchController = [[UISearchController alloc]   initWithSearchResultsController:nil];
villeSearchController.searchResultsUpdater = self;
villeSearchController.dimsBackgroundDuringPresentation = NO;
villeSearchController.searchBar.delegate = self;
villeTableView.tableHeaderView = villeSearchController.searchBar;
villeSearchController.searchBar.scopeButtonTitles = @[];
self.definesPresentationContext = YES;
[villeSearchController.searchBar sizeToFit];
</code>```

答:
If you run into this problem in iOS11 (and especially if it worked pre iOS11), I had to change my UISearchController to be attached to the navigationItem rather than the tableView.

After setting parameters on my searchController, I used to do this:

```<code>tableView.tableHeaderView = searchController.searchBar
</code>```

Now I have this:

```<code>navigationItem.searchController = searchController
</code>```

The "translucent" fix would allow the controller to appear, but when I would try and unwind to a specific segue, I'd get a crash. Attaching the searchController to the navigationItem fixed both the display and the crash.

Body:
I have implemented a UISearchController in a TableView, pushed by a Navigation Controller.

First my problem was that whenever I click on the SearchBar, it disappears. It works when I enter some text, but it stays completely blank. Then I managed to semi solve the issue using this code:

- (void)searchForText:(NSString*)searchText
{
    [self.view addSubview:villeSearchController.searchBar];
}

Which semi-works because now, when I click on the search bar, it blanks out, but if I enter one character, it appears again, and then it stays there, no matter what. Until I cancel the search, and click on it again, in that case it blanks out.
I have made some tests and this method (searchForText) is called on the very first click, so that isn't the reason.

Does anyone know how I can solve this issue and make the searchbar appear from the very first click?

EDIT:

This is how I initialize the SearchController:

villeSearchController = [[UISearchController alloc]   initWithSearchResultsController:nil];
villeSearchController.searchResultsUpdater = self;
villeSearchController.dimsBackgroundDuringPresentation = NO;
villeSearchController.searchBar.delegate = self;
villeTableView.tableHeaderView = villeSearchController.searchBar;
villeSearchController.searchBar.scopeButtonTitles = @[];
self.definesPresentationContext = YES;
[villeSearchController.searchBar sizeToFit];

Body:
If you run into this problem in iOS11 (and especially if it worked pre iOS11), I had to change my UISearchController to be attached to the navigationItem rather than the tableView.

After setting parameters on my searchController, I used to do this:

tableView.tableHeaderView = searchController.searchBar

Now I have this:

navigationItem.searchController = searchController

The "translucent" fix would allow the controller to appear, but when I would try and unwind to a specific segue, I'd get a crash. Attaching the searchController to the navigationItem fixed both the display and the crash.


问:
Enter entity property from the inversed side in one to one relation
Let's assume i have an one-to-one relation with one entity person

```<code>class Person
{
...
    /**
     * @var Player
     * @ORM\OneToOne(targetEntity="AppBundle\Entity\Player", inversedBy="person")
     */
    private $player;
...
}
</code>```

and one entity Player

```<code>class Player
{
...
    /**
    * @var Person
    * @ORM\OneToOne(targetEntity="AppBundle\Entity\Person", mappedBy="player")
    */
    private $person;
...
}
</code>```

Now the person side is holding the foreign key for the person.

Every try to access something from the inversed side is failing, for example

```<code>$em->getRepository('AppBundle:Player')->findByPerson();
</code>```

ends up in

[Doctrine\ORM\ORMException]

  You cannot search for the association field
  'AppBundle\Entity\Player#person', because it is the inverse side of
  an association. Find methods only work on owning side associations.

Doing the same to the owning side (find player for the person), everything is fine.

I cant figure out: How can i access entities from both sides?

I need that, because i need to know, which player hasn't already persons assigned and vice versa. I thought, doctrine is loading the related entities ... for this case plain sql seems the easier solution for that? Or have i really to deal with dql and joins?

答:
In your class Player, can you try with this :

```<code>class Player
{
...
    /**
    * @var Person
    * @ORM\OneToOne(targetEntity="AppBundle\Entity\Person", mappedBy="player")
    * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
    */
    private $person;
...
}
</code>```

Here is the doctrine doc: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-one-bidirectional

Body:
Let's assume i have an one-to-one relation with one entity person

class Person
{
...
    /**
     * @var Player
     * @ORM\OneToOne(targetEntity="AppBundle\Entity\Player", inversedBy="person")
     */
    private $player;
...
}

and one entity Player

class Player
{
...
    /**
    * @var Person
    * @ORM\OneToOne(targetEntity="AppBundle\Entity\Person", mappedBy="player")
    */
    private $person;
...
}

Now the person side is holding the foreign key for the person.

Every try to access something from the inversed side is failing, for example

$em->getRepository('AppBundle:Player')->findByPerson();

ends up in

[Doctrine\ORM\ORMException]

  You cannot search for the association field
  'AppBundle\Entity\Player#person', because it is the inverse side of
  an association. Find methods only work on owning side associations.

Doing the same to the owning side (find player for the person), everything is fine.

I cant figure out: How can i access entities from both sides?

I need that, because i need to know, which player hasn't already persons assigned and vice versa. I thought, doctrine is loading the related entities ... for this case plain sql seems the easier solution for that? Or have i really to deal with dql and joins?

Body:
In your class Player, can you try with this :

class Player
{
...
    /**
    * @var Person
    * @ORM\OneToOne(targetEntity="AppBundle\Entity\Person", mappedBy="player")
    * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
    */
    private $person;
...
}

Here is the doctrine doc: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-one-bidirectional


问:
How to parse SOAP response in ColdFusion

Put very simply, how do I go about retrieving the data?  I want an array that I can loop over to display this data.  This is what I've been trying, without success:

```<code><cfset apicall = XMLParse(httpResponse.filecontent)>
<cfset certArray = xmlSearch(apiCall,"//BNEHFTPOfficerRosterSvcResponse/BNEHFTPOfficerRosterSvcResult/BNEHFTPOfficerRosterSvcResponse")>
</code>```

That second line in particular, or any variation thereof, returns an empty array.  What am I doing wrong?

Thanks.

After modifying my code per the suggestion:

```<code><cfset cols = xmlSearch(apiCall,"//*[local-name()='BNEHFTPOfficerRosterSvcResponse']")[1].XmlChildren>
</code>```

If I dump that, I get the second image.

Now I'm trying to get closer to having the array of data I need.  I've tried adding another .XmlChildren to it but that throws an error.  This is confusing! :)

答:
Since your XPath seaerch above is based from the root of the XML object, which is currently soap:Envelope, you need to either recurse in to your XML object to the soap:Body before running your XPath query

var soapBody = apiCall[ "soap:Envelope" ][ "soap:Body" ];

Then you can perform you Xpath search above.

Alternately you can use a more open XPath search string, which will perform the recursion for you:

```<code>xmlSearch(apicall,"//*[local-name()='BNEHFTPOfficerRosterSvcResponse']")
</code>```

Body:
Put very simply, how do I go about retrieving the data?  I want an array that I can loop over to display this data.  This is what I've been trying, without success:

<cfset apicall = XMLParse(httpResponse.filecontent)>
<cfset certArray = xmlSearch(apiCall,"//BNEHFTPOfficerRosterSvcResponse/BNEHFTPOfficerRosterSvcResult/BNEHFTPOfficerRosterSvcResponse")>

That second line in particular, or any variation thereof, returns an empty array.  What am I doing wrong?

Thanks.

After modifying my code per the suggestion:

<cfset cols = xmlSearch(apiCall,"//*[local-name()='BNEHFTPOfficerRosterSvcResponse']")[1].XmlChildren>

If I dump that, I get the second image.

Now I'm trying to get closer to having the array of data I need.  I've tried adding another .XmlChildren to it but that throws an error.  This is confusing! :)

Body:
Since your XPath seaerch above is based from the root of the XML object, which is currently soap:Envelope, you need to either recurse in to your XML object to the soap:Body before running your XPath query

var soapBody = apiCall[ "soap:Envelope" ][ "soap:Body" ];

Then you can perform you Xpath search above.

Alternately you can use a more open XPath search string, which will perform the recursion for you:

xmlSearch(apicall,"//*[local-name()='BNEHFTPOfficerRosterSvcResponse']")


问:
I want to search specific observations in a data frame and record them in an empty matrix. But, the code in not working.
```<code>search <- function(x,max_hp){
  count <- 1
  result <- matrix(NA, nrow =nrow(x), ncol = ncol(x), byrow = TRUE)
  for(i in 1:nrow(x)){
    temp_row <- x[i,]
    if(temp_row[4] < max_hp){
      result[count,] <- temp_row
      count <- count + 1
    }
  }
  return(result)
}

> search(mtcars,240)
Error in result[count, ] <- temp_row :
  incorrect number of subscripts on matrix
</code>```

<p>#I want the search function to return all observations in mtcars that      #have an horsepower less than 240 and record it in a new matrix.</p>

答:
To return a dataframe the same size as mtcars filled with NA,

```<code>newmt <- mtcars
newmt[newmt$hp>=240, ]  <-  NA
</code>```

If you really need a matrix, use as.matrix on the result.

Body:
search <- function(x,max_hp){
  count <- 1
  result <- matrix(NA, nrow =nrow(x), ncol = ncol(x), byrow = TRUE)
  for(i in 1:nrow(x)){
    temp_row <- x[i,]
    if(temp_row[4] < max_hp){
      result[count,] <- temp_row
      count <- count + 1
    }
  }
  return(result)
}

> search(mtcars,240)
Error in result[count, ] <- temp_row :
  incorrect number of subscripts on matrix

#I want the search function to return all observations in mtcars that      #have an horsepower less than 240 and record it in a new matrix.

Body:
To return a dataframe the same size as mtcars filled with NA,

newmt <- mtcars
newmt[newmt$hp>=240, ]  <-  NA

If you really need a matrix, use as.matrix on the result.


问:
Access VBA Pop Up Sub Form for Submission of Entries
Here's what I've got:
I have an Access form that accepts entries, and places them into a table when the ENTER button is clicked.  At the moment, I have a popup message box that comes up when the button is clicked, asking them to confirm that their entries are ok (your standard pop up box, with OK and CANCEL options).  This popup box comes up right in the middle of the data that the user has entered, and is pretty inconvenient for the user to deal with.

Instead of this popup message box, I came up with the idea of using a pop-up SUB-FORM, that would lie invisible just under the ENTER button, and would come up visible when ENTER is clicked. (Same options as the message box, etc, just different placement.  Making the "physical" subform design was a no brainer).  Since this is a new form/subform, how would I code this in order to make it work like the message box did?  The old code won't work.  This is the best idea I could come up with.  If there's an even better way to accomplish this, I'm open to suggestions...

答:
Try this function found in:

http://www.excely.com/excel-vba/define-a-position-of-messagebox.shtml

```<code>Option Explicit

' Import
Private Declare Function UnhookWindowsHookEx Lib "user32" _
    (ByVal hHook As Long) As Long

Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long

Private Declare Function SetWindowsHookEx Lib "user32" _
    Alias "SetWindowsHookExA" _
    (ByVal idHook As Long, _
     ByVal lpfn As Long, _
     ByVal hmod As Long, _
     ByVal dwThreadId As Long) As Long

Private Declare Function SetWindowPos Lib "user32" _
    (ByVal hwnd As Long, _
     ByVal hWndInsertAfter As Long, _
     ByVal x As Long, _
     ByVal y As Long, _
     ByVal cx As Long, _
     ByVal cy As Long, _
     ByVal wFlags As Long) As Long

' Handle to the Hook procedure
Private hHook As Long

' Position
Private msgbox_x As Long
Private msgbox_y As Long

' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5

' SetWindowPos Flags
Private Const SWP_NOSIZE = &H1      ' Retains the current size
Private Const SWP_NOZORDER = &H4    ' Retains the current Z order

Sub TestMsgBox()
    MsgBoxPos "Set non-Center Position", _
              vbOKOnly, _
              "Message Box Hooking", _
              400, 300
End Sub

Public Sub MsgBoxPos(strPromt As String, _
              vbButtons As VbMsgBoxStyle, _
              strTitle As String, _
              xPos As Long, _
              yPos As Long)

    ' Store position
    msgbox_x = xPos
    msgbox_y = yPos

    ' Set Hook
    hHook = SetWindowsHookEx(WH_CBT, _
                              AddressOf MsgBoxHookProc, _
                              0, _
                              GetCurrentThreadId)

    ' Run MessageBox
    MsgBox strPromt, vbButtons, strTitle
End Sub

Private Function MsgBoxHookProc(ByVal lMsg As Long, _
                                ByVal wParam As Long, _
                                ByVal lParam As Long) As Long
    If lMsg = HCBT_ACTIVATE Then
        ' Change position
        SetWindowPos wParam, 0, msgbox_x, msgbox_y, _
                     0, 0, SWP_NOSIZE + SWP_NOZORDER

        ' Release the Hook
        UnhookWindowsHookEx hHook
    End If

    MsgBoxHookProc = False
End Function
</code>```

Body:
Try this function found in:

http://www.excely.com/excel-vba/define-a-position-of-messagebox.shtml

Option Explicit

' Import
Private Declare Function UnhookWindowsHookEx Lib "user32" _
    (ByVal hHook As Long) As Long

Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long

Private Declare Function SetWindowsHookEx Lib "user32" _
    Alias "SetWindowsHookExA" _
    (ByVal idHook As Long, _
     ByVal lpfn As Long, _
     ByVal hmod As Long, _
     ByVal dwThreadId As Long) As Long

Private Declare Function SetWindowPos Lib "user32" _
    (ByVal hwnd As Long, _
     ByVal hWndInsertAfter As Long, _
     ByVal x As Long, _
     ByVal y As Long, _
     ByVal cx As Long, _
     ByVal cy As Long, _
     ByVal wFlags As Long) As Long

' Handle to the Hook procedure
Private hHook As Long

' Position
Private msgbox_x As Long
Private msgbox_y As Long

' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5

' SetWindowPos Flags
Private Const SWP_NOSIZE = &H1      ' Retains the current size
Private Const SWP_NOZORDER = &H4    ' Retains the current Z order

Sub TestMsgBox()
    MsgBoxPos "Set non-Center Position", _
              vbOKOnly, _
              "Message Box Hooking", _
              400, 300
End Sub

Public Sub MsgBoxPos(strPromt As String, _
              vbButtons As VbMsgBoxStyle, _
              strTitle As String, _
              xPos As Long, _
              yPos As Long)

    ' Store position
    msgbox_x = xPos
    msgbox_y = yPos

    ' Set Hook
    hHook = SetWindowsHookEx(WH_CBT, _
                              AddressOf MsgBoxHookProc, _
                              0, _
                              GetCurrentThreadId)

    ' Run MessageBox
    MsgBox strPromt, vbButtons, strTitle
End Sub

Private Function MsgBoxHookProc(ByVal lMsg As Long, _
                                ByVal wParam As Long, _
                                ByVal lParam As Long) As Long
    If lMsg = HCBT_ACTIVATE Then
        ' Change position
        SetWindowPos wParam, 0, msgbox_x, msgbox_y, _
                     0, 0, SWP_NOSIZE + SWP_NOZORDER

        ' Release the Hook
        UnhookWindowsHookEx hHook
    End If

    MsgBoxHookProc = False
End Function


问:
bidirectional belongs_to (one polymorphic)
I have two kinds of classes, one of which belongs_to the other kind, and one of which polymorphically belongs to the other kind.

```<code>class Term < ActiveRecord::Base
  belongs_to :reference, :polymorphic => true
end

class Course < ActiveRecord::Base
  belongs_to :term
end

class Career < ActiveRecord::Base
  belongs_to :term
end
</code>```

The relationships are belongs_to because I want fast access in both directions.  I'm under the impression that the has_one relationship would be slower because you would have to query the opposite table to search for a matching _id.

Right now, when I create a course c, I run an after_save method which creates a term t such that c.term = t and t.reference = c.  This seems like kind of a hack though... is there any way to automatically tell rails that this relationship exists and that setting c.term = t should automatically make t.reference = c?

I know that with polymorphic associations you can specify the :as attribute (see the API), but it looks like this doesn't work for belongs_to.

```<code>  class Asset < ActiveRecord::Base
    belongs_to :attachable, :polymorphic => true

    def attachable_type=(sType)
       super(sType.to_s.classify.constantize.base_class.to_s)
    end
  end

  class Post < ActiveRecord::Base
    # because we store "Post" in attachable_type now :dependent => :destroy will work
    has_many :assets, :as => :attachable, :dependent => :destroy
  end
</code>```

答:
Yeah, you're not really meant to do bi-directional belongs_to associations. As such, when you add polymorphicality (is that really a word?) into the equation, it will break.

The relationships are belongs_to because I want fast access in both directions. I'm under the impression that the has_one relationship would be slower because you would have to query the opposite table to search for a matching _id.

I don't see why you'd want to do this. If you're really concerned with speed, you can simply index the foreign_key column(s) on the table that belongs_to. The speed difference should be negligible.

Body:
I have two kinds of classes, one of which belongs_to the other kind, and one of which polymorphically belongs to the other kind.

class Term < ActiveRecord::Base
  belongs_to :reference, :polymorphic => true
end

class Course < ActiveRecord::Base
  belongs_to :term
end

class Career < ActiveRecord::Base
  belongs_to :term
end

The relationships are belongs_to because I want fast access in both directions.  I'm under the impression that the has_one relationship would be slower because you would have to query the opposite table to search for a matching _id.

Right now, when I create a course c, I run an after_save method which creates a term t such that c.term = t and t.reference = c.  This seems like kind of a hack though... is there any way to automatically tell rails that this relationship exists and that setting c.term = t should automatically make t.reference = c?

I know that with polymorphic associations you can specify the :as attribute (see the API), but it looks like this doesn't work for belongs_to.

  class Asset < ActiveRecord::Base
    belongs_to :attachable, :polymorphic => true

    def attachable_type=(sType)
       super(sType.to_s.classify.constantize.base_class.to_s)
    end
  end

  class Post < ActiveRecord::Base
    # because we store "Post" in attachable_type now :dependent => :destroy will work
    has_many :assets, :as => :attachable, :dependent => :destroy
  end


问:
Undefined properties in Angular expression binding
I have a binding {{getCategoryName(post.categories[0])['name']}} where I need to process the value post.categories[0] returned in the *ngFor loop with a method getCategoryByName() in my component before finally binding it to the template.The method returns an  Object.

I keep getting the error Cannot read property 'name' of undefined . I have tried getting the property using the ['name'] key instead of .name but still get the error.

Any thoughts for a workaround?

```<code>  <ion-item text-wrap class="news-item" *ngFor="let post of posts" (click)="viewStory(post)">
          <div >
          <p>{{getCategoryName(post.categories[0])['name']}}</p>
          <h2>{{post.title.rendered}}</h2>
          <p>By Fitz · {{post.date | fromNow}}</p>
        </div>
    </ion-item>
</code>```

The method

```<code>  getCategoryName(categoryId) {
    return this.categories[this.categories.findIndex((el)=>{ return el.id == categoryId})];
  }
</code>```

Example ember of the Array from which the Object is returned by method above

```<code>[
  {
    "id": 33,
    "count": 1,
    "description": "",
    "link": "http://XXXXXXXXXXXXX.co/category/apps/",
    "name": "Apps",
    "slug": "apps",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
      "self": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/categories/33"
        }
      ],
      "collection": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/categories"
        }
      ],
      "about": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/taxonomies/category"
        }
      ],
      "wp:post_type": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/posts?categories=33"
        },
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/jobs?categories=33"
        }
      ],
      "curies": [
        {
          "name": "wp",
          "href": "https://api.w.org/{rel}",
          "templated": true
        }
      ]
    }
  },

]
</code>```

答:
In your getCategoryName method check if post.categories is undefined, and then return object {name : ''}:

```<code>if (post.categories === undefiend) {
return {name : ''}
}
</code>```

or you could use in template:

```<code>{{(getCategoryName(post.categories[0]) || {name : ''})['name']}}
</code>```

Body:
I have a binding {{getCategoryName(post.categories[0])['name']}} where I need to process the value post.categories[0] returned in the *ngFor loop with a method getCategoryByName() in my component before finally binding it to the template.The method returns an  Object.

I keep getting the error Cannot read property 'name' of undefined . I have tried getting the property using the ['name'] key instead of .name but still get the error.

Any thoughts for a workaround?

  <ion-item text-wrap class="news-item" *ngFor="let post of posts" (click)="viewStory(post)">

{{getCategoryName(post.categories[0])['name']}}

{{post.title.rendered}}

By Fitz · {{post.date | fromNow}}

    </ion-item>

The method

  getCategoryName(categoryId) {
    return this.categories[this.categories.findIndex((el)=>{ return el.id == categoryId})];
  }

Example ember of the Array from which the Object is returned by method above

[
  {
    "id": 33,
    "count": 1,
    "description": "",
    "link": "http://XXXXXXXXXXXXX.co/category/apps/",
    "name": "Apps",
    "slug": "apps",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
      "self": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/categories/33"
        }
      ],
      "collection": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/categories"
        }
      ],
      "about": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/taxonomies/category"
        }
      ],
      "wp:post_type": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/posts?categories=33"
        },
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/jobs?categories=33"
        }
      ],
      "curies": [
        {
          "name": "wp",
          "href": "https://api.w.org/{rel}",
          "templated": true
        }
      ]
    }
  },

]

Body:
In your getCategoryName method check if post.categories is undefined, and then return object {name : ''}:

if (post.categories === undefiend) {
return {name : ''}
}

or you could use in template:

{{(getCategoryName(post.categories[0]) || {name : ''})['name']}}


问:
Where to store data files in WinStore app (win32 Project Centennial)
I am porting my native Win32 app to Windows 10 Store with Desktop App Convertor.

What is the most recommended place to store local data files,  it seems %APPDATA% works, but is it most recommended place for user data in Win10 Store Apps?

Is this %appdata% virtualized and cleaned automatically  if user uninstall app from Win Store?

答: %LOCALAPPDATA% is new requirement to be compatible with store</p>