You may be a little confused about how a binary search operates. Your doc comment seems to suggest you understand and my cursory look at your code didn't reveal any bugs (but then again, I didn't look too hard). But, this function doesn't really make logical sense.

The purpose of a binary search is to find an item in O(log(n)) time instead of doing a full scan of a linear datastructure (or at least scanning until you find the item, which worst case is O(n)). This of course requires the datastructure to already be sorted. Your comment indicates you understand this. But what you end up doing with pred makes it seem like you confused yourself.

Why? Well if pred is not a constant time operation, then your binary search is no longer O(log(n)) (I suspect this is the case, because instead of passing lst[mid] to pred you pass the entire lst and index mid). Let's say pred is O(n). Now the total runtime of xbinsearch is O(n*log(n)), which is significantly worse. In this case, a linear search may be better.

Now, let's just assume pred is a constant time function. Now the overall runtime remains O(log(n)), but the return value of pred still doesn't make sense. Why is this? Well, the list must already be sorted by some ordering. If pred is constant time, it can only make decisions about the value at mid (and maybe a few surrounding values), but it can't scan lst to make decisions. So this means there must be some sort of dependency between the return value of pred and the sort order of lst. If there wasn't, your search probably wouldn't work (if say lst was sorted by ascending value but pred negated the values before comparing them, it would throw out the wrong half of the list).

So now we assume that pred is a constant time function that has some dependency on the sort order of lst. We've shown previously that if either of these doesn't hold, your algorithm is either inefficient or breaks. We now arrive at the last issue. pred's comparison criteria must be monotone over the sorted list. That is just a fancy way of saying that when lst is sorted then pred's comparison criteria must also be sorted. In which case, there isn't a purpose for pred, since the value of the item itself (which lst is sorted by this item value) is a proxy for the pred comparison criteria.

If you didn't follow all of that, don't be too worried. The important point is that you're probably misusing a binary search here. If you want to find the smallest value satisfying a predicate in a list you can just do: min(lst, key=pred).

For example:

people = [
    # (name, age)
    ('Doe Jane', 52),
    ('John Doe', 33),
    ('Jane Doe', 42),
]

# Min tuple from people by age
youngest_person = min(people, key=lambda p: p[1])

Note that with namedtuple this example becomes even more clear:

from collections import namedtuple

Person = namedtuple('Person', 'name age')

people = [
    # (name, age)
    Person('Doe Jane', 52),
    Person('John Doe', 33),
    Person('Jane Doe', 42),
]

youngest_person = min(people, key=lambda p: p.age)

Now you may notice people is not sorted. You could pass in a sorted list though, but it doesn't make much sense to sort the list, because it's not like you can perform multiple of these operations. min of a list (that you don't modify) will always be the same. If you change key then you'd need to resort the list. If you wanted both the min and max, use min and max. If performance is of concern (which is unlikely), you could optimize this by having one function that scans over the entire list and keeps track of both the min and max values. If you want to modify the list, then you're probably better off using a heap, which remains sorted with inserts and removals.

Some extraneous issues:

default=None isn't a very common pattern in Python. Sure you see it with dict.get (and less commonly with iter), but those are the two places where I can think of. These places have appropriate uses of allowing a default value. For your function a default value doesn't make much sense. Since it returns an index, what use would a "default index" be? I see two options:

return None (and only None). This simplifies the interface you provide. Allowing for a default value makes it hard for a user of your function to understand what's going on (it's just one more thing to wrap your head around). This way you can explain the function in a sentence: "Returns the minimum or maximum index of the item satisfying a predicate in a sorted list, or None"
Raise an exception (say ValueError) if no items satisfy the predicate. This is a very common approach in Python: dicts raise KeyError if a key doesn't exist (instead of returning None), lists raise IndexError if an index is out of bounds (instead of returning None). This is probably the right choice for you, because a predicate not being satisfied by anything in the list provided is probably an exceptional case that needs to be handled differently (eg. if you were to return None you couldn't treat it like a number if you wanted to do indexing with it).

Your use of string constants to indicate the mode (type="min") while common in numpy is a dangerous pattern IMO. You do no assert type in ('min', 'max'), so what if someone passes in type="median"? What if they make a typo: type="mIn"? Both of these appear to lead to behavior you don't want. Worst case (although your code doesn't appear to do this), this could cause an error inside your function. How frustrating would that be for a user of your function to see an error inside your function? This forces them to understand its internals to see if this is a bug in your function or a bug in their use of it. At the least, prefer an Enum so that if they choose an invalid type they get a AttributeError (if they tried to do type=SearchMode.PENULTIMATE, for example).

PEP8 your code. Your spacing needs work. Also wrap to 79 chars, it's really annoying to need to scroll right to read the docs. They're almost surely indented too far.

Instead of doing p[0] and p[1], consider tuple unpacking to give those values more descriptive names:

predicate_satisfied, direction = pred(mid, lst)

You should probably use required kwargs for type and default, otherwise, the function call site becomes unclear. Eg. is it xbinsearch(my_pred, 'min', 1) or xbinsearch(my_pred, 1, 'min'). Much clearer: xbinsearch(my_pred, type='min', default=1):

def xbinsearch(pred, lst, *, type='min', default=None):
    # ...


Rewrite BehaviorSuject that takes either localStorage or Observable in Angular

I think the ngOnInit() is the best suitable way for that. Clean and easy to spot. The initialization of the other two variables should also be part of ngOnInit (employee and employeeToken).
Something like that:
employee: Empoyee;
employeeToken: Observable<string>;
currentHead: BehaviorSubject<ADD-TYPE-HERE>;

...

ngOnInit() {
    const headFromStorage = localStorage.getItem('head');
    employee = this.identityService.me;
    employeeToken = this.employee.pipe(map((e) => e.token));
    this.currentHead = new BehaviorSubject(localStorage.getItem('head'));

    this.employeeToken.subscribe(e => this.currentHead.next(e));
}

Not sure you need this:
if (!this.currentHead.value || this.currentHead.value === '') {

Because this is a subscription. Every time the empoloyeeToken change, you have to update it, right?


Move common code to function

The first thing you could do to eliminate duplication is to take the common code and move it to a function.  In your case, the result would look like this:

// Returns 1 for buzz, 0 for any other.
int handleNum(int num)
{
    // if the number is multiple of both three and five
    if (num % 15 == 0) {
        printf("lancelot\n");
    }
    // if the number is multiple of 3
    else if(num % 3 == 0) {
        printf("Fizz\n");
    }
    // if the number is multiple of 5
    else if(num % 5 == 0) {
        printf("Buzz\n");
        return 1;
    }
    else {
        printf("%d\n", num);
    }
    return 0;
}

int myseries(int n) {
    int i, cpt = 0;
    if (n < 0) {
        for (i = 0; i >= n; i--) {
            cpt += handleNum(i);
        }
    }
    else {
        for (i = 0; i <= n; i++) {
            cpt += handleNum(i);
        }
    }
    return cpt;
}

Handle negative and positive alike

The next thing you could do is to combine the negative and positive cases into the same loop.  Both loops iterate the same number of times, just in different directions.  So you could just remember whether the original number was negative, and then iterate only in the positive direction, like this:

int myseries(int n) {
    int i, cpt = 0;
    int numberSign = (n < 0) ? -1 : 1;

    n *= numberSign;
    for (i = 0; i <= n; i++) {
        cpt += handleNum(i * numberSign);
    }
    return cpt;
}

Other things

Your indentation level of 2 is too small for my eyes.  I had to increase the indentation to 4 to properly distinguish the different levels.

When you print the result in main(), you should print a newline as well.  When I ran your program, my shell prompt was put at the end of your output.


It would be helpful for you to break up the code into functions, that will simplify each task.
Process the command line arguments first, then once you have the delimiter process the text files.

Declare the variable delim above any logic and initialize it to the default value
Process the command line to get the actual delimiter.
Process the input file.

This should shorten the code because you only need one loop to process the input file rather than 2.


Experienced ruby programmer starting with Java

Edit: As Landei suggested, use camelCase! Thanks Landei.

Your set function does not need to take an Integer. Idiomatic code would only use an int. Autoboxing means you can still add an int to this.possibles.
Why don't you use is_solved in not?
not is surprising, and I need to read the code to know what it does. I'd suggest naming it remove?
What about this.possibles.iterator().next() instead of the toArray trick?
Use a for each statement in inform_groups:

for(CellGroup g : this.groups) {
     g.cell_solved(this, this.possibles.iterator().next());
}


After some research I found that it's slightly more efficient to get the half quaternion directly from the double quaternion:

QVector3D rotaxis = QVector3D::crossProduct (vec1, vec2);
double cos = QVector3D::dotProduct (vec1, vec2);

// rotaxis and cos describe the double quat
// add 1 to cos so normalizing will 0.5 lerp between the null quat and the double quat
QQuaternion quat (1+cos,rotaxis);
quat.normalize ();

This saves the normalization of the bisector.

The rotation matrix can be constructed from a non-unit quaternion without first normalizing it. You do have to provide your own function to do so because the Qt algorithm assumes a unit quaternion:

inline QMatrix4x4 quatToMat(QQuaternion q)
{
    //based on algorithm on wikipedia
    // http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion
    float w = q.scalar ();
    float x = q.x();
    float y = q.y();
    float z = q.z();

    float n = q.lengthSquared();
    float s =  n == 0?  0 : 2 / n;
    float wx = s * w * x, wy = s * w * y, wz = s * w * z;
    float xx = s * x * x, xy = s * x * y, xz = s * x * z;
    float yy = s * y * y, yz = s * y * z, zz = s * z * z;

    float m[16] = { 1 - (yy + zz),         xy + wz ,         xz - wy ,0,
                         xy - wz ,    1 - (xx + zz),         yz + wx ,0,
                         xz + wy ,         yz - wx ,    1 - (xx + yy),0,
                               0 ,               0 ,               0 ,1  };
    QMatrix4x4 result =  QMatrix4x4(m,4,4);
    result.optimize ();
    return result;
}

Using that eliminates all normalization from in mouseMoveEvent except to get the arcballVectors themselves.


Retrieving ListBox.column values and store into objects

Start with proper indentation. There shouldn't be anything (other than subroutine/line labels) at the same level of indentation as a Private Sub statement, other than the End Sub.

Code blocks are more readable and code as a whole is easier to follow when code blocks are indented. General rule of thumb, if there's an End X for a statement, you're in a code block. Give that Tab key some lovin'!

Private Sub DoSomething()
|...If Not FooBar Then
|...|...DoSomethingElse
|...End If
End Sub DoSomething

Using a For..Next loop here is tricky, because you're accessing a different property every time. You're going to need to access the properties by name, and to do that you need them in an indexed structure, like an array:

Dim properties(1 To 7) As String
properties(1) = "wellName"
properties(2) = "wellActive"
properties(3) = "wellDiameter"
properties(4) = "wellCasing"
properties(5) = "screenedInternal"
properties(6) = "wellSock"
properties(7) = "wellDepth"

Now you can go from 1 to 7 and, assuming CWell is a class module (I'm not all that familiar with Access, I hope my assumption is correct)...

For i = 1 To 7
    value = Well_List.Column(i, row)
    If value <> vbNullString Then SetPropertyValue wellObj, properties(i), value
Next

Notice I'm using vbNullString instead of an empty string literal "". vbNullString is a null string pointer, which isn't allocated a memory address. "" has its own memory spot. No biggie, but not needed either.

So, how would that SetPropertyValue method be implemented? The VBA standard library has this little wonder in its VBA.Interaction module, called CallByName:

Private Sub SetPropertyValue(ByRef instance, ByVal member, ByVal value)
    CallByName instance, member, vbLet, value
End Sub

This is assuming CWell exposes a Property Let accessor/mutator. If wellName and friends are public fields, you need to properly encapsulate them and expose them via properties.

That said, public members should be PascalCase, so "wellName" would be "WellName".

Now, I really introduced that SetPropertyValue method just to make an abstraction level for the sake of this answer. The one-liner could just as well be inlined:

Dim properties(1 To 7) As String
properties(1) = "wellName"
properties(2) = "wellActive"
properties(3) = "wellDiameter"
properties(4) = "wellCasing"
properties(5) = "screenedInternal"
properties(6) = "wellSock"
properties(7) = "wellDepth"

For i = 1 To 7
    value = Well_List.Column(i, row)
    If value <> vbNullString Then
        CallByName wellObj, properties(i), vbLet, value
    End If
Next


You don't really need to use ng-html2js since you don't really have a file .html file.
Answered on question 1.
You can just use angular.mock.module if you want. I usually use this pattern for my tests.

Example:

const angular = window.angular,
  expect = window.chai.expect,
  sinon = window.sinon;

const inject = angular.mock.inject,
  module = angular.mock.module;

I have a repo with some patterns for unit testing. Feel feel to take a look at it.

https://github.com/rodoabad/angularjs-unit-testing-patterns


I would have used str.format together with a transparent dictionary to achieve this result. It gives you the familiarity of the format syntax and not having to come up with the regex on your own. This comes at the cost of not being able to specify the regex anymore at all.

The transparent dict is taken from this answer and is needed because otherwise format raises a KeyError when trying to do a partial replace.

from collections import defaultdict

class SafeDict(dict):
    def __missing__(self, key):
        return '{' + key + '}'

def parse(val, vars, callback=None):
    if callback:
        val = callback(val)
    if isinstance(val, dict):
        return parse_dict(val, vars, callback)
    elif isinstance(val, list):
        return parse_list(val, vars, callback)
    try:
        return val.format(**SafeDict(vars))
    except Exception:
        return val

def parse_list(l, vars, callback=None):
    parsed = type(l)()
    for val in l:
        parsed.append(parse(val, vars, callback))
    return parsed

def parse_dict(d, vars, callback=None):
    parsed = type(d)()
    for key, val in d.items():
        parsed[key] = parse(val, vars, callback)
    return parsed

parse_dict and parse_list could be replaced by the one-liners you use. This way, however, they return the same data type as was originally there (this is relevant for sub-classes of list or dict). If you don't need this, just replace them with what you've got.

usage:

a = 'blah'
my_dict = {'test': '{a}',
           'another': 'my {a} test',
           'nested': {'child': 'here is {a} {a}'},
           'boo': 1,
           'test2': False}
print(parse(my_dict, globals()))

When adding more parsers for other data types than list or dict (their sub-classes are already included), you would probably define a mapping from type to parsers to avoid repetition in parse.

As an alternative you should have a look at f-strings, which will be included in Python 3.6, scheduled to be released soon.

With this you could do:

a = 'blah'
table = "Users"
row = 42
parsed_dict = {'test': f'{a}',
               'another': f'my {a} test',
               'nested': {'child': f'here is {a} {a}'},
               'boo': 1,
               'test2': False,
               'complex': f'result: {db_lookup(table, row))}'}


You can wrap the functionality in an object. You instantiate it with a canvas element and some configuration options.

(function($) {

// config defaults
var defaults = {
    LEFT_INDENT: 100,
    START_WORK_HOUR: 8,
    END_WORK_HOUR: 17,
    AXIS_SIDE_MARGIN: 20,
    AXIS_TOP_MARGIN: 40
};

// constructor
axis = function(canvas, config)
{
    this.config = $.extend({}, defaults, config);
    this.canvas = canvas;

    this.setup();
}

// define prototype functions
axis.prototype.setup = function() {
    this.context = this.canvas.getContext('2d');

    this.HOURS_IN_WORKDAY = this.config.END_WORK_HOUR - this.config.START_WORK_HOUR;
    this.CANVAS_WIDTH = this.canvas.width;
    this.CANVAS_HEIGHT = this.canvas.height;

    this.AXIS_ORIGIN = {
        x: this.config.AXIS_SIDE_MARGIN,
        y: this.config.AXIS_TOP_MARGIN
    };

    this.AXIS_RIGHT = this.canvas.width - this.config.AXIS_SIDE_MARGIN;

    this.TICK_INCREMENT = (this.CANVAS_WIDTH - this.config.LEFT_INDENT - 2*this.config.AXIS_SIDE_MARGIN)) / this.HOURS_IN_WORKDAY;
}

axis.prototype.draw_lines = function() {
    this.context.beginPath();
    this.context.moveTo(this.LEFT_INDENT, this.AXIS_ORIGIN.y);
    this.context.lineTo(this.AXIS_RIGHT,  this.AXIS_ORIGIN.y)
    this.context.stroke();
    this.counter = this.config.START_WORK_HOUR;

    for(x = this.config.AXIS_SIDE_MARGIN + this.config.LEFT_INDENT ; x < this.AXIS_RIGHT ; x = x + this.TICK_INCREMENT) {
        // grid lines
        this.context.beginPath();
        this.context.moveTo(x,30);
        this.context.lineTo(x,50)
        this.context.stroke();

        // background line - top to bottom
        this.context.save();
        this.context.fillStyle = "#F0F8FF";
        this.context.beginPath();
        this.context.lineWidth = .1;
        this.context.moveTo(x,30);
        this.context.lineTo(x, this.CANVAS_HEIGHT - 20)
        this.context.stroke();
        this.context.restore();

        // text
        this.context.font = "14px Arial";
        this.context.fillStyle = "#011f5b";
        this.counter++;
        this.context.fillText(this.counter+":00",x-7,20);
    }
}

}(jQuery));

To use it:

var a = new axis(document.getElementById('myCanvas'), {
     // whatever you want to override
});
a.draw_lines();


Functor to compare two floats with tolerance

A few remarks:

Seems appropriate to add a default value of 0.0f in the constructor:

Less(const float tolerance = 0.0f)
    : m_tolerance(tolerance)
{

}

This class could most certainly be used as a base class.

For example:

class Less1 : public Less
{
public:
    Less1():Less(1.0f)
    {
        ...
    }
    ...
}

So you may as well make it suitable to serve as such:

Declare virtual ~Less()
Change private to protected where needed

The operation f1 < f2 is most likely less expensive than abs(f2 - f1).

So you may as well check it first:

bool operator()(const float f1, const float f2) const
{
    return f1 < f2 && std::abs(f2 - f1) >= m_tolerance;
}

You should add an assertion on the value of m_tolerance being non-negative.

Alternatively, you could use std::abs(m_tolerance), but it seems a bit hacky.


errorlocation() routine, implemented in C++ based on pseudocode

Writing psuedo-code first, then turning it into code is great. However, we should then delete the pseudo-code.

The problem with comments like this is that they mainly just repeat the code. If we need a comment to explain what the code does, we should make the code clearer instead. Comments that explain why the code does something the way it does are more helpful.

Note also that if we change the code in the future, we would have to update all these comments too, which is twice the work.

Comments for documentation purposes tend to be structured according to the documentation tool in use (e.g. short description, purpose of arguments, return values, etc.). However, they are probably unnecessary for a small function that will be used internally in a project.

Some issues with the code:

Do we ever really expect locationStart to be after locationCurrent? Perhaps an assertion, or an exception would be more appropriate.
Otherwise std::optional would be a better choice for the return value.
We should use appropriate types for indexing. If the range of indices for Iter cannot be negative, and needs to cover the range of a standard container (e.g. std::string), we should use std::size_t, not int.
It's probably clearer to use the divide and remainder operators directly, instead of std::div (if that's what div is). Note that std::div, std::ldiv, and std::lldiv all use signed integer types, which probably don't cover the appropriate range.
The local error variable is unnecessary.
What is 80? Perhaps this should be a function argument (or at least a named constant).
We can be more consistent with naming. (The function is getErrorPosition, but we're returning a Point. Perhaps CharacterPosition would be a better name than Point).
Although it's called getErrorPosition, this function is not specific to errors - it just gets the character position from the iterators. If we give it a more general name, then we can use it for other things too.

So I'd suggest something like this (though the doc comments are probably not needed):

#include <cassert>
#include <cstdlib>
#include <iterator>

struct CharacterPosition
{
    std::size_t row;
    std::size_t column;
};

/// \brief Returns the character position (row / column) from its index.
/// \param index The distance of the character from start of the document.
/// \param lineLength The line length of the document (all lines must be this length for the returned character position to be correct).
/// \return Row and column of the character.
CharacterPosition getCharacterPosition(std::size_t index, std::size_t lineLength)
{
    return { index / lineLength, index % lineLength };
}

/// \brief Returns the character position (row / column) from its iterator position.
/// \param start An iterator pointing to the first character of the document.
/// \param current An iterator pointing to the current character (for which we will return the position).
/// \param lineLength The line length of the document (all lines must be this length for the returned character position to be correct).
/// \return Row and column of the character.
/// \pre The current iterator must not be positioned before the start iterator
template<typename Iter>
CharacterPosition getCharacterPosition(Iter start, Iter current, std::size_t lineLength)
{
    assert(start <= current);

    auto distance = std::distance(start, current);

    return getCharacterPosition(distance, lineLength);
}


repr shouldn't be used as a general pretty print method. It should give a short description of an object, preferably one which looks like code.

Its best to use correct english in variable names, i.e. children not childs.

Rather then combining a lot of strings, use StringIO

The TreeMap.build method is mostly concerned with a node. It should really be on the node class. The only interaction it has with TreeMap is the rectangles. But since you store those on the object anyway, we will provide a seperate iteration for those.

Once we've moved build into Node, TreeMap doesn't do anything, so we eliminate it.

There doesn't seem to be a really good reason for a Node to worry about its own depth.

I don't like the Node constructor. I don't think that a constructor should be concerned with conversion from a seperate format like that. Format conversions should be done in other functions. Since iter_method and size_method are only for that conversion, they should be arguments there

The tricky bit is the Node.build function. You have two for loops which look pretty much the same. We can combine them by pulling the bits of logic unique to each direction out.

My results:

from StringIO import StringIO

class Rectangle(object):

    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height

    def __repr__(self):
        return "Rectangle({0},{1},{2},{3})".format(
            self.x, self.y, self.width, self.height)

    def slice(self, horizontal, start, length):
        if horizontal:
            return Rectangle(self.x + start, self.y, length, self.height)
        else:
            return Rectangle(self.x, self.y + start, self.width, length)

class Node(object):

    def __init__(self, children, value):
        self.children = children
        self.value = value

    @classmethod
    def from_nested_tuple(class_, data):
        return class_.from_data(data, iter, int)

    @classmethod
    def from_data(class_, data, iter_method, size_method):
        try:
            iterable = iter_method(data)
        except TypeError:
            value = size_method(data)
            return class_([], value)
        else:
            children = [ class_.from_data(item, iter_method, size_method)
                for item in iterable]
            return Node(children, sum(child.value for child in children))

    def __repr__(self):
        return "Node< {}, {} children>".format( self.value, len(self.children))

    def _pretty_print(self, output, depth):
        output.write('\t' * depth)
        output.write('Node: {}'.format(self.value))
        output.write('\n')
        for child in self.children:
            child.pretty_print(output, depth + 1)

    def pretty_print(self):
        output = StringIO()
        self._pretty_print(output, 0)
        return output.get_value()

    def build(self, rect, horizontal=True):
        self.rect = rect

        sizes = [child.value for child in self.children]
        total_size = self.value

        if horizontal:
            space = rect.width
        else:
            space = rect.height

        position = 0.0
        for child in self.children:
            length = child.value * space
            child.build( rect.slice(horizontal, position, length),
                not horizontal)
            position += length

    def rectangles(self):
        yield self.rect
        for child in self.children:
            for rect in child.rectangles():
                yield rect

import unittest

class Test_TreeMap(unittest.TestCase):

    def test_build_depth0(self):
        nodes = (2,1,(2,2))

        known = (1, 1), (2.0/7, 1), (1.0/7, 1), (4.0/7, 1), (4.0/7, 0.5), (4.0/7, 0.5)

        Node.iter_method = iter
        Node.size_method = int
        root = Node.from_nested_tuple(nodes)
        root.build( Rectangle(0,0,1,1) )

        widths = tuple((rect.width, rect.height) for rect in root.rectangles())
        self.assertEqual(known, widths)
unittest.main()


How to optimize jQuery to run on asp.net web form updatepanel?

Some notes in no particular order:

1

//get all elemnt with class .resource-download
$.each($(".resource-download"), function () {
    var fileExtension = getFileExtension(this.href);
    if (fileExtension == "" || fileExtension != "pdf") {
        $(this).addClass("hideLinke");
    }
});

//load script agine
function init() {
    $.each($(".resource-download"), function () {
        var fileExtension = getFileExtension(this.href);
        if (fileExtension == "" || fileExtension != "pdf") {
            $(this).addClass("hideLinke");
        }
    });
}

better to define the function and call it rather than copy paste the code.

function init() {
    $.each($(".resource-download"), function () {
        var fileExtension = getFileExtension(this.href);
        // see point 2
        if (fileExtension == "" || fileExtension != "pdf") {
            $(this).addClass("hideLinke");
        }
    });
}

init();

2

if (fileExtension == "" || fileExtension != "pdf") {

Is pointless, "" !== "pdf" so you should just have the second condition.

if (fileExtension !== "pdf") {

3
It's better to be in the habit of using === and !== to avoid subtle bugs caused by type coercion.

4

$.each($(".resource-download"), function ()  {}); is better written as $(".resource-download").each(function() {});


Listing payments where all payments lines and transactions are closed

White space
Since you come from a Java background, you will understand the importance of using white space to make the code easier to read. Also it is best to stay consistent with capitalization of keywords. I would go for something like this:
SELECT p.*
FROM payment p
  JOIN transaction t
    ON t.payment_bk = p.bk
  JOIN payment_line pl
    ON  p.bk = pl.payment_bk
WHERE p.valid IS NULL
  AND p.valid_to IS NULL
  AND p.date>{ts '2015-05-21 00:00:00'}
  AND p.date<{ts '2015-05-22 00:00:00'}
  AND t.valid IS NULL
  AND t.valid_to IS NULL
  AND t.transaction_status = 'CLOSED'
  AND NOT EXISTS (
    SELECT 1
    FROM transaction t
    WHERE t.payment_bk = p.bk
      AND t.transaction_status <> 'CLOSED'
      AND t.valid and t.valid_to IS NULL
  )
  AND pl.valid IS NULL
  AND pl.valid_to IS NULL
  AND pl.payment_line_status = 'CLOSED'
  AND NOT EXISTS (
    SELECT 1
    FROM payment_line
    WHERE pl.payment_bk = p.bk
      AND pl.payment_line_status <> 'CLOSED'
      AND pl.valid IS NULL
      AND pl.valid_to IS NULL
  );

So, that already reads a lot better!

Table aliases are handy, but in your case I think your use of single-letter aliases makes the query harder to read. For instance, instead of payment p JOIN transaction t I would suggest something like payment AS pay INNER JOIN transaction AS tran. And payment_line pl could be payment_line AS line or something like that.

Normally I would recommend using Common Table Expressions instead of sub-queries, but since this will eventually be done by Hibernate it would not matter too much right now.

For clarity's sake, I would avoid to chain WHERE conditions like this:
WHERE p.valid AND p.valid_to IS NULL

I missed those at first, so that gives you an idea why.


Find the biggest rectangle in a bar graph

As others have pointed out, your algorithm is very inefficient. Especially if the size of the columns vary widely:

int[] columns = { 1, 5, 40000, 3 } // Just to make my point clear :-)

This will cause your algorithm to check 39996 numbers (= column heights) for no reason.

So a minor change in your code could make it a lot more efficient, although it isn't still a very efficient approach:

private int GetBiggestRectSize(List<int> barGraph)
{
  int maxRectSize = 0;
  //int max = barGraph.Max();

  // CHANGE: Instead of checking all values from max to 1 - only check values in the input graph.
  foreach (int i in barGraph)
  {
    int tempSize = 0;
    for (int j = 0; j < barGraph.Count; j++)
    {
      if (barGraph[j] >= i)
      {
        tempSize += i;
      }
      else
      {
        if (tempSize > maxRectSize)
        {
          maxRectSize = tempSize;
        }
        tempSize = 0;
      }
      if (tempSize > maxRectSize)
      {
        maxRectSize = tempSize;
      }
    }
  }

  return maxRectSize;
}


Recursive Function to Produce Constrained List of Integer Partitions

Python is not designed for recursion. To avoid stack overflows there is a limit
In [2]: import sys

In [3]: sys.getrecursionlimit()
Out[3]: 1000

So we can easily design a test that will fail
In [4]: partition(1000, {1})
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-4-884568e60acd> in <module>()
----> 1 partition(1000, {1})

<ipython-input-1-60a0eb582d3c> in partition(number, interesting)
      6     for x in range(1, number):
      7         if x in interesting:
----> 8             for y in partition(number - x, interesting):
      9                 answer.add(tuple(sorted((x, ) + y)))
     10     return answer

... last 1 frames repeated, from the frame below ...

<ipython-input-1-60a0eb582d3c> in partition(number, interesting)
      6     for x in range(1, number):
      7         if x in interesting:
----> 8             for y in partition(number - x, interesting):
      9                 answer.add(tuple(sorted((x, ) + y)))
     10     return answer

RecursionError: maximum recursion depth exceeded in comparison

You may increase the recursion limit
In [5]: sys.setrecursionlimit(1500)

In [6]: partition(1000, {1})
Out[6]:
{(1, ...

but that is only applicable if your numbers are guaranteed to be in a certain range. Most probably you should implement a non-recursive solution. For 10-50 million you have to.
If your problem e. g. guarantees 1 <= number <= 500 you should still do some assertions in your function
assert 1 <= number <= 500


Minor Python cleanup
First, a bunch of little stuff:
This -
(str(i).zfill(len(str(111))))

does not need outer parens. Also, why the acrobatics to get "3"? Just declare a MAX_DIGITS = 3.
This -
'.'.join( list( reversed( line.split('\t')[1].split('.') ) ) )

should not be creating an inner list. The output of reversed is iterable.
This -
if(len(buffer_array) == 1000):

does not need outer parens; you're not in (C/Java/etc).
This -
save_file.close()

needs to be deleted both places that it appears. There's an implicit close() from your use of a with.
This -
    except Exception as e:
        pass

is a bad idea. Log or output the exception.
87 deserves a named constant.
Broad performance
gethostbyname is probably slow (as indicated in the comments). Consider running a local caching DNS resolution service to eliminate the first network hop.


Soo.. let me tell you a secret about Java's HashSet...

  This class implements the Set interface, backed by a hash table (actually a HashMap instance)

to cut the chase short: you could've just used a HashSet, it would've been at worst equally slow.

now to review the code... Since you don't make any guarantees for execution order in your code, neither will I:

System.out.println("String value with no duplicates: "
    + new HashSet<>(Arrays.asList(test.toCharArray())).stream().collect(Collectors.joining("")));

It should be acceptably easy to see, that this is horrendous code, but it does the same thing as your code...

Either way, the code presented also has some issues:

Unnecessary creation of (relatively speaking) expensive objects.
String.valueOf(test.charAt(i)) is just bad form
Strangely hidden complexity.
In nodups.put(..) there's a hideous hidden complexity. You're hashing the character (which basically just turns it into an int and does some modulo calculations) and then put the char into it's place.
Double loop, where one is sufficient.
Currently the code does two loops, where one is sufficient. In a HashSet the contains-operation is \$\mathcal{O}(1)\$. This allows you to just collapse the loops instead of repeatedly overwriting the same value:

Set<Character> knownChars = new HashSet<>();
StringBuilder nodupsString = new StringBuilder();
for (Character c : test.toCharArray()) {
    if (!knownChars.contains(c)) {
        knownChars.add(c);
        nodupsString.append(c);
    }
}

This reduces the mathematical complexity from \$\mathcal{O}(2n)\$ to \$\mathcal{O}(n)\$. And don't come with the "constants are ignored in O-notation" fallacy. The problem is that too many people think that and as a result write badly performing code, which they think can't be made faster ... </rant>

Aside from that ... good job, I guess?


Two minor points on the code and one on unit test:

Combining if clauses

You can combine both if clauses as such:

if (isPalindrome(current) && current.length() > palindrome.length()) { ... }

Enhancing use of for loop

Multiple local variables can be declared in the for loop, so you can include your last variable as such:

private static boolean isPalindrome(String s) {
    for (int i = 0, last = s.length() - 1; i < s.length() / 2; i++, last--) {
        if (s.charAt(i) != s.charAt(last)) {
            return false;
        }
    }
    return true;
}

Unit testing

As mentioned in my comment, it will be better to turn your main() code into a series of unit tests to ensure your logic is working correctly. The example below uses TestNG and Hamcrest matchers, and is meant to be a simple showcase for how this can be done. You should consider a variety of tests (e.g. empty Strings, non-palindromic inputs) to also ensure it works for as many cases as possible. That is when you can consider some of the features of TestNG such as parameterized testing.

@Test
public void doTest() {
    assertThat(findLongestPalindrome("xyzracecar"), equalTo("racecar"));
    assertThat(findLongestPalindrome("abcexcbaddd"), equalTo("ddd"));
    assertThat(findLongestPalindrome("cacxx"), equalTo("cac"));
}

Bonus: Oh yeah, is it the largest or longest palindrome you are looking for? Since you are dealing with Strings, my suggestion is to be consistent and stick with permutations of 'longest palindrome'. :)


Finding the closest value in a collection in a game-server plugin implementation

This problem can be solved mathematically much better than it can with a list, or collection.

What you have is 9 states, and a timer that counts down. The timer can be expressed as a proportion of 1. Because the states are all equally spaced on 1/9 intervals, you can just do math....

So, if the time is \$x\$ and the total time is \$y\$, then the current portion is \$\frac{x}{y}\$ If you multiply this value by 9, you get something on the scale of 0 to 9 inclusive. you really want:

public int tileID(int currentTime, int totalTime, int tileCount) {
    // we want the shift to happen at less than half-the-time (in the middle of the period).
    double shift = (1.0 / tileCount) / 2;
    double progress = (double)currentTime / (double)(totalTime);
    int tile = (int)(progress * tileCount + shift);
    return tile;
}

shift is needed to make the (int) truncation work. Your comment has made me think, and, in reality, it is not the most readable/understandable code. In fact it is broken, and shift should just be 0.5 always... Let me re-do it in the form of a round() instead of a truncation:

public int tileID(int currentTime, int totalTime, int tileCount) {
    double progress = (double)currentTime / (double)totalTime;
    int tile = (int)Math.round(progress * tileCount + 0.3);
    // because your tiles are in the opposite order: tileCount - 1 - tile
    return tileCount - 1 - tile;
}

Then, you can use this with:

TargetScope tile = TargetScope.values[tileId(this.time,
              TargetManager.TARGET_SEARCH_WAIT, TargetScope.values[].length)];


Guides the User with Prompts to go through a procedure and Records User Input

The way you are declaring your variables isn't what you expect it to be. Luckily, you're declaring variants anyway. But if you weren't declaring Variants they would all by default be Variants.
Dim step1 as variant
Dim step2 as variant, step3 as variant

You need to give all variables a type.
You also have some superfluous variables -

step6a = InputBox("Step 6: Experiment Measurement Results Solution 1")
    Cells(21, 3).Value = step6a
step6b = InputBox("Step 6: Experiment Measurement Results Solution 2")
    Cells(22, 3).Value = step6b

Since you don't re-reference these variables later on, you can just write to the cell
.Cells(21,3) = InputBox("Step 6: Experiment Measurement Results Solution 1")
.Cells(22,3) = InputBox("Step 6: Experiment Measurement Results Solution 2")

Guiding the user
You mention you want to guide the user here. When you prompt them for input, you should tell them what type of input, and then check it's the correct Type.

 Cells(7, 3).Value = step3 - step2

This will error if there are values that aren't numerical. You can define what type you want.
You asked me

What is the Measured Actual Value?

But I didn't know if you wanted what kind of measurement or an integer. This can cause a mismatch error later on.
 step3 = Application.InputBox("Step 3: What is the Target Value Desired?", Type:=1)

Now you require me to enter a number value. You control what happens if I don't put in the expected type.

Refactoring
You see yourself doing the same thing over and over. Normally you would farm this out to a function, sending arguments and getting data back. But, you're using the InputBox which is already a function. So how to make this cleaner? Arrays!
Make yourself an input array and an output array. We know how many questions there are, so no problem.
Dim questions(1 to 21) as String
Dim answers(1 to 21) as Variant

And then populate your questions and pass them to inputbox with a type, and set each consecutive item in the answers array to the response. Then a simple loop
For i = 9 to 25
  .Cells(3,i) = answers(i-8)
Next

There are some other things you could do with your strings and whatnot, but that's up to you.

For the brave
Something like this -
Const STEP1 As String = "Define the Problem."
Const STEP2 As String = "What is the Measured Actual Value?"
Const STEP3 As String = "What is the Target Value Desired?"
Const STEP4a As String = "Why is " & questions(1) & " happening?"
Const STEP4b As String = "Why is " & questions(4) & " happening?"
Const STEP4c As String = "Why is " & questions(5) & " happening?"
Const STEP4d As String = "Why is " & questions(6) & " happening?"
Const STEP4e As String = "Why is " & questions(7) & " happening?"
Const STEP5a As String = "Step 5: Describe your First Possible Solution"
Const STEP5b As String = "Step 5: Describe your Second Possible Solution"
Const STEP5c As String = "Step 5: Describe your Third Possible Solution"
Const STEP5d As String = "Step 5: Describe your Fourth Possible Solution"
Const STEP5e As String = "Step 5: Describe your Fifth Possible Solution"
Const STEP6a As String = "Step 6: Experiment Measurement Results Solution 1"
Const STEP6b As String = "Step 6: Experiment Measurement Results Solution 2"
Const STEP6c As String = "Step 6: Experiment Measurement Results Solution 3"
Const STEP6d As String = "Step 6: Experiment Measurement Results Solution 4"
Const STEP6e As String = "Step 6: Experiment Measurement Results Solution 5"
Const STEP7 As String = "Step 7: When did you impliment a solution?"
Const STEP8 As String = "Step 8: Now that the solution is implemented perminently, what is the current measurement?"
Const STEP9 As String = "Step 9: Any other Ideas that have sprung up since you have started this nine step related to this area?"

Dim questions(1 To 21) As String
questions(1) = STEP1
questions(2) = STEP2
questions(3) = STEP3
questions(4) = STEP4a
questions(5) = STEP4b
questions(6) = STEP4c
questions(7) = STEP4d
questions(8) = STEP4e
questions(9) = STEP5a
questions(10) = STEP5b
questions(11) = STEP5c
questions(12) = STEP5d
questions(13) = STEP5e
questions(14) = STEP6a
questions(15) = STEP6b
questions(16) = STEP6c
questions(17) = STEP6d
questions(18) = STEP6e
questions(19) = STEP7
questions(20) = STEP8
questions(21) = STEP9

Then you can loop through like
For i = 1 To 21
    answers(i) = InputBox(questions(i))
End Sub

But you might need a custom argument in case you need to restrict what Type the user can enter. This you cannot do with a UserForm unless you get into keypresses and whatnot.


ASP.NET Core 3.1 AddHttpClient call that includes a call to the database

No need to manually create the DbContext. Since you have already registered it with the service collection, resolve it as needed.

AddHttpClient has an overload that provides access to the service provider.

services.AddHttpClient("VendorAPICall", (sp, c) => {
    c.BaseAddress = new Uri("https://api.vendorname.com/");
    c.Timeout = new TimeSpan(4, 0, 0);
    c.DefaultRequestHeaders.Accept.Clear();
    c.DefaultRequestHeaders.Add("Accept", "application/json");
    var ctx = sp.GetService<DatabaseContext>(); //<-- resolve context
    Security security = ctx.Security.First();
    // Header must include the API Token for all requests,
    // or the request will be rejected
    c.DefaultRequestHeaders.Add("ApiToken", security.Apikey);

});

This will allow the framework to manage its lifetime instead of constantly having to dispose of it yourself in a using block


Frames are specifically designed to be a tool in organizing the widgets in your GUI.

In the case of a simple form like this, I recommend using one frame for the labels and entries, and one for the buttons. grid is the natural choice for the form, and it looks like pack would be best for the buttons. pack is also best to put the form on top and the buttons on the bottom.

For the form, I would not use a frame for each row.

Example:

# the root window and its children
form = tk.Frame(root)
buttons = tk.Frame(root)

form.pack(side="top", fill="both", expand=True)
buttons.pack(side="bottom", fill="x")

# the buttons
b1 = tk.Button(buttons, ...)
b2 = tk.Button(buttons, ...)

b1.pack(side="left", ...)
b2.pack(side="left", ...)

# the form
for row, field in enumerate(fields):
    lab = tk.Label(form, ...)
    ent = tk.Entry(form, ...)

    lab.grid(row=row, column=0, ...)
    ent.grid(row=row, column=1, ...)

The form can be thought of as a single complex widget. You can do that by creating a class for the form, based off of the Frame widget:

class Form(tk.Frame):
    def __init__(self, parent, fields):
        tk.Frame.__init__(self, parent)
        for row, field in enumerate(fields):
            ...

You would then use it like a normal frame when adding it to the window:

form = Form(root, fields=fields)
...
form.pack(side="top", fill="both", expand=True)

With that, you now have a general purpose form that could be reused for different purposes with different sets of fields.


This code can be much improved.

The jmp prime_check is superfluous.

The comment ; The check for whether 2 is a prime is done separately here is wrong because it actually jumps to is_prime when n=3 due to the dec eax used at lb2.
Also checking for 2 is usually done with cmp eax,2 and je is_prime.

If you cleared EDX (with xor edx,edx) after lb1: you wouln't have to write it 2 times.

Why don't you replace that downright inelegant code with cmp eax,1 and je exit?

The usual way to test if EDX is zero is to use test edx,edx and jz lb2.


Generate consecutive sentence of int values accessed from different threads

private static int i = 0;

Are you sure that i should be static? If it's static there isn't too much sense of the Counter instance = new Counter() instance and the Next and the Reset methods also could be static.

Anyway, I'd use a longer variable name, like nextValue for better readability.

Furthermore, consider the drawbacks of the Singleton pattern:

  This pattern makes unit testing far more difficult,
  as it introduces global state into an application.

More on Wikipedia.


Backing up a file to prevent its corruption during processing

How great is the risk that your files will be corrupted? Is there a particular reason why you think this might happen, and if so, is that cause something you can address?

Are you concerned that it is your act of processing the file that might corrupt it? If so, you may want to do the opposite of what you're doing. Don't create a backup, but instead leave the original alone and create a working copy which you discard when you're done. If something goes wrong then at least your original file is still there, untouched.

This may sound facetious but it's not: If you don't trust your file system then it's not a good place for your application's data. How do you know that even after backing up, the file you're reading won't become corrupt as your're reading it? How do you know it wasn't already corrupt when it was backed up? How do you know that the backups won't be corrupted?

The best approach depends not only on how much you trust (or distrust) your storage but also how great the risk is if your data gets lost. If your server gets backed up regularly then that might be all the protection you need. Perhaps you could create a hash or a checksum for each file and store it with the file. When you process the file, validate that it matches the hash. That gives you about as much certainty as you could possibly want.


Berkeley CS61A alum here. Your solution looks fine. Having sat through many a lecture where the prof would go through problems like this, I can pretty much guarantee this is the solution that would have been given:

def min_element(tup):
    min = tup[0]
    for element in tup[1:]:
        if element < min:
            min = element
    return min

So this solution might be considered by someone really pedantic to be a bit "better" than yours since it is less verbose and because, in general, recursion tends to be slower than iteration. Your solution works just fine though :)


My suggestions are less about your design of the automaton, but rather a few comments on the style and language which I hope you will find useful.

Know your functions
Note that, string-null? is #t if the string has zero length. Thus, if ((string-null? str) "") is the same as if ((string-null? str) str). And that combines well with the else part in max-suffix-that-is-prefix which also returns str.

  (define (max-suffix-that-is-prefix str)
    (if (string-prefix? needle str)
        str
        (max-suffix-that-is-prefix (string-tail str))))

Named let
I noticed that some functions (enumerate and run-automata) define local functions only to then call them with initial values. Scheme provides a syntactic form for that, the named let:

(let proc-id ([id init-expr] ...) body ...+)

More on named let: https://docs.racket-lang.org/reference/let.html

Adhering to the declarative paradigm
The enumerate function could be written in a declarative style. To enumerate from start to end is to cons start to the enumeration from (+ start 1) to end.

(define (enumerate start end)
  (if (= start end)
      `(,end)
      (cons start (enumerate (+ start 1) end))))

Note, however, that this is not an equivalent formulation of the iterative style using an accumulator since the call the enumerate in the call to cons prevents tail-recursion optimisation.

Cleaner syntax using a named let:

(define (enumerate start end)
  (let iter ([start start]
             [end end]
             [acc '()])
    (if (> start end)
        acc
        (iter start (- end 1) (cons end acc)))))


Displaying user selection in the browser

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

I'm assuming this is the part that reads the JSON? There's JSON.parse for that. Feed it a JSON string and it should give you the equivalent object. No need to use eval.

/*****************/
/* Number Format */
/*****************/
function moneyFormat(num) {
    return '$' + parseFloat(num).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

I would suggest putting functions and any other inert operations higher up in the code. It's mostly for readability, knowing what exists before trying to use them.

Another is that parseFloat may return NaN. You may want to guard by checking against isNaN before handing it over to other operations.

Lastly, concatenating a string to a number (i.e.: 'foo' + 2) will automatically coerce the number to a string. Therefore you don't need the trailing toString().

if (selection[index].couplings != null)
{
    for (i = 0; i < selection[index].couplings.length; i++) {
        result += '
';
        result += '' + selection[index].couplings[i].description + '	';
        result += '' + moneyFormat(selection[index].couplings[i].price) + '	';
        result += '
';
    }
}

There's 2 ways to avoid writing markup in JS. One would be to construct the elements using document.createElement or by using a template library and construct the markup elsewhere.

A third option, if you have ES6 at your fingertips is to use template strings. This allows you to write multi-line strings in JS. And guess what? We can do something like this:

result += `

    ${selection[index].couplings[i].description}
    ${moneyFormat(selection[index].couplings[i].price)}

`;


Using boost::mpi to take the Euclidean norm of a vector

You've misspelt std::sqrt.

Calculation of 2D and 3D Euclidean norm is more accurate and efficient via std::hypot() - would it be reasonable to use that as a basis for the N-dimensional form?

As always, prefer standard containers such as std::vector over raw pointers created with new[].


That bus controller is too complicated; in general you should not be using new Promise(fn) unless you are wrapping a callback, and what you're doing is better done by returning a promise from the .then(). (When you return a value from myPromise.then() it gets passed into Promise.resolve(p), which if p is not a promise creates a new one which immediately resolves with the value you created; or if p is a promise, just returns that promise.)

In addition I wouldn't mix camelCase and underscore_names; it leads to bigger confusions across the codebase. In addition the form a ? a : b is equivalent to the shorter a || b. I also would in general add a debugging string to any console.log so that while you're in development you can better drill down to exactly what you're looking for.

With those changes the bus controller simplifies to just:

addBus: function(record, schoold) {
    return new Bus({
        language: language || "",
        bus_number: record.bus_number || "",
        bus_driver: bus_driver  || {},
        bus_details: bus_details,
        trips: trips || [],
        school_id: schoold,
        location: location || {}
    }).save().then(function (bus) {
        var bus_creation_user = {
            name: "باص رقم" + ' ' + record.bus_number,
            type: "3",
            refid: bus._id,
            email: record.email,
            phone_number: record.phone_number,
            school_id: schoold
        };
        console.log("bus_creation_user", bus_creation_user);
        return UserController.addUser(bus_creation_user);
    });
});

The code for using it seems mostly fine but has some code smells. For example what is the if doing in your .catch(err => { if (err) { ... } })? Are you legitimately throwing non-Error objects like null and undefined and false? (In JS you can do this but it is widely considered to be a bad idea.) Instead you can just write,

BusController.addBus(record, schoolId).then(function(){
    res.json({status:"success", message: "bus successfully created"});
}).catch(function(error){
    console.log(error);
    res.json({status:"error", message: "error while creating bus"});
});


first of all you hold Next Block Index in allocated block. but you not use it . Next Block Index (which is implicit pointer to next free block) used only in free block. as result you not need Next Block Index and Padding in allocated block. the Object Data must begin at begin of block. this give serious optimization by memory size and simplify code.

also instead index (implicit pointer) better use explicit pointer to next free block (or 0 if no more free blocks). this yet more simplify code.

next your code is not thread safe and not design to allocate/free in concurrent from multiple threads. however this is very easy can be implemented.

finally CalculatePadding simply wrong. impossible calculate align of object by it size. different objects with same size, can have different align.

first we need implement structure describes an entry in a block linked list:

struct LE
{
    LE* next;

    static void Push(LE* head, LE* entry)
    {
        LE *_next = head->next, *next;

        for( ; ; _next = next)
        {
            entry->next = _next;

            next = (LE*)InterlockedCompareExchangePointerRelease(
                (void**)&head->next, entry, _next);

            if (next == _next)
            {
                return;
            }
        }
    }

    static LE* Pop(LE* head)
    {
        LE* _entry = head->next, *entry;

        for ( ;_entry;_entry = entry)
        {
            entry = (LE*)InterlockedCompareExchangePointerAcquire(
                (void**)&head->next, _entry->next, _entry);

            if (entry == _entry)
            {
                return entry;
            }
        }
        return 0;
    }
};

we put this LE at begin of every free block. this will pointer to next free block (or 0 if this is the last free block). instead of index. with this we can allocate block by LE::Pop and free block by LE::Push.

#define DEBUG_CHECK 1

class FixedSizeMemoryPool
{
    LE m_head;
    void* m_buf;
    void (__stdcall * m_Free)(void*);
#if DEBUG_CHECK
    ULONG m_count;
#endif

public:

    FixedSizeMemoryPool() { m_buf = 0; }

    ~FixedSizeMemoryPool();

    void* Alloc()
    {
        return LE::Pop(&m_head);
    }

    void Free(void* data)
    {
        LE::Push(&m_head, reinterpret_cast<LE*>(data));
    }

    bool Create(ULONG objectSize, ULONG nObjects,
        void* (__stdcall* XxxAllocate)(ULONG),
        void (__stdcall * XxxFree)(void*));
};

FixedSizeMemoryPool::~FixedSizeMemoryPool()
{
    if (m_buf)
    {
#if DEBUG_CHECK
        ULONG count = m_count;

        if (LE* next = m_head.next)
        {
            do
            {
                --count;
            } while (next = next->next);
        }

        if (count)
        {
            __debugbreak();
        }
#endif
        m_Free(m_buf);
    }
}

bool FixedSizeMemoryPool::Create(ULONG objectSize, ULONG nObjects,
                                 void* (__stdcall* XxxAllocate)(ULONG),
                                 void (__stdcall * XxxFree)(void*))
{
    if (!objectSize || !nObjects || objectSize > MAXLONG)
    {
        return false;
    }

    if (objectSize < sizeof(LE))
    {
        // we need space for LE in block
        objectSize = sizeof(LE);
    }

    // must be aligned how minimum as LE
    objectSize = (objectSize + alignof(LE) - 1) & ~(alignof(LE) - 1);

    ULONGLONG size = (ULONGLONG)objectSize * (ULONGLONG)nObjects;

    if (size > MAXULONG)
    {
        return false;
    }

    union {
        void* buf;
        char* pb;
        LE* entry;
    };

    if (buf = XxxAllocate((ULONG)size))
    {
#if DEBUG_CHECK
        m_count = nObjects;
#endif
        m_buf = buf;
        m_Free = XxxFree;
        LE* next = 0;
        do
        {
            entry->next = next, next = entry;
        } while (pb += objectSize, --nObjects);

        m_head.next = next;

        return true;
    }

    return false;
}

note that client of FixedSizeMemoryPool must provide itself routines for allocate/free block of memory, where pool will be implemented. this give ability implement different memory types. also if objects(pool blocks) require special align (more than default allocation align), user implement this in allocate routine. say if we not need extended alignment for object, we can use

void* __stdcall XxxAlocate(ULONG s)
{
    return new char[s];
}

void __stdcall XxxFree(void* data)
{
    delete [] data;
}

if we need extended alignment - say want 64byte align for blocks in pool:

void* __stdcall XxxAlocate(ULONG s)
{
    return _aligned_malloc(s, 64);
}

void __stdcall XxxFree(void* data)
{
    _aligned_free(data);
}

and of course size of object (block) must be multiple of object(block) align


Here is how Edward Kmett implemented traverse in the Data.Functor.Coproduct package.

instance (Traversable f, Traversable g) => Traversable (Coproduct f g) where
  traverse f = coproduct
    (fmap (Coproduct . Left) . traverse f)
    (fmap (Coproduct . Right) . traverse f)

While he writes in a points free style and uses Either under the hood instead of your bespoke Coproduct instance, the result is still the same.  Apply the supplied function to either the left or right branch and wrap the result back in the constructor.

I do not see a better way to than the implementation given unless η-conversion to points-free is appealing for some reason.


C++ template to randomly choose from N elements with uniform distribution

Here's a version of your code which works with C-Strings by using std::decay to turn any array arguments into pointers.

This also uses perfect forwarding in the recursion, to preserve argument types, just in case unconditional conversion to a const reference is inappropriate.

I'm making this Community Wiki, because it's more of an answer to your question about C-Strings, rather than a code review (ok, little review: rand() is usually so poorly implemented, you should use something from <random>, like std::mt19937, otherwise, thumbs up!).

#include <iostream>
#include <type_traits>
#include <utility>
#include <string>
#include <cstdlib>

template <typename T>
using decay_t = typename std::decay<T>::type;

template <typename T>
decay_t<T> chooseImpl(T&& cur, int total) {
  return cur;
}

template <typename T, typename U, typename... Args>
decay_t<T> chooseImpl(T&& chosen, int total,  U&& next, Args&&... rest) {
  decay_t<T> nextChosen = (std::rand() % total == 0) ? next : chosen;
  return chooseImpl(nextChosen, total + 1, std::forward<Args>(rest)...);
}

template <typename T, typename... Args>
decay_t<T> choose(T&& first, Args&&... rest) {
  return chooseImpl(std::forward<T>(first), 2, std::forward<Args>(rest)...);
}

int main() {
    std::srand(time(0));
    for(int i=0; i<4; ++i) {
        auto c = choose("one", "two", "three");
        std::cout << c << ' ';
    }
    std::cout << '\n';
    for(int i=0; i<4; ++i) {
        auto c = choose(256, 512, 1024, 13);
        std::cout << c << ' ';
    }
    std::cout << '\n';
    const std::string s[7] = {"Aa", "Bb", "Cc", "Dd", "Ee", "Ff", "Gg"};
    for(int i=0; i<4; ++i) {
        auto c = choose(s[0],s[1],s[2],s[3],s[4],s[5],s[6]);
        std::cout << c << ' ';
    }
    std::cout << '\n';
}

Here is an example of the output:

two three one two
13 1024 1024 256
Bb Ff Ee Ee


If you don't want to use a subquery, you can include the second table with a join before the group by:
SQL Fiddle

SELECT max(name) name, SUM(amount) total
FROM purchases
INNER JOIN users on users.id = purchases.user_id
GROUP BY user_id
ORDER BY user_id

yielding

name    total
Joe       600
Joey      700
Joe       100


Quicklyish finding primes by trial division

I get (primes-upto 100000) taking about 40 ms. I can't make it go much faster, but I can make it reliable. At present, it isn't.

The program works:

(primes-upto 10) ;[2 3 5 7]

But if you take away the transients, it fails:

(defn primes-upto [n]
  (let [primes [2 3]]
    (loop [i 5]
      (if (> i n)
        primes
        (do (when
              (loop [j 0, is-prime true]
                (let [p (primes j)]
                  (when is-prime
                    (or (> (* p p) i)
                        (recur (inc j) (not= 0 (mod i p)))))))
              (conj primes i))
          (recur (+ i 2)))))))

(primes-upto 10); java.lang.IndexOutOfBoundsException: null ...

The program is depending upon accidents of how transients are implemented. Transients don't promise to update their bindings. They revoke the promise of immutability.

Rewriting the program idiomatically, I get ...

(defn primes-upto [n]
  (loop [primes [2 3], i 5]
    (if (> i n)
      primes
      (let [i-prime? (loop [j 1]
                       (let [p (long (primes j))]
                         (or (> (* p p) i)
                             (and (not= 0 (mod i p))
                                  (recur (inc j))))))]
        (recur (if i-prime? (conj primes i) primes) (+ i 2))))))

... including a few variations:

The inner loop is simpler, and employs and and or for brevity.
Since we increment i by 2, we don't need to check for division by
2, so start with j at 1.
Convert p to a long explicitly, to help with type inference.
Dispense with transients.

When all's said and done, it's a little faster, but not much. Transients don't help much either.


There are a few things you could do to make what you've got a bit faster:

The numbers get quite big but BigInt is overkill (and slow). The longestCollatzSeqHelper() method will have to deal with values in the Long domain, but the problem set, and results, are well within the Int range, which will be faster.
Because of the large numbers, you're cache could grow immensely. Perhaps beyond system resources.
You're testing n as many as 4 times per iteration. That can be reduced to 2.

But this is mere window dressing. When you encounter HackerRank timeout limits, code optimization usually doesn't get you very far. 9 times out of 10 you need to go back, re-examine the problem statement, and rethink your approach to it.

When I tackled this problem I started by caching calculations, but eventually I gave that up and started focusing on the other end:

To find the longest Collatz length for numbers <= N, I don't have to count the Collatz length for every number below N. There's a threshold below which it is impossible for the C-length to surpass the lengths for numbers above that threshold.
Some numbers don't need to have their Collatz length calculated at all. Due to a simple mathematical property it is impossible for its C-length to surpass its neighbors.

With this in mind, and caching for reuse only individual results within a problem set, you should be able to pass this challenge.


DISCLAIMER I don't believe in wrapping EF with a repository. Entity Framework is a unit-of-work and repository implementation.

  I've changed IEnumerable to IQueryable.

You've just destroyed the usefulness of your repository, and leaked Linq-to-Entities to your clients: it doesn't matter what predicate you give GetWhere, the client code can now just say GetWhere().Where(x => whatever);, and the client code now controls when (execution is deferred until the result is iterated) and how the query will run on the database server... and that defeats the purpose of a repository.

What you had before was much more robust.

One of the answerers of your other question said In general, use IQueryable over IEnumerable in your repository. - that did not mean to expose IQueryable.


This method feels like it should be its own class, and the arguments to the method should be constructor arguments. This is really where a "service" class can clean things up, because this method is really doing a lot.

First, I'd like to draw attention to the following lines:

   def self.authorized_status plugin_id, store_id, application_id, version, locale=nil
     if plugin_id.match /^(\w|-)+$/
       I18n.locale = locale || :en # I think I can move it to a concern

The "locale" is being set as a class-level value, which I understand is needed later on. This might have the unintended side affect of changing the locale for outside code. Consider this:

# Change locale to Spanish
I18n.locale = :es

status = YourClass.authorized_status(plugin_id, store_id, application_id, version)

# I18n.locale is now :en

You've now changed the locale for the entire application just by calling this method. In the very least you should save the "current locale" to a local variable, and at the end just before returning the status hash set the locale back to what it was before.

Aside from that, let the refactoring begin!

Given that the return value is a Hash, I'm assuming this is returned from some API controller that converts the Hash to JSON. You have this Business Logic of detecting authorized plugins, which you then couple to the output format of your application back to the client. I would create a class specifically to hold the plugin authorization status:

class PluginAuthorization
  attr_reader :plugin, :status, :message

  def initialize(plugin, is_authorized, status, message)
    @plugin = plugin
    @is_authorized = is_authorized
    @status = status
    @message = message
  end

  def authorized?
    @is_authorized
  end

  def to_h
    { status: status, message: message }
  end
end

This has three advantages:

You are not coupling your Business Logic to your controller's output format
You have a concrete class you could repurpose for a web page as well as a JSON return type
You have a clearly defined interface for just what the authorization data looks like.

Now we can start building our plugin authorization service class -- in fact, that's a perfect name for this class:

class PluginAuthorizationService
  def initialize(plugin_id, store_id, application_id, version)
    # Initialize instance variables
  end

  def authorize(locale = :en)
    # Create and return a new PluginAuthorization object
  end
end

This gives us the basic skeleton to start our refactoring job. Without diving into the gritty details, let's look how you would use this service class in an API controller:

class PluginsController < ActionController::API
  def authorize
    plugin_id = params[:plugin_id]
    store_id = params[:store_id]
    application_id = params[:application_id]
    version = params[:version]
    locale = params[:locale]
    authorization_service = PluginAuthorizationService.new plugin_id, store_id, application_id, version
    authorization = authorization_service.authorize locale

    if authorization.authorized?
      # do something
    else
      # do something else
    end

    render json: authorization.to_h
  end
end

This keeps your controller simple, plus the business logic of authorizing a plugin is encapsulated by the service class. Now that we have an idea what our end goal will be, let's fill in the blanks (and they are big blanks).

First, the status constants should go in the service class, plus let's flesh out the constructor so it does as little work as possible (like any constructor should).

class PluginAuthorizationService

  PLUGIN_ID_FORMAT_ERROR = '...'
  UNREGISTERED_PLUGIN = '...'
  UNKNOWN_APPLICATION = '...'
  NOT_AUTHORIZED = '...'
  AUTHORIZED = '...'

  def initialize(plugin_id, store_id, application_id, version)
    @plugin_id = plugin_id
    @store_id = store_id
    @application_id = application_id
    @version = version
    @application_id_and_version = {
      application_id: application_id,
      version: version,
      status: Application::PUBLISHED_STATUS
    }
  end

  # ...
end

We need a plugin Id, store Id, application Id and version. The original code had the locale default to :en so we can supply that as an argument to the authorize method. The only other thing we do is create a Hash for the @application_id_and_version since this is referenced later as part of the WHERE condition for some queries.

The first bit of cleaning up is the plugin variable, which can be found using one of two methods, with the additional requirement that the method used to find the plugin is used elsewhere in a query:

class PluginAuthorizationService
  # ...

private

  def plugin
    return @plugin unless @plugin.nil?

    @plugin = Plugin.find_by_iid @plugin_id

    if @plugin.nil?
      @plugin_found_by = :aid
      @plugin = Plugin.find_by_aid @plugin_id
    else
      @plugin_found_by = :iid
    end

    @plugin
  end

  def plugin_found_by
    plugin
    @plugin_found_by
  end

Any time you need a Plugin object you call the plugin method. The plugin_found_by method calls plugin to make sure the method by which the plugin is found gets calculated.

Next, we have some ActiveRecord queries to clean up and encapsulate into their own methods:

   # Query 1
   ApplicationUpdate.where(application_id: application_id).joins(application: :store).where(application: {store_id: store_id} )

   # Query 2
   ApplicationUpdate.where(application_id_and_version).count == 0

   # Query 3
   Group.joins(users: :plugins).where(users: {plugins: {found_by => plugin_id}})
     .joins(:application_updates)
     .where(application_updates: application_id_and_version)

We will create methods on the service class for these queries:

private

  # Query 1
  def application_update
    @application_update ||= ApplicationUpdate.where(application_id: @application_id)
                                             .joins(application: :store)
                                             .where(application: {store_id: @store_id} )
                                             .first
  end

  # Query 2
  def application_update_exists?
    ApplicationUpdate.where(@application_id_and_version).count > 0
  end

  # Query 3
  def plugin_groups
    @plugin_groups ||= Group.joins(users: :plugins)
                            .where(users: {plugins: {plugin_found_by => @plugin_id}})
                            .joins(:application_updates)
                            .where(application_updates: @application_id_and_version)
  end

Notice that the plugin_groups method calls the aforementioned plugin_found_by method in the WHERE clause for the query.

Next, let's focus on the following line of code in the original post:

   is_store = update_by_application_id.first.application.is_store? if !update_by_application_id.first.nil?

This too is a good candidate for its own method, but first let's modify the ApplicationUpdate class to make it easier to adhere to the Principle of Least Knowledge:

class ApplicationUpdate < ActiveRecord::Base
  delegate :is_store?, :to => :application, :allow_nil => true

  # ...
end

This allows us to call application_update.is_store? and not require outside code to traverse the application property. Now, the method on PluginAuthorizationService:

private
  # ...

  def is_store?
    application_update.try :is_store?
  end

Calling application_update.try removes the need for a nil-check.

Another opportunity for properly encapsulated code is in the following line:

   if !authorized || BlacklistedPlugin.find_by_organisation_id_and_plugin_id(store.organisation_id, plugin.id)

The Plugin class should have a method that performs this logic:

class Plugin < ActiveRecord::Base
  # ...

  def blacklisted?(organization_id)
    !!BlacklistedPlugin.find_by_organisation_id_and_plugin_id(organisation_id, self.id)
  end
end

We will also add a few more helper methods to our service class to make our lives easier:

private
  # ...

  def plugin_unregistered?
    plugin.nil? || plugin.user.nil?
  end

  def store
    @store ||= Store.find @store_id
  end

  def valid_plugin_id?
    @plugin_id.match /^(\w|-)+$/
  end

  def authorized?
    @is_authorized ||= !store.preauthorized? || is_store? || plugin.authorized_for_store?(store)
  end

end # End of PluginAuthorizationService class

We've only seen bits and pieces of this, so let's put things all together, and see how the authorize method on the service class ends up:

class PluginAuthorizationService

  PLUGIN_ID_FORMAT_ERROR = '...'
  UNREGISTERED_PLUGIN = '...'
  UNKNOWN_APPLICATION = '...'
  NOT_AUTHORIZED = '...'
  AUTHORIZED = '...'

  def initialize(plugin_id, store_id, application_id, version)
    @plugin_id = plugin_id
    @store_id = store_id
    @application_id = application_id
    @version = version
    @application_id_and_version = {
      application_id: application_id,
      version: version,
      status: Application::PUBLISHED_STATUS
    }
  end

  def authorize(locale = :en)
    previous_locale = I18n.locale
    I18n.locale = locale

    authorization = if !valid_plugin_id?
                      PluginAuthorization.new plugin, false, PLUGIN_ID_FORMAT_ERROR, I18n.t('....')
                    elsif plugin_unregistered?
                      PluginAuthorization.new plugin, false, UNREGISTERED_PLUGIN, I18n.t('....')
                    elsif !application_update_exists? && !is_store?
                      PluginAuthorization.new plugin, false, UNKNOWN_APPLICATION, I18n.t('....')
                    elsif !is_store? && plugin_groups.empty?
                      PluginAuthorization.new plugin, false, NOT_AUTHORIZED, I18n.t('....')
                    elsif !authorized? || plugin.blacklisted?(store.organisation_id)
                      PluginAuthorization.new plugin, false, NOT_AUTHORIZED, I18n.t('....')
                    else
                      PluginAuthorization.new plugin, true, AUTHORIZED, I18n.t('....')
                    end

    I18n.locale = previous_locale

    authorization
  end

private

  def application_update
    @application_update ||= ApplicationUpdate.where(application_id: @application_id)
                                             .joins(application: :store)
                                             .where(application: {store_id: @store_id} )
                                             .first
  end

  def application_update_exists?
    ApplicationUpdate.where(@application_id_and_version).count > 0
  end

  def authorized?
    @is_authorized ||= !store.preauthorized? || is_store? || plugin.authorized_for_store?(store)
  end

  def plugin_groups
    @plugin_groups ||= Group.joins(users: :plugins)
                            .where(users: {plugins: {plugin_found_by => @plugin_id}})
                            .joins(:application_updates)
                            .where(application_updates: @application_id_and_version)
  end

  def is_store?
    application_update.try :is_store?
  end

  def plugin
    return @plugin unless @plugin.nil?

    @plugin = Plugin.find_by_iid @plugin_id

    if @plugin.nil?
      @plugin_found_by = :aid
      @plugin = Plugin.find_by_aid @plugin_id
    else
      @plugin_found_by = :iid
    end

    @plugin
  end

  def plugin_found_by
    plugin
    @plugin_found_by
  end

  def plugin_unregistered?
    plugin.nil? || plugin.user.nil?
  end

  def store
    @store ||= Store.find @store_id
  end

  def valid_plugin_id?
    @plugin_id.match /^(\w|-)+$/
  end

end

The authorize method has been reduced to 22 lines, and by utilizing properly named methods, authorize reads more like natural language and becomes much easier to understand:

if not a valid plugin id
    ...
else if plugin unregistered?
    ...
else if not application_update_exists? and not is_store?
    ...
else if not is_store? and plugin_groups is empty?
    ...
else if not authorized? or plugin blacklisted? by store.organisation_id
    ...
else
    Authorized!
end


You should declare variables in the smallest possible scope. E.g. instead of

String family;
for  (...) {
    family = ...;
    ...
}

we could do

for (...) {
    String family = ...;
    ...
}

The same applies to docInfo, doc1, doc2, sorted, intersectionWords, different, and index.

You have this snippet:

Iterator<String> iterator = different.iterator();
while (iterator.hasNext()) {
    String s = iterator.next();
    ...
}

which could be abbreviated to for (String s : different) { ... }.

If we clean up these two points, we end up with this:

public void setDocunents() {
    // Neighbor contain the arrayList of Documents
    neighbors.add(new Neighbor<Integer>("sky"));
    neighbors.add(new Neighbor<Integer>("earth"));

    try {
        Map<Long, String> docInfo = dbDocMeta.getDocInfo();
        for (Long id : docInfo.keySet()) {
            String family = docInfo.get(id).contains("sky") ? "sky" : "earth";
            for (Neighbor<Integer> neighbor : neighbors) {
                // check if the document in the Neighbour family
                if (neighbor.getFamily().equalsIgnoreCase(family)) {
                    HashSet<String> different = new HashSet<String>();
                    different.addAll(someWord);
                    Document<String> doc1 = dbWords.getNeighbors(id);
                    Document<Integer> doc2 = new Document<Integer>();
                    ArrayList<String> intersectionWords = new ArrayList<String>();
                    for (String word : doc1.getMap().keySet()) {
                        int index = dbWords.getIndex(word);
                        if (selectedFeatures.contains(word)) {
                            doc2.add(index, doc1.getAttributes().get(word));
                            intersectionWords.add(word);
                        }
                    }
                    if (!doc2.getMap().isEmpty()) {
                        different.removeAll(intersectionWords);
                        for (String s : different) {
                            int index = dbWords.getIndex(s);
                            doc2.add(index, 0);
                        }
                        Map<Integer, Long> sorted = new TreeMap<Integer, Long>(doc2.getAttributes());
                        doc2.setMap(sorted);
                        neighbor.addDocument(doc2);
                        break;
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        logger.error("InterruptedException msg : {} \n {}", e.getMessage(), e.getStackTrace());
    } catch (ClassNotFoundException e) {
        logger.error("ClassNotFoundException msg : {} \n {}", e.getMessage(), e.getStackTrace());
    }
}

In a next step, we remove calculations from inner loops that don't have to be recalculated each time. E.g. doc1 = dbWords.getNeighbors(id) depends only on id, and probably does not have to be called for each neighbor. On the other hand, different is only needed inside a specific if branch.

Furthermore, doc2 will be discarded unless that branch is entered, so we will build it only in that case (assuming doc2.getMap().isEmpty() is equivalent to intersectionWords.isEmpty().

We can further remove unnecessary variables – their types just add clutter to the code.

A bare break inside nested loops can be a bit confusing, so we'll use the labelled for: break neighbors.

The HashSet constructor can directly take a collection, there is no need to separately call addAll.

If the whole body of a loop us subject to an if (cond), it is often easier to read when at the beginning of a loop, we if (!cond) continue.

Unrelated implementation details like calculating the intersection of two sets should be factored out into helper functions.

public void setDocunents() {
    // Neighbor contain the arrayList of Documents
    neighbors.add(new Neighbor<Integer>("sky"));
    neighbors.add(new Neighbor<Integer>("earth"));

    try {
        Map<Long, String> docInfo = dbDocMeta.getDocInfo();
        for (Long id : docInfo.keySet()) {
            String family = docInfo.get(id).contains("sky") ? "sky" : "earth";
            Document<String> doc1 = dbWords.getNeighbors(id);

            neighbors:
            for (Neighbor<Integer> neighbor : neighbors) {
                // check if the document in the Neighbour family
                if (!neighbor.getFamily().equalsIgnoreCase(family)) {
                    continue neighbors;
                }

                Set<String> intersectionWords = intersection<String>(doc1.getMap().keySet(), selectedFeatures);
                if (intersectionWords.isEmpty()) {
                    continue neighbors;
                }

                HashSet<String> different = new HashSet<String>(someWord);
                Document<Integer> doc2 = new Document<Integer>();
                for (String s : intersectionWords) {
                    doc2.add(dbWords.getIndex(word), doc1.getAttributes().get(word));
                    different.remove(s);
                }
                for (String s : different) {
                    doc2.add(dbWords.getIndex(s), 0);
                }
                // due to the choice of a TreeMap, the elements are sorted
                doc2.setMap(new TreeMap<Integer, Long>(doc2.getAttributes()));
                neighbor.addDocument(doc2);

                break neighbors;
            }
        }
    } catch (InterruptedException e) {
        logger.error("InterruptedException msg : {} \n {}", e.getMessage(), e.getStackTrace());
    } catch (ClassNotFoundException e) {
        logger.error("ClassNotFoundException msg : {} \n {}", e.getMessage(), e.getStackTrace());
    }
}

private static <A> Set<A> intersection(final Set<A> xs, final Set<A> ys) {
    // make sure that xs is the smaller set
    if (ys.size() < xs.size()) {
        return intersection<A>(ys, xs);
    }

    final HashSet<A> result = new HashSet<>();
    for (A x : xs) {
        if (ys.contains(x)) {
            result.add(x)
        }
    }

    return result;
}

This could be optimized further, e.g. when doc2.add(…) has no side effects except setting the underlying map, or if the composition of someWord is known.


Output JavaScript object into HTML table of key-value pairs using jQuery

Let's start with your version:

1) Unnecessary optimization.

var array_length = Object.keys(basic_data).length;
var array_obj_names = Object.keys(basic_data);

This gives you nothing in terms of performance. It would be optimized away by the browser.

2) Chain-calling

$(table_id).empty();
$(table_id).append('
');

It is possible to do chain-calls like: $('#elem').doA().doB().doC()

3) Misunderstanding calls

$(table_id).find('thead:last').append('Tag');

.append() does exactly that: appending after the last element.

4) NuStyleLoopz

  for (var i = 0; i < array_length; i++) {
    var attr_name = array_obj_names[i];
    var tag       = '' + array_obj_names[i];
    var data      = '' + basic_data[attr_name];

You could iterate over the keys directly via Object.keys() with

Array.prototype.forEach()
Array.prototype.map()
Array.protoype.reduce() / Array.prototype.reduceRight().

Here a slighty pimped version:

makeTag=function(openTag, closeTag){
            return function(content){
                return openTag+content+closeTag;
            };
        };
tHead=makeTag("
","
");
tBody=makeTag("
","
");
td=makeTag("","	");
tr=makeTag("
","
");

function insertBasicTable(data,id){
    $('#'+id).html(
        tHead(
            tr(
                td("Tag")+
                td("Data")
            )
        )+
        tBody(
            Object.keys(data).reduce(function(o,n){
                return o+tr(
                    td(n)+""+
                    td(data[n]+"")
                );
            },"")
        )
    );
};

insertBasicTable({"key1":"value1","key2":"value2"},"mytable");

Here is the fiddle to play with.

To make HTML-generation less painfull and a bit more JS-stylish I define what is called a higher order function makeTag: simply a function returning a function. A call to var tHead=makeTag("
","
"); generates an anonymous function (a function without name), which returns every time it's called "
"+ parameter +"
". The same goes for the other tags. This allows me to do something like a DSL:

    tHead(
        tr(
            td("Tag")+
            td("Data")
        )
    )

That is not only handy, but cool B-)
Besides it is nearly as readable as html and not so noisy like the typical string concatenation and the risk of typos is really low.


Having a look at the HackerRank problem, the title is implying a HashTable might be a nice data structure to use for this problem ("Hash Tables: Ransom Note"). You might want to look up more about the theory, some examples in JS, (and even more/reference). JS objects can also be used as HashMaps, with a discussion of the pros and cons of this in other SO answers.

Essentially, with a (Hash)Map we can associate keys of some type, with values of the same or another type. Such as mapping strings -> integers. Setting and looking up a value in a map is in constant O(1) time, whereas with an array, looking for a value (indexOf()) is in linear O(n) time. Using Map, the problem could be reduced to linear complexity. (Additionally, splice is an 'expensive' O(n) operation to remove an element from an array in JS).

Here is an idea / some pseudocode of how you might use a Map to solve the problem by mapping each word (string) to the count of how many occurrences we have of that word (integer).

map is an initially empty map

for every word in magazine:
    if word not in map:
        add word to map with count 1
    else:
        increment count of word in map

for every word in note:
    if word not in map or count of word in map = 0:
        show "No."
        return
    else:
        decrement count of word in map (word has been used)

show "Yes."
return

Ignoring the hashtables for a moment, your code is a bit unnecessarily complicated in places. We don't actually need two nested for-loops. Only one that goes through all words in note and removes them from magazine array as we use them up. This removes the need for all the nested if- conditions and the boolean flag isRansom. Finally, if you have something that looks like at the end of a function:

if(someBooleanValue) {
    return true;
}

This can be replaced by:

return someBooleanValue;

Check also the parameter and return types of the function: in the HackerRank problem, magazine and note are already string arrays, and the function is not expected to return a boolean value, merely print to the console. With that in mind, here is how it could be done:

function checkMagazine(magazine, note) {
    for (let word of note) {
        let i = magazine.indexOf(word);

        if (i == -1) {
            console.log("No")
            return;
        }
        magazine.splice(i, 1);
    }

    console.log('Yes');
}

Note that despite there being no nested for-loops, it is still quadratic in complexity due to the outer loop (for every word in note), and the linear complexity of splice and indexOf inside this loop.


The way you define your various functions is inconsistent:

you define add, sub, putch, yet use data[index] = getch()[0] directly in the generated code;
you group together multiple +, -, <, and > but neither . nor , (not that this last one would be of great use but still, for the sake of consistency);
you access global data into those functions;
putch is defined using a lambda but add and sub uses def…

Since [ and ] are special anyway as they do more than producing a string, I'd rather choose to either:

inline everything in the generated code;
or only use functions that take data, index and count as parameters.

I would also generate code that respect some standard practices: defining a main function and wrapping its call into an if __name__ == '__main__': guard. This would mean starting level at 1 as you would generate code that is inside a def main():.

You should also take a look at textwrap.dedent to simplify your header (and thus footer too) generation.

And since you are using formated strings, you could make directly use of the variable width alignment such as f'{"": >{level*4}}rest of the code'.

Storing generated instructions into a list that is returned at the end feels like your function would benefit from being turned into a generator. Especially if you plan on writing the generated string to a file, this would help interleaving computation and waiting for I/O.

Lastly your assertion feels off as they can be turned off at runtime. Instead I would raise a real exception such as ValueError with a proper error message.

Proposed improvements with code inlined:

import itertools
from textwrap import dedent
from contextlib import suppress

BYTECODES = {
        '+': '{0: >{1}}data[index] = (data[index] + {2}) % 256',
        '-': '{0: >{1}}data[index] = (data[index] - {2}) % 256',
        '<': '{0: >{1}}index -= {2}',
        '>': '{0: >{1}}index += {2}',
        '.': '{0: >{1}}for _ in range({2}):\n{0: >{1}}    print(chr(data[index]), end="")',
        ',': '{0: >{1}}for _ in range({2}):\n{0: >{1}}    data[index] = getch()[0]',
}

def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    yield from itertools.zip_longest(a, b)

def compile(sourcecode):
    yield dedent("""\
            from collections import defaultdict
            from msvcrt import getch

            def main():
                index = 0
                data = defaultdict(int)""")

    level = count = 1
    for operation, next_operation in pairwise(sourcecode):
        if operation == '[':
            yield f'{"": >{level*4}}while data[index]:'
            level += 1
        elif operation == ']':
            level -= 1
            if level < 1:
                raise ValueError('Unbalanced brackets, found ] before opening [')
        elif operation == next_operation:
            count += 1
        else:
            with suppress(KeyError):
                yield BYTECODES[operation].format('', level * 4, count)
            count = 1

    yield dedent("""\

            if __name__ == '__main__':
                main()""")

def translate(sourcecode):
    return '\n'.join(compile(sourcecode))

if __name__ == '__main__':
    code = '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.'
    for line in compile(code):
        print(line)

    print('*------*')
    print(translate(code))

Proposed improvements with functions defined:

import itertools
from textwrap import dedent
from contextlib import suppress

BYTECODES = {
        '+': '{0: >{1}}add(data, index, {2})',
        '-': '{0: >{1}}sub(data, index, {2})',
        '<': '{0: >{1}}index -= {2}',
        '>': '{0: >{1}}index += {2}',
        '.': '{0: >{1}}putchar(data, index, {2})',
        ',': '{0: >{1}}getchar(data, index, {2})',
}

def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    yield from itertools.zip_longest(a, b)

def compile(sourcecode):
    yield dedent("""\
            from collections import defaultdict
            from msvcrt import getch

            def add(data, index, x):
                data[index] = (data[index] + x) % 256

            def sub(data, index, x):
                data[index] = (data[index] - x) % 256

            def putchar(data, index, x):
                for _ in range(x):
                    print(chr(data[index]), end='')

            def getchar(data, index, x):
                for _ in range(x):
                    data[index] = getch()[0]

            def main():
                index = 0
                data = defaultdict(int)""")

    level = count = 1
    for operation, next_operation in pairwise(sourcecode):
        if operation == '[':
            yield f'{"": >{level*4}}while data[index]:'
            level += 1
        elif operation == ']':
            level -= 1
            if level < 1:
                raise ValueError('Unbalanced brackets, found ] before opening [')
        elif operation == next_operation:
            count += 1
        else:
            with suppress(KeyError):
                yield BYTECODES[operation].format('', level * 4, count)
            count = 1

    yield dedent("""\

            if __name__ == '__main__':
                main()""")

def translate(sourcecode):
    return '\n'.join(compile(sourcecode))

if __name__ == '__main__':
    code = '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.'
    for line in compile(code):
        print(line)

    print('*------*')
    print(translate(code))

As you can see, differences are minimal but generated code feels neater for the second version. I also kept the translate function for ease of use but the generator is simple enough to use on its own.


Testing input validation and an AJAX request with Javascript and QUnit

My reasoning here is that unit tests aren't supposed to test anything
  external

I agree with that. You can't test external things like an AJAX call anyway.

  I'm unhappy with this, because it still doesn't tell me that
  appendSoldier works like it's supposed to.

Actually, you CAN test the appendSoldier method. You need to refactor it in the following way:

function appendSoldier() {
    $.get("/ajax/soldier",
    {
       rank: rankField.val(),
       name: nameField.val(),
    }).done(
        function(data) {
            // Notice that I extracted these 2 lines of code into a separate method
            // soldiers = extractSoldiersFromList(data);
            // renderHTMLListFromData(soldiers);
            appendSoldierSuccess(data);
        }
    );

    clearInput();
};

// This is the extracted method
function appendSoldierSuccess(data) {
    soldiers = extractSoldiersFromList(data);
    renderHTMLListFromData(soldiers);
}

Now you can unit test the functionality in the following way (I will use Jasmine because I'm familiar with it but the concepts can be mapped to Sinon):

it("appendSoldierSuccess()", function() {
    var data = {};
    var soldiers = {};

    spyOn(window, 'extractSoldiersFromList').and.returnValue(soldiers);
    spyOn(window, 'renderHTMLListFromData');

    appendSoldierSuccess(data);

    expect(window.extractSoldiersFromList).toHaveBeenCalledWith(data);
    expect(window.renderHTMLListFromData).toHaveBeenCalledWith(soldiers);
});