Create a complete binary tree and do level order traversal on it

using namespace std;

using namespace std;

Why is “using namespace std;” considered bad practice?

The particular problem I have with it here is that it obscures that you are using std::queue and not some custom class.

Note that this can also cause problems if you later convert it to header file, which would be natural for a general use data structure.

Don't go the long way around

Node *createNode(int data){
    Node *node=new Node;
    node->left=NULL;
    node->right=NULL;
    node->data=data;
    return node;
}

Rather than create a function for this, consider just creating a constructor for struct Node.

Node::Node(int datum) {
    this->datum = datum;
    left = NULL;
    right = NULL;
}

Note that datum is the singular form of data, so I changed the field in Node to datum as it only holds one piece.

        buildTree(createNode(i),q);

could become

        buildTree(new Node(i), q);

This calls a constructor directly rather than creating a function just to call the default constructor and set the data.

Why wait?

    if(f->left && f->right) {q.pop();f=q.front();}
    if(!f->left) f->left=newNode;
    else if(!f->right) f->right=newNode;

This could be

    if (f->left) {
        f->right = newNode;
        q.pop();
    } else {
        f->left = newNode;
    }

This works because you know that something is only in the queue until both its children are added.  Then it is removed.  So you don't need to check for the both children full case if you only ever add to the tree with this method.

I changed the order because I find it easier to read positive conditions with else blocks.  An else is essentially the negation of the if.  This way we aren't negating a negative.

What if something else adds to the tree?  That would be problematic.  Of course, that was already true.  Something else adding to the tree would interfere with the order that you use the queue to enforce.

Removals are also problematic with either implementation.

This is why Node would normally be a hidden data type, not exposed to callers.  Then you could be sure that only your tree class would be able to access it.

Don't make data structures that you don't use

    queue<Node*>q;
    if(root){

If you do this in the other order, you can save the overhead of creating the std::queue.

    if (root) {
        queue<Node*> q;

or even

    if (!root) {
        return;
    }

    queue<Node*> q;

Which also reduces the indent.

Efficiency

The biggest problem with efficiency that I see is that this doesn't seem to be a tree in any meaningful sense.  Sure, the data structure behind it is a tree, but the operations aren't.  You buildTree in insertion order.  Then you levelOrder to read back the tree in insertion order.  If you only wanted to do that, then a std::vector would be a much more efficient data structure.  You wouldn't need the std::queue to manage the insertions nor reading them back.

    Node *root=createNode(10);
    queue<Node *>q;
    q.push(root);
    for(int i=0;i<10;i++){
        buildTree(createNode(i),q);
    }
    levelOrder(root);

would become

    std::vector<int> data;
    data.push_back(10);
    for (int i = 0; i < 10; i++) {
        data.push_back(i);
    }

    for (auto datum : data) {
        std::cout << datum << " ";
    }

Isn't that simpler?  No new functions required.  Also, rather than using a pointer-based data structure and a queue, this just uses one array-based data structure.  You could also use a std::queue instead of a std::vector.

Encapsulation

This is also encapsulated better.  Instead of having to create a tree structure and a queue in order to call buildTree, this simply calls push_back and lets std::vector handle the details internally.  Consider the following interface

class InsertionOrderTree {
    struct Node {
        int datum;
        Node *left;
        Node *right;
    };

    Node *root;
    std::queue<int> q;

    public:
    InsertionOrderTree();
    build(int datum);
    traverse();
};

InsertionOrderTree::InsertionOrderTree() {
    root = NULL;
}

This hides the implementation detail of using a queue from any callers.  Callers shouldn't have to know how you do things, just what you promise to do.  They certainly should not have to create a specific data structure just to help you do whatever it is that you are doing.  You should create your own data structures if you need them.

Note that the implementations of build and traverse would change from your original versions.  In particular, build needs to handle a NULL root.

Unsolicited advice

This is a bad use case for a tree though.  You should probably either find a different use case that better fits a tree (if you just want to implement a tree) or use a different data structure (if this is really the problem that you need to solve).


You have the tightest coupling of interfaces I have seen in my life. You are also restricting them in abnormal manners. For example, IDrawer should not need to know about the IAnimalModel. Instead, it should be worried about IDrawableModel, which IAnimalModel can worry about. This way, the coupling is reduced and things are coupled with appropriate interfaces/classes. You want to reduce your coupling to only couple around what needs to depend on what else. Things that are generic like IDrawer shouldn't have to worry about more specific things. They should be, well, for the buzzword: generic.

Think about it as "what happens if I need something else to draw?" If you have another class/interface that has to draw something, and you need to modify IDrawer to count that in, then something is fishy.

You could test this better by developing around Test-Driven Development. You have interfaces for a reason, they are also very good at TDD. It's easy to mock things with them. (So that you can verify that whatever the thing is works. Especially with generics.)

Please do us all a favour and format your code more appropriately. C# does not use Egyptian braces (at least, not by any best-practices). (Java and JAVA do, but this is neither Java nor JAVA.)

namespace GenericInterface
{
    public interface IDrawer
    {
    }

    public interface IDrawer<TModel> : IDrawer
      where TModel : IAnimalModel<TModel>
    {
        void Draw(TModel model);
    }


First, it's not recommended to extend native objects. That's because modifying the prototype applies to all instances. Now let's say the spec added a newMap method that acted differently from your implementation. Code that uses newMap according to spec (like third party code) will break because your code overrides the native implementation and operates in a totally different way.

That's one reason why libraries like lodash and underscore don't extend native objects, and just accept the array/object as an argument. They also provide "wrapping" mechanisms, accepting an array and wrapping it in a container object with its own prototype methods. That way, they safely add methods without modifying native objects while keeping it looking like they extend.

// In lodash, the _ function wraps the array in a "lodash object" which
// has methods like map etc.
var newValues = _([1,2,3]).map(v => v * 3).value(); // [3,6,9]

// In jQuery, the $ function wraps the element in a "jQuery object" which
// has its own DOM manipulation methods.
$(document.getElementById('myElement')).remove();

Now let's say you didn't extend it via native objects.

newFilterMulti isn't really a true multi-dimensional array filter. It only appears to go 2 levels deep (2D). Either you make it a true multi-dimensional filter (going as deep as it can) or rename it so it's more apparent that it only goes 2 levels deep.

newReduce doesn't act the same way native reduce works (and this is a good example of spec-breaking implementation). reduce doesn't add return values. It carries over the last result to the next call regardless of type. This means the callback accepts 2 values, the carry and the current value. Also, most reduce implementations accept an initial argument for the carry value. If omited, reduce starts at the second element in the array, with the first element as carry.

Again, newReduceMulti isn't a true multi-dimensional reduce, just 2D. Re-implement or rename accordingly.

Now one technique used by most libraries is to reuse the operations that have already been defined. In the case of jQuery, internally it makes heavy use of its $.each. So if they need anything looped through, instead of tediously writing for loops everywhere, they use their $.each. Also, I heard FP operations rely heavily on map.

So if you could make a solid forEach and map implementation, you can readily reuse them in your other methods instead of writing a for loop every time.


Sequence-based enumeration of permutations with Heap's algorithm

I've been able to slash the execution time by almost half on my machine by declaring current and c as ContiguousArray:

struct HeapPermutationSequence<Element>: Sequence, IteratorProtocol {

    private var current: ContiguousArray<Element>
    private var c: ContiguousArray<Int>
    private var i = 0
    private var firstIteration = true

    init(elements: [Element]) {
        self.current = ContiguousArray(elements)
        self.c = ContiguousArray<Int>(repeating: 0, count: elements.count)
    }

    mutating func next() -> ContiguousArray<Element>? {
        ...
    }
}

Benchmarks

Using the same benchmarking code, compiled with -O in the terminal, on a  2.7 GHz i7 MacBook Pro :

Before: fluctuates between 0.126s and 0.139s
After:  0.07s with inferior fluctuations, thanks to current being a ContiguousArray, since such a type has predictable performance.

I've got to 0.022s by wrapping the benchmarking code in a do statement or any new scope (Makes the code 3x faster):

do {
    let N = 10
    var count = 0
    let start = mach_absolute_time()
    for _ in HeapPermutationSequence(elements: Array(1...N)) { count += 1 }
    let end = mach_absolute_time()
    print(count, Double(end - start)/Double(1e9))
}

 Putting the original code inside a single iteration for loop for _ in 0..<1 {...} brings its execution time down to 0.020 too. Putting it inside a do statement, repeat while false, closure, while true { ... break}..., takes it back to 0.13s .

N.B: The above result has only been observed on a mac (4 physical cores, 4 logical ones). On an iPhone and an iPad (both 2 physical cores), using a ContiguousArray makes the code a full second faster (2.~s vs 3.~s).

We can gain 1 to 2ms by rearranging the conditions:

private var notFirstIteration: Bool = false
//...
if notFirstIteration {
//...
} else {
    notFirstIteration = true
}

This would eliminate The (N! - 1) unnecessary conditional jumps in the assembly code.

As suggested by Mr. Martin: Not discarding manually the output of HeapPermutationSequence by using this code:

for x in HeapPermutationSequence(elements: Array(1...N)) {
    count += x.count
}

Gives a +/-2ms fluctuation in both solutions.


Single Linked List Implementation in Ruby

Firstly, your code's broken. If you instantiate a list with no initial value, and then append to it, it creates two nodes:

list = LinkedList.new
list.append("foo")
list.size #=> "List size: 2"

Secondly, implement an #each method to iterate through values and include Enumerable. That'll give a ton of methods for free: #find, #count, #to_a, and many others. Something like this should do:

def each
  node = @head
  until node.nil?
    yield node.value
    node = node.next_node
  end
end

Thirdly, return useful values. #size should not return a string. Neither should #head, #node_at_index, or #find. #size should return an int, and the others should return nil. Never ever return easy-to-print strings unless that's explicitly called for. Currently, you can get puzzling stuff like this:

some_list.head #=> "Empty list" (the head's value is the string "Empty list")
some_list.size #=> "List size: 2" (so, no, not empty)

And you can get useless stuff like this:

if some_array.size < some_list.size # ArgumentError: comparison of Fixnum with String failed
  ...

I trust you see the problem here.

Speaking of return values, you seem to have taken some care that your methods don't return a raw Node instance (which is smart, since nodes are internal/private to the linked-list)... but you made @head accessible from anywhere with attr_accessor. So some_list.head = "foo" is perfectly legal, and will break things. Also, #append and #prepend implicitly return Node instances.

Fourth, you might want to keep track of the tail as well as the head. Many of your methods rely on finding the tail one way of another, so why not keep it around? Or at least use your own #tail method for these cases, rather than do it differently each time.

Other stuff:

Check the indices passed to #insert_at and #remove_at and raise an appropriate error if the index is out-of-bounds. Otherwise you'll just get a NoMethodError which doesn't explain much.
Don't put assignments into ternary branches; use the branch to determine the value to assign. I.e. this

element.nil? ? @head = nil : @head = Node.new(element)

should be

@head = element.nil? ? nil : Node.new(element)

of course, in this particular case, @head will be nil by default, do you could just as well do:

@head = Node.new(element) unless element.nil?

Your #to_s would be a lot cleaner if you collected all the values in an array, used map to add parentheses, and join to add the "->" arrows. If you include Enumerable as described above, your #to_s could just be:

def to_s
  values = map { |value| "(#{value})" }
  values << "nil"
  values.join(" -> ")
end


The comment about the globals is noisy, but at least you're aware that they're bad.  You can reduce the possibility of bugs by removing them, which is always good idea.  Otherwise, it could suggest that this implementation needs reworking, especially if you do encounter some bugs.

Side-note: size is technically a constant, not a global.  It's okay to have constants in global scope as they cannot be modified elsewhere.
I would recommend replacing the C-arrays with a storage container such as std::vector or std::array (if you have C++11).  In C++, it's not good to pass C-arrays to functions because they decay to pointers instead of passing the array itself.  Storage containers, on the other hand, do not do this; they pass an object.  That said, your implementation looks very C-like, although that's not relevant to the sorting.  It's still worth knowing about storage containers in C++.

You will also be able to invoke operator= in one line to reassign the master array to the temp array instead of using a manual loop.  These little things will help make your code cleaner.
For bruteCount():

Why are i and j declared outside the loop statement?  It's done differently elsewhere, so it should be done here as well.
The loops and the if statement should have curly braces, even if the body of a statement is just one line (also more a general recommendation).  Not having them this way could hurt maintenance, in case you ever need to add or remove something.


Quicksort in JavaScript using destructuring and spread syntax

Interesting question;

your quicksort is far slower than the regular sort, and is harder to read.
You can find details here: https://jsperf.com/codereview-js-quicksort/15

But in essence this implementation is 90% slower than a regular sort. Using CPU profiling I can tell that most of the time is spent in _.partition which makes sense. Plus you keep creating functions like arr => quicksort(arr, compareFn) in every call of quicksort which adds up. Finally, that name should really be quickSort; JavaScript functions follow the lowerCamelCase convention.

My counter proposal would simply be:

console.log(
  Array.from('the quick brown fox jumps over the lazy dog').sort(
    (a, b) => a.charCodeAt(0) - b.charCodeAt(0)
  ).join('')
);

Historically, I have never heard of folks beating the native sort.


DRY

Apply the DRY (Do not Repeat Yourself) method. For instance, the check to remove the file. Since it's being called in two places, we can make this a function. I've re-written your code in a more functional style. This is also easier to read what's occurring.

else

Your else: None statements are not doing anything.

continue

Same goes for this in the while loop. This happens anyway.

if

When you check the user's answer, just assume it's going to be varying. Instead of checking for an UPPERCASE 'y' and lowercase, just lower it. Also stripping it to make sure to remove erroneous spaces.

answer = input("Do you want to repeat? (Y/N) ").strip().lower()
if answer in ['yes', 'y']:
# instead of
answer = input("Do you want to repeat? (Y/N): ")
if answer == "y" or answer == "Y":

Exceptions

Since you're interacting with the user from the interpreter, you can catch if the user exits the program and run any cleanup code before cleanly exiting. I've wrapped the loop of the interaction in a try/except statement so that this can be caught.

if name == 'main':

Check this SO post out.

Rewritten

import webbrowser
import os
import time
import getpass
from gtts import gTTS
from mutagen.mp3 import MP3

my_file = "C:/Users/%USERNAME%/Desktop/TTS/bob.mp3" #Sets a variable for the file path.

username = getpass.getuser() #Gets the username of the current user.

def remove_file():
    """Checks if myfile exists and if so, deletes."""
    if os.path.isfile(my_file):
        os.remove(my_file)

def play_tts():
    webbrowser.open(my_file)  # Opens the .mp3 file
    audio = MP3(my_file)  # Sets a variable so that the Mutagen module knows what file it's working with.
    audio_length = audio.info.length  # Sets a variable of the length of the .mp3 file.
    time.sleep(audio_length + 0.25)  # Waits until the file has finished playing.
    os.system('TASKKILL /F /IM wmplayer.exe')  # Closes Windows Media Player.
    time.sleep(0.5)  # Waits until Windows Media Player has closed.

def ask_and_play():
    # Takes the user's input and uses it for the Text-To-Speech
    tts = gTTS(text=input(
        "Hello there " + username + ". This program isn\n"
        "used to output the user's input as speech.\n"
        "Please input something for the program to say: ")
    )
    tts.save('bob.mp3')  # Saves a .mp3 file of the user's input as speech.
    play_tts()

def check_continue():
    """Checks if the user wants to continue.
    Returns a boolean value."""
    while True:
        answer = input("Do you want to repeat? (Y/N) ").strip().lower()
        if answer in ['yes', 'y']:
            return True
        elif answer in ['no', 'n']:
            return False
        else:
            print("Sorry, I didn't understand that. Please try again with either Y or N.")

def repeat():
    """Repeatedly ask the user to type text to play,
    and check if the user wants to repeat or exit."""
    while True:
        remove_file()
        ask_and_play()
        if not check_continue():
            raise KeyboardInterrupt

if __name__ == '__main__':
    try:
        repeat() #Calls the function.
    except KeyboardInterrupt:
        # clean up
        remove_file()
        print('Goodbye!')


Determine if someone has won a game of Tic-Tac-Toe on a board of any size

You should not use namespace std. It is bad practice, that will hurt you in the long run.
I do not really like your constructor:

TicTacToe(int sz) : N(sz) {
   board.resize(N);
   winArr.resize(2*N+2, 0);
   for(int i = 0; i < N; i++)
      board[i].resize(N, '.');
}

The argument should be const. Then you should use the initializer list for all variables:

TicTacToe(const int sz)
    : board(sz, std::vector<char>(sz, '.')), winArr(2*sz+2), N(sz) {}

In your updateWinArr() function you only check the diagonal in one direction:

// check diagonals :
if(nRow == nCol) // left diagonal
    winArr[2*N] += nVal;
else if(nRow+nCol == N-1) // right diagonal
    winArr[2*N+1] += nVal;

However, there are 4 attached diagonal points you should check.
You logic is flawed. An X negates all previous 'O's. However, in your code you simply decrement:

int nVal = (player == 'X' ? 1 : -1);
winArr[nRow] += nVal;
winArr[N + nCol] += nVal;

This will make the following sequence a win, although it is not valid:

Sequence: X X O X X
Values  : 1 2 1 2 3

I think it would be better to create a simple struct, that holds the relevant information:

X or O
left diagonal value
right diagonal value
horizontal value
vertical value

Now you can calculate the appropriate values by first checking, whether the mark is the right one and then add the horizontal value of the left/right neighbor and so on.


HTTP request for a single URL or list of URLs based on arguments provided

__call__ really confuses me. Type checking is the way to go for readability. On top of that, if you need to accept new types later, all you need to do is add an if statement.

In my opinion, if you absolutely want the brevity of __call__, accepting multiple types of arguments is fine, and so is returning multiple types (as is the case with many builtin and standard library functions). It is important that you mention this in the documentation, though.

Some other questionable things:

Instead of comparing type directly, you can use isinstance:

if isinstance(url_or_list_of, str):
    ...

url_or_list_of is a somewhat unfriendly name for a public API. How about url_or_list_of_urls?
It's good that you provide a 'clean exit' method. __del__ isn't the right method to override, however, since the implementation is CPython-specific, and it may never actually be called. Instead, try defining __enter__ and __exit__:

class AioRequest:
    ...
    def __enter__(self):
        return self
        # This should be all in most cases,
        # unless you want to do something with `self` before returning
    ...
    def __exit__(self, exc_type, exc_value, exc_traceback):
        self._session.close()

You can then use with:

  with AioRequest() as request:
      # __enter__ called
      response = request( ... )
  # __exit__ called


Remove the callback, and call that code at the level where it's used best.

I.e.:

When you create a batch of records:

#find and cache user
user = UserSession.find.user
# create your 100 records however you want... this is a dumb example
100.times { Post.create!(user: user) }

When you're in a controller, you want to do the same thing, except you're just creating one post.

user = UserSession.find.user
Post.create!(user:user, some:other, params:go_here)

Now that I've written it, it appears if you wanted to DRY up this example, you could wrap it in some class like this:

class CreatesPosts
  def self.create(num_records = 1, user = UserSession.find.user)
    num_records.times { Post.create!(user:user) }
    # might need to tweak to vary up the Post attributes
  end
end


Function to parse an XML and find specific regex considering the size attribute of the document

Mixed languages

Regardless of one's opinion on whether English is the lingua franca of programming, mixing languages is a bad idea. This would be better in all-Italian (where possible; libraries are still in English) or all-English than a mixture.

Type hints

Use them; for instance

def get_xml_by_tag_names(xml_path: str, tag_name_1: str, tag_name_2: str) -> dict:

Unused variable

Here:

l = []

Items iteration

for k in dizionario:
    for v in dizionario[k]:

should be

for k, values in dizionario.items():
    for v in values:

Magic numbers

Move this:

"7.489"

to a named constant variable somewhere.

Multiple replacement

This:

    for to_remove in (" < ", " >", ".", ",", ";", "-", "!", ":", "’", "?", "<>"):

would be easier as a single regular expression and a single call to sub.

Intermediate list

values = [x for x in dict_fasi.values()]
myxml_fasi = ' '.join(values)

can just be

myxml_fasi = ' '.join(dict_fasi.values())


Which swift screen handler approach is better for instantiating a utility class and then presenting a viewController?

The only difference between the first and the second approach is whether
the handler is assigned to a variable or not. None of them is more
"functional" than the other. Therefore:

If you need a reference to the handler (perhaps to cancel the request)
then use the first approach.
If you don't need that reference, choose whatever you feel more
comfortable with, or what you find better readable.

Some more remarks:

The method name showWhatNewScreeen is (apart from the typo)
misleading. The method creates a view controller but does not
present it. Something like createWhatsNewController might be
more appropriate.
According to the API Design Guidelines, variable names should be lowerCamelCase, that is violated at
let WhatsNewVC = ....
The right-hand side of

whatsNewVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.985)

can be abbreviated to .black.withAlphaComponent(0.985), the
type UIColor is then inferred from the context.


1. Correctnes.

compareTo() method of the WinningSet class is not correct. As of now Integer.MAX_VALUE < System.currentTimeMillis(). Consider the following example:

    long time1 = System.currentTimeMillis();
    System.out.println(time1 > 3*Integer.MAX_VALUE);
    System.out.println(time1 - 3*Integer.MAX_VALUE);
    System.out.println((int)(time1 - 3*Integer.MAX_VALUE));

It could be the case that your events are generated around the same time and it will not result in any error but in general - e.g. in future, if you restore some serialized objects, it could lead to a possible problem. You can rewrite it int the following way:

        @Override
        public int compareTo(WinningSet another) {
            if (this.unixtime > another.getUnixtime()) return 1;
            if (this.unixtime < another.getUnixTime()) return -1;
            return 0;
        }

2. Performance

Copy of the 3 lists is indeed a bad thing. You can use set() method from ListIterator to traverse through the lists and replace values in place.

private void demap(ArrayList<WinningSet> list) {
            Iterator li = list.iterator();
            Iterator si = sets.iterator();
            Iterator di = dates.iterator();
            Iterator ui = unixtimes.iterator();
            //you can add iterators for other lists here.
            while (li.hasNext()) {// we assume number is the same
              WinningSet temp = li.next();
              si.next(); //need to advance to the right element;
              di.next(); //need to advance to the right element;
              ci.next(); //need to advance to the right element;
              si.set(temp.getSet());
              di.set(temp.getDate());
              ui.set(temp.getUnixTime());
            }
        }

3. Design

Are you sure that instead of a 3 lists you can't consider TreeMap<Long, SomeClass> where SomeClass is pair or Calendar and Object ? In this case you will always have the right order of items to work with - there is no need to sort lists on demand and do an extra work.


Find the Hardy–Ramanujan number using R5RS scheme

Your code looks mostly fine, I see a few very minor things to comment on:

There's no need to define cube and cube-root at the innermost scope,
Using define for internal functions makes it look a little clearer,
This is related to the second part of your question: you're using inexact->exact on a floating point number which can lead to large rationals (in the sense that you allocate a pair of two big integers) -- it would be better to avoid this,
Doing that still doesn't solve the extra test that you do -- but that's only because you're not certain if you have the right number of if you missed by 1.  Given that it should be close to an integer, you can just use round and then do one check, saving you one test.

Fixing the above, and doing it in one function that returns the number when it's found, and using some more "obvious" identifier names, I get this:

(define (hardy-ramanujan-number n)
  (define (cube n) (expt n 3))
  (define (cube-root n) (inexact->exact (round (expt n 1/3))))
  (let iter ([i 1] [count 0])
    (if (> (+ (cube i) 1) (/ n 2))
      (hardy-ramanujan-number (+ n 1))
      (let* ([i^3   (cube i)]
             [j^3   (cube (cube-root (- n i^3)))]
             [count (if (= n (+ i^3 j^3)) (+ count 1) count)])
        (if (= count 2) n (iter (+ i 1) count))))))

I'm running this on Racket, and it looks like it's about 10 times faster (50ms vs 5ms).


Wouldn't it be simpler to:

strip out any '$' and ',' characters;
convert to a real number;
multiply by 100;
take the integer part.

You can probably do that in one line (my Javascript is a bit rusty):

return Math.round(100 * parseFloat(dollarsAndCentsString.replace(/[$,]/g, '')));

Having said that, I think your f('1000') example is probably wrong: my intuition says I should interpret '1000' as dollars, not cents.


Determining if a palindrome exists in a linked list using recursion

Generally, when you end up with an expression like this, it is a sign that something is not right, and something needs rethinking or refactoring.

I don't see the point of node here - since you always write to node[0] -  and if you would eliminate it, that is, use it as the return value, your function would be a lot simpler:

def recurse(head, length):
    if length == 1:  # odd number of nodes
        return head.next
    elif length == 0:  # even number of nodes
        return head

    return recurse(head.next, length//2)

or, on one line

def recurse(head, length):
    return head if length==0 else head.next if length==1 else recurse(head.next, length//2)

BUT - 1//2 == 0, so both of these get a lot easier if you realize you have only one base case:

def recurse(head, length):
    if length == 0:
        return head

    return recurse(head.next, length//2)

or, on one line:

def recurse(head, length):
    return head if length==0 else recurse(head.next, length//2)

Of course, this might be better not to recurse:

def nonrecurse(head, length):
    while (length > 0):
        head = head.next
        length//=2

    return head


Using composition or inheritance to enhance this linked list

Considering that…

You have full access to the source code of the original SList class
To make inheritance work, you had to edit SList.java to change head and size from private to protected access
The assignment asks you to "modify the representation of SList"
The resulting class performs the same task as the original code, adding no new functionality (just a large performance optimization for insertEnd() with a negligible cost to insertFront())

I see no reason to use either inheritance or composition.  Just edit SList.java directly to modify its implementation.  The resulting SList class should be fully substitutable with the original, just with better performance characteristics.


There is no reason to use an external file and command. Python can sort strings just fine, unless the file is too big

something like this should work

def rearrange_ids(file):
    pattern = re.compile(r'id(\d+)')
    for line in file:
        spt = line.strip().split()
        if spt:
            ids = sorted(int(pattern.findall(id_string)[0]) for id_string in spt[0:2])
            yield ids, '\t'.join(['id%i' % i for i in ids] + spt[2:]) + '\n'

with open(input_file, 'r') as file, open(output_filename, 'w') as output_file:
    output_lines = sorted(rearrange_ids(file), key=lambda x: x[0])
    output_file.writelines(line for ids, line in output_lines)

id1   id2 ....
id1   id2 ....
id1   id3 ....
id3   id4 ....
id3   id4 ....

edit

I changed my original algorithm because id did not keep the original order when comparing, and sorted 10 before 2


A few observations:

You are adding spaces before most of your : throughout, which reads weird. I'd remove this as I've never seen any other Python code that does this
I would check out Pep8 as a way to clean up a variety of formatting things, as it is the more or less accepted Python formatting standard

This will show things like lacking spaces around operators, too many line breaks, etc

Also, I am not sure how you are using underscores here. Generally, underscores signify private members/methods in Python and it looks like you have quite a few places you could make your member variables private.

Also this could be a bit more clear:

self.train.loc[self.train[feat].value_counts()[self.train[feat]].values <  self.rare_threshold, feat] = "RARE"

You might consider some intermediate steps here to help with readability. Even something as simple as:

val = self.train[feat].value_counts()[self.train[feat]].values <  self.rare_threshold
self.train.loc[val, feat] = "RARE"

is more clear. Trying to read that many nested dictionary lookups is not simple.


A few notes:

for(Integer index : this.getBlockedParticles()){
    this.getParticles()[index].render();
}

This should be:

for( Particle particle : getBlockedLivingParticles() ) {
  particle.render();
}

By maintaining a list of living particles, you can eliminate a number unwarranted calls to render and eliminate the following check:

if(!this.isAlive()){
    return;
}

Assuming the width and height cannot change while rendering:

    GL11.glTexCoord2f(0, 0);
    GL11.glVertex2f(-PARTICLE_TEXTURE.getImageWidth()/2.0f,
            -PARTICLE_TEXTURE.getImageHeight()/2.0f);

As Marco commented, that duplicate code can be refactored:

    float width = PARTICLE_TEXTURE.getImageWidth() / 2.0f;
    float height = PARTICLE_TEXTURE.getImageHeight() / 2.0f;

    GL11.glTexCoord2f(0, 0);
    GL11.glVertex2f(-width, -height);

This will reduce the number of divisions (an expensive operation) from 8 to 2. You'll also note that there's a relationship between glTexCoord2f and the sign of the width/height passed to glVertex2f, which can be abstracted.

Architecturally, I'd be concerned that the Particle can only be rendered using the GL11 API. Use an Abstract Factory to decouple the rendering device from the application logic. This will also help determine the slower parts of the code (i.e., you could employ a dummy particle that has no rendering device to quickly and easily tune the other parts of the application).

One other trick to speed things up: if all calculations can be made with integer math, then instead of diving by 2, bit-shift by 1.


//gcc -Wextra -Wall -Werror -O3 -march=native -std=c99 -o test.exe gameOfLife.c

This should probably be put into some Makefile (well... the Makefile can be written more idiomatically, but I'm not the person to really ask about Makefiles...)

srand(time(0));

There may be better alternatives to this as a random number generator. This answer seems to suggest that Mersenne Twisters produce higher quality pseudo random numbers and that it is faster. However, informally speaking Mersenne Twisters are no longer consider "high quality enough".

To clarify, I am suggesting the alternative not so much because the output is a "higher quality" random number, but because of speed concerns.

This:

if(rand() / (float)RAND_MAX < fill)

this:

for(size_t c = 0; c < cols; ++c)

and this:

if(neighbors == 3 || (neighbors == 2 && field[entry]))

They all don't use braces. Please use braces. To put this in to context, there was a OpenSSL bug in Mac OSX. IF they had used braces, the double goto fail would not have mattered*. It caused a lot of issues. So I would advise at the very least you put the statements on the same line if you don't use brackets.

* Well, it could have mattered, but autocompletion of brackets in an IDE would mitigate the chances. Better safe than sorry!


Bug:

You have a bug in the following line:

AudioPlugin.seekChapter(contentId, partIndex, chapterIndex function(response) {

You're missing a comma after chapterIndex.

Structure:

So, as init and playAudio follow the same style, as well as getCurrentChapter and getCurrentPosition following the same style, so you can substitute those out. Additionally, the resolve and reject functions can be taken out, leaving:

angular.module('ngCordova.plugins.audioPlugin', [])
.factory('$audioPlugin', ['$q', function($q) {
    function resolve(response){ return $q.defer.resolve(response).promise; }
    function error(error){ return $q.defer().reject(error).promise; }
    function generic(audioPluginMethod, parameter){
        if (parameter){
            return AudioPlugin[audioPluginMethod](parameter, resolve, error);
        }
        return AudioPlugin[audioPluginMethod](resolve, error);
    }
    return {
        init: generic('init', sessionKey),
        playAudio: generic('playAudio', contentId),
        getCurrentPosition: generic('getCurrentPosition'),
        getCurrentChapter: generic('getCurrentChapter'),
        seekChapter: function(contentId, partIndex, chapterIndex) {
            AudioPlugin.seekChapter(contentId, partIndex, chapterIndex, resolve, error);
        }
    }
}]);


Value Object encapsulating different units of measure

Some quick remarks:

Don't pointlessly abbreviate: you gain nothing with "FromCMeters" or "heightInCms". Just use "Centimeters". I'd even argue that you shouldn't use the plural to express the height; I'd always say "I'm 189 centimeter". Same for "InMeters". (But I'm not a native English speaker.)
There are several magic numbers used repeatedly: 30.48, 2.54, 12. IMHO these should be const with a meaningful name.
I fully agree with Graipher's review: you should use one canonical unit and store its value in a private variable, and InMeter, InFeet and InInches should be "translations" of that unit (e.g. if you store it in cm, InMeter should divide the value by 100).


1. Review

The name calculate is vague. Something like attack_freq would be more specific.
There's no docstring. What does calculate do? What does it return?
The values in two_dice_prob are not probabilities, they are counts or frequencies. (To get probabilities, you'd have to divide by 36.) I would use a name like two_dice_freq.
By default numpy.zeros gives you an array of floats, but the result array only contains integers, so you could specify dtype=int when creating it. (Alternatively, by constructing the result using NumPy throughout, it can be arranged that it has the right data type.)
When working with NumPy it's nearly always fastest if you structure the code to consist of a sequence of whole-array operations, rather than looping over the elements in native Python.

In this case we can use numpy.mgrid to construct arrays containing all possibilities for attack shift, defence roll and attack roll:

shift, defence, attack = np.mgrid[-12:13, 1:7, 2:13]

Then we can find the difference between attack and defence simultaneously for all possibilities:

diff = attack + shift - defence

The three outcome classes can now be computed by comparing the difference against 0 and 5 to get arrays of Booleans, and then assembling the outcomes into a single array using numpy.stack:

missed = diff <= 0
destroyed = diff >= 5
disabled = ~(missed | destroyed)
outcome = np.stack((missed, disabled, destroyed), axis=1)

The reason for choosing to stack along axis=1 is so that the outcome array has the right shape, that is, (25, 3, 6, 11). We multiply the last axis by the two-dice frequencies, and then sum over the last two axes. This leaves us with an array of frequencies with shape (25, 3) as required:

return (outcome * two_dice_freq).sum(axis=(2, 3))

If we had chosen to stack along axis=0, then at this point we would have an array with shape (3, 25) and we'd have to transpose it before returning. By choosing the right axis to stack along we avoided this transposition.

2. Revised code

import numpy as np

def attack_freq():
    """Return array with shape (25, 3), whose (i + 12)'th row contains the
    frequencies of the three outcome classes (missed, disabled,
    destroyed) when attack bonus minus defense bonus is i.

    """
    two_dice_freq = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
    shift, defence, attack = np.mgrid[-12:13, 1:7, 2:13]
    diff = attack + shift - defence
    missed = diff <= 0
    destroyed = diff >= 5
    disabled = ~(missed | destroyed)
    outcome = np.stack((missed, disabled, destroyed), axis=1)
    return (outcome * two_dice_freq).sum(axis=(2, 3))

This computes the same results as the code in the post:

>>> np.array_equal(calculate(), attack_freq())
True

but it's roughly four times as fast:

>>> from timeit import timeit
>>> timeit(calculate, number=1000)
0.38954256599993187
>>> timeit(attack_freq, number=1000)
0.09676001900004394

The actual runtimes are so small, less than a millisecond, that this speedup doesn't really matter in practice, since you'd only need to build this table once. However, the general technique, of applying a series of whole-array NumPy operations instead of looping in native Python, can make practical differences in other kinds of program, so it's worth practicing the technique even in small cases like this.


Trying to simplify a setTimeout sequence

// Put everything in one function, but break it up internally
function opening() {
  // A tiny, internal helper function
  // I've switched the order of arguments compared to setTimeout
  // because it makes for nicer code (no dangling argument after
  // a function body)
  function createTimeout(delay, func) {
    return function () {
      setTimeout(func, delay);
    };
  }

  var step1, step2, step3, // Declare some vars that'll hold functions
      stage = $('#stage'); // and find the #stage element right away

  // Create the first step. When called, it'll wait 400ms
  // and then execute the function
  step1 = createTimeout(400, function () {
    stage.find('h1').fadeIn('slow', step2); // call step2, when the fade-in completes
  });

  // Same principle as above
  step2 = createTimeout(800, function () {
    stage.find('.logo').fadeIn('slow', step3); // call step3
  });

  // and again
  step3 = createTimeout(400, function () {
    stage.find('p').fadeIn('slow');
    stage.find('#btn').fadeIn('slow');
  });

  step1(); // execute step 1
}

So calling opening() will

wait 400ms
make the H1 to fade in
wait 800ms
make the logo fade in
wait 400mx
make the P and #btn elements fade in


Headers

You can remove stdlib.h as it is redundant to use both stdlib.h and cstdlib. The cstdlib is the c++ variant.
The same goes for the time.h header. Use ctime instead.
The Sleep() functions are virtually useless, I removed them and also the <windows.h> header along with it. Don't confuse your users with pauses such as those, not to mention the portability issues. Keep it simple and let the program run at its own pace on their machines.

Namespace

Don't make a habit of utilizing using namespace std;. You will run into trouble later on down the road if you choose to build something that another developer will make use of. It is heavily frowned upon as it will potentially cause namespace collisions, especially if included in a header file for say, a library.

Instead just explicitly call the functions with the scope operator:

std::cout << "Don't muddy your scope!";

Variables

You have quite a few extra variables that can be removed, and also ones that could be more productive as a different data type.

The minimum and maximum variables should be declared as constants as they're not configurable anywhere in your code. Also, they could probably be a little more descriptive instead of just 'min' and 'max'.

const int LOWER_NUMBER_BOUND = 1;
const int UPPER_NUMBER_BOUND = 10;

number is also pretty vague and should be renamed to infer its purpose.

int numberToGuess;

It appears you have two variables keeping track of the same data. You decrement tries when the player guesses incorrectly but at the same time you increment playerTimesToPlay. I would advise removing one of these and sticking to one variable that tracks the guess attempts remaining. It would also be a good idea to include a constant variable that holds the max attempts so you can reset the tracking variable after a game ends.

const int GUESS_ATTEMPTS = 3;
int guessAttemptsRemaining;

userInput can also be named more clearly. Something to solidify the function of the variable.

int userGuess;

Random

You're currently reseeding the random algorithm every time you play the game. This is unnecessary and it can be moved out of your loop.
Consider using the newer <random> instead, however the rand() function is simpler and more easily understood for a beginner. Also your distribution isn't critical so I wouldn't worry about this for the moment.

Logic

Inside of the inner do loop, the while statement can be altered to reflect when there are guesses remaining instead of using the incremented variable that was removed. It's also redundant to check if the user's guess is correct so that can also be removed.

do{...} while (guessAttemptsRemaining > 0);

You can shrink the input validation and remove some of the output by simply asking them to enter a number between the bounds.

while (userGuess < 1 || userGuess > 10)
{
    std::cout << "Please pick a number between 1 and 10: ";
    if (!(std::cin >> userGuess))
    {
        std::cin.clear();
        std::cin.ignore(10000, '\n');
    }
}

There is a logic error when checking the bounds of the user's input. Instead of checking if the number is less than 0 it should be if it is less than 1 as 0 is invalid input.

while (userGuess < 1 || userGuess > 10)

You check for the same conditions multiple times. Instead of repeating yourself you can restructure your logic to only check for a condition once. There is quite a bit of this going on so instead of pointing out every specific example I'll just go ahead and refactor it to show you what I mean.

Output

Instead of std::endl consider using \n instead. It is faster than a function call and also doesn't have the additional overhead of buffer manipulation that is included with std::endl.

Refactored Code

#include <iostream>
#include <ctime>
#include <cstdlib>

const int LOWER_NUMBER_BOUND = 1;
const int UPPER_NUMBER_BOUND = 10;
const int GUESS_ATTEMPTS = 3;

int main(int argc, _TCHAR* argv[])
{
    int userGuess;
    int numberToGuess;
    int guessAttemptsRemaining;
    int playAgain = 0;

    srand(time(0));

    do
    {
        system("CLS");
        std::cout << "Welcome to my number guessing game!\n";
        std::cout << "====================================================\n";
        std::cout << "The computer is generating a number between 1 and 10.\n";
        std::cout << "====================================================\n";

        numberToGuess = rand() % (UPPER_NUMBER_BOUND - LOWER_NUMBER_BOUND + 1) + LOWER_NUMBER_BOUND;
        guessAttemptsRemaining = GUESS_ATTEMPTS;

        do
        {

            userGuess = 0;

            while (userGuess < 1 || userGuess > 10)
            {
                std::cout << "Please pick a number between 1 and 10: ";
                if (!(std::cin >> userGuess))
                {
                    std::cin.clear();
                    std::cin.ignore(10000, '\n');
                }
            }

            --guessAttemptsRemaining;
            std::cout << "You picked: " << userGuess << ".\n";

            if (userGuess != numberToGuess)
            {
                std::cout << "Sorry! You've guessed incorrectly!\n";

                if (guessAttemptsRemaining > 0)
                {
                    std::cout << "Please try again. You have " << guessAttemptsRemaining << " guess(es) remaining.\n";
                }
                else
                {
                    std::cout << "You have no guess remaining. Play Again?\n";
                    std::cout << "1. Yes\n";
                    std::cout << "2. No\n";
                    std::cin >> playAgain;
                }

            }
            else
            {
                std::cout << "Congratulations! You guessed the correct number!\n";
                std::cout << "Thanks for playing!\n";
                break; //Add some way to continue here?
            }

        } while (guessAttemptsRemaining > 0);

    } while (playAgain == 1);

    return 0;
}

Additional

I didn't cover everything so I may add more in the future. I also didn't go into extreme detail about the topics I went over so take my additions/alterations/etc. with a grain of salt and do your own research!


You see this same pattern in the framework for IEquatable<T>.  The most frequent use case for this is writing a generic method where you constrain the generic parameter type to implement the interface.  This then allows you to write code in terms of a statically typed method Equals<T>.  Another example is IComparable<T>, which is very handy for implementing methods relying on sorting without having to use the older style of providing an external Comparator class.  For instance, the default comparison mechanism for the LINQ OrderBy method uses IComparable<T>, if it's available.  In both of these cases, it's very natural to say that an instance of a type is comparable or equatable to other instances of the same type.


Parsing an IP address (Bit manipulation)

First impressions

Some basic issues that immediately jump in the eye:

A method that doesn't need data in member fields can be static. The IPAddress method looks like a good candidate for a static utility method in an IPAddressUtils class.
The Java convention is camelCase for method names (violated by IPAddress)
Poor naming: the IPAddress method takes a dotted decimal notation and returns a 32-bit integer representation. The name "IPAddress" does very little to describe that
finalByte is unused, unnecessary
Unusual declaration: instead of int numbers[], the convention is int[] numbers
Unusual formatting

Simplification

You don't need an int[] to calculate the value. You need just one value, and shift it to the left by 8 bits for each parsed byte value.

Instead of the number 48 for '0', you can just use '0' to make the meaning obvious.

Suggested implementation

Applying the above suggestions, here's a utility class:

public class IPAddressUtils {

    public static int toInt(String dottedDecimal) {
        int byte1 = 0;
        int value = 0;
        for (char c : dottedDecimal.toCharArray()) {
            if (c != '.') {
                byte1 = 10 * byte1 + (c - '0');
            } else {
                value <<= 8;
                value += byte1;
                byte1 = 0;
            }
        }
        value <<= 8;
        value += byte1;
        return value;
    }
}


e.g. of adding a new node to the graph

Well for starters I don't see the graph:

I would expect the code to be:

 Graph    graph;
 graph.add_node(20,q); // Add nodes to graph.

Stop passing pointers around.

node* add_node(int id,std::queue<int> q , node* root)

Pointers have no associated ownership semantics. This is normal in C. But if you are writing C++ you should never do this. Ownership symantis defines who owns and thus who is responsible for calling delete on dynamically allocated objects. If it is an automatic variable you should probably be passing a reference (or in the case more likely making add_node() a member of the graph object.

Also you manipulate node and adj_list directly from add_node. Again fine from a C perspective but not from a C++ one. You should ask the object to manipulate itself by asking it to perform some operation (ie method). Since your code is so intertwined without methods it makes it real hard to read and understand. So that's about all I have.

Update:

Comment on update section

For every call to new there MUST be a call to delete. Without this the code will leak memory. In your case here we don't actually need any calls to new so we can remove all the leaks by just using normal automatic variables.

// might be a bit overkill
// For just holding a destination vertex.
struct edge
{
    // This should really be private
    // Once created you don't really want it changing.
    // So make it hard to change accidentally by making it private.
    // Alternatively you can make it const (but this makes copying hard
    // so I would make it private and private an accessor)
    private: int destination_vertex;
    public:  int getDest() const {return destination_vertex;}

    // Prefer to use initializer lists.
    edge(int ver){
        destination_vertex = ver;
    }

    // i.e. Prefer to write like this
    edge(int ver)
        : destination_vertex(ver)
    {}

    // A friend for printing.
    friend std::ostream& operator<<(std::ostream& s, edge const& e)
    {
        return s << e.destination_vertex;
    }
};

struct vertex
{
    int id;                 // This should probably be const
                            // as it never changes.
                            // But because this makes copying hard
                            // prefer to make it private and provide
                            // an accessor.
    std::list<edge>  list;

    // Prefer initializer lists.
    // Also prefer not to put '_' on the front of your identifers.
    // The rules are non trivial and most people don't know the actual
    // rules so its is easy to get wrong (in this case you got it correct)
    //
    vertex(int id)
        : id(id)    // The compiler can easily distinguish between these too.
    {}

    friend std::ostream& operator<<(std::ostream& s, vertex const& v)
    {
          s << v.id << "->";
          std::copy(v.list.begin(), v.list.end(),
                    std::ostream_iterator<edge>(s, ","));
          return s;
    }
};

Lets fix some memory leaks.

class graph
{
    private:
        // No need for this to be vertex*
        std::vector<vertex*> vertexes;

        // If you just make it a vector of `vetrtex` then everything works
        // as expected and you don't need to call new anywhere.
        std::vector<vertex>   vertexes;
        int                   next;

    public:
        // Prefer initializer list
        // Don't put void as the parameter list.
        graph(void)
            : next(0)
        {}

        // You should have written this so it cleaned up all the
        // allocated memory. If your destructor does nothing then
        // don't write one, let the compiler generate one do the work
        //
        // Since we are not going to have any dynamic allocation just
        // delete it now.
        //
        // ~graph(void){}

        // Comment code that is non trivial it took me a while to
        // figure this out!
        //
        // Add a new node node 'n'
        // The vector of edges defines what node(s) 'n' connects too.
        //      add an edge from 'n' to each node in `edges'
        //      add an edge from each node in `edges' to 'n'
        //
        // Note It is assumed that `edges` does not contain any nodes
        //      larger than (n-1)

        // When passing non trivial objects pass by reference
        // If your code is not supposed to change the code make it const
        // as well. Thus the compiler warns you if you try and modify it
        // accidentally.
        void add_node(std::vector<int> const  & edges)
                                   /// ^^^^^  ^
        {
            // no need for dynamic allocation.
            // vector is already doing most of the work
            // vertex* v = new vertex(next++);
            // vertexes.push_back(v);

            // Rather just add a new element to vector
            // Then grab a reference to it for convenience.
            vertexes.push_back(vertex());
            vertex&  v = vertexes.back();  // a reference to the element you
                                           // just added.

            for(unsigned int i=0;i<edges.size();i++)
            {
                // Added comment to the beginning about this
                // assumption.
                vertex& existing_vertex = vertexes[edges[i]];

                // This:    *(new edge (v->id))
                // Dynamically allocates an edge then de-references
                // so it can be copied into a list. You lost all
                // information about the pointer you created with new
                // so the memory is leaked and lost.
                // There is no need to create dynamically allocated object
                // just use the int automatic value.

                existing_vertex.list.push_back(v.id);

                // This has the same problem as the last line.
                // apart from you are doing it in two steps so keep
                // the pointer (which you should have deleted after use)
                // edge* e = new edge(edges[i]);
                // v->list.push_back(*e);

                // This can be replaced with
                v.push_back(edges[i]);

               // In fact I would get rid of all the above lines and
               // replace with code that looks symmetrical so that you
               // can see that you are adding edges in both directions.

               vertexes[edges[i]].list.push_back(v.id);
               vertexes[v.id].list.push_back(edges[i]);

            }
        }

        // Methods that do not change the state of the object should
        // be marked const.

        void print()  const
        {       ///   ^^^^^

            // Sure you can iterate by index.
            // But you could just as easily have used an iterator.
            // Also prefer to use ++i rather than i++
            // It makes no difference for integers but if you change
            // changed the way you iterate then you don't need to think
            // am I using the correct increment style.
            for(unsigned int i = 0 ; i < vertexes.size();i++){

                // Get a reference for ease of use
                vertex& v =  vertexes[i];
                std::cout << v.id << "->";

                // Nice use of iterator.
                // But prefer const_iterator if you are not going
                // to modify the container.

                for(std::list<edge>::const_ iterator iter = v.list.begin() ; iter != v.list.end();iter++)
                {
                    std::cout << iter->destination_vertex <<",";
                }

                // Prefer '\n' over std::endl
                // The difference is that std::endl() outputs a '\n'
                // then calls flush on the stream. This makes it very
                // efficient (as the whole pointer of the buffer is
                // so we only flush to the physical stream rarely).
                std::cout << '\n';
            }
        }

        // Since we have defined output operators for edge and vertex
        // We can do the same for graph:
        friend std::ostream& operator<<(std::ostream& s, graph const& g)
        {
             std::copy(v.vertexes.begin(), v.vertexes.end(),
                       std::ostream_iterator<vertex>(s, "\n"));
             return s;
        }
        // Now you can print a graph like this:
        //    std::cout << g;

};

After cleaning up all the comments.
It looks like this:

Headers

#include <iostream>
#include <list>
#include <vector>
#include <iterator>

Edge

class edge
{
    int destination_vertex;
    public:
        int getDest() const {return destination_vertex;}

        edge(int ver)
            : destination_vertex(ver)
        {}

    friend std::ostream& operator<<(std::ostream& s, edge const& e)
    {
        return s << e.destination_vertex;
    }
};

Vertex

class graph;
class vertex
{
    friend class graph;
    int id;
    std::list<edge>  list;

    public:
        vertex(int id)
            : id(id)
        {}

    friend std::ostream& operator<<(std::ostream& s, vertex const& v)
    {
          s << v.id << "->";
          std::copy(v.list.begin(), v.list.end(),
                    std::ostream_iterator<edge>(s, ","));
          return s;
    }
};

Graph

class graph
{
    private:
        std::vector<vertex>   vertexes;
        int                   next;

    public:
        graph()
            : next(0)
        {}

        //
        // Add a new node node 'n'
        // The vector of edges defines what node(s) 'n' connects too.
        //      add an edge from 'n' to each node in `edges'
        //      add an edge from each node in `edges' to 'n'
        //
        // Note It is assumed that `edges` does not contain any nodes
        //      larger than (n-1)
        void add_node(std::vector<int> const  & edges)
        {
            vertexes.push_back(vertex(next));

            for(unsigned int i=0;i<edges.size();++i)
            {
               vertexes[edges[i]].list.push_back(next);
               vertexes[next].list.push_back(edges[i]);
            }
            ++next;
        }

        friend std::ostream& operator<<(std::ostream& s, graph const& g)
        {
             std::copy(g.vertexes.begin(), g.vertexes.end(),
                       std::ostream_iterator<vertex>(s, "\n"));
             return s;
        }
};

Main

int main()
{
    graph   g;

    std::vector<int>    v;
    g.add_node(v);

    v.push_back(0);
    g.add_node(v);

    std::cout << g << "\n";
}


Python program to take in two strings and print the larger string

Python strings supports Python built-in len function. You don't need to iterate through them manually, as for lists/dicts/sets etc (it is not Pythonic):

def compare_strings_len(s1, s2):
    if len(s1) > len(s2):
        print('String 1 is longer: ', s1)
    elif len(s1) < len(s2):
        print('String 2 is longer: ', s2)
    else:
        print('Strings length are equal!')


Whenever you have that pattern, use a dict comprehension.

new_types = {t['type']: t for t in types}

That is more elegant and expressive, but no more performant than your original code. No matter what, you need to transform every item in the list. There's not much you can do to change that fact.


A Public and Private Key generator for RSA

I can't really comment on the RSA key generation itself, since I only know the basics. From a layman's perspective it seems fine, but I cannot touch on details. However, there are some other parts that we can focus on.

Good code is hard to write, especially cryptographic one. Whenever we read cryptographic code, it's usually a good idea to have the algorithm or the original paper at hand to follow the steps. Since we're already occupied with the state machine and the mathematics behind the scenes, the code should be easy to read.

Let us have a look at modExp:

modExp :: Integer -> Integer -> Integer -> Integer
modExp b 0 m = 1
modExp b e m = t * modExp ((b * b) `mod` m) (shiftR e 1) m `mod` m
  where t = if testBit e 0 then b `mod` m else 1

That's the usual double-and-add method for b ^ e `mod` m, and it's completely fine. However, testBit and shiftR are misleading. We're not using some intricate bit patterns here and xor values later, nor do we use the number of bits as a seed. We just want to check whether e is currently odd and divide by two:

-- | Returns (b ^ e) `mod` m.
modExp :: Integer -> Integer -> Integer -> Integer
modExp b 0 m = 1
modExp b e m = t * modExp ((b * b) `mod` m) (e `div` 2) m `mod` m
  where t = if odd e then b `mod` m else 1

Note that you want to replace div by quot and mod by rem if all your values are guaranteed to be positive if you focus on performance, since quot/rem is slightly faster than div/mod. However, their result differs for negative values.

Speaking of positive, defaultExp is missing its type signature. Apart from that, it's great that every function has a type signature, although additional documentation wouldn't harm, e.g.

-- | Generates 'k' random numbers to check whether `n` is prime.
fermatPrimeTest :: StdGen -> Int -> Integer -> Bool
fermatPrimeTest g k n = all (\a -> modExp a (n-1) n == 1) as
  where
    as = take k $ randomRs (2,n-2) g

Similarly some bindings are never used. euclideanAlg2 is the greatest offender here:

euclideanAlg2 rk0 sk0 tk0 0 sk1 tk1 = (rk0,sk0,tk0) -- <- sk1 tk1 unused

Note that the worker is usually called go or similar:

euclideanAlg :: Integer -> Integer -> (Integer, Integer, Integer)
euclideanAlg a b
  | b > a     = tripFlip $ go b 1 0 a 0 1
  | otherwise =            go a 1 0 b 0 1
  where
    tripFlip (a,b,c) = (a,c,b)

    go rk0 sk0 tk0 0   _   _   = (rk0,sk0,tk0)
    go rk0 sk0 tk0 rk1 sk1 tk1 =
        let qi = rk0 `div` rk1
        in go rk1 sk1 tk1 (rk0 - qi*rk1) (sk0 - qi*sk1) (tk0 - qi*tk1)

It's easy to get rid of those bindings if we enable all warnings with -Wall. By the way, you defined but never used totient, nor did you use anything from ByteString. You probably intended to use totient it in genRSAKeys but automatically inlined it.

Apart from those nitpicks, your code seems fine. As I said, I cannot comment about the cryptographic details and whether your implementation is prone to side channel attacks or similar. Also, the quality of the random numbers depends heavily on CryptoRandomGen and therefore is out of scope for this review.

Personally, I would use a top-down approach instead of a bottom-up approach in the code, though. That makes it easier to know our goal:

data PublicKey  = PublicKey Integer Integer deriving (Show,Eq)
data PrivateKey = PrivateKey Integer Integer deriving (Show,Eq)

-- genRSAKeys e g k minPrime maxPrime
-- e is public exponent, g is random seed,
-- k is number of iterations to run Rabin-Miller test.
-- minPrime, maxPrime is range to search for primes.
genRSAKeys :: CryptoRandomGen g => Integer -> g
           -> Int -> Integer -> Integer
           -> (PublicKey, PrivateKey)
genRSAKeys e g k minPrime maxPrime =
  let  (p,q) = genPQ g k minPrime maxPrime
       n    = p*q
       t    = totient p q
       d    = modMultInv t e
  in (PublicKey n e, PrivateKey n d)

-- | Generates a pair of primes in the given range.
genPQ :: CryptoRandomGen g => g -> Int -> Integer -> Integer -> (Integer,Integer)
genPQ g k minPrime maxPrime = if p /= q
                                 then (p,q)
                                 else ...
  where
    Right (g1,g2) = splitGen g
    p = genPrime g1 k minPrime maxPrime
    q = genPrime g2 k minPrime maxPrime

...

That's a matter of preference though.


create_board()

You explicitly return a hard-coded board, using 5 lines of code.  This could be written as one line, using list multiplication and list comprehension:

return [ [EMPTY]*3 for _ in range(3) ]

[EMPTY]*3 creates a list of 3 EMPTY values: [EMPTY, EMPTY, EMPTY], and the outer [ ... for _ in range(3) ] repeats that operation 3 times, producing the required board.  (As pointed out in the comments, using list multiplication for the outer loop doesn’t produce 3 unique rows, but 3 references to the same row.)

show_board()

This function does not return anything, so certainly does not :return: <str> A clean-looking version of the board

place_player()

Despite the comment above the function, this method can be used to place an "O" on a spot on the board.

Suggestion: indicate somehow if the move is invalid (beyond row 1..3 or column 1..3, or if the spot is not empty, such as by raising an exception or returning a success/failure code.

check_if_win()

This function is using active_player * 3 in a total of six places.  Instead of repeating this expression six times, you could assign the result to a local variable, and test against that variable instead:

win_pattern = active_player * 3
# ...
for row in board:
   # ...
   if "".join(row) == win_pattern:
      return True
# ... etc ...

But a winning pattern isn't actually a string; it is a list of cells each containing the active_player symbol: ['X', 'X', 'X'].  You've just used "".join(...) to convert the list into a string.  Why create the string when you can just check for equality with the list?

win_pattern = [ active_player ] * 3
# ...
for row in board:
   # ...
   if row == win_pattern:
       return True

if column1 == win_pattern or column2 == win_pattern or column3 == win_pattern:
    return True
elif diagonal1 == win_pattern or diagonal2 == win_pattern:
    return True
else:
    return False

But this code is still quite verbose.  There is a pythonic way of testing if any item in a list of items matches a condition.  It uses the any(iterable) call; if any of the iterable items is True, the resulting any(...) expression evaluates to True.  Using this to test for any of the rows of the board matching the win_pattern is straight forward:

if any(row == win_pattern for row in board):
    return True

Your for row in board: loop also constructs the column1, column2, column3, diagonal1 and diagonal2 lists.  Whenever you have a set of variables with the same prefix name and numeric suffixes, you aught to ask yourself if you could use a list (for example, column[0], column[1], and column[2]) or a loop.  Let's start by making a single column in a loop:

column = []
for row in board:
    column.append(row[col])

If col was 0, this would make your column1 variable from your code.  List comprehension can reduce this to one line:

column = [ row[col] for row in board ]

We actually only need the column variable for just the test against win_pattern, so we could actually eliminate it and perform the test directly:

if [ row[col] for row in board ] == win_pattern:
   return True

Doing that in a loop, for all 3 col values completes the test for a win in any column:

for col in range(3):
    if [ row[col] for row in board ] == win_pattern:
       return True

But above, we replaced a for x in y: and an inner if condition: with an any(...) statement; we can do the same thing here!

if any( [ row[col] for row in board ] == win_pattern for col in range(3)):
    return True

We can also do this for the forward diagonal:

if [ board[i][i] for i in range(3) ] == win_pattern:
    return True

And the reverse diagonal:

if [ board[i][2-i] for i in range(3) ] == win_pattern:
    return True

This looks a lot shorter, and simpler:

win_pattern = [ active_player ] * 3

if any(row == win_pattern for row in board):
    return True

if any( [ row[col] for row in board ] == win_pattern for col in range(3)):
    return True

if [ board[i][i] for i in range(3) ] == win_pattern:
    return True

if [ board[i][2-i] for i in range(3) ] == win_pattern:
    return True

return False

... but I don't quite like it yet.  We can get rid of the win_pattern list, and all the [ ... for x in y ] list creation, using something similar to any(...): the all(...) function.  It returns True when all elements are True.  So instead of

if [ row[col] for row in board ] == [ active_player ] * 3:

which creates a list of 3 items on the left-hand-side and creates a list of 3 items on the right hand side and tests if the lists are the same, we'll test if the first element on the left-hand-side is the same as the first element on the right-hand-side, and ditto for the second elements, and ditto for the third elements.  Of course, all 3 elements on the right-hand-side are the same element.  So the all(...) statement will look like:

if all(row[col] == active_player for row in board):

Again, that is testing one particular column index: col.  If we want to check if any column has the winning pattern, we'll wrap this in an any call:

if any( all(row[col] == active_player for row in board) for col in range(3)):
    return True

So, changing the implementation slightly, to exploit the duality nature of rows and columns, you might write this method as:

def check_if_win(board, active_player):

    if any( all(board[r][c] == active_player for c in range(3)) for r in range(3)):
        return True

    if any( all(board[r][c] == active_player for r in range(3)) for c in range(3)):
        return True

    if all(board[i][i] == active_player for i in range(3)):
        return True

    if all(board[i][2-i] == active_player for i in range(3)):
        return True

    return False

main()

if check_if_win(board, active_player) is True:

could be written without the is True portion:

if check_if_win(board, active_player):

Asking for user input, and converting it to an integer int(input(...)) can lead to ValueError if the user enter bad values, such as "fish".  You should check for and catch exceptions.  Moreover, you should range-check the input.  A user could enter 42 -1 for the row/column.  Finally, the user could enter a valid, legal board position which is already used.  If the user enters bad values (either not valid integers, or out-of-bound values, or already taken locations), the program should complain and ask the user to re-enter the row column input.

Bug: Finally, the game could end in a Tie, which is currently not handled.


I would write the function like this:

#include <string.h>

/* Return 1 if string s1 ends with s2; return 0 otherwise. */
int strend(const char *s1, const char *s2)
{
    size_t l1 = strlen(s1);
    size_t l2 = strlen(s2);
    return l2 <= l1 && memcmp(s2, s1 + l1 - l2, l2) == 0;
}

If we know the length of the strings (as here), then memcmp is usually the quickest way to compare them. That's because memcmp doesn't have to check for the end of the string (unlike strcmp), and because standard library implementations of memcmp tend to be well optimized, using word-at-a-time comparison and other tricks if possible.


Your tests seem to be of appropriate size and scope but there are a couple things I'd address.

Assertions
First and foremost I don't see your code asserting on anything.
You manipulate the binarySearch tree, which is the first step, but then you don't check the state of it afterward.  As a reviewer I'd ask "what are your tests actually testing?"

Magic numbers
It's clear you thought about what each test was supposed to accomplish but the intent of the test could be clearer to the reader.  You could try adding meaning to the numbers you are inserting to the tree, adding comments, or some other way of making the purpose of each test very clear to the reader.


Currently your code is all over the place. You have global variables (which should be named in ALL_CAPS according to Python's official style-guide, PEP8), functions which modify these globals, then some actual code in between the functions and at the end some code that actually executes the code, also in the global namespace (preventing you from importing any of the functions defined here in another script).

In addition I would also change:

Use random.choice(entries) instead of random.randint(0, len(entries)).
Make Entry a collections.namedtuple (which allows using tuple unpacking).
Since you say you are using Python 3.x, use the new f-strings introduced in Python 3.6.
Where this is not possible, use str.format instead of building the strings using addition and manual calls to str.
Make main take the file path (defaulting to the global constant) so it is more extendable.
Making sure to close all opened files again using with ... as.
Use if __name__ = "__main__" guard to allow importing.
Call strip on the manually entered words, removing the need to do that every time you compare them later.
Remove the wrong variable, it is unused (and can be easily calculated as total - right).
raw_input is not called that anymore in Python 3. It is now called input (and the input from Python 2 is gone).

import random
import os
import sys
from collections import namedtuple

FILE_PATH = "./words.txt"
Entry = namedtuple("Entry", ["french", "english"])

def insert(entries):
    while True:
        french = input("French word: ").strip()
        if french == "#":
            return
        english = input("English word: ").strip()
        if english == "#":
            return
        entries.append(Entry(french, english))

def query(entries):
    total, right = 0, 0
    while True:
        word_pair = random.choice(entries)
        french = input(f"French translation of {word_pair.english}:")

        if french == "#":
            percentage = (right * 100) / total
            print(f"You answered {right} question out of {total} correct.")
            print(f"Percentage: {percentage} %")
            return
        total += 1
        if french.strip() == word_pair.french:
            print("Correct.")
            right += 1
        else:
            print("Wrong!")

def printall(entries):
    if len(entries) == 0:
        print("No words stored.")
        return
    for word_pair in entries:
        print("{} : {}".format(*word_pair))

def backup_wordpairs(entries, file_path):
    with open(file_path, 'w') as words:
        for word_pair in entries:
            words.write("{},{}\n".format(*word_pair))

def main(file_path=FILE_PATH):
    if os.path.isfile(file_path):
        with open(file_path) as words:
            entries = [Entry(*map(str.strip, line.split(",")))
                       for line in words]
    else:
        print("File does not exist")
        sys.exit()

    while True:
        command = input("Please enter a command: ")

        if command == "add":
            insert(entries)
            backup_wordpairs(entries, file_path)
        elif command == "test":
            query(entries)
        elif command == "list":
            printall(entries)
        elif command == "end":
            break
        elif command == "reset":
            entries.clear()
            if os.path.isfile(file_path):
                os.remove(file_path)
        else:
            print("No known command.")

    print(" ------- Vocabulary becomes terminated. ----------  ")
    sys.exit()

if __name_ == "__main__":
    main()

As you can see now, almost all functions take entries as the first argument and modify it somehow. This should tell you that you could easily make this a class.


This is actually an interesting question.

@RuslanOsipov has provided a solution, but technically it is vulnerable to a time-of-check vs. time-of-use race condition.  In other words, there is a brief window between the isfile() call and the open() call where a things could go wrong.  Depending on the application, that could even be considered a security vulnerability.

So, what to do?  For the full story, read Python Issue 12760.  In Python 3.3, open() gained an 'x' mode flag that makes it behave like the code in this question wants it to.  For older versions of Python that lack the 'x' flag, the workaround is:

def create(file):
    fd = os.open(file, os.O_EXCL | os.O_CREAT | os.O_WRONLY)
    return os.fdopen(fd)


Bash grep taking 3 days to finish. Any suggestions to enhance it?

Without your data, it's difficult to test if the changes help at all. I can only assume that the constant reading and writing to files on disk is slowing down your program. If your data is simply big enough to require 3 days to run in a bash script, then you may have to switch to another programming language with more complex data structures that can do your processing faster.

The first thing I notice is that you have cat and temporary files everywhere. The programs you are piping cat output to can take file name arguments. Plus, writing to disk is one of the slowest things you can do to move data around. For example, all this

cat R*op.txt > R.total.op.txt
awk '{if( (length($8)>9) || ($8 ~ /^AAA/) ) {print $0}}' R.total.op.txt > temp && mv temp R.total.op.txt

cat S*op.txt > S.total.op.txt
awk '{if( (length($8)>9) || ($8 ~ /^AAA/) ) {print $0}}' S.total.op.txt > temp && mv temp S.total.op.txt

cat R.total.op.txt S.total.op.txt | awk '{print $4}' | sort -k1,1 | awk '!x[$1]++' > genes.txt
rm *total.op.txt

can be replaced with the following with only one file write

awk '{if( (length($8)>9) || ($8 ~ /^AAA/) ) {print $0}}' R*op.txt S*op.txt | awk '{print $4}' | sort -k1,1 | awk '!x[$1]++' > genes.txt

Now, for the loop you marked

for j in R1_with-genename R2_with-genename S1_with-genename S2_with-genename
do
    for i in `cat genes.txt`
    do
        cat $j'.op.txt' | grep -w $i >> $j'_'$i'_gene.txt'
    done
done

Try changing this to (with some better names)

for file in R1_with-genename R2_with-genename S1_with-genename S2_with-genename
do
    while read -r line
    do
         grep -w $line $file'.op.txt' >> $file'_'$line'_gene.txt'
    done < genes.txt
done

This will read the file line by line instead of all at once with cat genes.txt. An important note is that this will give different results than your script if there are multiple words per line in genes.txt. To read word-by-word, use

for file in R1_with-genename R2_with-genename S1_with-genename S2_with-genename
do
    while read -r line
    do
        for word in $line
        do
            grep -w $word $file'.op.txt' >> $file'_'$word'_gene.txt'
        done
    done < genes.txt
done

If genes.txt is much larger than the R1_with-genename, etc., files, then reversing the order of the loops could help by only reading the larger file once.

while read -r line
do
    for file in R1_with-genename R2_with-genename S1_with-genename S2_with-genename
    do
         grep -w $line $file'.op.txt' >> $file'_'$line'_gene.txt'
    done
done < genes.txt

Using >> appends to the end of the file if the file exists. Is this what you want? If running the script should overwrite previous results, use a single >.

Also, since you delete the genes.txt file right afterward, you don't even have to create it.

awk '{if( (length($8)>9) || ($8 ~ /^AAA/) ) {print $0}}' R*op.txt S*op.txt | awk '{print $4}' | sort -k1,1 | awk '!x[$1]++' | while read -r line
do
    for file in R1_with-genename R2_with-genename S1_with-genename S2_with-genename
    do
         grep -w $line $file'.op.txt' >> $file'_'$line'_gene.txt'
    done
done


Find and replace strings in the first column of data

You could use a dictionary instead of a list of tuples for chem_fix, and then you could get rid of fix_terms. Then you could use search from the re module in the list comprehension and then look up any matches in the dictionary. And you can use walrus operator to store whatever is returned from search since first you have to make sure it’s not None. Here’s an example of that:
# there’s already a function called “compile”
# “import re” used so it doesn’t get overwritten
pattern = re.compile('|'.join(chem_fix))
pattern_search = pattern.search # method will be looked up faster
test_and_value_f = [
    (
        chem_fix[m.group(0)]
        if (m := pattern_search(lab_test)) is not None
        else lab_test,
        value
    )
    for lab_test, value in test_and_value
]


Parsing latitude and longitude, using Try[T] to ignore errors

That looks pretty good to me.

Try is preferable over try/catch since it gives more options on how to process the Failure case.  In particular, the fact that Try can be flatMap'd means that you an build a for-comprehension to cover the processing and essentially abort on the first failure.

for {
  x <- Try("1".toInt)
  y <- Try("a".toInt)
  z <- Try("3".toInt)  // never invoked due to above error
} yield x + y + z

// returns: Failure(java.lang.NumberFormatException: For input string: "a")

For parsing a String to an Int it doesn't matter as much, but if the body of the Try is expensive then some of that cost can be avoided.

Depending on the context you're working in then it might behoove you to capture and log the Failures as well; for some one-off code silently ignoring the failures might be fine, but in an application it can save a lot of heartache when dirty data inevitably makes its way in.


1. Comments on your code

The documentation does not match the implementation. The docstring says "append Nones to list" but it does not append: if the list does not have the required length, it returns a newly allocated list.
It seems wrong to return the original list if it was the right length, but return a newly allocated list if it was too short. For consistency, the function should either always return a new list, or always (update and) return the old list.
It's a loss of generality to support only the addition of None elements. Why not let the caller pass in their preferred placeholder element.
If you run help(AttributeError) you'll see that its description is "Attribute not found." This does not seem appropriate here. ValueError would be a better choice, or better still, create your own.
There's no need to name the variable list_: this avoids shadowing the built-in function list, but you don't use that function, so it doesn't matter if you shadow it.
You call len(list_) three times. Simpler to call it once and store the value.
The case len(list_) == length could be combined with the case len(list_) < length and so simplify the code.
The error message "Length error list is too long" makes no sense in English.
The error message would be more useful if it contained the actual numbers.
This kind of function is ideal for doctests.

2. Revised code

I've chosen to make the function always update its argument, and fixed all the problems noted above.

class TooLongError(ValueError):
    pass

def pad(seq, target_length, padding=None):
    """Extend the sequence seq with padding (default: None) so as to make
    its length up to target_length. Return seq. If seq is already
    longer than target_length, raise TooLongError.

    >>> pad([], 5, 1)
    [1, 1, 1, 1, 1]
    >>> pad([1, 2, 3], 7)
    [1, 2, 3, None, None, None, None]
    >>> pad([1, 2, 3], 2)
    ... # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    TooLongError: sequence too long (3) for target length 2

    """
    length = len(seq)
    if length > target_length:
        raise TooLongError("sequence too long ({}) for target length {}"
                           .format(length, target_length))
    seq.extend([padding] * (target_length - length))
    return seq


On principle the code is sound except for one issue: you do not check if the language is "valid". This raises some questions:

How will your localization code behave if I added a lang parameter with the value "foobar"?
How will it behave if I try to do an SQL injection using the parameter value?

In both cases, the sane outcome would be to default to your "main" language, which would probably be hardcoded in your application.

Another issue you may want to consider is that nobody knows that there is an Accept-Language header and how to use it, so using that as a source of the user's preferred locale is not recommended:

  It is not a good idea to use the HTTP Accept-Language header alone to
  determine the locale of the user. If you use Accept-Language
  exclusively, you may handcuff the user into a set of choices not to
  his liking.

In your shoes I would totally scrap using $_SERVER['HTTP_ACCEPT_LANGUAGE'] (IMHO it's useless in practice). If you want to go the extra mile and auto-detect the user's locale, use an IP database (I have used MaxMind GeoIP in the past myself) or the upcoming W3C geolocation spec.


There are much simpler ways to do this.    The easy way is to use difflib.get_close_matches() which is very similar to what you are creating.  If you insist on making your own, there are still simpler ways.

First of all, why regex?  You don't have patterns to match.  You have simple equality tests.  The only thing that makes it different from a in b is re. IGNORE_CASE.  Simply fixed, do a.lower() in b.lower().  In this case, however, you actually mean a.lower() == b.lower().

Iterating through two sequences in parallel is a common enough task that Python made it easy with zip().  Instead of

for i in range(len(a))):

with a[i] and b[i], you can use

for a_item, b_item in zip(a, b):

Conveniently, it stops at the end of the shortest iterable (not in Python 3).

Your method of limiting the number of matches returned is not ideal. Instead of deleting the ones you don't want, keep only the ones that you do. That is done simply with a slice.

In Python, the bool class (for True and False) inherits from the int class. Therefore, you can do arithmetic with booleans.  True is 1, and False is 0. With that knowledge and the earlier improvements, we get something much simpler:

def diff_score(iter_a, iter_b):
    return sum(a == b for a, b in zip(iter_a.lower(), iter_b.lower()))

def best_matches(guess, names, num_matches):
    matches = sorted(names, key=lambda x: diff_score(x, guess), reverse=True)
    return  matches[:num_matches]


Simple chart class for SVG path generation

Repetition, similarities, and redundancies

To simplify code you start by looking for repetition and similarities. In most cases you can remove the repeating/similar code by adding variables to take care of the minor differences.

Count how often you use a variable name, eg end and start are defined 5 times, and you have had to type them in 10 times each, and point has even more.

Variable names also should not have repetition. If you find yourself creating a pile of variables that all share some prefix or postfix, it's a good sign that you can optimize and simplify.

Don't do something twice when once is enough. A common practice is

const blah = foo + bar;
return blah;

The blah is redundant return foo + bar; does the same with less complexity.

see note (*1)

Functional similarities

You have four almost identical functions that contain the following

    const point = (this.radius / 100) * perc
    const start = [this.cx, this.cy + point]
    const end = [this.cx - point, this.cy]
    return getPath(point, start, end)

The only difference is the addition or subtraction of point to the coordinates. For the four functions there are only 4 different combinations which you can define as an array of values, 0 for no change, -1 for subtraction and 1 for addition.

For the above snippet that would be [0, 1, -1, 0] so if you had a generic function that accepted an array

getCorner(perc, cornerDesc) {
    const point = (this.radius / 100) * perc;
    const start = [this.cx + cornerDesc[0] * point, this.cy + cornerDesc[0] * point];
    const end = [this.cx + cornerDesc[2] * point, this.cy + cornerDesc[3] * point];
    return getPath(point, start, end);
}

But this is a bit obscure and not very intuitive. We still want to to use named function calls to get a corner, "topleft..." rather than a non descriptive array to define a corner. (see below)

Variable repetition

If we look further there is still repetition of the arguments passed to getPath. We can define  point, start, and end in the getPath function and pass it the perc argument and array of offsets.

Looking at the functions named getTopRightSegmentPath, getTopLeftSegmentPath ... etc, each contains SegmentPath which is a good clue in what to remove and create once.

A good rule of thumb. If adding the same name to a bunch of variables, that similarity should be an object, eg getTopRightSegmentPath becomes segmentPath.topRight (the get is redundant in lieu of more info about Path's functionality)

Though Javascript class syntax is not conducive to complicated Objects (*), so it is best to redefine the whole Path object as a factory function (see rewrite)

So we can create something like

segmentPath = {
    topLeft(perc = 1) { return getPath(perc, [-1,0,0,-1]) },
    topRight ... // and so on
}

Redundency

Looking at the getPath function we can remove some redundancy now that we have moved the defining of end and start into that function. The function xy can be removed as we can directly define start and end as strings skipping the need for the function xy and creating arrays that we immediately join.

this is redundant.

My favorite redundancy removal is this. When I see code that is full of this I see bad practice. The token this should only ever be used for properties that are to be accessed outside the object. The (so popular) class token encourages the exposure of everything, if you see the token class you can guarantee that by word count this is the most used (eg you use this 25 times) and mostly incorrectly.

Personalty, if you put effort in you can actually write good Javascript without ever needing this

The rewrite.

So with all that said let's put it together, (I can only guess at the overall requirements of the Path object so the rewrite may not suit additional behavioural and state management needs)

The variable cx, cy, and radius dont need to be exposed so we can close over them, the function getPath look like it is only used internally so again I will close over it.

function Chart(options) {
    var cx = options.center[0];
    var cy = options.center[1];
    var radius = options.radius;
    function getPath(offsets, perc = 1) {
        const rad = (radius / 100) * perc;
        const start = `${cx + offsets[0] * rad},${cy + offsets[1] * rad}`;
        const end = `${cx + offsets[2] * rad},${cy + offsets[3] * rad}`;
        return `M${start} A${rad}, ${rad} 0 0 1 ${end} L${cx}, ${cy} Z`;
    }
    return {
        segmentPath : {
            topLeft(perc) { return getPath([-1, 0, 0, 1], perc) },
            topRight(perc) { return getPath([0, -1, 1, 0], perc) },
            bottomLeft(perc) { return getPath([0, 1, -1, 0], perc) },
            bottomRight(perc) { return getPath([1, 0, 0, 1], perc) },
        }
    };
}

Which is used as follows

const chart = Chart({center : [x,y], radius : 10});
const svgPath = chart.pathSegment.topLeft(2);

Alternative

I did consider the following...

    return {
        topLeft(perc = 1) { return getPath(prec, -1, 0, 0, 1) },
        topRight(perc = 1) { return getPath(prec, 0, -1, 1, 0) },
        bottomLeft(perc = 1) { return getPath(prec, 0, 1, -1, 0) },
        bottomRight(perc = 1) { return getPath(prec, 1, 0, 0, 1) },
    };

...with the function getPath defined as

    function getPath(perc, ...offsets) {

But the repetition of perc = 1 annoyed me

Access properties via getters and setters

If you need to change the properties it is better to use getters and setters, though only as example, you can include some vetting on the setters

    return {
        segmentPath : {
            topLeft(perc) { return getPath([-1, 0, 0, 1], perc) },
            topRight(perc) { return getPath([0, -1, 1, 0], perc) },
            bottomLeft(perc) { return getPath([0, 1, -1, 0], perc) },
            bottomRight(perc) { return getPath([1, 0, 0, 1], perc) },
        }
        get center() { return [cx, cy] },
        get radius() { return radius },
        set center(cent) { [cx, cy] = cent },
        set radius(r) { radius = r },
    }

Usage

const chart = Chart({center : [x,y], radius : 10});
chart.radius *= 2;
console.log(chart.radius); // >> 20
chart.center = [x * 2, y * 2];
const svgPath = chart.pathSegment.topLeft(2);

Look mum no this

Some notes

(*) Called Object/s because in Javascript there are no "classes" only Objects. The class token is just a way of defining an object.

(*1) Note that in some cases to such as conditional and loop statements (where you use conditional operators) it is better to define befor the statement variables that require operations.

if (foo & bar === something) {

is better written as

const blah = foo & bar;
if (blah === something) {

This is because it can be a source of bug when precedence can give non intuitive results.

if(10 & 0 === 0) { // false
if((10 & 0) === 0){ // true
return 10 & 0 === 0 // returns 0 not a boolean
return (10 & 0) === 0 // returns a boolean true

Unless you have very familiar with all off javascript's operator precedence dont add expressions to statements.

Also if the following line becomes too long, dont remove

const blah = foo + bar + apple + sauce;
const poo = blah + " something else is " + value * 2 + " when " + num + count;

is better than

const poo = (foo + bar + apple + sauce) + " something else is " + value * 2 + " when " + num + count;

^^ scroll bar bad :(


I updated your code to remove the first click-handler and the each-loops.
However I'm not quite sure if this is necessarily faster then your solution.

My suggestion relies on callbacks, css-selectors and conditions:

$(".tags_cloud div").click(function() {

  var $this = $(this),
    $tags = $(".tags_cloud div:not(#all-tags)"),
    $all = $(".tags_cloud div#all-tags");

  var all = $(this).is('#all-tags') ? true : false;
  if (all) {
    $this.toggleClass(function() {
      if (!$(this).hasClass('is_active')) {
        $tags.addClass('is_active');
      } else {
        $tags.removeClass('is_active');
      }
      return "is_active";
    });
  } else {
    $this.toggleClass('is_active');
    ($tags.not('.is_active').length === 0) ? $all.addClass('is_active') : $all.removeClass('is_active');
  }
});

Demo


Get all children recursively in Entity Framework Core

If you remove virtual from Children it'll work with Include(e => e.Children):

  public abstract class RecursiveEntity<TEntity>
    : Entity, IRecursiveEntity<TEntity>
    where TEntity : RecursiveEntity<TEntity>
  {
    public virtual TEntity Parent { get; set; }
    public ICollection<TEntity> Children { get; set; }
  }

The meaning with virtual is to provide lazy loading. If you can't live with that, you'll have to do it manually, as you do.

Alternatively I think, you can add "MultipleActiveResultSets=True" to your connection string.

UPDATE

I seems that EF 6 and EFCore work differently when it comes to Include?

EFCore has the Include() and ThenInclude pattern but that is rather useless for recursive initialization.

When loading manually have you then experimented with the abilities to load navigation properties on each object as in:

public IEnumerable<TEntity> Get<TEntity>(Expression<Func<TEntity, bool>> filter) where TEntity: RecursiveEntity<TEntity>
{
  foreach (TEntity entity in Set<TEntity>().Where(e => e.Parent == null).Where(filter))
  {
    GetChildren(entity, filter);
    yield return entity;
  }
}

private void GetChildren<TEnity>(TEnity parent, Expression<Func<TEnity, bool>> childFilter) where TEnity : RecursiveEntity<TEnity>
{
  Entry(parent).Collection(e => e.Children).Query().Where(childFilter).Load();
  // Entry(parent).Reference(e => e.Parent).Load(); // I think this shouldn't be necessary because loading the children will load the parent on them

  if (parent.Children != null)
  {
    foreach (TEnity child in parent.Children)
    {
      GetChildren(child, childFilter);
    }
  }
}

It should produce the same result as yours, but is maybe a little clearer and in line with the EF concept.


Converts numbers in range 0 through 15 into ASCII-coded character '0' through 'F'

I see a few things that may help you improve your code.

Don't alter registers unless specified

The current code alters the $a0 register, which is appropriate to the problem, but the specification doesn't say that the register may be altered.  I'd suggest not altering passed in registers unless the specification says to.

Know your instruction set

The ble instruction can also work with a constant, so there's no real need to load a register with the value 9.  Also, it would be better to simply use a move instruction than the curious construct addi $t0,$zero,0x9.

Avoid nop instructions

I don't know of a reason that would require nop instructions where this code has them, so I'd recommend eliminating them.

Minimize register use

One of the most important things to keep track of in assembly language programming is register usage.  In this particular case, I'd suggest that there is no need to use more than a single register.  Here's how I'd do it:

hexasc:
andi $v0,$a0,0xf        # save only low 4 bits
addi $v0,$v0,0x30   # turn into ASCII
ble $v0,0x39,L2     # if it's > ASCII '9'
addi $v0,$v0,7      #   add additional 7 for 'A'-'F'
L2:
jr $ra