How to create EBS based EC2 AMI from scratch?

Question: after Amazon announced the new EBS based AMIs, I'm wondering if it is or will be possible to create new AMIs that are not based on the existing Fedora/Windows AMIs. The documentation says:

The easiest method involves starting from an existing public AMI  and modifying it according to your requirements. This is applicable for both Amazon EBS-backed and Amazon S3-backed AMIs, and is described in Starting with an Existing AMI.
Another approach is to build a fresh installation either on a stand-alone machine or on an empty file system mounted by loopback. This is only applicable for AMIs backed by Amazon S3 and entails building an operating system installation from scratch.

That sounds like all future AMIs have to be based on existing ones, but that would be very limited. Do I understand this correctly or are there any other ways of creating AMIs not based on existing ones? I would be interested in creating ubuntu AMIs.
Answer: http://www.elastician.com/2009/12/creating-ebs-backed-ami-from-s3-backed.html
Comment: Please reproduce the important part of your link in your answer.  You have no guarantee the site you linked to won't disappear in future, making your answer worthless.
Answer: For Ubuntu in particular you could try these instructions http://alestic.com/2010/01/vmbuilder-ebs-boot-ami.
Answer: Here's a script I use to build a Git/gitolite server AMI using the downloadable Ubuntu server file system as a base:
https://github.com/alestic/alestic-git/blob/master/bin/alestic-git-build-ami
Here's more info about the Alestic Git server project for EC2:
http://alestic.com/alestic-git/
The vmbuilder-ebs-boot-ami article I wrote on Alestic.com (linked to in the answer by Bribles) is now outdated.
Answer: AMIs do not have to be based on existing ones, but creating one from EC2 is convoluted because it gives you a computer with remote access and hardware configuration but no console input.
The trick here is that ISO images can be booted directly from hard disk if they include a boot sector.  Also, installation of the new OS needs to be completely automated because you won't be able to interact with the console when the installer is running.
You will need to use three EBS disks, and switch which ones are attached: development, the installer and the final result.

Start an EC2 instance with an existing AMI.
Edit the ISO image for your new OS to make an unattended install (i.e. loopback mount, copy files, edit, mkisofs, isohybrid).  For Ubuntu you need to edit the preseed file and isolinux.cfg.  The install must write to a fresh EBS disk that will become the new AMI.
Copy the edited ISO image to a third EBS disk and boot from it.

I created an AMI for Linux Mint 18.2 using this method (starting with Amazon AMI Linux) as described in detail here.


Prove AB is hermitian if A is hermitian and B is hermitian

Question: If $A$ and $B$ are two hermitian transformations, prove that $AB$ is hermitian if $AB = BA$, knowing that a hermitian transformation is one such that $(T(f), g) = (f, T(g))$ and basic axioms for inner products: $(x,y) = (y,x)$, $(x,x) > 0$, $(cx, y) = c(x,y)$, and $(x,y+z) = (x,y) + (x,z)$.
Answer: $$\langle ABf, g \rangle = \langle Bf, Ag \rangle = \langle f, BAg \rangle = \langle f, ABg \rangle.$$
Here

I "=" $\longleftarrow$ $A$ is Hermitian,
II "=" $\longleftarrow$ $B$ is Hermitian,
III "=" $\longleftarrow$ $AB = BA$.
Comment: How do you get from $(ABf,g)=(Bf,Ag)=(f,BAg)$? A and B are transformations and not scalars so can you provide a justification for that?
Comment: @bob, I added more explanation to the answer.
Comment: Heh, I actually saw it just after I posted that question; thanks for trying to clarify, though.
Answer: We prove that $(AB)^*=AB$ by these equalities
$$\langle x,(AB)^*y\rangle=\langle ABx,y\rangle=\langle Bx,A^*y\rangle=\langle Bx,Ay\rangle=\langle x,B^*Ay\rangle=\langle x,BAy\rangle=\langle x,ABy\rangle$$


How to separate access to remoteapp and remote desktop for same user on different computers?

Question: I have a:

WS2012 Domain Controller.
Windows 10 Workstation.
Terminal Server RDP  2012.
Domain user.

In my case I need to deny access to RDP server via RDP, and allow remoteapp. For Windows 10, sometimes need to not connect local but via remote RDP.
Answer: Taken from Permissions for RemoteApp but not RemoteDesktop:

Short Answer: No.
Long Answer:
RemoteApp utilizes the remote desktop protocol and actually runs a
  complete remote desktop session whenever a user opens RemoteApp it
  just hides the full desktop and provides a container that the
  application runs within. So technically by using RemoteApp you are
  using Remote Desktop.
If you truly want a virtualized or remotely hosted application you are
  looking into the wrong technology. You really want to investigate
  App-V. It's a more expensive technology and came out of a company
  Microsoft bought a couple of years ago. Essentially with this
  technology the application is streamed to the client as bits and
  pieces are needed. There are also other options like the offerings
  Citrix provides as well.
Hope that helps.
Edit:
After a quick search it looks like there may also be some freeware
  available to accomplish this. However a lot of people simply have
  login tasks that call logoff.exe. So when a user tries to use remote
  desktop it simply makes a call to immediately log them off. Kinda
  hacky but it appears to work.
Comment: I understand that remoteapp is just a part of RDP. I found solution like using logoff.exe, but the problem how to use it only to the RDP Server, not on workstation. Because one person that domain user can work via remoteapp on RDP Server, but can be situation when he work from home connecting to his workstation via RDP, for example. Maybe exist some local politics to resolve this problem?
About App-V, dont know about it before, so I will need time learn this technology
Comment: use related GPO or local policies only for RDP server
Comment: And what exactly GPO should use?
Comment: Question is still actual. I cant find guide to solve this with GPO.


The same database name different server in same domain possible?

Question: In Oracle world - is it possible to have the same database name in a different server in the same domain?  In our test environment the database server is cloned (VMWare) and then our DBA have to reconfigure and change the database name because he said insist it is not possible to have the same database name in a different server in the same domain.
I've experience in MS-SQL server and it's possible to have the same database name in different servers in the same domain so I just need clarification.
Answer: Depends on what you mean by Domain. Oracle neither knows nor cares about Windows domains.
However there is a DB_DOMAIN database parameter used for networked databases
And there are various ways for clients to connect to Oracle databases (or at least finding out where the database is to connect to) which could also impact database naming.
It can also impact OEM/Grid Control, backing up etc.
And at the simplest level, it is good to be able to determine, from within the database, what database you are in. So most places will have separate names for Prod, Dev and test databases (even or especially if they have been copied from the same source).
So while it may be possible to have multiple, identically names databases on different servers, the DBA probably has good reasons not to do that.
Answer: Used to work in a shop where they did nothing but that: Every oracle production server had 'numbered' databases: PR01, PR02, PR03 etc. etc.
You just identify the database by the SID + servername, thus PR01@big_iron is another database than PR01@small_iron.
Keep your tnsnames.ora in order, and you're set!


How can I call browser back or forward buttons using jquery?

Question: Is it possible? And how can I call browser back function using jquery?
Answer: You don't need JQuery for this.
history.go(-1); // go back
history.go(1); // go forward

Answer: why jquery? normal javascript support history.go(-1) or go(1)
or look at: http://www.w3schools.com/jsref/met_his_back.asp and http://www.w3schools.com/jsref/met_his_forward.asp
Comment: one reason why a library such as jquery would be helpful is that not all browsers support history.go().   See [mdn](https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history).  It claims that IE doesnt support this until version 10.
Comment: @dsjoerg thats for the html5 history api. `history.go` has been around for a while.
Comment: which one should I prefer, history.go(-1) or window.history.back() and why
Answer: You don't need jquery for that:

forward: window.history.go(+1)
backward: window.history.go(-1)
Comment: You could check if `window.history.next` contains a url. see https://developer.mozilla.org/en-US/docs/Web/API/History
Comment: Hi, how can I detect if page has forward page?
Ex: if(window.history.go() >= 1){ window.history.go(+1); }
I want that to hide forward button if do not needed.
Answer: JQuery makes sense to use when you want an unobtrusive way to display a browser back button. The following example will not display anything if javascript is disabled:
!function($){
$(document).ready(function(){
    $('#ELEMENT').append('
back
');
    $('#ELEMENT .browser_back a').click(function() {
    window.history.go(-1);
    return false;
    });
}); }(jQuery);

Answer: Now, you could also do:
window.history.back() to go back, or
window.history.forward() to go forward.


Swift mastermind

Question: I try to make a Mastermind in swift but I can't get each digit of the random number using an index to check if I found a number of the code.
I tried this but it's not works.. :
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var textView: UITextView!

    var code = String(arc4random_uniform(9000) + 1000)

    override func viewDidLoad() {
        super.viewDidLoad()
        println(code)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }

    @IBAction func sendDidPressed(sender: AnyObject) {
        var find = 0

        for (var i = 0; i < 4; i++) {

            var number = textField.text
            var numberInCode = map(code) { String($0) }

            if contains(numberInCode, String(find)) {
                find++
            }

            self.textView.text = "\(self.textField.text): Bien placées: \(String(find))"
        }
    }

    @IBAction func resetCode(sender: AnyObject) {

    }
}

I need help
Comment: Please be clear on what you mean by "not works." What precisely do you expect to happen? What precisely does happen?
Comment: What are you trying in your code? It doesn't make a lot of sense.
Comment: It appears that he is trying to get each digit of the 4 digit random number individually.
Comment: Changed the answer, this should get what you want
Answer: If you're trying to get each digit of the random number individually:
class ViewController: UIViewController {

    var code = [String]()
    let textFromField = "1" // Text from your textField

    override func viewDidLoad() {
        let number = String(arc4random_uniform(9000) + 1000)
        code = map(number) { String($0) }
    }

    @IBAction func sendDidPressed(sender: AnyObject) {
        for index in 0..<code.count {
            if textFromField == code[index] {
                println("Match found at index: \(index + 1)")
            }
        }
    }
}

code is now an Array with the numbers separated as Strings
You should change the way you convert the random number to Int because according to this post:

Int(arc4random()) will crash 50% of the time it's executed on a 32-bit platform because a UInt32 won't fit in an Int32

EDIT: Simplified things
Comment: I'm not entirely sure what you want, but you should be able to get what you need with this example
Comment: Can you explain me what you did ?
Comment: First, you generate a random number, convert the number to `String` and store it in `code`. `map()` converts `code` to an array of type `String` and store it in `separated`. Now you have an array and can try to check if the array contains `find` using `contains()`.
Comment: Now it will iterate through the array of "numbers" and check if the "number" of your textfield matches with any of them.
Answer: Turn the random number into an array of characters,
var code = (arc4random_uniform() % 9000 + 1000)  //e.g. 1245
var codeAsArray = Array(String(code))    //e.g. [1, 2, 4, 5]

for (var i = 0; i < 4; i++) {
   // var number = textField.text

    println(codeAsArray[i]) //is a swift Character
}

Swift mastermind


Analyzing Hisaishi Joe's Song "Reprise"

Question: I was trying to analyze a song called "Reprise"
from my favorite composer Hisaishi Joe
and it really blew my mind how this song keep changing Keys
and doing all this harmony techniques that I don't get.
So I need some help to analyze this and explain it to me.

 (this is the song)

Picture 1 (Listen from 0.30)

this is a G major key song
if you see picture number 1
at bar 6 they end the part with the G Chord
and at part [C]
they go and start with the D Chord which is the dominant chord on the G key
the feeling this part give is kind of odd? not common to me.
is this part some kind of "Diatonic modulation"?
and they went to D key for a while?
could anybody analysis this chord progression for me?
this something happen here?
or am I just over thinking and he just started with the dominant chord
(and if he did isn't that kind of weird ?
to start the part with a dominant chord ?)

Picture 2 (Listen From 1:04)

At bar 3 after G/D it goes to A/C#
and then it goes to C maj chord.
is the A/C# just a passing chord?
How could you go to A/C# to C maj ?

Picture 3 (listen From 2:00)

(at this point the song changed in to E maj Key)
now if you see at part [H]
he went from B7 to G Maj chord
is this "Deceptive Cadence"
using flat 3 Maj7 modal interchange chord?
which is G Maj chord from the E Maj key?
and from this Part [H] the key changed again to C Maj Key
and after the beginning G chord
C#m7-5/G came out..what is this chord ?
how could this just come out of no where on C Maj key?
this four bars going from G major chord too the C Maj Chord.
I dont get this chord progression whats going on?
(I'm kind of thinking that it went to G key instead of C Key
because after the beginning G chord
the C#m7-5 is the #lVm7-5 of the G Maj key
and its also used as Tonic on the G Maj key
so after that it went down to F Maj
which is another modal interchage chord "flat Vll M7" on the G key
and also a pivot chord to C Maj Key which is about to come out
an then comes the F dim7
which could be kind of like G7 flat 9 with out the root
than it goes to C Maj Key..what do you think?)

4.
Picture 4 (listen from 2:40)
so its still C Maj key
and if you see at bar 4
its ends the part with D7
and gives a little space to the next bar
and then at Part [J]
it goes to this part with no chords..
so whats really going on here..
I'm kind of thinking that it went to G7
which is the Dominant chord on the C maj key
and its just extending it
and they didn't wrote down the chord because
its just arpeggios going on and no harmony

5.
At picture 5 (3:00)
now the arpeggios stops and came to Am7
(in the orginal orchestra version the arpeggios goes on while chords keep on coming out from now on)
if what I said at Picture 4,G7 Extended arpeggio thing was right
then it fits that it came to Am7
after a few bars
it goes starts again with
Am to Em/B
and from this part I really don't know whats going on in this chord progressions
I couldn't find anyways to connect this progressions to make sense to me..
whats going on here??..

wow it really took me long to right this all down..
I hope I didn't come too complicated..
sorry for my poor English.
English isn't my first language
hope I get some good answers
Comment: I think that you have some good questions here, but it is preferred that you ask one focused question in a post. You may want to break this question into smaller chunks and post separate questions; this might make it more likely for you to get detailed answers to each of your questions. It will certainly make it easier for answerers to read.
Comment: Sorry for many questions in one post
I'm new to this place and this was my first post and I didn't know about that. I thought that it wouldn't be a good thing to fill the board up with multiple question at one time..
anyway thanks for the advice !
I will consider that !
Answer: Lots of questions, but they're good ones!

At [C], the music has moved into G major. Two bars before [C], the Am7-D7-G is just a ii7-V7-I progression that modulates to G major. As such, the D at [C] is just the dominant of G.
We can analyze this A/C♯ a few ways, but I think the most important thing to recognize is the chromatically descending bassline. Starting with the Em chord, the bass moves E-D♯-D♮-C♯-C♮. The A/C♯ is just a passing chord that harmonizes that C♯ in the bass.
The B7 to G resolution is a type of deceptive resolution, yes. Typically deceptive resolutions go to ♭VI, but ♭III (which is what G is in the key of E) are also possible. As for the C♯m7♭5/G, I wouldn't worry too much about trying to analyze that one; I think it's a pretty poor label, honestly, and it just confuses what's actually happening. In my opinion, it's best to just recognize this as chromatic motion between the G and F chords.
[J] is just a vague in-between space that splits A minor and C major. This is another type of deceptive motion, because you were expecting a G chord after the D7.
After the cadence on Am, the music moves towards C major. The Fmaj7 to G9 are firmly in C major, but then the music uses mode mixture with the Fm and Gm harmonies. The mode mixture continues with the A♭ and B♭ chords; ♭VI to ♭VII to I is a really common progression, and that's all that's taking place here. (But note that it resolves to A, the vi, not to C, the I.)

You may try asking these questions individually; you'll probably get more in-depth answers that way.
Comment: I add a another answer to your question
I couldn't add it to it on the comment section because it was too long.
And yes I'll definitely post these questions individually now on

Analyzing Hisaishi Joe's Song "Reprise"


ScrollView with fixed height inside dialog in Android

Question: I am trying to do ScrollView in dialog popup with this code:
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="40dp" >

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="40sp"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/new_realm_avatar"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_centerHorizontal="true"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/new_realm_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/new_realm_avatar"
            android:text="long text" />
    </RelativeLayout>
 </ScrollView>

</RelativeLayout>

So when I call this in my message part and the text is bigger than the screen it becomes scrollable but hides the keys and it's height is as big as the phone screen. I want the message in the dialog to be  with fixed height like I tried by wrapping the ScrollView with another layout and enforcing it height but it doesn't work that way too. So anyone has any ideas?
Answer: Try this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="40dp" >

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="40dp" >

        <ImageView
            android:id="@+id/new_realm_avatar"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_centerHorizontal="true"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/new_realm_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/new_realm_avatar"
            android:text="long text" />
    </RelativeLayout>
</ScrollView>

</RelativeLayout>

Comment: It helped me. Thanks! Can you explain me the reason behind this?
Answer: First of all in your child RelativeLayout replace this :
android:layout_height="40sp"

with
android:layout_height="40dp"

Because sp uses for font size


What is inverse tangent?

Question: I recently started thinking about what inverse tangent is. It is obvious that the definition of tangent is $\frac{\sin x}{\cos x}$, however, what is inverse tangent?
I first thought $\tan^{-1} x = \frac{\sin^{-1} x}{\cos^{-1} x}$, but it didn't seem right when I graph it out.
One interesting I find is in most of the programming language I know, there are two atan functions. Does this mean there are two definition of $\tan^{-1}$?
Answer: I will not comment on a relationship between arctan and arcsine and/or arccosine., other than I do not know of anything simple or commonly known.
In common programming languages, there are two arctan functions.  $\phi=\text{atan}(y)$ is an angle whose tangent is $y$, such that $x \in (-\pi/2,\pi/2)$.  This ignores anything in the second and third quadrant.  To fix this, $\phi=\text{atan2}(x,y)$ (the arguments are sometimes reversed) is the angle whose cosine is $x$ and whose sine is $y$.  This allows the second and third quadrant to be determined at the cost of having to input the sines and cosine instead of simply the tangent.

What is inverse tangent?


Struct defined in header and included in two source codes is only defined in one

Question: I have a struct defined in a header file with three other files that #include that header file.  One is another header(queue.h) file that defines a very basic hash table and the other two are source codes where one is defining the functions from the hash table header(queue.cpp) and the other contains main(p2.cpp).
The problem that I'm having is that the struct seems to work fine in p2.cpp but in queue.h the compiler is telling me that the struct is undefined.
Here is p2.h containing the struct definition.
#ifndef __P2_H__
#define __P2_H__

#define xCoor 0
#define yCoor 1

#include <iostream>
#include <string>
#include "queue.h"
#include "dlist.h"  //linked list which I know works and is not the problem

using namespace std;

struct spot {
    float key[2];
    string name, category;
};

#endif /* __P2_H__ */

I have queue.h included in this header so that I only have to include p2.h in p2.cpp.
Here is p2.cpp
#include <iostream>
#include <string>
#include <iomanip>
#include "p2.h"
using namespace std;

int main () {

    cout << fixed;
    cout << setprecision (4);
    Queue hashTable;
    spot *spot1 = new spot;
    spot1->key[xCoor] = 42.2893;
    spot1->key[yCoor] = -83.7391;
    spot1->name = "NorthsideGrill";
    spot1->category = "restaurant";
    hashTable.insert(spot1);
    Dlist<spot> test = hashTable.find(42.2893, -83.7391);
    while (!test.isEmpty()) {
        spot *temp = test.removeFront();
        cout << temp->key[xCoor] << " " << temp->key[yCoor] << " " << temp->name << " " << temp->category << endl;
        delete temp;
    }
    return 0;
}

Places and item in the hash table and takes it back out.
Here is queue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__

#include <iostream>
#include <string>
#include "dlist.h"
#include "p2.h"
using namespace std;

class Queue {
    // OVERVIEW: contains a dynamic array of spaces.

 public:

    // Operational methods

    bool isEmpty();
    // EFFECTS: returns true if list is empy, false otherwise

    void insert(spot *o);
    // MODIFIES this
    // EFFECTS inserts o into the array

    Dlist<spot> find(float X, float Y);

    // Maintenance methods
    Queue();                                   // ctor
    ~Queue();                                  // dtor

 private:
    // A private type
    int numInserted;
    int maxElts;
    Dlist <spot>** queue;

    // Utility methods

    //Increases the size of the queue.
    void makeLarger();

    int hashFunc(float X, float Y, int modNum);

};

#endif /* __QUEUE_H__ */

Here is queue.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include "queue.h"
using namespace std;

bool Queue::isEmpty() {
    return !numInserted;
}

void Queue::insert(spot *o) {
    if (numInserted >= maxElts) {
        makeLarger();
    }
    int index = hashFunc(o->key[xCoor], o->key[yCoor], maxElts);
    queue[index] -> insertFront(o);
}

Queue::Queue() {
    numInserted = 0;
    maxElts = 1000;
    queue = new Dlist<spot>*[maxElts];
    for (int i = 0; i < maxElts; i++) {
        queue[i] = new Dlist<spot>;
    }
}

Queue::~Queue() {
    for (int i = 0; i < maxElts; i++) {
        delete queue[i];
    }
    delete[] queue;
}

void Queue::makeLarger() {
    Dlist <spot>** temp = queue;
    queue = new Dlist <spot>*[maxElts*2];
    for (int i = 0; i < maxElts*2; i++) {
        queue[i] = new Dlist<spot>;
    }
    for (int i = 0; i < maxElts; i++) {
        while (!temp[i] -> isEmpty()) {
            spot *spotTemp = temp[i] -> removeFront();
            int index = hashFunc(spotTemp->key[xCoor], spotTemp->key[yCoor], maxElts*2);
            queue[index] -> insertFront(spotTemp);
        }
    }
    for (int i = 0; i < maxElts; i++) {
        delete temp[i];
    }
    delete[] temp;
    maxElts *= 2;
}

int Queue::hashFunc(float X, float Y, int modNum) {
    return ((int)(10000*X) + (int)(10000*Y))%modNum;
}

Dlist<spot> Queue::find(float X, float Y) {
    Dlist<spot> result;
    Dlist<spot> *temp = new Dlist<spot>;
    int index = hashFunc(X, Y, maxElts);
    while (!queue[index] -> isEmpty()) {
        spot *curSpot = queue[index] -> removeFront();
        if ((curSpot->key[xCoor] == X) && (curSpot->key[yCoor] == Y)) {
            result.insertFront(new spot(*curSpot));
        }
        temp -> insertFront(curSpot);
    }
    delete queue[index];
    queue[index] = temp;
    return result;
}

I believe that the problem is in my queue.h file because it's where I get all of the errors like "spot has not been declared".  Every time spot appears in queue.h I have at least one error.  I searched around for anything like this but all I could find was people trying to share one instance of a struct across multiple source files, or the obvious question of putting a struct in a header and including that header across multiple source files(which is what I'm doing but my problem seems to be a rather unique one).
Comment: Note that identifiers starting with a double underscore are reserved by the implementation, don't use them.
Answer: You are including queue.h within the header that actually defines spot, so by the point the file is actually included spot has not been defined yet.
For your scope guards, note that identifiers starting with a double underscore are reserved by the implementation, don't use them.
And this is a poor choice even in plain C:
#define xCoor 0
#define yCoor 1

use this instead:
enum {
    xCoor = 0
  , yCoor = 1
};

Comment: Thanks, I'll make those changes.
Answer: Ok first never ever using "using" clauses in header files (it destroys the purposes of namespaces)
2nd provide a complete example that fails to compile
Comment: Sorry, this is for a class and just in case there are other people from my class with the same problem I didn't want to post everything for them to copy.  I left a lot out.
Comment: :-) np - but its easier for me even if its just skeleton classes to try your example and see what errors I get.
Comment: I'll do that next time. This was in fact my first rodeo with stack overflow.
Comment: Nice one - just make sure your example causes same problems - If you look at it from my point of view I just want to see your problem - I probably am not using your OS/comp :-)
Answer: In addition to what others have said, you also have a circular reference error, which can also lead to similar undefined symbol errors.  You have queue.h include p2.h, which includes queue.h.
Comment: Thanks, I'll work that out of the code and keep it in mind in the future.


Why is my IPYNB file opened as IPY File in Visual Studio Code?

Question: I have a Jupyter Notebook file with IPYNB, which when I tried to open in Visual Studio Code, would display an IPY extension and no longer in Jupyter Notebook format, but looks like this:

Why is this happening and how can I convert it to Jupyter Notebook format?
Comment: Well the code you show looks to be `.ipynb`-based and not `.ipy`-based. `.ipy` code is basically Python with IPython magics allowed. What you show is fragment of json that is generally the underlying code of an `.ipynb` file. I would suggest opening it as a text file like you show in your image and copy it into a new file that you save specifically with an `.ipynb` extenstion. They try opening the new file. Hopefully it opens as a notebook and you can swap out the weird one.
Comment: If that doesn't work. I'd suggest doing the same thing inside a temorary Jupyter session served via MyBinder.org. To do that go [here](https://github.com/binder-examples/requirements) and press `launch binder`. After the session spins up, you'll have modern JupyterLab interface. Under `File` select `New` > `Text file` and paste in the text you have. Rename the file by right-clicking on the file name tab and change the extension to `.ipynb`. Try to double-click on that in the file navigator pane on the left & see if it opens as a notebook now. If it does, download that file back to your local.
Comment: Do you have the notebook plugin installed?
Comment: Hi @HristoIliev I think so, I have no problem opening other IPYNB files with VSC but just this one.
Answer: You can modify the file type manually.

Use "F2" and change .ipy to .ipynb


Which yum repositories for Oracle Linux 7 can I use to install Kubernetes?

Question: I've been able to successfully install Kubernetes in a CentOS 7 testing environment using the "virt7-testing" repo as described in the CentOS "Getting Started Guide" in the Kubernetes github repo.  My production environment will be running on Oracle Linux 7, and so far enabling "virt7-testing" on OL7 hasn't been working.
Are there any other yum repositories out there that are compatible with OL7 and include Kubernetes?
Answer: It's not the best solution to pull outside of OEL, but I couldn't find an OEL repository with these packages, so I used this:
[]# cat /etc/yum.repos.d/virt7-common.repo
[virt7-common]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirror.centos.org/centos/7/extras/$basearch/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

Comment: This worked fine in setting up my kubernetes cluster on OEL 7.2 (masters and minions).
Comment: Just a small addition, you need to install the centos 7 GPG key:

rpm --import http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-7
Comment: I get this error when I use the above on my OEL7.2. Error: Package: 2:container-selinux-2.10-2.el7.noarch (virt7-common)
           Requires: policycoreutils >= 2.5-11
           Installed: policycoreutils-2.2.5-20.0.1.el7.x86_64 (@anaconda/7.2)
               policycoreutils = 2.2.5-20.0.1.el7
Any clue?
Comment: updated all packages by adding this repo as well https://docs.oracle.com/cd/E52668_01/E54669/html/ol7-downloading-yum-repo.html and it worked. thx
Answer: A good start would be the rapidly updated fedora / epel kubernetes repositories.
Something like (untested)
yum --enablerepo=updates-testing install kubernetes kubernetes-devel flanneld docker
Should do it for you.


Functors with multiple arguments in OCaml

Question: I've the following situation:
module type M = sig type s = ...  end

module Make(P: Something) : (M with type s = P.t) = struct
   type s = P.t
   ...
end

that works fine to generate modules of M type that use specific implementation of modules of type Something inside their implementation.
Now suppose I have another module defined as
module type AU = sig
  val feed : float -> unitv
  val nth : int -> (float -> float)
  val reset : unit -> unit
end

that has various implementations
module SUAlg : AU = struct ... end
module MLAlg : AU = struct ... end
module ACEAlg : AU = struct ... end

The point of the question is that the M module should be parametrized over two things now: a Something module and a AU module so that it's something like
module Make(P: Something) : (M with type s = P.t) = struct
   type s = P.t
   module Alg = MLAlg (* just an example *)
   ...
end

but I would like to have a generic functor that given a Something and given an AU it produces a module with both things concretized. Is there a way to obtain that easily?
Since functor syntax is quite strange and I'm still new to it I don't know if what I'm asking can be solved in a simple way or not.
Thanks in advance
Answer: Yes, a functor can have several arguments. The syntax is like this:
module Make_LOffset
            (V:Lattice_With_Isotropy.S)
            (LOffset : Offsetmap.S with type y = V.t and type widen_hint = V.widen_hint) =
struct
   …
end

The functor can then be applied with Make_LOffset(V)(LOffset).
In this example, taken from existing code to ensure it is syntactically correct, Make_LOffset is parameterized by two modules V and LOffset, of respective signatures Lattice_With_Isotropy.S and Offsetmap.S. There are additional type constraints between the two signatures, the with type … and type … part.
Comment: @stumped Well the arguments would be module, so they would look like `Arg1` and `Arg2`. The syntax is  `Make_LOffset(Arg1)(Arg2)`. I have updated the answer.
Comment: Is there a different syntax for passing arguments into the functor? Make_LOffset(arg1 arg2)?


USAHockey registration purpose?

Question: So I've been just recently mastering ice skating and I'm getting pretty good at hockey from practice and I'm considering vouching for a small team to join soon.
I gave a few proposals, but was asked if I was part of the USAHockey group and I am not (didn't see a reason for it or didn't understand the purpose).
I checked the website and I am unsure what it is exactly.
Is this like a union or something? I read the benefits, but what is the purpose?
http://www.usahockey.com/membership

registering with USA Hockey provides all of the advantages of an unregistered league while eliminating the disadvantages.

So is it a league, group, union, all of the above, etc.? Is it a good idea to join if I intend to play hockey in minor league, or is this only for non-professional hockey? Yes, I am in the U.S.
Perhaps anyone can shed some more details on the purpose of this registration with regards to hockey, hockey players, and playing hockey professionally (in other words, for money).
Answer: Quite simply, USA Hockey is the official governing organisation for amateur ice hockey in the USA.
They decide what rules and regulations apply to national competitions; they educate and give accreditation to officials; they select the national teams; they run the Hall of Fame; they are the representative of USA in the IIHF and of USA ice hockey in the IOC.
They are not the organisers or managers of the USA NHL, but they claim a close partnership, and if you intend to play professionally, it is likely that you will need to play well in the amateur competitions that they do have oversight responsibility for - something that would almost certainly require membership.
I cannot find any regulation governing membership of USA-origin NHL players in external organisations and therefore cannot say whether USAH membership is neutral, recommended or even mandatory. However I doubt it would be considered a negative factor and therefore would be neutral at worst.
You can find a run-down of membership benefits in the PDF at http://www.usahockey.com/page/show/837667-usa-hockey-membership-benefits
Note that one is insurance, and some USAH policies relate to persons in contact with youth. Presumably a team or club or league has added financial and legal risk if allowing non-USAH members to play, and therefore may also mandate that you be a member before you can officially play (that is, if USAH itself doesn't; I cannot find a reference either way on this).
You should ask the team, club or league secretary if such a mandate is in place and whether they recommend membership, or what the potential outcomes would be for e.g. injury liability, playing and administration fees, eligibility.
Answer: Local clubs, which you may join to play in a local league, can be affliates of USA Hockey.  For example, local clubs in St. Louis belong to Missouri Hockey, which is an affliate of USA Hockey.   As mentioned in the previous answer, USA Hockey provides benefits such as insurance, training, goverance, safety programs, and other benefits.  If you want to participate in programs, leagues, and tournaments sponsored by a USA Hockey affiliated organization, you'll be required to join USA Hockey.  The annual fee for 2016-2017 is $40 plus an affiliate fee that goes back to the local affiliate for its own governance, training, screening programs, etc.  The 2016-2017 affliate fee for Missouri Hockey is $8 - it may be more or less for your local affliate.  Annual membership runs from September 1st though August 31st.  Renewals for the upcoming season start April 1st.
While most clubs in the United States are members of USA Hockey, it's not required for a local club to join.  There are other governing organizations, like the Amateur Athletic Union for example, in which local clubs can participate.  Or they could presumably stay independent if they provided their own insurance and such.  However, organizations and players who are not members of USA Hockey may not participate in any USA Hockey program, and USA Hockey members can not participate in any non-USA Hockey sanctioned program.  You can have dual membership, but that would be governed by the club.
Answer: The main benefit is going to be insurance coverage.  Many facilities require sports team participants to be registered with an organization that offers insurance coverage, so they don't have to go through the process of getting additional coverage, and then documenting people covered to the satisfaction of their facility's insurance carrier.
This coverage usually covers the team against liability and medical claims, and covers participants for medical costs if injured during an organized activity (practice, training, competition).

USAHockey registration purpose?


Next link on node page based on its taxonomy term

Question: So here is what I'd like to achieve:
I'd like to put a Next link to every content of a type, that links to the next content with the same taxonomy term.
So for examle if I have A, B and C products with the term 'clothing' on them, I need a link A product that points to B, one link on B that points to C and so on.
How is this possible to do?
Answer: It's only in Alpha but the Treewalk Previous / Next module appears to have that functionality:

Previous/Next (Back/Forward) links for entity and other pages, that allow to visit them in a sequence.
Unlike with the existing back/forward module, the sequence of items (entities etc) is not based on a view, but on hierarchical information already present in your site.

It provides a configurable block with prev/next links based on menu trees. The block is named "Treewalk Prev/Next (Menu)"
It provides Display suite fields with prev/next links based on entityreference / taxonomy_term_reference fields. The ds fields are named as "Treewalk Prev/Next (...)".

I've never used it but it might at least be a starting point to implement the logic yourself.
Answer: You can use the Flippy module for this.

Flippy is an ultra-simple module that generates previous/next pagers for content types. On the Node type administration screen, you can turn Flippy on or off
  for each content type. It'll generate a unique pager for each content type, so you can page through Articles or page through Blog posts, but you can't page
  through all nodes on the site.
Comment: Does that module work based on a vocabulary (per the question)?
Comment: @Clive: I am not sure but we can alter its query in our custom module..
:)
Comment: Flippy doesn't seem to be providing sorting content based on taxonomy terms.
Comment: @BálintDeáki: open this module and alter its query using hook_query_alter in your custom module


Are some viola tuning pegs the same size as 4/4 violin tuning pegs?

Question: I know that adult size violas are sold by length in inches, (i.e. instead of 4/4, 7/8, etc.) and can vary to better fit the player.
Are viola tuning pegs all the same diameter or do those have to change depending on the specific viola size? Are some 4/4 violin tuning pegs interchangeable with some violas, or are all adult viola tuning pegs larger in diameter than their violin counterparts?
Answer: There are different sizes of pegs for violas, but they are not really standardized.  And a thick violin peg will fit some viola, but the head is likely to be a bit smaller.
Comment: The taper of the pegs also needs to match the taper of the holes, otherwise tuning will be somewhere in between difficult and impossible. The taper can accommodate *small* differences in peg diameter between different instruments.
Comment: True.  While there is a modern standard of 1:30 taper for violins and violas, and 1:25 for cello, you can't assume any given hole or peg is going to fit, especially with old instruments.
Answer: From 15 inch Violas and larger the tuning pegs are larger than violin. The 14 inch Viola corresponds in size to the 4/4 violin, and the 13 inch to the 3/4 violin.
Tuning pegs are sold in "blanks" with the taper size large for cutting down to fit. Viola peg blanks often have "Standard" and "Thick" sizes available for the shank size as well. The head sizes change with the different size pegs.
How big the shank ends up being is different for each instrument, dependent on the manufacturer and age of the instrument. Each peg set is shaped specifically for each instrument and peg hole. Eventually with wear and/or reaming the peg holes may become too large and require filling and re-holing.
Taper size is currently standard at 1:30 ratio, and older tapers for gut string instruments may be found down to 1:20.


How to find all nodes and their links to other nodes by traversing them in both directions (fathers and children)?

Question: I have a client application consuming data from an external API based on a configuration during startup.
Since calculating the necessary data is not easy for me, I tried to fake the implementation and calculate it locally for now.
There are many WorkItems linked to each other and the configuration only knows about the relations to consider.

Some explanations:
Workitem
A workitem has a unique id and a type
e.g.
{
    id: 1,
    type: "person"
}

so you know that Workitem 1 is of type person
Linkrole
A linkrole is a composite key of three keys

The parrent workitem type
The child workitem type
The name of the role

e.g.
{
    parentWorkItemType: "person",
    childWorkItemType: "house",
    name: "owns",
}

which represents Person owns House
Links
The backend knows about the relations, a link between workitems might look like
{
    /* each link is unique */
    linkRole: {
        parentWorkItemType: "person",
        childWorkItemType: "house",
        name: "owns",
    },
    parentId: 1,
    childId: 2
}

so you know that Person 1 owns House 2

Fake prerequisites:
Fake backend
I created some fake data for my calculations. The file backend.js represents the backend / database
// backend.js

export const workItems = [{
    id: 1,
    type: "car"
}, {
    id: 2,
    type: "car"
}, {
    id: 3,
    type: "bird"
}, {
    id: 4,
    type: "bird"
}, {
    id: 5,
    type: "bird"
}, {
    id: 6,
    type: "invalid"
}, {
    id: 7,
    type: "house"
}, {
    id: 8,
    type: "house"
}, {
    id: 9,
    type: "house",
}, {
    id: 10,
    type: "person",
}];

export const workItemLinks = [{
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "bird",
        name: "isChildOf",
    },
    parentId: 1,
    childId: 3
}, {
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "bird",
        name: "isChildOf",
    },
    parentId: 1,
    childId: 4
}, {
    linkRole: {
        parentWorkItemType: "bird",
        childWorkItemType: "house",
        name: "with",
    },
    parentId: 3,
    childId: 7
}, {
    linkRole: {
        parentWorkItemType: "bird",
        childWorkItemType: "house",
        name: "with",
    },
    parentId: 3,
    childId: 8
}, {
    linkRole: {
        parentWorkItemType: "person",
        childWorkItemType: "car",
        name: "owns",
    },
    parentId: 10,
    childId: 1
}, {
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "car",
        name: "references",
    },
    parentId: 1,
    childId: 2
}];

Fake API
I created some methods inside the file api.js to fake an API asking the backend for data.
Important sidenote: These methods just help me to find the data I need. I can add more "helpers" if needed (In the real world I can ask to add more API endpoints) so everything can be queried. Please feel free to modify the "Fake API".
// api.js

import { workItems, workItemLinks } from "./backend.js";

export function getWorkItemsByType(workItemType) {
    return workItems.filter(workItem => workItem.type === workItemType);
}

export function getWorkItemsByIds(workItemIds) {
    return workItems.filter(workItem => workItemIds.some(workItemId => workItemId === workItem.id));
}

export function getWorkItemLinksByLinkRoleAndLeftSideIds(linkRole, leftSideIds, leftSideIsParentSide) {
    return workItemLinks.filter(workItemLink => {

        // Pseudo equality check

        if (workItemLink.linkRole.parentWorkItemType === linkRole.parentWorkItemType &&
            workItemLink.linkRole.childWorkItemType === linkRole.childWorkItemType &&
            workItemLink.linkRole.name === linkRole.name) {
            const leftSideIdInLink = leftSideIsParentSide ? workItemLink.parentId : workItemLink.childId;

            // Return this link if it matches with the left side id ( you're looking for the right side id )

            return leftSideIds.some(leftSideId => leftSideId === leftSideIdInLink);
        }

        return false;
    });
}

Fake configuration
I created definitions inside configuration.js to start the calculations based on those
// configuration.js

export const definitions = [
    {                                           // fetch linked birds from every root car
        linkRole: {
            parentWorkItemType: "car",
            childWorkItemType: "bird",
            name: "isChildOf",
        }
    },
    {                                           // !! Root Element !! Fetch work items based on type
        workItemType: "car",
        isRootWorkItem: true
    },
    {                                            // fetch linked houses from every bird ( car - bird - house )
        linkRole: {
            parentWorkItemType: "bird",
            childWorkItemType: "house",
            name: "with",
        }
    },
    {                                             // fetch every person from every car ( person - car )
        linkRole: {
            parentWorkItemType: "person",
            childWorkItemType: "car",
            name: "owns",
        }
    },
    {                                          // Self reference, fetch linked cars from every root car
        linkRole: {
            parentWorkItemType: "car",
            childWorkItemType: "car",
            name: "references",
        }
    },
];

Problem to solve:
I am looking for a performant way to fetch every related link and workitem from the backend based on the chain of relations starting with each root item.
Expected output based on the configuration:
export const workItems = [{
    id: 1,
    type: "car"
}, {
    id: 2,
    type: "car"
}, {
    id: 3,
    type: "bird"
}, {
    id: 4,
    type: "bird"
}, /* no car is linked to bird 5, no links for invalid 6 */ {
    id: 7,
    type: "house"
}, {
    id: 8,
    type: "house"
}, /* no bird is linked to house 9 */ {
    id: 10,
    type: "person",
}];

/* based on the configuration every workItemLink from the backend got fetched */

My first implementation approach:
import { inspect } from "util";

import { getWorkItemsByType, getWorkItemsByIds, getWorkItemLinksByLinkRoleAndLeftSideIds } from "./api.js";
import { definitions } from "./configuration.js";

// Find the root definition

const { workItemType: rootWorkItemType } = definitions.find(definition => definition.isRootWorkItem);

// Fetch all the root workitems and initialize the store holding unique workitems

const workItems = getWorkItemsByType(rootWorkItemType); // will hold car 1 and car 2

const initialWorkItemIds = workItems.map(workItem => workItem.id);

const workItemIdsToLoad = []; // try to read all missing ids from fetched links and fetch all the workitems at once later on

const workItemLinks = []; // global store for links

const definitionsToTraverse = definitions.filter(definition => definition.linkRole !== undefined); // do not consider the root definition

run(initialWorkItemIds, rootWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks);

const missingWorkItemIdsToLoad = workItemIdsToLoad.filter(workItemIdToLoad => !rootWorkItemIds.some(rootWorkItemId => rootWorkItemId === workItemIdToLoad)); // filter out all the existing root item ids

const workItemsToAdd = getWorkItemsByIds(missingWorkItemIdsToLoad); // fetch all the missing workitems at once

workItems.push(...workItemsToAdd); // add them to the global store

console.log(inspect({
    workItems,
    workItemLinks
}, false, null, true))

function run(leftSideWorkItemIds, leftSideWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks) {
    /*

        consider all the defitions from "definitionsToTraverse" directly related to "leftSideWorkItemType"
        remove them from "definitionsToTraverse" to prevent endless loops
        loop backwards so splice won't struggle with the indices

    */

    for (let definitionIndex = definitionsToTraverse.length - 1; definitionIndex >= 0; definitionIndex--) {
        const currentDefinition = definitionsToTraverse[definitionIndex];
        const { linkRole } = currentDefinition;
        const { parentWorkItemType, childWorkItemType } = linkRole;

        const leftSideWorkItemTypeIsParent = parentWorkItemType === leftSideWorkItemType;
        const leftSideWorkItemTypeIsChild = childWorkItemType === leftSideWorkItemType;

        // Check the direct relation

        if (leftSideWorkItemTypeIsParent || leftSideWorkItemTypeIsChild) {
            // Remove the inspected definition

            definitionsToTraverse.splice(definitionIndex, 1);

            const relatedWorkItemLinks = getWorkItemLinksByLinkRoleAndLeftSideIds(linkRole, leftSideWorkItemIds, leftSideWorkItemTypeIsParent);

            // store all the right side workitem IDs for the next run

            const rightSideWorkItemIds = [];

            for (let relatedWorkItemLinkIndex = 0; relatedWorkItemLinkIndex < relatedWorkItemLinks.length; relatedWorkItemLinkIndex++) {
                const relatedWorkItemLink = relatedWorkItemLinks[relatedWorkItemLinkIndex];

                // Process the link if not processed yet

                if (!workItemLinks.some(workItemLink => /* !!! pseudo equality check !!! */
                        workItemLink.linkRole.parentWorkItemType === relatedWorkItemLink.linkRole.parentWorkItemType &&
                        workItemLink.linkRole.childWorkItemType === relatedWorkItemLink.linkRole.childWorkItemType &&
                        workItemLink.linkRole.name === relatedWorkItemLink.linkRole.name &&
                        workItemLink.parentId === relatedWorkItemLink.parentId &&
                        workItemLink.childId === relatedWorkItemLink.childId)) {

                    // Push the link to the store

                    workItemLinks.push(relatedWorkItemLink);

                    // Get the right side id from the link

                    const rightSideWorkItemId = leftSideWorkItemTypeIsParent ? relatedWorkItemLink.childId : relatedWorkItemLink.parentId;

                    rightSideWorkItemIds.push(rightSideWorkItemId);

                    // Push the id to the store if it doesn't exist

                    if (!workItemIdsToLoad.some(workItemIdToLoad => workItemIdToLoad === rightSideWorkItemId)) {
                        workItemIdsToLoad.push(rightSideWorkItemId);
                    }
                }
            }

            // Find the opposite workitem type of the current definition

            const rightSideWorkItemType = leftSideWorkItemTypeIsParent ? childWorkItemType : parentWorkItemType;

            // Run again but use this definition as the previous one

            run(rightSideWorkItemIds, rightSideWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks);
        }
    }
}

The problem is that my approach crashes because the backwards loop even runs if definitionsToTraverse is empty. And I'm mutating the arrays from the parameters directly, I think I shouldn't do that.
So any help would be appreciated a lot!
Comment: Very thorough, but not minimal.  You could save potential answerers a ton of work by trimming it down and making it a runnable snippet.
Comment: There's a lot here, and I feel as through `linkRole` is entirely irrelevant to the question as asked; could it simply be removed?  Do I have this right?  You have (here) a single root type of `car`. and so you want to include both cars, and then you want to include all nodes which have either of those cars as parent or child values in a link, and then include all nodes which have any of those results a a parent or child in a link, and so on recursively, collecting all the results not in a tree but in a simple list.  Is that right?
Comment: @ScottSauyet I think you are right. The "chains" will be `person - car - bird - house` where `car` is the root one and all the relations are based on it.
Comment: @ScottSauyet the `linkRole` in the 'workItemLinks` is not properly normalized data structure, as the `workItemLinks[].parentId` and `.childId` can in turn reference the `workItems[].id` relating to the associated `.type`, which in turn can query `definitions[].linkRole.parentWorkItemType` or `.childWorkItemType`.  In which case, `linkRole` is necessary, but via the `definitions`.  In short, the `workItems`, `workItemLinks`, and `definitions` are not properly normalized if treating them as server side data tables...  (That being said, also see my next comment...)
Comment: @medsmh suggest within `definitions` to identify a root as just another linked role, but with a parent of null, and name of 'root'.  Also, there is then no need for the attribute of `linkRole`, but rather an array of objects only containing attributes of `parentWorkItemType`, `childWorkItemType`, and `name`.  Eg, `{parentWorkItemType:null, childWorkItemType:"car", name:"root"}`, `{parentWorkItemType:"car", childWorkItemType:"bird", name:"isChildOf"}`.
Comment: @Trentium: I did recognize that this was a denormalized data structure.  But my answer seems to demonstrate that for the purpose of the question, it's entirely irrelevant.  (I skip it altogether but still achieve the desired result.)  I read the question as starting with all element of any root types, find all elements that (recursively) have links to it.  Am I missing an edge case?  Something fundamental?
Answer: Update: Added a substantially cleaner version of the code.  I was bothered by the previous implementation.
I may be oversimplifying what you need to do here.  I'm treating this as described in my comment on the question:

Do I have this right? You have (here) a single root type of car. and so you want to include both cars, and then you want to include all nodes which have either of those cars as parent or child values in a link, and then include all nodes which have any of those results a a parent or child in a link, and so on recursively, collecting all the results not in a tree but in a simple list.

If that's correct, then this seems like a reasonable approach:

const getLinkedIds = (links, ids, toAdd = links
  .filter (({childId, parentId}) => ids .includes (childId) || ids .includes (parentId))
  .flatMap (({childId, parentId}) => [childId, parentId])
  .filter (id => !ids .includes (id))
) => toAdd .length == 0 ? ids : getLinkedIds (links, ids .concat (toAdd))

const linkedItems = (defs, items, links,
  rootTypes = defs.filter (({isRootWorkItem = false}) => isRootWorkItem)
    .map (({workItemType}) => workItemType),
  roots = items .filter (({type}) => rootTypes .includes (type)),
  ids = getLinkedIds (links, roots.flatMap (({id}) => id))
) => items .filter (({id}) => ids .includes (id))

const definitions = [ /* linkTypes deleted */  {workItemType: "car", isRootWorkItem: true}]
const workItems = [{id: 1, type: "car"}, {id: 2, type: "car"}, {id: 3, type: "bird"}, {id: 4, type: "bird"}, {id: 5, type: "bird"}, {id: 6, type: "invalid"}, {id: 7, type: "house"}, {id: 8, type: "house"}, {id: 9, type: "house"}, {id: 10, type: "person"}]
const workItemLinks = [ /* linkTypes deleted */ {parentId: 1, childId: 3}, {parentId: 1, childId: 4}, {parentId: 3, childId: 7}, {parentId: 3, childId: 8}, {parentId: 10, childId: 1}, {parentId: 1, childId: 2}]

console .log (
  linkedItems (definitions, workItems, workItemLinks)
)
.as-console-wrapper {max-height: 100% !important; top: 0}

In linkedItems, we start with the definitions to collect the root types, then use those to collect all the root elements.  We then call our main function, getLinkedIds using links, and the ids of these elements.  Then we filter the items to find those whose ids we chose.
getLinkedIds finds all the links that include any of our ids as either parent or child, and adds both parent and child to a list of ids that will be included, and when its done, filters out any that are already in our list.  If this list of ids to add is empty, we're done and return our current list.  Otherwise we recur on the combination of the two lists.  While there may be some inefficiencies here, I think the lists would have to be quite large for them to matter.
I haven't tried to read your code and understand how it differs from this, but if my guess is correct about your requirements, this is relatively simple.

Old Version
This is not my usual coding style, and it bothers me.  I tend to work with direct recursion, and I usually use immutable data structures.  I would love to see an approach that handles this using that style, but I didn't come up with one right away.
Update: The comment above applied to this older version of the code.  The newer version seems fine to me.
Here is a description of the original implementation of getLinkedIds (the other function has only cosmetic changes):
getLinkedIds keeps two lists of ids: those still to process and those we've already processed, repeatedly removing an id from the first list, adding it to the second and then queueing up all the unprocessed parentIds for which we have a childId link to the current value and then all the unprocessed childIds for which we have a parentId link to the current value.  When the toProcess queue is empty, we return the processed one.
And you can expand this snippet to see that version (which I don't recommend:

const getLinkedIds = (links, ids) => {
  const toProcess = [...ids], processed = []
  while (toProcess .length > 0) {
     const id = toProcess .pop ()
     processed .push (id)
     links .filter (({parentId}) => id == parentId)
       .forEach (({childId}) => {
         if (! processed .includes (childId) && ! toProcess .includes (childId)) {
           toProcess .push (childId)
         }
       })
     links .filter (({childId}) => id == childId)
       .forEach (({parentId}) => {
         if (! processed .includes (parentId) && ! toProcess .includes (parentId)) {
           toProcess .push (parentId)
         }
       })
  }
  return [...processed]
}

const linkedItems = (defs, items, links) => {
  const rootTypes = defs .filter (({isRootWorkItem = false}) => isRootWorkItem)
    .map (({workItemType}) => workItemType)
  const roots = items .filter (({type}) => rootTypes .includes (type))
  const ids = getLinkedIds (links, roots.flatMap (({id}) => id))
  return items .filter (({id}) => ids .includes (id))
}

const definitions = [ /* linkTypes deleted */  {workItemType: "car", isRootWorkItem: true}]
const workItems = [{id: 1, type: "car"}, {id: 2, type: "car"}, {id: 3, type: "bird"}, {id: 4, type: "bird"}, {id: 5, type: "bird"}, {id: 6, type: "invalid"}, {id: 7, type: "house"}, {id: 8, type: "house"}, {id: 9, type: "house"}, {id: 10, type: "person"}]
const workItemLinks = [ /* linkTypes deleted */ {parentId: 1, childId: 3}, {parentId: 1, childId: 4}, {parentId: 3, childId: 7}, {parentId: 3, childId: 8}, {parentId: 10, childId: 1}, {parentId: 1, childId: 2}]

console .log (
  linkedItems (definitions, workItems, workItemLinks)
)
.as-console-wrapper {max-height: 100% !important; top: 0}
Comment: Hey, I tried to provide another solution https://stackoverflow.com/a/71102756/7764329, I will compare your answer with mine and check for differences :)
Comment: Thanks, @PeterSeliger.  If I really got the requirements right, it's not that complex a problem.  But I'm afraid I may be missing something.
Answer: General Considerations
Suggest pushing most of the work onto the server, as presumably the workItems and workItemLinks will be comprised of a large number of records.  If the work of traversing the tree of workItems is left to the client making individual API calls, then network latency comes into play...
Data Structure
Suggest normalizing the data as follows:

WorkItems - No change.
WorkItemLinks - Reduce attributes to parentId and childId, which is essentially a many-to-many entity with the WorkItems entity.
Definitions - Flatten to parentWorkItemType, childWorkItemType, and name.  Root entries are handled by setting parentWorkItemType to null.

Note also that realistically, the need for Definitions is likely not necessary when traversing WorkItemLinks, as presumably the entries within the WorkItemLinks, when created, were only permitted to be created if the relationship between the parentId type and childId type conformed to the Defintions.  If indeed this is the case, then the proposed code can likely be simplified further...
Proposed APIs
The solution below proposes two (2) APIs:

getDefinitionChain( rootWorkItemType ) - Given a rootWorkItemType (eg, "car"), this API traverses the children and parents of the Definition entity, and returns all the related workItemTypes.
getWorkItemChain( rootWorkItemType ) - Initially calls getDefinitionChain to identify the related workItemTypes, and then traverses workItems starting with the rootWorkItemType.

Again, the concept being that these APIs are server side, reducing the chattiness between the client and server...

const workItems = [{"id":1,"type":"car"},{"id":2,"type":"car"},{"id":3,"type":"bird"},{"id":4,"type":"bird"},{"id":5,"type":"bird"},{"id":6,"type":"invalid"},{"id":7,"type":"house"},{"id":8,"type":"house"},{"id":9,"type":"house"},{"id":10,"type":"person"}];

const workItemLinks = [
  {
    "parentId": 1,
    "childId": 3
  },
  {
    "parentId": 1,
    "childId": 4
  },
  {
    "parentId": 3,
    "childId": 7
  },
  {
    "parentId": 3,
    "childId": 8
  },
  {
    "parentId": 10,
    "childId": 1
  },
  {
    "parentId": 1,
    "childId": 2
  }
];

const definitions = [
  {
    "parentWorkItemType": "car",
    "childWorkItemType": "bird",
    "name": "isChildOf"
  },
  {
    "parentWorkItemType": null,
    "childWorkItemType": "car",
    "name": "root"
  },
  {
    "parentWorkItemType": "bird",
    "childWorkItemType": "house",
    "name": "with"
  },
  {
    "parentWorkItemType": "person",
    "childWorkItemType": "car",
    "name": "owns"
  },
  {
    "parentWorkItemType": "car",
    "childWorkItemType": "car",
    "name": "references"
  }
];

function getDefinitionChain( rootWorkItemType ) {

  let alreadyVisitedType = new Set();
  let definitionChain = [];

  function recurse( workItemType ) {

    // Visit the children types...
    let nodeTypeChildList = definitions.filter( def => def.parentWorkItemType === workItemType );

    for ( let childType of nodeTypeChildList ) {
      if ( !alreadyVisitedType.has( childType.childWorkItemType ) ) {
        alreadyVisitedType.add( childType.childWorkItemType );
        definitionChain.push( childType.childWorkItemType );
        recurse( childType.childWorkItemType );
      }
    }

    // Visit the parent types...
    let nodeTypeParentList = definitions.filter( def => def.childWorkItemType === workItemType );

    for ( let parentType of nodeTypeParentList ) {
      // Don't go up the definition chain if parent is null.
      if ( parentType.parentWorkItemType && !alreadyVisitedType.has( parentType.parentWorkItemType ) ) {
        alreadyVisitedType.add( parentType.parentWorkItemType );
        definitionChain.push( parentType.parentWorkItemType );
        recurse( parentType.parentWorkItemType );
      }
    }

  }

  recurse( rootWorkItemType )
  if ( !alreadyVisitedType.has( rootWorkItemType ) ) {
    definitionChain.push( rootWorkItemType );
  }

  return definitionChain;

}

function getWorkItemChain( rootWorkItemType ) {

  // Get the list of allowable definitions...
  let allowableDefinitions = new Set( getDefinitionChain( rootWorkItemType ) );

  // Now, traverse the WorkItems tree, ensuring that they are in the WorkItemType list...
  let wim = new Map();

  function recurse( workItemCandidates ) {

    for ( let workItem of workItemCandidates ) {
      // Is this a workItemType that conforms to our allowable definitions?
      if ( allowableDefinitions.has( workItem.type ) ) {
        // If never having traversed this WorkItem, then let's traverse the children and parents.
        if ( !wim.has( workItem.id ) ) {
          wim.set( workItem.id, workItem );

          // Get the list of WorkItems that are children to the workItem.id.
          recurse( workItemLinks.filter( wix => wix.parentId === workItem.id ).map( wil => workItems.find( wif => wif.id === wil.childId )) );

          // Get the list of WorkItems that are parents to the workItem.id.
          recurse( workItemLinks.filter( wix => wix.childId === workItem.id ).map( wil => workItems.find( wif => wif.id === wil.parentId )) );
        }
      }
    }

  }

  // Start with all the workItems that are of type rootWorkItemType.
  recurse( workItems.filter( wi => wi.type === rootWorkItemType ) );

  return [...wim.values()];

}

console.log( 'WorkItem Types in Definitions with a root of "car".' );
let definitionChain = getDefinitionChain( 'car' );
console.log( definitionChain );

console.log( 'WorkItems with a root of "car"' );
let workItemChain = getWorkItemChain( 'car' );
console.log( workItemChain );
Comment: Hey, I tried to provide another solution https://stackoverflow.com/a/71102756/7764329, I will compare your answer with mine and check for differences :)


Can this differential equation be transformed into an hypergeometric equation?

Question: $$(1+x^2)y'' -4xy' + 6y = 0 $$
Can this be transformed into an hypergeometric equation of the form $x(1-x)y'' + (c - (a + b + 1)x)y' -aby = 0$?
I know that we can do the transform is the term before y'' a polynomial of degree 2, the term before y' of degree 1 and before y is a constant.  Another condition is that the polynomial term of degree two has two distincts roots.  Nothing is said about complex numbers, so I'm not sure.  $ 1 + x^2 $ has two complex roots.  Can I actually transform the equation into an hypergeometric equation?
Thank you.
Answer: First, introduce $\xi = -i x$, and write $y(x) = \eta(\xi)$, then the quadratic in front of the second derivative has two real roots in $\xi$; the ODE changes to
\begin{equation}
 (1-\xi^2)\eta'' +4 \xi \eta' -6 \eta = 0.
\end{equation}
Then, you just have to rescale $\xi$ such that the parabola in front of the second derivative has roots at $0$ and $1$ instead of at $\pm 1$; you can do this by introducing $z = \frac{1+\xi}{2}$, and writing $\eta(\xi) = F(z)$. Then, the ODE transforms to
\begin{equation}
 z(1-z) F'' + (4 z-2) F' -6 F = 0. \tag{1}
\end{equation}
Note that $(1)$ can be solved in terms of elementary functions, yielding
\begin{equation}
 F(z) = c_1 (1-z)^3 + c_2 \left(\frac{1}{3}-z(1-z)\right).
\end{equation}
Answer: Try let $y=px^2+qx+r$ ,
Then $y'=2px+q$
$y''=2p$
$\therefore(1+x^2)2p-4x(2px+q)+6(px^2+qx+r)\equiv0$
$2qx+2p+6r\equiv0$
$\therefore\begin{cases}2q=0\\2p+6r=0\end{cases}$
$\begin{cases}q=0\\p=-3r\end{cases}$
$\therefore$ The ODE has one group of linear independent solution $y=C_1(3x^2-1)$
Try let $y=sx^3+tx^2+ux+v$ ,
Then $y'=3sx^2+2tx+u$
$y''=6sx+2t$
$\therefore(1+x^2)(6sx+2t)-4x(3sx^2+2tx+u)+6(sx^3+tx^2+ux+v)\equiv0$
$6sx+2t+6sx^3+2tx^2-12sx^3-8tx^2-4ux+6sx^3+6tx^2+6ux+6v\equiv0$
$(6s+2u)x+2t+6v\equiv0$
$\therefore\begin{cases}6s+2u=0\\2t+6v=0\end{cases}$
$\begin{cases}u=-3s\\t=-3v\end{cases}$
$\therefore$ The ODE has another group of linear independent solution $y=C_2(x^3-3x)$
$\therefore$ The general solution is $y=C_1(3x^2-1)+C_2(x^3-3x)$


What does this example of using boost::mismatch mean?

Question: I try to understand the following example given here:
template<class SinglePassRange1, class SinglePassRange2>
std::pair <
    typename range_iterator<SinglePassRange1>::type,
    typename range_iterator<const SinglePassRange2>::type
>
mismatch(SinglePassRange1& rng1, const SinglePassRange2& rng2);

And here is the description:

mismatch finds the first position where the correseponding elements
  from the two ranges rng1 and rng2 are not equal.

The main thing that is not clear to me in the above example is: What is given as an input and what is an output of the mismatch function?
rng1 and rng2 are object of classes SinglePassRange1 and SinglePassRange2, respectively. But what are these classes? Where are they defined? They are supposed to be "ranges" but what are "ranges"?
It is also not clear to me what all these lines before the calling of the mismatch function do. The first line looks like we are going to define a class template, but we do not do it later.
Answer: A range is a pair of iterators operating on the same container. A SinglePassRange  is such a range where iterators are single pass iterators, ie. iterators which are comparable and incrementable. By overloading of the mismatch function, the parameters may also be containers supporting that type of range iterators, in which case the begin() and end() iterators of the container are used.
The returned value is the first pair of iterators - one of each range - which don't satisfy the equality predicate. That pair is what the first couple of lines decribes after the template parameter declaration.
std::pair <
    typename range_iterator<SinglePassRange1>::type,
    typename range_iterator<const SinglePassRange2>::type
>

As you can see, each argument is the type of the range iterator of each range type.
The keyword typename before arguments is necessary, because both are actually dependent names, ie. types that are defined within other types, which are themselves dependent on the outer template parameters (SinglePassRange1 and 2).
The mismatch function is probably similar to the following (types elided):
 auto mismatch(auto &rng1, auto &rng2){
     auto it1 = rng1.first, it2 = rng2.first;
     while (it1 != rng1.second && it2 != rng2.second)
          if (it1 != it2)
              break;
          else { ++it1; ++it2; }
     return make_pair(it1, it2);
 }

Answer:
It is also not clear to me what all these lines before the calling of
  the mismatch function do. The first line looks like we are going to
  define a class template, but we do not do it later.

This is not an example. It is a declaration of a function template, which is part of the boost range library.

The main thing that is not clear to me in the above example is: What
  is given as an input and what is an output of the mismatch function?

As documented further below on the page you link, the input must have a type that is a model of the Single Pass Range concept.
More information on boost ranges ist available at http://www.boost.org/doc/libs/1_50_0_beta1/libs/range/doc/html/range/introduction.html
As mentioned there, the most common use is to pass in standard containers. Built-in arrays  also work. And boost::iterator_range allows you to use any pair of (forward) iterators that form a range.
So you could have
vector<string> vec { ... };
list<string> lis { ... };

auto result = mismatch(vec, lis);

Here result will have type pair<boost::range_iterator<vector<string>>::type, boost::range_iterator<list<string>>::type>


printing $GLOBALS private static property not showing

Question: I am practicing the singleton pattern using several examples. My code so far:
class LimitedEditionBuggati {
    private $props = array(
                            'speed'     => 256,
                            'cylinders' => 18,
                            'color'     => 'metalic silver',
                            'hp'        => 1200,
                            'price'     => 5000000,
                            'vin'       => 'the one'
                           );
    private static $instance;

    private function __construct(){}

    public static function instance() {
        if( empty($instance) ) {
            return new LimitedEditionBuggati();
        }
        return self::$instance;
    }

    public function getProperty( $property ) {
        return $this->props[$property];
    }
}

$myCar = LimitedEditionBuggati::instance();

How come the private static $instance does not get printed using print_r( $GLOBALS )?
Comment: Why would it be printed again?
Comment: Google: Why not to use singletons in php (use Dependency Injection). Why not to use statics (global state, hard coupling, poor code re-use). This will eventually lead you to write your code with: no new calls, no statics and no singletons.
Answer:
How come the private static $instance does not get printed using print_r( $GLOBALS )?

Even though static class variables are variables that exist once and only once - as it is similar with global variables - they are not globally visible through $GLOBALS because they are not global variables in PHP.
You can compare that with static variables inside a function (perhaps a better known concept for you):
function my_function()
{
    static $variable = 1;
}

my_function();
print_r($GLOBALS);

Even though the static variable $variable exists once and only once - similar to a global variable, it is just, that it is not visible in $GLOBALS.


kubernetes duplicate pod ip addresses - are pod ips supposed to be unique cluster wide?

Question: I read this in the doc:

Every Pod gets its own IP address ... pods on a node can communicate with all pods on all nodes without NAT.

Should I read that as "every pod gets its own unique cluster wide IP address"?
I assumed this was the case, but reason I ask is I noticed pods with the same IP addresses just on different nodes just after I initialized a new cluster following the instructions here. The cluster has 3 nodes test-vm{4,5,6}, with test-vm4 as master, running on a local dummy network 10.1.4.0/16. I used flannel for the CNI and set it up like this:
kubectl patch node test-vm{4..6} -p '{ "spec": { "podCIDR": "10.244.0.0/16" } }' # Had to do this because didn't set it on cluster init. See https://stackoverflow.com/a/60944959/2038383.
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

Notice 3 IPs occur twice for 2 different pods - 10.244.0.{2,3,4}:
$ kubectl get pods --all-namespaces -o wide -w
NAMESPACE     NAME                               READY   STATUS    RESTARTS   AGE     IP           NODE       NOMINATED NODE   READINESS GATES
default       curl                               1/1     Running   0          14m     10.244.0.4   test-vm6   <none>           <none>
default       my-nginx-cf54cdbf7-d6s9m           1/1     Running   0          17m     10.244.0.3   test-vm6   <none>           <none>
default       my-nginx-cf54cdbf7-twrvw           1/1     Running   0          17m     10.244.0.2   test-vm6   <none>           <none>
default       my-nginx-cf54cdbf7-xpff6           1/1     Running   0          17m     10.244.0.4   test-vm5   <none>           <none>
default       my-nginx-more-5f79688b9d-4c9jk     1/1     Running   0          3m10s   10.244.0.6   test-vm5   <none>           <none>
default       my-nginx-more-5f79688b9d-7htsn     1/1     Running   0          3m18s   10.244.0.5   test-vm5   <none>           <none>
default       my-nginx-more-5f79688b9d-gqz9b     1/1     Running   0          3m4s    10.244.0.7   test-vm5   <none>           <none>
default       nginx1                             1/1     Running   0          9s      10.244.0.8   test-vm5   <none>           <none>
kube-system   coredns-64897985d-kt82d            1/1     Running   0          41m     10.244.0.2   test-vm5   <none>           <none>
kube-system   coredns-64897985d-rd7gz            1/1     Running   0          41m     10.244.0.3   test-vm5   <none>           <none>
kube-system   etcd-test-vm4                      1/1     Running   0          41m     10.1.4.36    test-vm4   <none>           <none>
kube-system   kube-apiserver-test-vm4            1/1     Running   0          41m     10.1.4.36    test-vm4   <none>           <none>
kube-system   kube-controller-manager-test-vm4   1/1     Running   0          41m     10.1.4.36    test-vm4   <none>           <none>
kube-system   kube-flannel-ds-snkhk              1/1     Running   0          29m     10.1.4.38    test-vm6   <none>           <none>
kube-system   kube-flannel-ds-wtmqg              1/1     Running   0          29m     10.1.4.37    test-vm5   <none>           <none>
kube-system   kube-flannel-ds-x46xw              1/1     Running   0          29m     10.1.4.36    test-vm4   <none>           <none>
kube-system   kube-proxy-mjl69                   1/1     Running   0          41m     10.1.4.37    test-vm5   <none>           <none>
kube-system   kube-proxy-vz2p2                   1/1     Running   0          41m     10.1.4.36    test-vm4   <none>           <none>
kube-system   kube-proxy-xg4gg                   1/1     Running   0          41m     10.1.4.38    test-vm6   <none>           <none>
kube-system   kube-scheduler-test-vm4            1/1     Running   0          41m     10.1.4.36    test-vm4   <none>           <none>

Despite what the docs say, all pods can't communicate with each other. They can only communicate with pods on the same node and it's causing errors. Wondering whether this is a red flag that something is wrong or not, and looking for clarification on this one point about pod IP address uniqueness.
Comment: I believe those are the Node's IP, which would happen with `hostNetwork: true`; can you confirm that?
Comment: The nodes LAN network is 10.1.4.0/24. The other network range that the pods are in is 10.244.0.0/16 and is created by flannel and is related to some other virtual device or iptables routing rule or some crap I don't yet understand. `kubectl get node test-vm4 -o json | jq .spec.podCIDR` gives `10.244.0.0/16"`. There is mention of  "hostNetwork: true" in the `kube-flannel.yml` file I used to install flannel CNI. Not sure what this means yet.
Comment: @mdaniel oh now I understand better: The flanneld DaemonSet is using host networking (as it should) but the pod networking is vxlan on 10.244.0.0/16. So no, pod IP is not host networking. It's the default vxlan.
Answer: I figured it out. Firstly, yes pods are absolutely supposed to have a cluster wide unique IP address. It's fundamental to the way k8s works. The linked k8s doc is crap, and leaves the question a little open. Better worded sources:

Platforms like Kubernetes assume that each container (pod) has a unique, routable IP inside the cluster. The advantage of this model is that it removes the port mapping complexities that come from sharing a single host IP. -- https://github.com/flannel-io/flannel#networking-details

One of the core requirements of the Kubernetes networking model is that every pod should get its own IP address and that every pod in the cluster should be able to talk to it using this IP address. -- https://ronaknathani.com/blog/2020/08/how-a-kubernetes-pod-gets-an-ip-address/

Now the question is, why are my pods being assigned same IP addresses? Basically doing this is at flannel CNI init is wrong ( I copied this suggestion from this SO answer):
kubectl patch node test-vm{4..6} -p '{ "spec": { "podCIDR": "10.244.0.0/16" } }' # Had to do this because didn't set it on cluster init.

The podCIDR has to be unique for each node. This is how k8s ensures each scheduled pod has a unique IP address - each node assigns some IP in it's podCIDR. See this great blog post explaining it. The above is not equivalent to setting --pod-network-cidr on kubeadm init like you are supposed to. The --pod-network-cidr command line option actually corresponds to ClusterConfiguration networking.podSubnet. So if you need to set it after the fact you remove flannel then edit the cluster configuration (haven't actually tested this approach, I just re-initd with --pod-network-cidr set):
kubectl delete -f kube-flannel.yml
kubectl edit cm -n kube-system kubeadm-config # and add setting.

Once set:

the control plane will automatically allocate CIDRs for every node. -- https://kubernetes.io/docs/reference/setup-tools/kubeadm/kubeadm-init/.

If you going to set each node's podCIDR setting it must be unique for each node. You should avoid setting it manually if nodes are expected to be coming and going dynamically - which is the normal scenario.

UPDATE: The above method of setting the ClusterConfiguration networking.podSubnet after init does not actually work. It doesn't even work if you de-register and re-register all workers nodes which is annoying. AFAIK the only way to get automatic node podCIDR setting to work is to blow away your cluster and re-initialize with --pod-network-cidr set or networking.podSubnet set in the initial config (see --config option).


Accessing the argument which was passed to the callback function

Question: I have a simple class which implements the AsyncTask:
class Async( private val workload: () -> String,
             private val callback: ( httpResponse : String ) -> Unit
) : AsyncTask<String, String, String>()
{
    override fun doInBackground( vararg params: String? ): String?
    {
        return workload()
    }

    override fun onPostExecute( result: String )
    {
        callback( result ) // <-- argument being passed to the callback
        super.onPostExecute( result )
    }
}

I pass two arguments to this class, which are:
string workload() - function which takes long time to execute and returns a string
callback( string ) - the callback function to which I want to pass the value, which was returned by the workload()

Everything works fine, except that I can't seem to be able to find a way how to access the argument within the callback function:
Async(
    {
        workload()
    },
    {
        // how to "receive" the "test" string returned by the workload()?
        Log.d( "myapp", ???_argumentPassedToCallback_??? );
    }
).execute( "" )

fun workload() : String
{
    Thread.sleep( 1000 )
    return "test";
}

Any suggestions please? Thank you!
Comment: You may want to read https://kotlinlang.org/docs/reference/lambdas.html if you haven't yet.
Answer: Async(
    {
        workload()
    },
    { response ->
      Log.d("foo", "The response is: $response")
    }
).execute( "" )


Regex for int Array

Question: I need to validate a string argument if it can be converted to an int Array.
String pattern = "(\\d+[,])+";
String test = "18,32,5,8,10";

test2.matches(pattern2) //returns false as i requires , in the end

Is there any way to ignore last ' , '
Answer: Use a group construct to specify that digits should be followed by (, digits) ...
\\d+(?:,\\d+)+

Comment: Yes. Now that I think about it, `\\d+(?:,\\d+)+` is indeed the right choice
Comment: Hi @hwnd , this is failing for single value  like test = "18"
Comment: Change `+` to `*` ... `(?:,\\d+)*`
Answer: Regex for both array and single element
(\d|\[(\d|,\s*)*])
Answer: This regex will work for you (checks for a "valid array") :
public static void main(String[] args) {
    String s = "18,32,5,8,10";
    System.out.println(s.matches("(?!.*,$)(?!,.*$)(\\d+(?:,|$))+"));
}

Checks and fails for:

multiple continuous commas
comma at beginning
comma at end
Answer: You can try
Pattern = "^\d+(,\d+)*$"

text = "10,5,10"    (TRUE)
text = "10,5,10,"   (FALSE)
text = "10,5,10 "   (FALSE)

Answer: Since I don't know how to use regex and if I were in your place then this would have been my way to do so
String test = "18,32,5,8,10";
String str[]=test.split(",");
int ar[] = new int[str.length];
for(int i = 0; i<ar.length; i++){
    ar[i] = Integer.parseInt(str[i]);
}

The problem in this code if any I can see is this that call to parseInt() method must be wrapped in try-catch as it can throw NumberFormatException if your string contains value other than digit and comma(,).

Regex for int Array


bring the Ylabels close to each other

Question: I've done a chart i my Android app with Achartengine. In my graph there are three ylabels  called for example: "A", "B", "C". When i show my graph, these ylabels go one in the center of the yaxis, one on the top and one on the bottom. I would have these ylabels more close and not in the bottom or top of the graph.
For example i used this to set the ylabels on the right side of my yaxis:
<code>mrenderer.setYLabelsAlign(Align.LEFT,0);
</code>
But how can i solve this problem?
Answer: you can try customizing the graph like this by setting.
mRenderer.setYLabelsAlign(Align.RIGHT, 0);
mRenderer.setYLabelsPadding(10);

bring the Ylabels close to each other