It's a nitpicky thing, but I prefer explicit scoping.

Sub MoveData()

Should be

Public Sub MoveData()

There are lots of reasons to avoid Activating and Selecting objects. Performance is just one of them.

Dim fileName As String
    Sheets("Cover").Select                                  '
    range("B5").Select
    fileName = Selection.Value

Would be better written as

Dim fileName As String
fileName = Worksheets("Cover").Range("B5").Value

Note that I used the Worksheets collection instead of Sheets. This is because Sheets can have charts, Worksheets can't.

Dim currentWB As Workbook
Set currentWB = ThisWorkbook

Good call and good naming. Well done.

It's very slow to open a workbook. Luckily, you might not even have to open the book with the source data. I would look into querying the Excel data source with ADODB instead. Once you have a recordset, you can use the CopyFromRecordset method of Range to paste into the current workbook. It's much faster than loading the data source into Excel.

Here's some untested code to get you started.

Dim cn as ADODB.Connection
Set cn = New ADODB.Connection
With cn
    .Provider = "Microsoft.Jet.OLEDB.4.0"
    .ConnectionString = "Data Source=" & path & ";" & _
"Extended Properties=Excel 14.0;"
    .Open
End With

strQuery = "SELECT * FROM [Sheet1$C2:C51]"

Dim rst As New ADODB.Recordset
rst.Open sqlQuery, cn

currentWB.Worksheets("Bms").Range("C7").CopyFromRecordset rst

I don't think you understand what parenthesis do in procedure calls.

openWB.Close (False)

There's no harm in passing a boolean literal ByVal in this case, but make sure you save yourself the headache down the road and go read that StackOverflow Q&A I linked to. Parenthesis change how the argument is passed to a procedure.


This looks mostly good to me. Your code looks like fairly clean C. I have some comments:

I think capacity is a better name than capability.
I would avoid calling your header memory.h, since memory is a header in C++. Maybe checked_alloc.h instead? Also, include it as "memory.h" and let your build system figure out its path.
How is your error handling in the assert_...alloc functions? Do they just terminate the program?
Two of your public interface functions are without documentation. Are they not supposed to be part of the public interface? If not, put them in the implementation file (only) and make them static. If they are, document them as well.
Note that the assert() macro is only evaluated if your library is compiled without NDEBUG. This means that the code using it will be unchecked for production builds. It might be fine, but maybe you want checking in production as well; I'm just pointing it out.
As far as I can see, you adhere to the Linux coding style.
Consider typedef uint8_t byte or something like that to emphasize what the role of the uint8_ts are. Remember that you have no guarantee that CHAR_BIT is 8. (Maybe you want to use char instead, which is guaranteed to always be one byte.)
I would change if (a->length == a->capability) to if (a->length >= a->capability). The latter is a bit clearer, and if you at one point allow adding larger objects the code will still work.
Your macro looks nasty.

I'd do:

#define CAPACITY_GROWTH_FACTOR 2

/* ... */

a->capability *= CAPACITY_GROWTH_FACTOR;

Or even better, change the #define into a const size_t.
The nmemb variable isn't very readable. Change it to num_members or something like that.
Consider sorting your #includes alphabetically.
While I don't see anything wrong with your reference counting, you should thoroughly test it to verify that it works.
Regarding reference counting and your interface, ask yourself these questions:

What happens when you copy your array? What do you want to happen? How should a copy be made?
How should copies behave when you modify an array that has multiple references to it?
Will this be used in a multi-threaded environment?

The answers affect how the interface should be designed. Personally, it seems to me that the reference counting is on a very low level (the caller has to take care of it himself), meaning it would be easy to make mistakes. Make your interface easy to use correctly, and hard to use incorrectly. Reference counting might not even be necessary here, depending on what the array is meant to be used for.


Improving performance in generating an Excel file

I'd like to shave off some more time, but I'm currently out of ideas.

Run the code in a profiler, to find out where the bottleneck is.  At a minimum, force the jvm to dump the thread stacks every 5 seconds or so, and find out where it is (because it is probably in the slow place almost all the time).

In your main loop, there are really two different ideas.  First idea: take the current result, and parse it to a string; second idea: to write that string out to a file.  You should make the separation of those ideas explicit.

That will be a lot easier if you create objects to encapsulate those responsibilities.

class Parser {
    private final String bodyStringDelim;
    private final String delimiter;
    private final int columnCount;

    Parser(String bodyStringDelim, delimiter, columnCount) {
        ...
    }

    String parser(ResultSet resultSet) {
        StringBuilder lineBuilder = new StringBuilder();

        for (int column = 1; column <= columnCount; column++) {
            String value = resultSet.getString(column);
            if (value != null) {
                if(bodyStringDelim != null){
                    lineBuilder.append(bodyStringDelim);
                }
                lineBuilder.append(value);
                if(bodyStringDelim != null){
                    lineBuilder.append(bodyStringDelim);
                }
            }

            if (column != columnCount) {
                lineBuilder.append(delimiter);
            }
        }

    }
}

If the garbage collector is getting in your way, you might try reusing the StringBuilder to see if that helps

class Parser {
    private final StringBuilder lineBuilder = new StringBuilder();

    private final String bodyStringDelim;
    private final String delimiter;
    private final int columnCount;

    Parser(String bodyStringDelim, delimiter, columnCount) {
        ...
    }

    String parser(ResultSet resultSet) {
        lineBuilder.setLength(0);
        ...

Similarly, you have a writer class -- at the moment, this is a lot simpler.

class Writer {
    private final File output;

    Writer (File output) {...}

    void write(String line) {
        FileUtils.writeStringToFile(output, line, true);
    }
}

FileUtils.writeStringToFile is the wrong idea for this problem -- in addition to opening and closing the file every time, you have to keep seeking forward in the file (which is getting longer) and you are flushing each individual line of the file to disk.

Much better here to manage your own FileOutputStream, which is opened with the append flag set.  You can still use IOUtils.write() if you like.

If that's still not fast enough an alternative would be to move the File IO to a different thread.  In that case, you would have two "writer" implementations.  The one running here, it would actually be pushing the Strings into a concurrent data structure (ConcurrentLinkedQueue, Disruptor, etc), and then the "real" writer lives in a second thread, pulling batches of data out of the shared structure, buffering it, and flushing it to disk.

Theoretically, this would allow you to overlap the slow parts of the read with the slow parts of the write, trading away CPU cycles for better wall clock time.


To answer your questions…

Your approach is fine.
Move your hundreds of lines into a function, then break down that function into reasonable-sized chunks.  If it's still huge and ugly, then pose that as another code review question.
If an error other an IOError occurred, then the error would not get caught.  However, when the with block is exited for any reason, input_file and output_file will get properly closed.

In addition to what @JimDennis said, I would like to point out that it it customary to print error messages to sys.stderr, and exit with a non-zero status when an error occurs.

def process(csv_reader, csv_writer):
    for row in csv_reader:
        # many lines of code...

def main(input_filename, output_filename):
    try:
        with open(input_filename, 'rb') as in_csv, open(output_filename , 'wb') as out_csv:
            writer = csv.writer(out_csv, delimiter='\t')
            reader = csv.reader(in_csv, delimiter='\t')
            process(reader, writer)
    except IOError as e:
        print >> sys.stderr, "Error: cannot open file"
        if e.errno == errno.EACCES:
            print >> sys.stderr, "\tPermission denied."
            print >> sys.stderr, "\tError message: {0}".format(e)
            sys.exit(1)
        # Not a permission error.
        print >> sys.stderr, "\tError message: {0}".format(e)
        sys.exit(1)
    except Exception as other_exception:
        print >> sys.stderr, "Error: " + str(other_exception)
        sys.exit(2)

if __name__ == '__main__':
    main('in_file.csv', 'out_file.csv')


Your code is odd in the sense that it is going to a lot of effort to calculate that 103 is 1000.

I understand why you are doing it, but I took the liberty of changing the count() terminating function and replacing it with:

StringBuilder sb = new StringBuilder();

.......
.forEachOrdered(prod -> sb.append(prod.toString()).append("\n");

This way we can store each result, instead of just counting it.

There are a few things to go through here.

Product

This class looks awkward:

 .mapToObj(c -> (new Product()).A(a).B(b).C(c))

Why not just have a useful constructor on Product like:

    public Product(int a, int b, int c) {
        super();
        this.a = a;
        this.b = b;
        this.c = c;
    }

Then, your mapping would look like:

 .mapToObj(c -> new Product(a, b, c))

Magic Numbers

You have 0 and 9 as magic numbers in multiple places. These should be declared as (effective) constants, or calculated somehow. With the 9 value especially, if you want to change the size of the product you have to change it in three places.

int vs. Integer

You start off with an IntStream, but then convert it to a Stream<Integer>. Why? If you can leave things as primitives, you should.

The actual stream

The most concerning aspect is the stream itself.

The flatMap operation is not doing what I think you think it does....

Let's consider the contents of the stream as it goes through things:

'a' range from 0-9 IntStream
convert each int to an Integer
for each Integer, flatMap that Integer
the flatMap creates an IntStream which it converts to a Stream
even though we are flatMapping the 'a' value, we are not using the 'a' value in the mapping. All we are really doing is creating a new 'b' value, and who cares that the stream now has the b values streaming through....
with these 'b' values on the stream, we then flatMap again....
again, we ignore what the actual 'b' value is, abut we generate a new 'c' value in a third nested stream, and then we combine the 'a' and 'b' values which are 'in scope', with the 'c' value from the stream, and we make a Product.

The point of what I am saying is that you actually are only using the Stream in the most inside IntStream, the 'c' stream. All the other streams are just 'tokens' that you need to count the events you are doing. A for-loop is the right thing for this construct (if it was not for the parallelism). If you include the parallelism, then a fork-join process is right. Not a stream.

My Attempt

I am not claiming this is right, or best practice, but consider this attempt to get essentially the same result as you:

/** Append an int to an array after the last array item **/
public static final int[] append(int[] base, int val) {
    int[] ret = Arrays.copyOf(base, base.length + 1);
    ret[base.length] = val;
    return ret;
}

/** Stream an int range and map to an appended array */
private static final Stream<int[]> appendInts(int[] base, int size) {
    return IntStream.rangeClosed(0, size).mapToObj(a -> Cartesian.append(base, a));
}

public static void main(String[] args) {

    final int last = 9;
    final StringBuilder sb = new StringBuilder();
    IntStream.rangeClosed(0,last) /* 0 <= A <= 9 */
             .parallel()
             .mapToObj(a  -> new int[]{a})
             // stream is int[1] array
             .flatMap(ab  -> appendInts(ab, last))
             // stream is int[2] array
             .flatMap(abc -> appendInts(abc, last))
             // stream is int[3] array
             .forEachOrdered(res -> sb.append(Arrays.toString(res)).append("\n"));;
    System.out.println("Enjoy your Cartesian product." + sb.toString());
}

Update

I have rewritten the OP's code to extract the stream preparations. Consider the following code:

    // convert two input values to a stream consisting of an arrays of int
    BiFunction<Integer, Integer, Stream<int[]>> stage3 = (a,b) -> {
        return IntStream.rangeClosed(0, last).mapToObj(c -> new int[]{a, b, c});
    };

    // convert an input value to a stream consisting of an arrays of int
    Function<Integer, Stream<int[]>> stage2 = a -> {
        Stream<Integer> s = IntStream.rangeClosed(0, last).boxed();
        Stream<int[]> ret = s.flatMap(b -> stage3.apply(a, b));
        return ret;
    };

    IntStream.rangeClosed(0,last) /* 0 <= A <= 9 */
            .parallel()
            .boxed()
            .flatMap(a -> stage2.apply(a))
            .map(r -> Arrays.toString(r))
            .forEachOrdered(System.out::println);

Which is essentially what the OP's code does.


It's weird that you offer two public functions: a general-purpose convertToDecimal(), and a calculateDecimalCharacterValue() that does the same thing but with more restrictive validation.  The latter should be a private helper function.

You are over-complicating things by a lot: the whole thing could be accomplished with Integer.parseInt(s, radix).  And — not that you would need it — calculateDecimalCharacterValue(c, base) could be done using Character.digit(ch, radix).

Technically, you aren't converting to and from decimal (base ten).  You are parsing numbers in a base-N representation to an int; it just happens that ints are conventionally formatted in base ten when you do things like System.out.println().  So, the function names aren't quite right.

You shouldn't need to use Math.pow().  The usual algorithm goes like this:

public static int convertFromBase(int base, String input) {
    // Validation omitted here...

    int result = 0;
    for (char c : input.toCharArray()) {
        result = result * base + Character.digit(c, base);
    }
    return result;
}


Some ideas:

Properly indent your code and strictly adhere to some style guide. (For example it's very uncommon to have class name starting with a lowercase letter.) I recommend you to read some style guide or study the code of some publicly available libraries. This is very important for readability and future maintainability of your code. It doesn't matter if you will be reading it or somebody else. Code is written once but read many times.
Define a custom class for vectors. (Having a function with 6 arguments is inconvenient and error prone and it is a signal for looking for alternative solutions).
Use this class to implement vector operations on it.
Variables that aren't modified should be declared val.
side could be made local to the index method.
center can be precomputed and reused.
Instead of modifying variables when computing adding a node, it's often more idiomatic to describe the new cell declaratively. Using a helper function can shorten the code.
Optimize recursive functions using tailrec, if possible.

After some refactoring:

case class Vector(x: Double, y: Double, z: Double) {
  def +(that: Vector) = Vector(this.x + that.x,
                               this.y + that.y,
                               this.z + that.z);
  def *(scalar: Double) = Vector(this.x * scalar,
                                 this.y * scalar,
                                 this.z * scalar);
}

class Octree(min: Vector, max: Vector) {
  val children: Array[Octree] = new Array[Octree](8)
  val center = (max + min) * 0.5

  def index(p: Vector): Int = {
    @inline
    def side(x: Double, y: Double): Int =
      if (x < y) 1
      else 0
    (side(center.x, p.x)) |
    (side(center.y, p.y)<<1) |
    (side(center.z, p.z)<<2)
  }

  @annotation.tailrec
  final def add(point: Vector): Octree = {
    var i = index(point)
    debug(i)
    if (children(i) == null) {
      @inline
      def pick(b: Int, f: Vector => Double, l: Vector, r: Vector): Double =
        if (b == 0) f(l)
        else f(r)
      def split(v1: Vector, v2: Vector): Vector =
        Vector(pick(i & 1, _.x, v1, v2),
               pick(i & 2, _.y, v1, v2),
               pick(i & 4, _.z, v1, v2));
      children(i) = new Octree(
        split(center, min),
        split(max, center));
      children(i)
    } else
      children(i).add(point)
  }

  @annotation.tailrec
  final def find(p: Vector): Octree = {
    var i = index(p)
    debug(i)
    if(children(i) == null)
      this
    else
      children(i).find(p)
  }

  private def debug(message: => Any) {
    // if you comment out the print statement, `message`
    // won't be evaluated, so even if it's computationally intensive,
    // you don't need to comment out `debug` from the code.
    print(message.toString)
  }
}


A few things to point out in retrospect:

There's inconsistent quotation marks everywhere
Lines like the following are confusing and hard to read: print_result += key + ':' + ratioPopulation[key] + ' '
These (throw) should be throw new Error as it includes a stack trace.
Don't use snake case (temp_drawn) use camel case (tempDrawn)
Be careful about using truthy value checks like (population.length % drawAmount != 0) as it can cause issues relating to booleans, for example false == 0 will return true, but false === 0 will return false. See Truthy and Falsy: When All is Not Equal in JavaScript for more information and examples.
run doesn't match the case of the other functions, it should be Run.
k < ratioPopulation[populationName];: declare the length as a variable within the for loop as it gets rid of the constant length checking which can strain when you have a really large array.
You should consider using an array here instead var final = {}; as it may reduce logic on the loops.


Function to convert strings from hmmss, mmss, ss format to milliseconds

Use const instead of let if the variable is not being reassigned.

You can do away with the millis variable if you return early throughout the switch statement. This also allows you to remove the break statements.

hhmmssToMillis(hhmmss) {
    const time = hhmmss.split(':').reverse();
    switch(time.length) {
       case 1:
         return parseInt(time[0]) * 1000;
       case 2:
         return (parseInt(time[1]) * 60 + parseInt(time[0])) * 1000;
       case 3:
         return (parseInt(time[2]) * 60 * 60 + parseInt(time[1]) * 60 + parseInt(time[0])) * 1000;
    }
    return 0;
}


Returning nested array with added key=>value

You could try something along these lines:

function add_tax($data){
        foreach($data as $product => $details) {
            $data[$product]['tax'] = 0;
        }
        return $data;
}

EDIT 1:

After a bit more researching on foreach I have come up with the following alternative:

function add_tax(&$data) {
    foreach($data as &$details)
        $details['tax'] = 0;
}

In reference to Alex L: I apologize, the original answer was rushed. The first snippet was simply a way of answering the question, that yes, it is possible to iterate through $data without generating a new variable. Also, to MikeiLL, yes, that would be a waste of memory. This second snippet passes both variables by reference, which does not require any excess usage of memory. It is the most optimal format of this process.

NOTE: The unset in the function is not exactly necessary, but as your question referenced memory usage, unset breaks the reference and releases that memory.

EDIT 2:

Due to very strong backing in the comments, I've removed the call to unset (truth be told I'd never use it myself, but wanted to reference it's usage within the function)


You need to:

Get the annotated signature of a target_class' __init__ method;
Apply whatever arguments come from the provided JSON string;
Check that all arguments are present;
Check that all arguments conform to the annotations of the class' __init__.

All except the last step is pretty straightforward using the inspect module:

import json
import inspect
from typing import Callable, Any, T

def deserialize_json(target_class: Callable[[Any], T], object_repr: str) -> T:
    data = json.loads(object_repr)
    signature = inspect.signature(target_class)
    bound_signature = signature.bind(**data)
    bound_signature.apply_defaults()
    return target_class(**bound_signature.arguments)

inspect.Signature.bind validate arguments pretty much the same as a real call to target_class.__init__ would; raising TypeError if a positionnal argument is missing or if an extra keyword argument is found.

Now you "just" need to validate the type of the arguments based on the annotations. A simple but potentially sufficient way of doing would check the annotation attribute of each parameter of the Signature and check it is the right type using isinstance:

def deserialize_json(target_class: Callable[[Any], T], object_repr: str) -> T:
    data = json.loads(object_repr)
    signature = inspect.signature(target_class)
    bound_signature = signature.bind(**data)
    bound_signature.apply_defaults()

    for name, value in bound_signature.arguments.items():
        expected_type = signature.parameters[name].annotation
        if not isinstance(value, expected_type):
            raise TypeError('<error message>')

    return target_class(**bound_signature.arguments)

Note that this simple example would most likely have troubles validating Generic types or parametrized Generic types. Adapting the code to fit those needs is left as an exercise for the reader (but Python 3.7 have better support for such checks).

As a side note, if all target classes ressemble the Foo example, and you don't mind having them immutable, you can make use of typing.NamedTuple:

class Foo(typing.NamedTuple):
    val: int
    msg: str
    frac: float = 1.0

print(Foo(1, 'bar'))  # Foo(val=1, msg='bar', frac=1.0)
print(Foo(2, 'baz', 0.0))  # Foo(val=2, msg='baz', frac=0.0)
print(Foo(3))  # TypeError: __new__() missing 1 required positional argument: 'msg'

or switch to Python 3.7 and use full-blown dataclasses.


Equalized PRNG number distribution - Part 2

Input validation

You shouldn't just change the user input if it is wrong. If a user calls var random_number = new RNG( 10, 19.9 ); they will expect to get number between 10 and 19.9. But that's not what they will get, because their assumption is wrong (your random number generator only generates integers). A user should be informed about this, instead of just silently correcting their wrong assumption.

Regarding I've completely ignored it to keep my code a little DRY and to improve performance: Are you sure that there is a performance problem? Because it doesn't seem like it (instantiating a new RNG is something that probably isn't done all that often), and the code is quite hard to read because it does too many things (changing data and comparing data), and it uses tricks (shifting instead of casting), which is generally not recommended, as it hurts readability.

Array Generation

This:

                for( var i = 0; i <= max - min; i++ )
                {
                    avail[i] = min + i;
                }

Would be a more natural and easier to read written as this (you can immediately see if min and max are inclusive or not:

                for( var i = min; i <= max; i++ )
                {
                    avail[i] = i;
                }

Comments

It's good that you added comments (although using a bit less tricky code would probably reduce the need for some comments in the first place).

But this comment is a bit misleading: //returns a random element between 0 and avail.length (excluded): The next line also changes the array, something the comment doesn't mention at all. I would rewrite it as removes and returns random array element (you don't need the range, as its from the complete array, which makes sense).


for_each_cons and for_each_slice, variants of std::for_each working on sliding windows

The two main issues I see are that

You require RandomAccessIterators although these should be implementable with ForwardIterators as well since you never have to skip an element.
This will fail for functors with an overloaded or templated operator() such as those with auto parameters

Also, what happens if the range's length isn't divisible by the step size in the second case?

As 2 isn't really possible to solve since in the overloaded case there may be multiple valid values for n_args you could allow the user to pass the number of arguments as a first parameter. You could then default that value to 0 (which is never valid) and infer the number of parameters as you currently do if it is set to 0.


Non-recursive approach:

# Binary search in a non-empty sorted array
def bin_search(a, val):
    l = 0
    r = len(a)
    # Trying to find val in a[l:r]
    while r - l > 1:
        m = (l + r) // 2
        if a[m] > val:
            r = m
        else:
            l = m
    return a[l] == val


Indents
PEP 8: Use 4 spaces per indentation level.

Main game loop
The way your game loop is set up now is a bit unelegant. You already implemented all the methods to be able to handle both players, there's only one piece missing:
from itertools import cycle

players = cycle(['X', 'O'])

cycle will provide a generator that infinitely repeats the iterable you pass it. This makes the loop quite a bit cleaner:
while not tictactoe.game_over():
    tictactoe.print_board()

    player = next(players)
    move = tictactoe.get_player_move(player)
    tictactoe.select_space(move, player)

I'd also suggest renaming select_space to something like do_move. Makes it a bit clearer what's going on.

Redundant calls to Tictactoe.available_moves()
In game_over and get_player_move you call self.available_moves() once without using the return value in any way. You can simply delete those lines.

game_over
The pattern
if self.has_won("X") or self.has_won("O") or len(self.available_moves()) ==0:
    return True
else:
    return False

can be simplified to
return self.has_won("X") or self.has_won("O") or len(self.available_moves()) == 0

What you were doing is basically manually returning the resulting bool value of a condition. We can instead simply return the condition directly.

print_board
Python lets you easily avoid an unelegant pattern
print("|    " + self.board[0][0] + " " + self.board[0][1] + " " + self.board[0][2] + "    |")

by using the * operator for unpacking an iterable
print("|   ", *self.board[0], "   |")

Since we need to do this for all rows in self.board we should let Python handle it for us as well:
for row in self.board:
    print("|   ", *row, "   |")

has_won
For a cleaner implementation of this method I would suggest implementing helper functions that provide lists of the rows, columns and diagonals of the board. They might also be useful for future feature additions.
def rows(self):
    return self.board[:]  # creates a mutable copy of the rows

def columns(self):
    return [[row[index] for row in self.board] for index in range(3)]

def diagonals(self):
    first = [self.board[index][index] for index in range(3)]
    second = [self.board[index][len(self.board[index]) - index - 1] for index in range(3)]
    return [first, second]

These methods are also ready to be used for boards of different sizes. Simply replace the 3s by a variable.
has_won is now a lot simpler and more readable:
def has_won(self, player):
    for line in self.rows() + self.columns() + self.diagonals():
        symbols = set(line)
        if player in symbols and len(symbols) == 1:
            return True

    return False

We can take this a step further (as pointed out in the comments) and change has_won to get_winner and return the winning symbol. This will also affect some other parts of your code:
class Tictactoe:
def get_winner(self):
    for line in self.rows() + self.columns() + self.diagonals():
        symbols = set(line)
        if len(symbols) == 1:
            return symbols.pop()

    return None

def game_over(self):
    return self.get_winner() is not None or len(self.available_moves()) == 0

Printing our winner in game:
def game(...):

    # main gameplay here

    if (winner := self.get_winner()) is not None:
        print(f"{winner} wins")
    else:
        print("tie")


Implementing a copy on write String class using reference counting in C++

Code simplification

mystring acts essentially as a smart pointer. It's already implemented in the standard library. You can use the std::shared_ptr class. This way, mystring can just have an std::shared_ptr<std::string> as a member. The default copy constructor, assignment operator and the desturctor will work properly.

Use of non-standard features

char cpy[strlen(ptr->pRC->str)+1]

variable sized arrays are not a part of the standard C++. Don't use them. If you need it, you should allocate it dynamically.

If you use the std::shared_ptr<std::string> as I said above, it'll be even simpler as std::string has a proper copy constructor.

Index

It's conventional to use size_t, not int as an index type (at least that's how an std::string works).


Unit of Work and Repository with Entity Framework 6

I've never TDD'd, but don't do that:

public class MyDataContext<T> : DbContext where T : class

This gives you a context-per-entity, which might work for ultra-simplistic CRUD scenarios, but doesn't scale very well and will quickly give you headaches as soon as you need to deal with more than a single entity type in a single transaction - because that's what a unit-of-work encapsulates: a transaction.

DbContext is a unit-of-work, and IDbSet<T> is a repository; they are an abstraction; by wrapping it with your own, you're making an abstraction over an abstraction, and you gain nothing but complexity.

This blog entry sums it up pretty well. In a nutshell: embrace DbContext, don't fight it.

If you really want/need an abstraction, make your DbContext class implement some  IUnitOfWork interface; expose a Commit or SaveChanges method and a way to get the entities:

public interface IUnitOfWork
{
    void Commit();
    IDbSet<T> Set<T>() where T : class;
}

Then you can easily implement it:

public class MyDataContext : DbContext, IUnitOfWork
{
    public void Commit()
    {
        SaveChanges();
    }
}

I don't like IEmployeeService either. This looks like an interface that can grow hair and tentacles and become quite a monster (GetByName, FindByEmailAddress, etc.) - and the last thing you want is an interface that needs to change all the time.

I'd do it something like this, but I'm reluctant to use the entity types directly in the views, I'd probably have the service expose EmployeeModel or IEmployee instead (see this question for more details - it's WPF, but I think lots of it applies to ASP.NET/MVC), so as to only have the service class aware of the Employee class, leaving the controller and the view working off some IEmployee implementation, probably some EmployeeModel class, idea being to separate the data model from the domain model.

public class EmployeeService
{
    private readonly IUnitOfWork _unitOfWork;

    public EmployeeService(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    IEnumerable<Employee> GetEmployees()
    {
        return _unitOfWork.Set<Employee>().ToList();
    }
}


Calculate the Degrees of a Clock Hand Based on Input Time

Currently your code has user input, calculation and output all mixed up. This is OK as a first step (your code works, yay!), but the next step should be separating the calculation from the IO part. For this a simple function which takes the input already as parsed numbers will do:

def clock_angles(hour, minute, second):
    """Convert the time in hour, minute, second into angles of clock hands
       on a 12 hour clock, in degrees."""
    if hour >= 12:
        hour -= 12
    assert 0 <= hour < 12 and 0 <= minute < 60 and 0 <= second < 60
    degrees_per_hour = 360 / 12
    degrees_per_minute = degrees_per_second = 360 / 60
    return (hour * degrees_per_hour,
            minute * degrees_per_minute,
            second * degrees_per_second)

It even has a docstring describing what it does and some simple input validation.

Your IO can then be wrapped under a if __name__ == "__main__": guard which ensures it is not being run when you import from this script from another script. You can also use a f-string to make formatting the output slightly easier.

if __name__ == "__main__":
    input_time = input("Please input a time (HH:MM:SS): ")
    hour, minute, second = map(int, input_time.split(":"))

    hour_angle, minute_angle, second_angle = clock_angles(hour, minute, second)
    print(f"When the time is {input_time} the hour hand is at {hour_angle}°, the minute hand is at {minute_angle}° and the second hand is at {second_angle}°.")

I included the second hand here. Being able to parse the input without the seconds is left as an exercise.


I actually quite like this pattern and use it relatively often. I'm not sure if there is something better than functors for this - if there is, I'm not really aware of it. That being said, with C++11, I'd write this in a slightly different way:

struct num {
  int val;

  const num& operator +=(const num & rhs) {
    return op_equals(rhs, std::plus<int>());
  }

  const num& operator -=(const num & rhs) {
    return op_equals(rhs, std::minus<int>());
  }

  template <typename op>
  const num & op_equals(const num & rhs, op&& o) {
    val = o(val, rhs.val);
    return *this;
  }
};

Note the rvalue reference (which is actually a "universal reference", so can bind to either an lvalue or rvalue reference), and the movement of op to a parameter - I don't really like having to specify it as a template parameter which then gets instantiated and called in the function. I think this way is slightly cleaner.


Initializing an array of string constants, and another constant array of the equivalent lengths

To expand on my comment, the X macro technique can be used for this. See here, for example
The idea is that we define the list once, for example
#define STRINGLIST \
X( "alice") \
X( "bob") \
X( "cat")

When we want to use this list, we invoke the above macro, having defined the macro X:
static const char *const DStr[] = {
#define X(S) S,
STRINGLIST
#undef X
};

static const unsigned short DLen[] = {
#define X(S) sizeof( S)-1,
STRINGLIST
#undef X
};

This way we only have to define the strings once, and guarantee that the arrays DStr and DLen are in the same order. The disadvantage is that it looks pretty bizarre first time you see it, and others maintaining your code might be boggled.


Use an optionally passed-in block without repeating yourself

Some notes:

select {... }[0] -> detect { ... }.
Is LOCATION a string? Then, "#{LOCATION}" -> LOCATION
Use File#join instead of manual string manipulation.
The only repetition in your code is File.open("#{LOCATION}/#{file_name}"). The solution is very simple: create a local variable and use it.
Don't you check whether file_name is nil?
File#open accepts a block, why don't you simply pass it? you get the file descriptor closed for free in the block case.

I'd write:

def file_from_pattern(pattern, &block)
  file_name = Dir.entries(LOCATION).detect { |f| f =~ pattern }
  if file_name
    # Refactor 1:
    # fd = File.open(File.join(LOCATION, file_name))
    # block_given? ? yield(fd) : fd
    File.open(File.join(LOCATION, file_name), &block)
  end
end


Convert bitcoin value based on exchange rate from JSON API

My take is that there is no harm in adding a few named functions. Also it is probably better to ignore the result of setting a standard .net property.

open System
open System.Net
open Newtonsoft.Json.Linq

let downloadPriceInfo () =
    let client = new WebClient()
    client.DownloadString("https://blockchain.info/ticker")

let getPriceOfEuro (price: JObject) = float (price.["EUR"].["buy"] :?> JValue)

let euroToBtc euro = 0.1234567 * euro

let btcOfEuro =
    downloadPriceInfo ()
    |> JObject.Parse
    |> getPriceOfEuro
    |> euroToBtc

printfn "%s" (btcOfEuro.ToString("N"))


Realy, dud its childish!

only ones:

lenf = len(folder)

just one 2d array:

len_types = 12
arr = np.zeros([lenf ,  12])

learn how to work with numpy arrays, you will avoid the loop as well. And for example the mean can be done in one line for 2d array:

means = np.mean(arr, axis = 1)

https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html


Printing integers with spaces between the digits

// Variable declaration

  int number; // User entered number to digitize
  int power;  // Power to generate divisor

So // is a C++ comment that is only available in newer versions of C.

Declaring variables at the beginning of the block is an old C standard that you don't need in newer versions of C.  The modern standard (in C and most other languages) is to put variable declarations as close to first use as possible.  For number, you're pretty much there.  For power, it could be declared with the  initialization.

    /* Power to generate divisor */
    int power = getNumLength(number);

I put the comment on a separate line so as to be more readable and to avoid side scroll (not so much here as in other examples).

I would have probably have written that

    int digit_count = count_digits(number);

That's clearer in my opinion and does not require an explanatory comment.  We're counting the number of digits and storing the result in a variable.  We'll know what the variable is later, because we call it digit_count.

I prefer snake_case, particularly in C.  It relies less on the reader (who may not be a native English speaker) being able to recognize capital letters.  That said, camelCase is quite common.  Which to use is up to you so long as you do so consistently.

I also changed to a four column indent.  That is more common than two column in code.  The only place that I'd recommend two column is in markup languages like HTML and XML.  They don't have methods, so their indent increases with their complexity.  With code, if you are indenting so much that you are running out of space on the screen, that may be a sign that you should push code into separate functions or methods.

An alternate approach

  int divisor; // the divisor from power
  int i;  // loop counter

  for(i = power - 1; i >=0; i--)
  {
    divisor = (int)pow(10, i);
    printf("%d  ", number / divisor);
    number = number % divisor;
  }

You are using the rather expensive pow function in each iteration of your for loop.

Consider

    for (int divisor = buildInitialDivisor(number); divisor > 0; divisor /= BASE) {
        printf("%01d  ", number / divisor);
        number %= divisor;
    }

This declares the loop variable as part of the loop declaration.

This uses a constant BASE instead of the magic number 10.  This improves readability and makes the program easier to modify.

I changed from %d to %01d.  Now if you wanted to display, say, two digits at a time, you could change that to %02d and change BASE to 100.  It should zero pad the number so as to always print two digits.  Of course, it would print a single leading digit as two digits too.  That might be undesirable.  You might consider how you could fix that.

The %= is just a shorter syntax.  Your original line and the revised one will do the exact same thing.  Assignment operators in C.

This gets rid of pow and replaces it with a different function and then divides on each iteration.

This gets rid of your i variable which only tracked the number of iterations.  We can do that directly.

I prefer to always put the curly brackets on the same line as the code structure.  Either form is fine so long as you are consistent.  But you'll see both as you go, so might as well start recognizing them now.

This also requires

const int BASE = 10;

and

int buildInitialDivisor(int number) {
    int divisor = 1;
    while (number / BASE >= divisor) {
        divisor *= BASE;
    }

    return divisor;
}

But it gets rid of your getNumLength function.

Recursion

You may not have gotten there yet, but when you get to recursion, you might try this problem again.  Recursion often helps when you need to reverse the natural order of output.  This is because you can display while returning from the recursion.  So rather than building the largest divisor first, you can incrementally increase the size of the divisor (or better yet, decrease the number, always using the same divisor).

You also might try this again after learning sprintf and character arrays.


Method for getting the DataTable when having connection ID and the SQL command

Like janos already stated it is ok to return out of an using block.
Naming
Based on the naming guidelines, method names should be named using PascalCase casing. So getData2 should become GetData2 which should be still renamed to a more meaningful name.
Also input parameters should be named using camelCase casing, so connection_string_id should become connectionStringId.
If you are sure, that there will only be 1 table, you can also use the overloaded Fill() method which takes a DataTable as input parameter.
You could also stack the usings, but this is a matter of taste.
using (SqlConnection con = new SqlConnection(connstring))
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd, con))
{
    con.Open();
    DataTable dataTable = new DataTable();
    adapter.Fill(dataTable);
    return dataTable ;
}

In my opinion, your code does a little bit to much.

Retrieving the ConnectionString
Query the database

So let us add a method to retrieve the ConnectionString, which is then passed to the Getdata2() method.
private String GetConnectionString(String connectionStringId)
{
    return ConfigurationManager
        .ConnectionStrings[connectionStringId].ConnectionString;
}

public DataTable GetData2(String connectionString, String sqlCommand)
{

    using (SqlConnection connection = new SqlConnection(connectionString))
    using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand, connection))
    {
        con.Open();
        DataTable dataTable = new DataTable();
        adapter.Fill(dataTable);
        return dataTable ;
    }
}

To answer when to use using: use it if the related object implements the IDisposable interface.


Is there a way to make this code simplier?

Performance The biggest issue with your current implementation is that it's O(n ^ 2). You have to iterate through an array of length N (N ^ 2) / 2 times in order to find matches. The algorithm can be improved by iterating only once, and by using a Set or an object when iterating to store which number the current number would have to be paired with in order to sum to the target.
For example, when iterating over 1, with a target of 5, you could put 4 into the Set, because 1 + 4 === 5. On further iterations, check to see if the element being iterated over exists in the Set. If it does, it's a match: return the pair. See bottom of answer for an implementation.
Prefer const over let Since N isn't being reassigned, declare it with const: https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6
Don't create global variables Always declare variables before using them. Your current code with for(i=0;i<=N-1;i++) and for(j=i+1;j<=N;j++) { is implicitly creating global i and j variables. This is both inelegant and can lead to confusing bugs if the function gets called again before its first call completes. (Also consider adding spaces between operators for readability). You'd want to do:
for (let i = 0; i < N; i++) {

Note the use of i < N, not i <= N; since N is the length, nums[N] will be undefined, so you shouldn't iterate over it.
Use strict equality Don't use == - it has many strange rules with type coercion. Even if you're sure the types of the operands are the same, to make it clearer for readers at a glance, better to avoid it and use === or !== instead.

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
const twoSum = function(nums, target) {
  // Key: Number which, if found, matches the number at the index value
  // eg: { 3 => 6 }: if 3 is found later, it'll be a match with the number at index 6
  const indexByPair = new Map();
  const { length } = nums;
  for (let i = 0; i < length; i++) {
    if (indexByPair.has(nums[i])) {
      return [indexByPair.get(nums[i]), i];
    }
    indexByPair.set(target - nums[i], i);
  }
};
console.log(twoSum([2,7,11,15], 9));


Several things can be improved in your existing code. First and foremost being, replacing your usage of re module. Regex matching is very heavy. You have a defined set of characters being replaced. Use str.replace or str.translate.

You have provided comments aptly throughout the program. However, you can place them as docstring for the function, including the examples as doctests. There are several syntaxes to format docstrings. I am mostly aware of epytext and reStructuredText. You can search around for other common formats :).

You'll end up with:

"""
Word Counter

Given an body of text, return a hash table of the frequency of each
word.
"""

def word_count(sentence):
    """
    Word Counter

    Given an body of text, return a hash table of the frequency of
    each word.

    ..  warnings::

        - Capital and lower case versions of the same word should be counted

    as the same word.

        - Remove punctuations from all words.

    ..  note::

    Where N is the number of characters in the string.

        - Time: O(N)

        - Space: O(N)

    :Example:

    >>> word_count('The cat and the hat.')
    {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
    >>> word_count('As soon as possible.')
    {'as': 2, 'soon': 1, 'possible': 1}
    >>> word_count("It's a man, it's a plane, it's superman!")
    {'its': 3, 'a': 2, 'man': 1, 'plane': 1, 'superman': 1}

    :param sentence: Input string
    :type sentence: str

    :return: Returns hash-table of frequence of each word in input
    :rtype: dict
    """

    translate = sentence.maketrans({char: None for char in "'.,:*!"})
    cleaned_words = sentence.lower().translate(translate).split()
    word_counter = {}
    for word in cleaned_words:
        if word in word_counter:
            word_counter[word] += 1
        else:
            word_counter[word] = 1
    return word_counter

You can also make use of collections.counter which has the same complexity as your current code. However, it also provides a few extra features on the resulting counter object, such as most_common.

The referenced links above are for python-2.7; however all the modules/packages are available in python 3.x


Single Linked List JavaScript implementation

This doesn't appear to function correctly right now so it may actually belong on Stack Overflow rather than on Code Review.

Regardless, here are the issues I'm seeing:

When you attempt to add values to the head of the list, they instead are getting added to the tail of the list since the head of the list is always null. The new value should always end up as the head of the list when it is added to the head of the list.
Your code is a bit visually confusing since you are using this to refer to 2 different objects in the same code block.
You are only incrementing the count of the list's elements inside the part of the addToHead which is unreachable, resulting in a count of null regardless of what you do. Instead the count should be incremented on any add interaction.
There doesn't seem to be an interaction to remove an item from the list, either front or back. Being able to remove items from the list is a core part of the functionality.

For the full definition of what a singly linked list needs to support, see this page.


When we are discussing performance of a particular piece of code, it's important to recognize bottlenecks and major contributors to the runtime of the program.

In your particular case, even though you've applied some optimizations like SoupStrainer speed-up for HTML parsing, the synchronous nature of the script is the biggest problem by far. The script is processing pages one by one, not getting to the next page until the processing for the current page is finished.

Switching to an asynchronous approach would be the natural next step in your optimizations. Look into using third-party frameworks like Scrapy or, if you are adventurous, things like asyncio or grequests.

You could apply one more optimization to your current script which should help you optimize the "crawling/scraping" part - instead of using requests.get(), initialize session = requests.Session() and use session.get() to make requests (documentation). This would allow the underlying TCP connection to be re-used for subsequent requests resulting in a performance increase.


Reading Database, scraping Barchart and uploading prices to DB

Python review

This could make better use of docstrings and functions; for example, your comment about the Quote class should be a well-formatted docstring instead. Additionally, each of your different comment blocks would be best suited as a function, and then piece them together inside of a __main__ block.

I would also do my best to remove any of your magic values, and instead use constants. This makes it easier if they come from somewhere else (e.g. a config file, or somewhere on the database) to adjust.

When formatting, prefer str.format over % formatting. If you're on a high-enough Python version, f-strings are even nicer.

This line is very magic: for x in range(3,len(row)). I would strongly prefer that you document what is going on here using non-magic numbers (and maybe a code comment). I think that what you're doing is getting the value from every column after the first 4; if that is what you're doing, then

Improving the SQL query is good to do here (see #1 in the SQL review below)
There are better variable names to use here

Generators are a good thing to use, as are list comprehensions. You can also use tuple-unpacking to make trivial assignments easier.

Instead of iteratively building a string, which performs poorly, use str.join. Similarly, instead of repeatedly list.appending, use list.extend or a list comprehension.

Instead of cascading your if/elif/else, use a dictionary and a default value.

SQL review

In general, your SQL is pretty straightforward so there isn't a ton to say. Overall, you should:

When SELECTing something, only get what you need. SELECT * should always be considered suspect.
Avoid embedding raw SQL in your source code; if the desired behavior ever changes, now you're needing to update this code for no reason. A stored procedure (or table-valued function) is likely going to be a better option.
Always use your language/libraries tools for parameterizing SQL; you seem to switch back and forth between this and using string formatting. Always remember that no input is trusted, even if it comes from your own database.
Instead of inserting VALUES row-by-row, investigate if there is a bulk INSERT option for your library. If not, consider other options (as row-by-row is going to perform poorly)
Consider deleting and inserting in a single commit so as to avoid leaving the database in an unusual state in-between operations.

Updated code

I came up with the following updates (that assume you have created the appropriate stored procedures, and I didn't bother with fully making all literals constants). I think there are a few more places for improvement here; for example, some of the formatting you do before instantiating the class could be done in the class itself (for example, a property that returns the formatted value, or a setter on that property that sets it in a formatted way). I also think you could likely break this up into a few more classes if you really wanted to make it OOP, but that is probably overkill for your use-case.
    """
    Gets barchart codes for a given year, then loads them into an array
    using BarChart's API. From there, the quotes are pushed to the database
    using the current date
    """

import datetime

import ondemand
import pyodbc

CONNECTION_STRING = "DRIVER={SQL Server};SERVER=MyComputer\\SQLEXPRESS;DATABASE=MarketDB"
API_KEY = "123"
END_POINT = "https://marketdata.websol.barchart.com/"
NAME_TO_CROP_MAPPING = {
    "Corn": (1, lambda price: price / 100),
    "Soybean Meal": (2, lambda price: price)
}
DEFAULT_CROP_MAPPING = (3, lambda price: price)

class Quote():
    """Stores the quotes as objects"""

    def __init__(self, seq_dimDate, symbol, month, year, price, crop, ficalYear):
        self.seq_dimDate = seq_dimDate
        self.symbol = symbol
        self.month = month
        self.year = year
        self.price = price
        self.crop = crop
        self.fiscalYear = ficalYear

def get_today_formatted():
    return datetime.datetime.now().strftime("%m/%d/%Y")

def get_sequence_date(cursor):
    now = get_today_formatted()
    row = cursor.execute("EXECUTE dbo.RetrieveDateAndFiscalYear @dateFilter = ?", now).fetchone()
    return (now, dateRow.Sequence, dateRow.FiscalYear)

def get_codes(cursor, fiscal_year):
    FIRST_CODE_INDEX = 3

    all_codes = cursor.execute("EXECUTE dbo.RetrieveBarchartCodesByYear = ?", fiscal_year)
    for row in all_codes.fetchall():
        for code in range(FIRST_CODE_INDEX, len(row)):
            yield row[code]

def get_date_from_timestamp(timestamp):
    date = datetime.datetime.strptime(timestamp, '%Y-%m-%dT00:00:00-%H:%M')
    return (date.month, date.year)

def get_quotes(od_connection, seq_dim_date, fiscal_year, quotes_to_query):
    raw_quotes = od_connection.quote(quotes_to_query)["results"]

    for raw_quote in raw_quotes:
        symbol = raw_quote["symbol"]
        month, year = get_date_from_timestamp(quote["tradeTimestamp"])
        base_price = q["lastPrice"]

        crop_id, adjusted_price = get_crop_sequence(q["name"], base_price)

        yield Quote(seq_dim_date, symbol, month, year, adjusted_price, crop_id, fiscal_year)

def get_crop_sequence(crop, base_price):
    crop_id, price_adjustor = NAME_TO_CROP_MAPPING.get(crop, DEFAULT_CROP_MAPPING)
    return (crop_id, price_adjustor(base_price))

def update_invalid_prices(cursor, seq_dim_date, quotes):
    cursor.execute("EXECUTE dbo.DeleteHistoricalPricesByDate @Date = ?", seq_dim_date)

    for quote in quotes:
        cursor.execute("EXECUTE dbo.UpdatePricesForQuote <<Fill in your parameters here>>", <<Fill in your parameters here>>)

    cursor.commit()

    print(f"MarketPrice table cleared of records with Date Sequence {seq_dim_date}...")
    print("\n".join([f"{q.symbol} Uploaded to MarketPrice Table in Hedging2" for q in quotes]))

if __name__ == "__main__":
    sql_connection = pyodbc.connect(CONNECTION_STRING)
    cursor = sql_connection.cursor()

    now, seq_dim_date, fiscal_year = get_sequnce_date(cursor)
    print(f"Sequence for {now} is {seq_dim_date} with a fiscal year of {fiscal_year}"))

    quotes_to_query = ",".join(get_codes(cursor, fiscal_year))
    ondemand_connection = ondemand.OnDemandClient(api_key=API_KEY, end_point=API_END_POINT)
    all_quotes = list(get_quotes(ondemand_connection, seq_dim_date, fiscal_year, quotes_to_query))
    print(f"{len(all_quotes)} total Quotes Collected")

    update_invalid_prices(cursor, seq_dim_date, all_quotes)


Algorithm that receives a dictionary, converts it to a GET string, and is optimized for big data

Considered as an interview question, my response would be, "what do you mean by 'optimized for big data'?" Wikipedia says,

  Big data is a term for data sets that are so large or complex that traditional data processing applications are inadequate to deal with them

and it's not clear how this is related to the problem of converting a dictionary to a query string (which would normally be solved by calling urllib.parse.urlencode). So there seems to be a hidden requirement here. Or possibly the interviewer is confused. Either way, you need to go through the requirements capture and analysis process before starting to write code.


Is this login page safe and can it be optimized?

The first thing I spotted was this: control-painel.php. I'm not sure if that's an error with your page name or code, but whichever it is needs to be fixed.

  Can it be optimized?

The best optimisation is only doing what's necessary. When checking the login, you don't check whether they've even been specified until after you hash it, consider reordering it like so:

$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username))
{
    $user_error = 'Please insert a username';
}
if(empty($password))
{
    $pass_error = 'Please insert a password';
}
elseif(!$user_error) //Password can't be empty here, don't need to check again
{
    $cost = '11';
    $salt = 'Cf1f11ePArKlBJomM0F6aJ';
    $password_hash = crypt($password, '$2a$' . $cost . '$' . $salt . '$');
    $id = 0;
    $stmt = $mysqli->prepare('SELECT id FROM user WHERE username = ? AND password = ?');
    $stmt->bind_param('ss', $username, $password_hash);
    $stmt->execute();
    $stmt->bind_result($id);
    $stmt->fetch();
    if($id)
    {
        $_SESSION['username'] = $username;
        $_SESSION['email'] = $email;
        header('location: control-painel.php');
        die();
    }
    else
    {
        $login_error = 'User or Password invalid';
    }
}

So the hashing is only performed when you have a username and password.


Optimizing mathematical index calculation function

First, I do not know anything about PAWN.

Does it have a profiler? Can any profiler be used? If yes, probably use it.
If no, write at least some test units to measure execution time.

I will assume typical language elements. I will assume polygonid > 0 and Polygon_Size > 0, because I do not know (and did not find in short time) the behavior of / and % for negative numbers.

As far as I understood, there is a virtual machine between compiler and execution. This makes things a little bit more complex, but well, we will assume that nothing special happens there.

Some of the optimizations could change nothing, because the compiler already does it. I can not predict or test it.

That said, I will choose line after line. I do not know if you can change the algorithm, because like Cygal I do not understand the exact purpose.

new polid = (polygonid - (polygonid % 2));

This makes polid the next smallest even number? % is rather costly, you could either do a polygonid & 1 instead of polygonid % 2 or new polid = polygonid & (max_value - 1) which will set all bits, but the last one to zero. max_value - 1 should be precalculated.

new mid = Polygon_Size/2;

Change to: new mid = Polygon_Size >> 1 This will be done most probably by the compiler anyway, but we do not know, so lets try it.

polid /= 2;

This is calculated in both branches. It could help to do it before the branching:

new polid_half = polid >> 1;
...

return (mid - (++polid));

This depends on the language details. It could be that ++polid as preincrement operator will load polid, update it by one, and store polid back. We do not plan to use the modified polid, so we could try return (mid - polid + 1) assuming that ++polid is not some magic fast special instruction compared to the normal +.

    if(polid == 0)
    {
        return 0;
    }

This does only happen if polygonid is 0 or 1. If this happens a lot, you should return immediately at the beginning, saving all the rest:

if (polygonid < 2 )  //assuming polygonid > 0
    return 0;

And remove the check inside the else branch.

    return --polid;

Same as before, it could be better to return polid - 1

Depending on the branch prediction handling, it could be better to have only one return point, not one in every branch. You could introduce a return value and set it according to the current logic.

I would try one change after the next and profile every step. All together, it could be:

stock GetNodeIndexFromPolygonIndex(polygonid,Polygon_Size)
{
    if (polygonid < 2 )  //assuming polygonid > 0
        return 0;
    new result = 0;
    new polid = polygonid & (max_value - 1); //polid is a bad name
    new polid_half = polid >> 1;
    new mid = Polygon_Size >> 1;
    if(polid > mid)
        result = mid - polid_half + 1;
    else
        result = polid_half - 1;
    return result;
}


Fisher-Yates shuffle Java implementation

You are both mutating & returning the value you are passing to the function.  Pick one.   Either return void or return a new array/ArrayList without mutating the input.

Your first shuffle() method requires an ArrayList, yet any Collection which implements the List interface would work, and will work well if it has \$O(1)\$ get & set complexity.  So consider loosening the type from a concrete type to the List interface.  (It will even work for LinkedList, albeit with horrible performance, but working slowly is arguably better than not being able to work at all.)

The value returned by ArrayList<T>::set(int idx, T obj) is the previous contents of that location.  Therefor, the temporary is not necessary.

        T temp = a.get(index);
        a.set(index, a.get(n));
        a.set(n, temp);

can become:

        a.set(n, a.set(index, a.get(n)));

or more clearly, just Collections.swap(a, n, index);.

Similarly,

        T temp = a[index];
        a[index] = a[n];
        a[n] = temp;

can also become Collections.swap(a, n, index);, a similar function which takes a T[] instead of a List<?> as the first argument.

Here is an implementation of your "something like K<T> using generics" from the comments.  And no longer coding from the hip, so the Java syntax is actually correct.

MacBook-Pro:~ aneufeld$ jshell
|  Welcome to JShell -- Version 10.0.1
|  For an introduction type: /help intro

jshell> public class ShuffleTest {
   ...>   public static <T,K extends List<T>> K shuffle(Collection<T> a, Supplier<K> supplier) {
   ...>     K dup = supplier.get();
   ...>     dup.addAll(a);
   ...>     Collections.shuffle(dup);  // Or use your shuffle implementation
   ...>     return dup;
   ...>   }
   ...> }
|  created class ShuffleTest

jshell> var orig = List.of("Hello", "world");
orig ==> [Hello, world]

jshell> ArrayList<String> shuffled = ShuffleTest.shuffle(orig, ArrayList<String>::new);
shuffled ==> [world, Hello]

jshell>


Run length encoding of vectors in MATLAB: looped version and vectorized version

I'm not sure about the performance of my following code however I'm using tabulate() to do the job. As you can see, the loops for filtering elements not to compute the frequency of elements. In other words, you might want to look at tabulate() or hist() to compute the frequent occurrence of elements.

x = [20 13 12 12 12 18 17 16 16 11];
j = 1;
elems = []; % store repeated elements
for i = 1:length(x)
    if isempty(find(elems == x(i)))
        elems(j) = x(i);
        j = j + 1;
    end
end
elems
t = tabulate(x); % get frequency table
for i = 1:length(elems)
    lens(i) = t(elems(i),2); % get how many each element in elems vector occurs
end
lens

The result is

elems =
    20    13    12    18    17    16    11
lens =
     1     1     3     1     1     2     1


Low level string manipulation functions in C

condense_buffer is equivalent to strcpy. If you still wish to implement it, use an idiomatic C construct:

    while ((*p1++ = *p2++) != 0)
        {}

begins_with is equivalent to strncmp(text, key, strlen(key)). It might be argued though that strncmp approach requires a call to strlen and thus incurs performance penalty.
Do put the loop body on a separate line. Do not omit curly braces even for one-liners:

   for (char *end = p + strlen(p); end >= p; end--) {
       *(end + content_len) = *end;
   }


1. Review

Some of the variable names could be improved:

complex_plane is an array of \$z\$ values for each pixel in the image, so naming it z would help the reader relate it to the z in douady_hubbard_polynomial.

imaginary_axis and real_axis are only used once in the very next line, so there is no need for them to have long and memorable names. I would use something short like im and re.

result is an array of iteration counts, so it could be named something like iterations.

mask is a Boolean array selecting pixels that have not yet diverged to infinity, so something like not_diverged or live would convey this better.
On each iteration, the iteration counts of the escaped pixels are incremented. This means that some pixels get incremented many times, for example a pixel that escapes on the first iteration gets its count incremented 256 times. It would be more efficient to set the iteration count for each pixel just once. A convenient time to do this is when it escapes.
As the number of iterations goes up, the number of pixels that have not escaped to infinity gets smaller and smaller. But the masking operations are always on the whole array. It would be more efficient to keep track of the indexes of the pixels that have not escaped, so that subsequent operations are on smaller and smaller arrays.

2. Revised code

im, re = np.ogrid[min_coordinate.imag: max_coordinate.imag: height * 1j,
                  min_coordinate.real: max_coordinate.real: width * 1j]
z = (re + 1j * im).flatten()
live, = np.indices(z.shape) # indexes of pixels that have not escaped
iterations = np.empty_like(z, dtype=int)
for i in range(iterations_count):
    z_live = z[live] = mapping(z[live])
    escaped = abs(z_live) > threshold
    iterations[live[escaped]] = i
    live = live[~escaped]
iterations[live] = iterations_count - 1
return (iterations_count - iterations).reshape((height, width))

Notes

This is about three times as fast as the code in the post.
Because we are maintaining an array of indexes, it is convenient to flatten the z array and then reshape iterations to two dimensions before returning it. If we left the array two-dimensional, there would need to be two arrays of indexes, live_i and live_j.
Pixels that don't escape are given the value iterations_count - 1 in order to match the code in the post. It would make more sense to use iterations_count or a larger value here.
The subtraction iterations_count - iterations is only there so that the returned values match the code in the post. The subtraction could be omitted if you reverse the colour map.


Perfect elimination ordering and high memory usage

Silly me. The function listify also includes the empty list. Therefore
in each recursion of do_elimination the length of list gets doubled. This
is not bounded by the length of the original list anymore.

All these empty lists get stripped away by concat later.

Acknowledgement: Finding this out would have taken a great deal longer if not for a very kind person who took me by the hand and walked me through it.


A non-recursive tuple_element implementation

Your approach on finding the nth element relies on being able to construct a tuple with the first n-1 types being some predictable thing that you can match against. But the types you chose for std::tuple<void, int, char> were, for index 1, std::tuple<itp_base<0>, itp<1, int>, itp_base<2>>.

But we don't actually need to introduce this itp thing to do this, we can simply turn it into std::tuple<void, int, void>. That way, deduct_impl's specialization instead of taking a std::tuple<itp_base<indices>..., itp<index, T>, R...>, we can simplify to:

template <std::size_t>
using make_void = void;

template <typename T, typename... R>
struct deduct_impl<std::tuple<make_void<indices>..., T, R...>>
{
    using type = T;
};

And on the other side, we pass in:

std::tuple<std::conditional_t<(indices == index), Types, void>...>

Same idea, just more direct.

For that matter, we don't even need the tuple! std::tuple is an expensive type to construct at compile-time, so it's best to avoid it entirely. Just pass in the types as a pack (though the following doesn't compile on gcc - though even there you don't need tuple, just use a light wrapper like template <class...> struct typelist;)

template <typename... Ts>
struct deduct_impl;

template <std::size_t>
using make_void = void;

template <typename T, typename... R>
struct deduct_impl<make_void<indices>..., T, R...>
{
    using type = T;
};

and:

using type = typename deduct<index, std::make_index_sequence<index>
>::template deduct_impl
<
    std::conditional_t<(indices == index), Types, void>...
>::type;

A different approach

Another non-recursive way to do this would be through an inheritance tree. We basically take std::tuple<void, int, char> and turn it into a type that inherits from indexed<0, void>, indexed<1, int>, and indexed<2, char>:

template <std::size_t I, typename T>
struct indexed {
    using type = T;
};

template <typename Is, typename ...Ts>
struct indexer;

template <std::size_t ...Is, typename ...Ts>
struct indexer<std::index_sequence<Is...>, Ts...>
: indexed<Is, Ts>...
{};

Then, given a function template constrained on an index, we can pull out the correct type:

template <std::size_t I, typename ...Ts>
struct at_index {
private:
    template <typename T>
    static indexed<I, T> select(indexed<I, T>);

    using impl = indexer<std::index_sequence_for<Ts...>, Ts...>;
public:
    using type = typename decltype(select(impl{}))::type;
};

I don't know which solution is better, but this one is certainly shorter.


Collection-like classes in Java - taking advantage of varargs

You have found the natural solution to this situation. Arrays.asList will give you a List with specific features - new xxList(Arrays.asList(...)) will give you a list with attributes you require.


First thing, I assume that you don't like to use Object Oriented concepts and we will continue by the function approach.
One thing that I should say to you about the comments is always to use them but in a meaningful way. Adding # Variables comment above of the variables will not add any additional value to your code. It only wastes space.
The second thing is about naming. You should always follow your chosen naming rules.
So it's better to use player_input_num or player_in_num instead of the playerin_num. That's more snake_case.
So the beginning of your program will be like this after doing the above things:
import os

test_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player_input_num = 0

Acording to the comment rule we said above, you can remove the clear_screen docstring:
def clear_screen():
    os.system("clear")

Now we can take a look at the display_board function. You've used the while loop heare. But in the Python and for this case, using the for loop is more convient and readable. First, let's see the code:
def display_board(board_cords):
    '''
    display the board
    board_cords = list(left to right from top to bottom)
    '''
    line = '-'*40
    for i in range(0, len(board_cords), 3):
        print("\t|\t\t|")
        print(f"{board_cords[i]}\t|\t{board_cords[i + 1]}\t|\t{board_cords[i + 2]}")
        print(line)

The i is the loop counter variable. We said that the loop should start counting from the zero until reaching the len(board_cords). And also we told that after each iteration, it should increase the i value by 3.
The next function is check_player_input. In this function, we can remove the syntax variable. Also, we can use a more pythonic way of checking the user input range.
def check_player_input():
    """
    Gets an integer between 0 and 10 and calls `player_input` by that
    """
    while True:
        try:
            temp = int(input("Enter a position: "))
            if 0 <= temp < 10:
                break
            else:
                print('Sorry the input is not in range [0-9].')
        except:
            print("Input is not a number")
    player_input(temp)

Why removing the syntax variable is better? Because it's a variable with no real use. The original code is an infinite loop with a redundant variable.
Now we can go to the player_input function. The function that has an unnecessary global value.
One of the most famous **Not To Do` rules of software development is to avoid global values as possible. How we can avoid using that global value? The best way for doing that is to get the global value as an input parameter. But here I don't do that (Stay tuned for knowing why. For now, we just remove it and keeping its place).
The second problem here is the documentation of this function is not sufficient. I mean, what are the "codes"? You should add an extra description here for helping people understanding what is going on.
def player_input(player_in):
    if player_input_num >= 2:
        while check_win(test_board) == False:
            result = place_marker(test_board, 'X', player_in)
            clear_screen()
            display_board(result)
            check_player_input()

        print("You Won!")
    else:
        while player_input_num <= 2:
            result = place_marker(test_board, 'X', player_in)
            clear_screen()
            display_board(result)
            player_input_num += 1
            check_player_input()

In the next function, you did a very good thing. Inputting the board instead of using global values. I don't do it in your code in this post, but I strongly recommend doing that in other places of your code.
Doing that makes your code cleaner, more readable, more testable, and less buggy.
In the check_win there is a big problem. The login is too long and unreadable. It's better to break the logic down.
def check_win(board):
    if board[0] == board[1] == board[2]:
        return True
    if board[0] == board[3] == board[6]:
        return True
    if board[0] == board[4] == board[8]:
        return True
    if board[2] == board[5] == board[8]:
        return True
    if board[6] == board[7] == board[8]:
        return True
    if board[2] == board[4] == board[6]:
        return True
    return False

Why we did that? There are 6 different conditions for winning. So it's better to divide them from each other. So the person who reads your code can understand them more quickly.
All the things I've said until now are good, but there is a problem here. The code doesn't work.
The first problem is the player_input_num  value. In the original code, we only allow the user for inputting 3 values. So, What if the game will not finish after 3 moves? We should continue getting the inputs from the user until he/she wins the game.
We can change the player_input function like this:
def player_input(player_in):
    result = place_marker(test_board, 'X', player_in)
    clear_screen()
    display_board(result)
    if check_win(test_board, 'X'):
        print("You won")
    else:
        check_player_input()

We should change the check_win function too. Additional to the previous conditions, we should check that all 3 cell values are equal to the marker.
def check_win(board, marker):
    if board[0] == board[1] == board[2] == marker:
        return True
    if board[0] == board[3] == board[6] == marker:
        return True
    if board[0] == board[4] == board[8] == marker:
        return True
    if board[2] == board[5] == board[8] == marker:
        return True
    if board[6] == board[7] == board[8] == marker:
        return True
    if board[2] == board[4] == board[6] == marker:
        return True
    return False

Here it is. But still, we had a problem. What if the all cells of the board has been filled? We can add a new function for checking if the game has finished or not. But we can do it now because for doing that, you should have two players with two different markers. And I think you can do that by yourself.
For avoiding mistakes, I leave all the codes we seen above here. I hope this help you (Don't forget that it's not the best program for doing what you wanted, but I think, for now, it is a acceptable one).
import os

test_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

def clear_screen():
    '''
    clearing the screen
    '''
    os.system("clear")

def display_board(board_cords):
    '''
    display the board
    board_cords = list(left to right from top to bottom)
    '''
    line = '-'*40
    for i in range(0, len(board_cords), 3):
        print("\t|\t\t|")
        print(f"{board_cords[i]}\t|\t{board_cords[i + 1]}\t|\t{board_cords[i + 2]}")
        print(line)

def check_player_input():
    """
    Gets an integer between 0 and 10 and calls `player_input` by that
    """
    while True:
        try:
            temp = int(input("Enter a position: "))
            if 0 <= temp < 10:
                break
            else:
                print('Sorry the input is not in range [0-9].')
        except:
            print("Input is not a number")
    player_input(temp)

def player_input(player_in):
        result = place_marker(test_board, 'X', player_in)
        clear_screen()
        display_board(result)
        if check_win(test_board, 'X'):
            print("You won")
        else:
            check_player_input()

def place_marker(board, marker, position):
    board[position] = marker
    return board

def check_win(board, marker):
    if board[0] == board[1] == board[2] == marker:
        return True
    if board[0] == board[3] == board[6] == marker:
        return True
    if board[0] == board[4] == board[8] == marker:
        return True
    if board[2] == board[5] == board[8] == marker:
        return True
    if board[6] == board[7] == board[8] == marker:
        return True
    if board[2] == board[4] == board[6] == marker:
        return True
    return False

if __name__ == "__main__":
    display_board(test_board)
    check_player_input()

Two other things: 1. your logic for winning is not complete. 2. search about the if __name__ == "__main__":, it's better to use that.


Clearing the text when `text select` release

The jQuery $.on(); event listener can use 2+ events in its event listener parameter and then let you specify which one through e.type. This allows us to shorten a lot of code. With that in mind, we can also shorten your $.trim(window.getSelection().toString()).length to be $.trim('' + window.getSelection()) and assign it to a variable for use in our if's. We can then further simplify it by testing for e.type being 'mouseup' and if it's evaluates to false, it has to be 'mousemove'. And so we don't have nested if's, we can just use logical AND and OR operators to do something if it even has a value, and something else if it doesn't. That brings your code down to this:

$('#tenderContent').on('mouseup mousemove', '.tenderdocument', function(e) {
  e.stopPropagation();
  var selection = $.trim('' + window.getSelection());
  if ('mouseup' == e.type) {
    selection && $('#text').text(selection);
  } else {
    selection || $('#text').empty();
  }
});

That is a major cut off the amount that you had before. It also simplifies a lot of stuff to be fast and efficient.


C-style generic stack implementation in C#

UIntPtr is the wrong type to represent a count (it's basically a void *). You want UInt32 or UInt64 depending on your architecture.
Count should be private set; callers should not be able to change it directly
Why are elemsize and alloclength both signed ints? Shouldn't they be unsigned? Or at least check the incoming elemsize in the constructor?
I hope that the documentation explains that the FreeFunction is for freeing individual elements that the Stack owns if it gets destroyed nonempty.
What's supposed to happen when they Pop an empty stack? Right now you get undefined behavior.
What's supposed to happen if the malloc() or realloc() fails?


File loop and logic in controller of view header

The way you are scanning the directory is going to get all files. If this is intentional thats cool, but if you are really just looking
for js & css files, use glob and scan for them directly. This will be much better in performance, and you can avoid the directory check.
It seems like its a brittle idea to have the paths mapped to a specific class name. There has to be an easier way to associate views
and view resources rather than referencing $this.
This does not belong in the controller unless you are assigning the view data there. In frameworks like Zend, there are action helpers
which take care of this for you. If you don't have access to that, create a base controller class and do a magic helper method to keep the
functionality the same across all pages. This will allow you to maintain this functionality closer, and you can still use the $this if needed.
Is this really a good idea to just scan a directory and include all files? What happens if a new developer comes along and dumps a js file
they were testing something in, in the directory and it got included by accident? If there are very few includes, try to just manually put them in;
either through a layout or just hardcoding them in there. If you really have that much js and css being included in.... maybe there is a more
fundamental problem.

Better Scandir w/ Glob:

$jsGlob = Vs.get_class($this).'/js/*.js';
foreach (glob($jsGlob) as $js)
{
    echo '<script type="text/javascript" src="$js"></script>' ;
}

$cssGlob = Vs.get_class($this).'/css/*.css';
foreach (glob($cssGlob) as $css)
{
    echo '<link type="text/css" href="$css" rel="stylesheet"/>' ;
}


Individual collapsible areas with accessibility in mind

Everything looks great, and I can see what you are trying to achieve.

Only things I can recommend is to clean your code, make it as simple as possible, to make it easy to read and come back on later.

For example this line here:

while ((el = el.parentElement) && !el.classList.contains(cls));

In the way it is used, it's okay, but it doesn't explain well what the intention is, instead, try to be more "if this, then", very straight forward. Instead of using a while you could use recursion instead, removing more confusion.

Another thing is, you may want to expand your variable names. You probably will put this code through a minifier either way, so no need to keep things short.

function findAncestor(element, findClass) {
   if (element.classList.contains(findClass)) {
      return element;
   }
   if (!element.parentElement) {
      // Did we hit body?
      return false;
   }
   // We didn't find it, so check the parent.
   return findAncestor(element.parentElement, findClass);
}

Now we can read this function, and know exactly whats happening, without making any assumptions.

The next function is great, and works well, but we could make this more accessible using the [hidden] attribute along with a .hidden class, this is so we don't need to worry about compatibility.

We only want to use the parent as a light wrapper, from that parent we can find the child we actually want to show/hide

You can do a bit of reading on [hidden] here
https://www.paciellogroup.com/blog/2012/05/html5-accessibility-chops-hidden-and-aria-hidden/

function openHolder() {
   var region = findAncestor(this, 'js-collapsible-region');
   var content = region.querySelector('.collapsible-area');

   if (content.classList.contains('hidden')) {
      content.classList.remove('hidden');
      content.removeAttribute('hidden');
   } else {
      content.classList.add('hidden');
      content.setAttribute('hidden', '');
   }
}

We also want to leave state out of the DOM if it isn't visual state (like we can check if something is hidden, but we could also track that another way).

We then simply need to add our even listeners on like we did before:

var btn = document.getElementsByClassName('js-collapsible-btn');
for (var i = 0; i < btn.length; i++) {
    // add click event to open holder
    btn[i].addEventListener('click', openHolder, false);
}

We can also change this to a "functional" approach to remove the loop (which we needed to handle manually)

Array.from(document.getElementsByClassName('js-collapsible-btn'))
   .forEach(function(element) {
      element.addEventListener('click', openHolder, false);
   });

The last thing we should do, is instantly tell the screen reader is hidden but having the content marked as hidden to start with:

Title

Content goes here

        <button class="js-collapsible-btn">Click to show some text</button>

Suprise

Title

Content goes here

        <button class="js-collapsible-btn">Click to show some text</button>

Suprise

We also will need to change the styles to match

.js-collapsible-region .collapsible-area {
    overflow: hidden;
}

.js-collapsible-region .collapsible-area.hidden {
    height: 0px !important;
}

.js-collapsible-region .collapsible-area:not(.hidden) {
    transition: height .3s linear;
}

You should note that the attribute hidden applies the styles display: none, which you may not want, so you can change your styles to override the way you want them to work.

Here is the resulting codepen https://codepen.io/anon/pen/KqgmNY

For some fun, since we are using ES6 with classList anyway, have a look at this version https://codepen.io/anon/pen/mwrmpL


Converting a hexadecimal string to a binary string using Rust pattern matching lookup

Rustfmt is a tool for automatically formatting Rust code to the community-accepted style.
Clippy is a tool for finding common mistakes that may not be compilation errors but are unlikely to be what the programmer intended.

Rustfmt points out that you are using 3-space indents (Rust uses 4), and that some of your lines don't need to be split.

Clippy points out:

warning: returning the result of a let binding from a block
 --> src/main.rs:9:5
  |
7 |     let to_binary = hex[2..].chars().map(|c| to_binary(c)).collect();
  |     ----------------------------------------------------------------- unnecessary let binding
8 |
9 |     to_binary
  |     ^^^^^^^^^
  |
  = note: #[warn(clippy::let_and_return)] on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#let_and_return
help: return the expression directly
  |
7 |
8 |
9 |     hex[2..].chars().map(|c| to_binary(c)).collect()
  |

warning: redundant closure found
 --> src/main.rs:7:42
  |
7 |     let to_binary = hex[2..].chars().map(|c| to_binary(c)).collect();
  |                                          ^^^^^^^^^^^^^^^^ help: remove closure as shown: `to_binary`
  |
  = note: #[warn(clippy::redundant_closure)] on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_closure

There's no reason to return a String here, a &'static str is lighter-weight. See What are the differences between Rust's String and str? for full details, but a String requires a heap allocation, while a &'static str is a reference to some existing data in the compiled binary.

With these changes, all of your tests pass:

fn main() {
    let binary_value = convert_to_binary_from_hex("0x39A7F8");
    println!("Converted: {}", binary_value);
}

fn convert_to_binary_from_hex(hex: &str) -> String {
    hex[2..].chars().map(to_binary).collect()
}

fn to_binary(c: char) -> &'static str {
    match c {
        '0' => "0000",
        '1' => "0001",
        '2' => "0010",
        '3' => "0011",
        '4' => "0100",
        '5' => "0101",
        '6' => "0110",
        '7' => "0111",
        '8' => "1000",
        '9' => "1001",
        'A' => "1010",
        'B' => "1011",
        'C' => "1100",
        'D' => "1101",
        'E' => "1110",
        'F' => "1111",
        _ => "",
    }
}

In fact, deleting all of your code causes your tests to pass. It would be a good idea to add some tests!

Depending on what routes you want to look down next, you could try:

to handle strings that do not start with 0x without panicking.
to handle upper- and lower-case hex
to reduce/avoid string munging yourself


Parsing a string to get the values of certain attributes

I think that you should include the space before the identifier and the separator after the identifier, that way it will find the right identifier even if the string contains properties in a different order.

If the string contains for example CallName: Peter, NameAlias: Johnny, Name: John you would want the last property when looking for Name rather than the first property because it ends with Name or the value "ias: Johnny" from the second property.

(Including the space before the identifier naturally won't find an identifier if it starts at the first character of the string, but that doesn't seem to be the case with your data.)

You don't need a loop to find the end of the value, you can use IndexOf with a start index.

private string GetValueFromMessage(string identifier) {
  identifier = " " + identifier + ": ";
  int index = this.Message.IndexOf(identifier) + identifier.Length;

  if (index != -1) {
    int index2 = this.Message.IndexOf(",", index);
    if (index2 == -1) {
      index2 = this.Message.Length;
    }
    return this.Message.Substring(index, index2 - index);
  }

  return null;
}

Additionally, you can use .IndexOf(identifier, 0, StringComparison.OrdinalIgnoreCase) if you want to make a case insensetive match on the identifier.

Using this.Message or Message is a matter of convention, neither is clearly better than the other. While this.Message is more specific, Message should usually be clear enough, but you have to be a bit more careful when naming members to avoid conflicts, but on the other hand you should always avoid those conflicts anyway.


fprintf(stderr, "Unable to read program output\n"); loses important information: exactly why the program output couldn't be read. Prefer perror.

Ditto for other fprintf(stderr, ....).
The parent doesn't wait for children. You may produce plenty of zombies.
The parent doesn't close(stdout_pipe[0]); when done with a child. You may run out of file descriptors.
The spec file format seems naive:

There is no way to deal with a multi-line output.
It mixes child's stdout and stderr. If the child produces both, their order is unpredictable.
It doesn't specify the child's return status.


Peter Kiss's code works, but it's not fast.

<?php

$tags = $product->getTags();
$c    = count($tags);
$str  = null;
for ($i = 0; $i < $c; ++$i) {
    if ($str) {
        $str .= ", ";
    }
    $str .= $tags[$i]->getTag();
}

?>

Yes, it’s not short (and not much different to your solution) but it’s highly efficient and therefor the solution I’d go for.


Script for creating a hierarchy of directories

One of the things I would do is remove the double occurrence of the strings 'project_euler' and 'codechef'. If you ever have to change one of these in TOP, you are bound to miss the repetition in the functions.

You should at least use TOP[0] in make_euler_folders() and TOP[1] in make_codechef_folders. A better approach however would be to take both definitions out of TOP and change def safe_make_folder():

TOP = ['spoj', 'functions', 'utilities']

def safe_make_folder(i):
    '''Makes a folder (and its parents) if not present'''
    try:
        os.makedirs(i)
    except:
        pass

The standard function os.makedirs() creates the 'project_euler' resp.
'codechef', as the first subdirectory of each is created.

The other is that I would create the directory names using os.path.join() (as it prevents e.g. the mistake of providing double path separators), in combination with standard string formatting to get the leading zeros on the subfolder names:

os.path.join('project_euler', '{:03}_{:03}'.format(i, i+49))

the {:03} gives a 3 character wide field with leading zeros. @Josay improvemed function would then become:

def make_euler_folders(highest):
    for i in (os.path.join('project_euler', '{:03}_{:03}'.format(i, i+49)) \
       for i in range(1,highest, 50)):
        safe_make_folder(i)

And the other function would become:

def make_codechef_folders(codechef):
    for i in codechef:
        safe_make_folder(os.path.join('codechef', i))


x86 assembly [fasm] code which takes a number and adds 155 then shifts right

push number
push frmspec
call [scanf]
sub esp, 8 ; clean stack

Cleaning up the stack is done by adding to esp. Because the stack on X86 grows downward, cleaning implies going upwards.
You make this mistake several times!

From your problem statement it's not very clear whether you want to

shift the number after the addition
shift the number as it was before the addition

Your code presently does the latter.

mov eax, [number]
add eax, 155
push eax
push [number]          <------ Original number
push msg3
call [printf]
pop ecx
pop eax                <------ Still original number
pop ecx
shr eax, 2             <------ Shifts the original number
mov dword [number], eax

frmspec db '%d'
number dd 0

Currently your program depends on the zero stored in number. In future you might want to re-use number several times and then the zero-terminator might not be there anymore.
I think it will be more robust if you wrote

frmspec db '%d', 0
number dd 0

msg2 db 13,10, 'The final result is: %d', 0, 13, 10

You've placed the zero before the carriage return/linefeed. Those won't be outputted as a consequence!

mov dword [number], eax

FASM does not require you to write this redundant size tag (dword). It serves no purpose.


Referring to 'Could I make use of any Groovy-specific features?':
You could use a Category to add a isMultipleOf() method to Integer. So you could write if (number.isMultipleOf3())
(see Groovy Goodness: Use Categories to Add Functionality to Classes)

class Multiple {
    static boolean isMultipleOf(Integer number, int multipleOf) {
        number % multipleOf == 0
    }
}

def foo = 5
use (Multiple) {
    if(foo.isMultipleOf(3))
        println "Fizz"
    else
        println "Buzz"
}


Bottom-up singly linked list merge sort in C++

For what it's worth, I feel your pain about not getting any useful feedback from an interview. At least they actually told you that you didn't get the job! I've had companies (very well known, well-respected companies) not contact me to let me know I didn't get the job. In any event, here are some improvements that I think you could make.
Naming
Your functions are named reasonably well, but your variables are not. Instead of pN, just write node. Instead of s, write size or length. It will make your code far easier to read. Also, Hungarian notation (prefixing variables with a letter to indicate type) is out-of-fashion. Even if it weren't, I'm not sure you've done it correctly. A pointer to a pointer to a node should be ppN, not pN, shouldn't it?
The name merge_two_first_sublists() is really confusing. Why are they called first? And why don't you pass the function 2 lists? Even if you implement it in O(1) space, you can still pass in the pointer to each list. And if you do it that way you can use it even for lists that aren't contiguous.
In merge_sort() you have a variable simply named l. This is a dangerous name. In many fonts, it looks like a numeral 1. In general 1-letter variable names are a bad idea. I can give a pass for loop counters i and j, but beyond that, you should really avoid them.
Classes
You're programming in an object-oriented language, but you aren't using objects, which is a little odd. Why aren't insert_before(), remove() and skip() methods on a List class? It's not clear to me from the requirements you posted that it wouldn't be acceptable to do it that way. It would encapsulate the list in a convenient way and protect it from being modified elsewhere.
Overuse of Pointers
C++ has a lot of ways to avoid using pointers. The reason it has them is because pointers are extremely error prone and code that uses raw pointers is a maintenance headache. You've doubled-down on pointers and are using pointers-to-pointers in every function. It doesn't look to me like you need them in most of the functions. For example, why can't skip() be written like this:
template  <typename T>
Node<T> *skip(Node<T> *pN, size_t s) {
    while (s-- && pN)
        pN = pN->next;

    return pN;
}

What do you gain by using a pointer to a pointer?
How does insert_before() even work? The first argument is a pointer-to-a-pointer to the node we wish to insert after the second argument, n. So we have to end up with n->next assigned to the address of the "after" node. Don't we also need to have the "after" node's next pointer pointing to whatever n->next was pointing to before the call? I don't see that happening anywhere. And for the life of me, I can't figure out what the last line of the function is doing. Why do you set the pointer that was pointing to the pointer to the "after" node to point to the "before" node? What does that accomplish?
Why does remove() return anything? I wouldn't expect a remove() function to return any value. I'd just expect it to remove the node in question from the list. But it doesn't even take a list an as argument, just a pointer to a pointer to a node. This is going to be difficult to use and maintain, in my experience.
I recommend avoiding pointers at all if you can. In C++ you can use references instead of pointers in many cases. With C++11 and later, you can use shared_ptr and unique_ptr where appropriate. The requirements do say that the list uses pointers, so at least encapsulate them as best you can. If you have to have a function that modifies a pointer that's an argument you can pass in a reference to a pointer instead of a pointer to a pointer.