问:
How to link to a collapsed hidden tabindex element with #
I am working on a glossary and have made a bulky file with terms in columns behind which are hidden texts (with display:none), in plain css/html.

Each entry looks like this in code:
Achidrupa
Here follows hidden explanation.

Instead of :hover I use :focus so the explanation is kept opened up in a sort of popup window, without use of Java or JS.
As there are entries with slightly different spelling I like to refer to the main entry, but not with the rather clumsy ‘‘See entry blah blah blah’’.

So, I like to make internal links, as we are used to with # and name or id in the linked-to element. But whatever I try, I cannot get another entry opened from the opened window with the link. Can I get some help with that? Very grateful for any solution.

I believe I did not make this issue clear enough from the start. I have the following code, including tabindex=0 and with .w:focus .tt{display: inline-block ; cursor:pointer; } in css.

1ste Entry Alpha

    Follows text as explanation on alpha which becomes visible after a click on Entry Alpha, otherwise it stays hidden with css display:none. [Probably about or 100 words here.]

 2nd Entry on beta

    Follows text as explanation on beta which link to entry alpha  after a click. [Probably about or 100 words here.]

What I need is the possibility to open window 1st Entry Alpha when I click in opened window Entry on beta and click on ‘link to entry alpha’.

I am sorry but the delivered javascript code and snippet didn’t work. It would not open any focused element. By the way, the glossary works great in this way, except for the internal linking.

答:
Here is a solution using javascript: get the hash, find element with corresponding name and focus it. The whole thing is wrapped in onload otherwise the browser wont focus the element.

window.onload = function () {
  var hash = window.location.hash.substr(1);
  if (hash) {
      var target = document.getElementsByName(hash)[0].focus()
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.w {
  display: block;
  color: black;
  text-decoration: none;
}
.w > div {
  display: none;
}
.w:focus {
  outline: none;
}
.w:focus > div {
  display: block;
}</code>```

name="q1" href="#q1" class="w">
  Question ?

mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad

name="q2" href="#q2" class="w">
  Question ?

mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad

name="q3" href="#q3" class="w">
  Question ?

mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad

```

Body:
Here is a solution using javascript: get the hash, find element with corresponding name and focus it. The whole thing is wrapped in onload otherwise the browser wont focus the element.

window.onload = function () {
  var hash = window.location.hash.substr(1);
  if (hash) {
      var target = document.getElementsByName(hash)[0].focus()
  }
}

.w {
  display: block;
  color: black;
  text-decoration: none;
}
.w > div {
  display: none;
}
.w:focus {
  outline: none;
}
.w:focus > div {
  display: block;
}

<a name="q1" href="#q1" class="w">
  Question ?
  <div>mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad</div>
</div>
<a name="q2" href="#q2" class="w">
  Question ?
  <div>mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad</div>
</div>
<a name="q3" href="#q3" class="w">
  Question ?
  <div>mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad</div>
</div>


来源: stackexchange

问:
Error when I use my val in function, but not when I access val on its own in REPL.
I am writing Scala code to search a QuadTree. I'm fairly new to Scala, so this may be a simple question: Why do I get a error: value rec not a member of QuadTree when I try to use tree.rec in a function, BUT if I ask the REPL to evaluate tree.rec, it successfully returns the data?

Anyway, I've got these classes to start with:

```<code>case class Rectangle (minx: Int, maxx: Int, miny: Int, maxy: Int)

abstract class QuadTree
case class Node (value : Int, nw : QuadTree, ne: QuadTree, sw: QuadTree, se: QuadTree, rec: Rectangle) extends QuadTree
case class Leaf (value : Int, rec: Rectangle) extends QuadTree
case class Empty (value: Int, rec: Rectangle) extends QuadTree
</code>```

So I'm defining a Rectangle, and then a QuadTree, which can has a value, and either contains a Node, a Leaf, or Empty.

Next I have a function that checks to see if two rectangles overlap called rectangles_Overlap, which returns True if two input Rectangles overlap, and returns False if there is no overlap.

If I define

```<code>val query = Rectangle(1, 8, 8, 16)
val tree1 = Node(13,Node(12,Leaf(7,Rectangle(1,4,12,16)),Leaf(3,Rectangle(4,8,12,16)),Leaf(2,Rectangle(1,4,8,12)),Empty(0,Rectangle(4,8,8,12)),Rectangle(1,8,8,16)),Empty(0,Rectangle(8,16,8,16)),Empty(0,Rectangle(1,8,1,8)),Leaf(1,Rectangle(8,16,1,8)),Rectangle(1,16,1,16))
</code>```

If I want to get the size of the tree, I can type into the REPL

```<code>scala> tree1.rec
res0: Rectangle = Rectangle(1,16,1,16)
</code>```

I can also use my rectangles_Overlap method to see if the query Rectangle overlaps with the tree Rectangle.

```<code>scala> rectangles_Overlap(query, tree1.rec)
res1: Boolean = true
</code>```

But if I try to use rectangles_Overlap(query, tree1.rec) in another function, its unhappy!

```<code>def queryBoolean(query: Rectangle, tree: QuadTree): Boolean = {
    if(rectangles_Overlap(query, tree.rec)) {
        println("Yay they overlap so I can do other stuff...")
        // I want to add other code here after I get this working
        true
    } else {
        println("Nah, they don't overlap, don't need to do anything")
        false
    }
}
</code>```

And then call the function with queryBoolean(query, tree1), I get this error:

```<code><console>:17: error: value rec is not a member of QuadTree
       if (rectangles_Overlap(query, tree.rec)) {
</code>```

So my question again is: Why can I evaluate tree1.rec in the REPL, but cannot use tree.rec in a function without an error?

My original thought was that perhaps I was overloading something... but rec is always a Rectangle in all of the case clase ... extends QuadTree. So I don't believe I am overloading anything?

答:
That is true. rec i.e. type of Rectangle, is not a member of QuadTree. If you change from QuadTree to Node, it will work. Otherwise it must be there in QuadTree too.

```<code>def queryBoolean(query: Rectangle, tree: Node): Boolean
</code>```

Add to QuadTree as val (val is needed to access it), and then you need to override and call super constructor as below:

```<code>  abstract class QuadTree(val rec: Rectangle)
  case class Node (value : Int, nw : QuadTree, ne: QuadTree, sw: QuadTree, se: QuadTree, override val rec: Rectangle) extends QuadTree(rec)
  case class Leaf (value : Int, override val rec: Rectangle) extends QuadTree(rec)
  case class Empty (value: Int, override val rec: Rectangle) extends QuadTree(rec)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing Scala code to search a QuadTree. I'm fairly new to Scala, so this may be a simple question: Why do I get a error: value rec not a member of QuadTree when I try to use tree.rec in a function, BUT if I ask the REPL to evaluate tree.rec, it successfully returns the data?

Anyway, I've got these classes to start with:

case class Rectangle (minx: Int, maxx: Int, miny: Int, maxy: Int)

abstract class QuadTree
case class Node (value : Int, nw : QuadTree, ne: QuadTree, sw: QuadTree, se: QuadTree, rec: Rectangle) extends QuadTree
case class Leaf (value : Int, rec: Rectangle) extends QuadTree
case class Empty (value: Int, rec: Rectangle) extends QuadTree

So I'm defining a Rectangle, and then a QuadTree, which can has a value, and either contains a Node, a Leaf, or Empty.

Next I have a function that checks to see if two rectangles overlap called rectangles_Overlap, which returns True if two input Rectangles overlap, and returns False if there is no overlap.

If I define

val query = Rectangle(1, 8, 8, 16)
val tree1 = Node(13,Node(12,Leaf(7,Rectangle(1,4,12,16)),Leaf(3,Rectangle(4,8,12,16)),Leaf(2,Rectangle(1,4,8,12)),Empty(0,Rectangle(4,8,8,12)),Rectangle(1,8,8,16)),Empty(0,Rectangle(8,16,8,16)),Empty(0,Rectangle(1,8,1,8)),Leaf(1,Rectangle(8,16,1,8)),Rectangle(1,16,1,16))

If I want to get the size of the tree, I can type into the REPL

scala> tree1.rec
res0: Rectangle = Rectangle(1,16,1,16)

I can also use my rectangles_Overlap method to see if the query Rectangle overlaps with the tree Rectangle.

scala> rectangles_Overlap(query, tree1.rec)
res1: Boolean = true

But if I try to use rectangles_Overlap(query, tree1.rec) in another function, its unhappy!

def queryBoolean(query: Rectangle, tree: QuadTree): Boolean = {
    if(rectangles_Overlap(query, tree.rec)) {
        println("Yay they overlap so I can do other stuff...")
        // I want to add other code here after I get this working
        true
    } else {
        println("Nah, they don't overlap, don't need to do anything")
        false
    }
}

And then call the function with queryBoolean(query, tree1), I get this error:

<console>:17: error: value rec is not a member of QuadTree
       if (rectangles_Overlap(query, tree.rec)) {

So my question again is: Why can I evaluate tree1.rec in the REPL, but cannot use tree.rec in a function without an error?

My original thought was that perhaps I was overloading something... but rec is always a Rectangle in all of the case clase ... extends QuadTree. So I don't believe I am overloading anything?

Body:
That is true. rec i.e. type of Rectangle, is not a member of QuadTree. If you change from QuadTree to Node, it will work. Otherwise it must be there in QuadTree too.

def queryBoolean(query: Rectangle, tree: Node): Boolean

Add to QuadTree as val (val is needed to access it), and then you need to override and call super constructor as below:

  abstract class QuadTree(val rec: Rectangle)
  case class Node (value : Int, nw : QuadTree, ne: QuadTree, sw: QuadTree, se: QuadTree, override val rec: Rectangle) extends QuadTree(rec)
  case class Leaf (value : Int, override val rec: Rectangle) extends QuadTree(rec)
  case class Empty (value: Int, override val rec: Rectangle) extends QuadTree(rec)


问:
ClassNotFoundException: org.grails.compiler.web.converters.RenderConverterTrait
I've converted a project from Grails 1.3.7 to 3.2.6.  I've worked through all of the errors that come out of grails compile as well as a ton of problems highlighted by IntelliJ.  Now, I'm trying to actually launch the app to see what I get, and I'm getting the error in the subject.

Here's the full stack/error:

```    2017-06-02 07:45:16.650 ERROR --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception

    java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@70e659aa: startup date [Fri Jun 02 07:45:09 EDT 2017]; root of context hierarchy
        at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404)
        at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97)
        at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968)
        at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:555)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:372)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:388)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:375)
        at grails.boot.GrailsApp$run.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
        at tbuilder326.Application.main(Application.groovy:8)

    2017-06-02 07:45:16.661 ERROR --- [           main] o.s.boot.SpringApplication               : Application startup failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grailsApplicationPostProcessor' defined in tbuilder326.Application: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [grails.boot.config.GrailsApplicationPostProcessor]: Factory method 'grailsApplicationPostProcessor' threw exception; nested exception is grails.plugins.exceptions.PluginException: Failed to initialize class [grails.plugin.springsecurity.LoginController] from plugin [springSecurityCore] : org/grails/compiler/web/converters/RenderConverterTrait
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:524)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:372)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:388)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:375)
        at grails.boot.GrailsApp$run.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
        at tbuilder326.Application.main(Application.groovy:8)
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [grails.boot.config.GrailsApplicationPostProcessor]: Factory method 'grailsApplicationPostProcessor' threw exception; nested exception is grails.plugins.exceptions.PluginException: Failed to initialize class [grails.plugin.springsecurity.LoginController] from plugin [springSecurityCore] : org/grails/compiler/web/converters/RenderConverterTrait
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 23 common frames omitted
    Caused by: grails.plugins.exceptions.PluginException: Failed to initialize class [grails.plugin.springsecurity.LoginController] from plugin [springSecurityCore] : org/grails/compiler/web/converters/RenderConverterTrait
        at org.grails.plugins.BinaryGrailsPlugin.initializeProvidedArtefacts(BinaryGrailsPlugin.java:175)
        at org.grails.plugins.BinaryGrailsPlugin.(BinaryGrailsPlugin.java:104)
        at grails.plugins.DefaultGrailsPluginManager.createBinaryGrailsPlugin(DefaultGrailsPluginManager.java:375)
        at grails.plugins.DefaultGrailsPluginManager.findCorePlugins(DefaultGrailsPluginManager.java:362)
        at grails.plugins.DefaultGrailsPluginManager.attemptLoadPlugins(DefaultGrailsPluginManager.java:314)
        at grails.plugins.DefaultGrailsPluginManager.loadPlugins(DefaultGrailsPluginManager.java:224)
        at grails.boot.config.GrailsApplicationPostProcessor.initializeGrailsApplication(GrailsApplicationPostProcessor.groovy:89)
        at grails.boot.config.GrailsApplicationPostProcessor.setApplicationContext(GrailsApplicationPostProcessor.groovy:225)
        at grails.boot.config.GrailsApplicationPostProcessor.(GrailsApplicationPostProcessor.groovy:77)
        at grails.boot.config.GrailsAutoConfiguration.grailsApplicationPostProcessor(GrailsAutoConfiguration.groovy:69)
        at tbuilder326.Application.grailsApplicationPostProcessor(Application.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1426)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 24 common frames omitted
    Caused by: java.lang.NoClassDefFoundError: org/grails/compiler/web/converters/RenderConverterTrait
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
        at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:677)
        at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:787)
        at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:775)
        at org.grails.plugins.BinaryGrailsPlugin.initializeProvidedArtefacts(BinaryGrailsPlugin.java:173)
        ... 40 common frames omitted
    Caused by: java.lang.ClassNotFoundException: org.grails.compiler.web.converters.RenderConverterTrait
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 56 common frames omitted```

Can anyone suggest what I might be missing?  Some sort of compile or runtime dependency?

答: I had the same problem, and I switched to spring-security-core 3.1.2 and it was solved.</p>

Body:
I've converted a project from Grails 1.3.7 to 3.2.6.  I've worked through all of the errors that come out of grails compile as well as a ton of problems highlighted by IntelliJ.  Now, I'm trying to actually launch the app to see what I get, and I'm getting the error in the subject.

Here's the full stack/error:

    2017-06-02 07:45:16.650 ERROR --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception

    java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@70e659aa: startup date [Fri Jun 02 07:45:09 EDT 2017]; root of context hierarchy
        at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404)
        at org.springframework.context.support.ApplicationListenerDetector.postProcessBeforeDestruction(ApplicationListenerDetector.java:97)
        at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:253)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968)
        at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:555)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:372)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:388)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:375)
        at grails.boot.GrailsApp$run.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
        at tbuilder326.Application.main(Application.groovy:8)

    2017-06-02 07:45:16.661 ERROR --- [           main] o.s.boot.SpringApplication               : Application startup failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grailsApplicationPostProcessor' defined in tbuilder326.Application: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [grails.boot.config.GrailsApplicationPostProcessor]: Factory method 'grailsApplicationPostProcessor' threw exception; nested exception is grails.plugins.exceptions.PluginException: Failed to initialize class [grails.plugin.springsecurity.LoginController] from plugin [springSecurityCore] : org/grails/compiler/web/converters/RenderConverterTrait
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:115)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:524)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:372)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:388)
        at grails.boot.GrailsApp.run(GrailsApp.groovy:375)
        at grails.boot.GrailsApp$run.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
        at tbuilder326.Application.main(Application.groovy:8)
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [grails.boot.config.GrailsApplicationPostProcessor]: Factory method 'grailsApplicationPostProcessor' threw exception; nested exception is grails.plugins.exceptions.PluginException: Failed to initialize class [grails.plugin.springsecurity.LoginController] from plugin [springSecurityCore] : org/grails/compiler/web/converters/RenderConverterTrait
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 23 common frames omitted
    Caused by: grails.plugins.exceptions.PluginException: Failed to initialize class [grails.plugin.springsecurity.LoginController] from plugin [springSecurityCore] : org/grails/compiler/web/converters/RenderConverterTrait
        at org.grails.plugins.BinaryGrailsPlugin.initializeProvidedArtefacts(BinaryGrailsPlugin.java:175)
        at org.grails.plugins.BinaryGrailsPlugin.(BinaryGrailsPlugin.java:104)
        at grails.plugins.DefaultGrailsPluginManager.createBinaryGrailsPlugin(DefaultGrailsPluginManager.java:375)
        at grails.plugins.DefaultGrailsPluginManager.findCorePlugins(DefaultGrailsPluginManager.java:362)
        at grails.plugins.DefaultGrailsPluginManager.attemptLoadPlugins(DefaultGrailsPluginManager.java:314)
        at grails.plugins.DefaultGrailsPluginManager.loadPlugins(DefaultGrailsPluginManager.java:224)
        at grails.boot.config.GrailsApplicationPostProcessor.initializeGrailsApplication(GrailsApplicationPostProcessor.groovy:89)
        at grails.boot.config.GrailsApplicationPostProcessor.setApplicationContext(GrailsApplicationPostProcessor.groovy:225)
        at grails.boot.config.GrailsApplicationPostProcessor.(GrailsApplicationPostProcessor.groovy:77)
        at grails.boot.config.GrailsAutoConfiguration.grailsApplicationPostProcessor(GrailsAutoConfiguration.groovy:69)
        at tbuilder326.Application.grailsApplicationPostProcessor(Application.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1426)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 24 common frames omitted
    Caused by: java.lang.NoClassDefFoundError: org/grails/compiler/web/converters/RenderConverterTrait
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
        at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:677)
        at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:787)
        at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:775)
        at org.grails.plugins.BinaryGrailsPlugin.initializeProvidedArtefacts(BinaryGrailsPlugin.java:173)
        ... 40 common frames omitted
    Caused by: java.lang.ClassNotFoundException: org.grails.compiler.web.converters.RenderConverterTrait
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 56 common frames omitted

Can anyone suggest what I might be missing?  Some sort of compile or runtime dependency?


问:
PHPSESSID security issues?
I've been curious for a while now about the security issues surrounding the PHP session name: PHPSESSID.

I've noticed that some websites rename their session ID cookie, while others just leave it as the default.

Is there any security advantage in using a different name? or is it merely useful for being able to track multiple sessions per user?

答: If you want to obscure the fact that you are running php then you should change the name.  However what is more common is that developers get the horrible idea of reinventing the wheal and writing their own (very broken) session handler.  9 times out of 10 this approach is far less secure than your usual session_start().

ContentLicense: CC BY-SA 2.5

Title: PHPSESSID security issues?


问:
Angular/TypeScript/RxJS - I've tried all renditions of map, concat, merge etc - trying to get nested items in array
Currently the following final lines (after retrieving from an Observable.forkJoin of 17 this.http.get requests):

```<code>        .map(data => Observable.from(data))
        .finally(() => { console.log(this.topicData) })
        .subscribe((data) => { this.topicData = data });
</code>```

And the console.log above you see gives me data in the following format:

As you can see, this has arrays within arrays.  I just want a single Observable array with the Objects nested two layers within shell arrays.  Again, I have tried all the maps, concat, reduce, merge etc.  With RxJS I feel like I just plug things in until it works.  When I read the documentation, I have difficulty understanding how it relates to what I am trying to do (training resources are welcome also).  For this problem in particular, does anybody know how I can return a single Observable array with the Objects?

Update with additional code from forkJoin:

```<code>return Observable.forkJoin(
            this.http.get(this.baseUrl + webs[0] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[1] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[2] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[3] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[4] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[5] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[6] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[7] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[8] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[9] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[10] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[11] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[12] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[13] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[14] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[15] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[16] + this.topicsRest, this.options).map((res: Response) => res.json().d.results)
        )
</code>```

答:
I figured it out. Here is the final code on the service function:

```<code>    return Observable.forkJoin(webs.map(web =>
        this.http.get(this.baseUrl + web + this.topicsRest, this.options).map((res: Response) => res.json().d.results)
    ))
        .flatMap(data => data.map(item => item.map(object =>  object )))
        .do(data => console.log(data))
}
</code>```

Where webs is an array of relative site paths.  I did an async pipe on the ngFor of the template and it pulled through.  Thank you all for the references and help, it helped point me in the right direction.

Body:
Currently the following final lines (after retrieving from an Observable.forkJoin of 17 this.http.get requests):

        .map(data => Observable.from(data))
        .finally(() => { console.log(this.topicData) })
        .subscribe((data) => { this.topicData = data });

And the console.log above you see gives me data in the following format:

As you can see, this has arrays within arrays.  I just want a single Observable array with the Objects nested two layers within shell arrays.  Again, I have tried all the maps, concat, reduce, merge etc.  With RxJS I feel like I just plug things in until it works.  When I read the documentation, I have difficulty understanding how it relates to what I am trying to do (training resources are welcome also).  For this problem in particular, does anybody know how I can return a single Observable array with the Objects?

Update with additional code from forkJoin:

return Observable.forkJoin(
            this.http.get(this.baseUrl + webs[0] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[1] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[2] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[3] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[4] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[5] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[6] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[7] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[8] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[9] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[10] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[11] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[12] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[13] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[14] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[15] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[16] + this.topicsRest, this.options).map((res: Response) => res.json().d.results)
        )

Body:
I figured it out. Here is the final code on the service function:

    return Observable.forkJoin(webs.map(web =>
        this.http.get(this.baseUrl + web + this.topicsRest, this.options).map((res: Response) => res.json().d.results)
    ))
        .flatMap(data => data.map(item => item.map(object =>  object )))
        .do(data => console.log(data))
}

Where webs is an array of relative site paths.  I did an async pipe on the ngFor of the template and it pulled through.  Thank you all for the references and help, it helped point me in the right direction.


问:
OpenMP - Initializing 1D Array
I am trying to initialize a dynamic array using OpenMP in C but it seems to be slower than the serial method. The function I am using is

```<code>int* createArray(int size, int num) {
    int i;
    int* M = (int*)malloc(size*sizeof(int));

    srand(time(NULL));
    double start = omp_get_wtime();

    #pragma omp parallel for num_threads(num)
    for (i = 0; i < size; i++) {
        M[i] = rand() % (MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
    }

    double end = omp_get_wtime();
    printf("Create Array %f\n",end-start);
    return M;
}
</code>```

I get an array of the given size containing random numbers but the fewer threads I use the faster the function is. Am I doing something wrong?

答:
I'm quite sure your program is suffering a problem called "false sharing" cache.

The article below explains it quite well.
https://software.intel.com/en-us/articles/avoiding-and-identifying-false-sharing-among-threads

this often affects performance a lot.
you can quickly have a test. add below to your omp pragma
schedule(static, 16)

this should improve a lot. then you can dig further about false sharing.

Title: OpenMP - Initializing 1D Array

Body:
I am trying to initialize a dynamic array using OpenMP in C but it seems to be slower than the serial method. The function I am using is

int* createArray(int size, int num) {
    int i;
    int* M = (int*)malloc(size*sizeof(int));

    srand(time(NULL));
    double start = omp_get_wtime();

    #pragma omp parallel for num_threads(num)
    for (i = 0; i < size; i++) {
        M[i] = rand() % (MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
    }

    double end = omp_get_wtime();
    printf("Create Array %f\n",end-start);
    return M;
}

I get an array of the given size containing random numbers but the fewer threads I use the faster the function is. Am I doing something wrong?


问:
MYSQL How to find entries that contain more than 10 numbers?
I need to clean up a table that contains a lot links to images. I can identify them by the name, because they include a lot numbers.

Question is how does the query looks like? Is it possible?

```<code>WHERE table REGEXP '[0-9]'
</code>```

This brings me every entry that contains a number.

But what I need are all entries that contain at least 20 numbers.

Example: /dsc-2342342432423432424234234

thanks again

答:
for at least 20 digit  .. </p>

```<code>select * from my_table
where my_column  regexp '[0-9]{20}'
</code>```

Body:
I need to clean up a table that contains a lot links to images. I can identify them by the name, because they include a lot numbers.

Question is how does the query looks like? Is it possible?

WHERE table REGEXP '[0-9]'

This brings me every entry that contains a number.

But what I need are all entries that contain at least 20 numbers.

Example: /dsc-2342342432423432424234234

thanks again

Body:
for at least 20 digit  ..

select * from my_table
where my_column  regexp '[0-9]{20}'


问:
In given a line from some file (or stdin) how can i reduce the extra spaces and convert the tabs to single space?
In given a line that exist in array. Like in this case:

```<code>char line[50];
while (fgets(line,50, input_file) != NULL) {
 // how can i do it here..
}
</code>```

How can i reduce all the extra spaces to single space , and to reduce all the tabs (between any two words) to a single space.

For example:

In give this line:

```<code>   a b   abb     ace    ab
</code>```

It's need to be:

```<code>a b abb ace ab
</code>```

答:
Here is a simple solution:

```<code>char line[50];
while (fgets(line, sizeof line, input_file) != NULL) {
    size_t i, j;
    for (i = j = 0; line[i] != '\0'; i++) {
        if (isspace((unsigned char)line[i])) {
            while (isspace((unsigned char)line[++i]))
                continue;
            if (line[i] == '\0')
                break;
            if (j != 0)
                line[j++] = ' ';
        }
        line[j++] = line[i];
    }
    line[j] = '\0';
    printf("reduced input: |%s|\n", line);
}
</code>```

Now since this is homework, here are a few extra questions to answer:

which include files are required?

why is the cast (unsigned char)line[i] needed?

what will happen if a line longer than 50 bytes is read from input_file?

what is wrong with the previous question?

Body:
In given a line that exist in array. Like in this case:

char line[50];
while (fgets(line,50, input_file) != NULL) {
 // how can i do it here..
}

How can i reduce all the extra spaces to single space , and to reduce all the tabs (between any two words) to a single space.

For example:

In give this line:

   a b   abb     ace    ab

It's need to be:

a b abb ace ab

Body:
Here is a simple solution:

char line[50];
while (fgets(line, sizeof line, input_file) != NULL) {
    size_t i, j;
    for (i = j = 0; line[i] != '\0'; i++) {
        if (isspace((unsigned char)line[i])) {
            while (isspace((unsigned char)line[++i]))
                continue;
            if (line[i] == '\0')
                break;
            if (j != 0)
                line[j++] = ' ';
        }
        line[j++] = line[i];
    }
    line[j] = '\0';
    printf("reduced input: |%s|\n", line);
}

Now since this is homework, here are a few extra questions to answer:

which include files are required?

why is the cast (unsigned char)line[i] needed?

what will happen if a line longer than 50 bytes is read from input_file?

what is wrong with the previous question?


问:
.NET assembly in current domain cannot be found
I have a project I am working that will search all loaded assemblies for any class that implements a certain interface. Then it will create an instance of that class and invoke a method of the interface. The code ran great on simple projects in testing environments. At the heart of it is the following function:

```<code>    public static List<Type> GetLoadedTypes(Type targetType)
    {
        var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
            .SelectMany(a => a.GetTypes())
            .Where(t => targetType.IsAssignableFrom(t)).ToList();
        return types;
    }
</code>```

I have another project that inserted this code into and the LINQ query fails because one of the assemblies in the domain cannot be found.

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Practices.ObjectBuilder, Version=1.0.51206.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I don't directly reference this assembly in any of my projects. How can I find out which assembly references it? How did the assembly even get into the domain if it cannot be found?

EDIT:
I am using Enterprise Library in the project but I am already referencing the Microsoft.Practices.ObjectBuilder2.dll. Apparently there is a difference between the two assemblies. Is that correct?

Thanks!
Jeff

答:
This is used by Microsoft's Unity. Copy the DLL to your bin at the time of build (using script, ...) or add a reference.

Update

In order to find out, you can add AppDomain's AssemblyResolve event and check RequestingAssembly property in the arguments.

Update 2

OK, here is how I would have approached it:

Use sysinternal's procmon to monitor your executable. You will see name of the file (objectbuilder2) popping up with a lot of FILE NOT FOUND events in there. See where it is looking for it, you need it to be there. I think DLL is being loaded in a different location

Make sure this specific version of the DLL exists

Body:
I have a project I am working that will search all loaded assemblies for any class that implements a certain interface. Then it will create an instance of that class and invoke a method of the interface. The code ran great on simple projects in testing environments. At the heart of it is the following function:

    public static List<Type> GetLoadedTypes(Type targetType)
    {
        var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
            .SelectMany(a => a.GetTypes())
            .Where(t => targetType.IsAssignableFrom(t)).ToList();
        return types;
    }

I have another project that inserted this code into and the LINQ query fails because one of the assemblies in the domain cannot be found.

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Practices.ObjectBuilder, Version=1.0.51206.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I don't directly reference this assembly in any of my projects. How can I find out which assembly references it? How did the assembly even get into the domain if it cannot be found?

EDIT:
I am using Enterprise Library in the project but I am already referencing the Microsoft.Practices.ObjectBuilder2.dll. Apparently there is a difference between the two assemblies. Is that correct?

Thanks!
Jeff


问:
Create a page in Confluence using ScriptRunner
I'm working for a company that it has Jira Cloud, and we need to create some Confluence page since a Jira flow using script runner, is this possible?, and if its possible how I can do it? Thanks</p>

答: Welcome to Stack Overflow. Answer is Yes, you can use Confluence REST API to create a page in Confluence from JIRA with Script Runner. There are couple of examples like this in Atlassian Community that you can take a look. However, since you are new user, I would also recommend you to take a look at How to Ask a Good Question documents as well. It will help you to get better answers if you let us what you have already tried.</p>


问:
How to remove a string from an array within Jquery autocomplete
I have the following piece of code within my cshtml file.
There are two fields which I am using autocomplete for:

```<code><div class="Wrapper">
    @using (Html.BeginForm("GetDetails", "TrainInfo", FormMethod.Post))
    {
        <div id="station_row">
            From <input type="text" placeholder="Departure Station" id="depart" name="DeptStation">
            to <input type="text" placeholder="Arrival Station" id="arrive" name="ArrvStation">
        </div>

        <div id="date_time">
            When: <input type="text" id="datepicker" name="DeptDate">
            At: <input type="text" class="timepicker" name="time">

        </div>

        <div id="go_button">
            <button type="submit" name="Submit">Go</button>
        </div>
    }
</div>

@section scripts
{
    <script type="text/javascript">
        (function ($) {
            $("#datepicker").datepicker({ dateFormat: "yy-mm-dd" });
        })(jQuery);
    </script>

    <script src="http://cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>

    <script type="text/javascript">
        (function ($) {
            $('.timepicker')
                .timepicker({
                    timeFormat: 'h:mm p',
                    interval: 15,
                    minTime: '00:00',
                    maxTime: '11:45pm',
                    defaultTime: '00',
                    startTime: '0:00',
                    dynamic: false,
                    dropdown: true,
                    scrollbar: true
                });
        })(jQuery);
    </script>

    <script>
        $(function () {
            var availableTags = [
                @{
                    GetAllStationsForUi stationNames = new GetAllStationsForUi(new DatabaseConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TrainTimes"].ConnectionString));
                    var station = stationNames.GetAllPossibleStations().Select(i => "\"" + i + "\"").Aggregate((s1, s2) => string.Format("{0},{1}", s1, s2));
                    @Html.Raw(station)
                }
            ];
            $("#depart").autocomplete({
                source: availableTags
            });
            $("#arrive").autocomplete({
                source: availableTags
                });
        });
    </script>

}
</code>```

When I select one option from either of the boxes, I want this option to be removed from the other selection. Does anyone have any idea on how this can be done?

答:
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];

var options = {
    source: availableTags,
    select: function(event, ui) {
      console.log(ui)
     availableTags = jQuery.grep(availableTags, function(value) {
  return value != ui.item.label;
});
      console.log(availableTags)

        $('.autocomplete').autocomplete('option', 'source', availableTags)

    }
}

    $('.autocomplete').autocomplete(options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

  <div class="ui-widget">
  <label for="tags-a">Tags A: </label>
  <input id="tags-a" class="autocomplete">
</div>

  <div class="ui-widget">
  <label for="tags-b">Tags B: </label>
  <input id="tags-b" class="autocomplete">
</div>

</body>
</html></code>```

If you want to have the removed (item selected) item reappear when the textbox is cleared (ie unselected), then just hook into the keyup event of the textbox and if it is empty, set availableTags to the original.

External demo

Some documentation.

Body:
I have the following piece of code within my cshtml file.
There are two fields which I am using autocomplete for:

    @using (Html.BeginForm("GetDetails", "TrainInfo", FormMethod.Post))
    {

            From <input type="text" placeholder="Departure Station" id="depart" name="DeptStation">
            to <input type="text" placeholder="Arrival Station" id="arrive" name="ArrvStation">

            When: <input type="text" id="datepicker" name="DeptDate">
            At: <input type="text" class="timepicker" name="time">

            <button type="submit" name="Submit">Go</button>

    }

@section scripts
{

}

When I select one option from either of the boxes, I want this option to be removed from the other selection. Does anyone have any idea on how this can be done?

Body:
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];

var options = {
    source: availableTags,
    select: function(event, ui) {
      console.log(ui)
     availableTags = jQuery.grep(availableTags, function(value) {
  return value != ui.item.label;
});
      console.log(availableTags)

        $('.autocomplete').autocomplete('option', 'source', availableTags)

    }
}

    $('.autocomplete').autocomplete(options);

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

  <div class="ui-widget">
  <label for="tags-a">Tags A: </label>
  <input id="tags-a" class="autocomplete">
</div>

  <div class="ui-widget">
  <label for="tags-b">Tags B: </label>
  <input id="tags-b" class="autocomplete">
</div>

</body>
</html>

If you want to have the removed (item selected) item reappear when the textbox is cleared (ie unselected), then just hook into the keyup event of the textbox and if it is empty, set availableTags to the original.

External demo

Some documentation.


问:
How can I use SFINAE to prevent narrowing in a template function?
I am trying to implement basic arithmetic operations for a Vector class and would like to support mixing underlying types while preventing narrowing from occurring.

```<code>template <typename T1,typename T2>
Vector<T1> operator+( Vector<T1> lhs, const Vector<T2>& rhs, std::enable_if< ! is_narrowing_conversion<T2,T1>::value >::type* = nullptr )
{ return lhs += rhs; }
</code>```

I would like to implement is_narrowing_conversion so that it will only allow the conversion if the types do not narrow. Here are some examples:

```<code>Vector<double> a = Vector<double>() + Vector<float>(); //OK
Vector<float> a = Vector<float> + Vector<double>; //Fails to find the operator+ function
</code>```

In the end I would like to write a second template operator+ function that will handle the inverse case by returning a Vector.

I found this post with an incomplete example. But it is insufficient as he notes that it disallows uint8_t to uint64_t conversions.

I also discovered Daniel Krügler's paper on fixing is_constructible. Specifically in this paper he mentions using list-initialization which already has the narrowing semantics working but I'm not sure how to convert what he mentions into a proper trait that I can use for SFINAE template deduction.

答:
What about using SFINAE through std::common_type ?

The following is a simplified example (no Vector but simples values; no operator+() but a sum() function) but I hope you can understand what I mean

```<code>#include <iostream>
#include <type_traits>

template <typename T1, typename T2>
T1 sum (T1 t1,
        T2 const & t2,
        typename std::enable_if<std::is_same<
              T1,
              typename std::common_type<T1, T2>::type
           >::value>::type * = nullptr)
 { return t1 += t2; }

int main()
 {
   float  a      = 1.1f;
   double b      = 2.2;
   long double c = 3.3;

   std::cout << sum(b, a) << std::endl;
   std::cout << sum(c, a) << std::endl;
   std::cout << sum(c, b) << std::endl;
   // std::cout << sum(a, b) << std::endl; compilation error
   // std::cout << sum(a, c) << std::endl; compilation error
   // std::cout << sum(b, c) << std::endl; compilation error
 }
</code>```

Body:
I am trying to implement basic arithmetic operations for a Vector class and would like to support mixing underlying types while preventing narrowing from occurring.

template <typename T1,typename T2>
Vector<T1> operator+( Vector<T1> lhs, const Vector<T2>& rhs, std::enable_if< ! is_narrowing_conversion<T2,T1>::value >::type* = nullptr )
{ return lhs += rhs; }

I would like to implement is_narrowing_conversion so that it will only allow the conversion if the types do not narrow. Here are some examples:

Vector<double> a = Vector<double>() + Vector<float>(); //OK
Vector<float> a = Vector<float> + Vector<double>; //Fails to find the operator+ function

In the end I would like to write a second template operator+ function that will handle the inverse case by returning a Vector.

I found this post with an incomplete example. But it is insufficient as he notes that it disallows uint8_t to uint64_t conversions.

I also discovered Daniel Krügler's paper on fixing is_constructible. Specifically in this paper he mentions using list-initialization which already has the narrowing semantics working but I'm not sure how to convert what he mentions into a proper trait that I can use for SFINAE template deduction.

Body:
What about using SFINAE through std::common_type ?

The following is a simplified example (no Vector but simples values; no operator+() but a sum() function) but I hope you can understand what I mean

#include <iostream>
#include <type_traits>

template <typename T1, typename T2>
T1 sum (T1 t1,
        T2 const & t2,
        typename std::enable_if<std::is_same<
              T1,
              typename std::common_type<T1, T2>::type
           >::value>::type * = nullptr)
 { return t1 += t2; }

int main()
 {
   float  a      = 1.1f;
   double b      = 2.2;
   long double c = 3.3;

   std::cout << sum(b, a) << std::endl;
   std::cout << sum(c, a) << std::endl;
   std::cout << sum(c, b) << std::endl;
   // std::cout << sum(a, b) << std::endl; compilation error
   // std::cout << sum(a, c) << std::endl; compilation error
   // std::cout << sum(b, c) << std::endl; compilation error
 }


问:
How to clear ng-init value on button click event?
Here is my code, I want to reset items.total model.
its not working

```<code><div ng-init="items.total">
   <ul ng-repeat="x in Arr">
      <li ng-init = "items.total.carat = items.total.carat + x.Carat">{{x.Carat}}</li>
   </ul>
</div>
<label>{{items.total.carat}}</label>
<input type="button" ng-click="GetNewData()" value="FETCH">
----------------------------------------------
script :

$scope.GetNewData = function(){
   $scope.items = {};
   -- code --
};
</code>```

答:
Using ng-init to total items in a list is an abuse of that directive:

[The ng-init] directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

— AngularJS ng-init Directive Reference

Instead use a JavaScript function to total the value:

```<code>$scope.computeTotal = function() {
    $scope.items.total.caret = 0;
    for (let i=0; i<$scope.Arr.length; i++) {
       $scope.items.total.caret += $scope.Arr[i];
    };
};
</code>```

AngularJS separates concerns into Model, View, and Controller. The template (or View) should only render the Model. The Controller should create and update the Model as needed. This separation of concerns simplifies the development and maintenance of applications.

Body:
Here is my code, I want to reset items.total model.
its not working

{{x.Carat}}

{{items.total.carat}}
<input type="button" ng-click="GetNewData()" value="FETCH">
----------------------------------------------
script :

$scope.GetNewData = function(){
   $scope.items = {};
   -- code --
};

Body:
Using ng-init to total items in a list is an abuse of that directive:

[The ng-init] directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

— AngularJS ng-init Directive Reference

Instead use a JavaScript function to total the value:

$scope.computeTotal = function() {
    $scope.items.total.caret = 0;
    for (let i=0; i<$scope.Arr.length; i++) {
       $scope.items.total.caret += $scope.Arr[i];
    };
};

AngularJS separates concerns into Model, View, and Controller. The template (or View) should only render the Model. The Controller should create and update the Model as needed. This separation of concerns simplifies the development and maintenance of applications.


问:
How to fix postinstall on a dependency with yarn?
I have a node dependency that has a simple postinstall step which includes a call to mkdirp.

with npm install - this was the structure

```<code> +- project
    +- node_modules
       +- dep1
          +- node_modules
             +- mkdirp
</code>```

so when dep1 postinstall used mkdirp it would find it in the path

now it fails because with yarn mkdirp is not longer in the path.

how can I resolve this?

I tried running npm install on the specific dependency that is breaking, and only then run yarn install - but it didn't work.

答:
According to this issue, Yarn doesn't (yet) run preinstall or postinstall scripts. If you are using a package that relies on those hooks, it will fail.

With the release of NPM v5 and the supposed 5x speed-up, you might just want to stick with npm.

Body:
I have a node dependency that has a simple postinstall step which includes a call to mkdirp.

with npm install - this was the structure

 +- project
    +- node_modules
       +- dep1
          +- node_modules
             +- mkdirp

so when dep1 postinstall used mkdirp it would find it in the path

now it fails because with yarn mkdirp is not longer in the path.

how can I resolve this?

I tried running npm install on the specific dependency that is breaking, and only then run yarn install - but it didn't work.


问:
Distance measure between two sets of possibly different size
I have 2 sets of integers, A and B, not necessarily of the same size. For my needs, I take the distance between each 2 elements a and b (integers) to be just abs(a-b).

I am defining the distance between the two sets as follows:

If the sets are of the same size, minimize the sum of distances of all pairs [a,b] (a from A and b from B), minimization over all possible 'pairs partitions' (there are n! possible partitions).

If the sets are not of the same size, let's say A of size m and B of size n, with m < n, then minimize the distance from (1) over all subsets of B which are of size m.

My question is, is the following algorithm (just an intuitive guess) gives the right answer, according to the definition written above.

Construct a matrix D of size m X n, with D(i,j) = abs(A(i)-B(j))

Find the smallest element of D, accumulate it, and delete the row and the column of that element. Accumulate the next smallest entry, and keep accumulating until all rows and columns are deleted.

for example, if A={0,1,4} and B={3,4}, then D is (with the elements above and to the left):

  3 4

0 3 4

1 2 3

4 1 0

And the distance is 0 + 2 = 2, coming from pairing 4 with 4 and 3 with 1.

答: Your answer gives a good approximation to the minimum, but not necessarily the best minimum. You are following a "greedy" approach which is generally much easier, and gives good results, but can not guarantee the best answer.</p>


问:
VBA Val Function Changing Value?
An equation produces this value as Variant/Double X: 36.0418746812314

But:

X <> Val(X) is true

X <> CStr(X) is false

X <> CDdl(X) is false

How is Val() changing the value?

When viewed in the watch list applying X = Val(X) does not appear to change the value or type of X.  But somehow it is different.

For instance:

A = X - Val(X) is very small, but not zero (2.1316282072803E-14).

B = X - CStr(X) is very small, but not zero (2.1316282072803E-14).

C = X - CDbl(X) is zero.

Update:
Thanks everyone for your replies and answers.  Here is some additional background.

Formula for dividend adjusted close price.  Reportedly used by Yahoo Finance.

A1 = A0 + A0 * (((P1 / S) - P0 - D) / P0)

Split and Dividend Adjusted Close Price

Ticker Symbol: INTC

Date: Friday, August 29, 1980

0.306757021582758 (Yahoo Finance calculated)

0.306757021582704 (My VBA calculation)

Converting A1 to string CStr(A1) or applying Val(A1), then my VBA result matches the Yahoo Finance calculated value.

It's not really a material difference but nice to understand why and how to make it match for purpose of formula validation.

Formula source, components details and explanation.

"How Yahoo Calculates the Adjusted Closing Price"

http://marubozu.blogspot.com/2006/09/how-yahoo-calculates-adjusted-closing.html

答:
Consider this MCVE:

```<code>Sub TestingVal()
  Dim x As Double, y As Double
  x = 36.0418746812314 + 2.1316282072803E-14
  y = Val(x)
  Debug.Print x, y, x <> y       ' 36.0418746812314  36.0418746812314  True
End Sub
</code>```

Both x and Y display the same way, due to the displaying precision. But their actual values (binary representations) are different.

For info, here are the binary representations of x and y in the IEEE-754 format:

```<code>0100000001000000000001010101110000100110010010010011010110101110
0100000001000000000001010101110000100110010010010011010110101011
'                                                            ^^^
</code>```

Only the last 3 bits (of the mantissa) differ! This difference was not big enough to show when they are displayed in base 10 with 14 decimal digits.

Now consider the Val Function:

Returns the numbers contained in a string as a numeric value of appropriate type

That means, in Val(x), the number x was first converted to a String to match the parameter type of the function. This resulted in its displayed value in Base 10. Then Val converted it back to a number and we stored it in y. Since in the first phase the displayed value was not the exact value, some bits of precision were lost and we got x <> Val(x).

As conclusion, when precision matters to the last bit in your calculations, dont apply Val on a number. Even if you dont know whether your initial variant is a double or a string, use CDbl which works well in both cases.

Title: VBA Val Function Changing Value?

Body:
Consider this MCVE:

Sub TestingVal()
  Dim x As Double, y As Double
  x = 36.0418746812314 + 2.1316282072803E-14
  y = Val(x)
  Debug.Print x, y, x <> y       ' 36.0418746812314  36.0418746812314  True
End Sub

Both x and Y display the same way, due to the displaying precision. But their actual values (binary representations) are different.

For info, here are the binary representations of x and y in the IEEE-754 format:

0100000001000000000001010101110000100110010010010011010110101110
0100000001000000000001010101110000100110010010010011010110101011
'                                                            ^^^

Only the last 3 bits (of the mantissa) differ! This difference was not big enough to show when they are displayed in base 10 with 14 decimal digits.

Now consider the Val Function:

Returns the numbers contained in a string as a numeric value of appropriate type

That means, in Val(x), the number x was first converted to a String to match the parameter type of the function. This resulted in its displayed value in Base 10. Then Val converted it back to a number and we stored it in y. Since in the first phase the displayed value was not the exact value, some bits of precision were lost and we got x <> Val(x).

As conclusion, when precision matters to the last bit in your calculations, dont apply Val on a number. Even if you dont know whether your initial variant is a double or a string, use CDbl which works well in both cases.


问:
regular expression to get html tag value
This is my HTML string
How to get the "title" value from regular expression using javascript only.

I want output should be "MyImage_147x91.png"

any suggestions?

i tried so far it's not working

```<code> var htmlString = "<img class='left' alt='""' src='182-35622' title='MyImage_147x91.png' uri='182-35622' style='width: 147px; height: 91px;'>"

 var setCookieMetaRegExp = /<img title=[\"'](.*)[\"'].*>/ig;

 var matches = [];

while (setCookieMetaRegExp.exec(htmlString)) {
  //matches.push(RegExp.$1);
}
</code>```

答:
Why not use HTML DOM information to obtain image title?

var img = document.querySelector('img.left');
console.log(img.title);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class='left' alt='""' src='182-35622' title='MyImage_147x91.png' uri='182-35622' style='width: 147px; height: 91px;'></code>```

If you really need to use regex on the string try below:

var s = "";
var regex = /title\s*=\s*'([^']*)/;
console.log(regex.exec(s)[1]);```

Regex DEMO with explanation

Body:
This is my HTML string
How to get the "title" value from regular expression using javascript only.

I want output should be "MyImage_147x91.png"

any suggestions?

i tried so far it's not working

 var htmlString = ""

 var setCookieMetaRegExp = //ig;

 var matches = [];

while (setCookieMetaRegExp.exec(htmlString)) {
  //matches.push(RegExp.$1);
}

Body:
Why not use HTML DOM information to obtain image title?

var img = document.querySelector('img.left');
console.log(img.title);

<img class='left' alt='&quot;&quot;' src='182-35622' title='MyImage_147x91.png' uri='182-35622' style='width: 147px; height: 91px;'>

If you really need to use regex on the string try below:

var s = "<img class='left' alt='&quot;&quot;' src='182-35622' title='MyImage_147x91.png' uri='182-35622' style='width: 147px; height: 91px;'>";
var regex = /title\s*=\s*'([^']*)/;
console.log(regex.exec(s)[1]);

Regex DEMO with explanation


问:
Android Studio error: Cannot load project
I have this error in Android Studio:

Cannot load project: com.intellij.ide.plugins.PluginManager$StartupAbortedException: com.intellij.diagnostic.PluginException: org/jetbrains/android/uipreview/AndroidLayoutPreviewToolWindowManager [Plugin: org.jetbrains.kotlin.android.dsl]

答:
The reason is that you have a plugin which is incompatible with the IDE.
In my case it was Gradle GUI, and in your case it's Plugin: org.jetbrains.kotlin.android.dsl.
Just simply uninstall it from Plugins in settings.


问:
PPM - Project Portfolio Management
What is your company solution for PPM (managing projects, demands, timesheets, etc)? And what is your experience with it?

I'm trying to know about the tool prespective and not your company's particular business process.

Regards for you all!

答:
We use Microsoft Great Plains, and hate it! We also use Siebel Service for defect tracking... and hate it!

A while back we implemented Mantis, an open source bug tracking tool for a small project that needed customers to access it (all our corporate apps are internal-access only). Mantis has been so successful we have 3 teams using it and resisting moving to using Siebel.

We also use dotProject for project management - its good, but I'm not sure its quite as good as more expensive Project tools.

So, my experience has been that the open source, web based tools are very good (eg OrangeHRM, WebERP, vTiger), very useable, (and free), and they do a perfectly good-enough job. The commerical apps can sometimes be complete pants.

OwnerDisplayName: Bruno Lopes

Title: PPM - Project Portfolio Management

OwnerDisplayName: gbjbaanb


问:
checking for URL validity in VB.net
I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :

```<code>Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate

    Try
        Dim uri As New Uri(args.Value)
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim reader As String = New StreamReader(stream).ReadToEnd()
        args.IsValid = True
    Catch ex As Exception
        args.IsValid = False
    End Try

End Sub
</code>```

I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".

What is wrong with this code ?

Update :

I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)

```<code>function testURLValide(sender, args)
{
    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("HEAD", args.Value, false);
    xmlhttp.send(null);

    if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}
</code>```

答: Instead of reading the stream, how about testing for the HTTP Status Code?  I believe it is response.StatusCode.  The value you would look for would be 200, or possibly something in the 300s (redirect).</p>

Title: checking for URL validity in VB.net

Body:
I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :

Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate

    Try
        Dim uri As New Uri(args.Value)
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim reader As String = New StreamReader(stream).ReadToEnd()
        args.IsValid = True
    Catch ex As Exception
        args.IsValid = False
    End Try

End Sub

I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".

What is wrong with this code ?

Update :

I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)

function testURLValide(sender, args)
{
    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("HEAD", args.Value, false);
    xmlhttp.send(null);

    if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}


问:
Best way to check if a variable exists in Javascript?
Well, my question is obvious,

Example:

Define a with default value undefined:

```<code>var a;
</code>```

If I want to check if a var exists, I will try with:

But in this case, a does exists and a value is undefined, but in the boolean evaluation this is false.

var a; // default value is 'undefined'
if (a) {
    alert('a exists');
} else {
    alert("a don't exists")
}```
</div>
</div>
</p>

<p>I can also try with the following example: but this example generates a error.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// var a;
// a is not defined
if (a) {
    alert('a exists');
} else {
    alert("a don't exists")
}</code>```

And in this example, I try with typeof. But a is defined with undefined value by default.

var a;
if (typeof a != 'undefined') {
    alert('a exists');
} else {
    alert("a don't exists")
}```
</div>
</div>
</p>

<p>And in this example</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log ('var a exists:', window.hasOwnProperty('a'));</code>```

What is the best way to verify if a variable actually exists and why?

Thanks.

答:
There are three different possibilities in JS for a variable.

Variable 'a' not at all declared;

Variable 'a' declared, but unassigned (undefined). Ex: var a;

Variable 'a' declared, but assigned with empty or null.  (Possible scenario, if a variable trying to get value from back-end)

Ex:

var a=null;
var a='';

If you are expecting a value in variable, other than 0 or false, then better to use following condition.  And of course its all based on your need and if you unsure about variable or object values, always enclose them in try & catch block.

//var a;
//var a=null;
//var a='';
//var a=0;
//var a='value';

if (typeof a != "undefined" && a) {
  alert("a is defined AND a is TRUE value");
} else {
  alert("a not exist OR a is a FALSE value");
}```

Body:
Well, my question is obvious,

Example:

Define a with default value undefined:

var a;

If I want to check if a var exists, I will try with:

But in this case, a does exists and a value is undefined, but in the boolean evaluation this is false.

var a; // default value is 'undefined'
if (a) {
    alert('a exists');
} else {
    alert("a don't exists")
}

I can also try with the following example: but this example generates a error.

// var a;
// a is not defined
if (a) {
    alert('a exists');
} else {
    alert("a don't exists")
}

And in this example, I try with typeof. But a is defined with undefined value by default.

var a;
if (typeof a != 'undefined') {
    alert('a exists');
} else {
    alert("a don't exists")
}

And in this example

console.log ('var a exists:', window.hasOwnProperty('a'));

What is the best way to verify if a variable actually exists and why?

Thanks.


问:
Categorical bar graph labels don't work on Matlab
I tried this code to get a categorical label on the bottom of my bar graph:

```<code>c = categorical({'apples','oranges','pears'});
prices = [1.23 0.99 2.3];
bar(c,prices)
</code>```

In the MATLAB documentation, this claims to have the bottom of the axis labelled with the categories in c. Instead I only see 1, 2, 3 along the bottom. Is something wrong with my setup?

答: This functionality was only introduced in Matlab 2017a. As you can see here it is absent from 2016b docs:

Body:
I tried this code to get a categorical label on the bottom of my bar graph:

c = categorical({'apples','oranges','pears'});
prices = [1.23 0.99 2.3];
bar(c,prices)

In the MATLAB documentation, this claims to have the bottom of the axis labelled with the categories in c. Instead I only see 1, 2, 3 along the bottom. Is something wrong with my setup?


问:
can't delete from specific row from generate table from mySQL
Hye, i'm working on a small project of Inventory system. Everything is okay until this last part. I have included a delete button at the end of each row for user to delete any item of choice, but when user press the delete button, it deleted the last row of the table, instead of the row/item of choices, where is my mistake in my coding?

Thank you!

<?php
 $result= mysql_query("SELECT * from Staff ORDER BY status");
 $count=1;

 while($row=mysql_fetch_array($result)){
?>

       <?php echo $count; ?>
    <?php echo $row['staffId']; ?>
    <?php echo $row['name']; ?>
    <?php echo $row['address'];?>
    <?php echo $row['pNum'];?>
    <?php echo $row['status'];?>
    <?php echo $row['type'];?>
                <input type="submit" name="deleteStaff" value="Delete" onClick="displayMessage()">
             <input type="hidden" name="staffId1" value="<?PHP echo $row['staffId']; ?>">

<?php
 $count++; }
 if(isset($_POST['deleteStaff'])){
  $id=$_POST['staffId1'];
  $result=mysql_query("DELETE from Staff WHERE staffId='$id' ");
  if($result){
   echo '';
   }
   else{
    ?>

                <?PHP
    }
  }
?>```

答:
since the name for the hidden field is the same for all rows being generated the post request is pulling the value of the last row( also "staffId1" ).

I recommend either using a individual form for each row in which case your code doesn't change as much or use js to get the required staffID using selectors


问:
How can I correctly install Ruby on Rails, bundler, etc on a fresh Mac OS X?
I recently reinstalled my Mac OS X (10.6.8) and want to install things properly this time.  I had some trouble last time so I just want to set things up right.

In particular, I want to install Ruby on Rails, bundler, and so on... but when I do "gem install bundler" I get the following error:

```<code>c-69-181-106-62:~ dave$ gem install bundler
WARNING:  Installing to ~/.gem since /Library/Ruby/Gems/1.8 and
    /usr/bin aren't both writable.
WARNING:  You don't have /Users/dave/.gem/ruby/1.8/bin in your PATH,
    gem executables will not run.
ERROR:  Error installing bundler:
    bundler requires RubyGems version >= 1.3.6
</code>```

I'm confused... can someone help me out, or point me to an article saying "OK, first, add this to this file, then download this, then do this..."?

Thanks

答:
A clean way to do it, it's also to sandbox the gems to your local user.

For that just create a gems directory with:

mkdir ~/gems

(you can use any directory you have access at)

Then configure the gems environment adding these lines to your shell start script (.bash_profile, .bashrc or .zshrc for instance):

export GEM_HOME=~/gems
export GEM_PATH=~/gems
export PATH=$GEM_PATH/bin:$PATH

Restart your shell terminal

Check your environment with the command

echo $PATH

(it should contain the new gems path bin directory)

Update your rubygems with:

gem update --system

(calling with sudo can be required)

Update the current gems:

gem update

Install bundler (optional):

gem install bundle

And presto !!

NOTE: Also ensure you have Xcode Command Tools installed (if not much of the gems will not be able to build natively)

Body:
I recently reinstalled my Mac OS X (10.6.8) and want to install things properly this time.  I had some trouble last time so I just want to set things up right.

In particular, I want to install Ruby on Rails, bundler, and so on... but when I do "gem install bundler" I get the following error:

c-69-181-106-62:~ dave$ gem install bundler
WARNING:  Installing to ~/.gem since /Library/Ruby/Gems/1.8 and
    /usr/bin aren't both writable.
WARNING:  You don't have /Users/dave/.gem/ruby/1.8/bin in your PATH,
    gem executables will not run.
ERROR:  Error installing bundler:
    bundler requires RubyGems version >= 1.3.6

I'm confused... can someone help me out, or point me to an article saying "OK, first, add this to this file, then download this, then do this..."?

Thanks


问:
Create launcher that kills all the previously opened apps
I have a simple launcher that enlists all the apps in a listview. I just want one feature in this launcher; when a certain item(say 5th item) in the listview is clicked, I want to completely kill all the previous opened apps and then open the 5th app enlisted there. I don't know what should I look for. I have the launcher app as the device admin and device owner and I think that it has something to do with DevicePolicyManager class. I also tried finishActivity(int requestcode) but it did not work. Below is the onItemClick() listener:

```<code>list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int pos,long id) {
                Intent i = manager.getLaunchIntentForPackage(apps.get(pos).name.toString());
                AppsListActivity.this.startActivity(i);

            }
        });
</code>```

答:
A little more context behind why you would like to kill the previously opened app before starting the activity of the next app would help. If I understand correctly, it would always be only one app to kill since only one app would always ever be running, right?

If you don't need to completely kill the apps, it would be much more elegant to suspend all packages setPackagesSuspended (if you're running API 24 or greater) except for the selected one and of course, your launcher. A suspended package will not be able to start activities. Its notifications will be hidden, it will not show up in recents, will not be able to show toasts or dialogs or ring the device. If you are worried about resources, is there a reason you can't trust Android to manage the resources and kill processes when it needs to?

Body:
I have a simple launcher that enlists all the apps in a listview. I just want one feature in this launcher; when a certain item(say 5th item) in the listview is clicked, I want to completely kill all the previous opened apps and then open the 5th app enlisted there. I don't know what should I look for. I have the launcher app as the device admin and device owner and I think that it has something to do with DevicePolicyManager class. I also tried finishActivity(int requestcode) but it did not work. Below is the onItemClick() listener:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int pos,long id) {
                Intent i = manager.getLaunchIntentForPackage(apps.get(pos).name.toString());
                AppsListActivity.this.startActivity(i);

            }
        });


问:
Embedding Xamarin Forms or native embedding
I will make an app where I need the native map. Either I do the app with Xamarin native and Embedding Xamarin.Forms in Xamarin Native on all pages without the page with the map. Or if it's possible I'll do an Xamarin Forms app and embedding the native map control, if it's possible? I read Adding Platform-Specific Controls to a Xamarin.Forms Layout but is the map included? Or is it only "small" controls as the label?

What should I use?

答:
I was helping in a project when developer did the follow and it seems worked for him. He did Xamarin Forms, created

```<code>public class CustomMap : Map
</code>```

where Map is Xamarin.Forms.Maps.Map. Then created custom renderers

```<code>[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace CustomRenderer.iOS
{
    public class CustomMapRenderer : MapRenderer
</code>```

and

```<code>[assembly:ExportRenderer (typeof(CustomMap), typeof(CustomMapRenderer))]
namespace CustomRenderer.Droid
{
    public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter, IOnMapReadyCallback
</code>```

Then you can do a lot of things with CustomPins, InfoWindow, etc

Body:
I was helping in a project when developer did the follow and it seems worked for him. He did Xamarin Forms, created

public class CustomMap : Map

where Map is Xamarin.Forms.Maps.Map. Then created custom renderers

[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace CustomRenderer.iOS
{
    public class CustomMapRenderer : MapRenderer

and

[assembly:ExportRenderer (typeof(CustomMap), typeof(CustomMapRenderer))]
namespace CustomRenderer.Droid
{
    public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter, IOnMapReadyCallback

Then you can do a lot of things with CustomPins, InfoWindow, etc


答:
You should avoid using regular expressions to parse HTML. Instead, use the getAttribute method:

```<code>const img = document.querySelector('.left');
img.getAttribute('title'); // => MyImage_147x91.png
</code>```

Title: regular expression to get html tag value

Body:
You should avoid using regular expressions to parse HTML. Instead, use the getAttribute method:

const img = document.querySelector('.left');
img.getAttribute('title'); // => MyImage_147x91.png


问:
What, exactly, is needed for "margin: 0 auto;" to work?
I know that setting margin: 0 auto; on an element is used to centre it (left-right). However, I know that the element and its parent must meet certain criteria for the auto margin to work, and I can never seem to get the magic right.

So my question is simple: what CSS properties have to be set on an element and its parent in order for margin: 0 auto; to left-right centre the child?

答:
Off the top of my cat's head, make sure the div you're trying to center is not set to width: 100%.

If it is, then the rules set on the child divs are what will matter.


答:
You could use something like this.

```<code>title='([^']+)'
</code>```

Use this website to learn regex. Though based on the other answers to this question there are better ways to go about doing this.

Body:
You could use something like this.

title='([^']+)'

Use this website to learn regex. Though based on the other answers to this question there are better ways to go about doing this.


问:
OWL domain range union
From a previous question I gained an understanding of how intersection works among multiple domains and ranges of a predicate.

It seems that union is the more common way to handle this scenario, so now I'm wondering what different inferences are made from a union of domains or ranges.

Given p rdfs:domain (C ∪ D ∪ E) and the triple a p b, what is inferred about a?

答:
For those who are not well versed in Set theory (like myself) I will provide some explanation of what I think it means for a to belong to the union of C, D, and E.

The type of a is at least one of C or D or E.

The type of a may be more than one of C and D and E.

For example, a may be type C and type E (or may be all three types).

If C, D, and E all have a common superclass S, then a is also of type S.

Given the information in the question, there is no more precise way to define the type of a beyond these "maybes". Specifically, we cannot infer that a has more than one type, but we cannot infer that a has less than three types either.

Title: OWL domain range union


问:
D3 small circle located on edge of radius of larger circle
I am working on a d3 visual with two circles where the smaller circle is placed on the edge of the radius of the larger circle.  A codepen of this is located here https://codepen.io/ajblack/pen/KqKpde.  I have a 200 pixel square SVG that I am placing these circles in, and then I have two values, uAssets and uAssetsCom that are dictating the sizes of the circles.  I create a ratio to ensure that the larger circle fits in the 200 pixel square using this code:

```<code>var ratioToFit = (200/uAssets)/2;
</code>```

Then I use cosine to calculate the distance between the outer radius of the large circle and the outer bound of the SVG container at a 45 degree angle:

```<code>var key = 100*((1-Math.cos(45*Math.PI/180))/Math.cos(45*Math.PI/180))
</code>```

To place the smaller circle I calculate cx and cy attributes as the radius of the inner circle plus this 'key'.

```<code>d3.select("#uAssetComCircle")
  .attr("cx", function(d){return (d.radius+key);})
  .attr("cy", function(d){return (d.radius+key);})
</code>```

This places the inner circle close to the radius of the larger circle but it's about 2 pixels off.  I can offset this with a hardcoded 2 pixel addition to cx and cy but I feel like I shouldn't have to.

Is my math off?

答:
My solution is posted here
https://codepen.io/ajblack/pen/qjOqmQ  .
This implementation uses the suggestions of scale and transform.  The problem that I was having was a misuse of the Pythagorean Theorem.  The radius of my larger circle is 100px and I can use this as the hypotenuse of a right triangle.  I know that I want my smaller circle to be offset at a 45 degree angle so I know that the two other sides of the triangle will be the same length.  Using the formula a²+b²=c² where a and b are the same value and c is equal to 100px minus the radius of my small circle I can easily solve for a and b.

```<code>var uAssets = 17;
var uAssetsCom = 3;
var scale = d3.scaleLinear()
.domain([0,uAssets])
.range([0,100]);
 d3.select("#uAssetComCircle")
    .attr("cx", function(d) {
    return Math.sqrt(Math.pow(100-scale(uAssetsCom),2)/2);
  })
    .attr("cy", function(d) {
    return Math.sqrt(Math.pow(100-scale(uAssetsCom),2)/2);
  });
</code>```

The finished product looks like this

Body:
I am working on a d3 visual with two circles where the smaller circle is placed on the edge of the radius of the larger circle.  A codepen of this is located here https://codepen.io/ajblack/pen/KqKpde.  I have a 200 pixel square SVG that I am placing these circles in, and then I have two values, uAssets and uAssetsCom that are dictating the sizes of the circles.  I create a ratio to ensure that the larger circle fits in the 200 pixel square using this code:

var ratioToFit = (200/uAssets)/2;

Then I use cosine to calculate the distance between the outer radius of the large circle and the outer bound of the SVG container at a 45 degree angle:

var key = 100*((1-Math.cos(45*Math.PI/180))/Math.cos(45*Math.PI/180))

To place the smaller circle I calculate cx and cy attributes as the radius of the inner circle plus this 'key'.

d3.select("#uAssetComCircle")
  .attr("cx", function(d){return (d.radius+key);})
  .attr("cy", function(d){return (d.radius+key);})

This places the inner circle close to the radius of the larger circle but it's about 2 pixels off.  I can offset this with a hardcoded 2 pixel addition to cx and cy but I feel like I shouldn't have to.

Is my math off?

Body:
My solution is posted here
https://codepen.io/ajblack/pen/qjOqmQ  .
This implementation uses the suggestions of scale and transform.  The problem that I was having was a misuse of the Pythagorean Theorem.  The radius of my larger circle is 100px and I can use this as the hypotenuse of a right triangle.  I know that I want my smaller circle to be offset at a 45 degree angle so I know that the two other sides of the triangle will be the same length.  Using the formula a²+b²=c² where a and b are the same value and c is equal to 100px minus the radius of my small circle I can easily solve for a and b.

var uAssets = 17;
var uAssetsCom = 3;
var scale = d3.scaleLinear()
.domain([0,uAssets])
.range([0,100]);
 d3.select("#uAssetComCircle")
    .attr("cx", function(d) {
    return Math.sqrt(Math.pow(100-scale(uAssetsCom),2)/2);
  })
    .attr("cy", function(d) {
    return Math.sqrt(Math.pow(100-scale(uAssetsCom),2)/2);
  });

The finished product looks like this