问:
radiobuttons option - option for all values
Working on building a shiny app where I've few options and I wish to create a further option which provides for all. For example,

Option A
Option B
Option C

Now A, B, C are particular values of a variable. Now I wish to see details when another option "Option All" is selected and that's the combined of (A, B, C).
Please help.

答:
Here You have the solution for Your question of radioButtons with the option All:

```<code>library(shiny)
library(DT)

value <- c(1,2,3)
variable <- c("A","B","C")

data <- data.frame(value, variable)

ui= fluidPage(
    radioButtons("choice","Choose:", choices = c("A","B","C","All"), selected = "All"),
      dataTableOutput("tab")
    )

server= function(input, output,session) {

  data_reactive <- reactive({
    if(input$choice =="All"){
      data <- data
    }
    else{
      data <- data[data$variable %in% input$choice, ]
    }
    data
  })

  output$tab <- DT::renderDataTable({
    datatable(data_reactive())})

}

shinyApp(ui, server)
</code>```

and for the future as @Konrad said, it would be good if You post reproducible example and more clearly define the problem.

Body:
Here You have the solution for Your question of radioButtons with the option All:

library(shiny)
library(DT)

value <- c(1,2,3)
variable <- c("A","B","C")

data <- data.frame(value, variable)

ui= fluidPage(
    radioButtons("choice","Choose:", choices = c("A","B","C","All"), selected = "All"),
      dataTableOutput("tab")
    )

server= function(input, output,session) {

  data_reactive <- reactive({
    if(input$choice =="All"){
      data <- data
    }
    else{
      data <- data[data$variable %in% input$choice, ]
    }
    data
  })

  output$tab <- DT::renderDataTable({
    datatable(data_reactive())})

}

shinyApp(ui, server)

and for the future as @Konrad said, it would be good if You post reproducible example and more clearly define the problem.


来源: stackexchange

问:
Garbarge collector order
I know the .Net garbage collector cannot guarantee any order when destroying objects but I am really suprised of the following behaviour:

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

namespace ConsoleApplication2 {
class Program {

    class A {
        public A() { i = 1; }
        private int i;

        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        ~A() {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Console.WriteLine("Disposed A");
        }
    }

    class B {
        static int p = 0;
        public B(A a) {
            this.a = a;
            j = p++;
        }

        ~B() {
            Console.WriteLine("Disposed " + j.ToString());
        }

        private int j;
        private A a;
    }

    static void Main(string[] args) {
        A a_obj = new A();
        List<B> bs = new List<B>();
        for (int i = 0; i < 10; i++) {
            B b = new B(a_obj);
            bs.Add(b);
        }
    }
}
}
</code>```

This execution has the following (possible) output:

Disposed 9

Disposed 2

Disposed 1

Disposed 0

Disposed A

Disposed 8

Disposed 7

Disposed 6

Disposed 5

Disposed 4

Disposed 3

I can understand that the order of B objects is not deterministic but
how is possible that the garbage collector destroys a_obj, if there are still some B objects that have a reference to a_obj and has not been destroyed still?

答: The output is produced when process is being shut down, at this point GC is cleaning whole memory allocated during process, references between objects do not affect the order of cleaning.</p>

ContentLicense: CC BY-SA 3.0

Title: Garbarge collector order

Body:
I know the .Net garbage collector cannot guarantee any order when destroying objects but I am really suprised of the following behaviour:

using System;
using System.Collections.Generic;

namespace ConsoleApplication2 {
class Program {

    class A {
        public A() { i = 1; }
        private int i;

        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        ~A() {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Console.WriteLine("Disposed A");
        }
    }

    class B {
        static int p = 0;
        public B(A a) {
            this.a = a;
            j = p++;
        }

        ~B() {
            Console.WriteLine("Disposed " + j.ToString());
        }

        private int j;
        private A a;
    }

    static void Main(string[] args) {
        A a_obj = new A();
        List bs = new List();
        for (int i = 0; i < 10; i++) {
            B b = new B(a_obj);
            bs.Add(b);
        }
    }
}
}

This execution has the following (possible) output:

Disposed 9

Disposed 2

Disposed 1

Disposed 0

Disposed A

Disposed 8

Disposed 7

Disposed 6

Disposed 5

Disposed 4

Disposed 3

I can understand that the order of B objects is not deterministic but
how is possible that the garbage collector destroys a_obj, if there are still some B objects that have a reference to a_obj and has not been destroyed still?


答:
.NET garbage collector does not use reference counting, so it doesn't matter how many references to a_obj there is. What matters is what objects are reachable from roots (like static variables). In your case, all objects (A and all Bs) become unreachable from root at the same time and so are all eligible to garbage collection, their mutual references do not matter. If A and B are both unreachable and will be collected in the same cycle, why bother about order in which this will happen? Also if order was dependent on which object references which - think about how it would then collect objects that have mutual references to each other?

Here is also a quote from documentation which fits your situation exactly:

The finalizers of two objects are not guaranteed to run in any
  specific order, even if one object refers to the other. That is, if
  Object A has a reference to Object B and both have finalizers, Object
  B might have already been finalized when the finalizer of Object A
  starts.

Also note that first all finalizers will run and only then objects will be really dead and memory taken by them might be reused (you can even ressurect object in finalizer via GC.ReRegisterForFinalize). So you can access A from B's finalizer, even though A's finalizer might have already been run at this point. Obviously you should avoid doing this anyway.

Title: Garbarge collector order


问:
Unexpected results with try, with open
Can't figure this one out and there doesn't seem to be any info on the web either. Tried it with both Python 2 and 3.

```<code>def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        load_settings()
</code>```

I would expect the above function to return 'default_settings' given that settings.txt doesn't already exist. Instead it returns None.

答:
Change your last line to

```<code>return load_settings()
</code>```

Otherwise, you call your function, but don't return its value.

Title: Unexpected results with try, with open

Body:
Can't figure this one out and there doesn't seem to be any info on the web either. Tried it with both Python 2 and 3.

def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        load_settings()

I would expect the above function to return 'default_settings' given that settings.txt doesn't already exist. Instead it returns None.

Body:
Change your last line to

return load_settings()

Otherwise, you call your function, but don't return its value.


问:
Convert RDD[Map[String, String]] to Spark dataframe
I'm trying to convert a val rec: RDD[Map[String, String]] into a Spark dataframe.

But when I execute:

```<code>val sqlContext = new SQLContext(sc)
val df = sqlContext.createDataFrame(rec, classOf[Map[String, String]])

df.write.json("/tmp/file.json")
</code>```

The file json is full of empty objects:

```<code>{}
{}
{}
{}
{}
</code>```

I'm converting it to json just because I want save the rec val and reuse it later with SQLContext object in python.

So the question is how to save my RDD[HashMap[String, String]] created in Scala and reuse later in Python?

UPDATE

rec val contains

```<code>Map(Param_timestamp -> 2017-03-28T02:00:02.887, Param_querytype -> listing, Param_slug -> /salute-beauty-fitness/bellezza-cura-del-corpo/cosmesi/makeup, Param_br -> CAUDALIE)
</code>```

df.show() returns:

```<code>++
||
++
||
... all the 20 lines are the alike "||"
||
++
only showing top 20 rows
</code>```

答:
As long as you master your schema, you can recreate it through the use of StructField and StructType, the doc explains it pretty well I believe. As for scala, I'm not exactly familiar with it but a small example in Java can perhaps help (I'll convert it to Scala later when I have more time):

```<code>    JavaSparkContext jsc = new JavaSparkContext(
            new SparkConf().setAppName("test").setMaster("local[*]"));
    jsc.setLogLevel("ERROR");
    System.setProperty("hadoop.home.dir", "C:\\Temp\\tt\\Tools");

    List<Tuple2<String, String>> test = new ArrayList<Tuple2<String, String>>();
    Tuple2<String, String> tt = new Tuple2<String, String>("key", "val1");
    test.add(tt);
    tt = new Tuple2<String, String>("key", "val2");
    test.add(tt);
    tt = new Tuple2<String, String>("key2", "val");
    test.add(tt);

    JavaPairRDD<String, String> testRDD = jsc.parallelizePairs(test);

    System.out.println(testRDD.first());

    SparkContext sc = JavaSparkContext.toSparkContext(jsc);
    SparkSession ss = new SparkSession(sc);
    StructField[] fields = {
            DataTypes.createStructField("key", DataTypes.StringType, false),
            DataTypes.createStructField("val", DataTypes.StringType, false) };
    StructType schema = DataTypes.createStructType(fields);
    JavaRDD<Row> testRowRDD = testRDD.map(line -> RowFactory.create(line._1, line._2));
    Dataset<Row> myDF = ss.createDataFrame(testRowRDD, schema);
    myDF.show();

    myDF.write().json("test.json");

    jsc.close();
</code>```

The output is several Json files, containing each one line like this:

```<code>{"key":"key2","val":"val"}
</code>```

Body:
I'm trying to convert a val rec: RDD[Map[String, String]] into a Spark dataframe.

But when I execute:

val sqlContext = new SQLContext(sc)
val df = sqlContext.createDataFrame(rec, classOf[Map[String, String]])

df.write.json("/tmp/file.json")

The file json is full of empty objects:

{}
{}
{}
{}
{}

I'm converting it to json just because I want save the rec val and reuse it later with SQLContext object in python.

So the question is how to save my RDD[HashMap[String, String]] created in Scala and reuse later in Python?

UPDATE

rec val contains

Map(Param_timestamp -> 2017-03-28T02:00:02.887, Param_querytype -> listing, Param_slug -> /salute-beauty-fitness/bellezza-cura-del-corpo/cosmesi/makeup, Param_br -> CAUDALIE)

df.show() returns:

++
||
++
||
... all the 20 lines are the alike "||"
||
++
only showing top 20 rows

Body:
As long as you master your schema, you can recreate it through the use of StructField and StructType, the doc explains it pretty well I believe. As for scala, I'm not exactly familiar with it but a small example in Java can perhaps help (I'll convert it to Scala later when I have more time):

    JavaSparkContext jsc = new JavaSparkContext(
            new SparkConf().setAppName("test").setMaster("local[*]"));
    jsc.setLogLevel("ERROR");
    System.setProperty("hadoop.home.dir", "C:\\Temp\\tt\\Tools");

    List<Tuple2<String, String>> test = new ArrayList<Tuple2<String, String>>();
    Tuple2<String, String> tt = new Tuple2<String, String>("key", "val1");
    test.add(tt);
    tt = new Tuple2<String, String>("key", "val2");
    test.add(tt);
    tt = new Tuple2<String, String>("key2", "val");
    test.add(tt);

    JavaPairRDD<String, String> testRDD = jsc.parallelizePairs(test);

    System.out.println(testRDD.first());

    SparkContext sc = JavaSparkContext.toSparkContext(jsc);
    SparkSession ss = new SparkSession(sc);
    StructField[] fields = {
            DataTypes.createStructField("key", DataTypes.StringType, false),
            DataTypes.createStructField("val", DataTypes.StringType, false) };
    StructType schema = DataTypes.createStructType(fields);
    JavaRDD<Row> testRowRDD = testRDD.map(line -> RowFactory.create(line._1, line._2));
    Dataset<Row> myDF = ss.createDataFrame(testRowRDD, schema);
    myDF.show();

    myDF.write().json("test.json");

    jsc.close();

The output is several Json files, containing each one line like this:

{"key":"key2","val":"val"}


问:
remove empty Arrays from multidimensional Array generated with simplexml
I have an xml file with the following structure:

```<code><categories>
  <category>
    <id>3</id>
    <title><![CDATA[Testname]]></title>
    <text><![CDATA[]]></text>
    <keywords><![CDATA[]]></keywords>
    <description><![CDATA[]]></description>
  </category>
</categories>
</code>```

Now I'm loading this file and creating an array of it:

```<code>$xmlData = simplexml_load_file( 'categories.xml', null, LIBXML_NOCDATA);
$array = json_decode(json_encode($xmlData), true);
</code>```

That generates me the following Result (print_r Output):

```<code>Array
(
  [@attributes] => Array
    (
      [version] => 1.0
    )

  [categories] => Array
    (
      [category] => Array
        (
          [0] => Array
            (
              [id] => 3
              [title] => Testname
              [text] => Array
                (
                )

              [keywords] => Array
                (
                )

              [description] => Array
                (
                )
            )
        )
    )
)
</code>```

Here is my question, how could I remove those empty arrays? I tried it with array Filter, but this didn't work. (I need the keys, but they should be empty)

I know there would be a way, in my next step where I'm renaming the array keys as needed, i could check for empty arrays in the foreach loop, but I think there is an easier way, because every field (except id) could be empty in the xml file.

```<code>foreach($array['categories']['category'] as $key => $category){
  $results[$key]['id'] = $category['id'];
  $results[$key]['headline'] = $category['title'];
  $results[$key]['content'] = $category['text'];
  $results[$key]['metaKeywords'] = $category['keywords'];
  $results[$key]['metaDescription'] = $category['description'];
}
</code>```

Does someone has an idea, what i could do after the json_decode? Or is there an easier way for all I'm trying to accomplish here?

Thanks!

答:
Every time I see someone use that json_decode(json_encode()) hack, it makes me sad. You don't need to turn the SimpleXML object into an array to loop over it, just read the usage examples in the manual.

If you loop over the SimpleXML object directly, you will never get those arrays, so will never need to remove them:

```<code>$xmlData = simplexml_load_file('categories.xml'); // LIBXML_NOCDATA is NOT needed
foreach($xmlData->categories->category as $key => $category){
  $results[$key]['id'] = (string)$category->id;
  $results[$key]['headline'] = (string)$category->title;
  $results[$key]['content'] = (string)$category->text;
  $results[$key]['metaKeywords'] = (string)$category->keywords;
  $results[$key]['metaDescription'] = (string)$category->description;
}
</code>```

The (string) tells SimpleXML you want the text content of a particular element (including CDATA), and will give you an empty string for the empty elements.

Body:
I have an xml file with the following structure:

<categories>
  <category>
    <id>3</id>
    <title><![CDATA[Testname]]></title>
    <text><![CDATA[]]></text>
    <keywords><![CDATA[]]></keywords>
    <description><![CDATA[]]></description>
  </category>
</categories>

Now I'm loading this file and creating an array of it:

$xmlData = simplexml_load_file( 'categories.xml', null, LIBXML_NOCDATA);
$array = json_decode(json_encode($xmlData), true);

That generates me the following Result (print_r Output):

Array
(
  [@attributes] => Array
    (
      [version] => 1.0
    )

  [categories] => Array
    (
      [category] => Array
        (
          [0] => Array
            (
              [id] => 3
              [title] => Testname
              [text] => Array
                (
                )

              [keywords] => Array
                (
                )

              [description] => Array
                (
                )
            )
        )
    )
)

Here is my question, how could I remove those empty arrays? I tried it with array Filter, but this didn't work. (I need the keys, but they should be empty)

I know there would be a way, in my next step where I'm renaming the array keys as needed, i could check for empty arrays in the foreach loop, but I think there is an easier way, because every field (except id) could be empty in the xml file.

foreach($array['categories']['category'] as $key => $category){
  $results[$key]['id'] = $category['id'];
  $results[$key]['headline'] = $category['title'];
  $results[$key]['content'] = $category['text'];
  $results[$key]['metaKeywords'] = $category['keywords'];
  $results[$key]['metaDescription'] = $category['description'];
}

Does someone has an idea, what i could do after the json_decode? Or is there an easier way for all I'm trying to accomplish here?

Thanks!

Body:
Every time I see someone use that json_decode(json_encode()) hack, it makes me sad. You don't need to turn the SimpleXML object into an array to loop over it, just read the usage examples in the manual.

If you loop over the SimpleXML object directly, you will never get those arrays, so will never need to remove them:

$xmlData = simplexml_load_file('categories.xml'); // LIBXML_NOCDATA is NOT needed
foreach($xmlData->categories->category as $key => $category){
  $results[$key]['id'] = (string)$category->id;
  $results[$key]['headline'] = (string)$category->title;
  $results[$key]['content'] = (string)$category->text;
  $results[$key]['metaKeywords'] = (string)$category->keywords;
  $results[$key]['metaDescription'] = (string)$category->description;
}

The (string) tells SimpleXML you want the text content of a particular element (including CDATA), and will give you an empty string for the empty elements.


问:
xapian-full installed on mac os x snow leopard but failed with dlopen LoadError
Since I have tried to install xapian but failed, I try another alternative with xapian-full. Installation seems goes well, but when I try to write code with that I got toasted with error message again:

```<code>irb(main):001:0> require 'xapian'
LoadError: dlopen(/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle, 9): Library not loaded: /usr/local/lib/libxapian-1.1.3.dylib
  Referenced from: /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
  Reason: image not found - /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
    from /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/xapian.rb:40
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from (irb):1
</code>```

Anyone know how to solve this?

答:
This question pertains to the Ruby gem, not the library itself.

I had the same problem trying to install the xapian-fu, and solved it by doing

cp /Library/Ruby/Gems/1.8/gems/xapian-full-1.1.3.4/xapian-core-1.1.3/.libs/* /usr/local/lib

(substitute the RubyGems path with the path to your installation).

ContentLicense: CC BY-SA 2.5

Body:
Since I have tried to install xapian but failed, I try another alternative with xapian-full. Installation seems goes well, but when I try to write code with that I got toasted with error message again:

irb(main):001:0> require 'xapian'
LoadError: dlopen(/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle, 9): Library not loaded: /usr/local/lib/libxapian-1.1.3.dylib
  Referenced from: /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
  Reason: image not found - /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
    from /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/xapian.rb:40
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from (irb):1

Anyone know how to solve this?


问:
How to test null return using Mockito thenReturn(Single.just(null))
I want to test the condition when single return null

```<code>when(repository.getSubLocations(ID)).thenReturn(Single.just(null));
</code>```

but it gives me error

```<code>at io.reactivex.internal.functions.ObjectHelper.requireNonNull(ObjectHelper.java:39)
</code>```

答:
I found the solution instead of doing this

```<code>when(repository.getSubLocations(ID)).thenReturn(Single.just(null));
</code>```

I do this

```<code>when(repository.getSubLocations(ID)).thenReturn(Single.just(SOME_DATA).map(data -> null));
</code>```

so now I can successfully test null condition

Body:
I want to test the condition when single return null

when(repository.getSubLocations(ID)).thenReturn(Single.just(null));

but it gives me error

at io.reactivex.internal.functions.ObjectHelper.requireNonNull(ObjectHelper.java:39)

Body:
I found the solution instead of doing this

when(repository.getSubLocations(ID)).thenReturn(Single.just(null));

I do this

when(repository.getSubLocations(ID)).thenReturn(Single.just(SOME_DATA).map(data -> null));

so now I can successfully test null condition


问:
Python decorator for function completion
Is it possible to develop a decorator to determine if a function successfully completed without crashing ? Something like the decorator below but it must detect if the function ran successfully. </p>

```<code>def functionStartDecorator():
    print("Function has started")
    def decoratorWrapper(functionToBeDecorated):
        def wrapper(*args, **kwargs):
            #Todo log function has run
            return functionToBeDecorated(*args, **kwargs)
        return wrapper
    return decoratorWrapper
</code>```

答:
As said in comments, simplest would be to wrap your function in a try/except. If your function returns nothing and simply operate by side-effect, it should be straightforward to have the decorated function return the status of that function run:

```<code>def tryfn(f):
    def decorated(*args, **kwargs):
        try:
            f(*args, **kwargs)
            return 'Ran successfully'
        except Exception as e:
            return 'Error: {}'.format(e)
    return decorated
</code>```

You can then tweak the exact return type of decorated: maybe return a boolean, maybe append the status of the function to the return of f, maybe log things... The core principle will probably still be around a try/except within the decorated function. For instance, if you want to return both your return value (or None if it failed) and whether this was a success:

```<code>def tryfn(f):
    def decorated(*args, **kwargs):
        try:
            res = f(*args, **kwargs)
            return True, res
        except:
            return False, None
    return decorated
</code>```

Note that in this case, you're losing the information about the exact error, so you might want to expand the return to include success, failure, error, etc... that becomes a trade-off between convenience and completeness, which will depend on your exact problem.

Body:
Is it possible to develop a decorator to determine if a function successfully completed without crashing ? Something like the decorator below but it must detect if the function ran successfully.

def functionStartDecorator():
    print("Function has started")
    def decoratorWrapper(functionToBeDecorated):
        def wrapper(*args, **kwargs):
            #Todo log function has run
            return functionToBeDecorated(*args, **kwargs)
        return wrapper
    return decoratorWrapper

Body:
As said in comments, simplest would be to wrap your function in a try/except. If your function returns nothing and simply operate by side-effect, it should be straightforward to have the decorated function return the status of that function run:

def tryfn(f):
    def decorated(*args, **kwargs):
        try:
            f(*args, **kwargs)
            return 'Ran successfully'
        except Exception as e:
            return 'Error: {}'.format(e)
    return decorated

You can then tweak the exact return type of decorated: maybe return a boolean, maybe append the status of the function to the return of f, maybe log things... The core principle will probably still be around a try/except within the decorated function. For instance, if you want to return both your return value (or None if it failed) and whether this was a success:

def tryfn(f):
    def decorated(*args, **kwargs):
        try:
            res = f(*args, **kwargs)
            return True, res
        except:
            return False, None
    return decorated

Note that in this case, you're losing the information about the exact error, so you might want to expand the return to include success, failure, error, etc... that becomes a trade-off between convenience and completeness, which will depend on your exact problem.


问:
Visual Studio locates systemjs typescript definitions, but cannot locate them on compile
I have a TypeScript project in Visual Studio, with modules installed via systemjs. I have the following code:

app.ts

```<code>import { Aurelia } from 'aurelia-framework';
</code>```

For example, hovering Aurelia and pressing F12 (Go to Definition) opens up the correct aurelia-framework.d.ts file installed by systemjs. However, when I click Build, I get the following output:

```<code>error TS2307: Build: Cannot find module 'aurelia-router'.
</code>```

Here is my tsconfig for reference.

tsconfig.json

```<code>{
  "version": "1.8.0",
  "compilerOptions": {
    "rootDir": "src/",
    "outDir": "dist/",
    "target": "es5",
    "module": "system",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  }
}
</code>```

答:
The answer appears to be to add a file - I call mine typings.d.ts - in the root of your aurelia app - /src or whatever you've called it - with a single /// reference to the index.d.ts file in your typings folder. </p>

<p>Then everything plays nice. </p>

Body:
I have a TypeScript project in Visual Studio, with modules installed via systemjs. I have the following code:

app.ts

import { Aurelia } from 'aurelia-framework';

For example, hovering Aurelia and pressing F12 (Go to Definition) opens up the correct aurelia-framework.d.ts file installed by systemjs. However, when I click Build, I get the following output:

error TS2307: Build: Cannot find module 'aurelia-router'.

Here is my tsconfig for reference.

tsconfig.json

{
  "version": "1.8.0",
  "compilerOptions": {
    "rootDir": "src/",
    "outDir": "dist/",
    "target": "es5",
    "module": "system",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  }
}

Body:
The answer appears to be to add a file - I call mine typings.d.ts - in the root of your aurelia app - /src or whatever you've called it - with a single /// reference to the index.d.ts file in your typings folder.

Then everything plays nice.


问:
What template is loaded by Django?
I was following Django tutorial, and got stuck where it asked me to replace the default template for administrative part of the site with my own.  The problem was a typo in the template's name.  I suspected there must be a problem like that, but to troubleshoot the problem it'd be very helpful to see some kind of report from Django on what template it used to render a particular page.  Is there any way to do this?</p>

答:
First if you have set DEBUG = True django automatically gives you information about where django was looking for templates (in general and especially in case it didn't find one)

You should see something like this:

second you can add the popular django plugin django-debug-toolbar. It can show you for each request what templates were used and what their context was.

see: https://django-debug-toolbar.readthedocs.io/en/stable/panels.html#template

Title: What template is loaded by Django?


问:
How to filter JSON data based on multiple criteria in JavaScript?
I am trying to filter out all records that don't contain values from the 5 arrays: ssn, spn, smft, ssl, svtv. The output is not correct because it only works in cases where the lists contain 1 element. The output array becomes empty when they contain multiple elements. I am trying to get records that don't contain one of the values from each list (OR). I think it doesn't work because it checks if each record doesn't contain all values in each list (AND). Any idea how to fix this?

jsonData

```<code>[{"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},{"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}]
</code>```

query

```<code>ssn: ['T234834U', 'T23423423'],
spn: ['1014114', '21412342'],
smft: ['Sbasdfa', 'asdfaser'],
ssl: ['BB03', 'SFD04'],
svtv: ['Yes']
</code>```

Code

```<code>function getFiltered() {
    var query = {
        sn: ssn,
        pn: spn,
        mft: smft,
        sl: ssl,
        vtv: svtv
    }
    var filtered = find_in_object(jsonData, query)
}

function find_in_object(my_object, my_criteria) {
    return my_object.filter(function(obj) {
        return Object.keys(my_criteria).every(function(c) {
            return JSON.stringify(obj[c]).indexOf(my_criteria[c]) === -1
        })
    })
}
</code>```

答:
You can use every for AND and some for OR. In your case you want to go thru the list of keys (so every for AND) and then check if the value exists in the search array. indexOf should do the job:

let jsonData = [
  {"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},
  {"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}
]

let query = {
  mft: [],
  sl: ["GG08"],
  vtv: ["No"]
}
console.log(find_in_object(jsonData, query)); //returns one

let query2 = {
  sn: ['T234834U', 'T23423423'],
  pn: ['1014114', '21412342'],
  mft: ['Sbasdfa', 'asdfaser'],
  sl: ['BB03', 'SFD04'],
  vtv: ['Yes']
}
console.log(find_in_object(jsonData, query2)); //returns none

function find_in_object(my_array, my_criteria) {
  return my_array.filter(function(obj) {
    return Object.keys(my_criteria).every(function(key) {
      return (Array.isArray(my_criteria[key]) &&
        (my_criteria[key].some(function(criteria) {
          return (typeof obj[key] === 'string' && obj[key].indexOf(criteria) === -1)
        })) || my_criteria[key].length === 0);
    });
  });
}```

Edited to cover some edge cases.

Body:
I am trying to filter out all records that don't contain values from the 5 arrays: ssn, spn, smft, ssl, svtv. The output is not correct because it only works in cases where the lists contain 1 element. The output array becomes empty when they contain multiple elements. I am trying to get records that don't contain one of the values from each list (OR). I think it doesn't work because it checks if each record doesn't contain all values in each list (AND). Any idea how to fix this?

jsonData

[{"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},{"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}]

query

ssn: ['T234834U', 'T23423423'],
spn: ['1014114', '21412342'],
smft: ['Sbasdfa', 'asdfaser'],
ssl: ['BB03', 'SFD04'],
svtv: ['Yes']

Code

function getFiltered() {
    var query = {
        sn: ssn,
        pn: spn,
        mft: smft,
        sl: ssl,
        vtv: svtv
    }
    var filtered = find_in_object(jsonData, query)
}

function find_in_object(my_object, my_criteria) {
    return my_object.filter(function(obj) {
        return Object.keys(my_criteria).every(function(c) {
            return JSON.stringify(obj[c]).indexOf(my_criteria[c]) === -1
        })
    })
}

Body:
You can use every for AND and some for OR. In your case you want to go thru the list of keys (so every for AND) and then check if the value exists in the search array. indexOf should do the job:

let jsonData = [
  {"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},
  {"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}
]

let query = {
  mft: [],
  sl: ["GG08"],
  vtv: ["No"]
}
console.log(find_in_object(jsonData, query)); //returns one

let query2 = {
  sn: ['T234834U', 'T23423423'],
  pn: ['1014114', '21412342'],
  mft: ['Sbasdfa', 'asdfaser'],
  sl: ['BB03', 'SFD04'],
  vtv: ['Yes']
}
console.log(find_in_object(jsonData, query2)); //returns none

function find_in_object(my_array, my_criteria) {
  return my_array.filter(function(obj) {
    return Object.keys(my_criteria).every(function(key) {
      return (Array.isArray(my_criteria[key]) &&
        (my_criteria[key].some(function(criteria) {
          return (typeof obj[key] === 'string' && obj[key].indexOf(criteria) === -1)
        })) || my_criteria[key].length === 0);
    });
  });
}

Edited to cover some edge cases.


问:
jQuery not triggering .click function from a jQuery generated HTML tags
I have a button on my document, upon clicking will generate certain html tags.

```<code><a type="button" name="repbut" >Reply</a> //on button click

    <script type="text/javascript"> // this script will be executed
    $(document).ready(function(){
    $('a[name=repbut]').click(function(){
        var boxid=$(this).attr("id");
        $("#"+boxid+"1").html('<ul><li><div class="comment"><div class="comment-content"><div class="comment-meta-author">Post your reply</div><br><div class="comment-body"><div class="form-group"><label>Message</label><textarea id="reep" class="form-control" rows="2"></textarea><br><span id="'+boxid+'2"></span><a type="button" name="repcom" id="test" value="'+boxid+'" class="btn btn-primary pull-right">Reply</a></div><br></div></div></div></li></ul>');
    });
    });
    </script>
</code>```

The problem is when i click the generated button nothing happens, not even alert function.

```<code><a type="button" name="repcom" id="test" class="btn btn-primary pull-right">

<script type="text/javascript">
$('a[name=repcom]').click(function(){
        alert("yes"); // not triggered
        });
</script>
</code>```

Am i doing something wrong? i am new to jQuery.
Any help is appreciated.

答:
 $(document).ready(function(){
    $('a[name=repbut]').click(function(){
        var boxid=$(this).attr("id");
        $("#newhtml").html('

Post your reply

Message<textarea id="reep" class="form-control" rows="2"></textarea>
Reply

');
    });

     $(document).on('click','a[name=repcom]',function(){
     alert("yes =" +  $("#reep").val())
     })

    });

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Reply
<div id='newhtml'> </div></code>```

Body:
I have a button on my document, upon clicking will generate certain html tags.

Reply //on button click

The problem is when i click the generated button nothing happens, not even alert function.

Am i doing something wrong? i am new to jQuery.
Any help is appreciated.

Body:
 $(document).ready(function(){
    $('a[name=repbut]').click(function(){
        var boxid=$(this).attr("id");
        $("#newhtml").html('<ul><li><div class="comment"><div class="comment-content"><div class="comment-meta-author">Post your reply</div><br><div class="comment-body"><div class="form-group"><label>Message</label><textarea id="reep" class="form-control" rows="2"></textarea><br><span id="'+boxid+'2"></span><a type="button" name="repcom" id="test" value="'+boxid+'" class="btn btn-primary pull-right">Reply</a></div><br></div></div></div></li></ul>');
    });

     $(document).on('click','a[name=repcom]',function(){
     alert("yes =" +  $("#reep").val())
     })

    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a type="button" name="repbut" >Reply</a>
<div id='newhtml'> </div>


问:
Select data from Sybase database but only select the row with the highest sequence
I'm trying to select data from my database from the highest sequence number, I have been struggling with this for a while and cant get it to work.

The database has a lot of Columns with data. I only want data from the row with the highest sequence number to search in, because the data from lower sequences is not of any value for me. Unfortunately the rows from the lower sequences can not be deleted.

Database looks like this:

```<code>-----------------------------
| ID | SEQ | rest of the data
-----------------------------
| 1  |  1  | ..
| 1  |  2  | ....
| 2  |  1  | ..
| 1  |  3  | ....
| 3  |  1  | ..
| 1  |  2  | ....
| 4  |  1  | ........
</code>```

My question is, how can i select only the ID's with the highest sequence number and search in those rows with the WHERE clause?

答:
```<code>SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY ID ORDER BY SEQ DESC ) AS rn
  FROM   your_table t
)
WHERE  rn = 1
</code>```

or

```<code>SELECT ID,
       MAX( seq ) AS seq,
       MAX( other_column_1 ) KEEP ( DENSE_RANK LAST ORDER BY seq ) AS other_column_1,
       MAX( other_column_2 ) KEEP ( DENSE_RANK LAST ORDER BY seq ) AS other_column_2
      -- ...
FROM   your_table
GROUP BY id
</code>```

or

```<code>SELECT *
FROM   your_table t
WHERE  seq IN ( SELECT MAX( seq )
                FROM   your_table x
                WHERE  x.id = t.id )
</code>```

or

```<code>SELECT t.*
FROM   your_table t
       INNER JOIN ( SELECT id, MAX( seq ) AS seq
                    FROM   your_table
                    GROUP BY id ) x
       ON ( x.id = t.id AND x.seq = t.seq )
</code>```

Body:
I'm trying to select data from my database from the highest sequence number, I have been struggling with this for a while and cant get it to work.

The database has a lot of Columns with data. I only want data from the row with the highest sequence number to search in, because the data from lower sequences is not of any value for me. Unfortunately the rows from the lower sequences can not be deleted.

Database looks like this:

-----------------------------
| ID | SEQ | rest of the data
-----------------------------
| 1  |  1  | ..
| 1  |  2  | ....
| 2  |  1  | ..
| 1  |  3  | ....
| 3  |  1  | ..
| 1  |  2  | ....
| 4  |  1  | ........

My question is, how can i select only the ID's with the highest sequence number and search in those rows with the WHERE clause?

Body:
SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY ID ORDER BY SEQ DESC ) AS rn
  FROM   your_table t
)
WHERE  rn = 1

or

SELECT ID,
       MAX( seq ) AS seq,
       MAX( other_column_1 ) KEEP ( DENSE_RANK LAST ORDER BY seq ) AS other_column_1,
       MAX( other_column_2 ) KEEP ( DENSE_RANK LAST ORDER BY seq ) AS other_column_2
      -- ...
FROM   your_table
GROUP BY id

or

SELECT *
FROM   your_table t
WHERE  seq IN ( SELECT MAX( seq )
                FROM   your_table x
                WHERE  x.id = t.id )

or

SELECT t.*
FROM   your_table t
       INNER JOIN ( SELECT id, MAX( seq ) AS seq
                    FROM   your_table
                    GROUP BY id ) x
       ON ( x.id = t.id AND x.seq = t.seq )


问:
How to draw graphics/text on top of another application
I want to enhance an application, but there is no 3:e party API available.
So basically the idea is to draw graphics/text on top of the applications windows.

There are problems with z order, clipping, and directing mouse clicks either to my application or the other application.

What is an elegant way of doing this?

Example image here. It is a trading application where my application wants to add extra information into the trading application's windows.
[URL=http://img104.imageshack.us/my.php?image=windowontop.png][/URL]

答:
There are problems with z order,
  clipping, and directing mouse clicks
  either to my application or the other
  application.

These are all tasks that the window manager was designed to deal with. You should create a layered window on top of the apps' windows.

See also: Prevent repainting of window in C++


问:
How to add "-l" (ell) compiler flag in CMake
Work on Ubuntu 16

I used g++ main.cpp -lpq command for compiler my small project. Now I use Clion and wanna do same what I do with g++. But I can't add compiler flags in cmake file and get compile error.

cmake_minimum_required(VERSION 3.5.1)
project(day_g)

set(CMAKE_CXX_FLAGS "-lpq")

add_definitions(-lpq)

message("CMAKE_CXX_FLAGS is ${CMAKE_CXX_FLAGS}")

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(day_g ${SOURCE_FILES})
```

<p>Also I run only cmake file and get <code>CMAKE_CXX_FLAGS</code> with <em>-lpq</em> flag.</p>

<pre class="lang-js prettyprint-override"><code>CMAKE_CXX_FLAGS is -lpq
-- Configuring done
-- Generating done
</code>```

How properly add compiler flags to cmake file?

答:
-lq is not a compiler flag (CFLAGS) but a linker flag.

To pass a library in a CMake project you should use:

```<code>target_link_libraries(target_name libraries...)
</code>```

Note that if you specify 'q' as library the project will link with libq.a or, if you are on windows q.dll.

... in your CMakeLists.txt the correct line to add is:

```<code>target_link_libraries(day_g pq)
</code>```

Note also that when you add a CFLAG you should also "remember" the previous ones that may be added by libraries or by your platform, ie:

```<code>set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")
</code>```

To check the exact flags cmake is passing to compiler or linker you can always run, from the build directory, the following command:

```<code>make VERBOSE=1
</code>```

Body:
Work on Ubuntu 16

I used g++ main.cpp -lpq command for compiler my small project. Now I use Clion and wanna do same what I do with g++. But I can't add compiler flags in cmake file and get compile error.

cmake_minimum_required(VERSION 3.5.1)
project(day_g)

set(CMAKE_CXX_FLAGS "-lpq")

add_definitions(-lpq)

message("CMAKE_CXX_FLAGS is ${CMAKE_CXX_FLAGS}")

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(day_g ${SOURCE_FILES})

Also I run only cmake file and get CMAKE_CXX_FLAGS with -lpq flag.

CMAKE_CXX_FLAGS is -lpq
-- Configuring done
-- Generating done

How properly add compiler flags to cmake file?

Body:
-lq is not a compiler flag (CFLAGS) but a linker flag.

To pass a library in a CMake project you should use:

target_link_libraries(target_name libraries...)

Note that if you specify 'q' as library the project will link with libq.a or, if you are on windows q.dll.

... in your CMakeLists.txt the correct line to add is:

target_link_libraries(day_g pq)

Note also that when you add a CFLAG you should also "remember" the previous ones that may be added by libraries or by your platform, ie:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")

To check the exact flags cmake is passing to compiler or linker you can always run, from the build directory, the following command:

make VERBOSE=1


问:
Values vary after conversion from excel
I am trying to get values from one of the column from excel and i am facing strange issue that i cannot overcome so far.

Excel cells text we working on

Column format is set to: [h]:mm:ss so means hours could exceed 12/24.

When i am getting that values they are in double format as excel probbaly stores it in that way therefore i decided to write function to convert it back again to hours, minutes and seconds so i did that function:

```<code>   Public Shared Function parseExcelHour(cellInput As String) As String
    Dim excelHour As Double = 0
    Dim hour As Integer
    Dim min As Integer
     Dim sec As Integer
    Try
        excelHour = [Double].Parse(cellInput)
    Catch
    End Try
    sec = CInt((excelHour * 1440 * 60) Mod 60)
    min = CInt((excelHour * 1440) Mod 60)
    'mod (%) takes only the remainder as an int (if 5/4 = 1.25 , % only takes the number 1 that cannot be divided into an integer)
    hour = CInt((excelHour * 1440) / 60)
    ' with the int cast you get only an integer.
    Return hour & ":" & min & ":" & sec
End Function
</code>```

However when i see the results, they are vary between excel and what i get after conversion. For three of them hours are either -1 or +1 if you compare. Also in one case we have additional + 1 minute. I suppose there is wrong hour calculation but i could be in wrong. See on screeshoot:

Results

Does anyone knows why i got those differences? Is that because i am missing something within my method or something else.

答:
Excel stores a full Datetime equivalent as one double. The part before the decimal point is the days (since 1.1.1900; 1.1.1904 on Mac; note the bug that 1900 is faultily cosnider a leap year in Excel).

The part after is the time of the day, wich is what you apparently want:
https://stackoverflow.com/a/981865/3346583

What you are seeing in excel is meerely a ToString Foramting of the double value. Same way DateTime.ToString() would give you a string representation of whatever value is actually stored (most often a realy big unsigned int, with the ticks since a date).

A difference in full hours sounds like it might be a Timezone issue. But I am not aware that Excel stores Timezones in the first place (or what default timezone it asumes).

Title: Values vary after conversion from excel

Body:
I am trying to get values from one of the column from excel and i am facing strange issue that i cannot overcome so far.

Excel cells text we working on

Column format is set to: [h]:mm:ss so means hours could exceed 12/24.

When i am getting that values they are in double format as excel probbaly stores it in that way therefore i decided to write function to convert it back again to hours, minutes and seconds so i did that function:

   Public Shared Function parseExcelHour(cellInput As String) As String
    Dim excelHour As Double = 0
    Dim hour As Integer
    Dim min As Integer
     Dim sec As Integer
    Try
        excelHour = [Double].Parse(cellInput)
    Catch
    End Try
    sec = CInt((excelHour * 1440 * 60) Mod 60)
    min = CInt((excelHour * 1440) Mod 60)
    'mod (%) takes only the remainder as an int (if 5/4 = 1.25 , % only takes the number 1 that cannot be divided into an integer)
    hour = CInt((excelHour * 1440) / 60)
    ' with the int cast you get only an integer.
    Return hour & ":" & min & ":" & sec
End Function

However when i see the results, they are vary between excel and what i get after conversion. For three of them hours are either -1 or +1 if you compare. Also in one case we have additional + 1 minute. I suppose there is wrong hour calculation but i could be in wrong. See on screeshoot:

Results

Does anyone knows why i got those differences? Is that because i am missing something within my method or something else.


问:
Tensorflow classification not running correctly with multiprocessing, but is with multithreading
I have an app that should be classifying images in parallel every 5 seconds. I want to get around the Global Interpreter Lock, so I am trying to use the multiprocessing library rather than multithreading. More or less, my code looks like this:

```<code># Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
                   in tf.gfile.GFile("/home/aneksteind/tensorflowSource/output_labels.txt")]

# Unpersists graph from file
f = tf.gfile.FastGFile("/home/aneksteind/tensorflowSource/output_graph.pb", 'rb')
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')

sess = tf.Session()
mainGraph = sess.graph

# a function that starts a thread for each region of interest to classify
def checkFrames():
    timer = threading.Timer(5.0, checkFrames)
    timer.daemon = True
    timer.start()
    if(started):
        index = 0
        threads = []
        for roi in rois:
            p = Process(target=containsPlane, args=(frame, roi, index))
            p.daemon = True
            p.start()
            index += 1

def containsPlane(frame, roi, index):
    tempGraph = mainGraph
    tempSession = tf.Session(graph=tempGraph)
    tempTensor = tempSession.graph.get_tensor_by_name('final_result:0')
    predictions = tempSession.run(tempTensor, \
             {'DecodeJpeg:0': subframe})

    ...
</code>```

When I am running this code using a Thread, it runs just fine. It prints out each preliminary message/warnings before classifying for the first time only once and classifies each image, but not in parallel.

When I change to a Process, the preliminary messages/warnings repeatedly show up and the images are never classified. Could this be due to the sessions sharing a state of some sort?  What can I do differently so that multiple images are classified in parallel?

答:
From TensorFlow doc: Creates a new TensorFlow session.

  If no graph argument is specified when constructing the session, the default graph will be launched in the session. If you are using more than one graph (created with tf.Graph() in the same process, you will have to use different sessions for each graph, but each graph can be used in multiple sessions. In this case, it is often clearer to pass the graph to be launched explicitly to the session constructor.

I think you should give graph=tf.Graph() as a parameter to def containsPlane(...). Try to become independent from global vars and try to create the session inside def containsPlane(...).

You have three arguments args=(frame, roi, index), but I did not see any using of them in def containsPlane(..)?

Question: ... running this code using a Thread, it runs just fine. ..., but not in parallel.

  for roi in rois:
     threads.append(threading.Thread(...

You start roi Threads, so I can't imagin why executing is not in parallel?

Your attemp to use multiprocessing this way will fail as you should not start more processes as your machine has cores.
Starting more will result in swaping and therefore reduce the overall performance.

Question: how could I tell which variable is the one that needs to be a multiprocess.Value?

All not readonly

Didn't understand why you doing the following:

```<code>sess = tf.Session()
mainGraph = sess.graph
# ...
def containsPlane(frame, roi, index):
    tempGraph = mainGraph
    tempSession = tf.Session(graph=tempGraph)
</code>```

Why not simple:

```<code>def containsPlane(frame, roi, index):
    tempSession = tf.Session()
</code>```

Body:
I have an app that should be classifying images in parallel every 5 seconds. I want to get around the Global Interpreter Lock, so I am trying to use the multiprocessing library rather than multithreading. More or less, my code looks like this:

# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
                   in tf.gfile.GFile("/home/aneksteind/tensorflowSource/output_labels.txt")]

# Unpersists graph from file
f = tf.gfile.FastGFile("/home/aneksteind/tensorflowSource/output_graph.pb", 'rb')
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')

sess = tf.Session()
mainGraph = sess.graph

# a function that starts a thread for each region of interest to classify
def checkFrames():
    timer = threading.Timer(5.0, checkFrames)
    timer.daemon = True
    timer.start()
    if(started):
        index = 0
        threads = []
        for roi in rois:
            p = Process(target=containsPlane, args=(frame, roi, index))
            p.daemon = True
            p.start()
            index += 1

def containsPlane(frame, roi, index):
    tempGraph = mainGraph
    tempSession = tf.Session(graph=tempGraph)
    tempTensor = tempSession.graph.get_tensor_by_name('final_result:0')
    predictions = tempSession.run(tempTensor, \
             {'DecodeJpeg:0': subframe})

    ...

When I am running this code using a Thread, it runs just fine. It prints out each preliminary message/warnings before classifying for the first time only once and classifies each image, but not in parallel.

When I change to a Process, the preliminary messages/warnings repeatedly show up and the images are never classified. Could this be due to the sessions sharing a state of some sort?  What can I do differently so that multiple images are classified in parallel?

Body:
From TensorFlow doc: Creates a new TensorFlow session.

  If no graph argument is specified when constructing the session, the default graph will be launched in the session. If you are using more than one graph (created with tf.Graph() in the same process, you will have to use different sessions for each graph, but each graph can be used in multiple sessions. In this case, it is often clearer to pass the graph to be launched explicitly to the session constructor.

I think you should give graph=tf.Graph() as a parameter to def containsPlane(...). Try to become independent from global vars and try to create the session inside def containsPlane(...).

You have three arguments args=(frame, roi, index), but I did not see any using of them in def containsPlane(..)?

Question: ... running this code using a Thread, it runs just fine. ..., but not in parallel.

  for roi in rois:
     threads.append(threading.Thread(...

You start roi Threads, so I can't imagin why executing is not in parallel?

Your attemp to use multiprocessing this way will fail as you should not start more processes as your machine has cores.
Starting more will result in swaping and therefore reduce the overall performance.

Question: how could I tell which variable is the one that needs to be a multiprocess.Value?

All not readonly

Didn't understand why you doing the following:

sess = tf.Session()
mainGraph = sess.graph
# ...
def containsPlane(frame, roi, index):
    tempGraph = mainGraph
    tempSession = tf.Session(graph=tempGraph)

Why not simple:

def containsPlane(frame, roi, index):
    tempSession = tf.Session()


问:
scalaz - type mismatch
I am facing 'type mismatch' issue, I tried more than two hours even not resolved because I am not good in scala.

Using:
   Scala 2.11.7

Error:

```<code>[error] AlertUUU.scala:297: type mismatch;
[error]  found   : scalaz.Validation StartTimeOverlap.type, OnPeakRange]
[error]  required: scalaz.Validation[String,OnPeakRange]
[error]       p.onPeakRanges.find(x ⇒ opr.startTime >= x.startTime && opr.startTime <= x.stopTime).map
</code>```

(_.startTimeOverlap).getOrElse(opr.success)

Code:

```<code>  def startTimeMustNotOverlap(p: UUUPeriod, opr: OnPeakRange): Validation[String, OnPeakRange] =
  p.onPeakRanges.find(x ⇒ opr.startTime >= x.startTime && opr.startTime <= x.stopTime).map(_.startTimeOverlap).getOrElse(opr.success)

case class OnPeakRange(
                        startTime: Int,
                        stopTime: Int,
                        originalThreshold: Int) extends OnPeakRangeT with OnPeakRangeValidations {
  def startTimeOverlap = OnPeakRange.StartTimeOverlap.failure
  def stopTimeOverlap = OnPeakRange.StopTimeOverlap.failure
  def allHoursPeakNotFullDay = OnPeakRange.AllHoursPeakNotFullDay.failure
}

case object StartTimeOverlap extends ValidationKey

trait ValidationKey {
  def failNel = this.toString.failureNel
  def nel = NonEmptyList(this.toString)
  def fail = this.toString.failure
}
</code>```

答:
The error explains everything, startTimeMustNotOverlap should return a Validation[String, OnPeakRange].

Your Success case is of type OnPeakRange, your Failure type is of case OnPeakRange.StartTimeOverlap instead of a String.

You have to just change the type of startTimeOverlap to String or change the Validation type.

def startTimeMustNotOverlap(p: Period, opr: OnPeakRange): Validation[String, OnPeakRange] =
  p.onPeakRanges.find(
    x => opr.startTime >= x.startTime && opr.startTime <= x.stopTime
  ).fold(opr.success[String])(_.startTimeOverlap)

case class Period(onPeakRanges: List[OnPeakRange] = Nil)
case class OnPeakRange(startTime: Int, stopTime: Int){
  def startTimeOverlap = "...".failure
}
```

Title: scalaz - type mismatch

Body:
I am facing 'type mismatch' issue, I tried more than two hours even not resolved because I am not good in scala.

Using:
   Scala 2.11.7

Error:

[error] AlertUUU.scala:297: type mismatch;
[error]  found   : scalaz.Validation StartTimeOverlap.type, OnPeakRange]
[error]  required: scalaz.Validation[String,OnPeakRange]
[error]       p.onPeakRanges.find(x ⇒ opr.startTime >= x.startTime && opr.startTime <= x.stopTime).map

(_.startTimeOverlap).getOrElse(opr.success)

Code:

  def startTimeMustNotOverlap(p: UUUPeriod, opr: OnPeakRange): Validation[String, OnPeakRange] =
  p.onPeakRanges.find(x ⇒ opr.startTime >= x.startTime && opr.startTime <= x.stopTime).map(_.startTimeOverlap).getOrElse(opr.success)

case class OnPeakRange(
                        startTime: Int,
                        stopTime: Int,
                        originalThreshold: Int) extends OnPeakRangeT with OnPeakRangeValidations {
  def startTimeOverlap = OnPeakRange.StartTimeOverlap.failure
  def stopTimeOverlap = OnPeakRange.StopTimeOverlap.failure
  def allHoursPeakNotFullDay = OnPeakRange.AllHoursPeakNotFullDay.failure
}

case object StartTimeOverlap extends ValidationKey

trait ValidationKey {
  def failNel = this.toString.failureNel
  def nel = NonEmptyList(this.toString)
  def fail = this.toString.failure
}


问:
Cassandra export/forward data only once
I have the requirement to forward data at certain intervals from my system to an external system. To do this, I already stored all rows in a table. Already forwarded data should not be exported again.

The idea is to memorize the last export time on client side and export the following records the next time. Old rows are deleted after a successful export.

```<code>CREATE TABLE export(
    id int,
    import_date_time timestamp,
    data text,
    PRIMARY KEY (id, import_date_time)
) WITH CLUSTERING ORDER BY (import_date_time DESC)

insert into export(id, import_date_time, data) values (1, toUnixTimestamp(now()), 'content')

select * from export where id = 1 and import_date_time > '2017-03-30 16:22:37'

delete from export where id = 1 and import_date_time <= '2017-03-30 16:22:37'
</code>```

Has anyone already implemented similar or do you have a different
solution?

If possible, I do not need an id for the request because I want to
    export all data

答:
If you used fixed partition key value (id = 1), then all the insert, select and delete will happen on a same node (If RF=1) over and over. And also for every delete cassandra create a tombstone entry, when you execute select query cassandra needs to merge each entry. So your select query performance will degrade.

So instead of having fixed value, use dynamic value like the below one :

```<code>CREATE TABLE export(
    hour int,
    day int,
    month int,
    year int,
    import_date_time timestamp,
    data text,
    PRIMARY KEY ((hour, day, month, year), import_date_time)
) WITH CLUSTERING ORDER BY (import_date_time DESC);
</code>```

Here you can insert the value of hour, day, month, year extracted from import_date_time

You need to take care of two case When selecting data :

Previous export time and current export time both at same hour.

Both time are not inside same hour.

For case one you need only one query and for case two you have to execute two query.

Example Query :

```<code>SELECT * FROM export WHERE hour = 16 AND day = 30 AND month = 3 AND year = 2017 AND import_date_time > '2017-03-30 16:22:37';
</code>```

Title: Cassandra export/forward data only once

Body:
I have the requirement to forward data at certain intervals from my system to an external system. To do this, I already stored all rows in a table. Already forwarded data should not be exported again.

The idea is to memorize the last export time on client side and export the following records the next time. Old rows are deleted after a successful export.

CREATE TABLE export(
    id int,
    import_date_time timestamp,
    data text,
    PRIMARY KEY (id, import_date_time)
) WITH CLUSTERING ORDER BY (import_date_time DESC)

insert into export(id, import_date_time, data) values (1, toUnixTimestamp(now()), 'content')

select * from export where id = 1 and import_date_time > '2017-03-30 16:22:37'

delete from export where id = 1 and import_date_time <= '2017-03-30 16:22:37'

Has anyone already implemented similar or do you have a different
solution?

If possible, I do not need an id for the request because I want to
    export all data

Body:
If you used fixed partition key value (id = 1), then all the insert, select and delete will happen on a same node (If RF=1) over and over. And also for every delete cassandra create a tombstone entry, when you execute select query cassandra needs to merge each entry. So your select query performance will degrade.

So instead of having fixed value, use dynamic value like the below one :

CREATE TABLE export(
    hour int,
    day int,
    month int,
    year int,
    import_date_time timestamp,
    data text,
    PRIMARY KEY ((hour, day, month, year), import_date_time)
) WITH CLUSTERING ORDER BY (import_date_time DESC);

Here you can insert the value of hour, day, month, year extracted from import_date_time

You need to take care of two case When selecting data :

Previous export time and current export time both at same hour.

Both time are not inside same hour.

For case one you need only one query and for case two you have to execute two query.

Example Query :

SELECT * FROM export WHERE hour = 16 AND day = 30 AND month = 3 AND year = 2017 AND import_date_time > '2017-03-30 16:22:37';


问:
Transfer of operations based on if else conditions
Thanks in advance. I am writing this in great detail. So dont panic looking at the length of this message.

I have a page called retrievefieldex11.29.2.56.php. Fields that need to be considered for this problem here is the ID field (name = usersubmit) the Key(name = key) field. Now when the user enters his id( name = usersubmit) and if he does not enter the key value in the key field which I am checking by using this condition if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key'] == ""))
It should be directed to the same page that is retrievefieldex11.29.2.56.php. And for this I am using the

```<code><form name="retrieve.php" action="retrievefieldex11.29.2.56.php" method="POST">
</code>```

Statement so that it postbacks to the same page and performs operations to retrieve records from the database and print it on the same page.

```<code>Database code to retrieve rows
Print rows on the same page.
</code>```

Now if the user enters into both id fields and the key field, I am using this statement for checking the condition.

```<code>else if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key']))
</code>```

then the page should be redirected to another page where in the following operation is carried out.

```<code>header( 'Location: Decryption.php' ) ;
</code>```

In the Decryption.php page part of the code is as follows

$userId = $_POST['usersubmit'];

[COLOR="red"]This value is not being fetched from the previous page.[/COLOR]. I need this page to be fetched from the previous page

Rest of the Database code to retrieve values from the table.

My problem is that when I am testing for the part where the user enters his id but not the key field the database operations are being performed. However when the user enters his id and the key, [COLOR="Red"]I am being redirected to the Decryption page but the ID value ( name = usersubmit [/COLOR]) is not being transferred from the previous page to the Decryption page. Please suggest me how do I deal this?

I hope that made sense. My whole problem would make further sense if you look at this whole program together. Please help. Thanks in advance.

Total code

```<code><html>
<head>
</head>

<body>
<form name="retrieve.php" action="retrievefieldex11.29.2.56.php" method="POST">
Enter your ID<input name="usersubmit" type="text"> <br>

<table><tr>
<td><b>Key size in bits: </b></td>

<td><select name="keySize">
<option value="128" selected="selected">128</option>
<option value="192">192</option>
<option value="256">256</option>
</select></td>
</tr>

<tr>
<td><b>Key in hex: </b></td>
<td><input type="text" size="66" name="key"></td></tr>

<tr>
<td><b>Ciphertext in hex: </b></td>
<td><input type="text" size="66" name="ciphertext"></td>

</tr>

</table>
<?php
mysql_connect("localhost","root","");
mysql_select_db("encryption") or die(mysql_error());
$userId = $_POST['usersubmit'];
if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key'] == ""))
{

 $query = mysql_query("select * from employee_details where id = '$userId'");
  if($row=mysql_fetch_assoc($query))
    {
     echo '<tr>';
     foreach($row as $value)
     echo '<td>'.$value.'</td>';
     echo '</tr>';
    }
  else
  echo "No rows returned";
  }
 else if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key']))
 {

   header( 'Location: Decryption.php' ) ;

In decryption page

<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
mysql_connect("localhost","root","");
mysql_select_db("encryption") or die(mysql_error());
$userId = $_POST['usersubmit'];
$columname = "ciphertext";
$tablename = "employee_details";

 function getField($field, $tbl_name, $condition)
 {

 $result = mysql_query("SELECT $field FROM $tbl_name WHERE id = ".$condition);
 return @mysql_result($result, 0);
 }

 $myValue = getField($columname,$tablename,$userId);
 echo "$myValue";
 echo "<br>";

?>

 }

?>
<br>
<input name="submit" type="submit" value="Submit"><table>
</table>
</form>
</body>
</html>
</code>```

答:
If you send a location header, the browser sends a GET request for that URI and it does not resubmit any data from the last request.
One solution could be to add the POSTed data as GET parameters to the URL you send as new location. Of course you must change Decryption.php to use $_GET then.
Another solution: Instead of sending a location header, just include Decryption.php right there in your script.

Body:
Thanks in advance. I am writing this in great detail. So dont panic looking at the length of this message.

I have a page called retrievefieldex11.29.2.56.php. Fields that need to be considered for this problem here is the ID field (name = usersubmit) the Key(name = key) field. Now when the user enters his id( name = usersubmit) and if he does not enter the key value in the key field which I am checking by using this condition if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key'] == ""))
It should be directed to the same page that is retrievefieldex11.29.2.56.php. And for this I am using the

<form name="retrieve.php" action="retrievefieldex11.29.2.56.php" method="POST">

Statement so that it postbacks to the same page and performs operations to retrieve records from the database and print it on the same page.

Database code to retrieve rows
Print rows on the same page.

Now if the user enters into both id fields and the key field, I am using this statement for checking the condition.

else if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key']))

then the page should be redirected to another page where in the following operation is carried out.

header( 'Location: Decryption.php' ) ;

In the Decryption.php page part of the code is as follows

$userId = $_POST['usersubmit'];

[COLOR="red"]This value is not being fetched from the previous page.[/COLOR]. I need this page to be fetched from the previous page

Rest of the Database code to retrieve values from the table.

My problem is that when I am testing for the part where the user enters his id but not the key field the database operations are being performed. However when the user enters his id and the key, [COLOR="Red"]I am being redirected to the Decryption page but the ID value ( name = usersubmit [/COLOR]) is not being transferred from the previous page to the Decryption page. Please suggest me how do I deal this?

I hope that made sense. My whole problem would make further sense if you look at this whole program together. Please help. Thanks in advance.

Total code

<form name="retrieve.php" action="retrievefieldex11.29.2.56.php" method="POST">
Enter your ID<input name="usersubmit" type="text">

Key size in bits:

<select name="keySize">
<option value="128" selected="selected">128</option>
<option value="192">192</option>
<option value="256">256</option>
</select>

Key in hex:
<input type="text" size="66" name="key">

Ciphertext in hex:
<input type="text" size="66" name="ciphertext">

<?php
mysql_connect("localhost","root","");
mysql_select_db("encryption") or die(mysql_error());
$userId = $_POST['usersubmit'];
if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key'] == ""))
{

 $query = mysql_query("select * from employee_details where id = '$userId'");
  if($row=mysql_fetch_assoc($query))
    {
     echo '
';
     foreach($row as $value)
     echo ''.$value.'	';
     echo '
';
    }
  else
  echo "No rows returned";
  }
 else if (($_SERVER['REQUEST_METHOD'] == 'POST') && ($_POST['key']))
 {

   header( 'Location: Decryption.php' ) ;

In decryption page

<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
mysql_connect("localhost","root","");
mysql_select_db("encryption") or die(mysql_error());
$userId = $_POST['usersubmit'];
$columname = "ciphertext";
$tablename = "employee_details";

 function getField($field, $tbl_name, $condition)
 {

 $result = mysql_query("SELECT $field FROM $tbl_name WHERE id = ".$condition);
 return @mysql_result($result, 0);
 }

 $myValue = getField($columname,$tablename,$userId);
 echo "$myValue";
 echo "
";

?>

 }

?>

<input name="submit" type="submit" value="Submit">

</form>


问:
Trying to obtain gray images from webcam using Visual Basic, OpenCV and EmguCV
I am learning about OpenCV and EmguCV. I succeed by trying to obtain images from my webcam and now I'm trying to obtain that images in a gray scale.

My purpose after achieve this, is to recognize and track colors, so im trying to obtain the image in a HVS format to filter the image to display only the color Im looking for in white, and the rest of the image in black (I hope you understand my explanation)

Now, I only want to obtain the image from my webcam in that gray scale using the following code:

```<code>Imports Emgu.CV

Imports Emgu.CV.Util

Imports Emgu.CV.Structure

Imports System.Drawing

Public Class Form1

Dim capturez As Capture = New Capture
Dim radius As Decimal = 50.0F
Dim x As Decimal
Dim y As Decimal

Private Sub Timer1_Tick() Handles Timer1.Tick

    'Define x and y to determinate the position of the circle in the PictureBox
    x = PictureBox1.Width / 2 - radius
    y = PictureBox1.Height / 2 - radius

    'PointF type defines the X and Y position of the future circle in the PictureBox
    Dim point1 As New PointF(x, y)
    Dim circle As CircleF = New CircleF(point1, radius)
    Dim img As Image(Of Bgr, Byte) = capturez.QueryFrame()

    'Convert camera capture from BGR to HVS
    Dim hvs_frame As Image(Of Hsv, Byte) = img.Convert(Of Hsv, Byte)()

    'Obtain the three channels that compose the HVS image (hue, saturation and value)
    Dim channels As Image(Of Gray, Byte)() = hvs_frame.Split()

    'Remove all pixels from the hue channel that are not in the range [40, 60]
    CvInvoke.cvInRangeS(channels(0), New Gray(200).MCvScalar, New Gray(255).MCvScalar, channels(0))

    'Display converted frame
    PictureBox1.Image = channels(0).ToBitmap()

    'When commenting the .CopyBlank() property, the back color of the PictureBox remains transparent
    'When uncomment this, the back color of the PictureBox becomes black
    Dim imageCircle As Image(Of Bgr, Byte) = img '.CopyBlank()
    imageCircle.Draw(circle, New Bgr(Color.Brown), 2)
    PictureBox1.Image = imageCircle.ToBitmap()
End Sub
</code>```

With this code, I am only obtaining the image in BGR, and I don't know why, because I am specifying in the 'PictureBox1.Image' that I want the image in that gray scale.

Please help me =(

I'm using OpenCV 2.4.9 and EmguCV 2.4.0 ... if needed

Thanks a lot!

答:
Currently you are capturing the image in color (BGR) so you can't just show one channel in your Picturebox as this won't be a GrayScale image (it's the Blue channel, since it's a BGR image). You can solve this in two ways.

The first option is to specifically retrieve the frame from your camera in GrayScale. You can achieve this like this:

```<code>Dim imgGrayscale As Image(Of Gray, Byte) = capturez.RetrieveGrayFrame()
</code>```

The other option is to convert your image to GrayScale after you've retrieved it from the webcam capture. You can achieve this like this:

```<code>Dim img As Image(Of Bgr, Byte) = capturez.QueryFrame()
Dim imgGrayscale As Image(Of Gray, Byte) = img.Convert(Of Gray, Byte)()
</code>```

Note that from this moment you will be working with a GrayScale image, which will impact the rest of your code (i.e. you will not have 3 channels anymore, etc.). Therefore the second option may be more suitable for you, as you will now have a Bgr and a GrayScale. You can now still use the Bgr image for your HSV conversion etc.

You can now show the GrayScale image like this:

```<code>PictureBox1.Image = imgGrayscale.ToBitmap()
</code>```

EDIT to threshold one color, instead of converting to grayscale:

If you want to extract one color from the image, you can't use Grayscale, even though the result will be a one channel image. This is because you need all channel values to extract the right color. Follow the following steps:

Retrieve you Bgr image and convert it to Hsv as you did.

Don't split your image into three channels, but just create a new empty image to store your color threshold result in

Call the CvInvoke.InRange function, but apply the scalar to all three HSV channels. I recommend the use of InRange and not InRangeS as the latter is from OpenCV 1.X.

The InRange function works as follows: the MCvScalars represent the bounds of your color values in HSV range. It checks each pixel and compares if it is within the scalar values you stated. If it is, it will get a 255 pixel value (white) and otherwise 0 (black). That will give you a thresholded image.

If you want to extract more ranges of colors, you can add more CvInvoke.Inrange methods and add the different results with a CvInvoke.Add function later.

Experiment with the MCvScalar bounds you set to extract your color if they don't give you the right result. Also, if you want to obtain a different color, modify the bounds. You can use color pickers to retrieve the HSV values of certain color. Even a color picker in MS Paint will give you the Hue/Sat/Lum values, but you have to convert these (they are on a different scale, MS Paint 0-239 and OpenCV 0-179). So convert them by multiplying the levels by 180/240.

You will get something like this:

```<code>` Get the webcam frame
Dim webcam_image As Mat
webcam_image = capturez.QueryFrame()

` Get an empty HSV image and threshold image
Dim HSV_img As New Mat(webcam_image.Size, DepthType.Cv8U, 3)
Dim threshold_img As New Mat(webcam_image.Size, DepthType.Cv8U, 1)

' Convert camera capture from BGR to HVS
CvInvoke.CvtColor(webcam_image, HSV_img, ColorConversion.Bgr2Hsv)

` Threshold the yellow colors only (please adopt the scalar values to whatever values suit your needs)
CvInvoke.InRange(HSV_img, New ScalarArray(New MCvScalar(20, 100, 100)), New ScalarArray(New MCvScalar(30, 255, 255)), threshold_img)
</code>```

Body:
I am learning about OpenCV and EmguCV. I succeed by trying to obtain images from my webcam and now I'm trying to obtain that images in a gray scale.

My purpose after achieve this, is to recognize and track colors, so im trying to obtain the image in a HVS format to filter the image to display only the color Im looking for in white, and the rest of the image in black (I hope you understand my explanation)

Now, I only want to obtain the image from my webcam in that gray scale using the following code:

Imports Emgu.CV

Imports Emgu.CV.Util

Imports Emgu.CV.Structure

Imports System.Drawing

Public Class Form1

Dim capturez As Capture = New Capture
Dim radius As Decimal = 50.0F
Dim x As Decimal
Dim y As Decimal

Private Sub Timer1_Tick() Handles Timer1.Tick

    'Define x and y to determinate the position of the circle in the PictureBox
    x = PictureBox1.Width / 2 - radius
    y = PictureBox1.Height / 2 - radius

    'PointF type defines the X and Y position of the future circle in the PictureBox
    Dim point1 As New PointF(x, y)
    Dim circle As CircleF = New CircleF(point1, radius)
    Dim img As Image(Of Bgr, Byte) = capturez.QueryFrame()

    'Convert camera capture from BGR to HVS
    Dim hvs_frame As Image(Of Hsv, Byte) = img.Convert(Of Hsv, Byte)()

    'Obtain the three channels that compose the HVS image (hue, saturation and value)
    Dim channels As Image(Of Gray, Byte)() = hvs_frame.Split()

    'Remove all pixels from the hue channel that are not in the range [40, 60]
    CvInvoke.cvInRangeS(channels(0), New Gray(200).MCvScalar, New Gray(255).MCvScalar, channels(0))

    'Display converted frame
    PictureBox1.Image = channels(0).ToBitmap()

    'When commenting the .CopyBlank() property, the back color of the PictureBox remains transparent
    'When uncomment this, the back color of the PictureBox becomes black
    Dim imageCircle As Image(Of Bgr, Byte) = img '.CopyBlank()
    imageCircle.Draw(circle, New Bgr(Color.Brown), 2)
    PictureBox1.Image = imageCircle.ToBitmap()
End Sub

With this code, I am only obtaining the image in BGR, and I don't know why, because I am specifying in the 'PictureBox1.Image' that I want the image in that gray scale.

Please help me =(

I'm using OpenCV 2.4.9 and EmguCV 2.4.0 ... if needed

Thanks a lot!

Body:
Currently you are capturing the image in color (BGR) so you can't just show one channel in your Picturebox as this won't be a GrayScale image (it's the Blue channel, since it's a BGR image). You can solve this in two ways.

The first option is to specifically retrieve the frame from your camera in GrayScale. You can achieve this like this:

Dim imgGrayscale As Image(Of Gray, Byte) = capturez.RetrieveGrayFrame()

The other option is to convert your image to GrayScale after you've retrieved it from the webcam capture. You can achieve this like this:

Dim img As Image(Of Bgr, Byte) = capturez.QueryFrame()
Dim imgGrayscale As Image(Of Gray, Byte) = img.Convert(Of Gray, Byte)()

Note that from this moment you will be working with a GrayScale image, which will impact the rest of your code (i.e. you will not have 3 channels anymore, etc.). Therefore the second option may be more suitable for you, as you will now have a Bgr and a GrayScale. You can now still use the Bgr image for your HSV conversion etc.

You can now show the GrayScale image like this:

PictureBox1.Image = imgGrayscale.ToBitmap()

EDIT to threshold one color, instead of converting to grayscale:

If you want to extract one color from the image, you can't use Grayscale, even though the result will be a one channel image. This is because you need all channel values to extract the right color. Follow the following steps:

Retrieve you Bgr image and convert it to Hsv as you did.

Don't split your image into three channels, but just create a new empty image to store your color threshold result in

Call the CvInvoke.InRange function, but apply the scalar to all three HSV channels. I recommend the use of InRange and not InRangeS as the latter is from OpenCV 1.X.

The InRange function works as follows: the MCvScalars represent the bounds of your color values in HSV range. It checks each pixel and compares if it is within the scalar values you stated. If it is, it will get a 255 pixel value (white) and otherwise 0 (black). That will give you a thresholded image.

If you want to extract more ranges of colors, you can add more CvInvoke.Inrange methods and add the different results with a CvInvoke.Add function later.

Experiment with the MCvScalar bounds you set to extract your color if they don't give you the right result. Also, if you want to obtain a different color, modify the bounds. You can use color pickers to retrieve the HSV values of certain color. Even a color picker in MS Paint will give you the Hue/Sat/Lum values, but you have to convert these (they are on a different scale, MS Paint 0-239 and OpenCV 0-179). So convert them by multiplying the levels by 180/240.

You will get something like this:

` Get the webcam frame
Dim webcam_image As Mat
webcam_image = capturez.QueryFrame()

` Get an empty HSV image and threshold image
Dim HSV_img As New Mat(webcam_image.Size, DepthType.Cv8U, 3)
Dim threshold_img As New Mat(webcam_image.Size, DepthType.Cv8U, 1)

' Convert camera capture from BGR to HVS
CvInvoke.CvtColor(webcam_image, HSV_img, ColorConversion.Bgr2Hsv)

` Threshold the yellow colors only (please adopt the scalar values to whatever values suit your needs)
CvInvoke.InRange(HSV_img, New ScalarArray(New MCvScalar(20, 100, 100)), New ScalarArray(New MCvScalar(30, 255, 255)), threshold_img)


问:
Drop a specific row in Pandas
I tried drop method of pandas but I didn't use it. How do I remove a specific row in pandas with Python?

e.g.: My specific row is => Name: Bertug  Grade: A  Age: 15

答:
```<code>df = pd.DataFrame([['Jhon',15,'A'],['Anna',19,'B'],['Paul',25,'D']])
df. columns = ['Name','Age','Grade']

df
Out[472]:
   Name  Age Grade
0  Jhon   15     A
1  Anna   19     B
2  Paul   25     D
</code>```

You can get the index of your row:

```<code>i = df[((df.Name == 'jhon') &( df.Age == 15) & (df.Grade == 'A'))].index
</code>```

and then drop it:

```<code>df.drop(i)
Out[474]:
   Name  Age Grade
1  Anna   19     B
2  Paul   25     D
</code>```

As @jezrael pointed our, you can also just negate all three:

```<code>df[((df.Name != 'jhon') &( df.Age != 15) & (df.Grade != 'A'))]
Out[477]:
   Name  Age Grade
1  Anna   19     B
2  Paul   25     D
</code>```

ContentLicense: CC BY-SA 4.0

Title: Drop a specific row in Pandas

Body:
df = pd.DataFrame([['Jhon',15,'A'],['Anna',19,'B'],['Paul',25,'D']])
df. columns = ['Name','Age','Grade']

df
Out[472]:
   Name  Age Grade
0  Jhon   15     A
1  Anna   19     B
2  Paul   25     D

You can get the index of your row:

i = df[((df.Name == 'jhon') &( df.Age == 15) & (df.Grade == 'A'))].index

and then drop it:

df.drop(i)
Out[474]:
   Name  Age Grade
1  Anna   19     B
2  Paul   25     D

As @jezrael pointed our, you can also just negate all three:

df[((df.Name != 'jhon') &( df.Age != 15) & (df.Grade != 'A'))]
Out[477]:
   Name  Age Grade
1  Anna   19     B
2  Paul   25     D


问:
Ruby on Rails complex search through foreign keys
Hi in my application I'm trying to search for an employee based on the skills. I have 3 classes involved Employee, Employee_skills and Skills

Could anyone point me in the direction of how to go about this search as everything I've tried returned errors. Here are their modals.

Employee

```<code>class Employee < ActiveRecord::Base
has_secure_password

has_many :employee_events
has_many :employee_skills , :class_name => EmployeeSkill, :foreign_key => "employee_id"
has_many :employee_projects
has_many :equipments
has_many :time_entry

has_one :holiday
has_one :role
has_one :skill
has_one :tax

accepts_nested_attributes_for :skill

  validates :email, :presence => true, :uniqueness => true
  validates :password, :confirmation => true #password_confirmation attr
  validates_length_of :password, :in => 6..20, :on => :create

  def self.search(search)
  if search
    where('empLastName LIKE ?', "%#{search}%")
  else
    where(:all)
  end
end

  end
</code>```

Employee_skills

```<code>class EmployeeSkill < ActiveRecord::Base

belongs_to :employee, :class_name => Employee, :foreign_key => "employee_id"
belongs_to :project
belongs_to :skill, :class_name => Skill, :foreign_key => "skill_id"

end
</code>```

Skills

```<code>class Skill < ActiveRecord::Base

has_many :employee_skills

def self.search(search)
  where("skillType LIKE ?", "%#{search}%")
end

end
</code>```

答:
I think your situation is a good candidate for has_many_through association

```<code>class Employee < ActiveRecord::Base
 has_many :employee_skills
 has_many :skills, through: :employee_skills
end

class EmployeeSkills < ActiveRecord::Base
 belongs_to :employee
 belongs_to :skills
end

class Skill < ActiveRecord::Base
 has_many :employee_skills
 has_many :employees, through: :employee_skills
end
</code>```

Now simply do

```<code>Skill.first.employees
</code>```

Body:
Hi in my application I'm trying to search for an employee based on the skills. I have 3 classes involved Employee, Employee_skills and Skills

Could anyone point me in the direction of how to go about this search as everything I've tried returned errors. Here are their modals.

Employee

class Employee < ActiveRecord::Base
has_secure_password

has_many :employee_events
has_many :employee_skills , :class_name => EmployeeSkill, :foreign_key => "employee_id"
has_many :employee_projects
has_many :equipments
has_many :time_entry

has_one :holiday
has_one :role
has_one :skill
has_one :tax

accepts_nested_attributes_for :skill

  validates :email, :presence => true, :uniqueness => true
  validates :password, :confirmation => true #password_confirmation attr
  validates_length_of :password, :in => 6..20, :on => :create

  def self.search(search)
  if search
    where('empLastName LIKE ?', "%#{search}%")
  else
    where(:all)
  end
end

  end

Employee_skills

class EmployeeSkill < ActiveRecord::Base

belongs_to :employee, :class_name => Employee, :foreign_key => "employee_id"
belongs_to :project
belongs_to :skill, :class_name => Skill, :foreign_key => "skill_id"

end

Skills

class Skill < ActiveRecord::Base

has_many :employee_skills

def self.search(search)
  where("skillType LIKE ?", "%#{search}%")
end

end

Body:
I think your situation is a good candidate for has_many_through association

class Employee < ActiveRecord::Base
 has_many :employee_skills
 has_many :skills, through: :employee_skills
end

class EmployeeSkills < ActiveRecord::Base
 belongs_to :employee
 belongs_to :skills
end

class Skill < ActiveRecord::Base
 has_many :employee_skills
 has_many :employees, through: :employee_skills
end

Now simply do

Skill.first.employees


问:
Doctrine Query Builder Length
how to reproduce in query builder this

```<code>AND     LENGTH( CONCAT_WS('', lsc.door_code, lsc.alarm_code, lsc.service_code, lsc.master_log) ) > 0"
</code>```

I try like this

```<code>            $orX = $qb->expr()->orX();

        $orX
            ->add($qb->expr()->length('lsc.doorCode > 0'))
            ->add($qb->expr()->length('lsc.alarmCode > 0'))
            ->add($qb->expr()->length('lsc.serviceCode > 0'))
            ->add($qb->expr()->length('lsc.masterLog > 0'));

        $qb->andWhere($orX);
</code>```

have error:

```<code>[Syntax Error] line 0, col 549: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '>'
</code>```

and my query

```<code>SELECT
            CONCAT(
            IFNULL(location.name, ''),' (',IFNULL(location.streetAddress, ''),' ',IFNULL(location.staircase, ''),' ',IFNULL(location.flatNumber, ''),' ',IFNULL(location.postal, ''),' ',IFNULL(location.postOffice, ''),')') as address,
            lsc.doorCode,
            lsc.serviceCode,
            lsc.alarmCode,
            lsc.masterLog
         FROM AppBundle:LocationServiceCompany lsc INNER JOIN lsc.location location WHERE lsc.serviceCompany = :sc AND (LENGTH(lsc.doorCode > 0) OR LENGTH(lsc.alarmCode > 0) OR LENGTH(lsc.serviceCode > 0) OR LENGTH(lsc.masterLog > 0))
</code>```

how to use length ?

答:
You have a typo here:

```<code>$orX = $qb->expr()->orX();

    $orX
        ->add($qb->expr()->length('lsc.doorCode > 0')); <--
        ->add($qb->expr()->length('lsc.alarmCode > 0'))
        ->add($qb->expr()->length('lsc.serviceCode > 0'))
        ->add($qb->expr()->length('lsc.masterLog > 0'));

    $qb->andWhere($orX);
</code>```

remove the ; and get rid of the syntax error.

And for the concat length, you can try something like this:

```<code>$query->andWhere("LENGTH( CONCAT_WS('', lsc.door_code, lsc.alarm_code, lsc.service_code, lsc.master_log) ) > 0")
</code>```

After the update
You can run native SQL queries with Doctrine like mentioned here:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html#the-nativequery-class

For reference:

```<code><?php
use Doctrine\ORM\Query\ResultSetMapping;

$rsm = new ResultSetMapping();
// build rsm here

$query = $entityManager->createNativeQuery('SELECT id, name, discr FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');

$users = $query->getResult();
</code>```

If your updated query works, this would be a way to make it work.

Title: Doctrine Query Builder Length

Body:
how to reproduce in query builder this

AND     LENGTH( CONCAT_WS('', lsc.door_code, lsc.alarm_code, lsc.service_code, lsc.master_log) ) > 0"

I try like this

            $orX = $qb->expr()->orX();

        $orX
            ->add($qb->expr()->length('lsc.doorCode > 0'))
            ->add($qb->expr()->length('lsc.alarmCode > 0'))
            ->add($qb->expr()->length('lsc.serviceCode > 0'))
            ->add($qb->expr()->length('lsc.masterLog > 0'));

        $qb->andWhere($orX);

have error:

[Syntax Error] line 0, col 549: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '>'

and my query

SELECT
            CONCAT(
            IFNULL(location.name, ''),' (',IFNULL(location.streetAddress, ''),' ',IFNULL(location.staircase, ''),' ',IFNULL(location.flatNumber, ''),' ',IFNULL(location.postal, ''),' ',IFNULL(location.postOffice, ''),')') as address,
            lsc.doorCode,
            lsc.serviceCode,
            lsc.alarmCode,
            lsc.masterLog
         FROM AppBundle:LocationServiceCompany lsc INNER JOIN lsc.location location WHERE lsc.serviceCompany = :sc AND (LENGTH(lsc.doorCode > 0) OR LENGTH(lsc.alarmCode > 0) OR LENGTH(lsc.serviceCode > 0) OR LENGTH(lsc.masterLog > 0))

how to use length ?

Body:
You have a typo here:

$orX = $qb->expr()->orX();

    $orX
        ->add($qb->expr()->length('lsc.doorCode > 0')); <--
        ->add($qb->expr()->length('lsc.alarmCode > 0'))
        ->add($qb->expr()->length('lsc.serviceCode > 0'))
        ->add($qb->expr()->length('lsc.masterLog > 0'));

    $qb->andWhere($orX);

remove the ; and get rid of the syntax error.

And for the concat length, you can try something like this:

$query->andWhere("LENGTH( CONCAT_WS('', lsc.door_code, lsc.alarm_code, lsc.service_code, lsc.master_log) ) > 0")

After the update
You can run native SQL queries with Doctrine like mentioned here:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html#the-nativequery-class

For reference:

<?php
use Doctrine\ORM\Query\ResultSetMapping;

$rsm = new ResultSetMapping();
// build rsm here

$query = $entityManager->createNativeQuery('SELECT id, name, discr FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');

$users = $query->getResult();

If your updated query works, this would be a way to make it work.


问:
How do I detect if ActiveX is enabled in the browser of client?
How do I detect if ActiveX is enabled in the browser of client?

I tried following code, but it's not working in Firefox.

```<code>window.ActiveXObject not working in Firefox
</code>```

any ideas?

check the example here: http://jsfiddle.net/qXSvQ/2/

I get false when I run this example.

答:
ActiveX objects do not exist in anything but Internet Explorer. If you're trying to use them for XMLHTTPRequests, use the XMLHTTPRequest() object instead, using feature detection.</p>

```<code>if ("ActiveXObject" in window) { /* Do ActiveX Stuff */ }
else { /* ActiveX doesnt exist, use something else */ }
</code>```

OwnerDisplayName: twesh

Body:
How do I detect if ActiveX is enabled in the browser of client?

I tried following code, but it's not working in Firefox.

window.ActiveXObject not working in Firefox

any ideas?

check the example here: http://jsfiddle.net/qXSvQ/2/

I get false when I run this example.

Body:
ActiveX objects do not exist in anything but Internet Explorer. If you're trying to use them for XMLHTTPRequests, use the XMLHTTPRequest() object instead, using feature detection.

if ("ActiveXObject" in window) { /* Do ActiveX Stuff */ }
else { /* ActiveX doesnt exist, use something else */ }