问:
Embedded SSRS Subreport returns all rows instead of matching specified parameters for each parent row
I have an SSRS report with an embedded subreport.  The subreport takes two parameters.  I configured the Table Adapter for the subreport DataSet to accept two parameters.  When I test the standalone subreport, it works as expected.  However when embedded in the parent report the subreport returns all the rows in the table instead of the rows matching the parent row parameters.  I have configured the subreport to accept the two parameters from the parent row. I want the subreport to only return rows that match the parent row parameter values.  Am I missing a step or going about this the wrong way?</p>

答:
You need to tell SSRS how to relate the subreport to the main report:

Right-click the subreport, select "Subreport properties"

Select "Parameters" in the left panel

Click "Add" and match your subreport field to a main report parameter


来源: stackexchange

问:
Which could become a strong alternative JVM language: Scala, Clojure, Fan, JavaFX Script, or other?
I am currently deciding on an alternative JVM language to port an existing Swing desktop application written in Java 6. Given that JavaFX specifically targets this kind of application, it would seem that my best option is JavaFX Script.

However, what about other kinds of applications and libraries? Would JavaFX Script be the best choice in general for a second JVM language?

Currently, it seems that Scala is the most talked about alternative to the Java language. This month (October 2009), it is at position 34 in the TIOBE index, while JavaFX Script is at position 44, and Clojure, Fan, and Groovy are at positions below 50.

So, what are your impressions? Which language would you invest your time in learning and using (and why), assuming you can freely choose the language for a given project to run in the JVM?

答:
My main question would be: why are you porting an existing application? The answer to this question may give you some idea of where you want to go.

Some quick perspectives on the main choices:

Scala is in my view, a better Java than Java. If you want a language that takes the best bits of Java buts adds a lot of new innovations and features, then it may well be for you.

Clojure is an amazingly well designed language, particularly if you believe in a future of highly complex, concurrent applications. It's also extremely productive - I can probably create more value/hour in Clojure than any other language. However, unless you already know Lisp it will seem very unfamiliar at first. If you are willing to live on the cutting edge to get these benefits, Clojure may well be for you.

JavaFX script - has some very nice features for GUI design, and clearly has support of Sun/Oracle. On the other hand, I don't see it having massive traction outside this domain. I'd suggest giving it a trail run to see if it meets you needs.

Java - should still be on your list! If the reason you are porting is because the code has become difficult to maintain, then maybe a focused phase of re-factoring while staying on Java can get you the benefits you want. It's possible to write perfectly good GUI applications in Java.

Groovy - really nice scripting language on the JVM. Particularly good if you want to embed scripting features within an existing Java/JVM application. Not sure I'd choose it for (re)writing a complete application however.

JRuby / Jython - haven't seen these much myself but heard good things. Probably most suitable if you have Ruby / Python skills in the team but also want the benefits of the JVM platform.

ContentLicense: CC BY-SA 2.5


问:
Setting properties in Javascript Classes at execution level
Example :

```<code>class MyClass {
    this.text : 'text';
}

console.log(MyClass.text);
</code>```

Is this not allowed? Can I not have classes as objects as you have in Python?

I want to access a class property without an instance.

Is there a workaround while still using the actual Class syntax?

答:
At the moment, no, you can't (here's the proposal).

You have to use the constructor for that.

```<code>class MyClass {
  constructor() {
    this.text = "text";
  }
}
</code>```

[edit] If you don't want an instance, you should really just use a
simple javascript object.

```<code>let MyClass = {
    text: "text"
};
</code>```

but if you really want the class syntax you would do this:

```<code>class MyClass {
}

MyClass.text = "text";
</code>```

or

```<code>class MyClass {
    static get text() {
        return "text";
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Example :

class MyClass {
    this.text : 'text';
}

console.log(MyClass.text);

Is this not allowed? Can I not have classes as objects as you have in Python?

I want to access a class property without an instance.

Is there a workaround while still using the actual Class syntax?

Body:
At the moment, no, you can't (here's the proposal).

You have to use the constructor for that.

class MyClass {
  constructor() {
    this.text = "text";
  }
}

[edit] If you don't want an instance, you should really just use a
simple javascript object.

let MyClass = {
    text: "text"
};

but if you really want the class syntax you would do this:

class MyClass {
}

MyClass.text = "text";

or

class MyClass {
    static get text() {
        return "text";
    }
}


问:
Protect laravel api service with Okta and JWT
Trying to put together a solution to protecting a Laravel 5.4 api using OKTA and JWT. I have an SPA that logs into my application via  OKTA and retrieves an access_token and id_token. It also passes this to API calls in the header using 'Authorization': Bearer ${accessToken} but now i am struggling to find a solution to verify this access token with OKTA within the Laravel backend. been looking at tymon/jwt-auth but cant workout how to add a custom solution to verifiy the token but i would assume it can be done using okta/jwt-verifier does anyone have any samples/guide? also looked at laravel/socialite and socialiteproviders/okta but that seems more about a traditional backend login rather than an SPA

答:
Our okta/jwt-verifier library should be able to help you out here.  You will have to create a custom middleware solution to capture and authorize the request based on the bearer token.  Once you have that middleware set up, inside of the verifier library, you can run the following to verify the accessToken.

```<code>$jwtVerifier = (new \Okta\JwtVerifier\JwtVerifierBuilder())
    ->setAudience('api://default')
    ->setClientId('{clientId}')
    ->setIssuer('https://{yourOktaDomain}.com/oauth2/default')
    ->build();

$jwt = $jwtVerifier->verify($jwt);
</code>```

By changing the client id and your okta domain above, you should be able to pass in the accessToken to the verify method.  If you do not get any exceptions, you can assume that the jwt is valid and approve the request.

See the github repo readme for information about what you have access to once you verify the validity of the JWT

Body:
Our okta/jwt-verifier library should be able to help you out here.  You will have to create a custom middleware solution to capture and authorize the request based on the bearer token.  Once you have that middleware set up, inside of the verifier library, you can run the following to verify the accessToken.

$jwtVerifier = (new \Okta\JwtVerifier\JwtVerifierBuilder())
    ->setAudience('api://default')
    ->setClientId('{clientId}')
    ->setIssuer('https://{yourOktaDomain}.com/oauth2/default')
    ->build();

$jwt = $jwtVerifier->verify($jwt);

By changing the client id and your okta domain above, you should be able to pass in the accessToken to the verify method.  If you do not get any exceptions, you can assume that the jwt is valid and approve the request.

See the github repo readme for information about what you have access to once you verify the validity of the JWT


问:
Sort DataGridView without changing Datasource/BindingList order
I have a C# custom MySortableBindingList : BindingList<MyClass>
which implements all stuff for sorting (SupportsSortingCore, SortPropertyCore, ApplySortCore(...) etc.), whereby MyClass : INotifyPropertyChanged

Because of that, I can use this list for a Forms DataGridView (myDataGridView1.DataSource = mySortableBindingList1) and sort the DataGridView in my GUI according to the columns/Properties.

Now the question: Can I define how sording the UI DataGridView affects the order of the MySortableBindingList?

Because right now, sorting the GridView also sorts the BindingList, but I need to keep the internal (original) order, as I need to access the list using stored indices.

Thank you in advance!

答:
I believe it's something to do with your sorting implementation that is causing this.  My suggestion would be to follow Chris Dogget's suggestion and download the open source BindingListView.

Usage is simple enough:

```<code>BindingList<Example> examples = new BindingList<Example>()
{
    new Example() { Foo = "foo1", Bar = "bar2" ),
    new Example() { Foo = "foo2", Bar = "bar4" ),
    new Example() { Foo = "foo3", Bar = "bar1" ),
    new Example() { Foo = "foo4", Bar = "bar3" ),
};

BindingListView blv = new BindingListView(examples);
dataGridView1.DataSource = blv;
</code>```

Sorting is baked in and leaves the underlying list in original order.  Using the previous data, we can iterate through both the source and the DataGridView and print out the results to see that they are different. We'll use a for loop to demonstrate the indexing you've requested:

```<code>BindingListView<Example> blv = this.dataGridView1.DataSource as BindingListView<Example>;
BindingList<Example> examples = examples.DataSource as BindingList<Example>;

Console.WriteLine("From BindingListView:");
for (int i = 0; i < examples.Count; i++)
{
    Example ex = examples[i];
    Console.WriteLine($"{ex.Foo} {ex.Bar}");
}

Console.WriteLine("\nFrom DataGridView:");

for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
{
    DataGridViewRow row = this.dataGridView1.Rows[i];
    Console.WriteLine($"{row.Cells["Foo"].Value} {row.Cells["Bar"].Value}");
}
</code>```

Output when the DataGridView has been sorted by the Bar column:

```<code>/*
From BindingListView:
foo1 bar2
foo2 bar4
foo3 bar1
foo4 bar3

From DataGridView:
foo3 bar1
foo1 bar2
foo4 bar3
foo2 bar4
*/
</code>```

Body:
I believe it's something to do with your sorting implementation that is causing this.  My suggestion would be to follow Chris Dogget's suggestion and download the open source BindingListView.

Usage is simple enough:

BindingList<Example> examples = new BindingList<Example>()
{
    new Example() { Foo = "foo1", Bar = "bar2" ),
    new Example() { Foo = "foo2", Bar = "bar4" ),
    new Example() { Foo = "foo3", Bar = "bar1" ),
    new Example() { Foo = "foo4", Bar = "bar3" ),
};

BindingListView blv = new BindingListView(examples);
dataGridView1.DataSource = blv;

Sorting is baked in and leaves the underlying list in original order.  Using the previous data, we can iterate through both the source and the DataGridView and print out the results to see that they are different. We'll use a for loop to demonstrate the indexing you've requested:

BindingListView<Example> blv = this.dataGridView1.DataSource as BindingListView<Example>;
BindingList<Example> examples = examples.DataSource as BindingList<Example>;

Console.WriteLine("From BindingListView:");
for (int i = 0; i < examples.Count; i++)
{
    Example ex = examples[i];
    Console.WriteLine($"{ex.Foo} {ex.Bar}");
}

Console.WriteLine("\nFrom DataGridView:");

for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
{
    DataGridViewRow row = this.dataGridView1.Rows[i];
    Console.WriteLine($"{row.Cells["Foo"].Value} {row.Cells["Bar"].Value}");
}

Output when the DataGridView has been sorted by the Bar column:

/*
From BindingListView:
foo1 bar2
foo2 bar4
foo3 bar1
foo4 bar3

From DataGridView:
foo3 bar1
foo1 bar2
foo4 bar3
foo2 bar4
*/


问:
Get address using geolocation in http website
Recently I created a website in asp.net core and hosted in Azure Shared tier (non-secure). there is one feature on my website, get user address based on geolocation and autofill registration form.

Problem

getCurrentPosition() and watchPosition() no longer work on insecure origins (As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS.)

The site is very small and I don't want to spend money on SSL certificate. (I can go with free SSL https://letsencrypt.org/)

Custom SSL certificate hosting only available on Azure Basic and above tier.

Is there any solution/workaround available?

Thanks,

答: Use Let's Encrypt (https://letsencrypt.org/) to get a certificate for free.</p>

ContentLicense: CC BY-SA 4.0


问:
Centering tabs inside superfish navbar
Superfish navbars are great, but when you are looking at the rightmost tab, the second tier navbar starts at the far left. So if there are only a few tabs, it looks off-center and the user has to mouse all the way to the left. How can you center the tabs inside the superfish navbar?</p>

答:
Never mind, found the appropriate line to change in the css:

```<code>.sf-navbar > li > ul > li {
float: left;
</code>```

}

Title: Centering tabs inside superfish navbar

Body:
Never mind, found the appropriate line to change in the css:

.sf-navbar > li > ul > li {
float: left;

}


问:
JNI Hello World Unsatisfied Link Error
This is my first attempt at JNI. My ultimate goal is to get all tasks currently running on a machine, but need to get even a simple example running. I keep getting this error when I try to execute my main program. I have supplied my simple Java main program, the header file generated, and the error.

I do not know what this DLL could be dependent on. It was initially referencing a DLL I tracked down and placed into system32 (msvcr90.dll).

Here is the command I used to compile the C code as well which produced the DLL, OBJ, LIB, EXP and manifest files.

cl -I"C:\Program Files\Java\jdk1.6.0\include" -I"C:\Program Files\Java\jdk1.6.0\include\win32" -MD -LD HelloWorld.c -FeHelloWorld.dll

```<code>class HelloWorld {
     private native void print();
     public static void main(String[] args) {
         new HelloWorld().print();
     }
     static {
         System.load("C:\\temp\\HelloWorld.dll");
     }
 }

#include <jni.h>
 #include <stdio.h>
 #include "HelloWorld.h"

 JNIEXPORT void JNICALL
 Java_HelloWorld_print(JNIEnv *env, jobject obj)
 {
     printf("Hello World!\n");
     return;
 }

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    print
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_print
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

java.lang.UnsatisfiedLinkError: C:\temp\HelloWorld.dll: A dynamic link library (DLL) initialization routine failed
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(Unknown Source)
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.load0(Unknown Source)
    at java.lang.System.load(Unknown Source)
    at HelloWorld.<clinit>(HelloWorld.java:7)
Exception in thread "main"
</code>```

答:
I just removed -MD option and compiled it worked like charm</p>

```<code>cl -I"C:\Program Files\Java\jdk1.6.0_21\include" -I"C:\Program Files\Java\jdk1.6.0_21\include\win32" -LD HelloWorld.c -FeHelloWorld.dll
</code>```

Title: JNI Hello World Unsatisfied Link Error

Body:
This is my first attempt at JNI. My ultimate goal is to get all tasks currently running on a machine, but need to get even a simple example running. I keep getting this error when I try to execute my main program. I have supplied my simple Java main program, the header file generated, and the error.

I do not know what this DLL could be dependent on. It was initially referencing a DLL I tracked down and placed into system32 (msvcr90.dll).

Here is the command I used to compile the C code as well which produced the DLL, OBJ, LIB, EXP and manifest files.

cl -I"C:\Program Files\Java\jdk1.6.0\include" -I"C:\Program Files\Java\jdk1.6.0\include\win32" -MD -LD HelloWorld.c -FeHelloWorld.dll

class HelloWorld {
     private native void print();
     public static void main(String[] args) {
         new HelloWorld().print();
     }
     static {
         System.load("C:\\temp\\HelloWorld.dll");
     }
 }

#include <jni.h>
 #include <stdio.h>
 #include "HelloWorld.h"

 JNIEXPORT void JNICALL
 Java_HelloWorld_print(JNIEnv *env, jobject obj)
 {
     printf("Hello World!\n");
     return;
 }

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    print
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_print
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

java.lang.UnsatisfiedLinkError: C:\temp\HelloWorld.dll: A dynamic link library (DLL) initialization routine failed
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(Unknown Source)
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.load0(Unknown Source)
    at java.lang.System.load(Unknown Source)
    at HelloWorld.<clinit>(HelloWorld.java:7)
Exception in thread "main"

Body:
I just removed -MD option and compiled it worked like charm

cl -I"C:\Program Files\Java\jdk1.6.0_21\include" -I"C:\Program Files\Java\jdk1.6.0_21\include\win32" -LD HelloWorld.c -FeHelloWorld.dll


问:
I can't get Transaction Result with QBitNinjaClient
I'm a beginner of C# and blockchain.

I'm studying blockchain with "Programming The Blockchain in C#".
I tried to run this source code following the book:

```<code>using NBitcoin;
using QBitNinja.Client;
using QBitNinja.Client.Models;

namespace NBitcoinTest1
{
    class Program
    {
        static void Main(string[] args)
        {
        // Create a client
        QBitNinjaClient client = new QBitNinjaClient(Network.Main);
        // Parse transaction id to NBitcoin.uint256 so the client can eat it
        var transactionId = uint256.Parse("f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94");
        // Query the transaction
        GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result;
        }
    }
}
</code>```

But it doesn't work because of exception.
It says "Method 'System.Net.Logging.get_On' not found.", so I tried to find "System.Net.Logging", but I couldn't find any package named "System.Net.Logging" in nuget.org.

How can I solve this problem?

Environment: macOS Sierra 10.12.6, Visual Studio for Mac[Community] 7.2(Build 636)

答: Your problem relies in the conflicting types of NBitcoin dependencies, as you installed NBitcoin first then installed QBitNinja which is installed with NBitcoin also and to my surprise a more up to date version! So delete the first dependency version which was v3. Everything should work then, don't worry i've only started to read it yesterday myself :) It is a community built book so i can expect some errors.</p>

Body:
I'm a beginner of C# and blockchain.

I'm studying blockchain with "Programming The Blockchain in C#".
I tried to run this source code following the book:

using NBitcoin;
using QBitNinja.Client;
using QBitNinja.Client.Models;

namespace NBitcoinTest1
{
    class Program
    {
        static void Main(string[] args)
        {
        // Create a client
        QBitNinjaClient client = new QBitNinjaClient(Network.Main);
        // Parse transaction id to NBitcoin.uint256 so the client can eat it
        var transactionId = uint256.Parse("f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94");
        // Query the transaction
        GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result;
        }
    }
}

But it doesn't work because of exception.
It says "Method 'System.Net.Logging.get_On' not found.", so I tried to find "System.Net.Logging", but I couldn't find any package named "System.Net.Logging" in nuget.org.

How can I solve this problem?

Environment: macOS Sierra 10.12.6, Visual Studio for Mac[Community] 7.2(Build 636)


问:
Angular dynamic creating table element and bind to a function
I have a problem with dynamic table creating with ng-click.

```<code>for (var j = 0; j < data.columns; j++) {
     content += '<td class="unchecked" ng-click="service.doSth()"></td>';
}
</code>```

The problem is that service.doSth() is normal string literal in the output and Angular doesn't do anything.. How to do it?

答:
The standard "AngularJS way" to add repeated elements that work with ng-click and other things is to use an ng-repeat. Wherever you want these elements placed, use something along the lines of this in your HTML:

```<code>  <td ng-repeat="column in data.columns" class="unchecked" ng-click="service.doSth()"></td>
</code>```

Body:
I have a problem with dynamic table creating with ng-click.

for (var j = 0; j < data.columns; j++) {
     content += '	';
}

The problem is that service.doSth() is normal string literal in the output and Angular doesn't do anything.. How to do it?

Body:
The standard "AngularJS way" to add repeated elements that work with ng-click and other things is to use an ng-repeat. Wherever you want these elements placed, use something along the lines of this in your HTML:

  <td ng-repeat="column in data.columns" class="unchecked" ng-click="service.doSth()"></td>


问:
Vectorizing a for loop of a logical comparison of vectors of different length in R
In R vectors of different lengths cannot be meaningfully compared, i.e.

```<code>x = 1:10
y = 7:12
x >= y
</code>```

gives a warning that y is shorter than x. I would like to cary out a comparison of each element of x to y and save or transform the resulting vector as in

```<code>v = numeric()
for(i in 1:length(x)){
  v[i] = sum( x[i] >= y )
}
</code>```

This operation is slow - is there a direct way to get here? Alternatiely to sum consider saving i in rows of  a matrix v[i,].

答:
We can do this with outer and rowSums

```<code>rowSums(outer(x, y, FUN= '>='))
#[1] 0 0 0 0 0 0 1 2 3 4
</code>```

Or another option is looping with sapply and then get the colSums of the logical matrix

```<code>colSums(sapply(x, '>=', y))
#[1] 0 0 0 0 0 0 1 2 3 4
</code>```

We can also translate the for loop in Rcpp

```<code>#include <Rcpp.h>

using namespace Rcpp;
using namespace std;

//[[Rcpp::export]]

NumericVector getSum(NumericVector v1, NumericVector v2) {
    NumericVector v(v1.size());

    for(int i = 0; i <= v1.size(); i++) {
        v[i] = sum(v1[i] >= v2 );

    }
    return(v);

}
</code>```

-from R console

```<code>library(Rcpp)
sourceCpp("rcppTrial.cpp")
getSum(x, y)
 #[1] 0 0 0 0 0 0 1 2 3 4
</code>```

Body:
In R vectors of different lengths cannot be meaningfully compared, i.e.

x = 1:10
y = 7:12
x >= y

gives a warning that y is shorter than x. I would like to cary out a comparison of each element of x to y and save or transform the resulting vector as in

v = numeric()
for(i in 1:length(x)){
  v[i] = sum( x[i] >= y )
}

This operation is slow - is there a direct way to get here? Alternatiely to sum consider saving i in rows of  a matrix v[i,].

Body:
We can do this with outer and rowSums

rowSums(outer(x, y, FUN= '>='))
#[1] 0 0 0 0 0 0 1 2 3 4

Or another option is looping with sapply and then get the colSums of the logical matrix

colSums(sapply(x, '>=', y))
#[1] 0 0 0 0 0 0 1 2 3 4

We can also translate the for loop in Rcpp

#include <Rcpp.h>

using namespace Rcpp;
using namespace std;

//[[Rcpp::export]]

NumericVector getSum(NumericVector v1, NumericVector v2) {
    NumericVector v(v1.size());

    for(int i = 0; i <= v1.size(); i++) {
        v[i] = sum(v1[i] >= v2 );

    }
    return(v);

}

-from R console

library(Rcpp)
sourceCpp("rcppTrial.cpp")
getSum(x, y)
 #[1] 0 0 0 0 0 0 1 2 3 4


问:
android ActiveSessions from MediaController
How restore all(or almost) session data of users activity by media controller(android.media.session.MediaController). at least Youtube and GP Music?

I can`t get pending intent from media controller for GPMusic (null). Intent from Youtube can restore only home screen(I wanna restore video and position)

```<code>List<MediaController> list = mgr.getActiveSessions(new ComponentName(getApplicationContext().getPackageName(), TestService.class.getName()));
...
PendingIntent pIntent = currentController.getSessionActivity()
pIntent.send();
</code>```

答:
This is discussed on the Android TV Developers community. Check out this post: https://plus.google.com/u/1/110913444113360071708/posts/HDs8UsyQwxL

From the MediaController you can get the Session activity to launch into the app. If you are not seeing it, then the app is not using MediaSession correctly, you can just launch the app using the package name. You can get the package name from the controller as well: mediaSessionController.getPackageName()

If you implemented OnActivieSessionsChangedListener correctly (which it sounds like you have if you made it this far) then the rest is dependent on the apps properly maintaining and updating their MediaSessions. Sadly, there are a lot of apps that do not maintain their MediaSession 100% correctly. It is possible that they do not update their metadata, playback state, or even not unregister their session correctly. Each app may act differently depending on how much they invested into MediaSession.

Body:
How restore all(or almost) session data of users activity by media controller(android.media.session.MediaController). at least Youtube and GP Music?

I can`t get pending intent from media controller for GPMusic (null). Intent from Youtube can restore only home screen(I wanna restore video and position)

List<MediaController> list = mgr.getActiveSessions(new ComponentName(getApplicationContext().getPackageName(), TestService.class.getName()));
...
PendingIntent pIntent = currentController.getSessionActivity()
pIntent.send();


问:
Vue Router. Bind data
I am developing vue app and now I am on step when I should use vue router.
But I have a little problem with data bind into router template.

Please help me.

HTML:

```<code><div id="app">
  <h1>Hello App!</h1>
  <p>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>
</code>```

Script:

```<code>const Foo = { template: '<div>{{foo}}</div>' }
const Bar = { template: '<div>bar</div>' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
el: '#app',
  router,
  data: function(){
    return {foo: "asdasdas"}
  }
})
</code>```

{{foo}} bind doesn't work.

Live example:
https://jsfiddle.net/xgrjzsup/4430/

答:
From the guide on components :

Every component instance has its own isolated scope. This means you
cannot (and should not) directly reference parent data in a child
component’s template. Data can be passed down to child components
using props.

and Foo is a child component of your app set via the router.

One way to pass data from parent to child is to use props.

Modify your Foo definition to accept a foo property:

const Foo = {
    props: ['foo'],
    template: '
{{foo}}
'
}
```
<p>and bind the parent property in the template</p>
<pre class="lang-html prettyprint-override"><code><router-view :foo="foo"></router-view>
</code>```

An updated Fiddle : https://jsfiddle.net/xgrjzsup/4431/

Title: Vue Router. Bind data

Body:
I am developing vue app and now I am on step when I should use vue router.
But I have a little problem with data bind into router template.

Please help me.

HTML:

Hello App!

    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>

  <router-view></router-view>

Script:

const Foo = { template: '
{{foo}}
' }
const Bar = { template: '
bar
' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
el: '#app',
  router,
  data: function(){
    return {foo: "asdasdas"}
  }
})

{{foo}} bind doesn't work.

Live example:
https://jsfiddle.net/xgrjzsup/4430/

Body:
From the guide on components :

Every component instance has its own isolated scope. This means you
cannot (and should not) directly reference parent data in a child
component’s template. Data can be passed down to child components
using props.

and Foo is a child component of your app set via the router.

One way to pass data from parent to child is to use props.

Modify your Foo definition to accept a foo property:

const Foo = {
    props: ['foo'],
    template: '<div>{{foo}}</div>'
}

and bind the parent property in the template

<router-view :foo="foo"></router-view>

An updated Fiddle : https://jsfiddle.net/xgrjzsup/4431/


问:
Jooby custom interceptor
I have the following problem:

I have a rest API on a jooby server. I want to create a custom annotation interceptor which handles particular requests and validates the oauth token in the header.

```<code>@GET
@Path("current")
@AuthenticationTokenValidator
public Result getCurrentUser(final Request req) {
    ...
</code>```

Or for an entire controller

```<code>@Path("/v1/some_route")
@Consumes("json")
@Produces("json")
@AuthenticationTokenValidator
public class SomeController {
</code>```

How can I do that? Thanks in advance!

答:
You need a filter and then ask for route attributes. Something similar to this:

```<code>{
    use("*", (req, rsp, chain) -> {
        String value = req.route().attr("authenticationTokenValidator");
        // your code goes here
    });
}
</code>```

Not sure if the annotation at the class level is supported.

Checkout the documentation about route attributes, there is a similar example.

Title: Jooby custom interceptor

Body:
I have the following problem:

I have a rest API on a jooby server. I want to create a custom annotation interceptor which handles particular requests and validates the oauth token in the header.

@GET
@Path("current")
@AuthenticationTokenValidator
public Result getCurrentUser(final Request req) {
    ...

Or for an entire controller

@Path("/v1/some_route")
@Consumes("json")
@Produces("json")
@AuthenticationTokenValidator
public class SomeController {

How can I do that? Thanks in advance!

Body:
You need a filter and then ask for route attributes. Something similar to this:

{
    use("*", (req, rsp, chain) -> {
        String value = req.route().attr("authenticationTokenValidator");
        // your code goes here
    });
}

Not sure if the annotation at the class level is supported.

Checkout the documentation about route attributes, there is a similar example.


问:
Checking if python sqlite table is populated
Here is my code:

```<code>dbContent = cursor.execute("SELECT COUNT(*) FROM parse")
if dbContent is None:
    # This should run the nested code if it worked.
</code>```

Instead it runs the else statement which is not what should be happening.

答:
```<code>dbContent = cursor.execute("SELECT COUNT(*) FROM parse")
rows = dbContent.fetchall()
if not rows:
     ...
</code>```

Lists have implicit booleanness which you can use.

Body:
Here is my code:

dbContent = cursor.execute("SELECT COUNT(*) FROM parse")
if dbContent is None:
    # This should run the nested code if it worked.

Instead it runs the else statement which is not what should be happening.

Body:
dbContent = cursor.execute("SELECT COUNT(*) FROM parse")
rows = dbContent.fetchall()
if not rows:
     ...

Lists have implicit booleanness which you can use.


问:
FileNotFoundError for shortcut files
I'm trying the practice project, Deleting Unneeded files (Chapter: Organising files, Page: 213) from the book Automate the boring task with python. The full problem statement is,

It’s not uncommon for a few unneeded but humongous files or folders to take up the bulk of the space on your hard drive. If you’re trying to free up room on your computer, you’ll get the most bang for your buck by deleting the most massive of the unwanted files. But first you have to find them.

Write a program that walks through a folder tree and searches for excep-
tionally large files or folders—say, ones that have a file size of more than
100MB. (Remember, to get a file’s size, you can use os.path.getsize() from
the os module.) Print these files with their absolute path to the screen.

Here's my code,

```<code>#!/usr/bin/python
# A program to walk a path and print all the files name with size above 100MB

import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        file = os.path.join(folder, file)
        if int(os.path.getsize(file)) > 100000000:
            print('File located, Name: {fileName}, Location: {path}'.format(fileName=file, path=folder))
</code>```

However for some files I get FileNotFoundError. So, when trying this

```<code>#!/usr/bin/python
# A program to walk a path and print all the files name with size above 100MB

import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        file = os.path.join(folder, file)
        try:
            if int(os.path.getsize(file)) > 100000000:
                print('File {fileName} located at {path}'.format(fileName=file, path=folder))
        except FileNotFoundError:
            print('FileNotFoundError: {}'.format(file))
</code>```

I found that the files which are shortcuts with size zero bytes causes the error.

So, how should I overcome this error?
Is there any function in python is check if the file is shortcut?

答:
You can use os.path.islink() </p>

```<code>import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        if not os.path.islink(file):
           # rest of code
</code>```

Title: FileNotFoundError for shortcut files

Body:
I'm trying the practice project, Deleting Unneeded files (Chapter: Organising files, Page: 213) from the book Automate the boring task with python. The full problem statement is,

It’s not uncommon for a few unneeded but humongous files or folders to take up the bulk of the space on your hard drive. If you’re trying to free up room on your computer, you’ll get the most bang for your buck by deleting the most massive of the unwanted files. But first you have to find them.

Write a program that walks through a folder tree and searches for excep-
tionally large files or folders—say, ones that have a file size of more than
100MB. (Remember, to get a file’s size, you can use os.path.getsize() from
the os module.) Print these files with their absolute path to the screen.

Here's my code,

#!/usr/bin/python
# A program to walk a path and print all the files name with size above 100MB

import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        file = os.path.join(folder, file)
        if int(os.path.getsize(file)) > 100000000:
            print('File located, Name: {fileName}, Location: {path}'.format(fileName=file, path=folder))

However for some files I get FileNotFoundError. So, when trying this

#!/usr/bin/python
# A program to walk a path and print all the files name with size above 100MB

import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        file = os.path.join(folder, file)
        try:
            if int(os.path.getsize(file)) > 100000000:
                print('File {fileName} located at {path}'.format(fileName=file, path=folder))
        except FileNotFoundError:
            print('FileNotFoundError: {}'.format(file))

I found that the files which are shortcuts with size zero bytes causes the error.

So, how should I overcome this error?
Is there any function in python is check if the file is shortcut?

Body:
You can use os.path.islink()

import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        if not os.path.islink(file):
           # rest of code


问:
Add Glyphicon to Every Button (bootstrap 3.5)
I'd like to add a glyphicon after the text on all my default buttons.

I found how to include the glyphicon in lists here:
Using a Glyphicon as an LI bullet point

I tried applying this to buttons, but I haven't got it right

```<code>.btn-default button:after {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    float: left;
    margin-top: 4px;
    margin-left: -17px;
    color: #0099FF;
}
</code>```

I realise I can add it like this:

```<code><a class="btn btn-default" href="testpage.aspx">
    Learn more
    <span class="glyphicon glyphicon-chevron-right"></span>
</a>
</code>```

But I'd prefer not to have to add it each time.  I'd also like to set the colour.

答:
I understand that this is the correct way of doing it:

```<code><span class="glyphicon glyphicon-chevron-right"></span>
</code>```

To give it a different colour just add a class or reference the span by using a selector and give the colour in css.

```<code>.color-red {
    color:#FF0000;
}
</code>```

Body:
I'd like to add a glyphicon after the text on all my default buttons.

I found how to include the glyphicon in lists here:
Using a Glyphicon as an LI bullet point

I tried applying this to buttons, but I haven't got it right

.btn-default button:after {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    float: left;
    margin-top: 4px;
    margin-left: -17px;
    color: #0099FF;
}

I realise I can add it like this:

    Learn more

But I'd prefer not to have to add it each time.  I'd also like to set the colour.

Body:
I understand that this is the correct way of doing it:

<span class="glyphicon glyphicon-chevron-right"></span>

To give it a different colour just add a class or reference the span by using a selector and give the colour in css.

.color-red {
    color:#FF0000;
}


问:
how To parse a string in file geoxml3?
I want to parse this file:
http://www.emsc-csem.org/Earthquake/Map/earth/kml.php
with  geoxml3.

I download this file by proxy, but I don't know how to parse a string

For example, I want to parse a string:

```<code><name> ..... </name>
<description>....</description>
</code>```

Can you help me?

答:
To parse a string (containing KML) using [geoxml3](https://github.com/geocodezip/geoxml3), use the .parseKmlString method of the parser.

```<code>map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
geoXml = new geoXML3.parser({
  map: map,
  singleInfoWindow: true
});
geoXml.parseKmlString(kmlData); // kmlData contains a string containing valid KML
</code>```

proof of concept fiddle

code snippet:

var geoxml = null;

function initialize() {
  var myLatlng = new google.maps.LatLng(39.397, -100.644);
  var myOptions = {
    zoom: 5,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
  geoXml = new geoXML3.parser({
    map: map,
    singleInfoWindow: true
  });
  geoXml.parseKmlString(kmlData);
}
google.maps.event.addDomListener(window, "load", initialize);
var kmlData = '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2"><Document><name>EMSC - Last 2 Weeks earthquakes worldwide</name><Folder><name>2017 12 - 6</name><open>0</open><visibility>1</visibility><Placemark><name>ML 2.3 - SOUTHERN CALIFORNIA</name><description><![CDATA[
ML 2.3 - SOUTHERN CALIFORNIA

2017-12-06   16:37:55.1 UTC

Latitude	34.60 N

Longitude	116.30 W

Depth	1   Km

Magnitude	ML 2.3

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>-116.3006,34.5925,0</coordinates></Point><LookAt><longitude>-116.3006</longitude><latitude>34.5925</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>ML 2.0 - GREECE</name><description><![CDATA[
ML 2.0 - GREECE

2017-12-06   10:21:54.5 UTC

Latitude	40.51 N

Longitude	22.53 E

Depth	4   Km

Magnitude	ML 2.0

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>22.5358,40.5114,0</coordinates></Point><LookAt><longitude>22.5358</longitude><latitude>40.5114</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>M 3.6 - OAXACA, MEXICO</name><description><![CDATA[
M 3.6 - OAXACA, MEXICO

2017-12-06   10:19:47.0 UTC

Latitude	16.64 N

Longitude	94.91 W

Depth	15   Km

Magnitude	M 3.6

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>-94.9192,16.6313,0</coordinates></Point><LookAt><longitude>-94.9192</longitude><latitude>16.6313</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>M 3.5 - COSTA RICA</name><description><![CDATA[
M 3.5 - COSTA RICA

2017-11-22   18:03:30.0 UTC

Latitude	9.50 N

Longitude	84.57 W

Depth	15   Km

Magnitude	M 3.5

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>-84.5601,9.501,0</coordinates></Point><LookAt><longitude>-84.5601</longitude><latitude>9.501</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>mb 4.3 - FOX ISLANDS, ALEUTIAN ISLANDS</name><description><![CDATA[
mb 4.3 - FOX ISLANDS, ALEUTIAN ISLANDS

2017-11-22   17:38:20.4 UTC

Latitude	53.81 N

Longitude	165.56 W

Depth	65   Km

Magnitude	mb 4.3

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>-165.5595,53.81,0</coordinates></Point><LookAt><longitude>-165.5595</longitude><latitude>53.81</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>ML 3.2 - ALBANIA</name><description><![CDATA[
ML 3.2 - ALBANIA

2017-11-22   17:08:15.6 UTC

Latitude	40.35 N

Longitude	20.57 E

Depth	5 f Km

Magnitude	ML 3.2

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>20.5607,40.3405,0</coordinates></Point><LookAt><longitude>20.5607</longitude><latitude>40.3405</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>ML 3.8 - ANTOFAGASTA, CHILE</name><description><![CDATA[
ML 3.8 - ANTOFAGASTA, CHILE

2017-11-22   17:00:52.0 UTC

Latitude	22.50 S

Longitude	69.00 W

Depth	108   Km

Magnitude	ML 3.8

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>-68.9908,-22.4948,0</coordinates></Point><LookAt><longitude>-68.9908</longitude><latitude>-22.4948</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>ML 2.1 - NORTHERN ITALY</name><description><![CDATA[
ML 2.1 - NORTHERN ITALY

2017-11-22   16:55:07.0 UTC

Latitude	44.65 N

Longitude	10.04 E

Depth	26   Km

Magnitude	ML 2.1

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>10.0312,44.6493,0</coordinates></Point><LookAt><longitude>10.0312</longitude><latitude>44.6493</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>mb 4.6 - SUMBA REGION, INDONESIA</name><description><![CDATA[
mb 4.6 - SUMBA REGION, INDONESIA

2017-11-22   16:53:10.7 UTC

Latitude	10.56 S

Longitude	120.30 E

Depth	40   Km

Magnitude	mb 4.6

Link to the event ]]></description><Snippet maxLines="0"></Snippet><Point><altitudeMode>absolute</altitudeMode><coordinates>120.3089,-10.551,0</coordinates></Point><LookAt><longitude>120.3089</longitude><latitude>-10.551</latitude><range>1000000</range></LookAt></Placemark></Folder></Pair><Pair><key>highlight</key></Pair></StyleMap></Pair><Pair><key>highlight</key></Pair></StyleMap></Pair><Pair><key>highlight</key></Pair></StyleMap></Pair><Pair><key>highlight</key></Pair></StyleMap></Pair><Pair><key>highlight</key></Pair></StyleMap><ScreenOverlay><name>EMSC Legend</name><color>ccffffff</color><Icon><href>https://static1.emsc.eu/Images/legendge.png</href></Icon><overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/><screenXY x="0.01" y="0.02" xunits="fraction" yunits="fraction"/></ScreenOverlay><ScreenOverlay><name>EMSC Logo</name><color>ccffffff</color><Icon><href>https://static2.emsc.eu/Images/logoge.png</href></Icon><overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/><screenXY x="0.5" y="0.99" xunits="fraction" yunits="fraction"/></ScreenOverlay></Document></kml>';```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}</code>```

```

Title: how To parse a string in file geoxml3?

Body:
I want to parse this file:
http://www.emsc-csem.org/Earthquake/Map/earth/kml.php
with  geoxml3.

I download this file by proxy, but I don't know how to parse a string

For example, I want to parse a string:

<name> ..... </name>
<description>....</description>

Can you help me?

Body:
To parse a string (containing KML) using [geoxml3](https://github.com/geocodezip/geoxml3), use the .parseKmlString method of the parser.

map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
geoXml = new geoXML3.parser({
  map: map,
  singleInfoWindow: true
});
geoXml.parseKmlString(kmlData); // kmlData contains a string containing valid KML

proof of concept fiddle

code snippet:

var geoxml = null;

function initialize() {
  var myLatlng = new google.maps.LatLng(39.397, -100.644);
  var myOptions = {
    zoom: 5,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
  geoXml = new geoXML3.parser({
    map: map,
    singleInfoWindow: true
  });
  geoXml.parseKmlString(kmlData);
}
google.maps.event.addDomListener(window, "load", initialize);
var kmlData = '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2"><Document><name>EMSC - Last 2 Weeks earthquakes worldwide</name><Folder><name>2017 12 - 6</name><open>0</open><visibility>1</visibility><Placemark><name>ML 2.3 - SOUTHERN CALIFORNIA</name><description><![CDATA[ <h2>ML 2.3 - SOUTHERN CALIFORNIA</h2><br><b>2017-12-06   16:37:55.1 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">34.60 N<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">116.30 W<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">1   Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">ML 2.3<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=634406">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#rouge</styleUrl><Style><IconStyle><scale>0.25</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>-116.3006,34.5925,0</coordinates></Point><LookAt><longitude>-116.3006</longitude><latitude>34.5925</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>ML 2.0 - GREECE</name><description><![CDATA[ <h2>ML 2.0 - GREECE</h2><br><b>2017-12-06   10:21:54.5 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">40.51 N<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">22.53 E<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">4   Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">ML 2.0<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=634358">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#rouge</styleUrl><Style><IconStyle><scale>0.25</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>22.5358,40.5114,0</coordinates></Point><LookAt><longitude>22.5358</longitude><latitude>40.5114</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>M 3.6 - OAXACA, MEXICO</name><description><![CDATA[ <h2>M 3.6 - OAXACA, MEXICO</h2><br><b>2017-12-06   10:19:47.0 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">16.64 N<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">94.91 W<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">15   Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">M 3.6<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=634392">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#rouge</styleUrl><Style><IconStyle><scale>0.5</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>-94.9192,16.6313,0</coordinates></Point><LookAt><longitude>-94.9192</longitude><latitude>16.6313</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>M 3.5 - COSTA RICA</name><description><![CDATA[ <h2>M 3.5 - COSTA RICA</h2><br><b>2017-11-22   18:03:30.0 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">9.50 N<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">84.57 W<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">15   Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">M 3.5<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=631799">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#rouge</styleUrl><Style><IconStyle><scale>0.5</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>-84.5601,9.501,0</coordinates></Point><LookAt><longitude>-84.5601</longitude><latitude>9.501</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>mb 4.3 - FOX ISLANDS, ALEUTIAN ISLANDS</name><description><![CDATA[ <h2>mb 4.3 - FOX ISLANDS, ALEUTIAN ISLANDS</h2><br><b>2017-11-22   17:38:20.4 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">53.81 N<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">165.56 W<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">65   Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">mb 4.3<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=631805">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#jaune</styleUrl><Style><IconStyle><scale>0.5</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>-165.5595,53.81,0</coordinates></Point><LookAt><longitude>-165.5595</longitude><latitude>53.81</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>ML 3.2 - ALBANIA</name><description><![CDATA[ <h2>ML 3.2 - ALBANIA</h2><br><b>2017-11-22   17:08:15.6 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">40.35 N<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">20.57 E<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">5 f Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">ML 3.2<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=631793">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#rouge</styleUrl><Style><IconStyle><scale>0.375</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>20.5607,40.3405,0</coordinates></Point><LookAt><longitude>20.5607</longitude><latitude>40.3405</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>ML 3.8 - ANTOFAGASTA, CHILE</name><description><![CDATA[ <h2>ML 3.8 - ANTOFAGASTA, CHILE</h2><br><b>2017-11-22   17:00:52.0 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">22.50 S<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">69.00 W<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">108   Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">ML 3.8<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=631792">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#vert</styleUrl><Style><IconStyle><scale>0.5</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>-68.9908,-22.4948,0</coordinates></Point><LookAt><longitude>-68.9908</longitude><latitude>-22.4948</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>ML 2.1 - NORTHERN ITALY</name><description><![CDATA[ <h2>ML 2.1 - NORTHERN ITALY</h2><br><b>2017-11-22   16:55:07.0 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">44.65 N<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">10.04 E<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">26   Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">ML 2.1<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=631788">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#rouge</styleUrl><Style><IconStyle><scale>0.25</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>10.0312,44.6493,0</coordinates></Point><LookAt><longitude>10.0312</longitude><latitude>44.6493</latitude><range>1000000</range></LookAt></Placemark><Placemark><name>mb 4.6 - SUMBA REGION, INDONESIA</name><description><![CDATA[ <h2>mb 4.6 - SUMBA REGION, INDONESIA</h2><br><b>2017-11-22   16:53:10.7 UTC</b><br /><br /><table style="width:100%;"><tr><td><b>Latitude</b></td><td style="padding-left:5px;">10.56 S<br></td></tr><tr><td><b>Longitude</b></td><td style="padding-left:5px;">120.30 E<br></td></tr><tr><td><b>Depth</b></td><td style="padding-left:5px;">40   Km<br></td></tr><tr><td><b>Magnitude</b></td><td style="padding-left:5px;">mb 4.6<br></td></tr></table><br /><br /><a href="https://www.emsc-csem.org/Earthquake/earthquake.php?id=631789">Link to the event </a>]]></description><Snippet maxLines="0"></Snippet><styleUrl>#jaune</styleUrl><Style><IconStyle><scale>0.625</scale></IconStyle></Style><Point><altitudeMode>absolute</altitudeMode><coordinates>120.3089,-10.551,0</coordinates></Point><LookAt><longitude>120.3089</longitude><latitude>-10.551</latitude><range>1000000</range></LookAt></Placemark></Folder><Style id="inactive_rouge"><IconStyle><Icon><href>https://static2.emsc.eu/Images/evt/c8-rouge.png</href></Icon></IconStyle><LabelStyle><scale>0</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="active_rouge"><IconStyle><Icon><href>https://static2.emsc.eu/Images/evt/c8-rouge.png</href></Icon></IconStyle><LabelStyle><scale>1</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="inactive_jaune"><IconStyle><Icon><href>https://static3.emsc.eu/Images/evt/c8-jaune.png</href></Icon></IconStyle><LabelStyle><scale>0</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="active_jaune"><IconStyle><Icon><href>https://static3.emsc.eu/Images/evt/c8-jaune.png</href></Icon></IconStyle><LabelStyle><scale>1</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="inactive_vert"><IconStyle><Icon><href>https://static1.emsc.eu/Images/evt/c8-vert.png</href></Icon></IconStyle><LabelStyle><scale>0</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="active_vert"><IconStyle><Icon><href>https://static1.emsc.eu/Images/evt/c8-vert.png</href></Icon></IconStyle><LabelStyle><scale>1</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="inactive_bleu"><IconStyle><Icon><href>https://static2.emsc.eu/Images/evt/c8-bleu.png</href></Icon></IconStyle><LabelStyle><scale>0</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="active_bleu"><IconStyle><Icon><href>https://static2.emsc.eu/Images/evt/c8-bleu.png</href></Icon></IconStyle><LabelStyle><scale>1</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="inactive_violet"><IconStyle><Icon><href>https://static3.emsc.eu/Images/evt/c8-violet.png</href></Icon></IconStyle><LabelStyle><scale>0</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><Style id="active_violet"><IconStyle><Icon><href>https://static3.emsc.eu/Images/evt/c8-violet.png</href></Icon></IconStyle><LabelStyle><scale>1</scale></LabelStyle><BalloonStyle><text><![CDATA[<font face="Verdana"><table width="400"><tr><td><img src="https://www.emsc-csem.org/Css/img/logo.png" alt="EMSC" width="150" height="82" /><br/>$[description]</td></tr></table></font>]]></text></BalloonStyle></Style><StyleMap id="rouge"><Pair><key>normal</key><styleUrl>#inactive_rouge</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#active_rouge</styleUrl></Pair></StyleMap><StyleMap id="jaune"><Pair><key>normal</key><styleUrl>#inactive_jaune</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#active_jaune</styleUrl></Pair></StyleMap><StyleMap id="vert"><Pair><key>normal</key><styleUrl>#inactive_vert</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#active_vert</styleUrl></Pair></StyleMap><StyleMap id="bleu"><Pair><key>normal</key><styleUrl>#inactive_bleu</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#active_bleu</styleUrl></Pair></StyleMap><StyleMap id="violet"><Pair><key>normal</key><styleUrl>#inactive_violet</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#active_violet</styleUrl></Pair></StyleMap><ScreenOverlay><name>EMSC Legend</name><color>ccffffff</color><Icon><href>https://static1.emsc.eu/Images/legendge.png</href></Icon><overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/><screenXY x="0.01" y="0.02" xunits="fraction" yunits="fraction"/></ScreenOverlay><ScreenOverlay><name>EMSC Logo</name><color>ccffffff</color><Icon><href>https://static2.emsc.eu/Images/logoge.png</href></Icon><overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/><screenXY x="0.5" y="0.99" xunits="fraction" yunits="fraction"/></ScreenOverlay></Document></kml>';

html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://cdn.jsdelivr.net/gh/geocodezip/geoxml3@master/polys/geoxml3.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>


问:
Compare or align 3D objects
I have two 3D matrices. Each pixel is a gray scale value.

The first 3D matrix is a reference shape. e.g. imagine a 3D model of a mouth.

The second 3D matrix is an approximate subsection of the reference shape. e.g. imagine a tooth. The subsection is approximate as it is from a different mouth. Note the subsection could be slightly oblique.

The challenge is to identify what are the coordinates of the subsection inside the reference matrix. Expanding on the mouth example above, the challenge is to identify what tooth the second 3D matrix most accurately represents.

The output could be a 3D pixel location and an orientation value.

答:
You  can use imregister, imregtform and imwarp to automatically align two volumetric datasets. See matlab's documentation for an example...
Or if you want to work harder, convolve in 6D (convn) where you start with (x,y,z,theta=0,phi=0,psi=0) for the first matrix, and create a representation of the 3d tooth in all angle projections....

Title: Compare or align 3D objects


问:
my nodejs script is not exiting on its own after successful execution
I have written a script to update my db table after reading data from db tables and solr. I am using asyn.waterfall module. The problem is that the script is not getting exited after successful completion of all operations. I have used db connection pool also thinking that may be creating the script to wait infinitly.
I want to put this script in crontab and if it will not exit properly it would be creating a hell lot of instances unnecessarily.</p>

答:
We can quit the execution by using:</p>

```<code>connection.destroy();
</code>```

Body:
We can quit the execution by using:

connection.destroy();


问:
Django: Filter for get_foo_display in a Queryset
I've been trying to filter a queryset on a simple model but with no luck so far.

Here is my model:

```<code>class Country(models.Model):
    COUNTRY_CHOICES = (
        ('FR', _(u'France')),
        ('VE', _(u'Venezuela')),
    )

    code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)

    def __unicode__(self):
        return self.get_code_display()
</code>```

And I would like to do something like:

```<code>Country.objects.filter(get_code_display__icontains="france")
Country.objects.filter(code__display__icontains="france")
Country.objects.filter(get_code_display__icontains="france")
</code>```

But none of those above are working. How do you filter on a field that has a choices attribute? I thought the overridden __unicode__ would help but I guess I'm missing something.

答:
You can use Choices

```<code>from model_utils import Choices

class Country(models.Model):
    COUNTRY_CHOICES = Choices((
        ('FR', _(u'France')),
        ('VE', _(u'Venezuela')),
    ))

    code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)
</code>```

And make a query:

```<code>Country.objects.filter(code=Country.COUNTRY_CHOICES.france)
</code>```

Body:
I've been trying to filter a queryset on a simple model but with no luck so far.

Here is my model:

class Country(models.Model):
    COUNTRY_CHOICES = (
        ('FR', _(u'France')),
        ('VE', _(u'Venezuela')),
    )

    code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)

    def __unicode__(self):
        return self.get_code_display()

And I would like to do something like:

Country.objects.filter(get_code_display__icontains="france")
Country.objects.filter(code__display__icontains="france")
Country.objects.filter(get_code_display__icontains="france")

But none of those above are working. How do you filter on a field that has a choices attribute? I thought the overridden __unicode__ would help but I guess I'm missing something.

Body:
You can use Choices

from model_utils import Choices

class Country(models.Model):
    COUNTRY_CHOICES = Choices((
        ('FR', _(u'France')),
        ('VE', _(u'Venezuela')),
    ))

    code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)

And make a query:

Country.objects.filter(code=Country.COUNTRY_CHOICES.france)


问:
Encryption Algorithm
I am creating an application which uses a steganography algorithm. Now I can encrypt and decrypt text. But I want my application to ask for password after encrypting the text into the image, so that whenever someone will decrypt the image it would ask for the password for authentication. Is this even possible? If yes, how?</p>

答: strictly speaking, steganography isn't encryption, it's simply an encoding. If you want the encoded message to be truly encrypted, then use a trusted algorithm (don't be tempted to invent one!). as Andre suggests in another answer, AES would be fine.

Title: Encryption Algorithm


问:
"Index Out Of Range" error in UICollectionView when dataSource array is correct
I'm using sizeForItemAt indexPath with a UICollectionView.

When I commit an action to remove an item from the collectionView and from the dataSource array, I call reloadData. However, in sizeForItem, I'm getting a Fatal error: Index out of range.

The dataSource count is correct, and is reflecting the change. For example, from 4 to 3 items. The indexPath that sizeForItem is trying to access is 0 - 3, the fourth index.

Why am I getting this error? Does it matter that sizeForItem runs before either cellForItem or numberOfItemsInSection?

After removing the item and calling reloadData, sizeForItem is called. Here are the delegate and dataSource methods:

```<code>func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath)
    cell.updateStyle
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let view = array[indexPath.row]
    return view.intrinsicContentSize
}
</code>```

Please let me know if I can clarify.

Edit: Here's where I'm removing the item from the dataSource array

```<code>func deleteItem() {
    removeItem(item)
    collectionView.reloadData()
}
</code>```

答:
As @ozzieozumo said, the call to sizeForItemAt indexPath was getting called before reloadData.

After mutating the dataSource array, I changed the reloadData call to come first.

Body:
I'm using sizeForItemAt indexPath with a UICollectionView.

When I commit an action to remove an item from the collectionView and from the dataSource array, I call reloadData. However, in sizeForItem, I'm getting a Fatal error: Index out of range.

The dataSource count is correct, and is reflecting the change. For example, from 4 to 3 items. The indexPath that sizeForItem is trying to access is 0 - 3, the fourth index.

Why am I getting this error? Does it matter that sizeForItem runs before either cellForItem or numberOfItemsInSection?

After removing the item and calling reloadData, sizeForItem is called. Here are the delegate and dataSource methods:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath)
    cell.updateStyle
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let view = array[indexPath.row]
    return view.intrinsicContentSize
}

Please let me know if I can clarify.

Edit: Here's where I'm removing the item from the dataSource array

func deleteItem() {
    removeItem(item)
    collectionView.reloadData()
}


问:
Scraping href, teams, odds off bet site
I am trying to scrape data off of this website.  The page uses heavy javascript and I am struggling to get the href and odds off it.

My current output looks like this:

I am wanting my output to look similar to... (in green):

```<code>class BlueBet(scrapy.Spider):
    name = "BlueBet"
    start_urls = ['https://www.bluebet.com.au/api/sports/SportsMasterCategory?withLevelledMarkets=true&id=100']

    custom_settings = {
        'FEED_FORMAT': 'csv',
        'FEED_URI': 'odds.csv',
        'FEED_EXPORT_ENCODING': 'utf-8',
    }

    def parse(self, response):
        data = json.loads(response.body)

        for master_category in data['MasterCategories']:
            for category in master_category['Categories']:
                for event in category['MasterEvents']:
                    item = {}
                    item['Event_name'] = event.get('MasterEventName')
                    item['Outcomes'] = {}
                    try:
                        for market in event['Markets']:
                            item['Outcomes'][market.get('OutcomeName')] = market.get('Price')
                    except TypeError:
                        continue
                    yield item
</code>```

答:
You get data like this

```<code>{
    'Event_name': 'Melbourne Victory v Adelaide United',
    'Outcomes': {
        'Melbourne Victory': 2.05,
        'Draw': 3.5,
        'Adelaide United': 3.4
     }
}
</code>```

and you want to split Outcomes into separated columns.

But columns need names in scrapy Item.

I will use names key1, val1,  key2, val2, key3, val3

```<code>data = {'Event_name': 'Melbourne Victory v Adelaide United',
  'Outcomes': {'Melbourne Victory': 2.05, 'Draw': 3.5, 'Adelaide United': 3.4}}

# ---

item = {'Event_name': data['Event_name']}

for number, (key, val) in enumerate(data['Outcomes'].items(), 1):
    number = str(number)
    print(number, key, val)
    item["key"+number] = key
    item["val"+number] = val

print(item)
</code>```

and this gives item

```<code>{
    'Event_name': 'Melbourne Victory v Adelaide United',
    'key1': 'Melbourne Victory',
    'val1': 2.05,
    'key2': 'Draw',
    'val2': 3.5,
    'key3': 'Adelaide United',
    'val3': 3.4
}
</code>```

And this should gives you data in separated columns in Excel.

Title: Scraping href, teams, odds off bet site

Body:
I am trying to scrape data off of this website.  The page uses heavy javascript and I am struggling to get the href and odds off it.

My current output looks like this:

I am wanting my output to look similar to... (in green):

class BlueBet(scrapy.Spider):
    name = "BlueBet"
    start_urls = ['https://www.bluebet.com.au/api/sports/SportsMasterCategory?withLevelledMarkets=true&id=100']

    custom_settings = {
        'FEED_FORMAT': 'csv',
        'FEED_URI': 'odds.csv',
        'FEED_EXPORT_ENCODING': 'utf-8',
    }

    def parse(self, response):
        data = json.loads(response.body)

        for master_category in data['MasterCategories']:
            for category in master_category['Categories']:
                for event in category['MasterEvents']:
                    item = {}
                    item['Event_name'] = event.get('MasterEventName')
                    item['Outcomes'] = {}
                    try:
                        for market in event['Markets']:
                            item['Outcomes'][market.get('OutcomeName')] = market.get('Price')
                    except TypeError:
                        continue
                    yield item

Body:
You get data like this

{
    'Event_name': 'Melbourne Victory v Adelaide United',
    'Outcomes': {
        'Melbourne Victory': 2.05,
        'Draw': 3.5,
        'Adelaide United': 3.4
     }
}

and you want to split Outcomes into separated columns.

But columns need names in scrapy Item.

I will use names key1, val1,  key2, val2, key3, val3

data = {'Event_name': 'Melbourne Victory v Adelaide United',
  'Outcomes': {'Melbourne Victory': 2.05, 'Draw': 3.5, 'Adelaide United': 3.4}}

# ---

item = {'Event_name': data['Event_name']}

for number, (key, val) in enumerate(data['Outcomes'].items(), 1):
    number = str(number)
    print(number, key, val)
    item["key"+number] = key
    item["val"+number] = val

print(item)

and this gives item

{
    'Event_name': 'Melbourne Victory v Adelaide United',
    'key1': 'Melbourne Victory',
    'val1': 2.05,
    'key2': 'Draw',
    'val2': 3.5,
    'key3': 'Adelaide United',
    'val3': 3.4
}

And this should gives you data in separated columns in Excel.


问:
How to specify numba jitclass when the class's attribute contains another class instance?
I'm trying to use numba to boost the python performance of scipy.integrate.odeint.
To this end, I have to use @nb.jit(nopython=True) for the function defining the ODE system. However, this function has to take another python-class instance as an argument in my program. I had to jit the class also with @nb.jitclass(spec) with appropriate specs. This worked fine, until I found a serious issue when the specs of the class includes another type of class instance as its method. My code is following.

```<code>import numba as nb
from scipy.integrate import odeint

spec1=[("hi", nb.i4)]
@nb.jitclass(spec1)
class Hi(object):
    def __init__(self):
        self.hi = 0

spec2=[("dummy", nb.i4), ("dummy1", nb.i4)]
@nb.jitclass(spec2)
class Dummy(object):
    def __init__(self, anotherClassInstance):
        self.dummy = 0
        self.dummy1 = anotherClassInstance

class A:
    def __init__(self, someClassInstance):
        self.a1 = someClassInstance

    def odeSystem(self, x, t):
        return _odeSystem(x, t, self.a1)

    def odeSolve(self, iValues, ts):
        sol = odeint(self.odeSystem, iValues, ts)
        return sol

@nb.jit(nopython=True)
def _odeSystem(x, t, someClassInstance):
    return 1-x

if __name__ == "__main__":
    c = Hi()
    b = Dummy(c)
    a = A(b)
    print a.odeSolve(0.5, range(0, 10))
</code>```

In summary:
So here "class A" is my ode solver.

To compile the method "odeSystem" with numba, it must not a class method. So I made another function outside of the class "_odeSystem".

Unfortunately however, my odeSystem has to have a class instance as an argument. Hence I used @jitclass to compile the class instance argument properly.

I again encountered another problem, where this class "Dummy" also takes another type of class instance as one of its attribute. I have no idea how to set "spec" for this class. I tried the type for "dummy1" with "nb.typeof(Hi)" but it didn't work.

Please help me. Thanks in advance.

答:
You can use .class_type.instance_type in your spec definition for holding an instance of another type.  See example in the numba source tree here

```<code>spec2=[("dummy", nb.i4), ("dummy1", Hi.class_type.instance_type)]
@nb.jitclass(spec2)
class Dummy(object):
    def __init__(self, anotherClassInstance):
        self.dummy = 0
        self.dummy1 = anotherClassInstance
</code>```

Body:
I'm trying to use numba to boost the python performance of scipy.integrate.odeint.
To this end, I have to use @nb.jit(nopython=True) for the function defining the ODE system. However, this function has to take another python-class instance as an argument in my program. I had to jit the class also with @nb.jitclass(spec) with appropriate specs. This worked fine, until I found a serious issue when the specs of the class includes another type of class instance as its method. My code is following.

import numba as nb
from scipy.integrate import odeint

spec1=[("hi", nb.i4)]
@nb.jitclass(spec1)
class Hi(object):
    def __init__(self):
        self.hi = 0

spec2=[("dummy", nb.i4), ("dummy1", nb.i4)]
@nb.jitclass(spec2)
class Dummy(object):
    def __init__(self, anotherClassInstance):
        self.dummy = 0
        self.dummy1 = anotherClassInstance

class A:
    def __init__(self, someClassInstance):
        self.a1 = someClassInstance

    def odeSystem(self, x, t):
        return _odeSystem(x, t, self.a1)

    def odeSolve(self, iValues, ts):
        sol = odeint(self.odeSystem, iValues, ts)
        return sol

@nb.jit(nopython=True)
def _odeSystem(x, t, someClassInstance):
    return 1-x

if __name__ == "__main__":
    c = Hi()
    b = Dummy(c)
    a = A(b)
    print a.odeSolve(0.5, range(0, 10))

In summary:
So here "class A" is my ode solver.

To compile the method "odeSystem" with numba, it must not a class method. So I made another function outside of the class "_odeSystem".

Unfortunately however, my odeSystem has to have a class instance as an argument. Hence I used @jitclass to compile the class instance argument properly.

I again encountered another problem, where this class "Dummy" also takes another type of class instance as one of its attribute. I have no idea how to set "spec" for this class. I tried the type for "dummy1" with "nb.typeof(Hi)" but it didn't work.

Please help me. Thanks in advance.

Body:
You can use .class_type.instance_type in your spec definition for holding an instance of another type.  See example in the numba source tree here

spec2=[("dummy", nb.i4), ("dummy1", Hi.class_type.instance_type)]
@nb.jitclass(spec2)
class Dummy(object):
    def __init__(self, anotherClassInstance):
        self.dummy = 0
        self.dummy1 = anotherClassInstance