问:
Ocaml List: Implement append and map functions
I'm currently trying to extend a friend's OCaml program. It's a huge collection of functions needed for some data analysis.. Since I'm not really an OCaml crack I'm currently stuck on a (for me) strange List implementation:

```<code>type 'a cell = Nil
    | Cons of ('a * 'a llist)
and 'a llist = (unit -> 'a cell);;
</code>```

I've figured out that this implements some sort of "lazy" list, but I have absolutely no idea how it really works. I need to implement an Append and a Map Function based on the above type. Has anybody got an idea how to do that?

Any help would really be appreciated!

答:
It might help to note that function closures are essentially equivalent to lazy values:

```<code>lazy n : 'a Lazy.t    <=>    (fun () -> n) : unit -> 'a
force x : 'a          <=>    x () : 'a
</code>```

So the type 'a llist is equivalent to

```<code>type 'a llist = 'a cell Lazy.t
</code>```

i.e., a lazy cell value.

A map implementation might make more sense in terms of the above definition

```<code>let rec map f lst =
  match force lst with
    | Nil -> lazy Nil
    | Cons (hd,tl) -> lazy (Cons (f hd, map f tl))
</code>```

Translating that back into closures:

```<code>let rec map f lst =
  match lst () with
    | Nil -> (fun () -> Nil)
    | Cons (hd,tl) -> (fun () -> Cons (f hd, map f tl))
</code>```

Similarly with append

```<code>let rec append a b =
  match force a with
    | Nil -> b
    | Cons (hd,tl) -> lazy (Cons (hd, append tl b))
</code>```

becomes

```<code>let rec append a b =
  match a () with
    | Nil -> b
    | Cons (hd,tl) -> (fun () -> Cons (hd, append tl b))
</code>```

I generally prefer to use the lazy syntax, since it makes it more clear what's going on.

Note, also, that a lazy suspension and a closure are not exactly equivalent. For example,

```<code>let x = lazy (print_endline "foo") in
  force x;
  force x
</code>```

prints

```<code>foo
</code>```

whereas

```<code>let x = fun () -> print_endline "foo" in
  x ();
  x ()
</code>```

prints

```<code>foo
foo
</code>```

The difference is that force computes the value of the expression exactly once.

OwnerDisplayName: Chriss

ContentLicense: CC BY-SA 2.5

Body:
I'm currently trying to extend a friend's OCaml program. It's a huge collection of functions needed for some data analysis.. Since I'm not really an OCaml crack I'm currently stuck on a (for me) strange List implementation:

type 'a cell = Nil
    | Cons of ('a * 'a llist)
and 'a llist = (unit -> 'a cell);;

I've figured out that this implements some sort of "lazy" list, but I have absolutely no idea how it really works. I need to implement an Append and a Map Function based on the above type. Has anybody got an idea how to do that?

Any help would really be appreciated!

LastEditorDisplayName: starblue

Body:
It might help to note that function closures are essentially equivalent to lazy values:

lazy n : 'a Lazy.t    <=>    (fun () -> n) : unit -> 'a
force x : 'a          <=>    x () : 'a

So the type 'a llist is equivalent to

type 'a llist = 'a cell Lazy.t

i.e., a lazy cell value.

A map implementation might make more sense in terms of the above definition

let rec map f lst =
  match force lst with
    | Nil -> lazy Nil
    | Cons (hd,tl) -> lazy (Cons (f hd, map f tl))

Translating that back into closures:

let rec map f lst =
  match lst () with
    | Nil -> (fun () -> Nil)
    | Cons (hd,tl) -> (fun () -> Cons (f hd, map f tl))

Similarly with append

let rec append a b =
  match force a with
    | Nil -> b
    | Cons (hd,tl) -> lazy (Cons (hd, append tl b))

becomes

let rec append a b =
  match a () with
    | Nil -> b
    | Cons (hd,tl) -> (fun () -> Cons (hd, append tl b))

I generally prefer to use the lazy syntax, since it makes it more clear what's going on.

Note, also, that a lazy suspension and a closure are not exactly equivalent. For example,

let x = lazy (print_endline "foo") in
  force x;
  force x

prints

foo

whereas

let x = fun () -> print_endline "foo" in
  x ();
  x ()

prints

foo
foo

The difference is that force computes the value of the expression exactly once.

OwnerDisplayName: Chris Conway

LastEditorDisplayName: Chris Conway


来源: stackexchange

问:
Cannot install openslide-python on google datalabs Jupyter notebook
I am trying to install openslide-python on google datalabs Jupyter notebook using:
        !apt-get install python-openslide

It runs, until it prints out:

```<code>   Need to get 13.0 MB of archives.
   After this operation, 44.7 MB of additional disk space will be used.
   Do you want to continue? [Y/n]
</code>```

I type in Y in the next cell, and hit run. It says running... but nothing seems to happen.
How do it get to install python-openslide here ?

答:
Please can you try the following which includes the -y option?

```<code>!apt-get install -y python-openslide
</code>```

Here is the definition of the -y option for apt-get from http://manpages.ubuntu.com/manpages/wily/man8/apt-get.8.html.

```<code>   -y, --yes, --assume-yes
       Automatic yes to prompts; assume "yes" as answer to all prompts and
       run non-interactively. If an undesirable situation, such as
       changing a held package, trying to install a unauthenticated
       package or removing an essential package occurs then apt-get will
       abort. Configuration Item: APT::Get::Assume-Yes.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to install openslide-python on google datalabs Jupyter notebook using:
        !apt-get install python-openslide

It runs, until it prints out:

   Need to get 13.0 MB of archives.
   After this operation, 44.7 MB of additional disk space will be used.
   Do you want to continue? [Y/n]

I type in Y in the next cell, and hit run. It says running... but nothing seems to happen.
How do it get to install python-openslide here ?

Body:
Please can you try the following which includes the -y option?

!apt-get install -y python-openslide

Here is the definition of the -y option for apt-get from http://manpages.ubuntu.com/manpages/wily/man8/apt-get.8.html.

   -y, --yes, --assume-yes
       Automatic yes to prompts; assume "yes" as answer to all prompts and
       run non-interactively. If an undesirable situation, such as
       changing a held package, trying to install a unauthenticated
       package or removing an essential package occurs then apt-get will
       abort. Configuration Item: APT::Get::Assume-Yes.


问:
Rails: Controller code out of control
First off, I must apologize for the punny title.

With that out of the way, I'm new to RoR and I am working on a small project that is slowly growing in size. One of the controllers is now a mess of logic that I would like to refactor it.

What I'm seeing from a multitude of questions/answers out there on this topic is mostly fragmented information on what I think is best practice. I'm having a hard time seeing the big picture. The sites for "where to put code?" have a high level information and miss the nitty-gritty.

Here's the question:

What's the best practice for refactoring code out of Controllers? (Locations, type of code)

Background: My app does not use a database, the code in the controller is mostly HTTP calls to external APIs based on params from a form, and a few lines of logic for creating arrays with fetched data for the view to consume. Some of these API calls depend on previously fetched info.

Thank you very much in advance!

MP

答:
Using the single responsibility principle, I would create classes in app/support/, app/services to achieve the desired functionality that you have currently sitting in your controller. The controller should be about sending/receiving the requests, dish off the grunt work to your "support" classes. I found this useful for this problem.

If you can justify that the functionality is concerned with a particular model and only that model, then use the model. I have seen the argument that you could use your model's for this logic, however my opinion is that a particular model should contain code only concerned with that model alone.

Title: Rails: Controller code out of control


问:
Get the First Parent(Volume Name or Drive Letter) from File using Java

First Question(Actually this one i need more)

I have searched through the google and i can't find how to do it .
For example i have the path :

```<code>C:\Users\Alexander\Desktop\Hello\Hello2\AudioFile.mp3
</code>```

I want to get the name of the drive|volume containing this File , here it is C

What i was doing until now is :

```<code>new File(path).substring(0,1);
</code>```

But what if the drive has two letters..

Second Question

What if i want to get the 3rd Parent of The File it it exists(Desktop).

Can you please provide an answer on the above?

Ps:
I have found Paths.get(path).getRoot().toString() but it returns C:\

答:
Apache Commons IO has a FilenameUtils class and its getPrefix() method does what you asked in question 1 .

I suppose You can find a work around for the 2 Question from Apache Commons IO.

```<code>String filename = "C:\Users\Alexander\Desktop\Hello\Hello2\AudioFile.mp3";

String prefix = FilenameUtils.getPrefix(filename);
System.out.println("Prefix: " + prefix);

String path = FilenameUtils.getPath(filename);
System.out.println("Path: " + path);

String fullPath = FilenameUtils.getFullPath(filename);
System.out.println("Full path: " + fullPath);

String name = FilenameUtils.getName(filename);
System.out.println("Name: " + name);

String baseName = FilenameUtils.getBaseName(filename);
System.out.println("Base name: " + baseName);

String extension = FilenameUtils.getExtension(filename);
System.out.println("Extension: " + extension);
</code>```

Body:
First Question(Actually this one i need more)

I have searched through the google and i can't find how to do it .
For example i have the path :

C:\Users\Alexander\Desktop\Hello\Hello2\AudioFile.mp3

I want to get the name of the drive|volume containing this File , here it is C

What i was doing until now is :

new File(path).substring(0,1);

But what if the drive has two letters..

Second Question

What if i want to get the 3rd Parent of The File it it exists(Desktop).

Can you please provide an answer on the above?

Ps:
I have found Paths.get(path).getRoot().toString() but it returns C:\

Body:
Apache Commons IO has a FilenameUtils class and its getPrefix() method does what you asked in question 1 .

I suppose You can find a work around for the 2 Question from Apache Commons IO.

String filename = "C:\Users\Alexander\Desktop\Hello\Hello2\AudioFile.mp3";

String prefix = FilenameUtils.getPrefix(filename);
System.out.println("Prefix: " + prefix);

String path = FilenameUtils.getPath(filename);
System.out.println("Path: " + path);

String fullPath = FilenameUtils.getFullPath(filename);
System.out.println("Full path: " + fullPath);

String name = FilenameUtils.getName(filename);
System.out.println("Name: " + name);

String baseName = FilenameUtils.getBaseName(filename);
System.out.println("Base name: " + baseName);

String extension = FilenameUtils.getExtension(filename);
System.out.println("Extension: " + extension);


问:
How to count checked checkbox with Javascript?
I would like to count the checkboxes that are checked and display the count in the Div.

Here is my HTML :

```<code><form name="liste_figurine" method="post">

<input type="checkbox" id="radio-1" class="z" name="chck1[]" onclick="updateCount()" />
<input type="checkbox" id="radio-2" class="z" name="chck2[]" onclick="updateCount()" />

</form>

<div id="y"></div>
</code>```

Here is my JS :

```<code>function updateCount {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};
</code>```

Here is an exemple : https://jsfiddle.net/r3todbs6/3/

Sorry, I'm not really used to JS... What is wrong with my code ?

Finally, it's working but I have one last issue : the onclick must contain 2 functions and I don't manage to make them working together.

Now this function works, alone : onclick="updateCount()"

This other function works also, alone : onclick="document.getElementById(\'radio-'.$ligne['id'].'-2\').checked = false"

But these two functions doesn't work, together :
onclick="updateCount(); fx2(document.getElementById(\'radio-'.$ligne['id'].'-1\').checked = false);"

What is wrong with the third proposition ? Is it a syntax error ?

答:
There are three issues for your Fiddle code:

As others have mentioned, it should be length, not size().

You should change the JavaScript setting -> Load type to "No wrap - in ". Otherwise, updateCount is not defined in global scope.

You need to configure Fiddle to use jQuery if you use your original code.

A working example: https://jsfiddle.net/c5ez4w7y/

Body:
I would like to count the checkboxes that are checked and display the count in the Div.

Here is my HTML :

<form name="liste_figurine" method="post">

<input type="checkbox" id="radio-1" class="z" name="chck1[]" onclick="updateCount()" />
<input type="checkbox" id="radio-2" class="z" name="chck2[]" onclick="updateCount()" />

</form>

Here is my JS :

function updateCount {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};

Here is an exemple : https://jsfiddle.net/r3todbs6/3/

Sorry, I'm not really used to JS... What is wrong with my code ?

Finally, it's working but I have one last issue : the onclick must contain 2 functions and I don't manage to make them working together.

Now this function works, alone : onclick="updateCount()"

This other function works also, alone : onclick="document.getElementById(\'radio-'.$ligne['id'].'-2\').checked = false"

But these two functions doesn't work, together :
onclick="updateCount(); fx2(document.getElementById(\'radio-'.$ligne['id'].'-1\').checked = false);"

What is wrong with the third proposition ? Is it a syntax error ?

Body:
There are three issues for your Fiddle code:

As others have mentioned, it should be length, not size().

You should change the JavaScript setting -> Load type to "No wrap - in <head>". Otherwise, updateCount is not defined in global scope.

You need to configure Fiddle to use jQuery if you use your original code.

A working example: https://jsfiddle.net/c5ez4w7y/


答:
```<code>function updateCount {
    var x = document.querySelector('.z:checked').length;
    document.getElementById("y").innerHTML = x;
};
</code>```

try this fuction if you don't want to use jQuery

Title: How to count checked checkbox with Javascript?

Body:
function updateCount {
    var x = document.querySelector('.z:checked').length;
    document.getElementById("y").innerHTML = x;
};

try this fuction if you don't want to use jQuery


问:
How to configure a dynamic autocomplete in Orbeon Forms?
I need to use a dynamic autocomplete based on ws rest to show suggestions of my field. I used it but it didn't work, it didn't update the list of suggestions. Example:

```<code><fr:autocomplete
        id="control-3-control"
        appearance="minimal"
        labelref="@label"
        resource="http://127.0.0.1/api/ws/pays/all"
        bind="control-3-bind">

    <xf:label ref="$form-resources/control-3/label"/>
    <xf:hint ref="$form-resources/control-3/hint"/>

    <xf:alert ref="$fr-resources/detail/labels/alert"/>
    <xf:itemset ref="./_">
        <xf:label ref=".//libelle"/>
        <xf:value ref=".//id"/>
    </xf:itemset>
</fr:autocomplete>
</code>```

And this is the screenshot:

答:
Doing the "filtering" based on the value entered by users is the responsibility of the service the autocomplete is calling. However, it can't do this if you don't provide it with the current value of the field. For this, use {$fr-search-value} somewhere in the URL, e.g. something like:

```<code>http://127.0.0.1/api/ws/pays/all?search={$fr-search-value}
</code>```

And of course, then your service needs to take the value of the search request parameter into account. The autocomplete component will automatically call the service again and again, as necessary as users type in the field.

This allows you to search in a large dataset without having to return the whole set of possible values to Orbeon Forms.

Body:
I need to use a dynamic autocomplete based on ws rest to show suggestions of my field. I used it but it didn't work, it didn't update the list of suggestions. Example:

<fr:autocomplete
        id="control-3-control"
        appearance="minimal"
        labelref="@label"
        resource="http://127.0.0.1/api/ws/pays/all"
        bind="control-3-bind">

    <xf:label ref="$form-resources/control-3/label"/>
    <xf:hint ref="$form-resources/control-3/hint"/>

    <xf:alert ref="$fr-resources/detail/labels/alert"/>
    <xf:itemset ref="./_">
        <xf:label ref=".//libelle"/>
        <xf:value ref=".//id"/>
    </xf:itemset>
</fr:autocomplete>

And this is the screenshot:

Body:
Doing the "filtering" based on the value entered by users is the responsibility of the service the autocomplete is calling. However, it can't do this if you don't provide it with the current value of the field. For this, use {$fr-search-value} somewhere in the URL, e.g. something like:

http://127.0.0.1/api/ws/pays/all?search={$fr-search-value}

And of course, then your service needs to take the value of the search request parameter into account. The autocomplete component will automatically call the service again and again, as necessary as users type in the field.

This allows you to search in a large dataset without having to return the whole set of possible values to Orbeon Forms.


问:
How to make selector choose div class and with tag name of p?
Hello I am kind of stuck right now. I am trying to make my script choose all paragraph inside a div class of change but I don't really understand how to do it. The html looks something like this in the body

```<code><body>
<div id="top" class="change">
<p> Microsoft </p>
<p> Apple </p>
<p> Sony </p>
</div>

<div id="middle">
<p> Disney </p>
<p> Nintendo </p>
<p> Sony </p>
</div>

<div id="bottom" class="change">
<p> Ice</p>
<p> Tea</p>
<p> Water</p>
</div>
</body>
</code>```

I am trying to make it so when the mouse cursor touches anything that has a class of change in a paragraph, it will change the color to a color of my choice but I don't know how to do it with selectors with pure javascript. This is the current code I have but it is not working. I can only use javascript

```<code>var fontChange = document.getElementsByClass("change").getElementsByTagName("p");

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseover=function() {
        this.style.color = "red";
    }
}

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseout=function() {
        this.style.color = "black";
    }
}
</code>```

答:
There's no function getElementsByClass, it's getElementsByClassName.

document.getElementsByClassName() returns a collection (see What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?), you have to index it to use getElementsByTagName on the elements that it returns.

```<code>var fontChange = [];
var change = document.getElementsByClassName("change");
for (var i = 0; i < change.length; i++) {
    var paras = [].slice.call(change[i].getElementsByTagName("p"));
    fontChange.concat(paras);
}
</code>```

Or you could just use querySelectorAll

```<code>var fontChange = document.querySelectorAll(".change p");
</code>```

You also have a typo. You set the variable fontChange, but then use changeFont in the loop.

Body:
Hello I am kind of stuck right now. I am trying to make my script choose all paragraph inside a div class of change but I don't really understand how to do it. The html looks something like this in the body

 Microsoft

 Apple

 Sony

 Disney

 Nintendo

 Sony

 Ice

 Tea

 Water

I am trying to make it so when the mouse cursor touches anything that has a class of change in a paragraph, it will change the color to a color of my choice but I don't know how to do it with selectors with pure javascript. This is the current code I have but it is not working. I can only use javascript

var fontChange = document.getElementsByClass("change").getElementsByTagName("p");

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseover=function() {
        this.style.color = "red";
    }
}

for (let i = 0; i < changeFont.length; i++) {
    changeFont[i].onmouseout=function() {
        this.style.color = "black";
    }
}

Body:
There's no function getElementsByClass, it's getElementsByClassName.

document.getElementsByClassName() returns a collection (see What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?), you have to index it to use getElementsByTagName on the elements that it returns.

var fontChange = [];
var change = document.getElementsByClassName("change");
for (var i = 0; i < change.length; i++) {
    var paras = [].slice.call(change[i].getElementsByTagName("p"));
    fontChange.concat(paras);
}

Or you could just use querySelectorAll

var fontChange = document.querySelectorAll(".change p");

You also have a typo. You set the variable fontChange, but then use changeFont in the loop.


问:
Any latex web services with an API?
Is there a web service API that takes this type of a latex http-request:

```<code>http://some_web_service/texfile?texfile=

\new\documentclass[12pt]{article}
\begin{document}
  bla
\end{document}
</code>```

and returns:

```<code>bla.pdf
</code>```

答: Fundamentally, this shouldn't be any different than a build server like you see for lots of open source projects (along the lines of Koji for example).  Ultimately, you would just hook into pdflatex instead of gcc.</p>

Title: Any latex web services with an API?

Body:
Is there a web service API that takes this type of a latex http-request:

http://some_web_service/texfile?texfile=

\new\documentclass[12pt]{article}
\begin{document}
  bla
\end{document}

and returns:

bla.pdf


问:
How to set the metadata type according to the file format?
Example:

if bitstream format =

```<code>   .mp4
   .mpeg
   .avi
</code>```

set dc.type = video

if bitstream format =

```<code>   .pdf
   .text
   .doc
</code>```

set dc.type = text

if bitstream format =

```<code>   .png
   .jpeg
   .gif
</code>```

set dc.type = image

etc...

It is possible do this for internal collections and collections collected externally via harvest?

Via database or altering source-code?

答:
I would write a curation task for this, and run it periodically over all items in the harvested collection. In fact I have one right here that does almost what you need -- it populates dc.format.mimetype with the mime types of all ORIGINAL bitstreams in the item.

Terry's suggestion of customising the submission process / the collection template mechanism may not work -- I'm not sure that harvested items go through either of these two processes.

Body:
Example:

if bitstream format =

   .mp4
   .mpeg
   .avi

set dc.type = video

if bitstream format =

   .pdf
   .text
   .doc

set dc.type = text

if bitstream format =

   .png
   .jpeg
   .gif

set dc.type = image

etc...

It is possible do this for internal collections and collections collected externally via harvest?

Via database or altering source-code?


问:
Submitting a form by pressing enter without a submit button
Well I am trying to submit a form by pressing enter but not displaying a submit button. I don't want to get into JavaScript if possible since I want everything to work on all browsers (the only JS way I know is with events).

Right now the form looks like this:

```<code><form name="loginBox" target="#here" method="post">
    <input name="username" type="text" /><br />
    <input name="password" type="password" />
    <input type="submit" style="height: 0px; width: 0px; border: none; padding: 0px;" hidefocus="true" />
</form>
</code>```

Which works pretty well. The submit button works when the user presses enter, and the button doesn't show in Firefox, IE, Safari, Opera and Chrome. However, I still don't like the solution since it is hard to know whether it will work on all platforms with all browsers.

Can anyone suggest a better method? Or is this about as good as it gets?

答:
```<code><input type="submit" style="display:none;"/>
</code>```

This works fine and it is the most explicit version of what you're trying to achieve.

Note that there is a difference between display:none and visibility:hidden for other form elements.

OwnerDisplayName: PythonPower

Body:
Well I am trying to submit a form by pressing enter but not displaying a submit button. I don't want to get into JavaScript if possible since I want everything to work on all browsers (the only JS way I know is with events).

Right now the form looks like this:

<form name="loginBox" target="#here" method="post">
    <input name="username" type="text" />

    <input name="password" type="password" />
    <input type="submit" style="height: 0px; width: 0px; border: none; padding: 0px;" hidefocus="true" />
</form>

Which works pretty well. The submit button works when the user presses enter, and the button doesn't show in Firefox, IE, Safari, Opera and Chrome. However, I still don't like the solution since it is hard to know whether it will work on all platforms with all browsers.

Can anyone suggest a better method? Or is this about as good as it gets?

Body:
<input type="submit" style="display:none;"/>

This works fine and it is the most explicit version of what you're trying to achieve.

Note that there is a difference between display:none and visibility:hidden for other form elements.


答:
```<code>window.updateCount = function() {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};
</code>```

https://jsfiddle.net/73yfczcj/

try this. you have to use jquery in javascript setting.

Body:
window.updateCount = function() {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};

https://jsfiddle.net/73yfczcj/

try this. you have to use jquery in javascript setting.


问:
Cross compile on windows linux subsystem and deploy to target using Visual Studio 2017
I have a beaglebone black for which I want to cross compile on the windows linux subsystem but deploy it afterwards onto the target (Beaglebone). I have installed the cross compiler on the linux subsystem but I'm not quite sure how to hook everything up on the visual studio end.

Basically I want to:

Write code in Visual Studio 2017

Build on the Windows Linux Subsystem

Deploy on the ARM Target over SSH (Beaglebone black)

答:
The first two steps are straightforward and there are several guides for you to read, one of which has been referenced above.

Using WSL, you're only going to be able to target x86 with a simple project type (MSBuild). But you can at least get it compiled and maybe do some debugging.

For the Beaglebone you'll need a makefile project. Visual Studio sees the makefile as a black box that generates a build target. Inside that box you will write the commands to cross-compile to an ARM executable and copy it to the appropriate destination. Build errors will be reported back to Visual Studio but you won't be able to debug the cross-compiled application on the Beaglebone.

You'll find some information here to get you started with makefile projects.


问:
SceneKit game architecture
I am trying to design an architecture for a SceneKit iOS game. I've shown below two rough high level object diagrams/graphs of my current preferred ideas.

I am only looking at the high level architecture at the moment, i.e. managing transition between Menu/GameLevel/Config/Paused app states and making the app data-driven, so that it can handle multiple levels, etc. Once I get this working, then I'll address lower level architecture, e.g. for the GameLevel state I'll have a GameLevelModel object to represent an actual game level logic.

Would be great to hear which one looks more promising, any obvious pitfalls or things to avoid?

Version A) MVC based, with Custom Container & Nested VCs

I'm trying to stay close to the MVC paradigm with this version.

The behaviour of the app changes significantly between its different states (Menu/GameLevel/Config/etc) so I'll be using a permanent container view controller that will manage/transition between several nested VCs, in a parent-child relationship as per Apple's "View Controller Programming Guide for iOS". These will be effectively entire MVCs.

Because none of Apple's container controllers (UINavigation-, UISplitScreen-, UITabBar-) are suitable (I need the entire screen) I'll have a custom container VC (RootViewController) that will have one nested child VC at all times. The View of each child VC will be fully covering the container's one at all times. The transition between child VCs will be managed by the RootVC and driven by its StateMachine.

Each child VC (effectively entire MVC) is created each time when its corresponding state becomes current and then deallocated when it is replaced with next state's one and no longer needed. Similar to how UINavigationController deals with it's contained VCs.

My only worry with this architecture is that it seems a bit heavy. SceneKit looks like it's designed to work with a single SCNView and to transition between multiple SCNScenes when we need to change the 3D content. This gives more transition options as well.

```<code>                         --------------------------
                         |   RootViewController   |
                         --------------------------
                           |  |   |        |    |
     ------------------    |  |   |        |    |      ------------------
     | GameLevelsData |-----  |   |        |    -------|     SCNView    |
     ------------------       |   |        |           ------------------
     ------------------       |   |        |
     |   PlayerData   |--------   |        |
     ------------------           |        |
                                  |        |
                       ----------------    |
                       | StateMachine |    |
                       ----------------    |
                         |                 |
                         |-(*MenuState)    |
                         |-(LevelState)    |
                         |-(ConfigState)   |
                                           |
                                           |
                         ------------------------
                         |  MenuViewController  |
                         ------------------------
      -----------------     |                |      ------------------
      |   MenuData    |------                -------|  MenuSCNView   |
      -----------------                             ------------------

   (child VCs for other States, Level-/Config-/etc are created as needed)
                                           |
                         ------------------------
                         |  LevelViewController |
                         ------------------------
     ------------------     |                |      ------------------
     | GameLevelModel |------                -------|  LevelSCNView  |
     ------------------                             ------------------
</code>```

Version B) Scene-based (one VC, multiple Scenes)

I'll have only one View Controller (GameViewController) with its View (SCNView) and they will last for the entire app lifecycle.
(I will not have container and nested VCs here.)

The change in behaviour and content between app states (Menu/GameLevel/Config/etc) is achieved by the only View transitioning between Scenes and different TouchHandlers (UIResponder subclasses for each state) given First Responder status when relevant.

The (Menu-, GameLevel-, etc) TouchHandler classes will only override touchesBegan/Moved/Ended and canBecomeFirstResponder so that I can intercept touch events without bloating the single controller and view. None of my other objects are UIResponders. I've not tested exactly this part yet.

With each app state the required objects for that state will be created, like corresponding Scene, TouchHandler, (GameLevelModel with game level logic when in GameLevelState), etc and deallocated when next state is entered.

My current issue with this one is, that when using SKTransition to transition between multile SCNScenes on the single SCNView, after 5-20 transitions there is memory leakage. I tried resolving by simplifying the scene, removing all actions, nodes before deallocating but nothing helps. The only way to avoid leakage is avoiding SKTransition and directly assigning scenes to the View's scene property scnView.scene = scnScene. So this will require me to animate my own transitions.

```<code>                         --------------------------
                         |   GameViewController   |
                         --------------------------
                           |  |   |             |
     ------------------    |  |   |             |      ------------------
     | GameLevelsData |-----  |   |             -------|     SCNView    |
     ------------------       |   |                    ------------------
     ------------------       |   |                            |
     |   PlayerData   |--------   |                            |
     ------------------           |                            |
                                  |                            |
                       ----------------                        |
                       | StateMachine |                        |
                       ----------------                        |
                         |                            ------------------
                         |-(*MenuState)---------      |  MenuSCNScene  |
                         |-(LevelState)     |  |      ------------------
                         |-(ConfigState)    |  |
                                            |  |
                     --------------------   |  |
                     | MenuTouchHandler |---|  |
                     --------------------      |
                      -----------------        |
                      |   MenuData    |---------
                      -----------------

              (When entering, each state creates objects of corresponding
              dedicated subclasses for its Model, TouchHandler and Scene)
                                            |  |              |
                    --------------------    |  |     -------------------
                    | LevelTouchHandler |---|  |     |  LevelSCNScene  |
                    --------------------       |     -------------------
                     ------------------        |
                     | GameLevelModel |---------
                     ------------------
</code>```

Thanks in advance.

答:
I'm not quite following your terminology, especially the notion of "child MVC". The acronym MVC in iOS usually refers to the model-view-controller pattern, and in that context I don't know what a child MVC would be.

There's nothing wrong with multiple SCNViews, and it appears in option B that you're using them for different purposes. Remember that you don't have to do everything in an SCNView. You can still use UIView/NSView, or even an SKView. Using SKView for the menus and controls is a common approach.

Implementing your own touch handlers and transition animations is IMO overkill. Use what's there. That's what SceneKit is for.

I would like to see you break your game logic out of your view controller logic. Consider what will happen when you want to move the game over to tvOS or macOS. If the game logic is in the VCs, you'll have a lot of unwinding to do. Keeping them separate also avoids one of the other meanings of MVC, "Massive View Controller", a bloated mess trying to handle all tasks at once.

Many online tutorials and code samples put everything into one game/view controller class, and while that's fine for simple examples and toy problems, it's not a practice that lends itself to clean code, good maintenance, and unit testability. If my game model logic is in a separate class (perhaps owning the state machine), I can easily write unit tests for that piece.

Title: SceneKit game architecture

Body:
I am trying to design an architecture for a SceneKit iOS game. I've shown below two rough high level object diagrams/graphs of my current preferred ideas.

I am only looking at the high level architecture at the moment, i.e. managing transition between Menu/GameLevel/Config/Paused app states and making the app data-driven, so that it can handle multiple levels, etc. Once I get this working, then I'll address lower level architecture, e.g. for the GameLevel state I'll have a GameLevelModel object to represent an actual game level logic.

Would be great to hear which one looks more promising, any obvious pitfalls or things to avoid?

Version A) MVC based, with Custom Container & Nested VCs

I'm trying to stay close to the MVC paradigm with this version.

The behaviour of the app changes significantly between its different states (Menu/GameLevel/Config/etc) so I'll be using a permanent container view controller that will manage/transition between several nested VCs, in a parent-child relationship as per Apple's "View Controller Programming Guide for iOS". These will be effectively entire MVCs.

Because none of Apple's container controllers (UINavigation-, UISplitScreen-, UITabBar-) are suitable (I need the entire screen) I'll have a custom container VC (RootViewController) that will have one nested child VC at all times. The View of each child VC will be fully covering the container's one at all times. The transition between child VCs will be managed by the RootVC and driven by its StateMachine.

Each child VC (effectively entire MVC) is created each time when its corresponding state becomes current and then deallocated when it is replaced with next state's one and no longer needed. Similar to how UINavigationController deals with it's contained VCs.

My only worry with this architecture is that it seems a bit heavy. SceneKit looks like it's designed to work with a single SCNView and to transition between multiple SCNScenes when we need to change the 3D content. This gives more transition options as well.

                         --------------------------
                         |   RootViewController   |
                         --------------------------
                           |  |   |        |    |
     ------------------    |  |   |        |    |      ------------------
     | GameLevelsData |-----  |   |        |    -------|     SCNView    |
     ------------------       |   |        |           ------------------
     ------------------       |   |        |
     |   PlayerData   |--------   |        |
     ------------------           |        |
                                  |        |
                       ----------------    |
                       | StateMachine |    |
                       ----------------    |
                         |                 |
                         |-(*MenuState)    |
                         |-(LevelState)    |
                         |-(ConfigState)   |
                                           |
                                           |
                         ------------------------
                         |  MenuViewController  |
                         ------------------------
      -----------------     |                |      ------------------
      |   MenuData    |------                -------|  MenuSCNView   |
      -----------------                             ------------------

   (child VCs for other States, Level-/Config-/etc are created as needed)
                                           |
                         ------------------------
                         |  LevelViewController |
                         ------------------------
     ------------------     |                |      ------------------
     | GameLevelModel |------                -------|  LevelSCNView  |
     ------------------                             ------------------

Version B) Scene-based (one VC, multiple Scenes)

I'll have only one View Controller (GameViewController) with its View (SCNView) and they will last for the entire app lifecycle.
(I will not have container and nested VCs here.)

The change in behaviour and content between app states (Menu/GameLevel/Config/etc) is achieved by the only View transitioning between Scenes and different TouchHandlers (UIResponder subclasses for each state) given First Responder status when relevant.

The (Menu-, GameLevel-, etc) TouchHandler classes will only override touchesBegan/Moved/Ended and canBecomeFirstResponder so that I can intercept touch events without bloating the single controller and view. None of my other objects are UIResponders. I've not tested exactly this part yet.

With each app state the required objects for that state will be created, like corresponding Scene, TouchHandler, (GameLevelModel with game level logic when in GameLevelState), etc and deallocated when next state is entered.

My current issue with this one is, that when using SKTransition to transition between multile SCNScenes on the single SCNView, after 5-20 transitions there is memory leakage. I tried resolving by simplifying the scene, removing all actions, nodes before deallocating but nothing helps. The only way to avoid leakage is avoiding SKTransition and directly assigning scenes to the View's scene property scnView.scene = scnScene. So this will require me to animate my own transitions.

                         --------------------------
                         |   GameViewController   |
                         --------------------------
                           |  |   |             |
     ------------------    |  |   |             |      ------------------
     | GameLevelsData |-----  |   |             -------|     SCNView    |
     ------------------       |   |                    ------------------
     ------------------       |   |                            |
     |   PlayerData   |--------   |                            |
     ------------------           |                            |
                                  |                            |
                       ----------------                        |
                       | StateMachine |                        |
                       ----------------                        |
                         |                            ------------------
                         |-(*MenuState)---------      |  MenuSCNScene  |
                         |-(LevelState)     |  |      ------------------
                         |-(ConfigState)    |  |
                                            |  |
                     --------------------   |  |
                     | MenuTouchHandler |---|  |
                     --------------------      |
                      -----------------        |
                      |   MenuData    |---------
                      -----------------

              (When entering, each state creates objects of corresponding
              dedicated subclasses for its Model, TouchHandler and Scene)
                                            |  |              |
                    --------------------    |  |     -------------------
                    | LevelTouchHandler |---|  |     |  LevelSCNScene  |
                    --------------------       |     -------------------
                     ------------------        |
                     | GameLevelModel |---------
                     ------------------

Thanks in advance.


问:
First Azure Deployment - Intellitrace has tonnes of exceptions
I enabled IntelliTrace on an ASP.NET MVC2 app that seems to working very well in the staging area. My app talks to a SQL Azure database, and everything's running smoothly, but the intellitrace log is filled with Exceptions. Some of those are obvious MVC2 messages (like an exception about not being able to find a file in the controller's view folder, but it finds it in the Shared folder instead... ), but some have me a little worried. Should I be?

See the attached screenshot.

Bottom Line - should the tracelog be filled with garbage like this or am I doing something silly?

答: Alright, here is a repost so everyone with a similar issue can find the solution.. After you've deployed your application don't forget to adjust configuration settings DiagnosticsConnectionString and DataConnectionString to re-point them to the actual Azure storage instead of development storage.</p>

ContentLicense: CC BY-SA 4.0


问:
Vim: Close All Buffers But This One
How can I close all buffers in Vim except the one I am currently editing?</p>

答:
I like 1,100bd (suggested by juananruiz) which seems to work for me.

I added a quit! to my mapping to give me

```<code>nnoremap <leader>bd :1,100bd<CR>
nnoremap <leader>bdq :1,100bd<CR>:q!<CR>
</code>```

This kills all the buffers and shuts down Vim, which is what I was looking for mostly.

Title: Vim: Close All Buffers But This One

Body:
I like 1,100bd (suggested by juananruiz) which seems to work for me.

I added a quit! to my mapping to give me

nnoremap <leader>bd :1,100bd<CR>
nnoremap <leader>bdq :1,100bd<CR>:q!<CR>

This kills all the buffers and shuts down Vim, which is what I was looking for mostly.


问:
How can I simplify this code?
I want to input a single argument (spend) to this function, and then have it return a string stating which of the 9 possibilities (plan500_90, plan500_80, etc.) is the lowest number.

It's currently working but seems much longer than it has to be.

```<code>def woof(spend):
    plan500_90 = 35.05 * 12
    plan500_80 = 32.63 * 12
    plan500_70 = 29.85 * 12
    plan250_90 = 42.66 * 12
    plan250_80 = 39.41 * 12
    plan250_70 = 35.80 * 12
    plan100_90 = 53.38 * 12
    plan100_80 = 49.10 * 12
    plan100_70 = 44.41 * 12

    if spend > 500:
        a = plan500_90 + spend - 0.90 * (spend - 500)
        b = plan500_80 + spend - 0.80 * (spend - 500)
        c = plan500_70 + spend - 0.70 * (spend - 500)
    else:
        a = plan500_90 + spend
        b = plan500_80 + spend
        c = plan500_70 + spend
    if spend > 250:
        d = plan250_90 + spend - 0.90 * (spend - 250)
        e = plan250_80 + spend - 0.80 * (spend - 250)
        f = plan250_70 + spend - 0.70 * (spend - 250)
    else:
        d = plan250_90 + spend
        e = plan250_80 + spend
        f = plan250_70 + spend
    if spend > 100:
        g = plan100_90 + spend - 0.90 * (spend - 100)
        h = plan100_80 + spend - 0.80 * (spend - 100)
        i = plan100_70 + spend - 0.70 * (spend - 100)
    else:
        g = plan100_90 + spend
        h = plan100_80 + spend
        i = plan100_70 + spend

    list1 = [a, b, c, d, e, f, g, h, i,]

    if min(list1) == a:
        print "Plan500_90 is the cheapest plan at $%d per year." % a
    elif min(list1) == b:
        print "Plan500_80 is the cheapest plan at $%d per year." % b
    elif min(list1) == c:
        print "Plan500_70 is the cheapest plan at $%d per year." % c
    elif min(list1) == d:
        print "Plan250_90 is the cheapest plan at $%d per year." % d
    elif min(list1) == e:
        print "Plan250_80 is the cheapest plan at $%d per year." % e
    elif min(list1) == f:
        print "Plan250_70 is the cheapest plan at $%d per year." % f
    elif min(list1) == g:
        print "Plan100_90 is the cheapest plan at $%d per year." % g
    elif min(list1) == h:
        print "Plan100_80 is the cheapest plan at $%d per year." % h
    elif min(list1) == i:
        print "Plan100_70 is the cheapest plan at $%d per year." % i
</code>```

答:
You are repeating the code. Also instead of printing the result in the method, you can return the value and show at once. Also the if-else if not needed, as min() function returns minimum anyways.</p>

```<code>def woof(spend):
    plan500_90 = 35.05 * 12
    plan500_80 = 32.63 * 12
    plan500_70 = 29.85 * 12
    plan250_90 = 42.66 * 12
    plan250_80 = 39.41 * 12
    plan250_70 = 35.80 * 12
    plan100_90 = 53.38 * 12
    plan100_80 = 49.10 * 12
    plan100_70 = 44.41 * 12

    a = plan500_90 + spend
    b = plan500_80 + spend
    c = plan500_70 + spend

    d = plan250_90 + spend
    e = plan250_80 + spend
    f = plan250_70 + spend

    g = plan100_90 + spend
    h = plan100_80 + spend
    i = plan100_70 + spend

    if spend > 500:
        a = a - 0.90 * (spend - 500)
        b = b - 0.80 * (spend - 500)
        c = c - 0.70 * (spend - 500)

    if spend > 250:
        d = d - 0.90 * (spend - 250)
        e = e - 0.80 * (spend - 250)
        f = f - 0.70 * (spend - 250)

    if spend > 100:
        g = g - 0.90 * (spend - 100)
        h = h - 0.80 * (spend - 100)
        i = i - 0.70 * (spend - 100)

    list1 = [a, b, c, d, e, f, g, h, i,]

    return min(list1)

# Any spending variable
spend = 1000

cheapest_plan = woof(spend)
print "Plan100_70 is the cheapest plan at $%d per year." % cheapest_plan
</code>```

Title: How can I simplify this code?

Body:
I want to input a single argument (spend) to this function, and then have it return a string stating which of the 9 possibilities (plan500_90, plan500_80, etc.) is the lowest number.

It's currently working but seems much longer than it has to be.

def woof(spend):
    plan500_90 = 35.05 * 12
    plan500_80 = 32.63 * 12
    plan500_70 = 29.85 * 12
    plan250_90 = 42.66 * 12
    plan250_80 = 39.41 * 12
    plan250_70 = 35.80 * 12
    plan100_90 = 53.38 * 12
    plan100_80 = 49.10 * 12
    plan100_70 = 44.41 * 12

    if spend > 500:
        a = plan500_90 + spend - 0.90 * (spend - 500)
        b = plan500_80 + spend - 0.80 * (spend - 500)
        c = plan500_70 + spend - 0.70 * (spend - 500)
    else:
        a = plan500_90 + spend
        b = plan500_80 + spend
        c = plan500_70 + spend
    if spend > 250:
        d = plan250_90 + spend - 0.90 * (spend - 250)
        e = plan250_80 + spend - 0.80 * (spend - 250)
        f = plan250_70 + spend - 0.70 * (spend - 250)
    else:
        d = plan250_90 + spend
        e = plan250_80 + spend
        f = plan250_70 + spend
    if spend > 100:
        g = plan100_90 + spend - 0.90 * (spend - 100)
        h = plan100_80 + spend - 0.80 * (spend - 100)
        i = plan100_70 + spend - 0.70 * (spend - 100)
    else:
        g = plan100_90 + spend
        h = plan100_80 + spend
        i = plan100_70 + spend

    list1 = [a, b, c, d, e, f, g, h, i,]

    if min(list1) == a:
        print "Plan500_90 is the cheapest plan at $%d per year." % a
    elif min(list1) == b:
        print "Plan500_80 is the cheapest plan at $%d per year." % b
    elif min(list1) == c:
        print "Plan500_70 is the cheapest plan at $%d per year." % c
    elif min(list1) == d:
        print "Plan250_90 is the cheapest plan at $%d per year." % d
    elif min(list1) == e:
        print "Plan250_80 is the cheapest plan at $%d per year." % e
    elif min(list1) == f:
        print "Plan250_70 is the cheapest plan at $%d per year." % f
    elif min(list1) == g:
        print "Plan100_90 is the cheapest plan at $%d per year." % g
    elif min(list1) == h:
        print "Plan100_80 is the cheapest plan at $%d per year." % h
    elif min(list1) == i:
        print "Plan100_70 is the cheapest plan at $%d per year." % i

Body:
You are repeating the code. Also instead of printing the result in the method, you can return the value and show at once. Also the if-else if not needed, as min() function returns minimum anyways.

def woof(spend):
    plan500_90 = 35.05 * 12
    plan500_80 = 32.63 * 12
    plan500_70 = 29.85 * 12
    plan250_90 = 42.66 * 12
    plan250_80 = 39.41 * 12
    plan250_70 = 35.80 * 12
    plan100_90 = 53.38 * 12
    plan100_80 = 49.10 * 12
    plan100_70 = 44.41 * 12

    a = plan500_90 + spend
    b = plan500_80 + spend
    c = plan500_70 + spend

    d = plan250_90 + spend
    e = plan250_80 + spend
    f = plan250_70 + spend

    g = plan100_90 + spend
    h = plan100_80 + spend
    i = plan100_70 + spend

    if spend > 500:
        a = a - 0.90 * (spend - 500)
        b = b - 0.80 * (spend - 500)
        c = c - 0.70 * (spend - 500)

    if spend > 250:
        d = d - 0.90 * (spend - 250)
        e = e - 0.80 * (spend - 250)
        f = f - 0.70 * (spend - 250)

    if spend > 100:
        g = g - 0.90 * (spend - 100)
        h = h - 0.80 * (spend - 100)
        i = i - 0.70 * (spend - 100)

    list1 = [a, b, c, d, e, f, g, h, i,]

    return min(list1)

# Any spending variable
spend = 1000

cheapest_plan = woof(spend)
print "Plan100_70 is the cheapest plan at $%d per year." % cheapest_plan


问:
Execute a query for all tables and fill in data in new one
I need to get the result table with there fields
 - table_name, min_date, max_date

Here is my query, which I should execute for all tables

```<code>SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM testTable
GROUP BY  short_date
HAVING COUNT(*) > 1) as Duplicates
</code>```

Then I found out how to get all table names
I do it in this way

```<code>SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%'
</code>```

But I don't know how to execute it for all table and fill in the result in a new table.

I tried to do it in this way

```<code>DECLARE @DB_Name varchar(50)
DECLARE @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END

CLOSE database_cursor
DEALLOCATE database_cursor
</code>```

But I got this error

Syntax error or access violation: 1064 You have an error in your SQL
  syntax; check the manual that corresponds to your MySQL server version
  for the right syntax to use near 'DECLARE @DB_Name varchar(50) DECLARE
  @Command varchar(100)' at line 1

UPD

```<code>CREATE PROCEDURE GetData()
BEGIN

DECLARE @DB_Name varchar(50), @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%_') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END;

CLOSE database_cursor
DEALLOCATE database_cursor

END;

CALL GetData()
</code>```

答:
Add DELIMITER $$ at the start; add DELIMITER ; after END.

Get rid of declaring Command.  Instead use @command, which does not need to be declared.

Add SELECT @command; after the SELECT @command := ...; so that we can do some debugging.

The CLOSE and DEALLOCATE statements need ; to terminate them.

Test for running out of rows to FETCH.

You really need to look at a number of examples of Stored procedures, especially those with cursors.

Update

Ugh, I did not spot even half the syntax errors.  This might work (I can't tell because I don't have your particular tables or columns.):

```<code>DROP PROCEDURE IF EXISTS so42856538;

DELIMITER $$

CREATE PROCEDURE so42856538()
    LANGUAGE SQL
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
BEGIN

DECLARE _TableName varchar(64);
DECLARE _done INT DEFAULT FALSE;
DECLARE database_cursor CURSOR FOR
    SELECT TABLE_NAME
        FROM `information_schema`.`TABLES`
        WHERE `TABLE_SCHEMA` = 'test'
          AND `TABLE_NAME` LIKE 'test%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;

OPEN database_cursor;
curs_loop: LOOP
    FETCH NEXT FROM database_cursor INTO _TableName;
    IF _done THEN  LEAVE curs_loop;  END IF;
    SET @Command := CONCAT(
           'SELECT MIN(short_date) as FirstDuplicatedDate,
                           MAX(short_date) as LastDuplicatedDate
           FROM ( SELECT  short_date, type, value,  count(*) as cnt
                    FROM ', _TableName, '
                    WHERE type = "test"
                    GROUP BY  short_date, type, value
                    HAVING COUNT(*) > 1 ) as Duplicates'
                        );
    SELECT _TableName, @command;   -- Debugging (remove if it is clutter)
    PREPARE _sql FROM @command;
    EXECUTE _sql;
    DEALLOCATE PREPARE _sql;
END LOOP;
CLOSE database_cursor;

END $$

DELIMITER ;

CALL so42856538;
</code>```

Body:
I need to get the result table with there fields
 - table_name, min_date, max_date

Here is my query, which I should execute for all tables

SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM testTable
GROUP BY  short_date
HAVING COUNT(*) > 1) as Duplicates

Then I found out how to get all table names
I do it in this way

SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%'

But I don't know how to execute it for all table and fill in the result in a new table.

I tried to do it in this way

DECLARE @DB_Name varchar(50)
DECLARE @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END

CLOSE database_cursor
DEALLOCATE database_cursor

But I got this error

Syntax error or access violation: 1064 You have an error in your SQL
  syntax; check the manual that corresponds to your MySQL server version
  for the right syntax to use near 'DECLARE @DB_Name varchar(50) DECLARE
  @Command varchar(100)' at line 1

UPD

CREATE PROCEDURE GetData()
BEGIN

DECLARE @DB_Name varchar(50), @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%_') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END;

CLOSE database_cursor
DEALLOCATE database_cursor

END;

CALL GetData()

Body:
Add DELIMITER $$ at the start; add DELIMITER ; after END.

Get rid of declaring Command.  Instead use @command, which does not need to be declared.

Add SELECT @command; after the SELECT @command := ...; so that we can do some debugging.

The CLOSE and DEALLOCATE statements need ; to terminate them.

Test for running out of rows to FETCH.

You really need to look at a number of examples of Stored procedures, especially those with cursors.

Update

Ugh, I did not spot even half the syntax errors.  This might work (I can't tell because I don't have your particular tables or columns.):

DROP PROCEDURE IF EXISTS so42856538;

DELIMITER $$

CREATE PROCEDURE so42856538()
    LANGUAGE SQL
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
BEGIN

DECLARE _TableName varchar(64);
DECLARE _done INT DEFAULT FALSE;
DECLARE database_cursor CURSOR FOR
    SELECT TABLE_NAME
        FROM `information_schema`.`TABLES`
        WHERE `TABLE_SCHEMA` = 'test'
          AND `TABLE_NAME` LIKE 'test%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;

OPEN database_cursor;
curs_loop: LOOP
    FETCH NEXT FROM database_cursor INTO _TableName;
    IF _done THEN  LEAVE curs_loop;  END IF;
    SET @Command := CONCAT(
           'SELECT MIN(short_date) as FirstDuplicatedDate,
                           MAX(short_date) as LastDuplicatedDate
           FROM ( SELECT  short_date, type, value,  count(*) as cnt
                    FROM ', _TableName, '
                    WHERE type = "test"
                    GROUP BY  short_date, type, value
                    HAVING COUNT(*) > 1 ) as Duplicates'
                        );
    SELECT _TableName, @command;   -- Debugging (remove if it is clutter)
    PREPARE _sql FROM @command;
    EXECUTE _sql;
    DEALLOCATE PREPARE _sql;
END LOOP;
CLOSE database_cursor;

END $$

DELIMITER ;

CALL so42856538;


问:
best way to organize a long piece of code in ruby refinement block
```<code>module Access
  def last
    self[-1]
  end

  def start_end
    self[0] + last
  end
end

module StringExt
  refine String do
    include Access
  end
end

using StringExt

puts 'abcd'.last       # => d
puts 'abcd'.start_end
</code>```

When a class being refined with too many connected methods, I think it is better to extract them to a module. However, in above example which demos a problem when one method calls another(see the last statement), and it produces following error.

in 'start_end': undefined local variable or method 'last' for "abcd":String (NameError)

Similar issue was solved using a global variable, which also works for my example. But I'm seeking another better way to organize inter-called methods being refined and avoid a global thing.

How would advice a better way to organize those methods?

答:
Here's a general pattern I ended up using. Basically I found no workaround for using global identifiers at some level. But this can be done fairly cleanly by making those globals classes/modules. This will be more clear as an example:

```<code>module StringPatches

  def self.non_empty?(string)
    !string.empty?
  end

  def non_empty?
    StringPatches.non_empty?(self)
  end

  def non_non_empty?
    !StringPatches.non_empty?(self)
  end

  refine String do
    include StringPatches
  end

end

class Foo
  using StringPatches
  puts "asd".non_empty? # => true
  puts "asd".non_non_empty? # => false
end
</code>```

The class methods on StringPatches don't get exported to using. But since classes/modules are constants (globals) they can be accessed from anywhere.

Body:
module Access
  def last
    self[-1]
  end

  def start_end
    self[0] + last
  end
end

module StringExt
  refine String do
    include Access
  end
end

using StringExt

puts 'abcd'.last       # => d
puts 'abcd'.start_end

When a class being refined with too many connected methods, I think it is better to extract them to a module. However, in above example which demos a problem when one method calls another(see the last statement), and it produces following error.

in 'start_end': undefined local variable or method 'last' for "abcd":String (NameError)

Similar issue was solved using a global variable, which also works for my example. But I'm seeking another better way to organize inter-called methods being refined and avoid a global thing.

How would advice a better way to organize those methods?

Body:
Here's a general pattern I ended up using. Basically I found no workaround for using global identifiers at some level. But this can be done fairly cleanly by making those globals classes/modules. This will be more clear as an example:

module StringPatches

  def self.non_empty?(string)
    !string.empty?
  end

  def non_empty?
    StringPatches.non_empty?(self)
  end

  def non_non_empty?
    !StringPatches.non_empty?(self)
  end

  refine String do
    include StringPatches
  end

end

class Foo
  using StringPatches
  puts "asd".non_empty? # => true
  puts "asd".non_non_empty? # => false
end

The class methods on StringPatches don't get exported to using. But since classes/modules are constants (globals) they can be accessed from anywhere.


问:
My JScrollPane won't scroll vertically over my JPanel
I have a code where I have a lot of 'nested' layouts. Border, Flow, and in my main program I have a GridBag. I'm adding panels dynamically to one panel, and have it sized so that each element gets added vertically but it won't scroll up or down. I looked on the net and found something similar but that only alows mine to scroll horizontally and not vertically like i want. This is my test code that I wrote:

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Main {

    public Main() {
        JFrame frame = new JFrame("Blah");

        Font font = new Font("Sans-Serif", Font.BOLD, 30);

        JPanel memoryPanel = new JPanel();
        memoryPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
        //memoryPanel.setPreferredSize(new Dimension(80 * 4, 55 * 9));

        JScrollPane s = new JScrollPane(memoryPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        s.getViewport().setPreferredSize(new Dimension(80 * 4, 55 * 9));

        for (int i = 0; i <= 10; i++) {

            JPanel nextPanel = new JPanel();
            nextPanel.setLayout(new BorderLayout());
            nextPanel.setBackground(Color.CYAN);
            nextPanel.setForeground(Color.BLACK);

            JPanel labelPanel = new JPanel();
            labelPanel.setLayout(new BorderLayout());

            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.TRAILING, 0, 0));

            JLabel label = new JLabel();
            label.setText("" + i);
            label.setPreferredSize(new Dimension(80 * 4, 55));
            label.setHorizontalAlignment(JLabel.RIGHT);
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));

            JButton button1 = new JButton("A");
            JButton button2 = new JButton("B");
            JButton button3 = new JButton("C");

            label.setFont(font);
            labelPanel.add(label);

            buttonPanel.add(button1);
            buttonPanel.add(button2);
            buttonPanel.add(button3);

            nextPanel.add(labelPanel, BorderLayout.PAGE_START);
            nextPanel.add(buttonPanel, BorderLayout.PAGE_END);

            memoryPanel.add(nextPanel, 0);
            memoryPanel.revalidate();
            memoryPanel.repaint();
        }
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(s);
        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }
}
</code>```

With that commented line, it shows the horizontal scroll bar. With it not commented, it doesn't show any. Not sure if I'm using the layouts wrong or not but I've been trying to fix it for a few hours. The line I added was s.getViewport().setPreferredSize(new Dimension(80 * 4, 55 * 9)); Which is making everything going horizontally instead of vertically. Not sure how to fix this. Suggestions?

答:
Start by getting rid of s.getViewport().setPreferredSize(new Dimension(80 * 4, 55 * 9));.  You don't want to change the size of the view port, it's a container for your content and acts as the "window" showing the visible portion of the component.

Next, get rid of frame.setResizable(false);, this will now allow pack to actually pack the window around the content.  Because you're using a FlowLayout, this tends to make the window as wide as the screen.

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Main {

    public Main() {
        JFrame frame = new JFrame("Blah");

        Font font = new Font("Sans-Serif", Font.BOLD, 30);

        JPanel memoryPanel = new JPanel();
        memoryPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
        //memoryPanel.setPreferredSize(new Dimension(80 * 4, 55 * 9));

        JScrollPane s = new JScrollPane(memoryPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        //        s.getViewport().setPreferredSize(new Dimension(80 * 4, 55 * 9));

        for (int i = 0; i <= 10; i++) {

            JPanel nextPanel = new JPanel();
            nextPanel.setLayout(new BorderLayout());
            nextPanel.setBackground(Color.CYAN);
            nextPanel.setForeground(Color.BLACK);

            JPanel labelPanel = new JPanel();
            labelPanel.setLayout(new BorderLayout());

            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.TRAILING, 0, 0));

            JLabel label = new JLabel();
            label.setText("" + i);
            label.setPreferredSize(new Dimension(80 * 4, 55));
            label.setHorizontalAlignment(JLabel.RIGHT);
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));

            JButton button1 = new JButton("A");
            JButton button2 = new JButton("B");
            JButton button3 = new JButton("C");

            label.setFont(font);
            labelPanel.add(label);

            buttonPanel.add(button1);
            buttonPanel.add(button2);
            buttonPanel.add(button3);

            nextPanel.add(labelPanel, BorderLayout.PAGE_START);
            nextPanel.add(buttonPanel, BorderLayout.PAGE_END);

            memoryPanel.add(nextPanel, 0);
            memoryPanel.revalidate();
            memoryPanel.repaint();
        }
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(s);
        //        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Main();
            }
        });
    }
}
</code>```

If you want to affect the size of the scrollable view area, then you will need to create a custom class which implements the Scrollable interface and return appropriate values according to your needs

Body:
I have a code where I have a lot of 'nested' layouts. Border, Flow, and in my main program I have a GridBag. I'm adding panels dynamically to one panel, and have it sized so that each element gets added vertically but it won't scroll up or down. I looked on the net and found something similar but that only alows mine to scroll horizontally and not vertically like i want. This is my test code that I wrote:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Main {

    public Main() {
        JFrame frame = new JFrame("Blah");

        Font font = new Font("Sans-Serif", Font.BOLD, 30);

        JPanel memoryPanel = new JPanel();
        memoryPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
        //memoryPanel.setPreferredSize(new Dimension(80 * 4, 55 * 9));

        JScrollPane s = new JScrollPane(memoryPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        s.getViewport().setPreferredSize(new Dimension(80 * 4, 55 * 9));

        for (int i = 0; i <= 10; i++) {

            JPanel nextPanel = new JPanel();
            nextPanel.setLayout(new BorderLayout());
            nextPanel.setBackground(Color.CYAN);
            nextPanel.setForeground(Color.BLACK);

            JPanel labelPanel = new JPanel();
            labelPanel.setLayout(new BorderLayout());

            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.TRAILING, 0, 0));

            JLabel label = new JLabel();
            label.setText("" + i);
            label.setPreferredSize(new Dimension(80 * 4, 55));
            label.setHorizontalAlignment(JLabel.RIGHT);
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));

            JButton button1 = new JButton("A");
            JButton button2 = new JButton("B");
            JButton button3 = new JButton("C");

            label.setFont(font);
            labelPanel.add(label);

            buttonPanel.add(button1);
            buttonPanel.add(button2);
            buttonPanel.add(button3);

            nextPanel.add(labelPanel, BorderLayout.PAGE_START);
            nextPanel.add(buttonPanel, BorderLayout.PAGE_END);

            memoryPanel.add(nextPanel, 0);
            memoryPanel.revalidate();
            memoryPanel.repaint();
        }
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(s);
        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }
}

With that commented line, it shows the horizontal scroll bar. With it not commented, it doesn't show any. Not sure if I'm using the layouts wrong or not but I've been trying to fix it for a few hours. The line I added was s.getViewport().setPreferredSize(new Dimension(80 * 4, 55 * 9)); Which is making everything going horizontally instead of vertically. Not sure how to fix this. Suggestions?

Body:
Start by getting rid of s.getViewport().setPreferredSize(new Dimension(80 * 4, 55 * 9));.  You don't want to change the size of the view port, it's a container for your content and acts as the "window" showing the visible portion of the component.

Next, get rid of frame.setResizable(false);, this will now allow pack to actually pack the window around the content.  Because you're using a FlowLayout, this tends to make the window as wide as the screen.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Main {

    public Main() {
        JFrame frame = new JFrame("Blah");

        Font font = new Font("Sans-Serif", Font.BOLD, 30);

        JPanel memoryPanel = new JPanel();
        memoryPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
        //memoryPanel.setPreferredSize(new Dimension(80 * 4, 55 * 9));

        JScrollPane s = new JScrollPane(memoryPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        //        s.getViewport().setPreferredSize(new Dimension(80 * 4, 55 * 9));

        for (int i = 0; i <= 10; i++) {

            JPanel nextPanel = new JPanel();
            nextPanel.setLayout(new BorderLayout());
            nextPanel.setBackground(Color.CYAN);
            nextPanel.setForeground(Color.BLACK);

            JPanel labelPanel = new JPanel();
            labelPanel.setLayout(new BorderLayout());

            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.TRAILING, 0, 0));

            JLabel label = new JLabel();
            label.setText("" + i);
            label.setPreferredSize(new Dimension(80 * 4, 55));
            label.setHorizontalAlignment(JLabel.RIGHT);
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));

            JButton button1 = new JButton("A");
            JButton button2 = new JButton("B");
            JButton button3 = new JButton("C");

            label.setFont(font);
            labelPanel.add(label);

            buttonPanel.add(button1);
            buttonPanel.add(button2);
            buttonPanel.add(button3);

            nextPanel.add(labelPanel, BorderLayout.PAGE_START);
            nextPanel.add(buttonPanel, BorderLayout.PAGE_END);

            memoryPanel.add(nextPanel, 0);
            memoryPanel.revalidate();
            memoryPanel.repaint();
        }
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(s);
        //        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Main();
            }
        });
    }
}

If you want to affect the size of the scrollable view area, then you will need to create a custom class which implements the Scrollable interface and return appropriate values according to your needs


问:
Why is Cassandra client failing without epoll in production?
When I run my service locally, I get a warning that epoll isn't available, so it's using NIO. Fair enough. When I deploy it in Kubernetes, I get this, which prevents the service from running:

```<code>2017-03-29T19:09:22.739482458Z 19:09:22.739 WARN  com.datastax.driver.core.NettyUtil - Found Netty's native epoll transport in the classpath, but epoll is not available. Using NIO instead.
2017-03-29T19:09:22.739505903Z java.lang.UnsatisfiedLinkError: could not load a native library: netty-transport-native-epoll
2017-03-29T19:09:22.739509966Z  at io.netty.util.internal.NativeLibraryLoader.load(NativeLibraryLoader.java:224)
2017-03-29T19:09:22.739513326Z  at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:269)
2017-03-29T19:09:22.739516421Z  at io.netty.channel.epoll.Native.<clinit>(Native.java:64)
2017-03-29T19:09:22.739519628Z  at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:33)
2017-03-29T19:09:22.739522527Z  at java.lang.Class.forName0(Native Method)
2017-03-29T19:09:22.739525253Z  at java.lang.Class.forName(Class.java:264)
2017-03-29T19:09:22.739528047Z  at com.datastax.driver.core.NettyUtil.<clinit>(NettyUtil.java:68)
2017-03-29T19:09:22.739530907Z  at com.datastax.driver.core.NettyOptions.eventLoopGroup(NettyOptions.java:99)
2017-03-29T19:09:22.739533585Z  at com.datastax.driver.core.Connection$Factory.<init>(Connection.java:769)
2017-03-29T19:09:22.739544382Z  at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1400)
2017-03-29T19:09:22.739547340Z  at com.datastax.driver.core.Cluster.init(Cluster.java:159)
2017-03-29T19:09:22.739550134Z  at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:330)
2017-03-29T19:09:22.739555749Z  at com.datastax.driver.core.Cluster.connect(Cluster.java:280)
2017-03-29T19:09:22.739558846Z  at io.getquill.context.cassandra.CassandraSessionContext.<init>(CassandraSessionContext.scala:38)
2017-03-29T19:09:22.739562704Z  at io.getquill.CassandraAsyncContext.<init>(CassandraAsyncContext.scala:19)
2017-03-29T19:09:22.739565629Z  at io.xxxxxxxxx.platform.db.Datastore.<init>(Datastore.scala:26)
2017-03-29T19:09:22.739568481Z  at DatastoreModule.configure(DatastoreModule.scala:22)
2017-03-29T19:09:22.739571234Z  at com.google.inject.AbstractModule.configure(AbstractModule.java:62)
2017-03-29T19:09:22.739574009Z  at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:340)
2017-03-29T19:09:22.739576726Z  at com.google.inject.spi.Elements.getElements(Elements.java:110)
2017-03-29T19:09:22.739579348Z  at com.google.inject.util.Modules$OverrideModule.configure(Modules.java:177)
2017-03-29T19:09:22.739581979Z  at com.google.inject.AbstractModule.configure(AbstractModule.java:62)
2017-03-29T19:09:22.739584688Z  at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:340)
2017-03-29T19:09:22.739587416Z  at com.google.inject.spi.Elements.getElements(Elements.java:110)
2017-03-29T19:09:22.739590109Z  at com.google.inject.internal.InjectorShell$Builder.build(InjectorShell.java:138)
2017-03-29T19:09:22.739592859Z  at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:104)
2017-03-29T19:09:22.739595643Z  at com.google.inject.Guice.createInjector(Guice.java:99)
2017-03-29T19:09:22.739598376Z  at com.google.inject.Guice.createInjector(Guice.java:84)
2017-03-29T19:09:22.739600979Z  at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:181)
2017-03-29T19:09:22.739603649Z  at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:123)
2017-03-29T19:09:22.739606361Z  at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
2017-03-29T19:09:22.739609008Z  at play.core.server.ProdServerStart$.start(ProdServerStart.scala:47)
2017-03-29T19:09:22.739611618Z  at play.core.server.ProdServerStart$.main(ProdServerStart.scala:22)
2017-03-29T19:09:22.739614246Z  at play.core.server.ProdServerStart.main(ProdServerStart.scala)
2017-03-29T19:09:22.739616846Z Caused by: java.lang.RuntimeException: failed to get field ID: DefaultFileRegion.transfered
2017-03-29T19:09:22.739619540Z  at java.lang.ClassLoader$NativeLibrary.load(Native Method)
2017-03-29T19:09:22.739624975Z  at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
2017-03-29T19:09:22.739627704Z  at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1824)
2017-03-29T19:09:22.739630403Z  at java.lang.Runtime.load0(Runtime.java:809)
2017-03-29T19:09:22.739632988Z  at java.lang.System.load(System.java:1086)
2017-03-29T19:09:22.739635608Z  at io.netty.util.internal.NativeLibraryUtil.loadLibrary(NativeLibraryUtil.java:36)
2017-03-29T19:09:22.739638288Z  at io.netty.util.internal.NativeLibraryLoader.loadLibrary(NativeLibraryLoader.java:255)
2017-03-29T19:09:22.739640937Z  at io.netty.util.internal.NativeLibraryLoader.load(NativeLibraryLoader.java:222)
2017-03-29T19:09:22.739643779Z  ... 33 common frames omitted
2017-03-29T19:09:22.902948521Z 19:09:22.902 WARN  i.n.util.concurrent.DefaultPromise - An exception was thrown by com.datastax.driver.core.Connection$1.operationComplete()
2017-03-29T19:09:22.902975391Z java.lang.NullPointerException: null
2017-03-29T19:09:22.902979455Z  at io.netty.channel.group.DefaultChannelGroup.add(DefaultChannelGroup.java:146)
2017-03-29T19:09:22.902982663Z  at io.netty.channel.group.DefaultChannelGroup.add(DefaultChannelGroup.java:42)
2017-03-29T19:09:22.902985588Z  at com.datastax.driver.core.Connection$1.operationComplete(Connection.java:162)
2017-03-29T19:09:22.902988575Z  at com.datastax.driver.core.Connection$1.operationComplete(Connection.java:149)
2017-03-29T19:09:22.902991374Z  at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:514)
2017-03-29T19:09:22.902995665Z  at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:488)
2017-03-29T19:09:22.902998584Z  at io.netty.util.concurrent.DefaultPromise.access$000(DefaultPromise.java:34)
2017-03-29T19:09:22.903001524Z  at io.netty.util.concurrent.DefaultPromise$1.run(DefaultPromise.java:438)
2017-03-29T19:09:22.903004958Z  at io.netty.util.concurrent.GlobalEventExecutor$TaskRunner.run(GlobalEventExecutor.java:233)
2017-03-29T19:09:22.903008073Z  at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
2017-03-29T19:09:22.903011054Z  at java.lang.Thread.run(Thread.java:745)
</code>```

How do I:

a) Stop the error; and

b) Make it use epoll if that's more performant than whatever NIO uses otherwise (is it really using select?)

答:
Adding this dependency fixed the problem:

"io.netty" % "netty-transport-native-epoll" % "4.1.6.Final" classifier "linux-x86_64"

Body:
When I run my service locally, I get a warning that epoll isn't available, so it's using NIO. Fair enough. When I deploy it in Kubernetes, I get this, which prevents the service from running:

2017-03-29T19:09:22.739482458Z 19:09:22.739 WARN  com.datastax.driver.core.NettyUtil - Found Netty's native epoll transport in the classpath, but epoll is not available. Using NIO instead.
2017-03-29T19:09:22.739505903Z java.lang.UnsatisfiedLinkError: could not load a native library: netty-transport-native-epoll
2017-03-29T19:09:22.739509966Z  at io.netty.util.internal.NativeLibraryLoader.load(NativeLibraryLoader.java:224)
2017-03-29T19:09:22.739513326Z  at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:269)
2017-03-29T19:09:22.739516421Z  at io.netty.channel.epoll.Native.<clinit>(Native.java:64)
2017-03-29T19:09:22.739519628Z  at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:33)
2017-03-29T19:09:22.739522527Z  at java.lang.Class.forName0(Native Method)
2017-03-29T19:09:22.739525253Z  at java.lang.Class.forName(Class.java:264)
2017-03-29T19:09:22.739528047Z  at com.datastax.driver.core.NettyUtil.<clinit>(NettyUtil.java:68)
2017-03-29T19:09:22.739530907Z  at com.datastax.driver.core.NettyOptions.eventLoopGroup(NettyOptions.java:99)
2017-03-29T19:09:22.739533585Z  at com.datastax.driver.core.Connection$Factory.<init>(Connection.java:769)
2017-03-29T19:09:22.739544382Z  at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1400)
2017-03-29T19:09:22.739547340Z  at com.datastax.driver.core.Cluster.init(Cluster.java:159)
2017-03-29T19:09:22.739550134Z  at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:330)
2017-03-29T19:09:22.739555749Z  at com.datastax.driver.core.Cluster.connect(Cluster.java:280)
2017-03-29T19:09:22.739558846Z  at io.getquill.context.cassandra.CassandraSessionContext.<init>(CassandraSessionContext.scala:38)
2017-03-29T19:09:22.739562704Z  at io.getquill.CassandraAsyncContext.<init>(CassandraAsyncContext.scala:19)
2017-03-29T19:09:22.739565629Z  at io.xxxxxxxxx.platform.db.Datastore.<init>(Datastore.scala:26)
2017-03-29T19:09:22.739568481Z  at DatastoreModule.configure(DatastoreModule.scala:22)
2017-03-29T19:09:22.739571234Z  at com.google.inject.AbstractModule.configure(AbstractModule.java:62)
2017-03-29T19:09:22.739574009Z  at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:340)
2017-03-29T19:09:22.739576726Z  at com.google.inject.spi.Elements.getElements(Elements.java:110)
2017-03-29T19:09:22.739579348Z  at com.google.inject.util.Modules$OverrideModule.configure(Modules.java:177)
2017-03-29T19:09:22.739581979Z  at com.google.inject.AbstractModule.configure(AbstractModule.java:62)
2017-03-29T19:09:22.739584688Z  at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:340)
2017-03-29T19:09:22.739587416Z  at com.google.inject.spi.Elements.getElements(Elements.java:110)
2017-03-29T19:09:22.739590109Z  at com.google.inject.internal.InjectorShell$Builder.build(InjectorShell.java:138)
2017-03-29T19:09:22.739592859Z  at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:104)
2017-03-29T19:09:22.739595643Z  at com.google.inject.Guice.createInjector(Guice.java:99)
2017-03-29T19:09:22.739598376Z  at com.google.inject.Guice.createInjector(Guice.java:84)
2017-03-29T19:09:22.739600979Z  at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:181)
2017-03-29T19:09:22.739603649Z  at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:123)
2017-03-29T19:09:22.739606361Z  at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
2017-03-29T19:09:22.739609008Z  at play.core.server.ProdServerStart$.start(ProdServerStart.scala:47)
2017-03-29T19:09:22.739611618Z  at play.core.server.ProdServerStart$.main(ProdServerStart.scala:22)
2017-03-29T19:09:22.739614246Z  at play.core.server.ProdServerStart.main(ProdServerStart.scala)
2017-03-29T19:09:22.739616846Z Caused by: java.lang.RuntimeException: failed to get field ID: DefaultFileRegion.transfered
2017-03-29T19:09:22.739619540Z  at java.lang.ClassLoader$NativeLibrary.load(Native Method)
2017-03-29T19:09:22.739624975Z  at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
2017-03-29T19:09:22.739627704Z  at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1824)
2017-03-29T19:09:22.739630403Z  at java.lang.Runtime.load0(Runtime.java:809)
2017-03-29T19:09:22.739632988Z  at java.lang.System.load(System.java:1086)
2017-03-29T19:09:22.739635608Z  at io.netty.util.internal.NativeLibraryUtil.loadLibrary(NativeLibraryUtil.java:36)
2017-03-29T19:09:22.739638288Z  at io.netty.util.internal.NativeLibraryLoader.loadLibrary(NativeLibraryLoader.java:255)
2017-03-29T19:09:22.739640937Z  at io.netty.util.internal.NativeLibraryLoader.load(NativeLibraryLoader.java:222)
2017-03-29T19:09:22.739643779Z  ... 33 common frames omitted
2017-03-29T19:09:22.902948521Z 19:09:22.902 WARN  i.n.util.concurrent.DefaultPromise - An exception was thrown by com.datastax.driver.core.Connection$1.operationComplete()
2017-03-29T19:09:22.902975391Z java.lang.NullPointerException: null
2017-03-29T19:09:22.902979455Z  at io.netty.channel.group.DefaultChannelGroup.add(DefaultChannelGroup.java:146)
2017-03-29T19:09:22.902982663Z  at io.netty.channel.group.DefaultChannelGroup.add(DefaultChannelGroup.java:42)
2017-03-29T19:09:22.902985588Z  at com.datastax.driver.core.Connection$1.operationComplete(Connection.java:162)
2017-03-29T19:09:22.902988575Z  at com.datastax.driver.core.Connection$1.operationComplete(Connection.java:149)
2017-03-29T19:09:22.902991374Z  at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:514)
2017-03-29T19:09:22.902995665Z  at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:488)
2017-03-29T19:09:22.902998584Z  at io.netty.util.concurrent.DefaultPromise.access$000(DefaultPromise.java:34)
2017-03-29T19:09:22.903001524Z  at io.netty.util.concurrent.DefaultPromise$1.run(DefaultPromise.java:438)
2017-03-29T19:09:22.903004958Z  at io.netty.util.concurrent.GlobalEventExecutor$TaskRunner.run(GlobalEventExecutor.java:233)
2017-03-29T19:09:22.903008073Z  at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
2017-03-29T19:09:22.903011054Z  at java.lang.Thread.run(Thread.java:745)

How do I:

a) Stop the error; and

b) Make it use epoll if that's more performant than whatever NIO uses otherwise (is it really using select?)


问:
Estimated number of search results Google search API
When you search google, it estimates the number of search results e.g.

Results 1 - 10 of about 103,000,000 for hello world

How do I get the number 103,000,000 programmically?

I'm not interested in the results, just that number, and I need to do about 100 of these searches at a time so webpage scrapping is not an option since google tends to block this kind of thing.

I've seen solutions where you can use the google soap API to do this but that's no longer an option since it's deprecated and they're no longer giving away API keys, and the AJAX API doesn't seem to offer this field :/

答:
I completed this using C# with Bing instead of Google. You can find the answer here:

Google Search API - Number of Results


问:
bash script to run multiple C++ codes only after previous code has been finished
I want to run multiple C++ codes using bash script on a Linux cluster. I am able to do that but as multiple codes run at the same time on the cluster it becomes slow. Therefore, I want to run these simulations using bash script such that, the next code only starts running when the previous one has been completed.

I have been using sleep command for now by specifying number of hours it might run but as I do not know the run time before hand it is very inefficient. The next code has to wait till the sleep time is over.

This how my current bash script looks

```<code>#!/bin/bash
cd /home/Rectilinear_box_Loverl_16
make clean
make -f Makefile
echo "L/l = 16 started"
./Rod input_file.xml > log &
sleep 14h
echo "L/l = 16 completed"

cd /home/Rectilinear_box_Loverl_14
make clean
make -f Makefile
echo "\nL/l = 14 started"
./Rod input_file.xml > log &
sleep 14h
echo "L/l = 14 completed"

cd /home/Rectilinear_box_Loverl_12
make clean
make -f Makefile
echo "\nL/l = 12 started"
./Rod input_file.xml > log &
echo "L/l = 12 completed"
</code>```

each code takes different amount of time to finish but I have specified the maximum amount of time to be safe.

Could someone suggest a good way to do it?

答:
Remove the &. They make your calculations execute in the background.

```<code>./Rod input_file.xml > log &
</code>```

Can be:

```<code>./Rod input_file.xml > log
</code>```

Body:
I want to run multiple C++ codes using bash script on a Linux cluster. I am able to do that but as multiple codes run at the same time on the cluster it becomes slow. Therefore, I want to run these simulations using bash script such that, the next code only starts running when the previous one has been completed.

I have been using sleep command for now by specifying number of hours it might run but as I do not know the run time before hand it is very inefficient. The next code has to wait till the sleep time is over.

This how my current bash script looks

#!/bin/bash
cd /home/Rectilinear_box_Loverl_16
make clean
make -f Makefile
echo "L/l = 16 started"
./Rod input_file.xml > log &
sleep 14h
echo "L/l = 16 completed"

cd /home/Rectilinear_box_Loverl_14
make clean
make -f Makefile
echo "\nL/l = 14 started"
./Rod input_file.xml > log &
sleep 14h
echo "L/l = 14 completed"

cd /home/Rectilinear_box_Loverl_12
make clean
make -f Makefile
echo "\nL/l = 12 started"
./Rod input_file.xml > log &
echo "L/l = 12 completed"

each code takes different amount of time to finish but I have specified the maximum amount of time to be safe.

Could someone suggest a good way to do it?

Body:
Remove the &. They make your calculations execute in the background.

./Rod input_file.xml > log &

Can be:

./Rod input_file.xml > log


问:
Aligning an object to the surface of a sphere while maintaining forward direction
Using OpenGL as a rendering engine I'm attempting to generate a rotation matrix that will sit a mesh on the surface of a sphere at a given position. Initially I'd attempted to do this by calculating the spheres surface normal at the given position and using that as my meshes up vector.

This worked, but things are complicated by the fact that I'd also like to be able to rotate the mesh with absolute yaw, pitch and roll values - where a yaw of 0 will always leave the mesh pointing upwards (0, 1, 0) in a northern direction.

I have a mental block on how to achieve this and would appreciate any input.

Update with solution provided by Ripi2:

```<code>let earthAxisOfRotation = Vector3(0, 1, 0).normalized() // south -> north pole is `up` in world space
let surfaceNormal = position.normalized() // surface normal of the given position on sphere surface

let east = earthAxisOfRotation.cross(surfaceNormal).normalized()
let north = surfaceNormal.cross(east)

let rotationMatrix = Matrix4(
    east.x, east.y, east.z, 0,
    surfaceNormal.x, surfaceNormal.y, surfaceNormal.z, 0,
    -north.x, -north.y, -north.z, 0,
    0, 0, 0, 1
)
</code>```

答:
Let's work on an "Earth". Its axis of rotation (r) goes from south pole to north pole. A normal (n) to the surface goes "out" of Earth.

The cross product e= r x n gives a vector heading east.

The cross product d= n x e gives a vector heading north.

With normalized versions of e, n, d and translating to the point in the surface you can construct a lookAt matrix (see here).

 up = n and  f= center-eye = d  and s = e. Notice you may want to change f sign because this is not a real 'lookAt' transform, it doesn't look at, but just locates.

Now, if your mesh can be considered as another sphere concentric with the first sphere, all rotations must be over the shared center of both spheres. The axis of rotation, keeping always the "heading north" can be the "Earth axis" (r) and the "heading east" (e). When using 'e' you lose somehow north, vector goes "inside" the sphere. Angles can be computed from cross product, due to if c= a x b then |c| = |a|·|b|·sin(beta).

Body:
Using OpenGL as a rendering engine I'm attempting to generate a rotation matrix that will sit a mesh on the surface of a sphere at a given position. Initially I'd attempted to do this by calculating the spheres surface normal at the given position and using that as my meshes up vector.

This worked, but things are complicated by the fact that I'd also like to be able to rotate the mesh with absolute yaw, pitch and roll values - where a yaw of 0 will always leave the mesh pointing upwards (0, 1, 0) in a northern direction.

I have a mental block on how to achieve this and would appreciate any input.

Update with solution provided by Ripi2:

let earthAxisOfRotation = Vector3(0, 1, 0).normalized() // south -> north pole is `up` in world space
let surfaceNormal = position.normalized() // surface normal of the given position on sphere surface

let east = earthAxisOfRotation.cross(surfaceNormal).normalized()
let north = surfaceNormal.cross(east)

let rotationMatrix = Matrix4(
    east.x, east.y, east.z, 0,
    surfaceNormal.x, surfaceNormal.y, surfaceNormal.z, 0,
    -north.x, -north.y, -north.z, 0,
    0, 0, 0, 1
)