What you want to do is simply

public static double distanceBySounding(double seconds, boolean isEcho) {
    return (isEcho ? 0.5 : 1.0) * seconds * 1100 /* ft. per second */;
}

The question is, how should this function be expressed in an object-oriented way?  It's pretty safe to say that this…

SoundSpeed soundSpeed = new SoundSpeed();
soundSpeed.timeInSeconds = 35.079;
soundSpeed.isEcho = true;
System.out.println(soundSpeed.getResult());

… is an unpalatable interface.  Manipulating public instance variables like that is not only cumbersome, it is an unsound practice (pardon the pun).  Given a choice between the two options above, I would much prefer the simpler function to the contorted object.  And that's fine.  Java allows you to write code that doesn't fully conform to OOP.

What if you wanted an object-oriented design?  The key to object-oriented design is that you want to model objects.  That means that you have to find plausible objects to model — the more realistic, the better.  What's a SoundSpeedCalc?  I don't know; you can't buy one.  But you can sure buy a sonar!  It makes sense to instantiate a Sonar with its configuration parameters (the sound medium and its active/passive mode), then you can start "aiming" it at stuff by calling .distance().

public class Sonar {
    public enum Medium {
        AIR(1100);

        private final double ftPerSec;

        Medium(double ftPerSec) {
            this.ftPerSec = ftPerSec;
        }
    }

    private final Medium medium;
    private final boolean isEcho;

    public Sonar(Medium medium, boolean isEcho) {
        this.medium = medium;
        this.isEcho = isEcho;
    }

    public double distance(double seconds) {
        return medium.ftPerSec * seconds / (isEcho ? 2 : 1);
    }
}

Here's how you can use it effectively:

public static void main(String[] args) {
    double seconds = 35.079;
    boolean isEcho = true;

    Sonar sonar = new Sonar(Sonar.Medium.AIR, isEcho);
    String verb = isEcho ? "echo" : "travel";
    System.out.printf("The sound took %s seconds to %s and thus the distance is %s feet.\n",
                      seconds, verb, sonar.distance(seconds));
}

Note the use of System.out.printf() as a nicer alternative to string concatenation.  Also, I've used conditional expressions — it's a perfect way to assign one of two values depending on a boolean switch.


Simple/Naive Implementation of Identity and Maybe Monad in Elixir

I think you're sort of missing the point with this code - the difference between different kinds of monads (Maybe vs. List vs. Identity, etc.) is in the different implementations of return and bind. I think a good starting place might be reading through a library that implements monads in elixir, like monad. Looking into that you can see that for example Maybe is implemented like this (simplifying):

def return(x), do: {:just, x}

def bind({:just, x}, f), do: f.(x)
def bind(:nothing, _), do: :nothing

def fail(_), do: :nothing

While  for example Error (the second-simplest I think) is implemented like this:

def return(x), do: {:ok, x}

def bind(e = {:error, _}, _), do: e
def bind({:ok, x}, f), do: f.(x)

def fail(msg), do: {:error, msg}

The difference between the two being that in one case you only get information that there is no result (:nothing) while in the other you either get a result or some information on the error (represented by {:error, _}). Also note that both have additional helper functions to for example extract the result (presumably at the end of the computation).


Find the cheapest order placed out of all of the stores visited - follow-up #2

I see some things that may help you further improve your program.

Eliminate arrays by carefully rethinking the problem

At the end of the program, all that is needed is the cheapest_order and the cheapest_shop.  All of the arrays could be eliminated by simply keeping, as each shop total is calculated, the current cheapest order.  There is no need to keep any data from a shop that is not cheapest, nor any reason to store the ingredient costs in an array.

Fix the bugs

If the scanf fails, as it does if the user inputs a letter instead of a number, the program acts as if the number 1 had been entered, and the user gets no chance to correct it.  Also, when I entered -1 for the number of shops to be visited, I got this result:

How many shops will be visited? -1
The cheapest  order  was  at  shop #1, and the total cost of the order was $81082112.00

Test your code thoroughly

One way to test the code is to simply try it multiple times.  A better way is to automate the process by writing a test driver.  There are many ways to do this; one simple way is to manually create a few files with test input and then feed them to the program.

Don't use floating point for money

There is a problem using floating point (that is, float or double types) to represent money values.  See this question for a thorough explanation for why that's the case.

An alternative is to keep a number of cents as an integer value internally.  For more depth about floating point issues, I'd recommend the excellent article "What every computer scientist should know about floating-point arithmetic" by David Goldberg.


WIFSIGNALED / WIFSTOPPED
If you get into the "BAD" case, you may want to check whether WIFSIGNALED is true or WIFSTOPPED is true.  WIFSIGNALED tells you if the program terminated with a signal (such as segv).  WIFSTOPPED tells you if the program is currently stopped (but not terminated).
If your child process can never be stopped, then you can assume that it terminated abnormally and not bother checking those macros.  In your particular example, your child will either segfault or exit right away, so it's unlikely that someone would be able to kill -STOP your process before it crashed.


If you are compiling your regular expression there is no improvement if you do this inside your method, move your regular expression declaration outside the method so it will not be compile it again every time you call 'email_check'

In the line where you do length = mail.split('@'), I think the best name is parts. Just make sure you have some edge cases acknowledge.

Do the split just once, what about someone send "bill@@hotmail.com"? your code will mark this as correct.

local_part, domain = mail.split('@', 1)
if len(local_part) <= 128 and len(domain) <= 256:
     print 'Error'

Or even better add this rule to the regular expression, like ^[a-z]{3,128}$ where it reads any characters from a to z, at least three times found and no more than 128 times.

Maybe there are other things, but this are the first things that come to my mind.

Keep coding :)


Using reverse is generally a bad idea for performance — especially since Haskell lists can be infinite!  Observe:

*Main> let triangularNumbers = scanl (+) 0 [1, 2 ..]
*Main> let triangularNumbers2 = scanl2 (+) 0 [1, 2 ..]
*Main> take 5 triangularNumbers
[0,1,3,6,10]
*Main> take 5 triangularNumbers2          -- hangs forever


Some things that stuck out to me.  FWIW.

//NOTE: for me, this validator can only describe what went wrong without
//        giving you a specific way to handle each kind of thing that happened.
//        e.g.  NULL (translates to) NotFound
//        e.g.  AddError(<string>) can only be interpreted as "other" errors since they are just descriptions of the error and not the type
public IValidator<Thing> RemoveThing(int id)
{
    var thing = _repository.Get(id);
    // NOTE: this result has to be interpreted by the caller
    if (thing == null)
        return null;

    var validator = new ThingValidator(thing);
    var isValid = validator.Validate(new StatusSpecification("UnIndexed"));

    if (isValid)
    {
        thing.Delete();
        _repository.Save(thing);
    }
    else
    {
        // NOTE: since this message comes from outside of the class, it
        //         it not the nearest source of truth about what went wrong.
        //         i think this message should come from the class itself.
        //          this message is also typed twice in your code.
        validator.AddError("Only an UnIndexed thing may be deleted.");
    }

    return validator;
}

public JsonResult DeleteThing(int thingId)
{
    var command = _service.RemoveThing(thingId);

    // NOTE: this could be set up so that you don't have to interpret null as "not found"
    if (command == null)
        return Json(HttpStatusCode.NotFound);

    if (command.IsValid())
    {
        return Json(HttpStatusCode.OK);
    }
    else
    {
        return Json(command.ListErrors());
    }
}

OPTION #1

short and to the point.
idiomatic solution
very little logic.
explicitly typed errors for try/catch handling

THROW ALL THE EXCEPTIONS!!!

public void Delete()
{
    if (Status == "UnIndexed")
        Deleted = true;
    else
        throw new UnIndexedException();
}

public void RemoveThing(int id)
{
    var thing = _repository.Get(id);
    if (thing == null)
        throw new ThingNotFoundException(id);

    thing.Delete();
    _repository.Save(thing);
}

// Controller
public JsonResult DeleteThing(int thingId)
{
    try
    {
        _service.RemoveThing(thingId);
        return Json(HttpStatusCode.OK);
    }
    catch (ThingNotFoundException e)
    {
        return Json(HttpStatusCode.NotFound);
    }
    catch (Exception e)
    {
        throw;
    }
}

OPTION #2

less short but still to the point.
inching towards a more declarative solution. (which is good)
not that much logic.
explicitly stated errors for if/then handling

NEVER THROW EXCEPTIONS!!!

class RemoveThingResult
{
    private RemoveThingResult(bool isOk, boo isNotFound, bool isUnIndexed)
    {
        IsOk = isOk; IsNotFound = isNotFound; IsUnIndexed = isUnIndexed;
    }

    public readonly bool IsOk;
    public readonly bool IsNotFound;
    public readonly bool IsUnIndexed;

    public static RemoveThingResult Ok()
    {
        return new RemoveThingResult(true, false, false);
    }
    public static RemoveThingResult NotFound()
    {
        return new RemoveThingResult(false, true, false);
    }
    public static RemoveThingResult UnIndexed()
    {
        return new RemoveThingResult(false, false, true);
    }
}

// Service Layer
public RemoveThingResult RemoveThing(int id)
{
    var thing = _repository.Get(id);

    if (thing == null)
        return RemoveThingResult.NoFound();

    var validator = new ThingValidator(thing);
    if (!validator.Validate(new StatusSpecification("UnIndexed")))
        return RemoveThingResult.UnIndexed();

    thing.Delete();
    _repository.Save(thing);

    return RemoveThingResult.Ok();
}

// Controller
public JsonResult DeleteThing(int thingId)
{
    var command = _service.RemoveThing(thingId);

    if (command.IsNotFound)
        return Json(HttpStatusCode.NotFound);

    if (command.IsOk)
        return Json(HttpStatusCode.OK);

    if (command.IsUnIndexed)
        return Json("Only an UnIndexed thing may be deleted.");

}


Please give clear meaningful name. Your class name is Successor... now who's successor? yours? king Luthar's? who's? See the concern. I think BinarySearchTree is the apt. name for the class.
In makeBinarySearchTree you are creating a Binary Tree, so someone seeing your code will think it as a factory method, so better make it that way.
You can make your class generic but that's not a big deal for now but in future keep this in head and try to find always general solution for any given problem.
Someone using your getSucessor method(should be getSuccessor) will always get the inorder-successor. Now what if someday someone want to find preorder-successor or preorder-successor, what will you do then?

Otherwise your code is good and self-documenting.


Framework to drive a small personal site

All the basic parts are here, but there's still room for improvement.

First of all, I wouldn't have the constructor call route and route then call dispatch because it makes the second method less discoverable when the code is being read. Contrast this with:

function __construct() {
    //get the raw url
    $urlRaw = $_SERVER['REQUEST_URI'];

    $route = $this->route($urlRaw); // don't care what $route is exactly
    $this->dispatch($route);
}

Here it is much more obvious what you method you should be looking for. It's true that you, as creator of the code, do not need this -- but others might, and it's a totally free lunch.

Second: this line bakes an application configuration decision inside the router. You don't want to do this, as it's totally reasonable to want to change this configuration most of the time while the router would stay mostly untouched.

$controller =   ((!empty($urlRawParts[0])) ? $urlRawParts[0] : 'Index');

It's much better to make the default controller name part of the application configuration and have the router take it from there, because it's reasonable to want your "home" page to be equivalent to the "/something" url instead of "/index".

The same goes for

$action =       ((!empty($urlRawParts[1])) ? $urlRawParts[1] : 'index');

It would be better if you allowed the controller writer to pick which action is the default:

$action = ((!empty($urlRawParts[1])) ? 'action'.$urlRawParts[1] : 'defaultAction');

But why also rename index to defaultAction and add the "action" prefix to method names? Consider also your dispatch code:

$method = ((method_exists($controller, $action)) ? $action : 'index');

This check with method_exists would allow any url that maps to a public function to be successfully dispatched, even if that function does not map to a "real" action (it can simply be a helper method). That's not really a security issue (you can easily make sensitive functions private) but it's not very consistent: targeting nonExistentAction will get you to the index page, while targeting e.g. helperMethod will show a blank page as helperMethod most likely does not directly produce content.

By demanding that actions are implemented in functions with names starting with "action" you can make sure that this never happens. The default action is a special exception to this rule, as it allows the controller writer to effectively specify which url routes to the default action and what the default action should do at the same time.

Third: It's not consistent to show a 404 for a missing controller but not do that for a missing action and use the default one instead. You should do the same in both cases, and the right choice would be the 404.

Fourth: Parameter handling needs immediate attention.

To begin with, you are sanitizing parameters to an unreasonably restricted set. What if there's a search action somewhere and the user wants to type in a character like * or a non-alphanum string? Clearly parameter sanitization needs to simply be removed.

Apart from that, you are passing GET parameters to the controller action positionally. The positional part is not a dealbreaker by itself (although it would be a dealbreaker in a framework, or if the URL format were configurable), but the GET restriction is a bit ugly. However, this cannot be fixed easily because there's no good way to know where parameters from $_POST should be inserted, or what their order relative to one another should be.

To address this, you need to make the code reflect into the controller method and look for argument names and default values, pull these out from your list of GET parameters and $_POST, place them in an array ordered by the position of each named parameter in the function signature and call the function with that. You should also probably return an HTTP 400 if the action turns out to have a non-optional parameter the value of which was not provided.

All in all not the end of the world, but a speed bump and a non-trivial amount of code.


I don't do much python so I might be wrong but to my understanding, this:

job = job_server.submit(rxx_func, (arg_n,), (), ())

just submits a single job but it doesn't automatically parallelize it. If you want to process the input in parallel you need to submit n jobs each working on 1-nth of the input and then combine the results. I think your parallel execution code should look something like this:

slice_size = len(magn) / ncp;

# submit a job for each chunk
jobs = [job_server.submit(rxx_func, (magn,(i-1)*slice_size, slice_size), (), ()) for i in xrange(ncp)]

# combine the results into one list, requires #import itertools
rxx = list(itertools.chain.from_iterable([job() for job in jobs]))

You will have to change your rxx_func to accept a start index and a count which defines for how many items it is responsible:

def rxx_func(amp, start_index, count):
    N = len(amp)
    rxx = [0]*count

    for m in xrange(start_index, start_index + count - 1):
        for n in xrange(N-m):
            rxx[m]+=amp[n]*amp[n+m]
    return rxx

I'm sure there is plenty which can be optimized in the above.


Loop combinations of byte for Poker simulator

private IEnumerable<byte> NextSevenA(byte Skip1, byte Skip2)

Method arguments should be named using camelCase casing. In this way you wouldn't mistake them for being properties.

If you need the PascalCase casing of the arguments to distinguish them from your local variables, you should either change their names or use this for use with class level variables.
Omitting braces although they might be optional, like for single lined if statements, can lead to serious bugs which are hard to find. I would like to encourage you to always use them. This not only makes your code less error prone but also more readable because it looks more structured.
throwing an ArgumentOutOfRangeException is a good thing but the error message should be more expressive. "51 0" isn't telling really much.
You should validate

    if (Skip1 != skip1 || Skip2 != skip2)
        throw new ArgumentException("skippy");

earlier to make it clear where the validation happens.
by extracting the generation of the byte values of deck50seven to a separate method returning an IEnumerable<byte> the method could be shorter.

private static IEnumerable<byte> GetByteRange(byte start, byte end)
{
    for (byte b = start; b < end; b++)
    {
        yield return b;
    }
}

After introducing a private const int MaxCardsInDeck = 52 this could be called like

deck50seven = GetByteRange(0, MaxCardsInDeck).Except(new byte[] { Skip1, Skip2 }).ToList();

By changing the way you handle nextSevenLastStart you could get rid of the else part at the end. I say could because I don't know if you somewhere else using that variable. The way I would do this is like so

nextSevenLastStart += 7;
if (nextSevenLastStart >= 49)
{
    //shuffling now
}

If this isn't an option you should consider to invert the condition if (nextSevenLastStart >= 42) and return early which saves you one level of indentation.
The shuffeling of the deck50seven should be extracted to a separate method like so

private static Random rand = new Random();
private static void Shuffle(List<byte> items, int upperBound=42,int lowerBound=1)
{
    for (int i = upperBound; i >= lowerBound; i--)
    {
        int j = rand.Next(i + 1);
        if (j != i)
        {
            byte currentValue = items[i];
            items[i] = items[j];
            items[j] = currentValue;
        }
    }
}

You have a lot of magic numbers in your code of which I am unsure what they are about so I will leave them untouched. You should extract them to meaningful constants.

Implementing the mentioned points apart from the exception messages, because I don't have enough context, will lead to

private IEnumerable<byte> NextSevenA(byte skip1, byte skip2)
{
    if (skip1 == skip2)
    {
        throw new ArgumentOutOfRangeException("skip1 == skip2");
    }

    if (skip1 > 51 || skip2 > 51 || skip1 < 0 || skip2 < 0)
    {
        throw new ArgumentOutOfRangeException("51 0");
    }

    if (this.skip1.HasValue && (this.skip1 != skip1 || this.skip2 != skip2))
    {
        throw new ArgumentException("skippy");
    }

    if (skip1 == null)
    {
        this.skip1 = skip1;
        this.skip2 = skip2;
        deck50seven = GetByteRange(0, 52).Except(new byte[] { skip1, skip2 }).ToList();
    }

    nextSevenLastStart += 7;

    if (nextSevenLastStart >= 49)
    {
        nextSevenLastStart = 0;
        Shuffle(deck50seven);
    }

    return deck50seven.GetRange(nextSevenLastStart, 7);
}

private IEnumerable<List<byte>> NextSevenAsFiveTwo(List<byte> input)

Using the Count() extension method on a List<T> involves a (soft)cast to an ICollection<T> so it should be faster to just use the Count property.
Because the method is only called by requesting the enumerator you should extract the validation of the Count property to a separate method. IMO this ArgumentOutOfRangeException should be thrown at the moment you call the method.
Instead of the most inner loop and the check for if (k != i && k != j) you can use Enumerable.Range() excepting i and j. This range can be stored in a class level (but static) variable so we can make the method static as well.

Implementing the mentioned points will look like so

private static IEnumerable<List<byte>> NextSevenAsFiveTwo(List<byte> input)
{
    if (input.Count != 7)
    {
        throw new ArgumentOutOfRangeException("input.Count != 7");
    }
    return NextSevenAsFiveTwoIterator(input);
}
private static IEnumerable<int> range = Enumerable.Range(0, 7);
private static IEnumerable<List<byte>> NextSevenAsFiveTwoIterator(List<byte> input)
{
    // 21 ways to take 2 from 7
    // this is going to seem strange but need every combination of 2 to be the last 2

    List<byte> output = new List<byte>();
    for (int i = 0; i <= 5; i++)
    {
        for (int j = (i + 1); j <= 6; j++)
        {
            output.Clear();
            foreach (int k in range.Except(new int[] { i, j }))
            {
                output.Add(input[k]);
            }
            output.Add(input[i]);
            output.Add(input[j]);
            yield return output;
        }
    }
}


Linking the other version of pairwiseSum here Pairwise summation in Haskell
That version is an O(nlogn) algorithm, while this one is linear [ie O(n)]. In fact this version is probably the best you can do in Haskell with lists. It's reminiscient of a fold, which is the natural operation on a list data structure.
The previous version has a bunch of wasted effort as the lists are recursively split. Each time it's split the algorithm has to traverse the whole array. So it's perfectly reasonable that the first version is slower


Dice roll game that generates random number

First, get rid of the arrays RandomNum1 and RandomNum2.
You never use the data you store in them, but doing the storing might lead to out-of-bounds-accesses, as you fail to sanitize the user-input.
Only assume well-formedness of input which is under your control. Test whether scanf succeeds, and whether the result you get is valid.
Try to unify and simplify your conditional code.
Do you know that two string-literals only separated by white-space (including newlines) are fused?
Try to keep to the same style for all your names, I guess variable-names should all be lower pascal-case.
Adding a single whitespace around all binary operators, and after a comma, helps readability.


Is there a better way to make sure a variable is initialized when using blocks?

Create and run operation using

NSOperation *op = [NSBlockOperation ... your block...];
[[NSOperationQueue new] addOperation: op];

and instead of using a runloop, wait for the result:

[op waitUntilFinished];


Dependency Injection With Unity in MVC 5 without repository and unit of work

Naming

Based on the naming guidelines methods should be named using PascalCasing casing.
addNewCategory -> AddNewCategory
Based on the same guideline classes should be named using PascalCasing casing.
dataBaseContext -> DataBaseContext and therefor IdataBaseContext -> IDataBaseContext

General

You are injecting an interface in the constructor, but then you cast it to the concrete implementation. If you don't need any methods/properties of the concrete implementation, you should stick to the interface.

private IDataBaseContext _context;

public ProductCatagoryController(IDataBaseContext context)
{
    this._context = context;
}

This will make the ProductCatagoryController class independent of the concrete DatabaseContext object.

For the case that ModelState.IsValid is false, how will the consumer of this method see, that no category is added ?
If an exception occurs, the consumer of this method will only see it, if the log file is parsed. Returning an Exception view would do better.


Traversing a Binary Search Tree in Swift

Your generate() method works correctly, as far as I can see. But it
creates an AnyGenerator for every node in the tree, i.e. it uses
more memory than necessary. Each call to the next() method of the generator
then traverses down the next() methods along the left or right subtrees,
which makes it slow.

An iterative approach using a stack instead of "nested generators"
seems to be faster. Here is a possible implementation of
the iterativeInorder algorithm described in Wikipedia: Tree traversal:

func generate() -> AnyGenerator<(Key, Value)> {

    var node : BinarySearchTree? = self
    var stack : [BinarySearchTree] = []

    return AnyGenerator {
        // Traverse from current node to the far left, pushing all
        // nodes onto the stack:
        while let node1 = node {
            stack.append(node1)
            node = node1.left
        }
        if !stack.isEmpty {
            // Pop node from stack and return its (key, value),
            // then continue with right subtree.
            let current = stack.removeLast()
            defer { node = current.right }
            return (current.key, current.value)
        } else {
            return nil
        }
    }
}

Note that the size of the stack array is limited by the tree height.

In my test with a tree of 1,000,000 nodes, the traversal is done
in about 0.2 seconds, compared to 3.5 seconds with your original
method (test done in Release mode on a MacBook).


Convert an integer(seconds) into the format of an hour: minute: seconds in c

When we write

scanf("%d",&N);

it's important not to ignore the return value from scanf() (that indicates how many values were successfully converted).  Otherwise, we're working with the uninitialised value N.

Use of the modf() function requires a declaration:
#include <math.h>

But we would be better working with integers instead (use the / and % operators).

Presentation of negative values is strange:

-70:-29:-29

Normally, we'd just print that as -70:29:29.
I'd be inclined to just work with unsigned values, and get that working well, before extending to negatives.

Variable naming is inconsistent (singular hour and minute, but plural seconds).  N is a poor choice for a variable name - choose something more meaningful and lower-case; convention reserves upper-case for macros.

We should make the declaration of main() be a prototype.  Also, it's permitted to omit the return statement in main(); since we always return success, let's remove that clutter.

Modified code
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    unsigned long total_secs;
    while (scanf("%lu", &total_secs) != 1) {
        // consume some input
        if (scanf("%*s") == EOF) {
            return EXIT_FAILURE;
        }
        printf("Enter a valid integer: ");
        fflush(stdout);
    }

    unsigned long hour = total_secs / 3600;
    unsigned int minute = total_secs / 60 % 60;
    unsigned int second = total_secs % 60;

    printf("%lu:%u:%u\n", hour, minute, second);
}


Showing one category and hiding two others when one of three buttons is clicked

Give each #category-n-button a class like category_button.

Bind the handler in the each()[docs] method  so that you can use the index argument to calculate the background position.

Use this to reference the element that received the event in the click handler.

Use the not()[docs] method  to exclude the this element from the other category buttons when setting the opacity.

Use the filter()[docs] method  to show the category element that pertains to the index of .each() + 1.

$(function() {
    var categories = $('[id^="category_"]');
    var category_buttons_a = $('.category_button a').each(function( idx ) {
        $(this).bind('click', function() {
            $(this).css({opacity:'1'});
            category_buttons_a.not(this).css({opacity:'0.4'});
            $('#blog-headers').css({backgroundPosition: '0 ' + (idx * -144) + 'px'});
            categories.hide().filter( '#category_' + (idx + 1) ).show();
        });
    });
});


You can replace

friend = Friend.new(:screen_name => follower.screen_name)
client.friendship_create(friend.screen_name, true)
friend.save

With

friend = Friend.create(:screen_name => follower.screen_name)
client.friendship_create(friend.screen_name, true)

I'd also suggest wrapping creation of friend in separate class method:

class Friend < ActiveRecord::Base
  def create_with_follower(follower = nil)
    return unless follower
    create :screen_name => follower.screen_name
  end
end

Then code becomes like this:

friend = Friend.create_with_follower follower
client.friendship_create(friend.screen_name, true)

I'd probably hide the friendship_create method call somewhere too. Not sure what it does though. Is it separate API call?

update

Now whole code becomes like this:

def friend_all_followers(friends)
  followers = client.followers.reject { |f| friends.include?(f) }
  followers.each do |follower|
    friend = Friend.create_with_follower follower
    client.friendship_create(friend.screen_name, true)
  end
end

Now you can do some readable operation on array. Something like this:

def friend_all_followers(friends)
  (client.followers - friends).each do |follower|
    friend = Friend.create_with_follower follower
    client.friendship_create(friend.screen_name, true)
  end
end


You have what appears to be an unnecessary break tag here.

Score

    Card


Your friend's assertion that it's \$O(n^3)\$ is questionable. For that to be true, either or both of the replace or includes function needs to be \$O(n^2)\$ which is ... unlikely. It's more likely that both are \$O(mn)\$ complexity where m is the length of the source string, and n is the length of the search string ([] or {} or () all of which are "short")

Putting aside the complexity, it is still apparent that your code is not very efficient, even at \$O(n^2)\$.

An \$O(n)\$ solution is possible if you use a state machine and a stack (or recursion) to control the assertions. After any open parenthesis only 4 characters can follow, another open parenthesis ((, [, or {), or the matching close parenthesis. You can simplify the state machine by adding a dummy character, I'll use a . period to illustrate:

const terminator = ".",
    openers = "{[(",
    following = {
        "[": "]",
        "{": "}",
        "(": ")",
    };

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {

    // add terminating character.
    s = s + terminator;

    // seed stack with
    const stack = [terminator];

    for (const c of s) {
        if (openers.includes(c)) {
            // going deeper in to nesting.
            stack.push(following[c]);
        } else {
            // coming out of nesting, check the correct closer.
            // (which may be a "." at the end)
            if (stack.pop() != c) {
                return false;
            }
        }
    }
    return true;

};

console.log(isValid("({(())})")); // True
console.log(isValid("({((}))})")); // False


A few notes:

Is there a reason you aren't using JavaFX?  See this answer as
to why you should be using it.
Since I mostly rewrote your code, I'll do the best I can to explain all the components of implementing an app in JavaFX:

There are a few layers within a JavaFX app; the application, the stage, the scene, and the canvas.  I'll let you do more reading on your own about all of those if you wish to learn more, but these are the basic components for creating a GUI.
Within the canvas, we add the event handlers to handle all the different mouse events.  These are pretty self-explanatory, since you have them in your app as well.
Now we have to handle the actual painting on the canvas.  Again, you have a similar approach in your code, so I don't have to cover this in depth.

Small user-experience quip: don't start the program in the middle of the screen.  Often comes across as adware-like.

Final Code:

package javafx_drawoncanvas;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class JavaFX_DrawOnCanvas extends Application {

    @Override
    public void start(Stage primaryStage) {

        Canvas canvas = new Canvas(400, 400);
        final GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
        initDraw(graphicsContext);

        canvas.addEventHandler(MouseEvent.MOUSE_PRESSED,
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.beginPath();
                graphicsContext.moveTo(event.getX(), event.getY());
                graphicsContext.stroke();
            }
        });

        canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED,
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.lineTo(event.getX(), event.getY());
                graphicsContext.stroke();
            }
        });

        canvas.addEventHandler(MouseEvent.MOUSE_RELEASED,
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {

            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(canvas);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setTitle("Paint");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void initDraw(GraphicsContext gc){
        double canvasWidth = gc.getCanvas().getWidth();
        double canvasHeight = gc.getCanvas().getHeight();

        gc.setFill(Color.LIGHTGRAY);
        gc.setStroke(Color.BLACK);
        gc.setLineWidth(5);

        gc.fill();
        gc.strokeRect(
                0,              //x of the upper left corner
                0,              //y of the upper left corner
                canvasWidth,    //width of the rectangle
                canvasHeight);  //height of the rectangle

        gc.setFill(Color.RED);
        gc.setStroke(Color.BLUE);
        gc.setLineWidth(1);
    }

    public static void main(String... args) {
        launch(args);
    }

}


Your first if can be simplifed with any function.

function any ($list, $pred)
{
     foreach ($list as $value)
     {
          if (call_user_func ($pred, $value) == TRUE)
             return TRUE;
     }
     return FALSE;
}

So it will be :

 $toTest = [$_FILES['browseMovie'],
            $_FILES['browseThumbnail'],
            $_GET['title'],
            $_GET['description'] ]
 if (any ($toTest, "empty")) die ("Please insert all fields")

Then you can simplify the code even more by creating a validate type function

function validateFile ($filePartsMovie, $filePartsThumbnail)
{
      if($filePartsMovie['extension'] !== "mp4")
      {
           die('Video has to be a .mp4 file.');
      }

      if($filePartsThumbnail['extension'] !== "jpg" &&
         $filePartsThumbnail['extension'] !== "png")
      {
          die('Thumbnail has to be in jpg/jpeg or png format.');
      }

     if($_FILES['browseMovie']['size'] + $_FILES['browseThumbnail']['size'] > 1600600000)
     {
              die('filesize of video and thumbnail = higher 1.5 GB.');
     }
}

Then you can create a validate function for the rest of the code.

TLDR is to split your code in more separate functions.

BTW I think you do not need brackets when having only one statement after if.


If browser compatibility matrix satisfies your requirements (see CanIUse) then there is a simpler way to check if page is reloaded, read window.performance.navigation.type value. For reload event value is TYPE_RELOAD then you may simply drop your hidden input and:

if (window.performance.navigation.type != 1) {
    activeTab = "";
}

See also W3C specs for further details.

If you're not targeting IE you may want to use template literals instead of string concatenation, for example:

$(`#myTab a[href="${activeTab}"]`).tab('show');

Value you're persisting in localStorage does not need to be retained across different sessions then you'd better use sessionStorage instead. It also has the advantage to be isolated by window (or tab).

You may want to use let and, where appropriate, const instead of var.

To put everything all together you may want to revert the condition you're checking to simplify your code:

$(document).ready(function () {
    $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
        sessionStorage.setItem('activeTab', $(e.target).attr('href'));
    });

    if (window.performance.navigation.type === 1) {
        const activeTab = sessionStorage.getItem('activeTab');
        $(`#myTab a[href="${activeTab}"]`).tab('show');
    }
});

The recommended way to attach an handler to the ready event is:

$(function () {
    // ...
});

Absolutely nothing wrong with the verbose way (which BTW I find more clear).

I add this only because you may find it useful in future, to detect a page refresh may be done also server side, see asp.net mvc - Detecting page refresh.


I could not find anything wrong with your code,
so per Meta I am going to tell you why it is awesome ;)

Checking .toString() is icky, toString() could easily be replaced/enhanced
Your solution works across frames
I was not able to break it.

On a final note, it seems to me that needing to verify the type of an object ( besides assertions ) means you are doing something odd and probably the code should be re-thought.

Still, I am favouriting this question.

UPDATE : Turns out that according to jsperf, your solution is much slower :\


It seems like you need a Rails validation callback (and a virtual attribute for submitted_password). I'd write:

attr_accessor :submitted_password
validate :password_format_is_valid?

def password_format_is_valid?
  regex = Regexp.new(Setting['global_admin.password_format_regex'])
  unless submitted_password =~ regex
    self.errors.add(:password, Setting['global_admin.password_format_error_message'])
    false
  end
end

Comments:

In the vein of Lisp, the last expression of a body in Ruby is the return value of the method/block, so no need to use an explicit return (in fact it's unidiomatic and discouraged)
Note that Rails can validate fields with regular expression, you should use the predefined validations whenever possible: validates_format_of.


Recursion vs iteration of tree structure

I would have completely agreed with the idea that iterative should be faster than recursive, I have seen proof to that effect many times in other languages.  It is however harder to read.  Here however, in JavaScript perhaps it is not, at least the benchmarks seem to suggest that the necessary object creation outweighs the function call overhead.

To that end these two examples based on yours illustrate that it is the object creation, and array manipulation that lead to the lower performance of the iterative approach.  These two examples leverage the objects being iterated to create a linked list of those objects.  This has the downside that it modifies each object traversed and so may not be desirable, beyond illustrating the performance difference.

Within a margin of error, these methods outperform the optimized recursive algorithm.

Breadth-First

// simulates operations for walking through tree using iteration
parentElement.depth = 0;
parentElement.next = null;

var children, i, len;
var depth;
current = parentElement;
while (current) {
  depth = current.depth;
  children = current.childNodes;
  //removes this item from the linked list
  current = current.next;
  for (i = 0, len = children.length; i < len; i++) {
    child = children[i];
    child.depth = depth+1;
    //place new item at the head of the list
    child.next = current;
    current = child;
  }
}

Depth-First

// simulates operations for walking through tree using iteration
parentElement.depth = 0;
parentElement.next = null;

var children, i, len;
var depth;
var current,last;
current = parentElement;
last = current;

while (current) {
  children = current.childNodes;
    for (i = 0, len = children.length; i < len; i++) {
      child = children[i];
      child.depth = current.depth+1;
      child.next = null;
      //place new item at the tail of the list
      last.next = child;
      last = child;
    }
  //removes this item from the linked list
  current = current.next;
}

JSPerf Comparison


To convert an integer to a bit string with a particular number of digits, use string.format with the b format type. For example:

>>> ['{0:04b}'.format(i) for i in range(16)]
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
 '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']

But really it looks to me as though you don't want to be working with bit strings at all. You just want to be working with integers.

So instead of get_all, just write range(16) and instead of bytexor, write ^. Your entire program can be written like this:

from itertools import product
for a, b, c, d, e in product(range(16), repeat=5):
    if a ^ c ^ d == 3 and a ^ c ^ e == 10 and a ^ b ^ c ^ d == 6:
        print a, b, c, d, e, a ^ b ^ c ^ e

(This will also run a lot faster without all that fiddling about with strings.)


I will just be looking at your prime function.

You got the right idea, but you missed some edge cases, and it can also be optimized. 2 and 3 are prime but return false, since halfNum starts at 1, and do...while loops always run at least once. 1 is not prime but return true, along with some negative numbers. The easiest way to handle this is just to check for this special case at the start of the function.

if(n <= 1) return false;

You are checking for divisibility with all numbers between 2 and half the input, which is good. But it seems a bit confusing to me when you use a do...while loop and counting down, instead of just counting up with a good old for loop.

for(let i = 2; i <= halfNum; i++)

But we can optimize this, since we only need to check up to the square root of the number. For any divisible number larger than the square root, there will also be a divisible number lower than the square root. For example, 100 is divisible by 20, but also 5, since 20*5=100. I'm also going to pre-calculate it and rename halfNum as that name doesn't fit anymore.

const limit = Math.sqrt(num);

The final function looks like this.

function isPrime(num) {
    if(num <= 1) return false;
    const limit = Math.floor(Math.sqrt(num));
    for(let i = 2; i <= limit; i++) {
        if(num % i === 0) return false;
    }
    return true;
}


public class NoksStringBuilder {

When told that something implements StringBuilder, I would expect it to implement the same interfaces.

public class NoksStringBuilder implements CharSequence, Appendable, Serializable {

This way it can be used as a replacement for a StringBuilder used in more generic circumstances.

    String[] stringList = new String[INITIAL_SIZE];

You call this a stringList, but it's actually a String array.  If it were an actual List, you could quit mucking around managing capacity.

      List<String> strings = new ArrayList<>();

This would push all the memory management off onto the List.  But I actually don't think that anything involving String is correct here.  More on that later.

    public void add(String s){

Similarly, I would call this

    public Appendable append(CharSequence csq) {

Then you could use it the same way as with a real StringBuilder.  Or you could use it the way you do your method (realizing that a String is a CharSequence).

All this would make obvious that an array of String is not a good way to hold a StringBuilder.  For one thing, while it makes for a quick append of a String, it works less well with letters and you lose the random access aspect.  I'd probably try

    private char[] sequence = new char[DEFAULT_CAPACITY];

That puts more work into add but makes toString simpler.

    public String toString() {
        return new String(sequence, 0, length);
    }

Note that length is an object field that you'll have to maintain.  It's the equivalent of your characterCount.

Note that if you want to implement capacity(), you could just say

    public int capacity() {
        return sequence.length;
    }


Python Socket programming chat - getting a handle on PEP conventions

Instead of always manually parsing sys.argv, you can use the standard library tool argparse. It automatically enforces the right usage and prints a nicely formatted usage if not. For your given example it would look like this:

import argparse

def ip_address(ip):
    # TODO: implement checking if IP is valid
    return ip

def parse_args(args=None):
    parser = argparse.ArgumentParser(description="Tool for server client connection.",
                                     epilog="Ensure the socket server is live before using this tool.")
    parser.add_argument("ip", type=ip_address, help="The IP address of the server")
    parser.add_argument("port", type=int, help="The port where the server listens.")
    return parser.parse_args(args)

I put it into a function so you can test it without having to run the whole code, by passing a list of strings to the function. It also allows setting the type of arguments, which can be any callable (so in the above example you need to have e.g a function called ip_address that can check if the argument is a valid IP address). The help messages generated by this example are like this:

$ python3 /tmp/sock_client.py 127.0.0.1
usage: sock_client.py [-h] ip port
sock_client.py: error: the following arguments are required: port

$ python3 /tmp/sock_client.py -h
usage: sock_client.py [-h] ip port

Tool for server client connection.

positional arguments:
  ip          The IP address of the server
  port        The port where the server listens.

optional arguments:
  -h, --help  show this help message and exit

Ensure the socket server is live before using this tool.

You can also add optional arguments, arguments with multiple parameters, mutually exclusive arguments/argument groups. Check out the documentation for more examples.

Instead of iterating only over the keys of a dictionary, iterate over the keys and values at the same time if you need both of them. Also, don't use too short names. No matter how nice your docstring is, it is always better if your function signature already tells you everything you need to know.

def send_user(message, user):
    """
    Sends a message to a single client.

    Parameter:
    message -- the message to send
    user    -- the client to send to
    """
    for client, user_name in CLIENT_LIST.items():
        # only specific client/user
        if user_name == user:
            client.send(bytes(message, "utf8"))

Also, don't lie in your docstrings. This function sends a message to every client with the right name (i.e. value in the dictionary)! You can just break after you have found the user to ensure there is only one, or adapt the docstring to the reality of the code. In either case, add tests to ensure that your code does what it should.

Calling what appears to be a dictionary CLIENT_LIST is one of the reasons why you should not include the type in the variable. Here it is very misleading and probably wrong! Just call them CLIENTS or ALL_CLIENTS or even USER_NAMES.

There are two widely used docstring conventions (that I know of, i.e. in scientific computing). The first is the Google style and the other one the numpy style. Your code seems to be closer to the latter, but as long as you are consistent and include all necessary information you should be fine.


remove kth last element from singly-linked list

I don't know what OS and compiler you use but running gcc -O2 main.c -o main -Wall -Wextra produces several warnings:
main.c: In function ‘del_element_from_last’:
main.c:41:18: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ {aka ‘long unsigned int’} [-Wformat=]
   41 |     printf("len:%d \n", llist->length);
      |                 ~^      ~~~~~~~~~~~~~
      |                  |           |
      |                  int         size_t {aka long unsigned int}
      |                 %ld
main.c:47:10: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]
   47 |     if(k > (size_t)llist->length)
      |          ^
main.c:51:16: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]
   51 |     else if (k == (size_t)llist->length)
      |                ^~
main.c:73:1: warning: control reaches end of non-void function [-Wreturn-type]
   73 | }
      | ^

valgrind reports memory leak:
$ valgrind ./main
==10611== Memcheck, a memory error detector
==10611== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==10611== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info
==10611== Command: ./main
==10611==
len:100
deleted element:186
==10611==
==10611== HEAP SUMMARY:
==10611==     in use at exit: 1,600 bytes in 100 blocks
==10611==   total heap usage: 101 allocs, 1 frees, 2,624 bytes allocated
==10611==
==10611== LEAK SUMMARY:
==10611==    definitely lost: 32 bytes in 2 blocks
==10611==    indirectly lost: 1,568 bytes in 98 blocks
==10611==      possibly lost: 0 bytes in 0 blocks
==10611==    still reachable: 0 bytes in 0 blocks
==10611==         suppressed: 0 bytes in 0 blocks
==10611== Rerun with --leak-check=full to see details of leaked memory
==10611==
==10611== For lists of detected and suppressed errors, rerun with: -s
==10611== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)`

Why does this function
bool del_element_from_last(xllist *llist, int k)

and others return non-zero on success? Usually, functions in C return
0 on success and non-zero on failure. The current behavior in your
code is counter-intuitive.
You should add a function that prints the entire list.
If you do this:
del_element_from_last(&llist, 1);

your code crashes:
$ ./main
len:100
Segmentation fault


Well, i think, you should first ask yourself do you really want to complicate things? Is this something that you will re-use in other places? Because the feeling "i need to create something reusable and extendable" if familiar to every one of us, but the amount of code you'll need to write and debug is not always worth it in the end.

If you answer is "no", then you can simply do a little refactoring: move classes to separate files, replace individual viewmodel properties with Dictionary<ColourChoice, ViewModelBase>, stuff like that. It will end up looking fine.

If your answer is "yes", then i would probably create a tree-like structure from my view models by implementing something like:

interface ITreeViewModel
{
    IEnumerable<ITreeItem> Children { get; }
    bool IsSelected { get; }
    ITreeItem Parent { get; }
}

Then i would create a custom user control wich will display such tree using this interface and specidied DataTemplates (after i will fail to make wpf TreeView work as i want it too yet again -_-). This is a tricky task with plenty of pitfalls, but i think its possible. At least that would be an approach I'd try first.


Here is shorter method with regex

    private static String CreateText(string textIdentifier, IEnumerable<string> texts)
    {
        const int defaultNumber = 1;

        Regex regex = new Regex(@"\(\s*(?<num>\d+)\s*\)");

        var numbers =
            texts.Select(p => p.Trim()).Where(p => p.StartsWith(textIdentifier))
            .Select(str => { var m = regex.Match(str); return m.Success ? int.Parse(m.Groups["num"].Value) + 1 : defaultNumber; });

        int max = numbers.Any() ? numbers.Max() : 0;

        return max == 0 ? textIdentifier : string.Format("{0}({1})", textIdentifier, max);
    }

+1 to @dreza for tests ;)


Saving a contact and dealing with exceptions

You shouldn't use general catch, you should always catch only the exceptions that you actually want to catch.
Avoidable exceptions like index out of range or null reference should indicate an error in your code. Instead of handling them, you should make sure they never happen.

For your specific case, you could write an extension method that checks that the index isn't out of range and that the value isn't null (and returns empty string if it is).

Something like:

public static string GetAsStringOrEmpty(this object[] array, int index)
{
    if (array == null)
        throw new ArgumentNullException("array");

    if (index >= 0 && index < array.Length)
    {
        string value = array[index] as string;

        if (value != null)
            return value;
    }

    return string.Empty;
}

You would then use it like this:

var array = dtdetails.Rows[0].ItemArray;
save.Firstname = array.GetAsStringOrEmpty(1);
save.LastName = array.GetAsStringOrEmpty(2);
…


I'm afraid that there's no 'good' answer here. There are many ways to achieve a certain effect, but they are dependent on the context.

Floated containers differ from the ones that are positioned absolutely. An absolutely positioned container is 'taken out of the layout' - that means e.g. that if you have 2 divs in a parent div and you set position absolute on one, the other one is going to fill the whole parent and the absolutely positioned one is going to be 'on top' of it (provided it has a width & height set, has a higher z-index or is placed last in DOM, but that's another story). If in the same situation you float one of the divs (and it has width set), the other one will 'stick' to it, but again, it (the second div) has to fulfill some criteria (e.g. if it has width set to 100% or 'clear' property set to both or left/right, it will not stick to the other one)

As for width - if an element is a block element or it has display:block set, width: 100% will expand it to be as wide as the closest ancestor that has position:relative or position:absolute set (this might be a little tricky), whereas width:100% on inline elements will not do anything.

width:100% will probably not work as you expect if you have padding set on the element (element will be to wide).

width:auto behaves differently on floated an non floated, block elements...

There are just too many variations. The same solution works in some cases, but doesn't work in others. It's rarely possible to say 'this is just going to work' if you don't look at what's happening to the rest of the page.


I am trying to filter a queryset based on dates, I keep getting a duplicate error on the for loops,How do I refactor these code to remove duplicates?

Factoring duplication out
Whenever I have (near-)duplicate code, what I do is take a look at the repeated code. The parts that change ever so slightly are going to be controlled with arguments to functions and etc, whereas the parts that remain the same will just be left more-or-less as-is.
Having said that, here is what I see:

the queries being used change, so those are function arguments;
the attributes of the event being updated change, so those are function arguments;
the final dict being generated is the same, so we leave it the same.

From your code alone, here is a suggested modification:
def filter_and_update_events(Qs, event_changes, venue_changes):
    for event in Events.objects.filter(*Qs)
        for attr, new_value in event_changes.items():
            setattr(event, attr, new_value)
        event.save()
        for attr, new_value in venue_changes.items():
            setattr(event.venue, attr, new_value)
        event.venue.save()

        reserve_data = dict()
        reserve_data["sensor_id"] = event.venue.sensor_id
        reserve_data["status"] = event.venue.status
        return reserve_data

def get_ongoing_events():
    return filter_and_update_events(
        [
            Q(event_begin_datetime__lte=current_time),
            Q(event_end_datetime__gt=current_time),
        ],
        {"event_status": "ongoing"},
        {"status": "booked"},
    )

def get_complete_reservation():
    """
    Update reservations and sensors
    :return:
    """
    return filter_and_update_events(
        [
            Q(reservation_begin_datetime__lt=current_time),
            Q(reservation_end_datetime__lte=current_time),
        ],
        {"reservation_status": "complete"},
        {"status": "free"},
    )

Notice that I used setattr docs to set the attributes of the event and the venue.
Also notice that my new function has a bit of duplication in the loops, but that is the easiest way to deal with the fact that venue is inside event and there is no obvious way to use setattr to deal with the nesting.
If you need to expand your function to update even more things inside event, then I would also recommend creating a helper function that takes an event and a "setting name" and sets it, so that filter_and_update_events doesn't need to take one dictionary per object inside event.
Does this make sense?


I think I'd encode this into something on the order of a state machine--a table holding the conditions and actions associated with each, and a tiny bit of code to walk through those to carry out the tests:

#include <iostream>
#include <functional>

#ifdef TEST
bool do_n, do_a, do_up;
bool success;
bool T = true;

void run_do_up() { std::cout << "did up\n"; }
void run_do_a() { std::cout << "did a\n"; }
void run_do_n() { std::cout << "did n\n"; }
#endif

struct conditional_action {
     bool const &condition;
     std::function <void()> action;

     template <class F>
     conditional_action(bool const &b, F &a) : condition(b), action(a) {}

     conditional_action() : condition(T), action([&]{success = false; }) {}
};

conditional_action actions[4][3] {
    { { do_up, run_do_up }, { do_a, run_do_a }, { do_n, run_do_n } },
    { { do_n, run_do_n }, { do_a, run_do_a } },
    { { do_a, run_do_a }, { do_n, run_do_n } }
};

void exec(size_t x) {
    for (auto const &a : actions[x])
        if (a.condition) {
            a.action();
            return;
        }
}

#ifdef TEST

int main() {
    do_n = true;
    exec(0);

    do_a = true;
    exec(2);
}
#endif

Depending on viewpoint, you might want to add a { T, [&]{success = false; }} to the end of each row in the actions table. That's what the default ctor will fill those entries with anyway, but there's a fair argument to be made that since it was explicit in the original logic, it should remain explicit here as well.

There is probably at least a little argument to be made that this is kind of a borderline case. A case where there were more conditions and actions would favor this technique more strongly. Whether really it makes sense when you have only three conditions and actions may be open to a little more question.


Parsing function for a server, using the Jansson library

A few notes:

My first concern with your program is the use of the Jansson library.  Looking at some benchmarks shows me that it is less than stellar. (The Y-axis is parses-per-second. Thus, higher is faster.)

So a new library choice may be in order.  I would highly recommend looking a jsmn. I have yet to find a faster (and more portable!) option out there.  Here is a benchmark for jsmn compared to Jansson (jsmn is 19.28 times faster).

\$
\newcommand\T{\Rule{0pt}{1em}{.5em}}
\begin{array}{|c|c|c|c|c|c|}
\hline \textbf{Project} & \textbf{License} & \textbf{API} & \textbf{Neg. tests} & \textbf{Followers} & \textbf{Benchmark} \T \\\hline
  \text{Jansson} \T & \text{MIT} & \text{DOM} & \text{yes} & \dfrac{234}{59} & 25 \text{MB/s}, 52 \text{s} \\\hline
  \text{jsmn} \T & \text{MIT} & \text{custom} & \text{yes} & \dfrac{65}{4} & 482 \text{MB/s}, 2.3 \text{s} \\\hline
\end{array}
\$
You have used the preprocessor to define some oBIX request values.

#define OBIX_REQUEST_INVALID -1
#define OBIX_REQUEST_WATCH 0
#define OBIX_REQUEST_UPDATE 1

You could use an enum here instead.

typedef enum
{
    INVALID = -1,
    WATCH = 0,
    UPDATE = 1
} ObixRequest;

You can remove any != 0 tests from your if conditions for maximum C-ness.
You sometimes use printf() when you don't have to.

printf("\nInvalid JSON data.\n");

Use puts() for statements like this when you aren't formatting the string.  As a plus, you don't have to include the \n characters.

puts("Invalid JSON data.");


Reverse Polish Notation Evaluation in Java

public class EvaluateReversePolishNotation {

As a general rule, name classes and objects as nouns.  Verbs are used for methods.  I personally like PostfixCalculator, but if you want these words, consider:

public class ReversePolishNotationEvaluator {

Now it's a noun.

        HashSet<String> ops = new HashSet<>(Arrays.asList("+","-","*","/"));

I would mark down for this when evaluating code.

        Set<String> ops = new HashSet<>(Arrays.asList("+", "-", "*", "/"));

Unless you are specifically using some method that only exists in that specific implementation, I would always recommend using the interface as the type.

I prefer a little whitespace in my lists.

Note that you don't actually need this.

        HashSet<String> ops = new HashSet<>(Arrays.asList("+","-","*","/"));
        for (int i=0; i<tokens.length; i++) {
            if (!ops.contains(tokens[i])) {
                stk.push(Integer.parseInt(tokens[i]));
            }
            else {
                int secondOperand = stk.pop();
                int firstOperand = stk.pop();
                switch (tokens[i]) {
                    case "+":
                        stk.push(firstOperand+secondOperand);
                        break;
                    case "-":
                        stk.push(firstOperand-secondOperand);
                        break;
                    case "*":
                        stk.push(firstOperand*secondOperand);
                        break;
                    case "/":
                        if (secondOperand == 0) {
                            throw new ArithmeticException("Second operand can't be zero in division");
                        }
                        stk.push(firstOperand/secondOperand);
                        break;
                    default:
                        break;
                }
            }
        }

It's enough to write

        for (String token : tokens) {
            stk.push(processToken(stk, token));
        }

and separately

    public static String processToken(Stack stack, String token) throws ArithmeticException {
        switch (token) {
            case "+":
                return stack.pop() + stack.pop();
            case "-":
                Integer subtrahend = stack.pop();
                return stack.pop() - subtrahend;
            case "*":
                return stack.pop() * stack.pop();
            case "/":
                Integer divisor = stack.pop();
                if (divisor == 0) {
                    throw new ArithmeticException("Divisor can't be zero");
                }

                return stack.pop() / divisor;
            default:
                return Integer.parseInt(token);
        }
    }

The advantage of this is that you only write each operator down once.  So adding or removing an operator only needs to be done in one place.  In the original code, you had to change in two places.  This can lead to odd behavior if you make changes.

The separate method saves having to rewrite stk.push( constantly.  Yes, we write return a lot, but we no longer need to break.

I would prefer the for each form or the advanced for loop to a C-style for loop anytime you don't use the index variable for anything other than indexing the collection.

You also might consider having a PostfixCalculator class with an object field of a Stack.  Then you wouldn't have to pass the Stack around.  Obviously the two methods would no longer be static in that case.

It's not clear to me that you gain anything by the check for division by zero.  If you actually divide by zero, it will throw an ArithmeticException anyway.  Why do so manually?  Normally it would be because you wanted to add something to the error message or log something prior to throwing the exception.  Or to keep going after handling the exception.  But you don't do any of that here.  So why the extra code?  If there's a reason, put it in a comment so that no one undoes what you did.

It would make more sense to me to catch the exception for the stack being empty.  That's likely to happen due to bad input.  If you catch it, you can add additional information about the error.  In particular, what token failed.

Similarly, you might want to handle the situation where the stack is not empty.  If you have more than one value left on the stack after processing all the tokens, then there was a mistake somewhere.

Note that the JavaDoc for Stack says to use Deque instead.


Print all permutations from a given list of strings such that each set of strings is completely unique

I don't think your current algorithm is that good.

You loop through all input_values twice, not even removing clearly know duplicates.

If you instead used say a half_product function, then you'd remove a lot of checks.
This is as you know if you've already visited the value with i, then you won't need to visit again with j.

This is as set('ab') == set('ba').
You can group the anagrams, to reduce the code complexity.

Currently you have two \$O(n)\$ loops - running in \$O(n^2)\$ time - where \$n\$ is the size of input_values.
After this, you then run in \$O(v\log{v})\$ - where \$v\$ is the max size of the values.
And so is \$O(n^2 v\log{v})\$.

However you can group all the values in \$O(n v\log{v})\$ time.
This means you now have \$g\$ groups, of \$a\$ anagrams. Being roughly \$ag = n\$.
From this you have to loop all groups and anagrams leaving \$O(g^2 a^2)\$ time.
And so is \$O(n v\log{v} + g^2 a^2)\$. Which is better in all cases, except where \$g\$ or \$a\$ are \$1\$.

And so I'd use:

def half_product(it):
    it = list(it)
    for i, value in enumerate(it):
        for j in range(i+1, len(it)):
            yield value, it[j]

def random_set(values):
    d = {}
    for value in values:
        d.setdefault(tuple(sorted(value)), set()).add(value)

    for anagrams in half_product(d.values()):
        yield from itertools.product(*anagrams)


Command Pattern: Does my implementation make the point?

If this was a school exercise

It's a basic command pattern without any safety checks against programming errors. :) It would be a good idea to check that a word can not be removed from an empty list.

If this was a job interview assignment

While the code shows that you know how to code a command pattern it doesn't tell me if you understand why one would want to use it. Having WriteCommand and UndoCommand objects going around in isolation makes very little sense. And domain-wise, writing to a text editor with command objects is probably not something that I would do.

Instead put the command pattern into actual use by, for example, integrating it to the editor in the form of an undo/redo stack. Appending strings to the editor automatically create undo commands into the stack and performing the undo command executes the last command and adds a corresponding redo command into the redo stack.


What is the most pythonic way to solve a differential equation using the Euler method?

Using a for loop is not an unpythonic way at all. Instead, an Euler method could be implemented with a recursive function, but it not necessary and less optimized in Python.

However, methods for vectorizing recursive sequences are discussed on the numpy-discussion mailing-list. I encourage you to use structures like for loops in such situations. You will minimize the risk of errors by writing simple and concise codes.


You have a few different challenges that are affecting performance.

Expressions on the field used to filter, rather than converting the filtered result.
EX: RTRIM( ISNULL( cli.ClientName, '' )) + ' ' + LTRIM( ISNULL( cli.FirstMiddleName, '' )) LIKE '%' + @SearchText + '%'

AND  ISNULL( cli.Flg_Deleted, 0 ) = 0

Using a scalar valued function in your resultset

RegNum = dbo.Get_B_Car_RegNum( car.ID, GETDATE()),

Using a scalar valued function in a join

ON cli.ID = dbo.Get_B_Car_ID_B_Client( car.ID, GETDATE())

Using a wildcard at the start of the search string

car.Descr LIKE '%' + @SearchText

Possibly, the use of UNION rather than UNION ALL.

The expressions and wildcards negate the use of any indexes and force a table scan on the underlying table.
As an example changing AND  ISNULL( cli.Flg_Deleted, 0 ) = 0 to AND ( CLI.Flg_Deleted IS NULL OR cli.Flg_Deleted = 0 ) can allow the optimizer to use an index on Flg_Deleted because the desired value is not dependent on an expression

The scalar valued function turns your set based query into a procedural query, (one row at a time) for which SQL Server is not optimized.  See if you can convert this into an inline table-valued function.  You should also consider  dumping the result into a table variable and join on that.  That would at least prevent running the udf for every possible combination of your joined table.

Each UNION will check for duplicates in the top and bottom result sets.  If the data is guaranteed unique between the result sets, you'll gain some performance by switching to UNION ALL, removing the distinct sort across the combined results.


Python tool to reduce number of resistors in circuit

with open(filename) as json_data:

Good!

        lst = json.load(json_data)
        totalperms *= len(lst)
        pairlists.append(lst)

lst isn't a great name, but I think it's forgiveable with such a tight scope. Maybe worth sanity-checking that the structure is what you expect?

print("Calculating permutations: %d" % totalperms)
perms = list(itertools.product(*pairlists))

Why bother with the code to calculate totalperms if you can just extract it as len(perms)?

Although, on the flip side, why coerce perms to a list and force it all into memory?

# combo is a list of flattened lists of every resistor combination
combo = [[0 for rows in range(len(pairlists)*2)] for cols in range(len(perms))]

I'm not sure what the point of this is. Perhaps the comment should explain why we need it.

for i in range(0,len(perms)):

You're right to think there's a more Pythonic way of doing this:

    for i, perm in enumerate(perms):

This doesn't require perms to be a list, because it removes the need to index into it.

    for j in range(0,len(pairlists)):
        combo[i][2*j] = perms[i][j][0]
        combo[i][2*j+1] = perms[i][j][1]
        price[i] += perms[i][j][2]

This really isn't doing much. Why not inline the calculation of the best option?

        count += 1
        if ( count % 1000000 == 0 ):
            print("%d of %d" % (count,totalperms))

That's buggy: it should be at one less level of indentation.

# Find the combination with the least number of unique resistor values

This is a pet peeve of mine: unique means that there is only one in existence. Distinct expresses precisely and unambiguously what you mean here.

minlen = 999
for s in combo:
    if ( len(set(s)) < len(pairlists)*2 ):
        if ( len(set(s)) < minlen ):
            minlen = len(set(s))

It's not standard Python style to use brackets around the condition. The conditions can be merged into one as

    if len(set(s)) < min(len(pairlists)*2, minlen):
        minlen = len(set(s))

but then that points to just initialising minlen to len(pairlists)*2 instead of the magic number 999.

Finally, this doesn't strike me as likely to be an efficient approach.

I would think it's likely to be more efficient (although still not very) to build a set of the distinct values and then look at subsets in order of increasing size, maybe guided by frequencies of the values.

The best option is probably to try to work out an encoding to a standard problem and use an optimised solver. The obvious one is SAT: you've basically got a Boolean formula already: each resistor value corresponds to a variable, and each file is an OR of a bunch of two-variable ANDs. Then you just need to add a count of the number of variables which are TRUE and require it to be less than a threshold, and search for the critical value of the threshold. For the prices you can use the same SAT formulation and loop:

while sat_instance.solve():
    yield sat_instance.solution()
    add a rule to sat_instance to exclude the solution


It is not a good idea to have a completely detached thread. When one detaches thread, they usually use some sort of notification system like future/promise to ensure that the thread finished using resources. Here you file logger might have finished working and got destroyed while the detached thread still accesses this leading to UB. Instead you should keep thread as a part of the logger and trigger join in the destructor.

You shouldn't use std::endl; for every message - the flushing is a slow operation. You surely don't have a good reason to trigger it more often than more than once a second . Just make sure that you do trigger it once a second or so. std::condition_variable::wait_for/wait_until could be used to ensure that.

Another bug in destructor is that you modify mIsRunning without locking the mutex. Technically, it is a UB. In practice, this bug results in some very rare cases with the wait missing the notification and lasting eternity.

With the scheme that you are running I don't see why you use a std::deque for holding messages. Why not just std::vector? It is more efficient and also you shouldn't create new localMessages each time - just keep one constantly existing and clear it after each use. It saves some unnecessary memory allocations.

Also, once mIsRunning is false you need to ensure that all messages were written instead of quitting. Moreover, you shouldn't access mIsRunning in the while-loop condition as it should be guarded by the mutex.

The log function void log(const std::string &msg); accepts a string and copies it into the queue. It is a waste. You'd better have two other overloads: void log(std::string&& msg); and void log(std::string_view msg); with the former moving the string and it's content for printing instead of unnecessarily copying it, while latter is just a more general form of const std::string&.

In general, logger should support features like verbosity filterting and identification (e.g., info, warning, error), timestamping, and similar stuff that should be inherent part of a logger. Here you just accept arbitrary messages.


Parzen window density estimation in MATLAB

Indentation is automatically fixed in MATLAB by marking everything, and do Ctrl+I.

The common practice is to have the first level alligned all the way to the left. Click here to see a screenshot from the builtin MATLAB function ind2sub. I have made no edits to it.

matrix is not a very good variable name. I suggest you choose something else. I don't have a suggestion off the top of my head, but there are probably more descriptive names.

[r c] = size(matrix);

There's not much more to say, best practice is to separate output values with commas.

The following subtracts the value of datapoint from A. I'm assuming datapoint is a scalar, not a matrix.

[r c] = size(matrix);
A = ones(r, c).*dataPoint;
sub = matrix - A;

This can be simplified a lot. If you want to subtract one value from all elements of a matrix in MATLAB, you can just do:

sub = matrix - dataPoint;

If dataPoint is a matrix, of the same dimensions as matrix, then you can do:

sub = matrix - dataPoint

Yes, that was exactly the same as above. As long as the dimensions match, or one of the variables is a scalar, you can simply subtract one from the other.

I guess dw means down? If so, call it down, it's easier to understand, and is not very hard to write.

You mix camelCase and lowercase. I suggest you stick to one, and do dataPoint and returnValue.

You forgot end in the end. It works without it, but it is supposed to be there.

  Is it correct?

I don't know. I don't know what it's supposed to do. I guess the simplest way to check it is to compare it to your C# implementation.


A better approach to parsing this file name in Java?

My version:

public class CodeReview_27975 {
    // match everything between the last "_" and "." [explanation in the notes!]
    private final static Pattern FILENAME_DATE_PATTERN = Pattern.compile(".*_(.*?)\\..*");

    // apply the pattern to extract date from file name
    private String extractDateFromFilename(String filename) {
        Matcher m = FILENAME_DATE_PATTERN.matcher(filename);
        if (!m.matches()) {
            throw new IllegalArgumentException(
                    "Filename doesn't match expected format: " + filename);
        }

        return m.group(1);
    }

    private boolean compareDate(String fileName, String cellDateString) {
        SimpleDateFormat fileDateParser = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat cellDateParser = new SimpleDateFormat("MM/dd/yyyy");

        Date d1, d2;
        try {
            d1 = fileDateParser.parse(extractDateFromFilename(fileName));
            d2 = cellDateParser.parse(cellDateString);
        } catch (ParseException e) {
            throw new IllegalArgumentException(
                    "One of the input dates failed to be parsed:" + fileName
                            + ", " + cellDateString);
        }

        return d1.equals(d2);
    }

    // this is the only public method, but it delegates to private utility functions
    public boolean compareDate(File file, String cellDate) {
        return compareDate(file.getName(), cellDate);
    }

    public static void main(String[] args) {
        CodeReview_27975 app = new CodeReview_27975();
        // easy to test
        System.out.println(app.compareDate("file_user_20130125.csv", "1/25/2013"));
        System.out.println(app.compareDate("file_user_20130125.csv", "01/25/2013"));
        System.out.println(app.compareDate("file_user_20130101.csv", "1/1/2013"));
    }
}

split the single method into smaller, easier to test, chunks.
each function deals with a single concern (most of the code deals with strings, no need to pass the File object further down the stack). This makes it easier to test
regular expressions are useful when dealing with patterns in strings. Extracting date from file is much more robust this way (you'll most likely getting the NullPointerException for non-standard input; the current expression doesn't solve this problem but at least it reports it correctly, making it easier to create a fix)
comparing dates as strings is just wrong; your equals-or-contains trick would fail when comparing 1/1/2013 and 01/01/2013. Creating a Date object is a small price to pay for correctness.
the class could be visually longer but I believe it's easier to understand this way; most of the new code comes from exception handling - if you decided to simply make the caller handle checked exceptions, you could remove most of that.

Also, convention for compare functions is to return an integer: <0 if first argument is smaller, 0 if both are equal and >1 if the first argument if bigger. This would make the method more flexible and potentially useful for the caller. Changing the name to areDatesSame or something like that would be another option.

edit:
".*_(.*?)\\..*" pattern dissected:

.*    any character, zero or more of them at the start
_     an underscore
(.*?) capture a group (after underscore, before the dot)
\.    dot character (has to be escaped into "\\." if inside a String)
.*    any character, any number of them at the end

Regular expressions are a broad subject but knowing the basics (and where/how to look for more detailed information) will always pay off. You can start by having a look at the Java Tutorial on Regex

The expression could be changed to only accept exactly 8 digits in the group (rather than ANY string between "_" and "."), making it a bit more complicated but more specific.

Visualisation from debuggex.com:


Any criticism on my JavaScript micro-library?

Problems with it :

in the global namespace
use of innerHTML
no cross-compatibility
messing with object prototypes
quite useless


given that you duplicate nearly the whole $.ajax() call you can extract it into a function and add a parameter where it differs::

function doAjax(dataType, myval){
    $.ajax({
        contentType: "application/json; charset=utf-8",
        url: 'http://myserver.com/helpdesk/check_json.php',
        dataType: 'json',
        data: {type: dataType, term: myval},
        success: function (data) {
            if(typeof data == "undefined" | data == null | data.length == 0){
            alert("No Result");
            document.getElementById("form1").reset();
            return};
            //console.log(data);
            $("#empnum").val(data[0].empnum);
            $("#ext").val(data[0].extension);
            $("#omobile").val(data[0].omobile);
            $("#pmobile").val(data[0].pmobile);
            $("#ename").val(data[0].ename);
            $("#name").val(data[0].empnum);
            $("#email").val(data[0].email);
        },
        error: function (result) {
            alert("Error");
        }
    });
}


Your approach works but it is hard to read: all the logic is concentrated in the single smallestMultiple method, which is responsible for:

looping over the numbers
determining if one is divisible by all the number between 1 and l
printing the result

Dedicated methods
Looking at the points above, we clearly need a method whose goal will be to say if one number n is divisible by all the numbers between 1 and max.
private static boolean isDivisible(long n, int max) {
    for (int i = 2; i <= max; i++) {
        if (n % i != 0) {
            return false;
        }
    }
    return true;
}

This is very clear. It loops over all the numbers between 2 (no need to start at 1, thanks to Konrad Morawski that pointed it out) and max. If one does not divide n, then it returns false. If none were found, it means all divide n, so we return true.
Take note also of the spacing: adding a single space after the for, before the curly braces, after each semi-colon in the loop condition, greatly contributes to clarity.
long vs int
You are using inconsistently long and int. smallestMultiple takes a long as parameter but the inner loop uses an int:
//                                  vvvv
public static void smallestMultiple(long l){
    // ...
    while(true){
        //  vvv
        for(int i=1; i<=l; i++){

Also, count, which will be the result of the result is an int.
You need to clarify: what can be big enough to warrant using a long? Clearly, it is not the upper bound, which is 20 here. So l doesn't need to be a  long. count, on the other hand, is expected to be big so we could use a long for this variable. In this case, it turns out that the result fits in an int, but if we increase a little the upper bound, it won't fit anymore.
Namings

count is a bad name here. This is really the result of the calculation. It doesn't really count anything. It is merely an temporary variable that we increment. A generic result would be more explicit.
l is not very clear also. We could rename it upper or max to signify that this is the upper bound for the numbers to consider.

Main method
With the above dedicated method, we then have:
public static long smallestMultiple(int max) {
    long result = 1;
    while (!isDivisible(result, max)) {
        result++;
    }
    return result;
}

With such a method, one can clearly see what is happening: we are incrementing result while it is not divisible by all the numbers from 1 to max.
Note that it also returns the result, instead of printing it: you should let whoever is calling printing the result, printing is not the task of that method.
The big advantage here: no need to break any loop and no need for flag variables: having such flags is generally a code-smell indicating that the method is doing too much.
Faster methods
There are indeed faster methods:

taking the prime factorization of the numbers between 1 and the `max, as shown in this answer.
using a property of the lowest common multiple, as shown in this answer.


Using toString() as a hack to generate keys for react-select component

One possible down-site of this could be a performance issue and this depends on how toString() is implemented.

On my case I did it like this :

let options = [
  {
    label: 'Color',
    value: {
      r: 123,
      g: 78,
      b: 198,
      toString: function(){
        return uuid.v1();
      }
    }
  }
]

Whenever the state or props are updated React uses a diff. algorithm to check if it's VirtualDOM and DOM corresponds, which means every time React looped through options they had a different key value and React re-rendered every option no matter if their value changed or not.

In my case a fix was to hash the value object using this library;

let options = [
  {
    label: 'Color',
    value: {
      r: 123,
      g: 78,
      b: 198,
      toString: function(){
        return hash(this);
      }
    }
  }
]


Search string in file, replace it, and write back to file

Personally, I would do this kind of thing line by line. I don't like the idea of putting my entire file into memory, then overwriting it. What if something goes wrong in between? Basically I don't trust myself to write good code!

So, looping through line by line, I would write to a new file with any changes. In Python, you can open two files at once, which is perfect for reading from one and writing to another.

Applying PEP8 for naming, you'd end up with something like this:

def file_search_replace(open_file, search, replacement):

    with open(open_file, 'r') as read_file, open('new_file.txt', 'w+') as write_file:

        for line in read_file:
            write_file.write(line.replace(search, replacement))

I've changed a few of the names, notably replace to replacement so it's clear it's not the same as replace().

Finally, if you're happy with the result, you can easily rename the file to something else. Personally I'd keep the old one just in case.


Multiple similar methods to compute the average student grade

Since you are writing for Java 8, what you want to use is DoubleStream.average().  Java 8 streams are a new and powerful technique that drastically changes how code can be written in Java.

public class Student {

    ...

    public double getAverageGrade() throws NoGradesForStudentException {
        return getStudentSubjects().stream()
                                   .mapToDouble(Subject::getAverageGradeInSubject)
                                   .average()
                                   .orElseThrow(() -> new NoGradesForStudentException("Student does not have any grades yet"));
    }
}

This code is compact enough that near-duplication of code would not be a problem.

However, the NoGradesForStudentException would cause a bit of a problem.  In particular, with a stream-based solution, ignoring cases where a student has no grade in a particular subject would be a tricky exercise in exception handling.  A better approach is to embrace Java's convention for DoubleStream.average(), and change all of these getAverageGrade…() methods to return an OptionalDouble instead of a double.  Then, the code would look like this:

public class Student {

    ...

    public OptionalDouble getAverageGrade() {
        return getStudentSubjects().stream()
                                   .mapToObj(Subject::getAverageGradeInSubject)
                                   .filter(OptionalDouble::isPresent)
                                   .mapToDouble(OptionalDouble::getAsDouble)
                                   .average();
    }
}

Note that taking the average of the average of grades in each subject is not necessarily the same as taking the average of grades.  It may be appropriate to rename the method to make it clear that there is batching by subject.  Similarly, your GroupOfCourses.getAverageGrade() needs to make it clear that it calculates the average of each student's grade.


ways to code for better speed of processing date comparisions / slicing in python

There are a few small niceties that you can add.
long = pd.DataFrame(columns={'bene_id', 'day','date'})
cols_to_order = ['bene_id', 'day','date']

should reuse the list:
cols_to_order = ['bene_id', 'day','date']
long = pd.DataFrame(columns=set(cols_to_order))

This:
cols_to_order + (long.columns.drop(cols_to_order).tolist())

can drop the outer parens, since . takes precedence over +.
e, j and temp need better names.
This:
for i,j in zip(range(1,91), Series(date_range(start,stop))):
    long = long.append(pd.Series([e,i,j],index=cols_to_order), ignore_index=True)

shouldn't be a loop. There's almost certainly a way for Pandas to vectorize it.


Avoiding repetition when using the "snprintf idiom" to write text

@vnp's code is solid and helpful, but his stringify_state_helper is a single-purpose function, and still leaves a degree of repetition and memory management in stringify_state. I'd rather have general-purpose to_string that takes printf-style arguments, allocates sufficient space for the converted result, and prints into that space, and returns the result:

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

char *to_string(char const *fmt, ...) {
    va_list args;
    va_start(args, fmt);

    va_list args_dupe;
    va_copy(args_dupe, args);

    int size = vsnprintf(NULL, 0, fmt, args);

    char *ret = malloc(size+1);

    if (ret != NULL)
        vsnprintf(ret, size+1, fmt, args_dupe);

    va_end(args);
    va_end(args_dupe);

    return ret;
}

In fairness, this does require a little more code, and the v*printf functions (and argument-list macros) are a bit less known, so some may find it a bit more difficult to understand.

On the other hand, in exchange for that bit of extra investment, we get something that's more general, and works much more as I think most people would expect--for example, something like this:

char *s = to_string("%d, %d", 1, 2);

Using this, stringify_state should turn out something like this:

char* stringify_state(State* state) {
    Pet* p = state->pet;
    Settings* s = state->settings;

    return to_string("%lld %f %f %f %f %f %f %f %f %f %f",
                     state->last_update_time,
                     p->health,
                     p->max_health,
                     p->satiation,
                     p->max_satiation,
                     s->milliseconds_per_tick,
                     s->hunger_pain_per_tick,
                     s->hunger_per_tick,
                     s->satiated_heal_per_tick,
                     s->pain_per_wrong_answer,
                     s->satiation_per_right_answer);
}

Levels of abstraction

It may just be a pet peeve of mine, but I think this divides into cleaner layers of abstraction. With your original code, we have a single function that mixes a fairly high level of abstraction (format a State into a string) with lower levels of abstraction (e.g., memory management).

@vnp's code sort of inverts the layers of abstraction, so we have the higher level of abstraction at the bottom, and the lower level of abstraction above it.

This one gets the layers of abstraction closer to how I'd like to see them: the memory management and general purpose stringifying is at the bottom of the stack, and the more specific higher level concern of Stringifying a State is at an upper layer. So, something like a call graph accurately reflects the levels of abstraction being dealt with in the code.

Other Points

Given the number (and length) of arguments you're passing, I'd prefer to see the arguments passed one per line as I've formatted them above, rather than a variable number per line to justify out to some particular right margin.
Since stringify_state isn't intended to modify the State whose address is being passed, it's probably better to define the parameter as a State const *. Likewise with the local variables, so the first lines would probably be better written something like this:

char* stringify_state(State const* state) {
    Pet const* p = state->pet;
    Settings const* s = state->settings;


LINQ queries to generate a report on accrued work time on projects

I've thought about a factory method, but that won't work because it
  can't be translated to SQL by the expression interpreter.

Why don't you call (as suggested by t3chb0t) AsEnumerable() right before your factory method? You would perform the factory method in memory.

 var project = entities.Tickets
        .Where(p => p.ID == id)
        .AsEnumerable()   // <-- loads the tickets into memory
        .Select(p => myFactoryMethod(p))
        .Single();


StringBuilder in C v2: Not a charged dance

The main reason why C don't have a system like that is because that produce some overhead. But I suppose you know this and want the less overhead possible and this system.

The two following lines are not C idiomatic:

struct StringBuilder;
typedef struct StringBuilder *StringBuilder;

Of course, they are two side about this, I will give you my vision. You should not hide the implementation of structure in C. Why? Because C is design to trust the user, if your user want to "play" with his data, you can't prevent it. C allow user to hack easily and this could improve the use of your library. For example, if your library don't have a code functionality the user could code it.

The second problem is that you hide the pointer in the typedef. You should not hide pointer, this made the code hard to read. And the user could think that this is not a pointer and try to write StringBuilder *foo;. A answer about this is available on stackoverflow.

For the following, I will assume that the user know that you hide the pointer and I will use explicit struct StringBuilder in the code.

Next I will talk about your function sb_new(), first I think you should not allocate the structure StringBuilder, this made a lot of overhead. You should separate your function into two sb_new() and sb_init(), one if the user want allocate the structure and one if the user take care of it.

Plus, you use calloc(), this add a lot of useless overhead. You should use malloc(). If the user want to affect the string by zero you should implement an other function for it, like sb_unused_zero().

And, if the user want a zero size string you send NULL, I don't see the point. Maybe you should use this value for tell to the function to use a default value like 42.

A detail about your call of malloc(), you could write struct StringBuilder *ret = malloc(sizeof *ret);, this is more readable and you can read this answer about it. You don't need to use sizeof char because by definition the is equal to 1.

Example:

struct StringBuilder *sb_new(size_t init_cap) {
    struct StringBuilder *sb = malloc(sizeof *sb);
    if (!sb) return NULL;
    if (!sb_init(sb, init_cap)) {
        free(sb);
        return NULL;
    }
    return sb;
}

bool sb_init(struct StringBuilder *sb, size_t init_cap) {
    init_cap = init_cap == 0 ? 42 : init_cap;
    sb->mem = malloc(init_cap);
    if (!sb->mem) return false;
    sb->count = 0;
    sb->cap = init_cap;
    return true;
}

void sb_unused(struct StringBuilder *sb, char c) {
    memset(sb->mem + to->count, c, sb->cap - sb->count);
}

This allow the user to do the following:

struct foo {
    struct StringBuilder sb;
};

int main(void) {
    struct foo foo;
    sb_init(&foo.sb, 0);
}

Let talks about sb_append(), you don't check the potential overflow when you multiply by your LOAD_FACTOR, so you have an undefined behavior.

In this function, you affect new allocate byte to zero, this is again a big overhead that is useless in most of use cast. Again, the user should use the sb_unused() function that affect unused byte in your string. Plus, you suppose that your LOAD_FACTOR is equal to 2 in your use of memset().

bool sb_append(StringBuilder sb, char c) {
    if (sb->count + 1 == sb->cap) {
        if (SIZE_MAX / LOAD_FACTOR < sb->cap) return false; // this could be improve
        size_t new_cap = sb->cap * LOAD_FACTOR;
        char *new_mem = realloc(sb->mem, new_cap);
        if (!new_mem) return false;
        sb->mem = new_mem;
        sb->cap = new_cap;
    }
    sb->mem[to->count++] = c;
    return true;
}

Your next function sb_as_string() suppose that mem is already a valid c-string, maybe you should verify that your string contain a nil terminate byte.

I almost finish, the function sb_free_copy() has a strange name, maybe rename it to something like sb_into_string(). And your implementation is strange you add yourself the nil terminate byte contrary to the function sb_as_string(), more strcpy() already do it. Whatever, you should use memcpy() because you already know the good size to copy this would be faster.

Just a detail in sb_free() you verify that sb->mem is not NULL but free() handle this, so this is useless and add overhead.

Finally, maybe your structure should be rename String because I think the user could use it to keep dynamic string and not to transform it into standard c-string?

The last thing is about your use about bool, this limit the detail about the error. Maybe you could replace it by an enum of just an int that will give you more flexibility about error report.