Custom Web Api asynchronous filter implementation

Here is couple of things that I could done;

Implement a logger class, Logging with "Trace.WriteLine" is not usefull for everycase.
Override allow multiple; public override bool AllowMultiple => false;
Log the error...

public sealed class LogActionFilter : FilterAttribute, IActionFilter
{
    private readonly ILogManager _logManager;

    public LogActionFilter(ILogManager logManager)
    {
        _logManager = logManager;
    }

    private readonly Stopwatch _stopwatch = new Stopwatch();

    public override bool AllowMultiple => false;

    public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext,
                                                                    CancellationToken cancellationToken,
                                                                    Func<Task<HttpResponseMessage>> continuation)
    {
        await InternalActionExecuting(actionContext);

        if (actionContext.Response != null)
        {
            return actionContext.Response;
        }

        HttpActionExecutedContext executedContext;

        try
        {
            var response = await continuation();

            executedContext = new HttpActionExecutedContext(actionContext, null)
                              {
                                  Response = response
                              };
        }
        catch (Exception exception)
        {
            executedContext = new HttpActionExecutedContext(actionContext, exception);
            _logManager.Error(exception, "LogAction recorded an error");
        }

        await InternalActionExecuted(executedContext);
        _stopwatch.Reset();

        return executedContext.Response;
    }

    private Task InternalActionExecuting(HttpActionContext actionContext)
    {
        _stopwatch.Start();
        return Log("Executing", actionContext, 0);
    }

    private Task InternalActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        _stopwatch.Stop();
        return Log("Executed", actionExecutedContext.ActionContext, _stopwatch.ElapsedMilliseconds);
    }

    private Task Log(string action, HttpActionContext actionContext, long elapsedTime)
    {
        return Task.Run(() =>
                        {
                            var controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
                            var actionName = actionContext.ActionDescriptor.ActionName;
                            var parameters = string.Join(", ", actionContext.ActionArguments.Values.Select(x => x).ToArray());

                            var message = $"{action}: ctrl: {controllerName}, act: {actionName}, params: {parameters}" +
                                          $"{(elapsedTime > 0 ? "took (ms): " + elapsedTime : string.Empty)}";
#if (DEBUG)
                            Trace.WriteLine(message, "Action filter log");
#elif (RELEASE)
                            _logManager.Debug(null, message, "Action filter log");
#endif

                        });
    }
}


I guess that the first part of your code is just to initialize the sample data.

Then here are a few things:

Separate initialization and main loop. I know this is just an exercise, but always doing it will help you keep the mindset.
If you only need to count something, just count it. Don't keep track of everything.
If you only need to check the existence of something, use a boolean value and return as soon as you've found it. Adding elements to a list so that at the end you can count them and return a boolean based on the count is definitely not an efficient way to do it.
What you call cursor is actually an integer, not an object, so the name index may be more appropriate
If you want to give the chance to start searching from a specific index, you may also want to have a default value for that parameter (0 looks like a good choice)
You don't need the third parameter, that's what you are going to return

This is my attempt at it:

big_s = []

def init_big_s():
    for i in range(1,101):
        if i % 10 == 0:
            big_s.extend([1,2,3])
        else:
            big_s.append(i)

def looking_patt(pattern, index=0):
    for i in big_s:
        if i == pattern[index]:
            index += 1
            if index == len(pattern):
                return True
        else:
            index = 0
    return False

init_big_s()
print looking_patt([1, 2, 3])


Is it safe? Yes, it will currently do the right thing.

One of the features that plays in to best practice though, is how future proof it is. Over time, code gets edited, changed, etc. What you want is to make the code 'fail safe' in the future too. What if someone comments out the second line, you end up with a problem.

A better way to write your code would be to set the default, and only change it if the input is valid:

<?php
$menu = array( "page1","page2","page3" );

$section = "page1";
$input = $_GET['section'];
if ( isset( $input ) && in_array( $input, $menu ) ) {
    $section = $input;
}

?>


Regex to match each line in a file, with windows and/or linux line break included, even for missing line break at EOF

I think this would work:
.*(\r?\n|$)

.* matches anything except line breaks (at least '\n', but some regex engines also treat other characters as line breaks).
(\r?\n|$) matches the line break or the end of the string (in case the last line is missing a line break.


Testing after_save hooks in Rails 4.2 with MiniTest

A valid approach would be check if NotificationMailer.team_invitation was called. In order to get this job done, you'll need first of all change this NotificationMailer.team_invitation hard-coded call to something injected. Something like this:

class TeamMembership < ActiveRecord::Base
  # other methods

  after_create :invite_user_to_team!

  def notification_method(notification_service = NotificationMailer)
    @notification = notification_service
  end

  private
  def invite_user_to_team!
    @notification.team_invitation(team, user)
    nil
  end
end

Now, you can create an expectation over NotificationMailer. Inside your test, you can define your mock and define its behavior:

class TeamMemberTest < ActiveSupport::TestCase
  def test_after_create_new_team_member_it_should_be_notified
    notification = Minitest::Mock.new
    notification.expects(:team_invitation).with(team, user).once
    # your TeamMember class working to create new
  end
end

I hope it helps :)


Akka actor to calculate a soccer league rank

For starters you could try sending commands to you Actor instead of Nouns(source: Reactive Messaging Patterns with the Actor Model).

Put commands into a companion object for Actor.
Name commands in past tense.
Remove your "literal match" [Message("getRank")] and create a Command(type-safet) to handle the method.

See this thread for information on naming Commands.
https://stackoverflow.com/questions/12510535/naming-convention-for-commands-events


Isn't it quicker to compute the full product in linear time and then divide by each N?

EDIT: bugfix - (O3N) time with zero check:

#include <numeric>
#include <array>
#include <vector>
#include <iostream>

namespace notstd {

    template<class T>
    auto to_vector(std::initializer_list<T> il) {
        return std::vector<T>(il);
    }
}

static constexpr struct {
    template<class Iter>
    void operator()(Iter first, Iter last) const {
        if (first != last) {
            auto zeros = std::count(first, last, 0);
            switch (zeros) {
                case 0: {
                    auto accum = std::accumulate(std::next(first), last,
                                                 *first, std::multiplies<>());
                    std::transform(first, last,
                                   first,
                                   [accum](auto &&v) {
                                       return accum / v;
                                   });
                }
                    break;

                case 1: {
                    auto maybe_multiply = [](auto &&x, auto &&y) { return y == 0 ? x : x * y; };
                    auto accum = std::accumulate(first, last,
                                                 1, maybe_multiply);
                    std::transform(first, last,
                                   first,
                                   [accum](auto &&v) {
                                       if (v == 0)
                                           return accum;
                                       else
                                           return 0;
                                   });
                }
                    break;

                default: {
                    std::fill(first, last, 0);
                } break;
            }

        }
    }
} other_products {};

template<class Container, class Algo>
auto mutate_copy(Container c, Algo algo) {
    algo(std::begin(c), std::end(c));
    return c;
};

template<class T, class Algo>
auto mutate_copy(std::initializer_list<T> il, Algo &&algo) {
    return mutate_copy(notstd::to_vector(il),
                       std::forward<Algo>(algo));
};

template<class T, std::size_t N, class Algo>
auto mutate_copy(std::array<T, N> const &a, Algo &&algo) {
    return mutate_copy(std::vector<T>(a.begin(), a.end()),
                       std::forward<Algo>(algo));
};

template<class Container, class Algo>
auto &mutate_inplace(Container &c, Algo algo) {
    algo(std::begin(c), std::end(c));
    return c;
};

template<class Container>
std::ostream &emit(std::ostream &os, Container &&c) {
    auto impl = [&os](auto first, auto last) {
        using value_type = typename std::iterator_traits<decltype(first)>::value_type;
        std::copy(first, last,
                  std::ostream_iterator<value_type>(os, ", "));
    };
    impl(std::begin(c), std::end(c));
    return os;
}

int main() {

    emit(std::cout, mutate_copy({1, 2, 0, 4, 5}, other_products)) << std::endl;
    emit(std::cout, mutate_copy({2, 3, 4, 5, 6}, other_products)) << std::endl;
    emit(std::cout, mutate_copy({6, 5, 4, 3, 2}, other_products)) << std::endl;

    std::array<int, 5> ar{10, 20, 30, 40, 50};
    emit(std::cout, mutate_copy(ar, other_products)) << std::endl;
    emit(std::cout, mutate_inplace(ar, other_products)) << std::endl;

    auto in = std::vector<int> {10, 11, 12, 13, 14};
    emit(std::cout, mutate_copy(in, other_products)) << std::endl;

    std::vector<int> foo{};
    emit(std::cout, mutate_inplace(foo, other_products)) << std::endl;
}

previous code:

I believe this would give O(2N) time.

#include <numeric>
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>

template<class Iter>
auto other_products(Iter first, Iter last)
{
    using type = typename std::iterator_traits<Iter>::value_type;
    auto mega_product = std::accumulate(first, last,
                                        type(1), std::multiplies<>());

    std::vector<type> result;
    result.reserve(std::distance(first, last));
    std::transform(first, last,
                   std::back_inserter(result),
                   [mega_product](auto&& v)
                   {
                       return mega_product / v;
                   });
    return result;
}

//
// convenience specialisation for any container
//
template<class Container>
auto other_products(Container&& c)
{
    return other_products(std::begin(c), std::end(c));
}

template<class Value>
auto other_products(std::initializer_list<Value> c)
{
    return other_products(std::begin(c), std::end(c));
}

template<class Container>
std::ostream& emit(std::ostream& os, Container&& c)
{
    auto impl = [&os](auto first, auto last)
    {
        using value_type = typename std::iterator_traits<decltype(first)>::value_type;
        std::copy(first, last,
                  std::ostream_iterator<value_type>(os, ", "));
    };
    impl(std::begin(c), std::end(c));
    return os;
}

int main()
{

    emit(std::cout, other_products({1, 2, 3, 4, 5})) << std::endl;
    emit(std::cout, other_products({2, 3, 4, 5, 6})) << std::endl;
    emit(std::cout, other_products({6, 5, 4, 3, 2})) << std::endl;

    auto in = std::vector<int> { 10, 11, 12, 13, 14 };
    emit(std::cout, other_products(in)) << std::endl;

}

As a further refinement, I had a go are separating the concerns of 'in-place' or 'copy' operations from the actual mutating algorithm.

See what you think:

#include <numeric>
#include <array>
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
#include <initializer_list>

namespace notstd {

    template<class T>
    auto to_vector(std::initializer_list<T> il)
    {
        return std::vector<T>(il);
    }
}

static constexpr struct
{
    template<class Iter>
    void operator()(Iter first, Iter last) const
    {
        if (first != last) {
            auto accum = std::accumulate(std::next(first), last,
                                         *first, std::multiplies<>());
            std::transform(first, last,
                           first,
                           [accum](auto&& v)
                           {
                               return accum / v;
                           });
        }
    }
} other_products {};

template<class Container, class Algo>
auto mutate_copy(Container c, Algo algo)
{
    algo(std::begin(c), std::end(c));
    return c;
};

template<class T, class Algo>
auto mutate_copy(std::initializer_list<T> il, Algo&& algo)
{
    return mutate_copy(notstd::to_vector(il),
                       std::forward<Algo>(algo));
};

template<class T, std::size_t N, class Algo>
auto mutate_copy(std::array<T, N> const& a, Algo&& algo)
{
    return mutate_copy(std::vector<T>(a.begin(), a.end()),
                       std::forward<Algo>(algo));
};

template<class Container, class Algo>
auto& mutate_inplace(Container& c, Algo algo)
{
    algo(std::begin(c), std::end(c));
    return c;
};

template<class Container>
std::ostream& emit(std::ostream& os, Container&& c)
{
    auto impl = [&os](auto first, auto last)
    {
        using value_type = typename std::iterator_traits<decltype(first)>::value_type;
        std::copy(first, last,
                  std::ostream_iterator<value_type>(os, ", "));
    };
    impl(std::begin(c), std::end(c));
    return os;
}

int main()
{

    emit(std::cout, mutate_copy({1, 2, 3, 4, 5}, other_products)) << std::endl;
    emit(std::cout, mutate_copy({2, 3, 4, 5, 6}, other_products)) << std::endl;
    emit(std::cout, mutate_copy({6, 5, 4, 3, 2}, other_products)) << std::endl;

    std::array<int, 5> ar { 10, 20, 30 , 40, 50 };
    emit(std::cout, mutate_copy(ar, other_products)) << std::endl;
    emit(std::cout, mutate_inplace(ar, other_products)) << std::endl;

    auto in = std::vector<int> {10, 11, 12, 13, 14};
    emit(std::cout, mutate_copy(in, other_products)) << std::endl;
}


jquery script for inserting and deleting text

I suppose you're talking about these 3 JSLint warnings:
Combine this with the previous 'var' statement.
  var interval = 300 - Math.random() * 100;

Combine this with the previous 'var' statement.
  var interval = 3000;

Do not use 'new' for side effects.
      new Typing(this, toType, interval);

The first 2 are suggestions to combine multiple var declarations into one. For example, instead of:

var x = 3;
var y = 4;

The suggestion is to do like this instead:
var x = 3, y = 4;

The 3rd one is about instantiating something without storing the reference somewhere. This page explains why this is not recommended, in particular:

By not assigning the return value of a constructor to something you will lose the reference to that instance. Generally, by constructing an instance you would want to keep that reference, whether to use again later or for "internal" use as part of a comparison. What's the point of constructing something you are going to throw away as soon as it's been created?
If you have a constructor function that performs work beyond simply setting up an instance, and you are calling that constructor just for these "side effects", consider reworking your code to allow you to call the function normally, without the new operator.

Personally I disagree with the suggestion to combine the var statements, but agree with the 3rd warning.


Generating binary sequences without repetition

Generating all sequences and then checking if they are unique can be quite expensive, as you noticed. Consider this alternative approach:

Generate one sequence
Convert it to a tuple and add it to a set
If the set is of size batch_size return it, else go to step 1

This approach can be implemented like this:
def unique_01_sequences(dim, batch_size):
    sequences = set()
    while len(sequences) != batch_size:
        sequences.add(tuple(np.random.randint(0, 2, dim)))
    return sequences

Running the two solutions for dim=32 and batch_size=1000:
Original: 2.296s
Improved: 0.017s

Note: the result of the function I suggested is a set of tuples, but it can be converted to the format you prefer.
A few other suggestions and considerations:

Functions: consider to encapsulate the code in a function, it is easier to reuse and test.
Exit condition: this part:
if is_same:
    continue
else:
    break

Can be simplified to:
if not is_same:
    break

binary vs integer sequence: probably you know it, but the result is a "sequence" of integers, not a binary sequence as the title says.
Collisions: the suggested approach can become very slow for some configurations of dim and batch_size. For example, if the input is dim=10 and batch_size=1024 the result contains all configurations of 10 "bits", which are the binary representations of the numbers from 0 to 1023. During the generation, as the size of the set sequences grows close to 1024, the number of collisions increases, slowing down the function. In these cases, generating all configurations (as numbers) and shuffling them would be more efficient.
Edge case: for dim=10 and batch_size=1025 the function never ends. Consider to validate the input.


First, a palindrome can have an odd number of characters:

  Even-character palindrome: 1221
  Odd-character palindrome: 13531

You only support even-character palindromes, which is bad, but even worse, you do not return an error about invalid input for an odd-digit palindrome, you remove the first digit.

Second, to help prevent errors, you should always use braces around one-liner if and loop statements:

if (n % 2 != 0) {
    word.erase(0, 1);
}

Third, don't leave dead code in there.  You have a chunk of code commented out, so that should be removed.

Fourth, your comments are in the order of #1, #3, #2, ...  Either the comments should be fixed or the code should be re-ordered.

Fifth, there is a mistake right here:

for (int i = 0; i < n / 2; i++) {
    s.push(word[i]);
    word.erase(i, 1);
}

Sixth, it appears that you are using namespace std; somewhere in your code as you did not prefix stack or string.  This is not a good idea because namespaces can contain functions with the same name, so you can have problems with your code when you start using multiple namespaces, or even if you have a function in the same file that has the same name as a function in the namespace.  You can read more about it here.

So, with the word "qweewq", you first remove "q" so the word is "weewq".  Next, i == 1, so you remove "e", so the word is "wewq", and so on.  You should change this to:

for (int i = 0; i < n / 2; i++) {
    s.push(word[0]);
    word.erase(0, 1);
}

This is a working solution:

bool isPalindrome(std::string word) {

    int wordSize = word.size();

    // #1 load the stack
    std::stack<char> s;
    for (int i = 0; i < wordSize / 2; i++) {
        s.push(word[0]);
        word.erase(0, 1);
    }

    // #2 make sure word size is same as stack size (handle odd-character palindromes)
    if (word.size() > s.size()) {
        word.erase(0, 1);
    }

    // #3 if our stack is empty, then return true
    if (s.size() == 0) {
        return true;
    }

    // #4 validate palindrome
    while (s.size() > 0) {

        if (s.top() == word[0]) {
            s.pop();
            word.erase(0, 1);

            // return true only when our stack is empty
            if (s.size() == 0 || word.size() == 0) {
                return true;
            }
        }
        else {
            return false;
        }
    }
}

Improvements on this solution are given here.


Drawing a triangle and some concentric circles

Is it a good practice just to import everything so I don't have to go back and add stuff?

In a modern IDE (e.g. NetBeans) you can just type in the class you intend to use and quick-fix the import. I usually do this so that I don't have spare imports laying around inadvertently. Also, you can use the source cleanup tool to remove unused imports when you're done. I do this in Eclipse, but I'm exceptionally sure that a similar option is in NetBeans. Importing only what you need reduces compilation time.

  Is it bad just to let NetBeans do serialVersionUID for me? (I don't like yellow squiggles!)

Do you plan on "serializing" your class? Do you expect anyone else to? If so, you'll want that property to be set, so that different versions of your code can determine which version of the class you're deserializing to (or generate an error). You can use 1L for the first version, and increment it every time you add, remove, or change a member of the class. Or, you can just save that for last if you don't expect many changes when the class is done, and generate it then. If you really don't care about serializing the objects, just suppress the warning with an annotation.

  Are those anonymous classes smart or unnecessarily confusing?

The general rule of thumb is: if it's less than (approximately) 10 lines of code, and not frequently used (e.g. is used only once), than anonymous classes are perfectly acceptable, and in fact, encouraged. For code that is bound to be reused often, a named class should be preferred. The Java designers knew that there would often be small classes that only had a few lines of code that, in practice, wouldn't make sense to have in their own source files when one could simply inline the class definition and instantiation at once. Also, because anonymous classes share scope with the outer class, they can get access to the necessary variables and methods without having to accept an instance of the class, modifying member access modifiers, etc.

  Am I instantiating more than I need to?

There's no particular excess here, although this may not be the most efficient method you could have come up with. Unless you were under specific direction from a higher authority not to use certain constructs, such as BufferedImages, this almost qualifies as object abuse; components are generally meant to be a way to interact with users, not to just draw arbitrary objects. However, since we're only talking about two frames, it doesn't really matter, and I don't think it would be worth debating the merit of using components versus images.

  Is this the best way to handle graphics/Graphics?

Normally, one should create a sort of "canvas", and draw onto that. Here, you're changing the entire content of the window just to flop graphics around. Since there's only two frames, this works out okay, but in a game running at 60FPS, your players would get a headache and/or seizures. You could just as easily have made two BufferedImage elements, and flipped between the two, using a common component that you could draw to.

  Do all those fields have to be final?

Fields are final because you want to force certain behavior (e.g. a class cannot be inherited, a value can only be set once, etc). Assuming this was a module that you'd distribute to other developers to use, you'd want anything that should be locked down to be final. You might also use final to prevent yourself from writing code that accidentally modifies the variables. In short, it is a good practice, but it doesn't make sense logically in this example, because this program is sufficiently small enough that you wouldn't likely introduce such a logical error. I would recommend using final as frequently as necessary, but not necessarily here.

  Should I make all of the objects final that don't need to change?

Like before, it doesn't really matter in this example. You make values final so as to avoid accidental or intentional changes to the values. Also remember that final can affect inheritance, so if this were a module to a larger application, you might not want to lock everything down with final. In this case, most everything could be final just to prove to yourself that your code isn't making any unintentional changes. I would actually recommend having everything not be final, and for good measure, not static either.

  I tried to implement a Circle factory singleton in order not to repeat code. Are there problems? Is this worth it?

In a larger program, factories make sense. In this case, it makes no sense at all; the code needed to support the factory is larger than the savings of not having a factory at all. Consider this version (which does the same thing):

for (double i : circles) {
    g2.setColor(colors[count++]);
    g2.draw(new Ellipse2D.Double(200 - i / 2, 200 - i, i, i)));
}

It is perfectly legal, and in fact desirable, to instantiate anonymous, short-lived objects that are passed directly into the parameter list of the function, which is essentially what you're doing anyways. This lets people know, clearly, that you're simply creating a circle, instead of having to refer to the factory's source code to get an answer as to what is going on.

  In general, are there ways to make my code more succinct?

I believe I've outlined most of the problems in the prior answers, but let's go over them:

Drop the use of the factory, it's simply overkill in this case.
Drop the serial ids, especially in anonymous inner classes, as it is unlikely you'll ever serialize them. Warnings are okay, but you can use suppression annotations if you don't like the yellow squiggles (and I personally hate them; they're a guilt trip).
Use just one component to draw onto (or, one to manage the current view state, if you prefer).
Don't hide then show the frame. Instead, call invalidate() to force a repaint. No flickering.
Loading graphics and stuff as an initialization generally makes sense, but not here, because you're just wasting memory (although, not a ton, since this program only weighs in at a few KB, but, the principal remains). You should defer generating the two components until the last possible moment.
Generally speaking, your main app can be the JFrame; this is a normal design.

Without switching to images and all that, I can simply rearrange your code to the far simpler:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

public class JComponentDemo extends JFrame {

    public JComponentDemo() {
        super("Drawing");
    }

    public void start() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBounds(50, 50, 500, 500);
        setVisible(true);
        setContentPane(
            new JComponent() {
            @Override
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.draw(new Line2D.Double(180, 100, 100, 0));
                g2.draw(new Line2D.Double(20, 100, 100, 0));
                g2.draw(new Line2D.Double(180, 100, 20, 100));
            }
        });
        JOptionPane.showMessageDialog(null, "Click OK to Continue");
        setContentPane(new JComponent() {
            @Override
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                double[] circles = {40, 80, 120, 160, 200};
                Color[] colors = {Color.red, Color.green, Color.orange, Color.MAGENTA, Color.cyan};
                int count = 0;
                for (double i : circles) {
                    g2.setColor(colors[count++]);
                    g2.draw(new Ellipse2D.Double(200 - i / 2, 200 - i, i, i));
                }
            }
        });
        setVisible(true);
    }

    public static void main(String[] args) {
        new JComponentDemo().start();
    }
}

Note that anonymous inner classes are only good for "small" things, so this design wouldn't scale well (imagine a UI with hundreds of components). Regardless, you would still want to instantiate those elements either in a constructor, or in a thread that allocates the objects as the program is starting up or running so that the elements are available when needed.


Please review my implementation of a simple When/Then (pseudo Promise) in javascript

I made The following edits:

Prevent the same when function from calling pass twice(therefore invalidating results)
Sends pass function as 1st argument to avoid var that = this
It stores the first pass arg only for simplicity instead of all arguments in results(easily switched)
Then function can't be called more then one
I removed the need for When and when functions(you could leave the separate functions for clarity if you wanted)
There is now only one method then and prop funcs

https://gist.github.com/1115319

Usage

when(
    function(pass){setTimeout(pass,3000)},
    function(pass){pass('2nd');}
)
.then(function(results){
    console.log(results);
})


Writting day_of_month and month_day with pointers instead of array indexing

It would have been nice to see your daytab definition as well.  I'll just assume that you're satisfied with the way it's defined, and that the functions work as intended.

I find this condition in month_day() a bit monstrous:

if((leap == 1 && (yearday >= 1 && yearday <= 366)) || (leap == 0 && (yearday >= 1 && yearday <= 365)))

I would shorten it to the following.  Also, I've inverted the check, so that the function returns early if the parameters fail validation.  Returning early is a better habit, as it reduces indentation, and reduces mental load when reading the code by getting the simpler branch out of the way.

int leap = (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
if (yearday < 1 || yearday > 365 + leap) {
    return -1;
}
for (…) {
    …
}


Show list of states depending on user selection

Regarding your question about downloading all options at once versus fetching the state options dynamically using ajax, the answer depends on just how big the state list is, but probably the right answer is to download them all at once.

File Size Considerations

Consider that jquery, which you are already including, is about 30KB minified and compressed.  My guess would be that your state list is small compared with that, so you shouldn't worry about downloading the whole thing at once.  If that assumption is wrong, then ajax might be a reasonable choice.

UX Considerations

Think about the user experience when the entire state list is downloaded.  Making a new a country selection will instantly repopulate the states -- a seamless experience.  If you have to use ajax, there will be a pause between the user's country selection and when the states become available.  This is awkward, and ideally, if you do this, you'd display an ajax spinner (or some other indication that you are waiting for a network response).  This will make your code more complex, and can be difficult to get exactly right.  For example, you'd need to make sure you handle errors gracefully, and show appropriate messages to the user.  If you don't use ajax, you simply avoid all these issues.

So my advice would be to avoid ajax unless you really need it -- eg, your state lists are huge and you know you'll be supporting users with slow connections.


Using a state machine is generally a very elegant way to parse input. This is actually how parsers
generated by YACC or Bison work, and it's also how lexical analysers generated by LEX work. It allows
the parsing to be more flexible.

Generally the variable names you used are quite descriptive and makes the code easier to use, the
one exception is naming the matrix A.

Things That Would Have Improved This Question
It would have been much easier to review this question if the following had been provided:
1. The definition of the struct matrix.
2. The header files necessary (stdio.h, stdlib.h, strings.h and errno.h).
3. If the 2 different versions of matrix_fill() had been separated and included as matrix_fill1()
and matrix_fill2().
4. If the program had been compiled using -Wall and all warnings addressed prior to asking.

I have included the reformated code that allowed me to compile at the end of my answer to show what
would have made this a better question and easier to answer.

During development of code it is a good idea to compilte the code with -Wall compiler switch so
that all warnings are reported. The warning can also be treated as errors. The type size_t is
not completely compatible with the printf() statements in the commented out algorithm:
Parse2DMatrix.c:142: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘size_t’
Parse2DMatrix.c:142: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘size_t’

The matrix struct should be presented so that we could have suggested possible error handling,
there are times when i or j may cause memory access problems because they are outside the scope
of the matrix.

The choice of types is interesting, I would have used double instead of float, and unsigned int
instead of size_t.

Error Reporting
Rather than using errno.h and perror() for this portion of the code it would have been
better if there was an internal error handling mechanism providing a better description of
the errors. Invalid argument is a little too general, "Missing { at start of expression" might
have been more meaningful.

Exit Versus Return
Calling exit(-1) does not allow the code to clean up after itself, returning an error value
allows the calling code to clean up any allocated memory and reset all items that need to be
reset. If this code was part of an operating system or a daemon that calling exit() is actually
not an option because you wouldn't want the system to crash.

Switch Statement Without Default Case
There should always be a default: case in a switch statement to handle unknown/undefined
behavior. In this specific instance rather than having a goto in case of errors the
default: case could have been used to handle the errors on the next iteration through the
loop. There could be one additional enum value in the enum, error could be a status type.

Enum Coding Standards
It would be better to call attention to the enumerators in the ENUM, and follow general C
Coding Standards (UCSD has published this coding standard).
By making the enumerators ALL_CAPITALS the code would be clearer and show that these are defined someplace.

It is possible that the status/state might be used elsewhere so it would be better to define the enum
type outside the function, and possibly in a header file.

A better way to define the enum would probably be:

typedef status { START, OPEN, READ, DELIM, CLOSE, END, ERROR} Status;

I would probably call the variable status state since that is what it is really being for.

Alternative Implementation For The State Machine
YACC, BISON and LEX generate tables (matricies) for transition from one state to another. One possible
alternate implementation of the state machine is to have an array of function pointers. Another possible
implementation is to use the current state as an index into an array of the next state (how YACC, BISON and
LEX are implemented).

White Space
The parsing algorithm does not allow for white space. Handling white space would be easy to add and allows
the user of the program to make the input more readable. There are a number of ways to implement check on
white space. One possibility is to have matrix_fill() be only a parser and have it run a lexical analysing
function that tokenizes the input. Note: This assumes that the buffer char *input has not been previously
processed to remove white space.

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>

typedef struct Matrix {
    size_t m;
    size_t n;
    float values[20][20];
} matrix;

int matrix_set(matrix *A, size_t i, size_t j, float val)
{
    int error = 0;

    /* Algorithm not specified */

    return error;
}

int matrix_fill2(matrix *A, char *input)
{
    size_t i, j;
    float val;

    enum {
        start,
        open,
        read,
        delim,
        close,
        end
    } status = start;

    while (*input != '\0') {

        switch (status) {
        case start:
            if (*input != '{' || *(input + 1) != '{') {
                errno = EINVAL;
                goto error;
            }

            i = 0, input++;
            status = open;
            break;

        case open:
            j = 0, input++;
            status = read;
            break;

        case read:
            val = strtof(input, &input);
            if (errno < 0) goto error;

            matrix_set(A, i, j, val);
            j++;

            if (*input == ',')
                status = delim;

            else if (*input == '}')
                status = close;

            else {
                errno = EINVAL;
                goto error;
            }

            break;

        case delim:
            input++;

            if (*input == '{')
                status = open;

            else
                status = read;

            break;

        case close:
            input++;

            if (*input == ',')
                status = delim;

            else if (*input == '}')
                status = end;

            else {
                errno = EINVAL;
                goto error;
            }

            i++;
            break;

        case end:
            input++;
            A->m = i, A->n = j;

            break;
        }
    }

    return 0;

error:
    perror("matrix_fill");
    return -1;
}

int matrix_fill1(matrix * A, char * input)
{
    size_t i, j;
    float val;
    int error = 0;

    size_t input_len = strlen(input);
    if (input[0] != '{' || input[input_len - 1] != '}') {
        errno = EINVAL;
        perror("matrix_fill");
        exit(-1);
    }

    input[input_len - 1] = '\0';
    input++, input_len -= 2;

    i = 0;
    while (*input != '\0') {
        printf("input: %s\n", input);
        j = 0;

        if (*input == '{') {
            input++;

            while (1) {

                val = strtof(input, &input);
                printf("(%d,%d) = %f\n", i, j, val);
                matrix_set(A, i, j, val);
                j++;

                if (*input == ',')
                    input++;

                else if (*input == '}')
                    break;

                else {

                }
            }

            i++, input++;
            A->m = i, A->n = j;
        }

        else if (*input == ',') {
            input++;
        }

        else {
            errno = EINVAL;
            perror("matrix_fill");
            exit(-1);
        }
    }
    return error;
}


Leetcode online Find the judge, graph with highest degree

This is a wonderfully succinct solution. I will make one point:

final int[] degreeArray = new int[N + 1];

This creates a never-used int at degreeArray[0]. I understand that this was a choice so as to be able to use a simple access by value of the trustees:

degreeArray[itemInTrustArray[0]]--;

In the interest of creating the minimum number of objects necessary, and thus using the least memory possible, I would recommend initializing degreeArray to length N

final int[] degreeArray = new int[N];

And then left shifting your insert by value statements

degreeArray[itemInTrustArray[0]--]--;
degreeArray[itemInTrustArray[1]--]++;

and finally updating your final for loop to account for this change to the zero-based indexing inherent to arrays

// Now iterate though the degreeArray to find the index having degree as N-1.
for (int i = 0; i < N; i++) {

Since you are working with int primitives, the math operators here would add only a near-vanishing amount to overall runtime, if that is a concern.


Analysis of the most common and salient words in a text

First, I will start with PEP 8 specifications. The PEP 8 analysis shows the following:

E501:17:80:line too long (94 > 79 characters)
E501:25:80:line too long (99 > 79 characters)
E501:46:80:line too long (82 > 79 characters)
E501:66:80:line too long (114 > 79 characters)
E731:76:5:do not assign a lambda expression, use a def
W292:79:62:no newline at end of file

If I am not incorrect, one of the things that you are trying is to calculate the frequency distribution of words, namely the most common words and most rare words. I tried to re-write your code like viz.

from bs4 import BeautifulSoup
from nltk import FreqDist, re

import requests

def retrieve_text(url):
    """Downloads HTML content from a URL, parses with an HTML parser and returns text only."""
    response = requests.get(url)

    soup = BeautifulSoup(response.content, "html.parser")
    return soup.get_text()

if __name__ == '__main__':

    content = retrieve_text("http://www.washingtonpost.com/wp-srv/national/longterm/unabomber/manifesto.text.htm")
    wordList = re.sub("[^\w]", " ", content).split()
    fdist = FreqDist(wordList)

    # print out words only (without counts and weights)
    print(fdist.most_common(20))

As you see in the output, I am obviously not skipping connectorwords, like the,  of etc.:

[('the', 1735), ('of', 1251), ('to', 1078), ('a', 736), ('and', 719), ('that', 657), ('is', 611), ('in', 546), ('be', 412), ('for', 351), ('it', 319), ('or', 290), ('are', 281), ('have', 246), ('society', 239), ('not', 235), ('will', 233), ('as', 230), ('by', 229), ('they', 224)]

but, the execution was much faster and I did not have to spend a huge time downloading the gensim library. Off course if you need something as sophisticated as gensim, I have no substitute, else for frequency, this maybe much faster and you can easily write a method to remove connector words.


Verify that each named sequence is strictly increasing

You are using a list to store the association between names and the previous maximum value. This makes your algorithm O(N^2) because for each element, you might have to go through a list of all previous elements.

You can use a hash table (which has O(1) lookup) to make your algorithm O(N).

You can also add keys when they are not found rather than doing it all at the start for simpler code.

Try to avoid using indices when you can iterate by elements.

quick example solution:

(defun launchSequenceChecker (systemNames stepNumbers)
  (let ((ht (make-hash-table :test 'equal)))
    (loop named l
      for name in systemNames
      for num  in stepNumbers
      do (let ((prev (gethash name ht)))
           (if prev
             (progn
               (when (> prev num)
                 (return-from l nil))
               (setf (gethash name ht)
                     (max prev num)))
             (setf (gethash name ht) num)))
      finally  (return-from l t))))


How secure is this PDO Portfolio Script?

Your database queries are using bound parameters with prepared statements. Good.
You need to escape your output.

Other observations:

Your Database class adds nothing (unless you've abbreviated it here for simplicity?). Consider simply using PDO.
You have no error handling. Try loading your page with incorrect db credentials and see what I mean.
Consider using markup with php instead of string-ified markup in php. It is much easier to read and maintain.


Separate Declaration and Definition of private Node implementation in template Linked List

Your LinkedList does not manage its resources. You need a dtor, user-defined copy-ctor and user-defined assignment-operator at least.
Don't interact with the user from generic library code. Report any errors to the caller instead!
You probably want to provide the lists size to the public. Otherwise, consider whether optimizing removal of non-existent elements and insertion at the end by index is worth the overhead.
Only use std::endl if you really have to flush the stream. Remember flushing kills performance.
All your while-loops would be better off as for-loops.
createNode leaks memory if assignment to .data fails. Anyway, use aggregate-initialization, and you'll see that it's just not worth separating out into its own function:

auto p = new Node{data};

Regarding defining things in-class: There's nothing wrong with that, it's often even preferable, especially for templates.
If you define something outside a class in a header though, remember it won't automatically marked inline, meaning it must not be included in more than one compilation-unit.


Reading your code I can make the following remarks:

I don't like the name User as a service as it looks like it specifies one User object. A better name would be Users or UsersApi or UserService.
Having a User service return null in case of the user not found should return a rejected promise instead of a fulfilled promise as it greatly simplifies the logic of your code. In that case you won't have to do this:

if(user == null){
  res.sendStatus(404);
}

You can wrap all the thenable code in functions so that your code will   become more readable. For example this:

.then((user) => {
    if(user == null){
      res.sendStatus(404);
    } else {
      let token = user.generateResetToken();
      user.update({
        resetToken: token,
      }).then((user) => {
        email.sendResetToken(user.email,user.resetToken);
        res.sendStatus(200);
      })

will become this:

.then(generateResetToken)
.then(sendResetToken)

You do not have to return null as the intent of the function is to send an email here and not return anything. This also makes it more confusing.
Handle all your error cases in the catch function such as this:

function handleErrors(error) {
   console.error(err);
   switch(error.reason) {
     case ERRORS.USER_NOT_FOUND:
        res.sendStatus(404);
        break;
     case ERRORS.USER_UPDATE_FAILURE:
        res.sendStatus(400);
        break;
     default:
        res.sendStatus(417); // Or more cases
   }
}

So lets recap:

exports.sendResetToken = function(req,res) {
   const username = req.headers.username;

   Users
     .findOne({
        where: {username: username}
     }).then(generateResetToken)
     .then(sendResetToken)
     .catch(handleErrors)

    function generateResetToken(user) {
      const token = user.generateResetToken();
      const userUpdatePromise = user.update({
        resetToken: token,
      });

      return userUpdatePromise;
    }

    function sendResetToken(user) {
      EmailService.sendResetToken(user.email,user.resetToken);
      res.sendStatus(200);
    }

    function handleErrors(error) {
      console.error(err);
      switch(error.reason) {
        case ERRORS.USER_NOT_FOUND:
          res.sendStatus(404);
        case ERRORS.USER_UPDATE_FAILURE:
          res.sendStatus(400);
        default:
          res.sendStatus(417) // Or more cases here
    }
  }
}


Fetching counties and localities using JSON API calls

Basically you need to reuse your session variable on the code, for example:

print(login(session))
print(countries(session))
print(counties(session))
print(localities(session))

And inside that functions change the calls that referrers to "requests" to the "session" variable like:

request_url = session.get(
    'https://urgentcargus.azure-api.net/api/Localities',...


Basic one way hash to store a password C#

No, it isnt.

First, you only allow ASCII characters in the password. If I were to choose €¥≠≥≤©® as my password, it would probably be equivalent to choosing ??????? (7 question marks). Try it.

Second, a password hashing function must be slow. Otherwise it is too easy to crack the password.

Third, when you hash a password, you must add some salt to it. This has the effect that even when two people use the same password, the hashed passwords are different, so a possible attacker cannot group people by their passwords.

Fourth, if you print the hashed password and it contains lots of question marks, you are doing it wrong. Instead of converting the hash bytes directly to a string, you must encode them so that only printable characters remain. Typical choices for such an encoding are base64 and hex.

In every possible scenario, even in school, you should use an established algorithm like bcrypt or scrypt instead of inventing your own.


Node.js configuration object based on environment variables

Ideally, I would suggest two changes the the overall design:

the environment variable names could have one consistent prefix, e.g. MONGO_ and ATLAS_
the keys of the config object could match the environment variable names, e.g. databaseName would match MONGO_DATABASE_NAME

If that for some reason is not possible, then we can hardcode the config-to-environment name mapping:

function getConfigurationFor(prefix) {
  const configMap = {
    username:     'HUB_USERNAME',
    password:     'HUB_PASSWORD',
    cluster:      'CLUSTER',
    hosts:        'HOSTS',
    databaseName: 'DATABASE',
    replicaSet:   'REPLICA_SET'
  }

  prefix = prefix.toUpperCase() + '_'
  return Object
    .entries(configMap)
    .reduce((result, [key, envKey]) => {
      result[key] = process.env[prefix + envKey]
      return result
    }, {})
}

const config = getConfigurationFor(
  process.env.NODE_ENV === 'production'
    ? 'atlas'
    : 'mongo'
)

if you can make these design changes, then we have more flexibility: we can create a function that would read all the environment variables that start with a certain prefix and return this as a plain JavaScript object:

const getEnvironmentForPrefix(prefix, source) {
  const camelCase = require('lodash.camelcase')

  return Object
    .entries(source || process.env)
    .filter([key] => key.startsWith(prefix))
    .map(([key, value]) => [key.substring(prefix.length), value])
    .map(([key, value]) => [camelcase(key), value])
    .reduce((result, [key, value]) => {
      result[key] = value
      return result
    }, {})
}

const config = getEnvironmentForPrefix(
  process.env.NODE_ENV === 'production'
    ? 'ATLAS_'
    : 'MONGO_'
)


Process multiple request from different threads in batches on one processing thread

Well, technically you should really post complete code and not have
missing definitions.  Especially since Data and OtherData could
instead be generic type arguments perhaps, or interfaces, so that it's
actually clear what's happening.  I'm just gonna imagine they're
basically both Objects.  Also Processor is undefined.  If it was
really not important just pass it in as an argument to System, as it
is, this is incomplete too.

In System having a separate idList is pointless, the inputMap
already has the right size for implementing back pressure (I wanted to find a good definition, but right now at least Wikipedia doesn't have one under that term; basically if the input can grow unlimited, the system might not be able to catch up if processing takes too long and you might end up with a congested (read: out of memory) system).

In Evaluator, x.size() > 0 could be !x.isEmpty(), that might
potentially be cheaper, but it also expresses intent a bit more clearly:
The check is really whether the map "isn't empty", not about how many
items are in the container exactly.

InterruptedException is for control flow,
don't just print a stack trace.

Also now that I read it, why's there three containers, inputMap,
futureMap and idList all related to the same task?  It'd be much
easier if there was just a sequence of tuples, Tuple<Input, Future>,
and then work through them.  Then replace the List with a
BlockingQueue<Tuple<Input, Future>> and it's already supporting the
waiting / back pressure too.  An ArrayBlockingQueue could be used to
limit the number of elements, while a LinkedBlockingQueue could have
an unbounded size (that's really not advisable though).

Lastly instead of keepRunning a tombstone object could then be
inserted to cancel the thread, then there's also no need for polling via
wait.  That is, insert a new Tuple<>() (same as the IDs at the
moment via new Object()) and when dequeuing from the input, check
whether this element was inserted, due to the object identity being
unique that's then safe to do.

So without spelling it all out, the main thread would look like this
perhaps:

public void run() {
    while (true) {
        Tuple<Input, Future> tuple = input.take();
        if (tuple == tombstone) {
            return;
        }
        tuple.getFuture().complete(processor.apply(tuple.getInput()));
    }
}

With some implementation of Tuple of course; a custom class would work
too.

For the other questions:  I can't see it deadlocking right now, the check for 32 and the notifyAll are a bit odd though.

Other tools in the Java tool set?  Yes, I'd suggest starting with reading through the java.util.concurrent namespace.  In particular the ExecutorService perhaps.


How to get a centered mean (excluding max and min value) of a list in Python?

This code can be written more concisely in a couple of ways:

You can use the sum function rather than an explicit loop:

(sum(nums) - max(nums) - min(nums)) / (len(nums) - 2)

You could also use sorting and slicing to remove the extreme values, which is more concise but less efficient:

sum(sorted(nums)[1:-1]) / (len(nums) - 2)

The slice notation [1:-1] takes the elements of a list starting with the second element (index 1) and finishing with the last-but-one element (index -1, i.e. indexing from the end of the list rather than the start)

If you are using Python 3.4+ you can use the statistics module, which has a mean function:

from statistics import mean

mean(sorted(nums)[1:-1])


Multiply all elements in an array except one

What you have shown is an \$O(n^2)\$ solution in that you use nested loops to determine the results.

I would suggest an \$O(2n)\$ approach:

function main(numbers) {
    // one iteration to get product of whole array
    var arrayProduct = numbers.reduce(function(product, value) {
        return product * value;
    }, 1);

    // one iteration to map new array values by dividing
    // full array product by current value
    return numbers.map(function(value) {
        return arrayProduct / value;
    });
}

You could probably use for loops instead of Array functions to micro-optimize this, but if I put myself into the position of someone who might grade such an algorithmic challenge  as this. I would probably be happier to see code like this, as it still meets the requirement to optimize the performance to \$O(2n)\$, while providing code that is more readable.  In other words, I would rather see the reduce() and map() calls in a production code base unless I had a use case where I really needed to squeeze every drop of performance out of this function.

ES6 version:

const main = (numbers) => {
    const arrayProduct = numbers.reduce( (product, value) => product * value, 1);
    return numbers.map( (value) => arrayProduct / value );
}

One could also easily foresee a case where larger arrays could easily hit up against the Number.MAX_SAFE_INTEGER value in javascript (\$2exp53\$), so one might consider throwing an error at some point to abort the operation.

const main = (numbers) => {
    const arrayProduct = numbers.reduce(
        (product, value) => {
            const product = product * value;
            if (product >= Number.MAX_SAFE_INTEGER) {
                throw new RangeError('Product has reached Number.MAX_SAFE_INTEGER');
            }
            return product;
        },
        1
    );
    return numbers.map( (value) => arrayProduct / value );
}


/// <summary>
    /// Identifiers the generation.
    /// </summary>
    /// <returns>A Unique ID</returns>
    private string generateUniqueID(int _characterLength = 11)

A good summary should describe what the method does. This summary doesn't really tell me anything. Keep it simple: the method generates IDs, so write the summary as such.

generateUniqueID does not follow C# method naming conventions. Call it GenerateUniqueID. Note the PascalCase.

A character always has a length of 1, so _characterLength is a bit of a confusing name for me. What it describes is actually the length of the ID, so call it idLength, or just length since the thing it's describing is obvious from the method name anyway.

You got the camelCasing right for parameter and local identifiers, but it's not conventional to use underscores. Get rid of those.

It's not clear why you'd give such a method a default value, but in any case that 11 should be defined as a constant somewhere. Avoid magic numbers. By giving that number a name, you give it a meaning that's obvious to the next person who reads your code.

private const int DefaultIDLength = 11;

private string GenerateUniqueID(int length = DefaultIDLength)
...

StringBuilder _builder = new StringBuilder();

It's common to use var when the expression type is obvious.

Your ID will always be length characters long, so use the StringBuilder constructor that takes an initial capacity:

var builder = new StringBuilder(length);

Enumerable
            .Range(65, 26)
            .Select(e => ((char)e).ToString())
            .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
            .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
            .OrderBy(e => Guid.NewGuid())
            .Take(_characterLength)
            .ToList().ForEach(e => _builder.Append(e));

This is the crux of your implementation, and there's a lot to unpack here, so let's go step by step.

Enumerable
            .Range(65, 26)
            .Select(e => ((char)e).ToString())
            .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
            .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))

This produces the same sequence every time you run it. It's painful to read. Why not just specify it as a constant? This gets the point across far easier:

private const string AllowableIDCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

But we'll see later that none of this is necessary.

You don't need all those ToStrings everywhere. You gain nothing by using string as an intermediate representation instead of char. Keep them as chars during the shuffle: StringBuilder.Append() has an overload that accepts char.

I try to avoid writing lambdas with side effects. This would be more conventionally written as a foreach loop, which also avoids the need to convert the thing to a list:

foreach (char c in AllowableIDCharacters
            .OrderBy(e => Guid.NewGuid())
            .Take(length))
{
    builder.Append(c);
}

But by far the biggest problem here is your source of entropy, as Turksarama pointed out in the comments. By shuffling the alphabet, you are not allowing any repeated characters! This cuts down the number of unique IDs you can generate by more than half. Drop the shuffling idea entirely, it's not the best tool for this job.

You cannot generate unique IDs without keeping some kind of state. GUIDs work by generating sequences that, while not unique in a pure sense, are so astronomically unlikely to be repeated that they are "unique" for all practical intents and purposes.

If you embrace the non-determinism approach of generating unique IDs that GUID takes, then the question is no longer "how to generate a unique ID with as few characters as possible". It is now "what is an acceptable trade-off between ID length and probability of collision".

Because your method is just a mechanism for generating IDs given a length, then half of your problem reduces to something much simpler:

Given an ID length n, how do I minimize the probability of a collision?
How do I maximize the amount of information contained within a string of length n?

Both of these are straightforward problems. To minimize collisions you need a source of entropy that is both uniformly distributed and unpredictable. There are a lot of ways to do this, with varying degrees of uniformity and unpredictability, but do note that GUIDs are not uniformly distributed, are somewhat predictable, and are therefore not a great choice here. There is plenty of literature on how to generate such entropy so I won't go into detail for now. A common choice in .NET is to use RNGCryptoServiceProvider.

Maximizing the information contained in the ID means trying to squeeze as many bits of data as possible into that string. You chose an encoding that can represent 62 different things per character, or about 5.95 bits of data per character -- but because of the shuffling issue we talked about earlier, the actual number will be much smaller. For IDs of length 11 it's less than half.

I assume you're limited to ID strings of 8-bit ASCII-ish characters. But the alphabet you came up with is really close to Base 64, so why not just use Base 64? That'll give you an even 6 bits of information per character. By selecting a standard encoding as such, you'll avail to yourself a suite of standard tools for converting to and from that encoding.

Here's an example of how you could do it:

private static readonly RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

private string GenerateUniqueID(int length)
{
    // We chose an encoding that fits 6 bits into every character,
    // so we can fit length*6 bits in total.
    // Each byte is 8 bits, so...
    int sufficientBufferSizeInBytes = (length * 6 + 7) / 8;

    var buffer = new byte[sufficientBufferSizeInBytes];
    random.GetBytes(buffer);
    return Convert.ToBase64String(buffer).Substring(0, length);
}

This gives you 6 bits of entropy per character. It's up to you and the constraints of your business domain to pick an appropriate length. By the "birthday problem" rule of thumb, the probability of two random IDs of n bits to conflict with each other is about one in 2^(n/2); so an ID length of 11 gives you 66 bits, with a one in 2^33 chance of two IDs conflicting.


Only addressing your last point about the layout of operatorTable, i would use 4 space indentation as according to PEP8-indentation.

operatorTable = {
    "+": Operator(2, lambda a,b: a+b),
    "-": Operator(2, lambda a,b: a-b),
    "/": Operator(2, lambda a,b: a/b),
    "*": Operator(2, lambda a,b: a*b),
    "<": Operator(2, lambda a,b: a<b),
    ">": Operator(2, lambda a,b: a>b),
    "_": Operator(1, lambda a: -a),
    "p": Operator(0, lambda: math.pi),
    "e": Operator(0, lambda: math.e),
}

Also note the comma after the last item. This has a small advantage when you use a source control system, when another item is added after the last item only the new line will show up in a diff and not the previous line which only has a comma added.


Creating a simple 52-card data structure for Blackjack in Python

One thing that catches my eye:

Default list argument.

There is a bit of a footgun hiding in this method:

def __init__(self, card=[], card2=[], score=0):
    self.card = card
    self.card2 = card2
    self.score = score

Default arguments are only created once, when the method is defined.  The end result is that all Hands using default arguments will share the same lists. Observe:

>>> first = Hand()
>>> first.card
[]
>>> second = Hand()
>>> second.card.append(1)
>>> first.card
[1]

I mention this not because it currently causes problems in the code (it does not; card and card1 are never modified in-place), but because it is a problem you are bound to run into in the near future (or perhaps already have!).

There are a couple ways to get around this.

A good placeholder value is usually None.  The following lists are created each time the function is run:

def __init__(self, card=None, card2=None, score=0):
    if card is None: card = []
    if card2 is None: card2 = []
    self.card = card
    self.card2 = card2
    self.score = score

If you immediately take a copy of any mutable objects then they are harmless:

def __init__(self, card=[], card2=[], score=0):
    self.card = list(card) # copies the input list
    self.card2 = list(card2)
    self.score = score

("mutable" objects are those that can be modified in-place; list, dict, and set are mutable.  int, tuple, and str are immutable, and they are safe to use anywhere)

But I feel the most important alternative is probably this:

Simply require the cards to be passed in.

def __init__(self, card, card2, score=0):
    self.card = card
    self.card2 = card2
    self.score = score

Generating cards and remembering (i.e. storing) cards are two separate responsibilities.  It is clear (from the fact that playerScore and dealerScore both index into self.card[0]) that, in general, this class is expected to contain cards.  Therefore, a different one should generate them.

That said, it also has the dual responsibility of both tracking a score and making decisions based upon that score.  In fact, it would seem that these two are the only real reasons it needs to exist.  It feels more like the class is trying to be this:

class Player:
    def __init__(self):
        self.score = 0

    def playerScore(self, card):
        value = str(card)
        if value.isdigit():
            # yadda yadda yadda ...

    def dealerScore(self, card):
        value = str(card)
        if value.isdigit():
            # yadda yadda yadda ...

in which case we never even need to store the card in the class!

Duplicate logic

playerScore and dealerScore duplicate some logic which can be factored out with a flag:

def addCardScore(self, card):
    value = str(card)
    if value.isdigit():
        self.score += int(value)
    elif value == "Ace":
        if self.playerType == 'player':
            self.playerAceValue()
        else:
            self.dealerAceValue()
    else:
        self.score += 10

def playerAceValue(self):
    aceChoice = input("Play ace as 11 or 1? ")
    while not aceChoice.isdigit():
        try:
            aceChoice = input("Play ace as 11 or 1? ")
        except TypeError:
            print("Invalid response.")
    if aceChoice == "11":
        self.score += 11
    else:
        self.score += 1

def dealerAceValue(self):
    if self.score >= 11:
        self.score += 1
    else:
        self.score += 11

# ... somewhere else, not necessarily in a class ...
def playGame():
    player = Player('player')
    dealer = Player('dealer')
    while True:
        playerCard = drawCard()
        player.addCardScore(playerCard)

        dealerCard = drawCard()
        dealer.addCardScore(dealerCard)

This code has a new issue: looking at addCardScore, we see that two branches of the if modify self.score, but it is not immediately obvious that the middle branch (elif value == 'Ace') does the same.  Generally speaking, by rewriting the functions so that most of them simply return values instead of modifying members, it becomes generally easier to reason about when data is modified.  Here's an example version where only one function touches score:

def addCardScore(self, card):
    self.score += self.getCardScore(card)

def getCardScore(self, card):
    value = str(card)
    if value.isdigit():
        return int(value)
    elif value == "Ace":
        if self.playerType == 'player':
            return self.playerAceChoice()
        else:
            return self.dealerAceChoice()
    else:
        return 10

def playerAceChoice(self):
    aceChoice = input("Play ace as 11 or 1? ")
    while not aceChoice.isdigit():
        try:
            aceChoice = input("Play ace as 11 or 1? ")
        except TypeError:
            print("Invalid response.")
    if aceChoice == "11":
        return += 11
    else:
        return += 1

def dealerAceChoice(self):
    return 1 if self.score >= 11 else 11


The time complexity is \$O(NM)\$ where \$N,M\$ are lengths of the strings. Surely is is too much. The solution can be reached in \$O(N+M)\$. In pseudocode:

    build a character histogram from the first string
    build a character histogram from the second string
    for each c in alphabet,
        result += max(hist1[c], hist2[c]) - min(hist1[c], hist2[c])


Optimising single-delimiter string tokenisation

I tried the following change to your function. It does not use strtok. It does the tokenizing in the function itself. I got a little bit of speed up.

void split_line2(string &line, input_record &rec)
{
    int col = 0;
    char *start = &line[0];
    char sep = ','; // Using ',' instead of '\t' for my testing.
    for ( char* iter = start; *iter != '\0'; ++iter )
    {
       if ( *iter == sep )
       {
          *iter = '\0';
          switch(++col)
          {
             case 2 : rec.sequence = start; break;
             case 4 : rec.content = start; break;
             case 9 : rec.position = atoi(start); return;
          }
          start = iter+1;
       }
    }
}

Here's the test program and results from my testing:

#include <iostream>
#include <string>
#include <ctime>
#include <cstring>

using std::string;

struct input_record
{
    string sequence;
    string content;
    unsigned int position;
};

void split_line1(string &line, input_record &rec)
{
    int col = 0;
    char *row = &line[0];
    char *token = strtok(row, ",");
    while (token)
    {
        switch(++col)
        {
            case 2 : rec.sequence = token; break;
            case 4 : rec.content = token; break;
            case 9 : rec.position = atoi(token); return;
        }
        token = strtok(NULL, ",");
    }
}

void split_line2(string &line, input_record &rec)
{
    int col = 0;
    char *start = &line[0];
    char sep = ',';
    for ( char* iter = start; *iter != '\0'; ++iter )
    {
       if ( *iter == sep )
       {
          *iter = '\0';
          switch(++col)
          {
             case 2 : rec.sequence = start; break;
             case 4 : rec.content = start; break;
             case 9 : rec.position = atoi(start); return;
          }
          start = iter+1;
       }
    }
}

void test1(std::string &line, int n)
{
   clock_t start = clock();

   for ( int i = 0; i < n; ++i )
   {
      input_record rec;
      split_line1(line, rec);
   }

   clock_t end = clock();
   std::cout << "Time: " << (end-start)/CLOCKS_PER_SEC << std::endl;
}

void test2(std::string &line, int n)
{
   clock_t start = clock();

   for ( int i = 0; i < n; ++i )
   {
      input_record rec;
      split_line2(line, rec);
   }

   clock_t end = clock();
   std::cout << "Time: " << (end-start)/CLOCKS_PER_SEC << std::endl;
}

int main(int argc, char** argv)
{
   std::string line(argv[1]);
   int n = atoi(argv[2]);
   test1(line, n);
   test2(line, n);
}

Results:

~/Stack-Overflow/cpp>>./test-507 "1,abcd,3,xyz,4,5,6,7,8,9,10,11" 50000000
Time: 3
Time: 2

~/Stack-Overflow/cpp>>./test-507 "1,abcd,3,xyz,4,5,6,7,8,9,10,11" 100000000
Time: 6
Time: 4

~/Stack-Overflow/cpp>>./test-507 "1,abcd,3,xyz,4,5,6,7,8,9,10,11" 200000000
Time: 13
Time: 9

~/Stack-Overflow/cpp>>./test-507 "1,abcd,3,xyz,4,5,6,7,8,9,10,11" 400000000
Time: 26
Time: 18

Update

If I change the struct from containing std::string to char*, there is substantial savings.

struct input_record
{
    char* sequence;
    char* content;
    unsigned int position;
};

~/Stack-Overflow/cpp>>./test-507 "1,abcd,3,xyz,4,5,6,7,8,9,10,11" 400000000
Time: 16
Time: 8

If that is an option, that will be save you a bunch of time.


Very cool ideal.

Variable Declaration

Variables should be declared at the top of the subroutine. Variables should also be instantiated following the variable declarations when it makes sense to do so.  Separating variable declaration and instantiation from the body of the subroutine improves readability and allows you to better focus on the "Business Logic".

Names, Name, Name2

Naming is an essential skill that you need to develop to write good code.

Compare the following

Sheet1.ListObjects("Names") or Sheet1.ListObjects("Names") : Sheet1.ListObjects("SecretSantaTable")
Name column: Santas column
Name2 column: Children column

Random Stuff

The two lines of ↓code below↓ both target the same range

  Set namesRange = Intersect(.DataBodyRange, .DataBodyRange.Columns(1))
  Set namesRange = .ListColumns("Names").DataBodyRange

Why use a WorksheetFunction when you can use a VBA function?

  selectedName = hat.Keys(Application.WorksheetFunction.RandBetween(0, hat.Count - 1))
  selectedName = hat.Keys(Int(Rnd * hat.Count))

I would use an ArrayList instead of a Dictionary because you don't need Key/Value pairs.

Here is how I would do it. But it's still not quite right...I'll be back!

Public Sub Refactored_GenerateSecretSantaPairs()
    Dim key As Variant
    Dim n As Long, x As Long
    Dim tbl As ListObject, source As Range
    Dim Santas As Object, Children As Object
    Set tbl = Sheet1.ListObjects("SecretSantaTable")
    Set Santas = CreateObject("System.Collections.ArrayList")
    Set source = tbl.ListColumns("Santas").DataBodyRange

    If source Is Nothing Then Exit Sub
    'Remove Duplicates and Reset Source Range
    source.RemoveDuplicates (1)
    Set source = tbl.ListColumns("Santas").DataBodyRange

    For Each key In source.Value
        Santas.Add key
    Next

    Set Children = Santas.Clone

    For x = 0 To Santas.Count - 1
        Do
            n = Int(Rnd * Children.Count)
            key = Children(n)
        Loop Until key <> Santas(x) Or Children.Count = 1

        If Children.Count = 1 And Santas(x) = key Then
            key = Santas(x - 1)
            Santas(x) = Santas(x - 1)
        End If

        Santas(x) = key
        Children.Remove key
    Next

    tbl.ListColumns("Children").DataBodyRange.Value = Application.Transpose(Santas.ToArray)

End Sub

I recommend that you further simplify the Macro, reducing it to 3 lines of code:

Public Sub GenerateSecretSantaPairs()
    Sheet1.ListObjects("Names").ListColumns("Name2").DataBodyRange.Value = "Thomas Inzina"
End Sub


The Rust compiler will probably inline the code, and generate the exact same code in both situations. So there isn't a performance issue.

However, I think there is a better way to write it:

if let Some((x,y)) = match key.code {
   KeyCode::Left => Some((-1, 0)),
   KeyCode::Right => Some((1, 0)),
   KeyCode::Up => Some((0, -1)),
   KeyCode::Down => Some((0, 1)),
   _ => None
} {
   self.map.move_object_by(PLAYER, x, y);
}


I don't see any simple way to generalize your if statements, since they result in very different actions. You might be able to push that complexity into the widgetType instead, if that code is under your control, but it won't reduce the total amount of code.

What concerns me, though, is the length of the parameter list: 10 parameters, of which 9 are mandatory.  The caller is certainly going to look ugly.  A quick improvement might be to accept keyword arguments.  A deeper analysis might reveal that those parameters should belong in an object instead.


Overview
This isn't OOP. To me, object-oriented programming requires thinking about your programs in terms of classes, their responsibilities, their attributes, and behaviours. This means:

Information hiding
Encapsulation
Polymorphism
Collaboration

Config Class
Dearth of source code comments aside, let's look at the Config class. Here are some questions about the configuration options:

What are the options?
What do each of the options do?
How do the options affect the application?
How are the options communicated to the end user?

In this case, the Config "class" as written is nothing more than a functional structure (i.e., it is a dynamic array) wrapped in the syntax of a PHP class. A class, by definition, allows instances to have state and behaviour. The Config class has no discernible behaviour. To give it behaviour, we'd have to contemplate the purpose of the class: its raison d'être.
The name "Config" indicates that the class is responsible for some kind of configuration. (Note: I absolutely abhor abbreviations.) I would further imagine that the configuration is specifically for the CMS application. So I would have named the class CMSConfiguration, which inherits from a more generic Configuration class. Let's look at that generic class.
What can an application configuration class do? I imagine a general configuration class can do the following:

Load options (from a stream, a file, command line switches)
Save options (to maintain current state, or save preferences)
Answer whether an option is set
Answer whether an option is equal to a given value
Export help for the options in an display-device-neutral markup language

That's its behaviour. The single responsibility is clear: the Configuration class loads and queries the state of configuration options. The implementation might resemble:
<?php
/**
 * Responsible for loading and saving configuraiton options.
 */
class Configuration {
  /**
   * Loads the configuration options from application's database connection.
   */
  public function load() {
    Database database = Database::getInstance();
    $result = database->call( "get_configuration_options" );

    // Set the configuration options using the result set.
  }

  /** Saves the current state of the configuration options. */
  public function save() {
  }

  /**
   * Returns true to indicate that the option with the given name is set.
   *
   * @param $option The name of the option to check.
   * @return true The option has a value that is not false.
   */
  public function isOptionSet( $option ) {
    return $this->getOption( $option );
  }

  /** ... */
  public function isOptionEqual( $option, $value ) {
    return $this->getOption( $option ) === $value;
  }

  /** Writes the help for all the options as an XML document. */
  public function exportHelp() {
    foreach( $this->getOptions() as $option ) {
      // ...
    }
  }
}
?>

There seems to be a trend of not declaring attributes, but using magical __set and __get functions combined with dynamic arrays. This will lead to unmaintainable code. If the variables that are used by a class are not defined in a single location, how do you expect anyone else to understand how the code works?
You could, for example, have ClassA and ClassB. What is stopping ClassB from using ClassA as its container for attribute values? Nothing. And that's a terrible, terrible thing, as it completely violates both information hiding and encapsulation.
SQL Class
Judging by its name, the SQL Class seems to be some kind of holder for SQL statements? This will directly violate encapsulation again, as the class that needs to use the SQL will have to call the SQL class to get it. The SQL class should know nothing about the SQL that other classes need to perform.
I actually go a bit further than this. I don't like exposing SQL in my applications at all. SQL changes a lot over the lifetime of a project. When you have many different fingers all creating their own SQL statements, you wind up with a mess: duplicate code, inefficient queries, a burdened query cache, brittle code that will break anytime a table changes, and no clean way to unit test the queries.
The problem, in my mind, is that there is no contract prototype between a CRUD (Create, Read, Update, or Delete) statement and the calling code. This means that the two cannot easily vary independently.
To resolve this, I move the SQL code into stored procedures and stored functions (collectively stored routines). Some people will despise this approach, others will laud it. I prefer it because it means I can create a contract between the stored routine and the underlying code. (It also means that if I wanted to switch from PHP to another language, there's less code to change.)
Once all the SQL code is written in stored routines, it becomes trivial to write a generic database class that can call those routines with arbitrary parameters.
<?php
use PDO;
use PDOException;

/**
 * Used for interacting with the database. Usage:
 * <pre>
 * $db = Database::get();
 * $db->call( ... );
 * </pre>
 */
class Database {
  private static $instance;
  private $dataStore;

  /**
   * Sets the connection that this class uses for database transactions.
   */
  public function __construct() {
    global $dbhost;
    global $dbname;
    global $dbuser;
    global $dbpass;

    try {
      $this->setDataStore(
        new PDO( "pgsql:dbname=$dbname;host=$dbhost", $dbuser, $dbpass ) );
    }
    catch( PDOException $ex ) {
      $this->log( $ex->getMessage() );
    }
  }

  /**
   * Returns the singleton database instance.
   */
  public function get() {
    if( self::$instance === null ) {
      self::$instance = new Database();
    }

    return self::$instance;
  }

  /**
   * Call a database function and return the results. If there are
   * multiple columns to return, then the value for $params must contain
   * a comma; otherwise, without a comma, the value for $params is used
   * as the return column name. For example:
   *
   *- SELECT $params FROM $proc( ?, ? ); -- with comma
   *- SELECT $proc( ?, ? ) AS $params; -- without comma
   *- SELECT $proc( ?, ? ); -- empty
   *
   * @param $proc Name of the function or stored procedure to call.
   * @param $params Name of parameters to use as return columns.
   */
  public function call( $proc, $params = "" ) {
    $args = array();
    $count = 0;
    $placeholders = "";

    // Key is zero-based (e.g., $proc = 0, $params = 1).
    foreach( func_get_args() as $key => $parameter ) {
      // Skip the $proc and $params arguments to this method.
      if( $key < 2 ) continue;

      $count++;
      $placeholders = empty( $placeholders ) ? "?" : "$placeholders,?";
      array_push( $args, $parameter );
    }

    $sql = "";

    if( empty( $params ) ) {
      // If there are no parameters, then just make a call.
      $sql = "SELECT $proc( $placeholders )";
    }
    else if( strpos( $params, "," ) !== false ) {
      // If there is a comma, select the column names.
      $sql = "SELECT $params FROM $proc( $placeholders )";
    }
    else {
      // Otherwise, select the result into the given column name.
      $sql = "SELECT $proc( $placeholders ) AS $params";
    }

    $db = $this->getDataStore();
    $statement = $db->prepare( $sql );

    for( $i = 1; $i <= $count; $i++ ) {
      $statement->bindParam( $i, $args[$i - 1] );
    }

    try {
      $result = null;

      if( $statement->execute() === true ) {
        $result = $statement->fetchAll( PDO::FETCH_ASSOC );
        $this->decodeArray( $result );
      }
      else {
        // \todo Send an e-mail.
        $info = $statement->errorInfo();
        $this->log( "SQL failed: $sql" );
        $this->log( "Error: ". $info[2] );
      }
    }
    catch( PDOException $ex ) {
      // \todo Send an e-mail.
      $this->log( $ex->getMessage() );
    }

    return $result;
  }

  /**
   * Converts an array of numbers into an array suitable for usage with
   * PostgreSQL.
   *
   * @param $array An array of integers.
   */
  public function arrayToString( $array ) {
    return "{" . implode( ",", $array ) . "}";
  }

  /**
   * Recursive method to decode a UTF8-encoded array.
   *
   * @param $array - The array to decode.
   * @param $key - Name of the function to call.
   */
  private function decodeArray( &$array ) {
    if( is_array( $array ) ) {
      array_map( array( $this, "decodeArray" ), $array );
    }
    else {
      $array = utf8_decode( $array );
    }
  }

  private function getDataStore() {
    return $this->dataStore;
  }

  private function setDataStore( $dataStore ) {
    $dataStore->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $this->dataStore = $dataStore;
  }
}

The code is used in one of three ways:
// Returns a boolean value
$result = $db->call( "is_existing_cookie", "existing", $cookie_value );

// Calls a stored procedure
$this->call( "procedure_insert", "", $this->getId(), $action_name_id );

// Returns a tuple pair of ids and labels
return $this->call( "get_list", "id, label", $this->getId() );

The Database class has behaviours (make a database call) and attributes (the singleton instance). There is certainly room for improvement, but this should give you more ideas to ponder.
All of the text is great, but the example code... That database class violates just about every OOP principle there is. Importing global variables? Constructing a PDO instance in the constructor? A singleton? What? Why? Globals have no place in modern PHP, nor do singletons. Dependency injection is the way to go here. And suppressing exceptions? Nooooo. The consuming code needs to know something exceptional happened. Logging is not enough (and I would argue that either an extension, wrapper or consumer of the class should be responsible for logging).
Response to Corbin

That database class violates just about every OOP principle there is.

The Database class violates neither encapsulation nor information hiding. This is apparent from its intended usage:
return $this->call( "get_list", "id, label", $this->getId() );

The underlying implementation (of the call method) can change without any impact to the client code. No information about the internal workings of the Database class is being exposed.

Importing global variables?

True, this is poor form. However, it can be mitigated by using a configuration file, or dependency injection. Again, the calling classes will not need to change.

Constructing a PDO instance in the constructor? A singleton? What? Why?
Globals have no place in modern PHP, nor do singletons.

True, globals are poor form. The Singleton pattern was employed for its simplicity. In my application, every single class uses the Database, but most of the subclasses do not use it directly.
This code is also fairly temporary, as the application will be rewritten using Haxe.

And suppressing exceptions? Nooooo.

Depends on if the calling code needs them. In my case, the calling code never needs to care about the error. Users don't care if there was a database error. There is no point bubbling an error message to the user, as they'll never understand "ORA-10168: INSERT violates duplicate key" or whatever. Ergo, the message is suppressed and the application must handle an empty result set.
In this particular case, all empty result sets yield a relatively empty XML document, which is rendered using XSLT, to produce a web page for the user. There is little difference between the following:
try {
  $result = $this->call( ... );
}
catch( Exception $e ) {
  $result = $this->getErrorXML();
}

And this:
$result = $this->call( ... );

if( !isset( $result ) ) {
  $result = $this->getErrorXML();
}

They are functionally equivalent, although the exception handling allows slightly more flexibility for eliminating duplicate code (by allowing the exception to bubble naturally and get handled in a single location).
As I mentioned, there are a number of minor issues with the Database class, however it does not violate either encapsulation or information hiding.
From a big picture perspective, I'd rather see:
return $this->call( "get_list", "id, label", $this->getId() );

Sprinkled throughout the codebase, than hundreds of SELECT statements married to PDO calls.


Make two MySQL statements & loop quicker

Personally I would go with a join even if they are currently the same speed.

This way your code automatically gets upgraded when the DB gets upgraded (ie when a new index is added to the DB or they decide to partition the DB by latitude/longitude). In this situation if you are using a Join your code will automatically benefit from any improvement.


Fluid tag for displaying GitHub Gists with noscript tags in a Jekyll post

A couple of mostly minor notes and improvements:

return "" unless @text =~ /([\d]*) (.*)/
gist, file = $1.strip, $2.strip

I generally try to avoid magic variables where ever possible. Using match and the resulting MatchData object tends to be less error prone.

code       = code.gsub "<", "&lt;"

Is there a reason you only escape < characters? Unless I'm missing something, it seems preferable to use CGI.escapeHTML instead.

return string

It seems inconsistent to me that in some methods you have a return statement on the last line and in others you do not. I would always leave out the return statement on the last line as it is unnecessary.

return nil if @cache == false

It is pretty unidiomatic to use == with boolean literals - usually one would just negate the boolean instead of comparing to false. if !@cache or better unless @cache will read more natural to most people than if @cache == false.

File.new(file).read

You should never use File.new without storing its return value somewhere and then later calling close on it. As a matter of fact in most cases you should not use File.new at all, but rather File.open with a block, which closes the file automatically when the block's end is reached. The way you're doing it the file handle will remain open until the File object is garbage collected, which may be a while. This is a bad practice and can lead to subtle problems.

However in this case you don't even need File.open as there is already a method which does exactly what you need: File.read(file).

gist.gsub! /[^a-zA-Z0-9\-_\.]/, ''

You don't need to escape . as it has no special meaning inside brackets.

cache_gist(gist, file, data) unless @cache == false

This would really be a lot more readable without the explicit comparison and the double negation:

cache_gist(gist, file, data) if @cache


Some comments on your code.  In no particular order:

Blocks of text, should be blocks of text

Instead of a bunch of print statements, consider using one block of text, and a loop like:

  def print_help_text():
      help_text = """
          The processor.py utility is designed to take a single argument, the path
          to a NASA EarthData Global Fire Emissions Database GFED4.1s_yyyy.hdf5 file.
          Example - $ ./preprocess.py some/directory/GFED4.1s_2015.hdf5

          If a valid file path is passed to the utility it should output individual JSO
          files for each month, that contain data in the format required to train the
          emissions predictor."

          By default the new files will be ouput to the same directory that contains
          the script. Alternatively, you can provide a second argument with a path to
          another directory for the output files to be placed in.
      """
      for line in help_text.split()[1:-1]:
          print(line.strip())

in is handy

I would prefer to see this:

args = len(arguements)
if (args == 2 or args == 3) and arguements[1] != "--help":
    ...

as this:

if len(arguements) in (2, 3) and arguements[1] != "--help":
     ...

This construct makes it more obvious that you are looking for the length to be one of a specific list of values.

@staticmethod

Your Validator class has a bunch of staticmethods, but they are not declared as such. This is not terribly pythonic.  I suggest you investigate: https://docs.python.org/3/library/functions.html#staticmethod


JavaScript singleton with methods and properties

A singleton is an object which is the only instance of its type. Therefore, it makes most sense to define all non-function properties and methods directly on that singleton:

var singleton = {
    prop1: ...,
    prop2: ...,
    method1: function () { ... },
    method2: function () { ... }
};

Extending the singleton is easy:

singleton.prop3 = ...;
singleton.method3 = ...;


The problem statement indicates that path separators should be taken into account when computing the length.  You might add a test case to test for this case either by crafting a particular input or by returning the longest path along with longest count that you can verify.

Some of the code could be made more concise.

filename = path.split('\t')[-1]    # last of list, assumes no tabs in filenames
depth = len(path) - len(filename)  # yields number of tabs

Rather than repeatedly computing the sum of the paths, you could create a cumulative_sum.

cumulative_len = cumulative_len[:depth]
if depth > 0:
    # last element contains sum of entire path to depth
    # +1 to account for the preceding path separator
    cumulative_len.append(cumulative_len[-1] + len(filename) + 1)
else:
    # the problem statement does not include an initial path separator
    cumulative_len.append(len(filename))

Rather than joining the path for intermediate maximums that will be discarded, just store the list of path elements and join on final delivery.

You might consider asserting on the desired results so you get clearer feedback of failure.

def check(input, expected):
    longest_path = find_longest_path(input)
    assert input == expected, "Expected {} but got {}".format(expected, longest_path)
    print(longest_path)

if __name__ == "__main__":
    check("dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext",
          "dir/subdir2/subsubdir2/file2.ext")

    check("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext",
          "dir/subdir2/file.ext")


Should I call a method (i.e. size()) multiple times or store it (if I know the value will not change)

Calling size() twice, like you are, almost definitely get's optimized out in any modern compiler. How you are doing it is perfectly fine. You could also do it with std::max_element...

auto max = std::max_element(ways.begin(), ways.end(),
    [](const std::vector<void*>& left, const std::vector<void*>& right)
    {
        return left.size() < right.size();
    })->size();

Or maybe you write the lambda as a functor instead and a little more generic, like:

struct ContainerSizeComparer
{
    template<typename Container>
    bool operator()(const Container& left, const Container& right)
    {
        return left.size() < right.size();
    }
};

auto max = std::max_element(ways.begin(), ways.end(), ContainerSizeComparer())->size();

This is one of those interesting times when hand rolling the loop is actually more readable and as small as using standard algorithms though. Unless you have a reason to write ContainerSizeComparer and use it in multiple places I would personally stick with what you were doing.


Get most recent modified time of a folder recursively with PHP

Can you please correct me if I am doing anything wrong.

It depends on whether you care for the deleted files or not. If you do, you should also check the modification time for the directory itself, not only files in it.

The code itself could be also improved:

you can remove the duplicated condition
which in turn, can be substituted with max() function.
also you can utilize the glob() function that can save you that boring $file == '..' condition, as well as other unnecessary code.

So in the end the code could be

function get_m_time_dir ($directory)
{
    $last_modified_time = 0;
    $dirmtime = filemtime ($directory);
    foreach (glob("$directory/*") as $file)
    {
        if (is_file ($file))
        {
            $filemtime = filemtime ($file);
        } else {
            $filemtime = get_m_time_dir ($file);
        }
        $last_modified_time = max($filemtime, $dirmtime, $last_modified_time);
    }
    return $last_modified_time;
}


Simplifying if else statements in Python code snippet

Recursion here is going to be your friend:

def recurse_json(property, variant):
    # This is our exit condition
    if isinstance(property, dict):
        json_key_getter(property, variant)
    else:
        # Otherwise, WE NEED TO GO DEEPER!
        for item in property:
            recurse_json(item, variant)

Now all you have to do is call this function in your for loop:

# Use `isinstance` to check for types as it takes inheritance into account.
if isinstance(variant_list, dict):
    style_color_if(variant_list[style_colors_main], variant_list)
else:
    for variant in variant_list:
        try:
            recurse_json(variant[style_colors_main], variant)
        except KeyError:
            print('Property had no "{}" property'.format(style_color_main))

I had to put in the try-except blocks because in your example the first element of the list did not have the productStyleColors property (which is what I assume is in style_color_main).

The use of isinstance isn't ideal because we would typically like to use try-excepts blocks. However, because I don't know if your other functions throw any exceptions, I chose to use (as the link says) the 'less-bad option'.


Possible letter combinations of a dial pad in linear time using a recursive approach

What is your purpose in writing this code?

If the entire task is enumerate the combinations, it's not possible to do less work than going through all combinations. An \$ n \$ digit number will have between \$ 3^n \$ and \$ 4^n \$ possible combinations, depending on how many of those digits are 7s and 9s.

On the other hand, additional knowledge about the purpose of the function could guide the search for something more useful. For example, I imagine this function might then be the input to a filter which narrows them down it to dictionary words. In that case, you could preemptively stop searching if there are no words in the dictionary that start with a given prefix. (The trie data structure is a classic option for keeping track of this sort of thing.)

Assorted other comments on the code

Because what you are passing is fundamentally a sequence of keypresses rather than a number per se, consider having remp take a string instead of a number.
Set is probably unnecessary expense and complexity if all you want is to enumerate a few characters. Whatever data type you use, consider sharing an object for all usages of a given digit's letters.
all_possable isn't a particularly descriptive name for that function. I also have no idea what remp means.
Although it doesn't affect the code, the correct spelling is possible.


Difference between API time and server time

I would not parse the dt_txt field. You would have to make too many assumptions including the format of the date (Is it yyyy-mm-dd or the American mm-dd-yyyy) and the time zone. Instead create a date object from the dt field:

var apiHours = (new Date(weatherList[0].dt * 1000)).getHours();

All those operations to add 0 and do hours to string to integer conversions are redundant. The following should be sufficient:

let weatherList  = parsed.list;
let apiHours     = (new Date(weatherList[0].dt * 1000).getHours();
let serverHours  = (new Date()).getHours();
let indexToUse   = (apiHours - serverHours < 2) ? 1 : 0;

Update 1

David is right, I had missed that point. A better solution would be:

// All values in milliseconds
const oneHour   = 60 * 60 * 1000;
let  apiTime    = weatherList[0].dt * 1000;
let  serverTime = (new Date()).valueOf();
let  indexToUse = (apiTime - serverTime < 2 * oneHour) ? 1 : 0;