Abstractness

  To be precise, this class is meant to be inherited by multiple derived classes, which actually define the constants.

Do you mean there will be many classes each of which contain a constant set of bytes, but are otherwise the same? If so, then there is no need to create a new class for each one. You could instead just provide static readonly instances for each constant, e.g.

public static class MagicNumbers
{
    public static readonly Bytes Example1 = new Bytes(new byte[] { 0xFF, 0xFF });
    public static readonly Bytes Example2 = new Bytes(new byte[] { 0xFE, 0xFF });
}

Readonlyness

This certainly provides a read-only interface, which is good. The only way to violate the read-onlyness would be with reflection (which it is essentially always fine to ignore).

You are right that the backing collection of a ReadOnlyCollection<T> can change; this is all part of the 'interface is gospel' approach of languages like C# (which personally I subscribe to whole-heartedly). Note that if you pass a ReadOnlyCollection<T> to someone else, however, that they can't modify it. This means it is up to whoever creates the backing collections for the ReadOnlyCollection<T> as to what can or cannot be done with it. ReadOnlyCollection<T>, however, is not a type I would use for anything, pretty much, because it unhelpfully implements IList<T> (among other things). It's also annoyingly named (in my opinion), because IReadOnlyCollection<T> doesn't expose indexed retrieval (that's IReadOnlyList<T> job).

It's good that your constructor takes an IEnumerable<T>. You might consider implementing IReadOnlyList<T> (which 'includes' IEnumerable<T>) if you think it appropriate; this would expose an efficient implementation of Count and T this[int] (more discussion about this below).

Inside your class you could also use a read-only collection instead of List<byte>, to enforce the contract internally, e.g. IReadOnlyList<T>.

Properties

Your Count and Length properties are, as you comment, redundant. Don't do this: it will only create confusion. Length is (in my experiance) pretty much exclusive to arrays: go with Count instead (it's the property exposed by IReadOnlyList<T>), and instead of storing the value, I'd suggest retrieving it from the actual list, which means the construtor has less to do (which means there is less to go wrong).

 public int Count => bytesList.Count;

It's good that your external properties were readonly (this is preserved with the 'expression-bodied property' syntax above). You might also want to make bytesList readonly (the class is fine as it is, because it's public API is sound, but this again will enforce the contract inside the class, making it easier to maintain and understand).

Concerning readonly vs getter-only, unless I have good reason (which basically never happens), I go with getter-only. While what Rob says in the linked thread is true, I personlly don't care what a class does so long as the API makes sense, and a public readonly field has two important disadvantages over getter-only properties: it can't implement an interface property (e.g. int IReadOnlyList.Count), and you can't quietly change it to be a property in future. For example, changing your public int read-only Count to public int Count => byteList.Count is a binary breaking change: any code that depends on the old field needs to be recompiled to work with the new property. If, however, you had made it public int Count { get; }, then you could make this change to the implementation without breaking any consuming code. One case where you might want this would be AsString: if you found that this was hardly ever being used, you might consider deferring the creation until it is needed: you can't do this with a readonly field, but you can easily replace a getter-only property with one which implements caching.

In practical terms, as Henk Holterman points out in the linked thread, readonly fields are a nightmare when it comes to serialisation. A getter-only field, however, can become a { get; private set; } field without issue if your serialisation scheme demands it. This is by no means ideal, but it doesn't change the external API, so the unpleasantness is contained within the class.

Indexer this[int]

You might consider the expression-bodied member syntax again:

public byte this[int i] => this.bytesList[ i >= 0 ? i : i + this.Count ];

Though it's just syntatic sugar we could live without, it is arguably a bit easier to read, and makes it immediately apprent that there is no set block.

If you did decide to implement IReadOnlyList, you would need 2 versions of this methods; one with the negative-index support, and one without.

byte IReadOnlyList<T>.this[int i] => this.bytesList[i];
public byte this[int i] => this.bytesList[ i >= 0 ? i : i + this.Count ];

This means that code which misuses the IReadOnlyList<T> interface will still get an out-of-bounds error, but anyone who has an instance of your class by name of the class can use the negative-indexing.

Namespace qualifiers

It's been a while since I used Python for anything substancial, but my understanding is that *-imports pull methods as well as classes, so the issue is lesser in C# (only pulls types and other namespaces). As you say, it's pretty standard for C#ers to use *-imports, and because it is expected, APIs are designed in a manner which assumes it: e.g. there are many more namespaces in C# than C++. Most importantly, however, is that C# fails at compile-time if there are observed name-collisions (e.g. even if Horse could be interpreted as two things, the code is fine so long as you don't try to use Horse unqualified). This means two things have to change for library authors to break your code - the introduction of a 'duplicate' method or type in a dependency in Python will quietly create problems - and you can't break your own (because it won't compile). The only leak in all this, is that classes in their own namespace are preferred over classes in an imported namespace (but only the author of that namespace can change the behaviour of their code, not someone else).

using CollectionsGen = System.Collections.Generic would mostly horrifying me because Gen is truncated. Anothing think you'll find in C# is that we prefer long easy-to-remember-and-understand names over short quicker-to-type (if you can remember them) names. The time-to-type is minimised by auto-complete in the IDE/editor.

Documentation

It's good that your class has an inline-summary, but inline-documentation (///) on all public non-inherited members significantly improved usabily. The Count == Length thing, for example, would be confusing no end, which is why you have a comment in your code to remind you that it is correct: this same comment should be available to the people using your code. The negative-indexing support is another thing that should be documented externally. The constructor should also state that it takes a copy of the IEnumerable; while this is implied (by virtue of taking an IEnumerable<T> rather than, say, an IReadOnlyList<T>), as a consumer of your code I would appreciate knowing that this is the intended long-term behaviour and not just an implementation detail.

Remember: code is consumed far more often than it is read or written (which people all too often seem to forget).

Misc

I wouldn't bother with the lining stuff up; it's just effort to maintain.
I'd also avoid things like "x>=2", and some IDEs will 'correct' it to x >= 2, so you'll just end up fighting them. If expressions need grouping, then use parenthesis, which are unambiguous.
If you are worried about space, consider using a byte[] rather than a list (you can use LINQ's IEnumerable<T>.ToArray() (guarantees copy) to keep the code short. (Note that byte[] implements IReadOnlyList<T>).


You use explicit recursion, which is fun, but not always necessary. arraySearchBegin can be expressed with zipWith and and, for example:

arraySearchBegin :: (Eq a) => [a] -> [a] -> b -> Maybe b
arraySearchBegin hs ns k
  | and (zipWith (==) hs ns) = Just k
  | otherwise                = Nothing

But that's still to explicit. Data.List contains isPrefixOf, which is exactly what we need:

import Data.List (isPrefixOf)

arraySearchBegin :: (Eq a) => [a] -> [a] -> b -> Maybe b
arraySearchBegin hs ns k
  | ns `isPrefixOf` hs = Just k
  | otherwise          = Nothing

That being said, arraySearchBegin's name is misleading. [a] is a linked list, not an array. We should probably rename it, but we won't use it in the final variant of arraySearch.

Next, we don't need the Maybe Int in arraySearchNext:

arraySearchNext :: (Eq a) => [a] -> [a] -> Int -> Maybe Int
arraySearchNext []         ns _ = Nothing
arraySearchNext hss@(_:hs) ns i
  | ns `isPrefixOf` hss = Just i
  | otherwise           = arraySearchNext hs ns (i + 1)

We can stop as soon as our needle is a prefix of our haystack. However, we're basically checking all tails of hss here. And there is again a function in Data.List that yields those tails for us:

ghci> import Data.List
ghci> tails [1..5]
[[1,2,3,4,5],[2,3,4,5],[3,4,5],[4,5],[5],[]]

We therefore just check which one is the first list in tails haystack that can be prefixed by needle. If we zip the indexes with the tails we're able to write arraySearch  as a list comprehension:

import Data.Maybe (listToMaybe)
import Data.List (isPrefixOf, tails)

search :: Eq a => [a] -> [a] -> Maybe Int
search hs ns = listToMaybe [ idx | (idx, hss) <- zip [0..] tails hs
                                 , ns `isPrefixOf` hss
                           ]

But Data.List contains findIndex :: (a -> Bool) -> [a] -> Maybe Int, which brings us to:

import Data.List (isPrefixOf, tails, findIndex)

search :: Eq a => [a] -> [a] -> Maybe Int
search hs ns = findIndex (ns `isPrefixOf`) (tails hs)

This however needs knowledge of the standard library. So how do you find those functions if you don't know them yet? Welcome to Hoogle. We can find findIndex by searching for (a -> Bool) -> [a] -> Maybe Int, isPrefixOf by Eq a => [a] -> [a] -> Bool and tails by [a] -> [[a]].

If we didn't have any of those helpers, your code would be fine, except for the strange explicit result in arraySearchNext's first argument. That was too complex, as you will stop as soon as you find a Just either way.


There are a few things I've noticed.

This line if (null != node) return type == ParseType.InnerHtml ? node.InnerHtml : type == ParseType.OuterHtml ? node.OuterHtml : type == ParseType.InnerText ? node.InnerText : node.Attributes[attributes].Value; is very confusing.  You are mixing and if statement with multiple ternary really clutters up that line of code.
You shoud look into the var keyword.  When the variable type is obvious, it is pretty much stand practise to use it.  I think it really cleans up code.
I'm not sure why you are using GC.Collect() in your constructor.  In C# there is not usually a need to control Garbage Collection.  The framework deals with it pretty well.
I would change if (null != Documents) to if (Documents != null).  I know why that syntax is done in C/C++, but in C# it is not needed, and the latter is much more descriptive and easier to understand.
I would be careful about returning null from a method.  It adds extra code where the method is called to check for null.  Maybe look into the null object design pattern

Other than that, your use of white space and indentation is very well done.  Makes reading your code much easier.


You can use the following utility method:

public static void setStrings (CallableStatement stmt, Object ... values)
{
    for (int count = values.length, i = 0; i < count; i++)
        stmt.setString (i + 1, String.valueOf (values [i]));
}

in your run() like this:

setStrings (
    callableStatement,
    userId,
    Constants.getaAccount (userId),
    Constants.getaAdvertising (userId),
    ...
    Constants.getaSrpBuyerUpiCount (userId));

This is shorter and much more readable for me.


The challenge only asks for the biggest number after all operations.
Printing the complete array after each operation might cause it to fail –
either by the unexpected output or by the time spent for the log operation.

Also, determining the maximum after each operation is inefficient, this is
better done after all operations.

But what you actually need to pass the challenge is a better algorithm.
The inner loop

for (let k = startIndex; k <= endIndex; k++)

takes too much time because it is executed up to \$ 10^7 \$ times, according
to the given limits.

The crucial idea is not to execute the operations “verbatim,” but to
store and update at each array index the “cumulative increment/decrement” with respect
to the preceding element after all operations encountered so far.
This requires only 2 updates for each operation, plus a final run over
all array elements to find the maximum value.

I don't want to deprive you from the joy to figure out the concrete code
yourself, but you'll find more information at Maximum value in an array after m range increment operations, if necessary.


I'd change two things.  I'd start by declaring your var's in one statement like so:

function test_submit(id){
    var q=[],
        p=$(id).getElementsByTagName('SELECT');

Second I'd use more descriptive variable names than i, p, r, n.  If you run this code through a minifier it'll do this for you.  When you come back to edit this code in a few months you'll want to know exactly what each variable is for, and using a descriptive name helps with that.

I'd also be leary of using $ in the global namespace as a variable name since a lot of the popular libraries use it and you don't want to have any collisions with those.


Configuring Constructor Parameters and Unit Testing

Go with #3, "Create a nice mock for mockOperationQueue." The only reason you're having to do that stubbing is that OCMock creates "strict" mocks by default. Strict mocks used to be the standard, but mock object frameworks have evolved. The problem with strict mocking is that they make tests more brittle.

For example, let's say you find the need to add another "this needs to happen when I'm setting up the operation queue" call. Suddenly, your tests will break, because the strict mock will complain, "I don't know what this new call is." You've coded things well by setting up the mock operation queue in one place, so fixing it wouldn't be hard; you'd just add another stub in your -setUp. But the test failure isn't a failure; it's noise.

OCMock was originally written when strict mocks were the norm. It was also the norm then to state expectations first, call the method of interest, then ask the mock to verify itself:

[mockView expect] addTweet:[OCMArg any];

[controller displayTweets];

[mockView verify];

But mock object frameworks have evolved since then. People figured out that having non-strict mocks was almost never a problem. And new frameworks came along that state the expectation after calling the method of interest. Using OCMockito, the example above changes to:

[controller displayTweets];

[verify(mockView) addTweet:anything()];

This restores the standard order of unit tests: "Arrange - Act - Assert" (or if you prefer, "Given - When - Then"). The verification of expectations now happens in the Assert phase, rather than sitting up in the Arrange phase. So now the test code reads more naturally, like a DSL.

The author of OCMock recognizes the importance of this evolution, and has stated:

  The next major version of OCMock is planned to support nice-by-default
  and verification of specific calls after the fact.


Binary search-like algorithm to find local peak

Why else?  The if() branch never continues.

// Why `else`
if (m==i || m==j) {
    return A[m];
}
else {
   ....

// Alternative
if (m==i || m==j) {
    return A[m];
}
... rest of code

Does the above make a difference? Easier to see code is invalid as it is missing return paths

if (A[m+1]>A[m])
{
    Peak1D(A,m+1,j);
    // what happens here??? Looks like return missing
    // was return Peak1D(A,m+1,j); intended?
}
// Now do not need `else`
// else if (A[m-1]>A[m])
if (A[m-1]>A[m])
{
    // Peak1D(A,i,m-1);
    return Peak1D(A,i,m-1);
}
// Now do not need `else`
// else   return A[m];
return A[m];

int i,int j --> Why type int here?  Why not char or long long?  The best is to use size_t.  That is an unsigned type that is neither too narrow nor too wide for array indexing and size calculation.

// int Peak1D(int A[],int i,int j)
int Peak1D(int A[],size_t i,size_t j)

Consider more descriptive names. @Ron Beyer  How about "left" and "right"? or "starting_point" "ending_point"?

int Peak1D(int A[],size_t left,size_t right)

Code defensively.  Users of your useful code will try things not intended.  What happens when i>j?  Likely bad things.  Suggest adding some tests as assert() or other error handling code.

#include <assert.h>

...
assert(i <= j); // If assertion fails, code in debug mode exits with an error message

Use const for referenced data that is not modified.  This allows additional optimizations and allows execution with constant data.

int Peak1D(const int A[],int i,int j)

// Sample usage
const int sample[] = { 1,2,3,4,5};
printf("%d\n",  Peak1D(sample, 0,4));

Good top of file documentation.  Suggest adding month/year or at least year.
Above all, watch functionality.  This code seems odd as I would expect (A == {6,8}, i==0, j==1) to return 8, not 6.  OTOH, comment did say local peak - Oh, well.

// correct?
if (m==i || m==j) {
   return A[m];
}

Architecture style.:  A loop could have replaced the recursive function calls.  See little value to recursion here.
Indentation style.  It is consistent, which is most important.  I find it a bit too loose, but identation is a holy war.  IMO, best to follow an automated group's coding standards.


A shim to make make Node GRPC bindings more JavaScript-y

Both the idea and implementation look sound to me. As a nitpick, you might consider using a reduce on the opts, giving you a one liner. Also, I believe the hasOwnProperty test is superfluous here

Untested reduce version

Note that, per Joseph's suggestion, which I agree with, this creates the AudioOutConfig object for you, rather than requiring it as a parameter:

function config(opts) {
  return Object.keys(opts).reduce((audio, opt) => {
    const methodName = `set${opt.charAt(0).toUpperCase() + opt.slice(1)}`
    return audio[methodName] ?  audio[methodName](opts[opt]) : audio
  }, new AudioOutConfig())
}


Learn to love rustfmt.

Spaces go around operators and after commas

-    let c = make_odd((s.0/2, s.1/2));
+    let c = make_odd((s.0 / 2, s.1 / 2));

-    for (x,y,px) in buf.enumerate_pixels_mut() {
+    for (x, y, px) in buf.enumerate_pixels_mut() {

Don't put multiple statements on one line

-    o(&mut t.0); o(&mut t.1); t
+    o(&mut t.0);
+    o(&mut t.1);
+    t

Make a type for whatever (usize, usize) is. At the very least, create a type alias.
Actually, there are three places that want to apply a change to both components of the tuple. Promote the tuple to a type and add a map method.
If you have to give your closure arguments types anyway, and there's nothing captured by the closure, just make an inline function.
There's no real reason to take mutable reference to increment an integral value.
You define stack then immediately push a value on. instead, just use the vec! macro to create it all at once..
There's no need to specify the type of dirs
Instead of re-coding the number of elements in dir and having to potentially do bounds-checking again, just iterate over dirs directly
Characters are free. Use some longer variable names.
If you don't need the program name, skip it to avoid remembering it's there and then adding numbers here and there to compensate.
There's no need for the turbofish when parsing the maze size.
Use unwrap_or_else to handle a failure to parse.
Use enumerate to avoid indexing the args slice again.
Use std::cmp::max to provide a lower value for the sizes.
Don't ignore errors. If writing to stderr is important, use expect.
Use Vec::get instead of checking the size and then using the index operator (which checks the size again)
You don't need to contruct a Path, just pass in the &str
Prefer expect to unwrap.
You can use ImageBuffer::from_fn. Note that this removes the need to make your variable mutable.
Dont' use ref in let bindings. Using & on the right hand side is more idiomatic. In this case, &mut at call is more idiomatic.
To deal with the unsigned / signed transformations, remember that a + (-2) is the same as a - (+2). Add an enum to define the directions, a method to apply those directions to a point, use checked_add / checked_sub in that method to deal with under/overflow, then add your own "overflow" check for the size of the maze.

extern crate rand;
extern crate image;

use rand::Rng;
use std::cmp::max;
use std::io::Write;

#[derive(Clone, PartialEq)]
enum Cell {
    Blocked,
    Free,
}

#[derive(Debug, Copy, Clone)]
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

#[derive(Debug, Copy, Clone, PartialEq)]
struct Point(usize, usize);

impl Point {
    fn map<F>(self, mut f: F) -> Self
        where F: FnMut(usize) -> usize
    {
        Point(f(self.0), f(self.1))
    }

    fn move_by(self, amount: usize, dir: Direction) -> Option<Self> {
        use Direction::*;
        match dir {
            Left  => self.0.checked_sub(amount).map(|x| Point(x, self.1)),
            Right => self.0.checked_add(amount).map(|x| Point(x, self.1)),
            Up    => self.1.checked_sub(amount).map(|y| Point(self.0, y)),
            Down  => self.1.checked_add(amount).map(|y| Point(self.0, y)),
        }
    }
}

fn next_odd_number(n: usize) -> usize {
    n + if n % 2 == 0 { 1 } else { 0 }
}

fn generate_maze(size: Point) -> Vec<Vec<Cell>> {
    use Direction::*;

    let center = size.map(|v| v / 2).map(next_odd_number);
    let mut stack = vec![Point(center.0, center.1)];

    let mut maze = vec![vec![Cell::Blocked; size.1]; size.0];
    maze[center.0][center.1] = Cell::Free;

    let mut dirs = [Left, Right, Up, Down];
    let mut rng = rand::thread_rng();

    let ensure_in_bounds = |z: Point| {
        if z.0 >= size.0 || z.1 >= size.1 {
            None
        } else {
            Some(z)
        }
    };

    'next_odd_number: while let Some(&point) = stack.last() {
        rng.shuffle(&mut dirs);

        for &dir in &dirs {
            let new_point = match point.move_by(2, dir).and_then(&ensure_in_bounds) {
                Some(new_point) => new_point,
                None => continue,
            };

            if maze[new_point.0][new_point.1] != Cell::Free {
                stack.push(new_point);
                maze[new_point.0][new_point.1] = Cell::Free;
                let middle_point = point.move_by(1, dir)
                    .expect("Middle point cannot be out-of-bounds");
                maze[middle_point.0][middle_point.1] = Cell::Free;
                continue 'next_odd_number;
            }
        }
        stack.pop();
    }

    maze[0][1] = Cell::Free;
    maze[size.0 - 1][size.1 - 2] = Cell::Free;
    maze
}

fn print_usage() -> ! {
    writeln!(std::io::stderr(), "Usage: maze-gen width height [output.png]")
        .expect("Unable to write to stderr");
    std::process::exit(1);
}

fn main() {
    let args: Vec<_> = std::env::args().skip(1).collect();
    if args.len() < 2 {
        print_usage();
    }

    let mut dimensions = [0; 2];
    for (i, arg) in args.iter().enumerate() {
        dimensions[i] = arg.parse().unwrap_or_else(|_| print_usage());
    }
    let requested_size = Point(dimensions[0], dimensions[1]);
    let valid_size = requested_size.map(next_odd_number).map(|v| max(v, 3));

    if valid_size != requested_size {
        writeln!(std::io::stderr(),
                 "Warning: Adjusting sizes to {} and {}!",
                 valid_size.0,
                 valid_size.1)
            .expect("Unable to write to stderr");
    }

    let maze = generate_maze(valid_size);

    let buf = image::ImageBuffer::from_fn(valid_size.0 as u32, valid_size.1 as u32, |x, y| {
        let luma = match maze[x as usize][y as usize] {
            Cell::Free => 255,
            Cell::Blocked => 0,
        };
        image::Luma([luma])
    });
    let filename = args.get(2).map(String::as_str).unwrap_or("out.png");

    let mut file = std::fs::File::create(filename).expect("Couldn't open the file");
    image::ImageLuma8(buf).save(&mut file, image::PNG).expect("Coulding write the file");
}

I might next look into implementing a flat storage for the maze, one that can be directly indexed by a Point. That would allow this change:

-maze[middle_point.0][middle_point.1] = Cell::Free;
+maze[middle_point] = Cell::Free;

I'll be honest and say that I strongly dislike the usage of the labelled loop. I don't think I've ever needed them, and they are one of the rarest constructs in Rust, based on my experience. I'd probably spend a lot of time (more than I already did...) trying to rewrite that in a different manner.


Handy tool that provides easy syntax for specifying multi-dimensional types in C++

There's so little code here (and none of it anything that actually executes, just typedefs) that it's difficult to review the code as a thing in itself.

That leaves only the question of whether the basic idea of the code is a good one. At least in my opinion, the answer to that is a (heavily qualified) "no", at least as a general rule.

If you really need the equivalent of a muti-dimensional array, nested containers are rarely the best way to achieve that. Instead, you're usually better off with a single container and multi-dimensional indexing into that single container.

There are a couple of different ways of providing that. One is to overload operator() for the correct number of parameters (and optionally provide overloads for fewer parameters, which return entire collections rather than a single element). Another is to use multiple overloads of operator[], so indexing looks like a multi-dimensional array in C (e.g., x[i][j][k]), but the higher-order operators return proxy objects, so [i][j][k] ends up doing the multiplication necessary to find the correct element in the collection.

Relatively straightforward code for that (supporting only 3 dimensions) could look something like this:

#include <vector>
#include <iostream>

template<class T>
class matrix3 {
    size_t a, b, c;
    std::vector<T> data;

    friend class proxy;
    friend class proxy2;

    class proxy {
        matrix3 &m_;
        int index1_, index2_;
    public:
        proxy(matrix3 &m, int i1, int i2)
            : m_(m), index1_(i1), index2_(i2) { }

        T &operator[](int index3) {
            return m_.data[index1_ * m_.b * m_.c + index2_ * m_.c + index3];
        }
    };

    class proxy2 {
        matrix3 &m_;
        int index_;
    public:
        proxy2(matrix3 &m, int d) : m_(m), index_(d) { }

        proxy operator[](int index2) {
            return proxy(m_, index_, index2);
        }
    };
public:
    matrix3(size_t a, size_t b, size_t c) : a(a), b(b), c(c), data(a * b * c) { }

    proxy2 operator[](int index) {
        return proxy2(*this, index);
    }
};

Simple demo code:

int main() {
    matrix3<double> m(3, 3, 2);

    for (int x = 0; x < 3; x++)
        for (int y = 0; y < 3; y++)
            for (int z = 0; z < 2; z++)
                m[x][y][z] = x * 100 + y * 10 + z;

    for (int x = 0; x < 3; x++) {
        for (int y = 0; y < 3; y++) {
            for (int z = 0; z < 2; z++)
                std::cout << m[x][y][z] << "\t";
            std::cout << "\n";
        }
        std::cout << "\n\n";
    }
}

I haven't tried to work through really doing it, but I believe you should be able to shorten (and possibly even simplify) that by defining the proxy classes using a non-type parameter for the stored index, and recursion to a proxy<n-1>, where n is the dimension. Likewise, you'd need to define the operator[] to multiply and accumulate across N dimensions instead of the fixed number employed here.

This gives a number of advantages. First, improved locality of reference--all the data is allocated and accessed as a single, contiguous block. Second, reduce memory access--instead of a pointer to a pointer to a pointer to a block of data, you have only a single level of pointer to access, regardless of the number of dimensions. You do have to use some multiplications to avoid those memory accesses, but on a modern CPU that's a really good trade off.

Hope I haven't gotten too far afield from the original topic--this is quite a bit different code (really code for the entirety of a multi-dimensional array, not just typedefs for declaring/defining one), but it seems pretty obvious that if you're doing to declare/define one, you also want to use it...


Exotic bitmap renderer for core drawing functions

If loop iterations are reduced

Loop iterations can be only lowered in occasions in which you use lineto or/and larger than 1 pixel pen size.

  If loop body computations are reduced

The padding computation can be omitted from each iteration. Videlicet the modulo % operator slows down tremendously. Nevertheless with your current approach of raster scan I believe you are combining minimum resources during the loop.

  If the function is smart enough to figure out where to use lineto or
  larger pen

Relates to the first idea for speculative optimization. Idea, that can be achieved along the second idea for optimization. And that is to give RLE-compressed (figuratively) image instead of raw image, which compression determines where to use line, where to use larger pen size or a combination of these two.

I've been through similar cases where optimizing is precious and with that consideration and in this particular circumstance I am only capable of confirming these "theories" as well as share your opinion about how useful that could be. Quite frequently people's first game projects are based on drawing from scratch.. and they have a hard time rendering images with the desired quality.


Display the last N lines of a text file with line numbers in reverse order

cat -n is kind of an anti pattern. The cat command is for displaying the content, adding line numbering is a violation of the single responsibility principle.

tac is not portable. Although it's quite common in Linux, not so much in UNIX and osx.

Instead of head --lines=3 it's more common to use the shorter form head -n 3.

I don't quite get why you would want to see the last n lines reversed. If reversing is not important, then a portable alternative to print the last n lines with line numbers could be using awk and tail:

awk '{ print NR ":" $0 }' file | tail -n 3

You could write the whole thing in Awk, and also reverse the lines. It will be longer to write, but portable, and solved in a single process rather than a pipeline of multiple commands.


Correct approach to wait for multiple async methods to complete

Your code is absolutely correct in case when you want to start workflows only when all of them are configured.

But if you want to start each workflow once it's configured (independently from other workflows) then it might be a good idea to use continuations... In .NET 4.5 it would look like this:

public sealed class Engine : IEngine
{
    private readonly List<IWorkflow> _workflows;

    public Engine(IEnumerable<IWorkflow> workflows)
    {
        _workflows = new List<IWorkflow>(workflows);
    }

    private async Task RunWorkflow(IWorkflow workflow)
    {
        await workflow.ConfigureAsync();
        await workflow.StartAsync();
    }

    public void Start()
    {
        var startTasks = this._workflows.Select(RunWorkflow).ToArray();
        Task.WaitAll(startTasks);
    }

    public void Stop()
    {
        var stopTasks = _workflows.Select(w => w.StopAsync()).ToArray();
        Task.WaitAll(stopTasks);
    }
}

Also I would suggest to use CancellationToken to stop asynchronous processing.

UPDATE Based on comments it is really needed to wait for all workflows to be configured before starting them. So cancellable implementation can look like this:

public interface IWorkflow
{
    Task ConfigureAsync(CancellationToken token);
    Task StartAsync(CancellationToken token);
}

public sealed class Engine : IEngine
{
    private readonly List<IWorkflow> _workflows;
    private readonly CancellationTokenSource _cancellationTokenSource;
    private Task _mainTask;

    public Engine(IEnumerable<IWorkflow> workflows)
    {
        _workflows = new List<IWorkflow>(workflows);
        _cancellationTokenSource = new CancellationTokenSource();
    }

    private async Task RunWorkflows()
    {
        await Task.WhenAll(_workflows.Select(w => w.ConfigureAsync(_cancellationTokenSource.Token)));
        if (_cancellationTokenSource.IsCancellationRequested)
            return;
        await Task.WhenAll(_workflows.Select(w => w.StartAsync(_cancellationTokenSource.Token)));
    }

    public void Start()
    {
        _mainTask = RunWorkflows();
        _mainTask.Wait();
    }

    public void Stop()
    {
        _cancellationTokenSource.Cancel();
        var mainTask = _mainTask;
        if (mainTask != null)
            mainTask.Wait();
    }
}


Use a do-while loop, so the loop body gets always executed at least once:

final_count = 0
page = 1
begin
  individual_count = get_item_count(config, page)
  final_count += individual_count
  page += 1
end while individual_count > 20


Some notes:

Your bracing does not follow standard Java conventions. This is more of a matter of preference, but this is how I would format your code:

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
int count = list.size();
int number = 3;

while (count != 100) {
    boolean isPrime = true;
    for (int i = 0; i < list.size(); i++) {
        if (number % list.get(i) == 0) {
            isPrime = false;
        }
    }
    if (isPrime) {
        list.add(number);
    }
    number++;
    count = list.size();
}
System.out.println(list);

Some other points about formatting:

I have removed some excess blank spaces and lines.
I put braces around all the statements inside the if statement without braces.

Now, to the loop:

while (count != 100) {
    boolean isPrime = true;
    for (int i = 0; i < list.size(); i++) {
        if (number % list.get(i) == 0) {
            isPrime = false;
        }
    }
    if (isPrime) {
        list.add(number);
    }
    number++;
    count = list.size();
}

This could easily be a for loop:

for (int count = 1, number = 3; count < 100; number++) {
    boolean isPrime = true;
    for (int i = 0; i < list.size(); i++) {
        if (number % list.get(i) == 0) {
            isPrime = false;
        }
    }
    if (isPrime) {
        list.add(number);
    }
    count = list.size();
}

Also, all your list.size(). You can remove many of the calls:

for (int count = 1, number = 3; count < 100; number++) {
    boolean isPrime = true;
    for (int i = 0; i < list.size(); i++) {
        if (number % list.get(i) == 0) {
            isPrime = false;
        }
    }
    if (isPrime) {
        list.add(number);
        count++;
    }
}

You can also remove much of the iterations of the inner loop by breaking when isPrime is true, or just:

for (int count = 1, number = 3; count < 100; number++) {
    for (int i = 0; i < list.size(); i++) {
        if (number % list.get(i) == 0) {
            list.add(number);
            count++;
            break;
        }
    }
}

But the main thing is, your code is not as efficient as it could be. Try a Sieve:

List<Integer> result = new LinkedList<Integer>();
int n = 1.4 * 100 * Math.log(100);
boolean[] isPrimeArray = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
    isPrimeArray[i] = true;
}
for (int i = 2, primesLeft = 100; i * i <= n && primesLeft > 0; i++) {
    if (isPrimeArray[i]) {
        result.add(i);
        primesLeft--;
        for (int j = i; i * j <= n; j++) {
            isPrimeArray[i * j] = false;
        }
    }
}
System.out.println(result);

The sieve does:

Sets all numbers to true (as in, is a prime).
Starts at 2, and works its way through the primes. While doing that, marks all the multiples of a prime to false.
If it has 100 primes, the loop will terminate.
Print the result.

Also you have 100 as a magic number. Set it as a field:

private static final int MAX = 100;

// Code here

Use:

List<Integer> result = new LinkedList<Integer>();
int n = 1.4 * MAX * Math.log(MAX); // Overestimate by 40%
boolean[] isPrimeArray = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
    isPrimeArray[i] = true;
}
for (int i = 2, primesLeft = MAX; i * i <= n && primesLeft > 0; i++) {
    if (isPrimeArray[i]) {
        result.add(i);
        primesLeft--;
        for (int j = i; i * j <= n; j++) {
            isPrimeArray[i * j] = false;
        }
    }
}
System.out.println(result);

This will result in a much faster result.


Calculating the squares dominated by a queen on a chessboard

I would probably break this up into a function setDominatedForLine that would work for each direction. Instead of a true/false remove parameter I used a dominatedIncrement parameter with a value of +1 or -1.

function setDominatedSquares(queenPosition, dominatedIncrement = +1) {

  function setDominatedForLine(rowInc, columnInc) {
    let row    = queenPosition.row;
    let column = queenPosition.column;
    while (row >= 0 && row < boardSizeY && column >= 0 && column < boardSizeX) {
      chessBoardSquares[row][column].dominatedBy += dominatedIncrement;
      row    += rowInc;
      column += columnInc;
    }
  }

  // Column
  setDominatedForLine( 0,  1);
  setDominatedForLine( 0, -1);
  // Row
  setDominatedForLine( 1,  0);
  setDominatedForLine(-1,  0);
  // Diagonals
  setDominatedForLine( 1,  1);
  setDominatedForLine( 1, -1);
  setDominatedForLine(-1,  1);
  setDominatedForLine(-1, -1);

  // update the UI
  updateDominatedSquares();
}

You could also modify it slightly with something like:

let directions = [ {r:-1, c:-1}, {r:-1, c: 0}, {r:-1, c: 1},
                   {r: 0, c:-1},               {r: 0, c: 1},
                   {r: 1, c:-1}, {r: 1, c: 0}, {r: 1, c: 1} ]
for (let dir of directions)
  setDominatedForLine( dir.r, dir.c );

But I'm not sure if that is an improvement.


Pascal Triangle calculation with BigIntegers

using System.Numerics;
public class EggChallenge
{
    private static BigInteger mo = new BigInteger(998244353);
    public static BigInteger Height(BigInteger n, BigInteger m)
    {
        return n == 0 || m == 0 ? 0 : BigInteger.Remainder(SumHeight(n+1, m), mo);
    }

    public static BigInteger SumHeight(BigInteger n, BigInteger m)
    {
        BigInteger BigInt = new BigInteger(1);
        BigInteger BigIntegerSum = new BigInteger(0);

        for(int i = 1; i < n; i++)
        {
            BigInt = BigInteger.Divide(BigInteger.Multiply(m + 1 - i, BigInt), (BigInteger)i);
            BigIntegerSum = BigInteger.Add(BigIntegerSum, BigInt);
        }

        return BigIntegerSum;
    }
}

C# supports operator overloading subject to some constraints, and BigInteger has all of the arithmetical operators implemented. So you can improve legibility a lot by using standard operators rather than BigInteger.OperatorName(foo, bar).

Local variables in C# normally begin with a lower case letter, so using upper case is not very helpful. In addition, BigInt doesn't tell me anything useful: I know that the type is BigInteger because I can see the declaration, but what does the variable mean?

Renaming and using overloaded operators I get rewritten code which IMO is easier to read:

    BigInteger Height(BigInteger n, BigInteger m)
    {
        return n == 0 || m == 0 ? 0 : SumHeight(n + 1, m) % mo;
    }

    BigInteger SumHeight(BigInteger n, BigInteger m)
    {
        BigInteger term = 1;
        BigInteger sum = 0;

        for (int i = 1; i < n; i++)
        {
            term = (m + 1 - i) * term / i;
            sum += term;
        }

        return sum;
    }

  I don't think the algorithm is what to improve has it seems to run at
  O(n), but I could be very wrong.

I'm afraid that you are very wrong. The code is performing \$O(n)\$ arithmetical operations on BigIntegers, but an arithmetical operation on a BigInteger is not \$O(1)\$. The fundamental problem is this:

        ... SumHeight(n + 1, m) % mo;

It should instead be

        ... SumHeight(n + 1, m, mo);

with the % being applied regularly inside the loop:

        for (int i = 1; i < n; i++)
        {
            term = (m + 1 - i) * term % mo;
            term = ModDiv(term, i, mo); // I'll come back to this
            sum += term;
        }

        return sum % mo;

The massive advantage is that you no longer need BigInteger: it suffices to use long (or maybe ulong: it's a matter of taste because 998244353 was chosen such that long would work in languages like Java which don't have ulong).

I infer from your comment on an earlier answer that you haven't studied modular arithmetic. This is quite understandable: I think it's safe to say that 99% of programmers will never use it in their careers. But although it is irrelevant for most line-of-business programming, it is quite important in code contests/challenges (interpreted broadly to include katas, Project Euler, etc.) because they frequently use modular arithmetic to make large test cases feasible. If you find katas either enjoyable or useful for your CV, it's probably worth your time to study.

The properties I'm relying on are (treating % as an operator on arbitrary-width integers and assuming that we're avoiding overflow, which is % Pow(2, IntegerTypeWidth)):

((a % m) + (b % m)) % m == (a + b) % m
((a % m) * (b % m)) % m == (a * b) % m

Now I can come back to modular division. Essentially ModDiv(term, i, mo) needs to calculate a modular reciprocal of i (i.e. j such that i * j % mo == 1) and then return term * j % mo. There is always such a j as long as it is coprime with mo, and 998244353 is deliberately chosen to be a prime number, deliberately chosen so that you can divide by any number which isn't a multiple of it. The standard approach to calculate a modular reciprocal is the extended Euclidean algorithm, and is described in so many millions of web pages that I won't try to give my own explanation here.

To wrap up the explanation, I must address a point raised by Rick Davin. If you rewrite SumHeight so that n and m are both long, how to handle the test case m = BigInteger.Pow(2, 200)? If we look at how m is used, it takes part in addition and multiplication. So the way to do this is to do the modulo in BigInteger and then cast to long:

    long Height(BigInteger n, BigInteger m)
    {
        return n == 0 || m == 0 ? 0 : SumHeight((long)n + 1, (long)(m % mo), mo);
    }


Sum of left and right nodes (individually) in a Binary Search Tree

This code works and it seems quite fine.

  If there is an easier method to this problem then I would like to know.

You could do it without a Queue,
using a recursive solution,
if your tree is not too deep to lead to a stack overflow.
But since you need to track two kinds of values,
you would need to accumulate them in a helper object,
for example:

private static class Result {
    private long leftSum;
    private long rightSum;
}

public static void sumOfLeftandRightNodes(Node node, Result result) {
    if (node.left != null) {
        result.leftSum += node.left.value;
        sumOfLeftandRightNodes(node.left, result);
    }
    if (node.right != null) {
        result.rightSum += node.right.value;
        sumOfLeftandRightNodes(node.right, result);
    }
}

You could call this method with:

Result result = new Result();
sumOfLeftandRightNodes(root, result);

One advantage of this method is that the solution will become unit-testable,
thanks to this helper class.
When the above call returns, you could add test cases to validate your solution,
for example:

assertEquals(2, result.leftSum);
assertEquals(19, result.rightSum);

Coding style

I would recommend to make everything private when you can,
and final when you can.
The Node class also has a bit too much vertical spacing:

static class Node {
    Node left;

    Node right;

    int value;

I suggest to write this way:

private static class Node {
    private Node left;
    private Node right;
    private final int value;

In the breadth-first search implementation,
temp for the loop variable is not a great name.
I recommend to rename it to node.


I'd like to think security as a thing that at first refuses everything, and after that permits something specific. Your code does the opposite at the moment. It checks that if the user is NOT logged in, and if the condition does not pass, the user is permitted to view the page.

I'd do the opposite. I would first check that if the user IS logged in, and only after that permit the user to view the page if the condition pass. It is more strict when it comes to potential bugs, which means that if something goes wrong, the user will not be permitted anyhow.

Second thing, you really do not want to tell the browser the user name in the cookie you set. Instead you should hash it with some secret salt if it really is necessary to send it to the browser. Remember, every detail you send to the browser is a potential security risk that someone (man-in-the-middle attack, viruses, other malware) might abuse.

And then, if that is a php script you include at the top of every page, why do you include the login form there? It seems to me that you only display it when you are on index.php. It is not needed elsewhere. Of course this is not a big issue, but it's the tiny little seed of bloated software that will grow in time if not treated carefully. And by this I mean that if you begin to add lots and lots of thing that is being used in only one place, it will make the script run so much slower.

Also, I see a potential bug there. If you ever wanted to add a POST form (say, a guestbook or chat or shoutbox or your own forum) on your website, you will trigger the login() function every time when ANY of those POST forms get submitted. The login() function will not then find the correct data in the POST variable, and will refuse to display the page.


Script that fixes YML SIDs to be simplified for production

You could use rumael.yaml, it can preserve comments. https://stackoverflow.com/questions/7255885/save-dump-a-yaml-file-with-comments-in-pyyaml#27103244

Moreover, you want to be a better python developer (or maybe pythonist?) I can give you some tips:

Content duplication
You are storing the file content inside cont and after closing the file you are duplicating that info in a new variable newfile I think that is an unnecessary process in this situation. You could store all the data in cont and just modify the lines needed. You can replace the entire if-else by:

    if temp != (refnum+1):
        temp= (refnum+1)
        change=numRegex.sub(str(temp), cont[i])
        cont[i] = change

For loop's range
Change your range call in the for loop to range(2, len(cont)):
Now inside the loop you can access the current line with simply cont[i] it's more readable and efficient.

As with i's range you are accessing refnum always with a +1. By initializing it as refnum=int(act.group()) +1 your code saves that operations inside the loop. Another thing that you can do is do the +=1 increment at the beginning of the loop.

File management
You don't need to manually close files when using with statement you can remove finalfile.close(). Another thing, you are using with in the when writing but not when reading, think about always use the same method.

More things can be changed but I think that's enough for now.


from twitter import *

Importing * is generally considered bad practice, because you don't know what's being imported into your local namespace. For you case, I believe you can get away with just doing import twitter. In the general case, if you only need a few things from a module, you can do:

from foo import bar, baz, quux

Alternatively if you need everything from foo just do import foo and then call foo.bar(), foo.baz(), etc. If you get tired of typing long names, you can do something like import jabberwocky as foo.

def init(timestamp = datetime.now(pytz.timezone('Europe/Stockholm')).time()):

I think there's serious readability issues with this, and I also can't think of any time I've ever seen a function/method being called inside another function's signature. I'm going to go out on a limb and say this is a Bad Idea -- for one thing, I suspect that automated code documentation tools might have trouble parsing this. More fundamentally, a function/method's signature is its interface with the rest of the world. It just seems like a very bad trade off to muddy the readability of a signature in exchange for saving a couple of times of code. I would refactor to something like:

MY_TZ = pytz.timezone('Europe/Stockholm')
now = datetime.now(MY_TZ).time()
def init(timestamp = now):

You could also think about how you actually initialize this script. You mentioned you're running it as a cron job, so I think this layout makes sense, but you could also rewrite this as a class and place the init logic into the __init__ method of the class.

def get_number_of_times_to_display_alarm(timestamp):
    # Convert our timestamp to 12h format, split it, select first element(hours)
    # and cast to int to remove leading 0 (e.g. 09.00 will give us 9)
    return int(timestamp.strftime("%I:%M %p").split(':')[0])

This is not bad at all, but here are a couple of alternatives:

now = datetime.now(MY_TZ).hours
if now > 12:
    now -= 12
return now

We've already used datetime.now(), it's both simpler than timestamp.strftime and it's nice to not have to introduce new functions unless necessary. There's an even shorter alternative you could use, which trades off a little readability for space:

now = datetime.now(MY_TZ).hours % 12

This uses the modulo function to convert 24h to 12 h clock.

Also, it's better to use docstring in for your code documentation. Something like "Convert our timestamp to 12h format, split it, select first element(hours)
and cast to int to remove leading 0 (e.g. 09.00 will give us 9)" is closer to being documentation for yourself/others. It should be a docstring. You should also think about removing the implementation specific elements -- those are more appropriate to use a # comment. I would rewrite the comment as:

"""Convert our timestamp to 12h format and remove leading zeros. Returns an Int."""

That decouples the interface of the function from its implementation.

One nitpick about your above code, which I only noticed noodling around with it now in a shell session: get_number_of_times_to_display_alarm. That's a very long function name. It's generally good to be longer than shorter and more explicit than less, but also consider it can be tiring and people have to remember the names of your functions. Try to find the shortest name that accurately and specifically describes what the logic does. I would probably name that logic something like get_current_hour.

def compose_tweet(number_of_rings, timestamp):
    # Creates a tweet, e.g. "BONG...BONG...BONG #03:00
    ALERT_SOUND = "BONG"
    tweet = ""
    for i in range(number_of_rings):
        tweet += "%s%s" %(ALERT_SOUND, "..." if i < (number_of_rings - 1) else "")

This could be sweated down a bit. For example:

for i in range(hour):
    tweet += "%s%s" % (ALERT_SOUND, "..." if i < (hour - 1) else "")

I don't think you need the else clause in that. You could refactor it to something like:

def compose_tweet(hour, timestamp):
    """ Creates a tweet, e.g. "BONG...BONG...BONG #03:00. """
    ALERT_SOUND = "BONG..."
    tweet = ""
    for i in range(hour):
        tweet += ALERT_SOUND
    tweet += " #%s:%s" % (str(timestamp.hour).zfill(2), str(timestamp.minute).zfill(2))
    return tweet

An even shorter version could be built around tweet = ALERT_SOUND * hour.

init()

A common pattern for python modules is to place:

if __name__ == "__main__":
    init()

At the end of the file. This allows the file to either run as a script or to be imported into other modules. For example, if you wanted to reuse your get_current_hour function in a different project, you could then do from twitClock import get_current_hour.


Is it ok to use HttpContext inside View?

You should try creating ViewModel classes - they're simple classes which just have a bunch of properties, and you pass them to the view instead of using ViewData or ViewBag.  You can make them all inherit off of a base model which has a bunch of show/hide flags (like user1614543 suggested) or put the flags on individual models (the better choice) which get returned to the views that use those flags.  Either way, you can put in sane default values so you only need to set them when you're displaying different data.  You can even pass the name of the controller as a string, or use an enum to categorize them.

This will make your markup more readable, and ensure type-safety of your data, which will make working with it easier.

Here's an example, although you'll have to convert it from ASPX to Razor.


Use a multiplication to perform several shifts in a single instruction.

Trim the input to seven bits to avoid overlap in the second step.
Shift by 0, 7, 14, 21, 28, 35, 42 bits and aggregate the results in a 64-bit integer.
Keep only bits 0, 8, 16, 24, 32, 40, 48.
Handle the 8th bit of the input separately. Shift by 49, then add it to the others.

Example code in C#

ulong Expand(byte b)
{
    ulong shift = 0x0000040810204081ul; // bits set: 0, 7, 14, 21, 28, 35, 42
    ulong mask = 0x0001010101010101ul; // bits set: 0, 8, 16, 24, 32, 40, 48
    return (ulong)(b & 127) * shift & mask | (ulong)(b & 128) << 49;
}


Adding a list of brokers to a local SQLite database

A classicel one. String concatenation with the + operator is very inefficient, because it creates a new copy of the string every time.
See for example item 51 in Effective Java from Joshua Bloch or here: http://www.javapractices.com/topic/TopicAction.do?Id=4

Try to change it to StringBuilder:

public void Add(List<Broker> brokers)
{
    if(brokers == null || brokers.size() == 0)
      return;

    StringBuilder query = new StringBuilder(brokers.size() * 50); // size is a guess, could be furhter investigated
    query.append("INSERT INTO ").append(TABLE_NAME).append(" SELECT ").append(brokers.get(0).getId()).append(" AS '").append(COLUMN_BROKERID).append("', ").append(brokers.get(0).getOfficeId()).append(" AS '").append(COLUMN_OFFICEID).append("', '").append(brokers.get(0).getName()).append("' AS '").append(COLUMN_NAME).append("', ").append(brokers.get(0).getSuccessRate()).append(" AS '").append(COLUMN_SUCCESSRATE).append("'"); // it is not that important to change this line. this will probably be done by the java compiler anyway

    for(int i=1; i<brokers.size(); i++)
        query.append(" UNION SELECT ").append(brokers.get(i).getId()).append(", ").append(brokers.get(i).getOfficeId()).append(", '").append(brokers.get(i).getName()).append("', ").append(brokers.get(i).getSuccessRate());

    databaseManager.ExecuteNonQuery(query.toString(););
 }


Project Euler Smallest Multiple w/ JavaScript

Since the problem calls for a positive number evenly divisible by numbers from 1 to 20, I would overlook the fact that the function isn't reusable and it's strictly for this use case. But in real world programming, you will want to strive for reuse. Expanding the algorithm to do more than just 1-20 would be a good exercise.

The function name is misleading. The function is single-purpose but the name... is not. smallestMultiple doesn't even inform readers that it's simply just for the numbers 1-20. A name change will do.

I see you're putting opening braces in a new line and independently. I'm not really a fan of this formatting since it takes up too much space. I would suggest the collapsed "egyptian" brackets and 2-space indent because in JS, you easily run off to the right. You will realize this when you work with callbacks and nested functions.

while(...)
  {
    // stuff
  }

while(...){
  // stuff
}

Instead of a very long list of hard-coded conditions, consider using an array of factors and array.every. array.every executes a callback for each item in the array. If all items cause the callback to return true, array.every returns true and false if otherwise. This allows you to have a dynamic number of values to check against.

function smallestMultiple(){
  var factors = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
  var found = false;

  for(var number = 1; !found; number++)
    found = factors.every(factor => number % factor === 0);

  return number;
}

Now with the code a bit cleaner and the factors are not anymore hardcoded, you can now move factors as an argument to the function. This makes it accept any number of values. This solves the very first concern mentioned.

function smallestMultiple(factors){
  var found = false;

  for(var number = 1; !found; number++)
    found = factors.every(factor => number % factor === 0);

  return number;
}

smallestMultiple([11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);

Taking it a bit further, instead of a loop, we can use recursion. Much shorter but blows away the stack when the numbers become huge.

function smallestMultiple(factors, number = 1){
  return factors.every(factor => number % factor === 0) ? number : smallestMultiple(factors, number + 1);
}

smallestMultiple([11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);

Note that I am using ES6 syntax for the most part because it's convenient to write. However, browsers don't support all of the syntax yet. You can convert it to ES5 using transpilers like Buble or Babel.


Managing JS objects while preserving references

Instead of checking each property in the result to see whether it was in the source object, simply delete all of the properties in the destination object and then use angular.extend or Object.assign to copy from the source.

function replaceObj(target, source) {
    Object.keys(target).forEach(function(key) {
        delete target[key];
    });
    Object.assign(target, source);
}

Also, if you do want to check whether a property is in an object, using updates.kasOwnProperty(objKey) is more straightforward than making a separate array of keys and using indexOf.


How to hide implementation of JDBC while processing large query in client's code?

Your assumption that the entire dataset is read in to memory is not necessarily accurate. The JDBC clients I have worked with (DB2, MS-SQLServer, Sybase, Oracle, etc.) each default to, or have an option to limit the size of the client-side buffer. You only have a small amount of data on the actual client, and the ResultSet process fetches more data when you iterate through it.

There is no need to add another level of buffering. Are you sure the data is all being returned? Have you inspected the configuration options for your JDBC Client?


A couple of things that could help.

A menu and a switch block will simplify the main function.

A class to represent a vessel with quantity and a state that would be empty, full or partially full, would help clean up the rest of the code.

Make the menu options a '1' or a '2'.  This way you don't have to rely on the case.

And instead of explaining to the user how to enter the parameters, simply ask them which vessel to pour from and which vessel to pour to, and validate and correct, their answers before calling the functions.

Here's an example of using a class a menu and a switch block.  Some of the functions will need to be fleshed out, but you can easily see how mush easier it is to follow the flow of the program this way:

class Vessel
{
    map<char , string> states =
    { {
        {{'E',"Empty"}},
        {{'P',"Partial"}},
        {{'F',"Full"}}
    } };
    int _quantity = 0;
    int _capacity = 0;
public:
    Vessel( int capacity );
    string GetState();
    int GetCapacity();
    int GetQuantity();
    void SetQuantity( int volume );
    void Pour( Vessel other );
};
void DisplayVessels( map<int , Vessel> vessels )
{
    cout << "The state of the vessels:\n";
    cout << setw( 4 ) << "Size\t" << setw( 5 ) << "State\t" << setw( 4 ) << "Used\n";
    int counter = 1;
    for ( auto v : vessels )
    {
        cout << counter++ << setw( 4 ) << v.second.GetCapacity() << '\t' << setw( 5 ) << v.second.GetState() << '\t' << setw( 4 ) << v.second.GetQuantity() << '\n';
    }
}
void Pour( map<int , Vessel>& vessels )
{

}
int main()
{
    map<int , Vessel> vessels =
    { {
        {{24,Vessel( 24 )}},
        {{5,Vessel( 5 )}},
        {{11,Vessel( 11 )}},
        {{13,Vessel( 13 )}}
    } };
    cout << "Welcome to the Vessel Game\n"
        << "Three women stole a vase full of balsam(24 oz.)\n"
        << "During their get away they meet a glass merchant and buy 3 vessels from him.\n"
        << "Upon reaching a safe place to divvy up their spoils, they discover that the vessels are of odd sizes(5,11, and 13 oz.)\n"
        << "Your job is to figure out how to divide the balsam into 3 vessels each containing 8 oz.\n\n";
    vessels[24].SetQuantity( 24 );
    char choice;
    bool done = false;
    while ( !done )
    {
        cout << "1. Pour\n"
            << "2. Display\n"
            << "0. Quit\n";
        cin >> choice;
        switch ( choice )
        {
            case '1':
                Pour( vessels );
                break;
            case '2':
                DisplayVessels( vessels );
                break;
            case '0':
                done = true;
                break;
            default:
                cout << "Wrong choice.\n";
                break;
        }
    }

}


Convert a binary string, with each char separated by spaces, into a normal C string and print

OP: Please leave any feedback you see fit, with special attention to the loops and data types.

char type

Although char is signed or unsigned, string functions of the standard library work with the data as if it is was unsigned char.

  ... each character shall be interpreted as if it had the type unsigned char ... C17dr §7.24.1 3

Also: char output = 0; ... output |= 1 << 7-i; is or-ing bits potentially into the sign place.  This really is not a concern, but in general, logical bit manipulation is best done with unsigned types.

int/unsigned, in general, is the preferred type to use for efficient/clean code.  Thus using unsigned/int rather than char output can make for better code.

Putting these ideas together: recommend something more like

char bit_string_decode(char *const str) {
    unsigned output = 0;
    size_t i;
    for(i = 0; i < 8; ++i) {
        switch(str[i]) {
            case '1':
                output |= 1u << 7-i;  // I prefer unsigned types for bit manipulations
                break;
            case '0':
                break;
        }
    }
    return (char) output;
}

const

bit_string_decode(char *const str) does not modify the reference data. Use const for greater functional usage, more function clarity and help weak compilers optimize.

// bit_string_decode(char *const str)
bit_string_decode(const char *const str)
//                ^---^

// bool bit_string_is_valid(char *bit_string)
bool bit_string_is_valid(const char *bit_string)

Simplifications

Some alternative ideas to simplify the loop:

char bit_string_decode(const char *str) {
    const unsigned char *ustr = (const unsigned char *) str;
    unsigned output = 0;
    while (*(const unsigned char*)ustr) { // cast: see note below
        output <<= 1;
        // Given *str is '0' or '1'
        output |= *ustr++ - '0';
    }
    return (char) output;
}

Allocate to the size of the referenced data, not type

Code is easier to code right, review and maintain.

// char *output_buffer = malloc(sizeof(char)*(count+1));
char *output_buffer = malloc(sizeof *output_buffer *(count+1));
//                                  ^------------^  Referenced data

Consider decoding without destruction

binary_agent(char *bin_str) messes up bin_str due to strtok(bin_str,delim).  Use of strspn(), strcspn(), strchr() could be used to find the delimiter without changing bin_str.  This functional change I find would make for more useful code and greater applicability.

Missing validation in production

I would say strlen(bit_string) == 8 (or equivalent) should always test, not in only in assert.  Perhaps as

bool bit_string_is_valid(const char *bit_string) {
  if (bit_string == NULL) {
    return false;
  }
  const char *s = bit_string;
  while(* (const unsigned char*)s) {  // cast: see note below
    if((*s != '0') && (*s != '1')) {
      return false;
    }
    s++;
  }
  return (s - bit_string) == 8;
}

The cast (const unsigned char*) is only useful here for the all but extinct non-2's complement platforms to properly ID the null character.  Drop it, unless code needs that level of portability.

Minor

Spacing

Separate function declarations from functions a bit.

bool bit_string_is_valid(char *bit_string);
// add space here
int main(void)


evaluate_expr_pair

Your calculator performs integer division, which is a bit surprising.  To fix it to do floating-point or decimal arithmetic, though, you would have to do a search-and-replace of Int64.Parse, which has been written an unreasonable number of times in evaluate_expr_pair.

evaluate_expr_pair also does a lot of Parse and ToString round trips.  Not only is that inefficient, it could also cost you some loss of precision if you were doing floating-point arithmetic.

operand should really be called operator.  (The operands are a and b.)  Ignoring unrecognized operators is a bad idea, even if you have validated the input in check_expr.  If not doing exception handling, I'd rather leave out the default case and let it crash.  I'd also prefer to detect errors while attempting to evaluate the expression than pre-validate, because there are some errors that you can't reasonably detect without evaluating the expression (such as stack underflow).

evaluate_expr

Here, with your use of the program_stack, you are venturing outside the realm of functional programming, because the .Push() and .Pop() operations cause mutation.  A more FP approach would be to use a List as an immutable stack.

Instead of blindly pushing tokens, some of which are operators, onto a stack of strings, you should only put numeric data in the stack.

You would be better off treating the operators as functions that manipulate the entire stack directly, instead of as functions that take two operands and return one result.  Otherwise, you would have to implement an operation like swap as a special case, and distinguish between binary operations and unary operations such as negate and ex.

tokenize_expr

The simple strategy would be to use new Regex("\s+") as the delimiter pattern.  You're treating the operators as captured delimiters — presumably to make spaces optional in an expression like 1 2+ — and discarding the last element of the resulting array.  That works, as long as the expression ends with an operator.  If the expression is just 5, for example, you'll discard a number.

The regex could be written more succinctly using a [-+*/] character class.  I wouldn't bother naming split_pattern and split_regex as variables.

main

printf is preferred over System.Console.Write.

If you going to set up a |> pipeline, don't interrupt it by defining let tokenized_expr — that just gets in the way.

Summary

RPN calculators are much simpler when the operators work directly on the stack, rather than having a controller feed the operands to them.  In fact, every function except main has traces of the operator definitions.

Here's an implementation that I came up with:

open System
open System.Text.RegularExpressions

exception InputError of string

let tokenize (expr: string) =
    expr |> (new Regex("\s+|\s*([-+*/])\s*")).Split
         |> Array.toList
         |> List.filter(fun s -> s.Length > 0)

let perform (op: string) (stack: decimal list) =
    match (op, stack) with
    | ("+",     a :: b :: cs) -> (b + a) :: cs
    | ("-",     a :: b :: cs) -> (b - a) :: cs
    | ("*",     a :: b :: cs) -> (b * a) :: cs
    | ("/",     a :: b :: cs) -> (b / a) :: cs
    | ("swap",  a :: b :: cs) -> b :: a  :: cs
    | ("drop",  a :: cs)      -> cs
    | ("roll",  a :: cs)      -> cs @ [a]
    | (n,       cs)           ->
        try
            decimal n :: cs
        with
            | :? System.FormatException -> raise (InputError(n))

let evaluate (expr: string list) =
    let rec evaluate' (expr: string list) (stack: decimal list) =
        match expr with
        | []        -> stack
        | op :: exp -> evaluate' exp (perform op stack)
    evaluate' expr []

[<EntryPoint>]
let main argv =
    while true do
        printf ": "
        try
            match Console.ReadLine() |> tokenize |> evaluate with
            | num :: []  -> num   |> printfn "%g"       // Single answer
            | stack      -> stack |> printfn "%O"       // Junk left on stack
        with
        | InputError(str) -> printfn "Bad input: %s" str
    0


Filter out duplicates from an array and return only unique value

If is possible to improve or write in alternative way logic for
  createArray, maybe a better way in term of code repetition.

Why give the option to mutate the array? Most array methods return a new array, including filter, so it seems redundant in your code, since you get a new array anyway. Not mutating the array is usually the right thing to do. In any case, using JSON to clone an array is very inefficient, when all you need is var copy = array.slice(); and a recursive solution for nested arrays. If you get rid of this unusual requirement, and create your own function instead of extending the prototype, then you are left with what unique really is:

var unique = function(xs) {
  return xs.filter(function(x, i) {
    return xs.indexOf(x) === i
  })
}

  If it is possible to optimize the code for maximum performance and how

If you only deal with things that can be stringified properly, like numbers, and obviously strings, then you can improve performance by using a simple object to keep track of items that have been seen already:

var unique = function(xs) {
  var seen = {}
  return xs.filter(function(x) {
    if (seen[x])
      return
    seen[x] = true
    return x
  })
}

Although this would consider 1 and '1' to be a duplicate.


From what I understand, your code only keeps at most 1000 messages. First, you need to move out 1000 to a variable and away from your logic. That way, it's visible and easily configured.

Next, there is a possibility that your list of messages will grow greater than a thousand because you only slice it off when a connection is made. What if people kept chatting, but nobody new connected? Your array will continually grow. I suggest you move that check to the "chat message" event.

Another way to do it is to just separate this slicing logic into something periodic, like run on intervals. That way, you don't have to slice every time. The drawback to this, though, is when people chat faster than you can slice off.

Now for the logic that keeps your history in check. slice is expensive because it does a shallow copy of your array. Having a full 1000 messages in the list, if a person connects, you'd have 2 arrays of length 1000 at one moment. I suggest you use shift when the count runs over 1000. Assuming this system is only a single process, pushing in the 1001th message should immediately shift off the oldest one. Still an expensive process, but it's a lesser evil.

Lastly, to get the latest 1000 messages, it's an overhead to send 1000 events down the line to the new user individually. I suggest you create a new event that sends all 1000 at once instead of individually.

Let's try optimizing your logic:

var listOfMessages = [];
var MAX_HISTORY_LENGTH = 1000;

io.on('connection', function(socket){

  // Send down all old messages at once to this connection.
  socket.emit('new messages', listOfMessages);

  // When we recieve a message
  socket.on('chat message', function(msg){

    socket.broadcast.emit('chat message', msg);
    listOfMessages.push(msg);

    // Only splice when we need to
    if(listOfMessages.length > MAX_HISTORY_LENGTH) listOfMessages.shift();

  });
});


Printing letters in order like a pyramid

I propose a different method!
If you generate the center, and the size of the shape you can do the entire thing easily with str.format.

>>> '{0:-^16}'.format('yo')
'-------yo-------'

Simple.

The biggest problem is getting the diamond shape.
But this can be done with ease.
For the amount of different letters you want per line it goes:

1, 2, 3, 4, 3, 2, 1

Where the character you want goes:

3, 2, 1, 0, 1, 2, 3

If you make a range that goes like the first, you can change it to the second by subtracting from 4 each time.

I'll define this range as:

def piramid_range(size):
    return range(1, size) + range(size, 0, -1)

A quick run of size 4 gives us the correct output.
And subtracting from 4 each time gives us the correct output too.

>>> piramid_range(4)
[1, 2, 3, 4, 3, 2, 1]
>>> [4 - i for i in piramid_range(4)]
[3, 2, 1, 0, 1, 2, 3]

and so adding this all together, with two comprehensions makes for a nice small function:

def draw(size):
    fmt = '{{0:-^{size}}}'.format(size=4 * size - 3)
    return '\n'.join(
        fmt.format('-'.join([alphabet[size - s] for s in piramid_range(inner_size)]))
        for inner_size in piramid_range(size)
    )

And finally, as I think your separator character is quite ugly, I think adding the ability to change it would be nice. This is just replacing its two occurrences.

def draw(size, char='-'):
    fmt = '{{0:{char}^{size}}}'.format(char=char, size=4 * size - 3)
    return '\n'.join(
        fmt.format(char.join([alphabet[size - s] for s in piramid_range(inner_size)]))
        for inner_size in piramid_range(size)
    )

print draw(4)
print
print draw(4, char=' ')

Which would have the following output:

------d------
----d-c-d----
--d-c-b-c-d--
d-c-b-a-b-c-d
--d-c-b-c-d--
----d-c-d----
------d------

      d
    d c d
  d c b c d
d c b a b c d
  d c b c d
    d c d
      d


Find all files in directory and subdirectories while ignoring noncritical exceptions

You have multiple problems here:

For the case that an exception is thrown and swallowed you get a NullReferenceException at iterating over the filesInCurrent.
If the method would be called using C:/Windows/ (which is a valid path although it uses a slash instead of a backslash) the if condition would never result in true.
The if (folders.Count != 0) currentFolder = folders.Dequeue(); in addition with the continue can lead to problems. Assume the next folder in the queue would be a valid folder like C:\XFiles by calling Dequeue() and continue the folder would silently be swallowed.

Fixing the NullReferenceException is the easiest task. Just put the iterating over the filesInCurrent and foldersInCurrent inside the try block. By doing this you could place the declaration into the try as well.
Instead of checking if the currentFolder.Contains() a not wanted path, you should just refuse to add the paths while iterating over foldersInCurrent.
Instead of having the optimizer.IsSupported(f) which had former been a SomeLib.IsSupported() you should pass a Action<string, bool> which will just handle this. This will make your method future proof if e.g. the decision will be made to use a different lib.
To overcome the / vs \ problem you should create a DirectoryInfo() object using the root as parameter. By enqueueing the FullName property of the DirectoryInfo object any found subdirectory will have the \ as path separator.
The code should take advantage of the List<T>.AddRange() method instead of iterating over the files and adding them one by one.
If you later decide to exclude different paths it would be good to extract checking of the validness of the folders to a separate method which could be passed as Action<string, bool> parameter as well.
Parameters of public methods should always be ckecked for validness, hence a check for null and for emptiness of the root should be implemented.
One could use the var type if the right hand side of the assignment makes the type obvious.
Ommiting braces {} although tehy might be optional can lead to hidden and therfor hard to find bugs. I would like to encourage you to always use them.
Underscore prefixed variablenames are usually only for class-level variables.
Passing a root which doesn't exists should be checked at the beginning of the method as well. By returning early you won't need to catch a DirectoryNotFoundException.

Implementing the mentioned points will lead to

public static List<string> FindSupportedFiles(string root, Func<string, bool> isFileValid,Func<string,bool> isFolderValid)
{
    if (root == null) { throw new ArgumentNullException("root"); }
    if (string.IsNullOrWhiteSpace(root)) { throw new ArgumentException("The passed value may not be empty or whithespace", "root"); }

    var files = new List<string>();

    var rootDirectory = new DirectoryInfo(root);
    if (rootDirectory.Exists() == false) { return files; }

    //overcome problem about slash and backslash with using Contains()
    root = rootDirectory.FullName;
    if (isFolderValid(root) == false) { return files; }

    var folders = new Queue<string>();
    folders.Enqueue(root);
    while (folders.Count != 0)
    {
        string currentFolder = folders.Dequeue();

        try
        {
            var currentFiles = Directory.EnumerateFiles(currentFolder, "*.*").Where(f => isFileValid(f));
            files.AddRange(currentFiles);
        }
        // Ignore this exceptions
        catch (UnauthorizedAccessException) { }
        catch (PathTooLongException) { }

        try
        {
            var currentSubFolders = Directory.GetDirectories(currentFolder).Where(f => isFolderValid(f));
            foreach (string current in currentSubFolders)
            {
                folders.Enqueue(current);
            }
        }
        // Ignore this exceptions
        catch (UnauthorizedAccessException) { }
        catch (PathTooLongException) { }

    }
    return files;
}

private static bool IsFolderValid(string path)
{

    return (path.Contains(":\\Windows") ||
             (path.Contains(":\\Users") &&
              path.Contains("\\AppData"))) == false;
}

and could be called like so

var optimizer = new ImageOptimizer();
var supportedFiles = FindSupportedFiles(path, optimizer.IsSupported, IsFolderValid);


Some thoughts about your Tic-Tac-Toe version.

You made a confusion between Tile and Player. You assume a Player is the same as a Tile but it is not. A Tile can be Empty but a Player cannot be empty. You should separate these two notions. It will make your declarations clearer on what you expect. What if I call "gameLoop Empty startBoard" ?

The putStr function does not flush immediately its output in a compiled program. Your program asks the user for a row and a column and displays these labels after the user inputs.

Is it natural to ask for the row before the column ?

You have intertwined the game logic with the user interface in the gameLoop function. What will you do if you want to implement a computer player ? Or have a GUI to play the game ? You will have to patch your gameLoop function though the game logic has not changed.

Your solution is locked to the fact that your board is a 3×3 grid with a 3 tiles win. For example, your inRange functions works for row indices AND column indices, which are not the same. You use the constants 2 and 3 in your code (inRange, startBoard and whoWon), but nothing implies a relation between them. The 3 rows and 3 columns are characteristics of the Board, not of your functions.

Messages could be more specific. When you tell the user "Invalid position", there’s no way to know if it’s because the coordinates are out of bounds or because the tile has already been played.

Note: there are many Tic-Tac-Toe game related questions on CodeReview, you should take a look at:

Tic Tac Toe game in Haskell (a brute first attempt)
Tic Tac Toe game in haskell follow up (its follow up)
TicTacToe in Haskell (a version using Lens)
m,n,k-game (i.e. generalized tic-tac-toe) (its generalization)


Re version, since it was amusing to do. My version uses a slightly different technique: I build one big regexp, with two groups and replace everything in one go without any additional checking. If Re.replace provided slightly more control (per-group substitution) it would avoid the concatenation.

I used the combinators for building the regexp, instead of the symbolic version, because that's much more readable, really.

let map_to_umlauts =
  [ "ue","ü" ; "oe","ö" ; "ae","ä" ; "Ue","Ü" ; "Oe","Ö" ; "Ae","Ä" ]

let regexp =
  let open Re in compile @@
  seq [
    group @@ alt [ bow ; compl [no_case @@ set "aeiouy"] ] ;
    group @@ alt (List.map (fun (s,_) -> str s) map_to_umlauts) ;
  ]

let replace s =
  let f subs =
    Re.get subs 1 ^ List.assoc (Re.get subs 2) map_to_umlauts
  in
  Re.replace ~f regexp s

let () =
  print_endline @@ replace Sys.argv.(1)

On your version, apart from the change in algorithm, I have only one comment: You really don't need a regexp to check if a char is a voyel. ;)

Also, do note all of this is playing fast and, more important, very very loose, with Unicode.


Send / receive wrapper for System.Net.Sockets

Review

Property Connected is not thread-safe. Use Interlocked.CompareExchange to get the connection atomically.
Events DataReceived and Disconnected are never cleared. This will cause a memory leak. Implement a Clear function and/or implement IDisposable.
Methods Send, Disconnect, EndReceive are not thread-safe. Consider using a mutex/lock.
Checking fullyReceived on receivedLength == header.DataSize is naive and can be broken. TCP messages can be sent in several packets. Use an internal buffer instead. Also, receivedLength = 0 is a clean way of determining no more data is available.
Catching SocketException blindly is a code-smell.


It sounds like you're on the right track, but the cache key needn't be so specific. Unless you're storing to the same cache/dictionary as other code is using, there won't be collisions.
Since Fibonacci numbers build on the previous 2 numbers, recursion is a natural solution, but obviously gets slower for larger numbers. This post details a recursive memoization approach that seems like exactly what you're looking for:
https://www.hackingwithswift.com/plus/high-performance-apps/using-memoization-to-speed-up-slow-functions


Scraping weather conditions for mountain peeks

One option is to modify your TemplateView class to include the peak's name  as an instance attribute (say peak_name) and make the get_context_data method make use of it:
class  TemplateView():
    # Class attributes

    def __init__(self, peak_name):
        # Instance attributes
        # ...
        self.peak_name = peak_name

    # Class methods

    # Modification of the get_context_data method
    def get_context_data(self, **kwargs):
        context['Peak'] = PeakForecast.objects.filter(
            name_of_peak=self.peak_name).order_by('date')  #<- Modification here
        print(context['Peak'])
        return context

And then you can generate your peak views as instances of that class:
krivan_view = TemplateView('Krivan')
krivan_view.get_context_data(arg1='arg1', arg2='arg2')


Find max number you can create from an array of numbers

Your code

Your code as such seems to be functional, but not really elegant or concise.

First, the variable names don't speak for themselves. Nobody would be hurt if the function input was named numbers instead of a and number instead of ai. work_dict is also  not a particularly good name since it's very generic. How about digit_histogram?

Handling single digit numbers separately seems unnecessary. The algorithm you implemented can handle them without special treatment.

When constructing max_num, there is a lot of repeated code. You could simplify this using a list comprehension and join (more on that soon).

How I would have tackled this

Since we have the luxury that combination of these numbers should be maximized in base 10, we can get their digits simply by looking at their str representation (which coincidentally happens to be in base 10 ;-) )1.

If you include the other recommendations from above you end up with:

def maximum_number_str(arr):
    digit_histogram = {
        "0": 0, "1": 0, "2": 0, "3": 0, "4": 0,
        "5": 0, "6": 0, "7": 0, "8": 0, "9": 0
    }
    # or: digit_histogram = {str(i): 0 for i in range(10)}

    for number in arr:
        for digit in str(number):
            digit_histogram[digit] += 1

    max_num = "".join(str(i)*digit_histogram[str(i)] for i in reversed(range(10)))

    return int(max_num)

Depending on how familiar you are with Python and if other modules are allowed, you could come up with a solution using collections.Counter, or at least skip the dict initialization all-together if you use .get(...) instead of [...] when accessing the dictionary as presented by Pål GD in is answer.

Just for reference, this is how it could look like using a Counter:

from collections import Counter

def maximum_number_counter(arr):
    digit_histogram = Counter()

    for number in arr:
        digit_histogram.update(str(number))

    max_num = "".join(
        str(i) * digit_histogram[str(i)] for i in reversed(range(10)))

    return int(max_num)

Edit: The other way to think about that task

There seems to be a vivid discussion here if you understood the task correctly. If you follow the arguments that speak against your and my former interpretation, this actually leads to another interesting problem.

I came up with the solution below, though I highly doubt that I could have come up with this in an interview situation.

from functools import cmp_to_key

def maximize_joint_number(number1, number2):
    joined12 = int(str(number1)+str(number2))
    joined21 = int(str(number2)+str(number1))
    return joined21 - joined12

def maximum_number(numbers):
    """
    Generate the largest possible number that can be generated rearanging the
    *numbers*, not the digits of the input sequence
    """
    return int("".join(str(i) for i in sorted(numbers, key=cmp_to_key(maximize_joint_number))))

The idea to this is actually from this blog post that was given in a comment by Eric Duminil. The cmp_to_key trickery is needed because the cmp keyword was removed from sort in Python 3. You could also use cmp_to_key as a decorator, which makes it a little bit nicer:

from functools import cmp_to_key

@cmp_to_key
def maximize_joint_number(number1, number2):
    ...

def maximum_number(numbers):
    return int("".join(str(i) for i in sorted(numbers, key=maximize_joint_number)))

A quick test seems to fulfill all the presented example outputs:

if __name__ == "__main__":
    assert maximum_number([0, 12]) == 120
    assert maximum_number([2, 21, 10]) == 22110
    assert maximum_number([9, 2, 5, 51]) == 95512
    assert maximum_number([20, 210, 32]) == 3221020
    assert maximum_number([1, 19, 93, 44, 2885, 83, 379, 3928]) == 93834439283792885191

The second and third test case break implementations that would try to use something like sorted(numbers, key=str, reverse=True) (lexicographical sort) directly.

1 Thanks to Peter Cordes for pointing out the inaccurate wording here in earlier revisions.


Should I unpack a Maybe with maybe or pass value around

Prelude
I think your code (sans bug) is fine. Your question is already a little nit-picky so my comments will mostly be nit-picks. I am not a Haskell expert either, so don't place too much authority in my comments. Evaluate them for yourself.
My comments are in a somewhat arbitrary order, but I've organized them with headers. The section pertaining specifically to your question is titled "What to do with the case".
The revised code is included at the end.
The Guess datatype
A datatype that is used precisely like this already exists, it's called Ordering and can be found in Data.Ord (although I believe it's included by default). No need to reinvent the wheel here. Especially because you'll see later that you can use already-made functions that work with Ordering.
Input validation
You correctly check that the input is a well-formed number, but you don't check that it's between the min and max value of the range. Here's an example of how this bug manifests itself.
Guess the number between 1 and 1000 !
50
Guess more !
Guess the number between 50 and 1000 !
20
Guess more !
Guess the number between 20 and 1000 !

Notice how the value goes down. The fix, which I will put in the section addressing your questions about Maybe, is to add another case that deals with a well-formed, but invalid guess.
Syntax and other small details
min and max are built-in functions, it's best not to shadow them. I would call them minValue and maxValue.
You can pattern match in function definitions so that you don't need to unpack range – you can instead have
askForNumber oracle tries (minValue, maxValue) = do
...

Function application has the highest precedence in Haskell, so you don't need parens around (show min). (oracle) <$> guess doesn't need the parens either.
maybe value id = fromMaybe value, so use that instead. You can get fromMaybe from Data.Maybe, but it might be included by default.
oracle
If you switch to using Ordering, you can nix your compareToSecret function and define oracle = compare secret.
What to do with the case
I think it's kind of clunky to extract a value from a Maybe after you've cased on it, which is what you're doing right now. A big utility of case is knowing that your value must be of a certain form in each branch. In that branch, guess must be of the form Just _. While you as a programmer know this to be true, it's much more helpful to have the type system be able to prove this.
As I see it, there are two ways to handle your case statement.
The first is to have two nested case statements. The first branches on guess. If guess is Nothing, it prompts the user for another input. If guess is Just g, it cases on oracle g.
The second is to do a slight modification of what you're doing. Instead of fmapping oracle, you can fmap the function \g -> (oracle g, g). This allows you to extract the guess safely without having to use Maybe. I believe this is what you were doing originally.
I prefer to avoid nesting cases when I can, so I opted for the second one.
If you would also like to validate the input (I chose to), then you will want to add a case at the beginning matching Just (_, guess) – i.e. one that ignores the comparison – to deal with invalid guesses. This pattern, however, will match both invalid and valid guesses. We need to add a guard that asserts that guess > max or guess < min. This looks like:
    ...
    Just (_, guess) | guess < min || guess > max -> do
      putStrLn "Guess out of range"
      askForNumber oracle tries range
    ...

Small note on using oracle
I use the function \g -> (oracle g, g) which might feel slightly clunky. Indeed, there are a few alternatives, but I warn you that they are somewhat arcane. In general, I would avoid using "cute" or "slick" code like this unless you know everyone who sets eyes on the code will understand it.
All of the below are equivalent (for your use case):
\g -> (oracle g, g)    -- plain definition
oracle &&& id          -- (&&&) needs to be imported from Control.Arrow
(,) =<< oracle         -- using the Reader Monad
(,) <$> oracle <*> id  -- using the Reader Applicative

I would be most inclined to use oracle &&& id because it'd be the most recognizable, but even it is a little arcane. I pretty much only included the last example because you'll see code that looks like f <$> g <*> h <*> i … a lot; it's a common idiom for other Applicatives (but I would advise against using it in this case). No matter what people say or do, there's nothing wrong with writing "plain" or "simple" Haskell.
Revised code
You'll find that not too much is different.
import System.Random
import Text.Read (readMaybe)

main :: IO ()
main = do
  gen <- getStdGen
  let maxSecret = 1000
  let (secret, newGen) = randomR (1,maxSecret) gen :: (Int, StdGen)

  -- putStrLn $ show secret
  let oracle = compare secret
  askForNumber oracle 1 (1, maxSecret)

askForNumber :: (Int -> Ordering) -> Int -> (Int, Int) -> IO ()
askForNumber oracle tries range@(minValue, maxValue) = do
  putStrLn $ "Guess the number between " ++ show minValue ++ " and " ++ show maxValue ++ " !"
  guessInput <- getLine
  let guessMaybe = readMaybe guessInput :: Maybe Int

  case (\guess -> (oracle guess, guess)) <$> guessMaybe of
    Nothing -> do
      putStrLn "That is not a number"
      askForNumber oracle tries range
    Just (_, guess) | guess < minValue || guess > maxValue -> do
      putStrLn "Guess out of range"
      askForNumber oracle tries range
    Just (LT, guess) -> do
      putStrLn "Guess less !"
      askForNumber oracle (tries+1) (minValue, guess)
    Just (GT, guess) -> do
      putStrLn "Guess more !"
      askForNumber oracle (tries+1) (guess, maxValue)
    Just (EQ, _) -> do
      putStrLn "You win !"
      putStrLn $ "It took you " ++ (show tries) ++ " tries."
```


Checking whether a grade combination exists

This is very much the same idea I'm using to encapsulate "business logic" queries for re-use in PL/SQL code. So if you're looking for a validation of a concept you'll pass my review :) In a comment to the other answer you said this is just a snippet from a package code - that's good you're using packages. For PL/SQL apps in practice all code should be located in a package - a standalone subprograms a rare.

The notes:

select count is always guaranteed to return a single number so the exception handler for no_data_found is a dead code and should be removed.
If you're just checking for existence there's no point to count beyond 1, thus enter rownum = 1. This also guarantees the select returns either 0 or 1. This might or might not help your query performance (check explain plan).
It's a bit questionable if such an utility subprogram should record the exception or not but more information about your error handling implementation would be required to comment further. I usually don't but I'll let the exception propagate to the caller context and then record the full stack trace there. The good thing is that you re-raise (I just assume that from the name of raise_fa_err).

Modified example with the points #1 and #2 applied:

function record#exists(
  i_math_grade    in pls_integer
 ,i_science_grade in pls_integer
 ,i_english_grade in pls_integer
 ,i_music_grade   in pls_integer
 ,i_average       in pls_integer
) return boolean is
  l_exists pls_integer;
begin
  select count(*)
  into   l_exists
  from   grade
  where math_grade    = i_math_grade
    and science_grade = i_science_grade
    and english_grade = i_english_grade
    and music_grade   = i_music_grade
    and average       = i_average
    and rownum        = 1
  ;

  return l_exists = 1;
exception
  when others then
    raise_fa_err('record#exists');
end record#exists;


Two groups of Buttons but with same class name

If you must use jQuery, then the simplest way by far is to wrap each section in a div :

Park One

    <button class="updateStatus" value="complete">Complete</button>
    <button class="updateStatus" value="on hold">On Hold</button>

Park Two

    <button class="updateStatus" value="complete">Complete</button>
    <button class="updateStatus" value="on hold">On Hold</button>

This allows you to use .siblings("button") to select the clicked button's counterpart :

$(".updateStatus").click(function () {
    $(this)
        .addClass(($(this).val() === "complete") ? 'green' : 'orange')
        .siblings("button").removeClass("green orange");
});

The .each() loop vanishes.

It's very common to use divs or spans like this, to give your DOM structure.

Updated fiddle