Using bucket sort to rank students based on their marks Problem:

  n students have marks and names. Rank students based on their marks and print their names.

#include <stdio.h>
#include <assert.h>

struct student
{
    int marks;
    char name[50];
};

struct listnode
{
    struct student * data;
    struct listnode *next;
};

addtofrontoflist(struct listnode *listhead,struct student *node)
{
    //make a block of listnode.
    struct listnode bucketnode;
    bucketnode.data=node;

    struct listnode *tmp;
    tmp=listhead->next;
    listhead->next=&bucketnode;
    bucketnode.next=tmp;
}

bucket_sort(struct student array[],int n)
{
    struct listnode *buckets[n];
    int i,j;
    struct listnode *temp;
    for(i=0;i<n;i++)
    {
            buckets[i]=malloc(sizeof(struct listnode));
            assert(buckets[i]!=NULL);
    }

    for(i=0;i<n;i++)
    {
            addtofrontoflist(buckets[array[i].marks],&array[i]);
    }

    for(i=0;i<n;i++)
    {
            if(buckets[i]==NULL) continue;
            for(temp=buckets[i];temp!=NULL;temp++)
            printf("%d %s\n",temp->data->marks,temp->data->name);
    }
}

main()
{
    struct student array[5]={"1,one","2,two","2,two","4,four","1,one"};
    bucket_sort(array,5);
}

Since your functions have no explicit return types (and surely you've compiled this), you must be implementing this under an older C standard that allowed for implicit return types.

Regardless, I would recommend adding explicit return types to your functions:

main() should return an int as it is supposed to return an integer value based on the program's execution outcome (either 0 for success or 1 for failure).  However, if it will always execute successfully, then you can omit the return 0 at the end.
The other functions should return void as they're not already returning anything.

You may typedef your structs to avoid having to type struct elsewhere.
You're inconsistently using snake_case naming and all-lowercase.  The latter is not very readable as compound words should be separated.  Since you're already using snake_case, just use that for all of your variable and function naming here.
marks should probably just be mark as it's just a single variable.  But if a student is supposed to have more than one, then marks should be an array.  Also, must this be an integer type, or can a student have a decimal value as a mark?  This would of course depend on how you want to implement this grading system.
The variable j declared in bucket_sort() is unused, so it should be removed.  You should have your compiler warnings up high so that you'll be told when this occurs.
You should add whitespace between operators for readability.  Keeping lines shorter would not be of much benefit as you should try not to have so much code on one line.

For instance, one of your for loops:

for(i=0;i<n;i++)

would look like this:

for (i = 0; i < n; i++)

And your array:

struct student array[5]={"1,one","2,two","2,two","4,four","1,one"};

should have its elements separated:

struct student array[5] = { "1,one", "2,two", "2,two", "4,four", "1,one" };

I'd recommend having a macro for the number of students:

#define NUM_STUDENTS 5

You can use this macro for the array size and anything else, and in case you'll ever need to change this number, this will be done in just one place.

In addition, bucket_sort() will no longer need to take a size.

student array[NUM_STUDENTS] = { "1,one","2,two","2,two","4,four","1,one" };
bucket_sort(array);


Calculating number of unharmed leaves I recently came across this problem that asks you to print the number of leaves not eaten by the caterpillars:

  As we all know caterpillars love to eat leaves. Usually, a caterpillar
  sits on leaf, eats as much of it as it can (or wants), then stretches
  out to its full length to reach a new leaf with its front end, and
  finally "hops" to it by contracting its back end to that leaf.

  We have with us a very long, straight branch of a tree with leaves
  distributed uniformly along its length, and a set of caterpillars
  sitting on the first leaf. (Well, our leaves are big enough to
  accommodate upto 20 caterpillars!). As time progresses our
  caterpillars eat and hop repeatedly, thereby damaging many leaves. Not
  all caterpillars are of the same length, so different caterpillars may
  eat different sets of leaves. We would like to find out the number of
  leaves that will be undamaged at the end of this eating spree. We
  assume that adjacent leaves are a unit distance apart and the length
  of the caterpillars is also given in the same unit.

  For example suppose our branch had 20 leaves (placed 1 unit apart) and
  3 caterpillars of length 3, 2 and 5 units respectively. Then, first
  caterpillar would first eat leaf 1, then hop to leaf 4 and eat it and
  then hop to leaf 7 and eat it and so on. So the first caterpillar
  would end up eating the leaves at positions 1,4,7,10,13,16 and 19. The
  second caterpillar would eat the leaves at positions
  1,3,5,7,9,11,13,15,17 and 19. The third caterpillar would eat the
  leaves at positions 1,6,11 and 16. Thus we would have undamaged leaves
  at positions 2,8,12,14,18 and 20. So the answer to this example is 6.

Fortunately, the question is easy and can put a workable code in a decent time. The problem is that it is probably taking more memory than expected, because all the test cases run fine in my PC, but one of them gives a runtime error when run on the servers. How can this be improved?

#include <iostream>
#include <vector>
#include <algorithm>

int main (int argc, char const* argv[])
{
    long long n , k;
    std::cin >> n >> k;
    std::vector<int> caterpillars;
    std::vector<long long>v;
    for(int i=0;i<k;i++){
        int a;
        std::cin >> a;
        caterpillars.push_back(a);
    }
    for(int i=0;i<k;i++){
        for(int j=0;caterpillars[i]*j +1 <= n;j++){
            int temp = caterpillars[i] * j +1;
            v.push_back(temp);
        }
    }
    sort(v.begin(),v.end());
    int number = 0;
    long long prev = 0;
    for(int i=0;i<v.size();i++){
        if(v[i] != prev){
            number++;
        }
        prev = v[i];
    }
    std::cout << n - number << std::endl;
    return 0;
}

And here is that particular testcase which is causing problems:

762744433 19
96412 40852 19611 563380 236733 559627 750968 413673 300332 65 682403 441221 180068 668364 493413 443706 613246 715846 728157

Uses too much memory, and too much time

Your current solution works but uses too much memory.  The problem requirement specifies maximum 16 MB memory to be used.  Your program uses 4 bytes for each number reached including duplicates.  Given the maximum n of 1000000000, maximum caterpillars of 20, and worst case of each caterpillar having value 2, your program would require 40 GB of memory to solve that case.

Also, your program takes too long to run.  Given the worst case scenario mentioned above, your program would need to iterate 10 billion times.  Even at a rate of 1 billion iterations per second, that would take 10 seconds and your time limit is 3.

I will describe some incremental improvements to your solution to fix the memory issue, and then describe a completely different approach that solves the time issue as well.

Slightly better: use sieve approach

Instead of adding reached numbers to a vector and then sorting, you can do better by creating a std::bitset or vector<bool> to store which numbers were reached.  For example, you could create a vector<bool> of size n+1, and then as you reach each number, you set reached[num] = true.  At the end, you scan the vector to count many numbers are unreached.  Assuming that vector<bool> uses 1 bit per element, this solution requires 125 MB of memory, which is still larger than permitted.  However, this at least won't crash your computer if you run it.  Here is a sample solution:

#include <iostream>
#include <vector>
#include <algorithm>

int main (int argc, char const* argv[])
{
    long long n , k;
    std::cin >> n >> k;
    std::vector<int> caterpillars;
    std::vector<long long>v;
    for(int i=0;i<k;i++){
        int a;
        std::cin >> a;
        caterpillars.push_back(a);
    }
    std::vector<bool> reached(n);
    for(int i=0;i<k;i++){
        int val = caterpillars[i];
        for(int j=0;j < n;j+= val) {
            reached[j] = true;
        }
    }
    int unreached = 0;
    for(int j=0;j < n;j++) {
        if (!reached[j])
            unreached++;
    }
    std::cout << unreached << std::endl;
    return 0;
}

This program solved the "tough case" 762744433 19 ... in 0.9 seconds on my computer.  However, on the worst case of 1000000000 20 2 2 2 2 ..., it took 16 seconds to solve, which exceeds the time limit of 3 seconds.

Next improvement: use fixed amount of memory

To keep your program within the 16 MB memory limit, you need to do the sieving in segments instead of all at once.  For example, you can compute the solution in segments of 1000000, using only 125 KB of memory for the vector<bool>.  Here is an example of how you can do that:

#include <iostream>
#include <vector>
#include <algorithm>

#define BUFSIZE        1000000

int main (int argc, char const* argv[])
{
    long long n , k;
    std::cin >> n >> k;
    std::vector<int> caterpillars;
    std::vector<long long>v;
    for(int i=0;i<k;i++){
        int a;
        std::cin >> a;
        caterpillars.push_back(a);
    }
    std::vector<bool> reached(BUFSIZE);
    int unreached = 0;
    for(int i=0;i<n;) {
        int size = n-i;
        if (size > BUFSIZE)
            size = BUFSIZE;
        std::fill(reached.begin(), reached.end(), false);
        for (int j=0;j<k;j++) {
            int val = caterpillars[j];
            int first = (i % val);
            if (first != 0)
                first = val - first;
            for (int r = first; r < size; r += val)
                reached[r] = true;
        }
        for (int r = 0; r < size; r++) {
            if (!reached[r])
                unreached++;
        }
        i += size;
    }
    std::cout << unreached << std::endl;
    return 0;
}

Similar to the previous program, this program also solved the "tough case" in 0.9 seconds.  It took 14 seconds to solve the worst case, though.  Although there are some optimizations that could be made, it seems that a new algorithm might be needed.

A different approach

This problem is somewhat reminiscent of the FizzBuzz problem.  In FizzBuzz, each number divisible by 3 is Fizz, each number divisible by 5 is Buzz, and each number divisible by both 3 and 5 is FizzBuzz.  If I asked how many numbers between 1 and n are one of Fizz/Buzz/FizzBuzz, you could come up with a \$O(1)\$ solution instead of an \$O(n)\$ solution.

If you think about it a little, n/3 numbers are either Fizz or FizzBuzz, and n/5 numbers are either Buzz or FizzBuzz, and n/15 numbers are FizzBuzz.  So the count of "named" numbers is n/3 + n/5 - n/15.

You can transfer this approach to the caterpillar problem.  Given 2 caterpillars of length a b, the number of leaves eaten is n/a + n/b - n/lcm(a,b), where lcm() is the least common multiple of a and b.

Now you can extend the approach for 3 caterpillars.  With three caterpillars of length a b c, you can have leaves eaten by a, b, c, ab, bc, ac, or abc, where ab means eaten by both a and b.  After doing some reasoning on this, you would come up with the formula:

Leaves eaten = n/a + n/b + n/c - n/lcm(a,b) - n/lcm(b,c) - n/lcm(a,c) + n/lcm(a,b,c)

The formula generalizes to:

Leaves eaten = Sum(n/one) - Sum(n/two) + Sum(n/three) - Sum(n/four) + Sum(n/five) - ...

where Sum(n/five) means the sum of all combinations of the form n/lcm(five caterpillars).

To solve using this method, you need to generate each combination of caterpillars.  With 20 caterpillars, this means you need to go through each of the \$2^{20}\$ combinations, which is actually only 1 million combinations so it should complete quickly.  In general, with \$k\$ caterpillars, this solution solves the problem in \$O(2^k)\$ time.  So you definitely do not want to use this solution with a large number of caterpillars.

I wrote a sample solution that used recursion to generate each combination.  The solve() function tries two cases: including the current caterpillar or not including it, and recurses to the next caterpillar for each case.  You can easily see that this generates 2^k cases.

Here is my solution using this approach:

#include <iostream>
#include <vector>
#include <algorithm>

// Returns greatest common divisor of a and b.
static inline int gcd(int a, int b)
{
    while (b != 0) {
        int tmp = b;
        b = a % b;
        a = tmp;
    }
    return a;
}

// Returns least common multiple of a and b.
static inline long long lcm(int a, int b)
{
    a /= gcd(a, b);
    return (long long) a * b;
}

static int solve(std::vector<int> caterpillars, int curCaterpillar,
        int numUsed, int curLcm, int n)
{
    if (curCaterpillar >= caterpillars.size())
        return 0;

    int val = caterpillars[curCaterpillar];
    int reached = 0;

    // Include current caterpillar:
    long long newLcm = lcm(curLcm, val);
    if (newLcm <= n) {
        if (numUsed & 1)
            reached -= n / newLcm;
        else
            reached += n / newLcm;
        reached += solve(caterpillars, curCaterpillar+1, numUsed+1, newLcm, n);
    }

    // Do not include current caterpillar:
    reached += solve(caterpillars, curCaterpillar+1, numUsed, curLcm, n);

    return reached;
}

int main (int argc, char const* argv[])
{
    long long n , k;
    std::cin >> n >> k;
    std::vector<int> caterpillars;
    std::vector<long long>v;
    int reached = 0;

    for(int i=0;i<k;i++){
        int a;
        std::cin >> a;
        caterpillars.push_back(a);
    }
    n--;
    reached = solve(caterpillars, 0, 0, 1, n);
    std::cout << n - reached << std::endl;
    return 0;
}

This solution solved the "tough case" in 0.01 seconds on my computer, and solved the "worst case" in 0.46 seconds.

There are further optimizations that could be made, such as filtering out caterpillars that are multiples of each other before starting the algorithm.  Such caterpillars can be removed without changing the result.  Using that optimization, the worst time I got for any input I tried was 0.08 seconds.


Pad a ragged multidimensional array to rectangular shape For some machine learning purpose, I need to work with sequences with different lengths. To be able to process efficiently those sequences, I need to process them in batches of size size_batch. A batch typically has 4 dimensions and I want to convert it to a numpy's ndarray with 4 dimensions. For each sequence, I need to pad with some defined pad_value such that each element has the same size: the maximal size.

For example, with 3 dimensional input:

[[[0, 1, 2],
  [3],
  [4, 5]],
 [[6]],
 [[7, 8],
  [9]]]

desired output for pad_value -1 is:

[[[0, 1, 2],
  [3, -1, -1],
  [4, 5, -1]],
 [[6, -1, -1],
  [-1, -1, -1],
  [-1, -1, -1]]
 [[7, 8, -1],
  [9, -1, -1],
  [-1, -1, -1]]]

which has shape (3, 3, 3).
For this problem, one can assume that there are no empty lists in the input.
Here is the solution I came up with:

import numpy as np
import itertools as it
from typing import List

def pad(array: List, pad_value: np.int32, dtype: type = np.int32) -> np.ndarray:
    """ Pads a nested list to the max shape and fill empty values with pad_value

    :param array: high dimensional list to be padded
    :param pad_value: value appended to
    :param dtype: type of the output
    :return: padded copy of param array
    """
    # Get max shape
    def get_max_shape(arr, ax=0, dims=[]):
        try:
            if ax >= len(dims):
                dims.append(len(arr))
            else:
                dims[ax] = max(dims[ax], len(arr))

            for i in arr:
                get_max_shape(i, ax+1, dims)
        except TypeError:  # On non iterable / lengthless objects (leaves)
            pass

        return dims

    dims = get_max_shape(array)

    # Pad values
    def get_item(arr, idx):
        while True:
            i, *idx = idx
            arr = arr[i]
            if not idx:
                break
        return arr

    r = np.zeros(dims, dtype=dtype) + pad_value
    for idx in it.product(*map(range, dims)):
        # idx run though all possible tuple of indices that might
        # contain a value in array
        try:
            r[idx] = get_item(array, idx)
        except IndexError:
            continue

    return r

It does not feel really pythonic but does the job. Is there any better way to do it I should know ? I think I might be able to improve its speed by doing smart breaks in the last loop but I haven't dug much yet.

nested methods

Why do you nest the get_max_shape etcetera in the pad? There is no need to do this.

get_max_shape

Here you use recursion and a global variable. A simpler way would be to have a generator that recursively runs through the array, and yields the level and length of that part, and then another function to aggregate this results. That way you can avoid passing

def get_dimensions(array, level=0):
    yield level, len(array)
    try:
        for row in array:
            yield from get_dimensions(row, level + 1)
    except TypeError: #not an iterable
        pass

[(0, 3), (1, 3), (2, 3), (2, 1), (2, 2), (1, 1), (2, 1), (1, 2), (2, 2), (2, 1)]

The aggregation can be very simple using collections.defaultdict:

def get_max_shape(array):
    dimensions = defaultdict(int)
    for level, length in get_dimensions(array):
        dimensions[level] = max(dimensions[level], length)
    return [value for _, value in sorted(dimensions.items())]

[3, 3, 3]

creating the result

Instead of r = np.zeros(dims, dtype=dtype) + pad_value you can use np.full

You iterate over all possible indices, and check whether it is present in the original array. Depening on how "full" the original array is, this can save some time. It also allows you to do this without your custom get_item method to get the element at the nested index

def iterate_nested_array(array, index=()):
    try:
        for idx, row in enumerate(array):
            yield from iterate_nested_array(row, (*index, idx))
    except TypeError: # final level
        for idx, item in enumerate(array):
            yield (*index, idx), item

[((0, 0, 0), 0),
 ((0, 0, 1), 1),
 ((0, 0, 2), 2),
 ((0, 1, 0), 3),
 ((0, 2, 0), 4),
 ((0, 2, 1), 5),
 ((1, 0, 0), 6),
 ((2, 0, 0), 7),
 ((2, 0, 1), 8),
 ((2, 1, 0), 9)]

slice

an even better way, as suggested by@hpaulj uses slices:

def iterate_nested_array(array, index=()):
    try:
        for idx, row in enumerate(array):
            yield from iterate_nested_array(row, (*index, idx))
    except TypeError: # final level
        yield (*index, slice(len(array))), array

[((0, 0, slice(None, 3, None)), [0, 1, 2]),
 ((0, 1, slice(None, 1, None)), [3]),
 ((0, 2, slice(None, 2, None)), [4, 5]),
 ((1, 0, slice(None, 1, None)), [6]),
 ((2, 0, slice(None, 2, None)), [7, 8]),
 ((2, 1, slice(None, 1, None)), [9])]

padding

def pad(array, fill_value):
    dimensions = get_max_shape(array)
    result = np.full(dimensions, fill_value)
    for index, value in iterate_nested_array(array):
        result[index] = value
    return result

array([[[ 0,  1,  2],
        [ 3, -1, -1],
        [ 4,  5, -1]],

       [[ 6, -1, -1],
        [-1, -1, -1],
        [-1, -1, -1]],

       [[ 7,  8, -1],
        [ 9, -1, -1],
        [-1, -1, -1]]])


Cross context joins in .NET This is how I made a cross context join.

What do you think?

How would you do this better?

using (var context = ContextFactory.Create())
{
    var users =  await context
                         .Users.AsNoTracking()
                         .OrderBy(user => user.DisplayName)
                         .Where(user => user.AccountName.Contains(query))
                         .Select(user => new UserProfileDTO
                         {
                             Id = user.Id,
                             DisplayName = user.DisplayName,
                         })
                         .ToListAsync().ConfigureAwait(false);

    foreach (var user in users)
    {
        var entity = await context.UserInfos.FindAsync(user.Id).ConfigureAwait(false);
        if (entity != null)
            user.HasPicture = entity.HasPicture == true ? true : false;
    }

    return users;
}

You can get the results with a single query like this one:

var result = await
    (from u in context.Users
     join ui in context.UserInfos on u.Id equals ui.UserId
     where u.AccountName.Contains(query) && ui.HasPicture
     select new UserProfileDTO
     {
         Id = u.Id,
         DisplayName = u.DisplayName,
     }
    ).ToListAsync().ConfigureAwait(false);

This would select all users with a picture in their user-info.

I assumed the UserInfo table has a foreign-key UserId that you can use for joining both tables.

This by the way

user.HasPicture = entity.HasPicture == true ? true : false;

is the same as:

user.HasPicture = entity.HasPicture;


Unit testing legacy code with static classes I am adding new functionality into a legacy application. For my new classes I have introduced Unit Testing. I still need to work with the existing code.

One of the problems I face is that a lot of static methods have been used.

Below is an example of a class I need to use:

public class HelperClass
{
    public static bool ReturnSomething()
    {
        return true;
    }
}

My fix for making this testable:

public interface IHelperClass
{
    bool ReturnSomething();
}

public class HelperClass : IHelperClass
{
    public static bool ReturnSomething()
    {
        return true;
    }

    bool IHelperClass.ReturnSomething()
    {
        return ReturnSomething();
    }
}

A class that used to use the static method, but by introducing a property (initialized by the constructor), that now uses the testable class. I can inject a mock using this property.
Note that I could have used a factory for injecting the mock, however I wanted to keep it simple for the example.

public class UserClass
{
    public UserClass()
    {
        // Initialize with default
        HelperClass = new HelperClass();
    }

    public IHelperClass HelperClass { get; set; }
}

My advantages:

No need to modify existing code that is using the static class
Code can be migrated from static to a testable instance
I can reuse the existing concrete class

My disadvantages:

Needed to modify legacy code that needs to be tested. Not always possible when in external assembly.
PropertyName is the same as the class Name

I welcome any feedback!

I happen to like your fix for making it testable, but would reverse the implementation order between the static method and the explicit interface method. This will allow you to slowly change existing code first to use the Singleton instead of the static and then finally use an injectable pattern:

public interface IHelperClass
{
    bool ReturnSomething();
}

public sealed class HelperClass : IHelperClass
{
    private static readonly IHelperClass instance = new HelperClass();

    private HelperClass()
    {
    }

    public static IHelperClass Instance
    {
        get
        {
            return instance;
        }
    }

    [Obsolete("Use the Instance singleton's implementation instead of this static method.")]
    public static bool ReturnSomething()
    {
        return Instance.ReturnSomething(); // Simply calls the Singleton's instance of the method.
    }

    bool IHelperClass.ReturnSomething()
    {
        return true; // The original static ReturnSomething logic now goes here.
    }
}


Tic-Tac-Toe code in C++ I wrote this as an exercise. I think that I have some repetitive code in the "winner" function but I don't know exactly how to reduce it. Any other general advice would be welcome too.

#include<iostream>
#include<iomanip>

char table[3][3];
int turn=1;

void print_table()
{
    for (int i=0;i<3;i++)
    {
        for (int j=0;j<3;j++)
            std::cout<<std::setw(3)<<table[i][j];
    std::cout<<std::endl;
    }
}

void create_table()
{
    for (int i=0;i<3;i++)
        for (int j=0;j<3;j++)
            table[i][j]='*';
}

void input(int turn)
{
    int x=0,y=0;
    std::cin>>x>>y;
    if(turn%2==1)
        table[x][y]='X';
    else
        table[x][y]='O';
}

char winner()
{
    for(int i=0;i<3;i++)
        if(table[0][i]==table[1][i]&&table[1][i]==table[2][i]&&table[0][i]=='X')
        {
            return 'X';
        }

    for(int i=0;i<3;i++)
        if(table[i][0]==table[i][1]&&table[i][1]==table[i][2]&&table[i][0]=='X')
        {
            return 'X';
        }

        for(int i=0;i<3;i++)
        if(table[0][i]==table[1][i]&&table[1][i]==table[2][i]&&table[0][i]=='O')
        {
            return 'O';
        }

    for(int i=0;i<3;i++)
        if(table[i][0]==table[i][1]&&table[i][1]==table[i][2]&&table[i][0]=='O')
        {
            return 'O';
        }

      if(table[0][0]==table[1][1]&&table[0][0]==table[2][2]&&table[0][0]=='O')
      {
            return 'O';
      }

      if(table[0][0]==table[1][1]&&table[0][0]==table[2][2]&&table[0][0]=='X')
      {
            return 'X';
      }

      return '\0'; ///default
}

int main(){

create_table();
print_table();

while (turn<=9&&winner()=='\0')
{
input(turn);
print_table();
winner();
turn++;
}

if(winner()!='\0')
    std::cout<<std::endl<<"winner:"<<winner();
else
    std::cout<<"Draw.";
}

1. Simplified winner() method

You could merge the checks for 'X' and 'O' by returning one of the chars in a match of three in a row:

char winner() {
  for (int i = 0; i < 3; i++) {
    if (table[0][i] == table[1][i] && table[1][i] == table[2][i]) {
      return table[0][i]; // 'X' if all are 'X' and 'O' if all are 'O'
    }
  }

  for (int i = 0; i < 3; i++) {
    if (table[i][0] == table[i][1] && table[i][1] == table[i][2]) {
      return table[i][0];
    }
  }

  if (table[0][0] == table[1][1] && table[1][1] == table[2][2]) {
    return table[1][1];
  }

  if (table[0][2] == table[1][1] && table[1][1] == table[2][0]) { // *
    return table[1][1];
  }

  return '\0';
}

*Note that your code is missing the forward slash diagonal

2. Consider eliminating your global variables

I know this is just a practice project, and your code is fine as it is. However, if you wanted to scale your code, then you've created some unnecessary problems for yourself in the future.

All of your functions depend on your two global variables, which limits you to one game and gets in the way of other features by polluting the global namespace. You could eliminate the globals by taking an object oriented approach or a more functional programming styled approach.

The Object Oriented way

The OO way would involve creating a TicTacToeGame class and making the global variables member variables members of your class.

class TicTacToeGame() {
private:
  char table[3][3];
  int turn;

public:
  TicTacToeGame() {
    for (int i=0;i<3;i++)
      for (int j=0;j<3;j++)
        table[i][j]='*';

    turn = 1;
  }

  char winner() {}

  void input() {
    // ...
    turn++;
  }

  void print() {}

  int getTurn() {
    return turn;
  }
}

int main() {

  TicTacToeGame game = TicTacToeGame();
  game.print();

  while (game.getTurn() <= 9 && game.winner() == '\0')
  {
    game.input();
    game.print();
    game.winner();
  }

  if(game.winner() != '\0')
    std::cout<<std::endl<<"winner:"<<winner();
  else
    std::cout<<"Draw.";
}

Creating a class comes with a few other benefits. Particularly that you can encapsulate how a Tic-tac-toe game is played which helps with code scalability.

A more functional approach

For the functional approach you can just pass the globals as parameters instead (be sure to pass by reference):

char[][] create_table() {
  // ...
  return table;
}

void input (int turn, char[][] &table) {
  // ...
}

char winner(char[][] &table) {
  // ...
}

int main() {

  int turn = 1;
  char[][] table = create_table();
  print_table(table);

  while (turn <= 9 && winner(table) == '\0') {
    input(turn, table);
    print_table(table);
    winner(table);
    turn++;
  }

  if(winner(table) != '\0')
    std::cout<<std::endl<<"winner:"<<winner(table);
  else
    std::cout<<"Draw.";
}

This way gives you a lot more control over when and where turn and board get declared. You can more easily create multiple games to be played simultaneously. The biggest benefit is that your functions have their dependencies explicitly defined; there are no hidden parameters.

Nice job overall! My second suggestion is mostly just to help with a few concepts with software development, and it isn't really applicable if you intend to keep your Tic-tac-toe game as simple as it is. Keep up the good work.


Creating an Array of Linked Lists from a BST Question

  Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)

Here is my attempt at a solution. I haven't test it, but I was trying to get feedback on whether or not this would be an appropriate approach to such solution.

public class solution {

    ArrayList<LinkedList<Node>> makeArrayList(Node n) {
        int level = 0;
        return addLists(new ArrayList<LinkedList<Node>>(), n, level);
    }

    ArrayList<LinkedList<Node>> addLists(ArrayList<LinkedList<Node>> arr, Node n, int level) {
        if (n != null) {
            if (arr.get(level) == null) {
                LinkedList<Node> newList = new LinkedList<Node>();
                arr.add(level, newList);
            }
            LinkedList<Node> nodeList = arr.get(level);
            nodeList.add(n);
            addLists(arr, n.leftChild, level + 1);
            addLists(arr, n.rightChild, level + 1);
        }
        return arr;
    }
}

Your return types and the types left of the assignments should be as general as possible, so you only need to change the instantiation if you want to change the implementation to an other type of list.

List<Node>
List<List<Node>>

In general it is a good idea to replace ifs that covers the whole function by a guard condition. So you get rid of a level of nesting.

{
    if (n == null) return arr;
    if (arr.get(level) == null) arr.add(level, new LinkedList<Node>());

    arr.get(level).add(n);
    addLists(arr, n.leftChild, level + 1);
    addLists(arr, n.rightChild, level + 1);

    return arr;
}

I only checked your code layout. If you want to see if it works, write a test as tb     suggested.


Several simple calculators on one page For my students (I am an Austrian math teacher) I would like to provide some simple online calculators on my blog.
Let's say there are two pages on my website("Circle" and "Cube") and on every page I want to have about 10 different calculators.
Here is an example of one page with two calculators:

My code
JSFiddle
HTML

Circle

Calculate circumference of circle

 Radius of circle: <input type="text" id="calc1-input"> <button onclick="calc1()">Calculate</button>

Circumference of circle:

Calculate area of circle

 Radius of circle: <input type="text" id="calc2-input"> <button onclick="calc2()">Calculate</button>

Area of circle:

Javascript
function commaToDot(number) {
    return parseFloat(number.replace(',','.').replace(' ',''));
}

function dotToComma(number){
    return number.toString().replace('.',',');
}

function calc1() {
    var input = document.getElementById("calc1-input").value;
    input = commaToDot(input);
    if (isNaN(input)) {
        document.getElementById('calc1-output').innerHTML = "Please enter a number!";
    } else {
      var output = 2 * Math.PI * input;
        document.getElementById('calc1-output').innerHTML = dotToComma(output);
    }
}

function calc2() {
    var input = document.getElementById("calc2-input").value;
    input = commaToDot(input);
    if (isNaN(input)) {
        document.getElementById('calc2-output').innerHTML = "Please enter a number!";
    } else {
      var output = Math.PI * Math.pow(input,2);
        document.getElementById('calc2-output').innerHTML = dotToComma(output);
    }
}

Explanation

Input: In my country we use commas as decimal separators.
So the students write 55,5 instead of 55.5 (see commaToDot()).
Output: The students expect the output to be with comma decimal separator, too (see dotToComma()).
Error: If the input is not a number (if (isNaN(input))) an error message will be displayed instead of the calculation result.

Questions

I see a lot of redundance in my code but I don't know how to improve it.
The only difference between calc1() and calc2() is the formula.
Maybe it is possible to improve the naming of the variables/functions?

calc1 and calc2 are really bad names. Names should always clearly describe what they are for or do. calculateCircleCircumference and calculateCircleArea would be better
choices.
I'm not a big fan of the names commaToDot and commaToDot either. I'd prefer more conceptional names such as parseNumber and formatNumber, maybe even parseGermanNumber and formatGermanNumber.
A slightly better HTML structure would be in order: Each calculator could be surrounded by a <form> element and there is an <output> element specifically for display calculation results.
In current JavaScript one should prefer const and let over var.
The following suggestions may introduce concepts, that the students haven't learnt yet, but they are considered good conventions.
For a better separation of layout and logic it is usually suggested not to use on... event handler attributes, but instead assign them using addEventListener.
Also one should move all element look ups to the initialization. This could look like this (notice the changed IDs):
const circleCircumferenceRadiusInput = document.getElementById("circle-circumference-radius-input");
const circleCircumferenceOutput = document.getElementById('circle-circumference-output');

function calculateCircleCircumference() {
    // Using separate variables so "const" can be used.
    const inputString = circleCircumferenceRadiusInput.value;
    const input = commaToDot(inputString);
    if (isNaN(input)) {
      circleCircumferenceOutput.innerHTML = "Please enter a number!";
    } else {
      const output = 2 * Math.PI * input;
      circleCircumferenceOutput.innerHTML = dotToComma(output);
    }
}

document.getElementById('circle-circumference-button').addEventHandler("click", calculateCircleCircumference);

This can be simplified a bit by wrapping HTML of the calculator in an <form> element and referring to the needed elements by name. Also I'm wrapping the code in an initialization function to avoid lots of global variables. Both of these prepare for generalizing and reusing the code.
<form id="circle-circumference">

Calculate circumference of circle

    Radius of circle: <input type="text" name="radius"> <button name="execute">Calculate</button>

    Circumference of circle: <output name="output"></output>

</form>

function initCircleCircumferenceCalculator(form) {
  const radiusInput = form.elements["radius"];
  const outputElement = form.elements["output"];

  function calculate() {
    const inputString = radiusInput.value;
    const input = commaToDot(inputString);
    if (isNaN(input)) {
      outputElement.innerHTML = "Please enter a number!";
    } else {
      const output = 2 * Math.PI * input;
      outputElement.innerHTML = dotToComma(output);
    }
  }

  form.elements["execute"].addEventHandler("click", calculate);
}

initCircleCircumferenceCalculator(document.getElementById("circle-circumference"));

Now that we have the initialization function it's easier to generalize this so that it can be used for multiple calculators:
function initCalculator(form, inputName, calculationFunction) {
  const inputElement = form.elements[inputName];
  const outputElement = form.elements["output"];

  function calculate() {
    const inputString = inputElement.value;
    const input = commaToDot(inputString);
    if (isNaN(input)) {
      outputElement.innerHTML = "Please enter a number!";
    } else {
      const output = calculationFunction(input);
      outputElement.innerHTML = dotToComma(output);
    }
  }

  form.elements["execute"].addEventHandler("click", calculate);
}

// Circle circumference
initCalculator(document.getElementById("circle-circumference"), "radius", r => 2 * Math.PI * r);

// Circle area
initCalculator(document.getElementById("circle-area"), "radius", r => Math.PI * Math.pow(r, 2));

The next step could be modify initCalculator so that it supports multiple input fields.


Using AJAX to interact with MVC I have the following ajax call:

function getPreviewText() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("PreviewWiki")',
        dataType: 'json',
        data: 'source=' + $('#markItUp').val(),
        success: function (data) {
            $('#previewMode').html(data.RenderedSource);
        }
    });
};

Controller action:

[HttpPost]
public ActionResult PreviewWiki(string source) {
    return Json(new { RenderedSource = m_wikiEngine.Render(source, GetRenderers()) });
}

And modal window:

I can switch between the design and preview tabs instantly which allows me to make changes in "Design Mode" and then instantly preview the effect of those changes before saving it to the Wiki. This works as I expect it to but I suspect that A. somehow I can accomplish this with get instead of post and B. I might not be going about this the right way.

Sure, it works exactly as I want it to but this is my first real web app and I'm confident that I'm "doing things right" here.

Well there's not much code to review here, but for what's here, I'd say it looks okay. I would only make one suggestion. If all you're going to do in your controller action is return single string wrapped up in a JSON object, why not dispose of the JSON and just return the HTML as content?

Ajax call:

function getPreviewText() {
    $.ajax({
        type: 'POST',
        url: '@Url.Action("PreviewWiki")',
        dataType: 'html',
        data: 'source=' + $('#markItUp').val(),
        success: function (result) {
            $('#previewMode').html(result);
        }
    });
};

Controller action:

[HttpPost]
public ActionResult PreviewWiki(string source) {
    return Content(m_wikiEngine.Render(source, GetRenderers()));
}


Why are these functions slower than BigInteger's included methods? I tried writing alternative functions to Java's BigInteger.add(BigInteger.ONE), BigInteger.add(BigInteger), and BigInteger.subtract(BigInteger):

 public static BigInteger increment(BigInteger x)
 {
  int i=0;
  while(x.testBit(i))
   x=x.clearBit(i++);
  x=x.setBit(i);
  return x;
 }

 public static BigInteger add(BigInteger x, BigInteger y)
 {
  boolean A, B, carry=false;
  BigInteger sum=BigInteger.ZERO;
  int firstBit=x.or(y).getLowestSetBit(),
      topBit=x.or(y).bitLength();
  for(int i=firstBit;i<=topBit;i++)
  {
   A=x.testBit(i);
   B=y.testBit(i);
   if((A^B)^carry)
    sum=sum.setBit(i);
   carry=(A&&B)||((A^B)&&carry);
  }
  return sum;
 }

 public static BigInteger subtract(BigInteger x, BigInteger y)
 {
  if(x.compareTo(y)==-1)
  return subtract(y,x).negate();
  boolean A, B, borrow=false;
  BigInteger diff=BigInteger.ZERO;
  int firstBit=x.or(y).getLowestSetBit(),
      topBit=x.or(y).bitLength();
  for(int i=firstBit;i<=topBit;i++)
  {
   A=x.testBit(i);
   B=y.testBit(i);
   if((A^B)^borrow)
    diff=diff.setBit(i);
   borrow=(!A&&B)||(!(A^B)&&borrow);
  }
  return diff;
 }

Instead of speeding my program up, they slowed it down. I'm thinking it might be related to the immutability of the Java BigInteger class: every time a new value is computed, a new BigInteger has to be created. Would I have different results if I wrote them as method overrides in a subclass, using MutableBigInteger?

Your question comes in multiple parts: General code review, adding algorithms, and then performance relative to standard BigInteger

General Review

Let's focus on this method, it shows essentially all the general issues I see:

 public static BigInteger add(BigInteger x, BigInteger y)
 {
  boolean A, B, carry=false;
  BigInteger sum=BigInteger.ZERO;
  int firstBit=x.or(y).getLowestSetBit(),
      topBit=x.or(y).bitLength();
  for(int i=firstBit;i<=topBit;i++)
  {
   A=x.testBit(i);
   B=y.testBit(i);
   if((A^B)^carry)
    sum=sum.setBit(i);
   carry=(A&&B)||((A^B)&&carry);
  }
  return sum;
 }

Breathing room around operators is important for readability. The code like:

for(int i=firstBit;i<=topBit;i++)

should be:

for (int i = firstBit; i <= topBit; i++)

Java code styles use brace-at-line-end style. C, C++, C# and other C* languages use next-line style. This sort of brace style is often debated, but, all common Java code style standards require end-of-line. You will regularly be criticised when sharing Java code using this style. Your code should look like:

public static BigInteger add(BigInteger x, BigInteger y) {
    boolean ...

mixed initialization is confusing, and variables should be declared in their tightest scope:

boolean A, B, carry=false;

That declaration is redundant, and confusing. Java defaults all boolean values to false when declared (unless specifically initialized to true). So, the carry=false is redundant (since A and B are also false).

Further, A and B are horrible names for variables. For a start, they are upper case, then they have poor meanings, and finally, A is a real word that tends to create a specific meaning when read out of context.

While talking bad names, x and y are not good names either. Those names imply that the two input variables are coordinates, and not two values to be added. I would recommend names like augend and addend because those are the official names for the two terms used in addition.

Finally, A and B are only used in the context of the for-loop, and not outside that context, so they should be declared where they are used:

boolean augBit = augend.testBit(i);
boolean addBit = addend.testBit(i);

Complicated functions should not be used when creating compound variable declarations:

int firstBit=x.or(y).getLowestSetBit(),
    topBit=x.or(y).bitLength();

That should be split in three, actually. The x.or(y) is repeated twice, so should be extracted....

 BigInteger orVals = augend.or(addend);
 int firstBit = orVals.getLowestSetBit();
 int topBit = orVals.bitLength();

1-liner if-statements and other 1-liner blocks. You have the 1-liner statement:

   if((A^B)^carry)
     sum=sum.setBit(i);

1-liners are know to be a leading cause of bugs introduced during the maintenance cycle of code. The easy solution is to brace 1-liners always. The code should be:

   if( (A ^ B) ^ carry) {
       sum=sum.setBit(i);
   }

Let's take a pause at this point, and see where we are at:

public static BigInteger add(BigInteger augend, BigInteger addend) {

    boolean carry = false;
    BigInteger sum = BigInteger.ZERO;

    BigInteger orVals = augend.or(addend);
    int firstBit = orVals.getLowestSetBit();
    int topBit = orVals.bitLength();

    for (int i = firstBit; i <= topBit; i++) {
        int augBit = augend.testBit(i);
        int addBit = addend.testBit(i);
        if ((augBit ^ addBit) ^ carry) {
            sum = sum.setBit(i);
        }
        carry = (augBit && addBit) || ((augBit ^ andBit) && carry);
    }
    return sum;
}

Alright, at this point, I can see the algorithm more clearly in the code, time to move on.....

Bug

Having isolated the code like this, it is apparent that there is a big bug too. If you have a carry coming from the highest bit sum, you ignore the carry... So, for example, if you have the two values 0x0f and 0x01, I would expect the sum 0x10, but you will not carry the last 1 bit in to the next value...

Performance

With the refactored code, it is clear that there are two major performance hits. The first is that the sum is a BigInteger value that gets recreated multiple times each loop (once for each set bit). Each time you call:

sum = sum.setBit(i);

you create a new BigInteger value, with the corresponding overheads, and memory allocations, etc. This could be a lot of allocations. The native Java routine breaks out of this situation by using primitive values and arrays, and keeps a bit-vector that is mutable for the duration of the addition cycle. By doing it that way, there is no memory management penalty....

A second issue related to performance, that is not obvious, is that the real BigInteger class does things both ways ..... it does a bit-vector for large integer values, but for 'small' values it uses a simple java long primitive. In other words, it simply does long sum = augend.longVal + addend.longVal if the two inputs are small enough for long value representations, and also if the sum will fit in a primitive long. In other words, it is much faster for smaller values than for values that exceed Long.MAX_VALUE/MIN_VALUE

Algorithm

I have, in the past, tried to out-perform BigDecimal (not BigInteger), by building a mutable version of BigDecimal. It became really complicated really fast. The concept of a MutableBigInteger is nice, but the reality is that it becomes a mess, fast. There are some open source attempts at this, though I believe they are all languishing in disuse. The reason is simple.... BigInteger is, by an large, fast. The penalty of the Immutable memory hit because  you need to create new values and arrays often, is outweighed by the cost of memory management and expansion that is required otherwise.

Finally, the individual operations inside the BigInteger class are able to use the native storage mechanism directly when doing calculations, and you don't need to do the translations for each bit, for example. In other words, 'wrapping' BigInteger is never going to give you the performance that BigInteger itself can give, simply because the internals of BigInteger can access the more efficient internal data structures.


Integer-to-hex string generator I am using this as a learning exercise primarily and want to ensure my code is optimal.  The main thing is that it is reliable and I am made aware of any flaws.

Could it be made more efficient or more readable?  How about style?

I thought about returning a char*, but then the caller would have to think to deallocate the returned string.  I saw this as a problem, so I left to caller to allocate and deallocate.  Is that the right decision?  Any comments?

/* Generate hex string from integer.  Odd number of characters must be preceded
   with zero character
   Eg. 9 becomes "09", 10 becomes "0A" and 16 becomes "10"
*/

#include <stdio.h>

unsigned int num_hex_digits(unsigned int n) {
    int ret = 0;
    while(n) {
        n >>= 4;
        ++ret;
    }
    return ret;
}

void make_hex_string_easy(unsigned int invokeid, char** xref)
{
    int pad = 0;
    int len = num_hex_digits(invokeid);
    /* if odd number, add 1 - zero pad number */
    if(len % 2 != 0)
        pad = 1;

    sprintf(*xref, "%s%X", pad ? "0" : "", invokeid);
}

void make_hex_string_learning(unsigned int invokeid, char** xref)
{
    char* p = *xref;
    int pad = 0;
    int len = num_hex_digits(invokeid);
    /* if odd number, add 1 - zero pad number */
    if(len % 2 != 0)
        pad = 1;

    /* move to end of number string */
    p+= len + pad - 1;

    while(invokeid) {
        int tmp = invokeid & 0xF;
        if(tmp < 10)
            *p = tmp + '0';
        else
            *p = tmp + 'A' - 10;

        invokeid >>= 4;

        p--;
    }

    if(pad) {
        *p = '0';
    }
}

int main() {
    unsigned int testdata[] = {~0, 1, 255, 256, 0xFFFE, 0xFFFF, 0x10000, 0xABC };
    int sz = sizeof(testdata) / sizeof(int);
    int i;

    char* test = (char*) calloc (20, 1);
    printf("Using sprintf method\n");
    for(i = 0; i < sz; ++i) {
        make_hex_string_easy(testdata[i], &test);
        printf("hex string of %#10x = \t%10s\n", testdata[i], test);
        memset(test, 0, 20);
    }

    printf("\nUsing homegrown method\n");
    for(i = 0; i < sz; ++i) {
        make_hex_string_learning(testdata[i], &test);
        printf("hex string of %#10x = \t%10s\n", testdata[i], test);
        memset(test, 0, 20);
    }
    free(test);

    return 0;
}

Output on my PC:

Using sprintf method
hex string of 0xffffffff =        FFFFFFFF
hex string of        0x1 =              01
hex string of       0xff =              FF
hex string of      0x100 =            0100
hex string of     0xfffe =            FFFE
hex string of     0xffff =            FFFF
hex string of    0x10000 =          010000
hex string of      0xabc =            0ABC

Using homegrown method
hex string of 0xffffffff =        FFFFFFFF
hex string of        0x1 =              01
hex string of       0xff =              FF
hex string of      0x100 =            0100
hex string of     0xfffe =            FFFE
hex string of     0xffff =            FFFF
hex string of    0x10000 =          010000
hex string of      0xabc =            0ABC

Nothing jumps out:

Rather than this:

   if(tmp < 10)
        *p = tmp + '0';
    else
        *p = tmp + 'A' - 10;

I would have used:

   *p = tmp + (tmp < 10) ? '0' : 'A' - 10;

Even though you pass around a pointer to a pointer (for re-alloc I assume). You don't actually do any reallocation. So I would simplify the code and just pass a pointer.

void make_hex_string_easy(unsigned int invokeid, char** xref)
                                                 ^^^^^^   I would just use char*

Note: A lot of common interfaces when you pass a NULL as the destination return how many characters it would have used in the buffer. This leads to a lot of C code that looks like this:

size_t  s = make_hex_string_easy(number, NULL); // assuming you changed your code to return a value.
char*   b = malloc(s+1);
make_hex_string_easy(number, b);

But Since you don't use dynamic buffers I would remove the calloc.

printf("Using sprintf method\n");
for(i = 0; i < sz; ++i) {
    char  test[50] = {0}; // inits to 0
    make_hex_string_easy(testdata[i], test);  // assuming you change to just a pointer
    printf("hex string of %#10x = \t%10s\n", testdata[i], test);
}


Query of users for some age, gender, and state, using a subselect I have this query:

SELECT * FROM
(SELECT u.id,u.email,u.verified,u.verified_on,u.created_on,ca.html AS age,cg.html AS gender,cs.html AS state
FROM users u
LEFT JOIN combo ca ON ca.combo_group='age' AND ca.value =u.age
LEFT JOIN combo cg ON cg.combo_group='gender' AND cg.value =u.gender
LEFT JOIN combo cs ON cs.combo_group='state' AND cs.value =u.state ORDER BY created_on DESC) users ORDER BY email ASC;

I am using sub query because I want sort created_on DESC and email ASC.

Would using sub query affect performance?

Your query doesn't do what you think it does. It discards the original ordering when it re-sorts. It might, depending on the sorting algorithm chosen, happen to come out how you want, but there's no guarantee.

  I am using sub query because i want sort created_on DESC and email ASC

If that's what you want, just write:

ORDER BY created_on DESC, email ASC

Your bigger worry with performance is that combo side table, which appears to be EAV and thus likely to be painful in performance terms. Consider using a hstore or json field instead.


Singleton Design Pattern implementation in a not traditional way For implementing Singleton we can use Traditional way like this Article,
but i think that to write it in another way:

 public class Person
 {
    private static Person personInstance;
    static Person()
    {
        personInstance = new Person();
    }
    private Person() { }

    public static Person GetPersonInstance()
    {
        return personInstance;
    }
}

As we know a Static Constructor will call automatically before the first instance is created or any static members are referenced and just once only. so if i write singleton like above, is it true (i mean this class is singleton)? or not?

Your implementation does the trick. For what it's worth, I would consider your implementation the current "traditional way". It is thread-safe. The static constructor is guaranteed to run only once, so you won't accidentally end up with two instances if two threads try to grab the instance for the first time simultaneously.

Laziness

There is one more thing you might want to consider though. Because of the way the static constructor works, it is executed the first time the class is referenced in the code. This means that the instance in your singleton is created, even when you don't try to grab the instance, but another static variable perhaps.

To fix this, you might want to make the creation of the instance lazy, so that it really only fires when you need it. To do this, you can use the Lazy<T> class.

Sealed

This is mostly a formality, but it's nice when trying to do it formally. The sealed keyword means that that class cannot be inherited from. The private constructor already ensured that, but this makes it more explicit.

Readonly

As Jesse mentioned in the comments, it's a good idea to make the instance field (lazy or not) readonly. This prevents you from accidentally mucking up your singleton instance from within the class.

public sealed class Person
{
    private Person() { }
    private static readonly Lazy<Person> lazyPersonInstance = new Lazy<Person>(() => new Person());
    public static Person GetPersonInstance()
    {
        return lazyPersonInstance.Value;
    }
}

Your method GetPersonInstance can also be a getter-property:

    public static Person Instance => lazyPersonInstance.Value;

Exceptions

IEatBagels already posted an answer about throwing exceptions. I'll elaborate a bit on how it would work in this example. We're looking at the scenario where instantiating the singleton instance throws an exception.

In your code, this exception would be thrown when the static constructor is ran. As IEatBagels points out, when this happens, the type is broken for the rest of the "program". This means that you have one shot at creating your instance.

In my example, the initiation of the instance does not happen during the execution of the static constructor. All we do during static initialization - static constructor and static fields act similarly IIRC - is creating the Lazy<T> object with the factory method. This method is only executed when lazyPersonInstance.Value is called.

However, Lazy<T> caches exceptions. This means that if the factory method throws an exception, that exception will be rethrown on every subsequent call to lazyPersonInstance.Value. Without re-executing the factory method. So in the end, this is the same problem as the static constructor problem. The Lazy<T> docs have the following to say:

  The Lazy stands in for an actual T that otherwise would have been initialized at some earlier point, usually during startup. A failure at that earlier point is usually fatal. If there is a potential for a recoverable failure, we recommend that you build the retry logic into the initialization routine (in this case, the factory method), just as you would if you weren't using lazy initialization.
  MSDN docs

So if you really must throw exceptions in your constructor, be sure to handle them in the factory method.

Exceptions and thread-safety

There's one more workaround for the problem of exceptions in constructors. Lazy has three thread-safety modes, defined in the enum System.Threading.LazyThreadSafetyMode which can be passed to the constructor of Lazy<T>.

None. No thread safety.
ExecutionAndPublication. This is the default. This ensures that the factory method is executed only once, and that the object on lazy.Value is always the same across threads.
PublicationOnly. This only ensures thread-safety on lazy.Value. It can happen that the factory method is executed simultaneously by multiple threads, but the resulting instance is still the same. The others are discarded. According to the Lazy<T> docs, Exceptions are not cached here.

This leaves you, the implementer of the singleton with a decision: if there are exceptions that might be thrown, that can't be handled within the factory method, and that might not throw in subsequent attempts (weird, but might happen), you could consider loosening up some of the locking on Lazy to allow for this behaviour.

For further reading, see this blog post by Jon Skeet.


Getting computer info I was trying to get my computer information and I came up with this code. It is working but I need opinions on how I am doing it. It is my first time to using std::string to return strings. Is it good or is there another way around?

struct USER
{
    std::string ID;
    std::string Username;
    std::string PCName;
    std::string OSVersion;
};

std::string GetOSVersion()
{
    OSVERSIONINFOEX osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
    GetVersionEx((LPOSVERSIONINFOA) &osvi);

    std::string Version = "Unknown Operating System";
    std::string ServicePack = osvi.szCSDVersion;

    if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion >= 1)
    {
        if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
            Version = "Windows XP Home Edition " + ServicePack;
        else
            Version = "Windows XP Professional " + ServicePack;

        return Version;
    }
    return Version;
}

void InitUser(User* u)
{
    char UsernameBuffer[UNLEN + 1];
    DWORD UsernameBufferSize = sizeof(UsernameBuffer);
    GetUserName(UsernameBuffer, &UsernameBufferSize);
    u->Username = UsernameBuffer;

    char ComputerNameBuffer[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD ComputerNameBufferSize = sizeof(ComputerNameBuffer);
    GetComputerName(ComputerNameBuffer, &ComputerNameBufferSize);
    u->PCName = ComputerNameBuffer;

    u->OSVersion = GetOSVersion();

    return;
}

It seems to me that it would be better if the User struct knew how to initialize itself, by putting the initialization code into a constructor.

So, your header would be something like this:

struct User
{
    User();
private:
    GetOSVersion();
    std::string Username;
    std::string PCName;
    std::string OSVersion;
};

...and the implementation (.cpp, or whatever) file something like this:

std::string
User::GetOSVersion() {
    // code from GetOSVersion here
}

User::User() {
    // code similar to body of InitUser goes here
}

Since you didn't seem to be using the ID member of User, I removed it. Since the information isn't all about the user, but includes the OS version and such, it would probably be better to rename User to something more like SystemInformation.

I'd also prefer to do initialization as initialization, so this:

OSVERSIONINFOEX osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

...would be implemented more like:

OSVERSIONINFOEX osvi = { 0 };

...or (if you can use C++11):

OSVESIONINFOEX osvi {};

I'd also probably add a stream insertion operator for the class (whatever you end up naming it), using code something like this (inside the class definition):

friend std::ostream &operator<<(std::ostream &os, User const &u) {
    return os << u.Username << " " << u.PCName << " " << u.OSVersion;
}

Finally, if you're going to do OS version information, you probably want to support more  than the two OS versions you have right now. Given that there are lots of other ways to get this information, and all of them do a better job than this, nearly the only reasonable choices seem to me to be either expand coverage substantially to the point that it's at least somewhat useful, or else remove it completely.


How to have  elements with different links on each image? Time ago I had a header implemented with a Bootstrap carousel: You know, something like this:

Pay attention to that link on "pic2.jpg", this will be fun...
Recently, I have been asked to use <picture> elements, so now it is posible to display images for mobile devices:

    <picture>
        <source media="(max-width: 576px)" srcset="pic1-small.jpg">

     </picture>

    <picture>
        <source media="(max-width: 576px)" srcset="pic2-small.jpg">

     </picture>

And here is the tricky question: I need to add a link only in the mobile image (pic2-small.jpg).
(Well, in fact could be links on every image, or none at all, only in the mobile image, only in the desktop image... This is managed by the administrator user)
So, I can't do this because the link should be only for pic2-small, not pic2:

        <picture>
            <source media="(max-width: 576px)" srcset="pic2-small.jpg">

         </picture>

What I did is this:

    <picture>
        <source media="(max-width: 576px)" srcset="pic2-small.jpg?target=pic2-small-link">

     </picture>

An onclick event in the carousel item and a javascript function.
A target value in the URL of the image.
A hidden  with the destination URL.

The magic is in this line:
var current_src = carousel_item.querySelector("img").currentSrc;

currentSrc has the URL of the image that the browser is currently showing according to the screen size. So, from that URL I take the target parameter and use it to get the corresponding link and then execute it.
All this is working, but I feel it too hacky for my taste. I'm not very experienced with the <picture> element, so my question is: this could be resolved in a better way?

Yes hacky!
This is very hacky as you are doing a media query the long way. Interpreting the resulting media aware DOM for a URL that you then manually parse.
Learn and use the API
There are many API's available to a modern browser environment. The general rule is if it can be done on the page via HTML/CSS there is an API that can do it in JavaScript.
I never use media queries as I serve to interrogated devices so I am not 100% up on media querie API's, but for static pages you can use matchMedia
Setting up media dependent links.
There are many ways to setup your page. But in code you can access media queries using matchMedia which returns the result of a media query as MediaQueryList
You can access an elements media attribute by name. for example if an image is clicked in your example HTML event.target.parentElement.querySelector("source").media
You can store the different links as data attributes.
I think the best approach is to pre-process the markup when it has loaded and just set the link references depending on the associated media query.
Example
The code checks each link (anchor element) for a source element and uses the source elements media attribute to do a media query.
Depending on the result of the media query it gets the appropriate data set item and set the link href property.
Each picture has a different media query. Hover to see link href (I have set title to show the link as example)

// do in page onload event
for (const link of linkedImages.querySelectorAll("a")) {
    const source = link.querySelector("source");
    if (source) {
        const isSmall = matchMedia(source.media).matches;
        link.href = isSmall ? link.dataset.linkSmall : link.dataset.linkNormal;
        link.title = link.href; // just for example
    }
}

        <picture>
            <source media="(max-width:  1700px)" srcset="https://i.stack.imgur.com/C7qq2.png?s=48&g=1">

        </picture>

        <picture>
            <source media="(max-width:  500px)" srcset="https://i.stack.imgur.com/C7qq2.png?s=48&g=1">

         </picture>


Search through server folders and display files that exist I have a folder called uploads in this folder is a folder for the year the file was uploaded(2013,2014,2015 etc...), inside the year folder are usernames(rick, dan, edward etc...), inside the usernames folder are folders 1-12 for the month that the file was uploaded.

I want to search through the folders and if there is a file in the folder display the link, the problem I am having is figuring out how to do the check on all of the folders:

Here is my code so far:

<?php

        //array for years to check for
        $year = array('2013','2014','2015','2016','2017','2018','2019','2020');
        $month = array('1','2','3','4','5','6','7','8','9','10','11','12');

        //loop through years array and populate $existingYears[] array with years that exist on server
        foreach($year as $years){

            if(is_dir($yearPath = ABSPATH."/"."uploads/".$years."/".$username)){

                $existingYears[] = $years;

            }

        }

        //loop through existings years
        foreach($existingYears as $year){

            //title
            print "
".$year."
";

                //loop for months
                for ($i=1; $i<=12; $i++) {

                    if($i == 1){
                        $title = "January";
                    } elseif($i == 2){
                        $title = "February";
                    }elseif($i == 3){
                        $title = "March";
                    }elseif($i == 4){
                        $title = "April";
                    }elseif($i == 5){
                        $title = "May";
                    }elseif($i == 6){
                        $title = "June";
                    }elseif($i == 7){
                        $title = "July";
                    }elseif($i == 8){
                        $title = "August";
                    }elseif($i == 9){
                        $title = "September";
                    }elseif($i == 10){
                        $title = "October";
                    }elseif($i == 11){
                        $title = "November";
                    }elseif($i == 12){
                        $title = "December";
                    }

                    //path to months directories
                    $url=$userPath.'/'.$i;

                    $newUrl = $url.'/'.$files[2];

                    print $newUrl;

                    //check if directory exists
                    if(is_dir($url)){

                        //assign open state to $dir
                        $dir = opendir($url);

                        //add all files to $files[] array
                        while (($file = readdir($dir)) !== false){

                            $files[] = $file;

                        }
                        closedir($dir);

                        //display link to payslips
                        print "
";
                        print "
".$title."
";
                        print "Download";
                        print "
";

                    }

                }

        }

        ?>

Very messy I know, I am sure there is a better way to do this just not sure how.

You might want to try using the scandir function to build your arrays of directories and files, makes it a bit more future proof.

$baseDir = ABSPATH."/uploads";
$calendarinfo = cal_info(0); //built-in function to generate calendar info, e.g. month names
$years = scandir($baseDir);

//You might want to ignore certain folders, e.g. on UNIX systems:
$ignore = [".","..",".DS_Store"];

foreach ($years as $year) {

    if (!in_array($year, $ignore)) { //the folder is not in the ignore array

        //then scan the year directory for user folders
        $users = scandir($baseDir."/".$year);
        foreach ($users as $user) {

            if ($user == $username) { //if the year contains a folder belonging to logged in user
                echo "
".$year."
"; //create a year heading
                $months = scandir($baseDir."/".$year."/".$user); //scan it for month folders
                foreach ($months as $month) { //scan for month folders

                if (!in_array($month, $ignore)) { //ignore specified folders

                    echo "
";
                    echo "
".$calendarinfo["months"][$month]."
";

                    $contents = scandir($baseDir."/".$year."/".$user."/".$month); //scan each month folder
                    foreach ($contents as $key=>$item) { //for every item found in the month folder

                        if (!is_dir($baseDir."/".$year."/".$user."/".$month."/".$item)) { //ignore directories
                            //and list out the files
                            echo "Download";
                        }
                    }

                    echo "
";

                }
            }
        }
    }
}
}


Iterator of iterator Given an iterator of iterators, return all of the elements from the iterators in order. Looking for code review, optimizations, and best practices. Verifying complexity to be \$O(n)\$, where \$n\$ is the total number of elements from all iterators.

public class IteratorOfIterator implements Iterator<Integer>{

    private final Iterator<Iterator<Integer>> iteratorOfIterator;
    private Iterator<Integer> currentIterator;

    public IteratorOfIterator(Iterator<Iterator<Integer>> iterator)  {
        this.iteratorOfIterator = iterator;
    }

    @Override
    public boolean hasNext() {
        while (currentIterator == null || !currentIterator.hasNext()) {
            if (!iteratorOfIterator.hasNext()) return false;
            currentIterator = iteratorOfIterator.next();
        }
        return true;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException("the stuff cannot be null.");
        }
        return currentIterator.next();
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("The remove operation is not supported.");
    }
}

public class IteratorOfIteratorTest {

    @Test
    public void testIterator() {
        List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
        List<Integer> list2 = new ArrayList<>(Arrays.asList(5, 6, 7, 8));
        List<Iterator<Integer>> combined = new ArrayList<>(Arrays.asList(list1.iterator(), null, list2.iterator()));

        IteratorOfIterator ioi = new IteratorOfIterator(combined.iterator());
        int[] expected = {1, 2, 3, 4, 5, 6, 7, 8};
        int[] actual = new int[8];
        int i = 0;
        while (ioi.hasNext()) {
             actual[i] = ioi.next();
             i++;
        }
        assertArrayEquals(expected, actual);
    }
}

I don't see any reason to limit this to Integers.  The solution can be trivially genericized.

IteratorOfIterator is a clumsy name.  By analogy with Python's itertools.chain(), I suggest calling this class ChainIterator<T>.  You can rename the iteratorOfIterator private variable accordingly, too.

I suggest adding an alternate constructor that takes an Iterable<Iterator<T>>, for convenience.

The hasNext() method seems fine.  As for next(), the message in the NoSuchElementException that you throw seems a bit weird; I would just omit it.

With not much extra effort, you can add support for remove().

public class ChainIterator<T> implements Iterator<T> {

    private final Iterator<Iterator<T>> chain;
    private Iterator<T> currentIterator;
    private Iterator<T> lastIterator;

    public ChainIterator(Iterable<Iterator<T>> iterable)  {
        this(iterable.iterator());
    }

    public ChainIterator(Iterator<Iterator<T>> iterator)  {
        this.chain = iterator;
    }

    @Override
    public boolean hasNext() {
        while (currentIterator == null || !currentIterator.hasNext()) {
            if (!chain.hasNext()) return false;
            currentIterator = chain.next();
        }
        return true;
    }

    @Override
    public T next() {
        if (!this.hasNext()) {
            this.lastIterator = null;         // to disallow remove()
            throw new NoSuchElementException();
        }
        this.lastIterator = currentIterator;  // to support remove()
        return currentIterator.next();
    }

    @Override
    public void remove() {
        if (this.lastIterator == null) {
            throw new IllegalStateException();
        }
        this.lastIterator.remove();
    }
}


Structure a webapp using RequireJS I've written a small webapp in JavaScript, and am now essentially rewriting it to use RequireJS.  I'm doing this partly to get more familiar with RequireJS (which I have little experience with), as well as for ease of maintaining and upgrading the app.

I'm hoping to get feedback on whether the structure I'm looking at implementing is reasonable/useful/extensible/totally insane.  I've been through the require docs, reading related SO posts and some samples on GitHub, but I'm not sure I'm totally 'getting' Require.

If there are fundamental flaws in the logic it'd be great to get some links to resources (either JS or RequireJS specific), and to get feedback about the overall structure of the app itself.  Suggestions for design patterns also very much appreciated, there's some stuff in there that feels kind of counter intuitive.

main.js

require({

    paths: {
        jquery: '../bower_components/jquery/jquery'
    }

}, function() {
    'use strict';
    require(['jquery', 'app', 'reader', 'env'], function($, App, Reader, Env) {

        $(document).ready(function() {

            var app = new App(
                new Reader(),
                new Env()
            );

        });

    })

});

app.js

define(function() {

    return function(reader, env) {

        this.reader = reader,
        this.env = env

    };

});

reader.js (it's an online e-reader)

define(['jquery'], function($) {

    return function() {

        this.components = [],
        this.firstPage = null,
        this.lastPage = null,
        this.maxFontSize = function() {
            return this.env.isIOS() ? 120 : 160;
        }

    };

});

env.js

define(['jquery'], function($) {

    return function() {

        this.isIOS = function() {
            return navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false; // for example.
        }

    };

});

This is honestly pretty good. I usually use requirejs.config to set the paths and configurations on require (it's going to grow a lot as you add things like shims, urlArgs, etc). You will also probably want to reuse it in several places. See my blog article on how I recommend doing this. The general idea is that you don't use data-main to bootstrap things, you instead have a request for the configuration file and another to actually bootstrap the specific page of your application.

Next, I'll ask why bother injecting reader and env manually into application? Injecting dependencies is what RequireJs already does.

app.js

define(['reader', 'env'], function(Reader, Env) {
    return function() {
        this.reader = new Reader(),
        this.env = new Env()
    };
});

Finally, a couple notes on your specific files - you probably want to name those top-level functions even when returning immediately

env.js

define(['jquery'], function($) {
    return function Env() {
      ...
    };
});

That both makes it clear from within what module you're in, the fact that you expect it to be used with new, and will generate nicer stacktraces.

I'll also point out that - it's a matter of style but you're on CR so I consider it solicited - hardly ever is code made more bugproof or more legible by using constructor functions.  reader.js could just as easily be the following and not depend on someone remembering to use new and always bind functions.

var env = {
    components: [],
    firstPage: null,
    lastPage: null,
    maxFontSize: function() {
                   return this.env.isIOS() ? 120 : 160;
                 }
};
return env;


Finding the busiest time-frame in a parking lot The text file containing cars' arrival and departure time will upload stuff from the parking lot.

Text will be like this:

10:10, 11:10
10:30, 12:40
10:25, 11:10
11:10, 12:20

I created a ParkedCar class:

public class ParkerCar
{
    public DateTime ArrivalTime { get; set; }
    public DateTime DepartureTime { get; set; }
}

The method that parses the text file, fills into List<ParkedCar>, and sorts them by the cars' arrival time:

public class ParkingLotRepository
{
    public List<ParkedCar> getParkedCars()
    {
        List<ParkedCar> parkedCars = new List<ParkedCar>();
        foreach (string line in File.ReadLines(path))
        {
            string[] times = line.Split(',');
            bool isValid = true;
            DateTime dtStart;
            if (!DateTime.TryParseExact(times[0].Trim(), "HH:mm",
                CultureInfo.InvariantCulture,
                DateTimeStyles.NoCurrentDateDefault, out dtStart))
                isValid = false;

            DateTime dtEnd;
            if (!DateTime.TryParseExact(times[1].Trim(), "HH:mm",
                CultureInfo.InvariantCulture,
                DateTimeStyles.NoCurrentDateDefault, out dtEnd))
                isValid = false;

            if (isValid)
            {
                parkedCars.Add(new ParkedCar
                {
                    ArrivalTime = dtStart,
                    DepartureTime = dtEnd
                });
            }
        }
        parkedCars = parkedCars
            .OrderBy(c => c.ArrivalTime)
            .ThenBy(c => c.DepartureTime)
            .ToList();

        return parkedCars;
    }
}

I wrote the method shown below to find the busiest time-frame and how many cars were in the parking lot. I'm not sure if this is an effective way to do that:

public static ParkTimeframe getPickTimeframe(List<ParkedCar> cars)
{
    List<ParkTimeframe> timeFrames = new List<ParkTimeframe>();
    DateTime dtStart = cars.First().arrivalTime;
    DateTime dtEnd = cars.First().leavingTime;
    int count = 0;

    foreach (ParkedCar car in cars)
    {
        if (car.arrivalTime <= dtEnd && car.arrivalTime >= dtStart)
        {
            count++;
        }
        else
        {
            timeFrames.Add(new ParkTimeframe
            {
                startTime = dtStart,
                endTime = dtEnd,
                countCars = count
            });
            dtStart = car.arrivalTime;
            dtEnd = car.leavingTime;
            count = 0;
        }
    }

    int maxCountCar = timeFrames.Max(x => x.countCars);
    return timeFrames.First(x => x.countCars == maxCountCar);
}

public class ParkedCar
{
    public DateTime arrivalTime { get; set; }
    public DateTime leavingTime { get; set; }
}

Also, is there a better way to do that using LINQ?

Naming Conventions

MSDN, General Naming Conventions

DO NOT use Hungarian notation:

[dt]Start in getPickTimeframe() --> DateTime currentFrameStartDate
[dt]End in getPickTimeframe() --> DateTime currentFrameEndDate

DO favor readability over brevity:

ParkedCar --> ParkingLog
getPickTimeframe(List<ParkedCar> [cars]) --> GetPeakTimeFrame(List<ParkingLog> parkingLogs)
public int [countCars]; --> public int TotalNumberOfParkedCars;
int [count] = 0; --> int currentFrameNumberOfParkedCars;

MSDN, Naming Guidelines / Capitalization Conventions
DO use PascalCasing for all public member, type, and namespace names consisting of multiple words:

[G]et[Pick]Time[F]rame() --> GetPeakTimeFrame()
class ParkTime[F]rame
ParkTime[F]rame.[S]tartTime
ParkTime[F]rame.[E]ndTime
ParkTime[F]rame.[C]ountCars --> Also see above for alternative name
ParkedCar.[A]rrivalTime
ParkedCar.[L]eavingTime

Implementation

Your current implementation, besides efficiency, is not working correctly.

For parkings as the following:

// Parking opens at 07:00
DateTime parkingOpenDate = DateTime.Now.Date.AddHours(7);

// t --xxxxxxxx--------------------------------07:02 - 07:10
// t ---xxxxxxxx-------------------------------07:03 - 07:11
// t --------------xxxxxxxx--------------------07:14 - 07:22
// t --------xxxxxxxxx-------------------------07:08 - 07:17
// t 001222223321112221111100000000000000000000

new ParkingLog[]
{
    new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(2), LeavingTime = parkingOpenDate.AddMinutes(10) },
    new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(3), LeavingTime = parkingOpenDate.AddMinutes(11) },
    new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(14), LeavingTime = parkingOpenDate.AddMinutes(22) },
    new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(8), LeavingTime = parkingOpenDate.AddMinutes(17) }
}

It should output

07:08.00 - 07:10:00 with 3 cars

However, it outputs:

07:02.00 - 07:10:00 with 2 cars

Here are my changes to the code, calculating the correct peak time frame, only assuming the LeavingDate of each ParkingLog (ParkedCar in your source) is greater than the ArrivalDate:

public class _113182
{
    private SortedList<DateTime, int> carParkCapacityTracker = new SortedList<DateTime, int>();

    public class ParkingTimeFrame
    {
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public int TotalNumberOfParkedCars { get; set; }

        public override string ToString()
        {
            return string.Format("{0:HH:mm.ss} - {1:HH:mm:ss} | #Cars: {2}", StartTime, EndTime, TotalNumberOfParkedCars);
        }
    }

    public class ParkingLog
    {
        public DateTime ArrivalTime { get; set; }
        public DateTime LeavingTime { get; set; }

        public override string ToString()
        {
            return string.Format("{0:HH:mm:ss} - {1:HH:mm:ss}", ArrivalTime, LeavingTime);
        }
    }

    private void TrackCarParkingAction(DateTime actionDate, int actionEffect)
    {
        if (!carParkCapacityTracker.ContainsKey(actionDate))
        {
            carParkCapacityTracker.Add(actionDate, actionEffect);
        }
        else
        {
            carParkCapacityTracker[actionDate] += actionEffect;
        }
    }

    private void TrackCarParkingAction(ParkingLog parkingLog)
    {
        TrackCarParkingAction(parkingLog.ArrivalTime, +1);
        TrackCarParkingAction(parkingLog.LeavingTime, -1);
    }

    public ParkingTimeFrame GetPeakTimeFrame(List<ParkingLog> parkingLogs)
    {
        carParkCapacityTracker.Clear();

        parkingLogs.ForEach(TrackCarParkingAction);

        int currentNumberOfParkedCars = 0;
        int maximumNumberOfParkedCars = 0;
        int maximumCapacityFrameOffset = 0;

        for (int currentFrameOffset =  0; currentFrameOffset < carParkCapacityTracker.Count; currentFrameOffset++)
        {
            currentNumberOfParkedCars += carParkCapacityTracker.Values[currentFrameOffset];
            if (maximumNumberOfParkedCars <= currentNumberOfParkedCars)
            {
                maximumNumberOfParkedCars = currentNumberOfParkedCars;
                maximumCapacityFrameOffset = currentFrameOffset;
            }
        }

        return new ParkingTimeFrame()
        {
            StartTime = carParkCapacityTracker.Keys[maximumCapacityFrameOffset],
            EndTime = carParkCapacityTracker.Keys[maximumCapacityFrameOffset + 1],
            TotalNumberOfParkedCars = maximumNumberOfParkedCars
        };
    }
}

And here is the code to test it:

public static void Main()
{
    Console.WriteLine("Enter to start..");
    Console.ReadLine();

    // Parking opens at 07:00
    DateTime parkingOpenDate = DateTime.Now.Date.AddHours(7);

    List<ParkingLog> parkingLogs = new List<ParkingLog>
    (
        // t --xxxxxxxx--------------------------------07:02 - 07:10
        // t ---xxxxxxxx-------------------------------07:03 - 07:11
        // t --------------xxxxxxxx--------------------07:14 - 07:22
        // t --------xxxxxxxxx-------------------------07:08 - 07:17
        // t 001222223321112221111100000000000000000000

        new ParkingLog[]
        {
            new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(2), LeavingTime = parkingOpenDate.AddMinutes(10) },
            new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(3), LeavingTime = parkingOpenDate.AddMinutes(11) },
            new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(14), LeavingTime = parkingOpenDate.AddMinutes(22) },
            new ParkingLog() { ArrivalTime = parkingOpenDate.AddMinutes(8), LeavingTime = parkingOpenDate.AddMinutes(17) }
        }
    );

    // Should output 07:08 - 07:10 with 3 cars
    Console.WriteLine("{0}", new _113182().GetPeakTimeFrame(parkingLogs));
}

Edit:

The OP told me that he tested the code and the code failed.

I tested it with the same input (as documented in the question by the OP) and it produced the correct result:

public static void Main()
{
    // According to the data provided by the OP
    // 10:10, 11:10
    // 10:30, 12:40
    // 10:25, 11:10
    // 11:10, 12:20

    //       10:00    10:10    10:25    10:30    11:10    12:20    12:40
    // CAR 1            xxxxxxxxxxxxxxxxxxxxxxxxxxx
    // CAR 2                              xxxxxxxxxxxxxxxxxxxxxxxxxxxx
    // CAR 3                     xxxxxxxxxxxxxxxxxx
    // CAR 4                                       xxxxxxxxxx

    // The peak time frame should be: 10:30 - 11:10 with 3 cars:

    List<ParkingLog> parkingLogs = getParkedCars();
    Console.WriteLine("{0}", new _113182().GetPeakTimeFrame(parkingLogs));
}

Output:

10:30.00 - 11:10:00 | #Cars: 3

Edit 2:

The OP provided new test data and asserted that the code fails with this data.

Here is my test, and it works as expected, or there is something wrong and we are not on the same page:

// According to the new data provided by the OP
//09:00, 15:00
//10:10, 11:10
//10:30, 12:40
//10:35, 11:20
//10:25, 11:10
//11:10, 12:20

//       09:00    10:10    10:25    10:30    10:35    11:10    11:20    12:20    12:40    15:00
// CAR 1   xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// CAR 2            xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// CAR 3                              xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// CAR 4                                       xxxxxxxxxxxxxxxxxxx
// CAR 5                     xxxxxxxxxxxxxxxxxxxxxxxxxxxx
// CAR 6                                                xxxxxxxxxxxxxxxxxxx

// The peak time frame should be: 10:35 - 11:10 with 5 cars:

List<ParkingLog> parkingLogs = getParkedCars();
Console.WriteLine("{0}", new _113182().GetPeakTimeFrame(parkingLogs));

And the output is:

10:35.00 - 11:10:00 | #Cars: 5


Prevent multiple async calls from all attempting to refresh an expired OAuth token I have some code that needs to access an API that requires OAuth authorization in the form of a token, and every time the token expires, it needs to be refreshed.

I made a function called _fetch() that wraps the API calls that I'm making, and will both authorize the requests, and automatically refresh the token if it has expired.

The caveat is that if I call some function that rapidly calls _fetch() \$N\$ amount of times when the token has expired, then reAuth(), which refreshes the token, will also be called \$N\$ amount of times, which is undesirable due to the fact that it'll make \$N\$ API calls to reauthorize the token when only 1 is required.

Reduced to a really small example, possibly with mistakes, the code that I have looks a little like this

import fetch from 'node-fetch'

class Example {
  async reAuth() {
    // refresh the token
    return fetch('authAPI')
  }

  async doMultipleAsyncThings() {
    return await Promise.all([
      _fetch('url1'),
      _fetch('url2'),
      _fetch('url3')
    ])
  }

  async _fetch(url, userOptions) {
    if (tokenIsExpired(this.token)) {
      this.token = await this.reAuth();
    }

    const options = {
      headers: {
        Authorization: `Bearer ${this.token}`
      },
      ...userOptions
    }
    return fetch(url, options);
  }
}

const e = new Example()
e.doMultipleAsyncThings() // reAuth called 3 times if token expired

I think I have a solution to the problem, but I'm not sure if it's overkill or not.

Basically, I would memoize the reAuth() function such that as long as the promise it returns the first time isn't resolved it would return that same promise for all future calls to prevent calling the OAuth API again and again. Then when the promise resolves it would delete itself from the internal cache so that the next time reAuth() is called it would once again actually call the API.

I implemented this here: https://github.com/AriaFallah/weak-memoize/blob/master/src/index.js

// @flow

function memoize(callback: Function): Function {
  const cache = {}
  function memoized(...parameters: Array<mixed>) {
    const cacheKey = JSON.stringify(parameters)

    if (cache[cacheKey]) {
      return cache[cacheKey]
    }

    // Get and add the value to the cache
    const value = callback.apply(this, parameters)
    cache[cacheKey] = value

    if (!value || value.constructor.name !== 'Promise') {
      throw new Error('Memoization Error, Async function returned non-promise value')
    }

    // Delete the value regardless of whether it resolves or rejects
    return value.then(function(internalValue) {
      cache[cacheKey] = false
      return internalValue
    }, function(err) {
      cache[cacheKey] = false
      throw err
    })
  }

  memoized.cache = cache
  return memoized
}

export default memoize

and then to solve the problem all I would need to do is decorate reAuth()

import memoize from 'weak-memoize/promise'
Example.reAuth = memoize(Example.reAuth)

I think the above makes sense, but I'm curious if there is a simpler way to fix the problem I'm facing.

What about modifying the return of _fetch()? Inside the if statement that checks you could have it return false or a custom error code at that point. And then back one scope, catch the return of _fetch() and test it against your error code or false then just handle it appropriately. Either escaping out with return or reauthorizing in between.


Super calculator in C For my mathematical research, I am to deal with very large numbers and I know that the standard C types are not going to stand a chance against them due to their limited capacity, so I decided to write a super calculator in C language in hope that I won't have to resort to a super computer.

I started with an add function that I want to be reviewed for bugs if any, and possible improvement in performance and general programming aspects. Note that, on my system, the program was able to add a number consisting of 200 million digits of 9 to the same number in 0.98 seconds, which is pretty impressive, but still, if there is anything in performance that can be enhanced, let me know. That is because the multiplication function is going to be dependent on this function, and things will get slower because multiplication is repeated addition.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

char *add(char *x, char *y);

int main(void)
{
    clock_t t1 = clock();
    /* ............................................................................................................................. */
    size_t nd = 200 * 1000 * 1000; // 2 hundred million digits
    char *x = (char *)malloc(nd + 1);
    char *y = (char *)malloc(nd + 1);
    if (!x || !y) {
        fputs("error: memory allocation failed.\n", stderr);
        goto dismantle;
    }
    /* assign x and y */
    for (size_t i = 0; i < nd; i++) {
        x[i] = '9';
        y[i] = '9';
    }
    /* NUL-terminate the arrays */
    x[nd] = '\0';
    y[nd] = '\0';
    /* add x and y */
    char *z = add(x, y);
    if (z) {
        //printf("x + y = %s\n", z);
        free(z);
    }
dismantle:
    if (x) free(x);
    if (y) free(y);
    /* ............................................................................................................................. */
    clock_t t2 = clock();
    fprintf(stderr, "time elapsed: %.4f\n", (double)(t2 - t1) / CLOCKS_PER_SEC);
    fprintf(stderr, "Press any key to continue . . . ");
    getchar();
    return 0;
}

void ReverseArray(char *buf)
{
    char tmp, *ptr = buf + strlen(buf) - 1;
    while (buf < ptr) {
        tmp = *buf;
        *buf++ = *ptr;
        *ptr-- = tmp;
    }
}

char *add(char *x, char *y)
{
    /* store number of digits in size_t variables*/
    size_t xlen = strlen(x);
    size_t ylen = strlen(y);
    /* essential variables */
    char *z = NULL;
    int r = -1;
    int val, var = (xlen >= ylen);
    size_t n = 0;
    /* pointers to x and y */
    char *p1, *p2;
    char *t1, *t2;
    /* assign pointers according to the value of var */
    if (var) {
        p1 = x + xlen - 1;  t1 = x;
        p2 = y + ylen - 1;  t2 = y;
        z = (char *)malloc(xlen + 2);
    }
    else {
        p1 = y + ylen - 1;  t1 = y;
        p2 = x + xlen - 1;  t2 = x;
        z = (char *)malloc(ylen + 2);
    }
    /* check for allocation failure */
    if (!z) {
        fputs("error: memory allocation failed.\n", stderr);
        return NULL;
    }
    /* stage 1 */
    while (p2 >= t2)
    {
        if (r == -1) {
            val = (*p1-- - '0') + (*p2-- - '0');
        }
        else {
            val = (*p1-- - '0') + (*p2-- - '0') + 1;
        }
        if (val > 9) {
            r = val - 10;
            z[n++] = r + '0';
        }
        else {
            z[n++] = val + '0';
            r = -1;
        }
    }
    /* stage 2 */
    while (p1 >= t1)
    {
        if (r == -1) {
            z[n++] = *p1--;
        }
        else {
            val = (*p1-- - '0') + 1;
            if (val > 9) {
                r = val - 10;
                z[n++] = r + '0';
            }
            else {
                z[n++] = val + '0';
                r = -1;
            }
        }
    }
    /* stage 3 */
    if (r != -1) {
        z[n++] = 1 + '0';
    }
    z[n] = '\0';
    ReverseArray(z);
    return z;
}

You are using textual strings to represent numbers. This is not ideal for the processor. It is better to store the numbers as arrays of 32 or 64-bit unsigned integers, depending on the type of CPU. The only issue of course is that you might have to convert from and to the textual representation for your input and output, but if you have to perform many operations on your numbers, this is a small cost to pay.

There are existing libraries that can handle very large numbers (usually called "bignums"). One of them is the GNU Multiple Precision Arithmetic library. You can use that one if you want, or look at its source code to see how they handle large numbers.


Converting to Roman numerals As an excercise to "Haskell: The Craft of Functional Programming", I created some code to convert an Integer to Roman numerals.

This is the first version and I think I'm probably not doing it in the "Haskell way" since my background is in imperative programming.

Any advice on how to improve this? Sometimes I think I'm missing a obvious way to do it in just one function.

convMap = [(1000,"M"), (900,"CM"), (500,"D"), (400,"CD"), (100,"C"),
           (90,"XC"), (50,"L"), (40,"XL"), (10,"X"), (9,"IX"), (5,"V"),
           (4,"IV"), (1,"I")]

toRoman :: Integer -> String
toRoman x
  | x == 0 = "N"
  | otherwise = (snd . numToSubtract $ x) ++ toRoman'(nextNum)
      where nextNum = x - (fst. numToSubtract $ x)

-- Auxiliary function just so we treat 0 differently
-- (avoids 3 == "IIIN" if not used)
toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = (snd . numToSubtract $ x) ++ toRoman'(nextNum)
      where nextNum = x - (fst. numToSubtract $ x)

-- Returns which item in the convMap should be subtracted
numToSubtract :: Integer -> (Integer, String)
numToSubtract x = head (filter (lessThan x) convMap)

-- Filter function to work on the tuples in convMap
lessThan :: Integer -> (Integer, String) -> Bool
lessThan n (a, b)
  | a <= n = True
  | otherwise = False

Booleans are normal values:

lessThan n (a, b)
  | a <= n = True
  | otherwise = False

Simply write:

lessThan n (a, _) = a <= n

Use pattern matching:

toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = (snd . numToSubtract $ x) ++ toRoman'(nextNum)
      where nextNum = x - (fst. numToSubtract $ x)

If you want to take fst and snd of the same tuple, think about pattern matching.
Minor point: brackets in toRoman'(nextNum) are redundant, simply write toRoman' nextNum.

toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = b ++ toRoman' (x - a)
      where (a, b) = numToSubtract x

Remove duplication:

toRoman and toRoman' contain duplicate code. In fact toRoman is only used to treat specially 0, so can be changed:

toRoman :: Integer -> String
toRoman 0 = "N"
toRoman x = toRoman' x

Move or remove utility functions:

lessThan and numToSubtract are used only once and don't seem to be generally useful, maybe inline them:

toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = b ++ toRoman' (x - a)
      where (a, b) = head $ filter (\(a,_) -> a <= x) convMap

As Dan Burton commented, you can write also:

      where (a, b) = head $ filter ((<= x) . fst) convMap

Final code

convMap = [(1000,"M"), (900,"CM"), (500,"D"), (400,"CD"), (100,"C"),
           (90,"XC"), (50,"L"), (40,"XL"), (10,"X"), (9,"IX"), (5,"V"),
           (4,"IV"), (1,"I")]

-- Auxiliary function just so we treat 0 differently
-- (avoids 3 == "IIIN" if not used)
toRoman :: Integer -> String
toRoman 0 = "N"
toRoman x = toRoman' x

toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = b ++ toRoman' (x - a)
      where (a, b) = head $ filter ((<= x) . fst) convMap

Fold

If you stare a little at the code, it turns out you each entry from convMap only once. First you check how many M's you need. Then CM's. Then D's. And so on. Using "filter" function always restarts search from beginning. In fact, toRoman can be written as a fold!

import Data.List (genericReplicate)

convMap = [(1000,"M"), (900,"CM"), (500,"D"), (400,"CD"), (100,"C"),
           (90,"XC"), (50,"L"), (40,"XL"), (10,"X"), (9,"IX"), (5,"V"),
           (4,"IV"), (1,"I")]

toRoman :: Integer -> String
toRoman 0 = "N"
toRoman x | x > 0 = snd $ foldl f (x,[]) convMap
  where f (n,s) (rn, rs) = (l, s ++ concat (genericReplicate k rs))
              where (k,l) = divMod n rn

Going crazy with abstractions

Erik Hilton's nice answer gives a solution using unfoldr. So you can write the code using fold and unfold, and these are two ways of looking at it. I believe that combination of fold and unfold is called "paramorphism" or "apomorphism" or something like that...