Credit card / IMEI check digit in Kotlin

I personally like one-line functions as long as they are short but I also prefer breaking things out into smaller functions and/or objects to improve readability, reuse, etc. e.g.:

fun String.plusLuhnCheckDigit() = this + luhnCheckDigit(this)
fun luhnCheckDigit(digits: CharSequence): Char {
    return digits.sumByIndexed { index, digit ->
        when {
            index.isEven -> digit.asInt()
            else -> sumDigits(2 * digit.asInt())
        }
    }.let { sum -> 10 - sum % 10 }.asChar()
}

With the following also defined:

Strings.kt

inline fun CharSequence.sumByIndexed(selector: (Int, Char) -> Int): Int {
    return foldIndexed(0) { index, sum, element -> sum + selector(index, element) }
}

Numbers.kt

val Int.isEven: Boolean
    get() = and(1) == 0

NumericalChars.kt

fun Char.asInt() = toInt() - 48
fun Int.asChar() = toChar() + 48

IntMath.kt

val Int.magnitude: Int
    get() = if (this < 0) -this else this

fun sumDigits(n: Int): Int = if (n.magnitude < 10) n else n % 10 + sumDigits(n / 10)


Here are a few comments. In general, your code deviates in surprising ways from the UNIX commands (and not just by missing flags or options):

Your ls command does more than you claim it does. os.walk recursively "walks" down from the current directory, so it returns the content of all subfolders as well (without indicating in which subfolder each file or directory actually is).
When working with paths you should use the library pathlib or at least os.path consistently. This allows your tools to also work in Windows, where the symbol separating paths is \ and not /. You could use os.path.join in your cd function. However, all that code there is not needed, because os.path.isdir("..") is also True. Use os.path.abspath to get the absolute name of a path. In my home directory os.path.abspath("..") returns /home.
Don't use special return values to indicate failure. What if I want to have a directory called "Not a directory"? It may not be the most common name for a directory, but it is at least a plausible name. Instead raise an exception and catch it in the surrounding scope.
Note that your cd does not actually change the directory, so any calls in another function to os.getcwd() (like in ls) will still return the old directory.
Instead of hard-coding 100 blank lines, try to find out how many lines the terminal has, as taken from this answer by @brokkr:

import os
rows, columns = os.popen('stty size', 'r').read().split()

This probably works only on linux, though.
Instead of reading the whole file into memory, joining it and then printing it, you can print it one line at a time. This is slightly slower, but has no memory limitation:

def cat(file_path: str) -> None:
    """
    Accepts a path to a file, and outputs the contents of that file
    """
    if os.path.exists(file_path):
        with open(file_path, "r") as file:
            for line in file:
                print(line, end="")
    else:
        print("Not a file!")

As long as all your functions are defined in the same module, you can simplify your whatis command:

def whatis(command: str) -> None:
    """
    Prints a description about the passed command
    """
    try:
        print(globals()[command].__doc__)
    except KeyError:
        print("Not a valid command!")

Although this does open you up slightly to a user getting access to the __doc__ attribute of any object in the global namespace (not sure if that is a security risk, though). To avoid this, you can also built a white-listed dictionary:

DOCS = {f.__name__: f.__doc__ for f in [ls, cd, clear, tree, whatis, cat]}

def whatis(command: str) -> None:
    """
    Prints a description about the passed command
    """
    try:
        print(DOCS[command])
    except KeyError:
        print("Not a valid command!")

I think the docstrings should be in the same style as linux manpages, i.e. like you have in your module docstring.


Evaluation of a solution for Run-length encoding algorithm

Avoid printing in methods, unless the purpose of the method is speicifically to print. The main purpose of the runLength method is certainly not to print. It should return the compressed value instead.

The description doesn't say that you should treat upper and lowercase characters equal. It's not correct to do that. And if you really wanted to do that,
it would have been simpler to lowercase the entire input string once.
This is a very wasteful operation:

for (int i = 0; i < str.length(); i++) {
    c = str.toLowerCase().charAt(i);

This would have been much better:

String lowered = str.toLowerCase();
for (int i = 0; i < lowered.length(); i++) {
    c = lowered.charAt(i);

Declare variables with the interface type, when possible.
Instead of:

HashMap<Character, Integer> hash = new HashMap<Character, Integer>();

This would have been better:

Map<Character, Integer> hash = new HashMap<Character, Integer>();

Btw are you still on Java6? You should definitely migrate to at least Java7,
where the above declaration becomes simply:

Map<Character, Integer> hash = new HashMap<>();

Note that in most use cases, StringBuilder is preferred over StringBuffer.
StringBuffer is synchronized, StringBuilder is not, which makes it faster.
In this program you don't need synchronization when building the compressed string.

Suggested implementation

This is simpler, without a hashmap:

public String compress(String str) {
    if (str.isEmpty()) {
        return "";
    }

    char[] chars = str.toCharArray();
    StringBuilder builder = new StringBuilder();

    int count = 1;
    char prev = chars[0];
    for (int i = 1; i < chars.length; i++) {
        char current = chars[i];
        if (current == prev) {
            count++;
        } else {
            builder.append(count).append(prev);
            count = 1;
        }
        prev = current;
    }
    return builder.append(count).append(prev).toString();
}

Unit testing

It's always good to have unit tests to verify correctness:

@Test
public void test_aabcccccaaa() {
    assertEquals("2a1b5c3a", compress("aabcccccaaa"));
}

@Test
public void test_a5() {
    assertEquals("5a", compress("aaaaa"));
}

@Test
public void test_empty() {
    assertEquals("", compress(""));
}

@Test
public void test_a() {
    assertEquals("1a", compress("a"));
}

@Test
public void test_a3b4() {
    assertEquals("3a4b", compress("aaabbbb"));
}

@Test
public void test_abc() {
    assertEquals("1a1b1c", compress("abc"));
}

@Test
public void test_wwwggopp() {
    assertEquals("3w2g1o2p", compress("wwwggopp"));
}


From a practical use point of view:

I'd use input.Max() (LINQ) to obtain the maximum. Less code to write and does the same.
While it is ok to use single letter variables for loop counter j is not really a loop counter. It's the index of the current element so I would rename j into currentIndex.
Consider changing your last while loop into a for loop. This avoids mutating the state of the count array (saves you a read and write on every iteration):

for (int k = 0; k < count[i]; k++)
{
     output[currentIndex++] = i;
}

Even on a 64 bit system the size of an array is limited to 2GB. So if your largest key is in the vicinity of Int32.Max / 4 or larger then you will get an OutOfMemoryException. Depending what else you are doing in your program you will get it much earlier. If you are experimenting around with sorting algorithms then there are some interesting approaches reducing the key space.


Optimizing a function with nested loops and if condition

Disclaimer: I have not tested any of these optimizations. Some of these optimizations could potentially even harm the speed - or they could already be covered by the JVM. Do your own benchmarking.

Helping the Compiler/JVM
If you don't need to override this method, declare it final. The compiler might inline the method if it thinks it helps. Additionally, declare constants as final - such as numTiles.

Preventing repeated lookups
You need to access x[i], tilecoords[j], z[i] and such multiple times. Consider storing those in temporary variables. Don't forget to test to see if it is actually faster to do so. An example (with really bad variable names - you might want to pick better names than xi and zi

for(int i=0;i<nRigidBodies;i++)
{
    // Check for the loaction of each tile to find which one should be switched on...
    //currently only supports 4
    float xi = x[i];
    float zi = z[i];
    for(int j=0;j<numTiles;j++)
    {
        if ((xi > tileCoords[j][0]) && (xi < tileCoords[j][1]) && (zi > tileCoords[j][2]) && (zi < tileCoords[j][3]))
        {
            serial[i]=j+1;
            break;
        }
    }
}

Fixing bugs
int serial[]=new int[nRigidBodies]; creates a new int array with a size of nRigidBodies. int's default value is 0. Thus, the entire array will be filled with 0. Given that your innerloop starts at index 0 and sets the "found" index into the array, it's possible it's setting 0 over the default value. That's not so important. What is important is the reverse implication: If the serial array contains a 0 at a given index, you do not know whether this is because no tile-index was found, or because the tile-index that was found was the first one.


Toggle dropdown menus for different menu items with Jquery

I think you can use html attribute to group it.

eg.

 or
 or whatever

and then

$('#main-menu [data-toggle="dropdown"]').hover(function(e) {
    $(e.currentTarget).find('ul').stop().slideToggle();
});


Inheritance: declare a method that returns the current instance class

let v = new Vector2(1, 2);
let w = v.opposite();
// this is wrong, since w is not a 2-dimensional vector
console.log(w.x);

The fact that the .opposite() returns a result that does not fit into the expected use cases, suggests that there is a design issue. In other words, it is a "hint" that Vector2 is not really a Vector in terms of OOP. Why so? Because it does not follow the intuitive contract in which the .opposite() method returns same exact type of the vector as the one on which the method is being invoked. Things will only get worse if one will need to work against a Vector3, Vector4, etc.

There's whole bunch of sources that explain how inheritance is very often not the best way to create new types nor reuse code.

If I was to design the VectorOf2, I would make it wrap the Vector class rather than inherit from it.

class VectorOf2 {
    private _vector: Vector;

    constructor(x: number, y: number) {
        this._vector = new Vector(x, y);
    }

    get x(): number {
        return this._vector[0];
    }

    get y(): number {
        return this._vector[1];
    }

    opposite(): VectorOf2 {
        return new VectorOf2( ... );
    }
}

With this design, each method added to Vector2 is always Vector2-specific and there's no confusion about it. The regular Vector's method can still be reused by VectorOf2 when a new method is implemented.


Multi threaded application to send large no of emails

Instead of rolling your own version of a parallel for each loop, you should use Parallel.ForEach(). It will make your code simpler, avoid the possibility of bugs in your Run() method and you will still be able to configure the number of threads used (through ParallelOptions).

  I start up five threads, but it will add up five more before the first five complete.

If I understand your code correctly, the only way this could happen is if you called Run() for a second time. If that's the case, it might make sense to use the producer-consumer pattern using BlockingCollection<T> and GetConsumingEnumerable() (or GetConsumingPartitioner() if you decide to switch to Parallel.ForEach()).

  How many threads can my server handle?

There is no way for us to answer that. You will have to perform your own measurements.

  I have database update inside the process. Is that good idea?

I don't see why would that cause any significant issues.

  Is there a chance that some threads will never finish?

There is no way for us to know that without seeing the code you didn't show.


Short Erlang function to demonstrate hd and tl

First, your code sample does not produce warnings under the Erlang compiler (I'm almost certain that specific version does not matter).

$ cat bar.erl
-module(bar).

-export([headAndTail/1]).

headAndTail(List) ->
  Head = hd(List),
  Tail = tl(List),
  {Head, Tail}.

$ erlc bar.erl
$

Now, regarding bad practises, the only comment is that what you are trying to do with hd and tl is usually done with pattern matching in functional programming languages:

headAndTail([Head|Tail]) ->
    {Head, Tail}.

Another minor bad practise is that Erlang's common naming convention does not use CamelCase for function names, preferring names_with_underscores instead. CamelCase is ok for variables.


Unnecessary matrix generation

In JavaScript, Arrays don't have a fixed size. For example, you could do this:

var arr = [];
arr[324] = 91;

with no problem.

Your GenerateMatrix function is really over-doing it. All you need to do is create the arrays for the rows/columns then change their values.

And, you can do that with a neat trick:

Array.apply(null, Array(rowCount)).map(function(){return []});


Simplifying multiple click events into something more extendable

The easier (imho) solution would be to store what you want in an nested object containing the matches :

var selectors = {
  left: {
    'something': ['third text replacement', 'more here'],
    'third text replacement': ['now the next item', 'something new here'],
  }
};

var $textContainer = $('#textContainer')
  , $elsewhere = $('.elsewhere');
for (var sel in selectors) {
  void function(sel, matches) {
    $('#'+sel).click(function() {
      for (var i = 0; i < matches.length; ++i) {
        // change "this.value" if it's not an input
        if (this.value == matches[i]) {
          // we found a match, let's update the value
          $textContainer.text(matches[i][0]);
          $elseWhere.text(matches[i][1]);
          // and return early
          break;
        }
      }
    });
  }(sel, selectors[sel]);
}


Brotli compression algorithm, translated from Python into Haskell

don't use lists

Almost any non-trivial operation on lists is O(n) or worse. Python is using mutable arrays. Haskell also mutable arrays, so why not use mutable arrays?

The only problem with Haskell's arrays is that there are so many choices to make:

pure vs. mutable
boxed vs. unboxed
array vs. vector
run in the ST monad or IO?

Here is the routine coded in Haskell which uses both pure and mutable unboxed vectors. It could be improved, but this is basically how you would go about it.

(code updated)

module Lib
where

import Control.Monad
import Control.Monad.Primitive
import Control.Monad.ST
import qualified Data.Vector.Unboxed.Mutable as UVM
import qualified Data.Vector.Unboxed as UV

calculate_codes :: PrimMonad m => UV.Vector Int -> UV.Vector Int -> m (UV.Vector Int)
calculate_codes tree codes = do
  next_codes <- UV.thaw codes
  UV.generateM (UV.length tree) $ \i -> do
    let x = tree UV.! i
    z <- if x /= 0
           then do y <- UVM.read next_codes x
                   UVM.write next_codes x (y+1)
                   return y
           else return 0
    return z

test = do
  let tree = UV.fromList [ 3, 3, 3, 3, 3, 2, 4, 4 ]
      codes = UV.fromList [ 0, 0, 0, 2, 14 ]
      next = runST $ calculate_codes tree codes
  print next

{-
tree      = [ 3, 3, 3, 3, 3, 2, 4, 4 ]
next_code = [0,0,0,2,14]

def calculate_codes( tree, codes ):
    tree_code = {}
    next_code = copy.copy( codes )
    for i in range(len(tree)):
        if tree[i] != 0:
            tree_code[i] = next_code[ tree[i] ]
            next_code[tree[i]] += 1             -- This "effectful" line is throwing me off.
    return tree_code

print calculate_codes( tree, next_code )
-}


Although DOM elements can be used like normal JavaScript objects, I'd avoid attaching JavaScript other than handlers. The problem is when they form circular references. In browser garbage collectors, they won't collect garbage if something still references them. If you accidentally form circular references, this will lead to memory leaks (unfreed memory)

jQuery avoids this by creating objects in an internal cache and assigns an ID to the element. That way, you are assigning a primitive to the element, not an object. This is how jQuery collects and manages event handlers, data attributes, and others.

So a general tip is: What is from JavaScript, stays in JavaScript. (And not cross over to the DOM)
In jQuery's case, the functions are not actually attached to the element. That's the purpose of the "jQuery object". In a gist, a jQuery object is just an array-like object (let's call it "pseudo-array" from this point on), that contains DOM elements. The prototype of the jQuery object is where the functions live. These functions operate on each value in the collection.

Executing a function in a jQuery object is not like this:

someElement.doSomething();

But rather, something like this:

collectionOfStuff.forEach(function(DOMElement,i,arr){
  //do something for each in the collection
});

Widget in your code is some function that manufactures "widget templates" which are used to bind to your elements. Rather than having Widget return the template, why not make Widget your namespace. You can then create a function that attaches to the namespace.

It would be synonymous to doing jQuery.fn.extend(function(){...})

//define widget
Widget.defineWidget('Page',function(){

  //local stuff, aka "private"
  var privateVar = 'foo';
  function privateFn(){...}

  //anything attached to `this` is "public"
  //we will execute this function, providing an object as `this`
  this.publicVar = 'bar';
  this.publicFn = function(){...}

});

//access widget
var reference = Widget.Page(bindingTarget);

defineWidget define a creator function into the namespace that uses the widget definition to build instances, something like:

Widget.defineWidget = function(name,fn){

  //store
  wigetCache[name] = fn;

  //attach to namespace
  Widget[name] = function(){

    //BaseClass could be some constructor with prototype containing
    //all functions that widgets should have
    var instance = new BaseClass();

    //run the instance through the definition to attach the internals
    return fn.call(instance);
  }
}


Performance optimization in function for datastructure mapping

The following code is about 35% faster (measured with Benchmark). The tricks:

no anonymous array created for $tmp.
explicit return removed.
variables created in place where their value is needed.

Some of the tricks added just a 3%, the first one seemed the most important. YMMV.

I experimented with $_ and maps, too, but it seems the plain old C-style loop is the fastest.

sub faster {
    my ($self, $columns, $rows) = @_;
    my $retval = {
        row_count   => my $row_count = @$rows,
        col_count   => my $col_count = @$columns,
    };
    for (my $col_index = 0 ; $col_index < $col_count ; $col_index++) {
        my $tmp;
        for (my $row_index = 0 ; $row_index < $row_count ; $row_index++) {
            $tmp->[$row_index] = $rows->[$row_index][$col_index];
        }
        $retval->{$columns->[$col_index]} = $tmp;
    }
    $retval
}


The performance of your current code depends a little about the implementation of the list, but what I primarily would have done is to extract first and last to variables that get initialized once, not in each iteration.

var first = result.FirstOrDefault();
var last = result.LastOrDefault();
foreach (var item in result)
{
   item.First = first == item;
   item.Last = last == item;
}

Secondly, if you're sure that all initial items have false at both the First and Last properties, then you don't need to use a loop at all, just do something like this:

if (result.Any())
{
    result.First().First = true;
    result.Last().Last = true;
}

I am no C# expert but this should give you an idea.

However, I'd question why you have the First and Last properties in the first place. Are you really really sure that you need them as properties? It feels to me that there's a risk that they will be inconsistent with their actual position in the list. And if you have access to the list itself where you want to get the value of the First/Last properties, well then you don't need the properties at all, do you?


When generating prime numbers with the sieve of Eratosthenes, you can treat 2 as a special case.  All other prime numbers are odd, so you can increment by 2:

for(int p = 3; p*p <= n; p += 2)

When you find a prime number \$p\$, you have already eliminated all multiples of prime numbers below \$p\$.  This means starting at \$2p\$ and going up is eliminating already eliminated multiples.  You can start at \$p^2\$, and since you are only concerned with odd numbers, go up multiples of \$2p\$

        for(int j = p*p; j <= n; j += 2*p)

When looping over the array for printing, you could again skip all even numbers, by going up by 2.  But make sure you start on an odd number!

m |= 1;
for(int i = m; i <= n; i += 2)

If you reversed your sense of the flag array, so true means "not prime", you wouldn't have to loop through the array to set all elements to true at the start.  They would start off as false, which would mean "prime".

Marking all prime numbers on one pass, and then looping through your marked array printing out prime numbers is looping twice for possibly no reason.  You can simply print out the prime numbers as you find them, if it is inside the required range.  It would require some juggling, and optimization tricks to ensure you print out a number only when required, and only exactly once.

You generate the sieve 10 times, if you have 10 test cases.  Maybe you could examine all 10 test cases, find the largest end point, and generate the sieve once???


Solution to Project Euler #1 - multiples of 3 and 5

In Scheme, we use hyphens to separate words, not underscores. Also boolean-returning procedures should end in ?. So it should be multiple-of?
Instead of (equal? x 0), use (zero? x).
Instead of a recursive loop, you can use for comprehensions:

(for/sum ((i (in-range 1000))
          #:when (or (multiple-of? 5 i)
                     (multiple-of? 3 i)))
  i)

Surely, that's much more readable. In my humble opinion. :-)
Notwithstanding the last comment, your formatting for your primes procedure is not ideal. Here's a more proper formatting:

(define (primes current total)
  (if (< current max)
      (primes (add1 current)
              (+ total (if (or (multiple-of? 5 current)
                               (multiple-of? 3 current))
                           current
                           0)))
      total))


Implementation of lru_cache for daily "top categories" query

From what I understand, the lru_cache is not the right tool when it comes to caching things in a production web application. Depending on how the web application is deployed, you would usually end up having multiple web server processes serving your application. Which means, that the LRU cache will be created in the memory space of every process. It's like if you would use the local-memory caching:

  Note that each process will have its own private cache instance, which
  means no cross-process caching is possible. This obviously also means
  the local memory cache isn’t particularly memory-efficient, so it’s
  probably not a good choice for production environments. It’s nice for
  development.

In other words, you should not be caching with Python, cache with Django built-in caching mechanisms in an external storage - a database, or a memcached or redis instance.    For instance, in a simple case to avoid external dependencies, you can just use a cache table in your database:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

Then, you can cache the result of top_categories in this table, letting Django handle the cache record expiration.


You're asking the wrong question. The right question is "What should I use instead of query?" The answer is that if you want to reinvent the wheel, you should use prepared statements, and if you don't then you should use an ORM which uses prepared statements under the hood. Prepared statements allow you to pass in parameters and ensure that the escaping is done correctly. E.g. you would use "SELECT * FROM foo WHERE bar = ?" passing parameter "baz" rather than "SELECT * FROM foo WHERE bar = " . mysqli_real_escape_string("baz").


It will not work well, I think. The only way to escape boxing on storing is to have a value type collection, so all your commands will need to be of the same type...
Also structs are very specific things, have a look below:

Here about Boxing/unboxing.
Size/speed issues - try to run this test.
See Using Structs:

When you create a struct object using the new operator, it gets created and the appropriate  constructor is called. Unlike classes, structs can be instantiated without using the new operator. In  such a case, there is no constructor call, which makes the allocation more efficient. However, the  fields will remain unassigned and the object cannot be used until all of the fields are initialized.
When a struct contains a reference type as a member, the default constructor of the member must be  invoked explicitly, otherwise the member remains unassigned and the struct cannot be used. (This  results in compiler error CS0171.)
There is no inheritance for structs as there is for classes. A struct cannot inherit from another  struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class  Object. A struct can implement interfaces, and it does that exactly as classes do.


Count values in one dataframe that are less than all the values in another

It may be a good idea to sort the columns you wish to compare first. That way you can iterate over both lists a single time. The idea is to use the index to keep track of how many items are larger than the values in your first list. A relatively untested function is:

import pandas as pd
import time

df1 = pd.DataFrame()
df2 = pd.DataFrame()
df1['a'] = [0.23, 1.2]
df2['a'] = [0.22, 1.25, 0.3, 0.5, 0.9, 0.0] * 1000 # Add some extra work

def sol(da, db):
    # Sort your columns
    x = sorted(da)
    y = sorted(db)

    t = []  # The results
    yi = iter(y)  # Use of an iterator to move over y
    yindex = 0
    y_item = next(yi)

    for val in x:
        # Search through y to find the index of an item bigger than val
        while y_item <= val:
            if yindex == len(y) - 1:
                t.append(0)
                return t
            y_item = next(yi)
            yindex += 1
        # Use the length of y and the index to find the number of item
        # larger than the current val
        t.append(len(y) - yindex)
    return t

t0 = time.time()
print sol(df1['a'], df2['a'])
print time.time() - t0

>>> [4000, 1000]
0.00200009346008

The problem with your initial solution is that you iterate over your second list for every value in your first list giving you an n^2 run time. This can be seen if you increase the length of the first list a bit. Ive modified your function a little to demonstrate:

def sol0(df1, df2):
    b = df2['a']
    for bio_row in df1.itertuples():
        a = float(bio_row[1])
        total = pd.eval('b > a')
        df1.set_value(bio_row[0], 'sim_p_val', total.sum())
    return df1

Testing with the following shows how the n^2 approach can get slow with longer lists, using the sorted list approach is ~750x quicker in this example:

df1['a'] = [0.23, 1.2] * 1000
df2['a'] = [0.22, 1.25, 0.3, 0.5, 0.9, 0.0] * 1000

t0 = time.time()
res = sol(df1['a'], df2['a'])
print time.time() - t0

df1['sim_p_val'] = [0]*len(df1)
t0 = time.time()
df1 = sol0(df1, df2)
print time.time() - t0

# Verify the result is the same
print res == sorted(list(df1['sim_p_val']), reverse=True)

>>>0.0024299621582
1.78539991379
True


First of all, it's great that you've used type signatures for all your functions. Also, all used functionality is hidden away in helpers, which is also a plus.

We can rewrite burstNative with  maximumBy and comparing:

import Data.List (maximumBy)
import Data.Ord (comparing)

burstNaive :: [Int] -> (Int, IndexOrder)
burstNaive [] = (0, [])
burstNaive xs = maximumBy (comparing fst) . allOrders $ xs

While it's possible to use ((0, []) . allOrders instead of the pattern matching, matching makes the base case more visible.

Also, this is a perfect spot to use IndexOrder instead of [Int].

In withOrder we traverse the list too often. Since lists are just forward linked lists in Haskell, we have to walk through the list four times, once for left, once for right, once for xs !! i and once for splitAt. That's a handful. So instead let's do that only once:

-- def: default value if list is too short/at end
moveAtStencil3 :: a -> Int -> [a] -> ((a,a,a), [a])
moveAtStencil3 def i xs
   | i < 1     = let (m:r:_) = xs in ((def, m, r), drop 1 xs)
   | otherwise = let (as,bs) = splitAt (i - 1) xs
                     (l:m:r) = take 3 (bs ++ repeat def)
                 in ((l,m,r), as ++ (l : r : drop 3 bs)

withOrder :: IndexOrder -> [Int] -> Int
withOrder []     _  = 0
withOrder (i:is) xs = left * middle * right + withOrder adjusted xss
  where
    ((left, middle, right), xss) = moveAtStencil3 1 i xs
    adjusted = map (\index -> if index > i then index - 1 else index) is

While we're at it, I renamed adjust to adjusted. Verbs (adjust) are usually functions, whereas adjusted is a list.

We could replace permutations in allOrders with recursion, but that wouldn't change much.


the (val · ¬cur · pos) | (¬val · ¬cur) = ¬cur (val·pos | ¬val) = ¬cur (pos | ¬val). So, the condition is

if ( (i != current) && (!val || [self isCurrentPosition:i]) ) {
        [self replaceObjectAtIndex:i withObject:@""];
    }

You just must practise factoring out the common subexpressions and subprograms and learn how to use the Carnot maps for boolean minimization.


import numpy
from numpy import *
import csv

df1 = csv.reader(open('cdd.ny.csv', 'rb'),delimiter=',')
tmp = list(df1)
b = numpy.array(tmp).astype('string')
b1 = b[1:,3:5]
b2 = numpy.array(b1).astype('float')

Firstly, I'd avoid all these abbreviated variables. It makes it hard to follow your code. You can also combine the lines a lot more

b2 = numpy.array(list(df1))[1:,3:5].astype('float')

That way we avoid creating so many variables.

nrow = b1.shape[0]
intercept = ones( (nrow,1), dtype=int16 )

b3 = empty( (nrow,1), dtype = float )

i = 0
while i < nrow:
    b3[i,0] = b2[i,0]
    i = i + 1

This whole can be replaced by b3 = b2[:,0]

X = numpy.concatenate((intercept, b3), axis=1)
X = matrix(X)

If you really want to use matrix, combine these two lines. But really, its probably better to use just array not matrix.

Y = b2[:,1]
Y = matrix(Y).T

m1 = dot(X.T,X).I
m2 = dot(X.T,Y)

beta = m1*m2

print beta


A benchmark is a scientific experiment.
An essential feature of a scientific experiment is that it be reproducible.
You do not provide any C++ code. You do provide some Go code. You do not define your methods for measuring CPU and memory. You provide some undefined CPU and memory measurements.
Your Go code looks inefficient.

1001. Reverse
Root
The input stream contains a set of integer numbers Aᵢ (0 ≤ Aᵢ ≤ 10¹⁸).
The numbers are separated by any number of spaces and line breaks. A
size of the input stream does not exceed 256 KB.
For each number Aᵢ from the last one till the first one you should
output its square root. Each square root should be printed in a
separate line with at least four digits after decimal point.

Compare my Go code (revroot.go) to your slower Go code (revroot.ivan.go):
$ ls -s -h revroot.in.data
256K revroot.in.data
$

$ go build revroot.go && time ./revroot < revroot.in.data > revroot.out.data
real    0m0.007s
user    0m0.007s
sys     0m0.000s
$ go build revroot.go && time ./revroot < revroot.in.data > revroot.out.data
real    0m0.008s
user    0m0.008s
sys     0m0.000s
$ ls -s -h revroot.out.data
208K revroot.out.data
$

$ go build revroot.ivan.go && time ./revroot.ivan < revroot.in.data > revroot.out.data
real    0m0.251s
user    0m0.141s
sys     0m0.113s
$ go build revroot.ivan.go && time ./revroot.ivan < revroot.in.data > revroot.out.data
real    0m0.245s
user    0m0.147s
sys     0m0.100s
$ ls -s -h revroot.out.data
208K revroot.out.data
$

revroot.go:
package main

import (
    "bufio"
    "fmt"
    "io"
    "math"
    "os"
    "strconv"
)

func RevRoot(in io.Reader, out io.Writer) error {
    var a []float64

    s := bufio.NewScanner(in)
    s.Split(bufio.ScanWords)
    for s.Scan() {
        i, err := strconv.ParseUint(s.Text(), 10, 64)
        if err != nil {
            return err
        }
        a = append(a, math.Sqrt(float64(i)))
    }
    if err := s.Err(); err != nil {
        return err
    }

    w, ok := out.(*bufio.Writer)
    if !ok {
        w = bufio.NewWriter(out)
    }
    defer w.Flush()
    buf := make([]byte, 0, 32)
    for n := len(a) - 1; n >= 0; n-- {
        buf = strconv.AppendFloat(buf[:0], a[n], 'f', 4, 64)
        buf = append(buf, '\n')
        _, err := w.Write(buf)
        if err != nil {
            return err
        }
    }
    err := w.Flush()
    if err != nil {
        return err
    }

    return nil
}

func main() {
    err := RevRoot(os.Stdin, os.Stdout)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
    return
}

revroot.ivan.go:
package main

import "fmt"
import "math"

var a []int64

func main() {
    for {
        var x int64
        k, _ := fmt.Scan(&x)
        if k != 1 {
            break
        }
        a = append(a, x)
    }
    n := len(a)

    for n > 0 {
        n--
        fmt.Printf("%.4f\n", math.Sqrt(float64(a[n])))
    }
}

In Go, to measure performance we run benchmarks. We exclude I/O and other OS functions.
$ go test revroot_test.go revroot.go -run=! -bench=. -benchmem
BenchmarkRevRoot-4   249   4775861 ns/op   833577 B/op   13202 allocs/op
$

My RevRoot function takes 4,775,861 nanoseconds (0.004,775,861 seconds) for 13,177 square roots.
revroot_test.go:
package main

import (
    "bytes"
    "io/ioutil"
    "math/rand"
    "strconv"
    "strings"
    "testing"
)

func BenchmarkRevRoot(b *testing.B) {
    buf := bytes.NewBuffer(make([]byte, 0, 256*1024))
    r := rand.New(rand.NewSource(42))
    for {
        buf.WriteString(strconv.Itoa(r.Int()))
        buf.WriteString("\n")
        if buf.Len() > 256*1024-256 {
            break
        }
    }
    data := buf.String()

    b.ResetTimer()
    for N := 0; N < b.N; N++ {
        err := RevRoot(strings.NewReader(data), ioutil.Discard)
        if err != nil {
            b.Fatal(err)
        }
    }
}


I thought it might be faster to:

first merely evaluate the value "standard" truth with !!value
then add conditions for your special requirements (including 'false', not cited in your question but present in your code)

This way, it also reduces the code, like this:

var isTrue = function(value) {
  return (!!value && value !== '0' && value !== 'false'
    && !!(typeof value !== 'object' || Object.keys(value).length));
}

console.log(false,isTrue(false));
console.log("'false'",isTrue('false'));
console.log(true,isTrue(true));
console.log(0,isTrue(0));
console.log(1,isTrue(1));
console.log("'0'",isTrue('0'));
console.log("'1'",isTrue('1'));
console.log("'test'",isTrue('test'));
console.log('{}',isTrue({}));
console.log('[]',isTrue([]));
console.log('Object',isTrue({a: 1}));
console.log('Array',isTrue([1]));

Now we can observe that it works more than 2 times faster.
Here an execution of the same cases set as above, repeated 100 times:

var isTrue = function(value) {
  switch (typeof(value)) {
    case "string":
      return !(value === '0' || value === 'false');
    case "number":
    case "boolean":
      return !!value;
    case "object":
      return Object.keys(value).length > 0
  }
}

var isTrue_2 = function(value) {
  return (!!value && value !== '0' && value !== 'false'
    && !!(typeof value !== 'object' || Object.keys(value).length));
}

var values = [false, 'false', true, 0, 1, '0', '1', 'test', {}, [], {a: 1}, [1]],
    times = 100;

console.time('isTrue');
for (var i = 0; i < times; i++) {
  for (var value of values) {
    isTrue(value);
  }
}
console.timeEnd('isTrue');

console.time('isTrue_2');
for (var i = 0; i < times; i++) {
  for (var value of values) {
    isTrue_2(value);
  }
}
console.timeEnd('isTrue_2');

Last point of interest: if you can have some statistics about how much the special requirements appear, you may change the order of the conditions to put the most frequent cases first, so yet improving performance.


Displaying sorted results of a web crawl

Removing duplication is a very worthy goal.  Just "factor out" the feature-extraction functions ("f-e-f"s):

import operator

class Sorter(BaseCrawler):

    def __init__(self, base_dir):
        self.base_dir = base_dir

    def _sort(self, fef, *options):
        file_list = [(fn, fef(fn)) for fn in self.files(*options)]
        return sorted(file_list, key=operator.itemgetter(1))

    def by_size(self, *options):
        def fef(fn): return float(os.path.getsize(fn))
        return self._sort(fef, *options)

    def by_mtime(self, *options):
        return self._sort(os.path.getmtime, *options)

etc, etc.

Not sure why by_size needs that float rather than the natural int returned by os.path.getsize (I'd rather do the float cast, if needed, downstream), but I've kept that dubious choice to show how best to deal with a f-e-f that's not already a plain existing function (hint: not with a lambda:-).

Other improvements are feasible which don't deal with duplication but with efficiency.  For example, consider:

def last_modified(self):
    '''
    Return the last modified file.
    '''
    return self.by_mtime()[0]

this does a lot of work (list building and sorting) that it doesn't need to do (and actually does not meet its name and docstring: it returns the file modified earliest, because the sort in by_mtime is in ascending order).  How much simpler to do...:

def last_modified(self):
    '''
    Return the last modified file.
    '''
    return max(self.files(), key=os.path.getmtime)

(this one fixes the bug; to maintain the bug, use min in lieu of max).


I think your choice of using a nested map/vector structure is a good one, and I think it is pretty idiomatic to Clojure. It can be tricky to work with nested structures like this, but it's certainly doable.

Your find-in function (and the private functions it depend on) is an imperative kind of solution -- you're iterating through the maps/lists and building up a "key vector" from scratch. I'm not sure if there is a strictly non-imperative way to navigate tree structures like this, but there is at least a much simpler way. You should have a look at clojure.zip. It provides zippers, which are data structures that represent a location in a tree-like data structure, and they keep track of the path that it took to get there.

With zippers, the approach to representing the "location of" (or "path to") an item is a bit different. To use your example:

(get-in master-list [:list 0 :list 0 :list 0])

This returns the node {:name "Come up with the plot" :details "What do I want to talk about?"}. In zipper terminology, this is "down down down" -- if you visualize the tree in your mind, with the master list as the root, you go down and end up at the first item in the list ("Writing"), then down again to the first item of that list ("Write A Best-Seller"), and then down a third time to the first item of that list, which is "Come up with the plot." Here's how you would code that:

(require '[clojure.zip :as z])

; (def master-list
;   ...)

(def zipper-list (z/zipper map? :list #(assoc %1 :list %2) master-list))

(-> zipper-list z/down z/down z/down z/node)

Zippers can be confusing at first, so I'll explain how this one works. The function clojure.zip/zipper takes 4 arguments:

A function that, given a node in the tree, returns true if that node can have children, even if it currently doesn't. I used map? because each node we're working with is a map that can potentially have a :list field, containing children.
A function that, given a branch node, returns a seq of its children. In this case, we can use :list as a function to get a given node's children (in Clojure, a keyword can be used as a function to look itself up in a map).
A function that takes two arguments -- (1) an existing node and (2) a seq of children -- and returns a new branch node that has the supplied children. In our case, the function would be #(assoc %1 :list %2).
The actual structure that we're navigating; in this case, it's master-list.

Now you can pass the zipper through any of clojure.zip's handy methods for navigating zippers. Once you've reached the node you want, you can use the clojure.zip/node method to return the actual data in the node.

I'm not sure what your use case is, but it sounds like you might want to have a way of representing an "address of" or "path to" a certain node. Working with zippers, you could actually represent a node's location as a list of the zipper functions necessary to reach it, something like this:

(def come-up-with-a-plot [z/down z/down z/down])

And then if you wanted to, you could write a helper function that inserts the zipper and the directions into a form just like we used above, sandwiched between -> and z/node:

(defn get-node [zipper directions]
  (eval `(-> ~zipper ~@directions z/node)))

(get-node zipper-list [z/down z/down z/down])

As an alternative, you could use a nested map structure that has only maps, no vectors, and use the names of each node as their keys:

(def master-list
   {:details "One List to Rule them all"
    "Writing"
      {:details "Writing things is fun"
      "Write A Best-Seller"
        {:details "Making money is also fun"
         "Come up with the plot"
           {:details "What do I want to talk about?"}}
      "Write for the New York Times"
      {:details "People need to hear this"}}
    "Reading"
      {:details "I have a long list of books to read"
       "The Catcher in the Rye"
         {:details "Who is Holden Caulfield and Why should I care?"}}
    "Profit"
      {:details "All Done"}})

This way, you would access each node using the exact names of each node in the tree in string form, like this:

(get-in master-list ["Writing" "Write A Best-Seller" "Come up with the plot"])

The obvious downside of this method is that it's vulnerable to accidental variation in the string keys. You might accidentally type, say, "Come up with a plot," and get nil as a result because the map doesn't have that key. Another downside is that maps aren't ordered or sorted, so any items that you add in (say by using assoc) are not stored in any particular order; although, you could remedy this by using ordered lists.

If you want my 2 cents, I think zippers are the best way to go for something like this. :)


Leap year check in Haskell, using pattern matching or bind operator

The first one is a lot more readable, whereas the second one uses a "hack". I would go with the first one, except that I would use rem, which is a little bit faster. And one could introduce some DRY:

isDivisibleBy :: Integral n => n -> n -> Bool
isDivisibleBy x n = x `rem` n == 0

isLeapYear :: Integer -> Bool
isLeapYear year
  | divBy 400 = True
  | divBy 100 = False
  | divBy   4 = True
  | otherwise = False
 where
   divBy n = year `isDivisibleBy` n

That being said, for a programming challenge, your version is perfectly fine:

isLeapYear :: Integer -> Bool
isLeapYear year
  | year `rem` 400 == 0 = True
  | year `rem` 100 == 0 = False
  | year `rem`   4 == 0 = True
  | otherwise           = False

The latter can be rewritten without >>= as list comprehension:

isLeapYear :: Integer -> Bool
isLeapYear year = head [isLeap | (interval, isLeap) <- classifications
                               , year `isDivisibleBy` interval]
  where
    classifications = [(400, True), (100, False), (4, True), (1, False)]

You could get rid of the "hack" with safeHead and maybe False, but that's left as an exercise.

If you really want to use check, remove the y. It just introduces an additional error source:

isLeapYear :: Integer -> Bool
isLeapYear year = head $
                  [(400, True), (100, False), (4, True), (1, False)]
                  >>= check
  where check (interval, isLeap) = [isLeap | year `rem` interval == 0]

Note that this shows perfectly that >>= is just flip concatMap for lists. So let's take advantage:

isLeapYear :: Integer -> Bool
isLeapYear year = head $ concatMap check classifications ++ [False]
  where
    check (interval, isLeap) = [isLeap | year `rem` interval == 0]
    classifications = [(400, True), (100, False), (4, True)]

Which is easier to grasp than the version with >>=.


Writing a JTable to a tab delimited file

Most of the issues with this code are stylistic and violations of Java conventions rather than functional.

public class excel {

Class names should always be capitalized (e.g., public class Excel).  Your class should probably also be named more descriptively and appropriately.  Your class isn't Microsoft Excel.  It's a class which converts JTable data into a CSV.  So it would make more sense to name your class JTableConverter or something like that.

String columnNames[] = { "Column 1", "Column 2", "Column 3" };

Class fields should always have an explicit access modifier (public, private, or protected).  Generally, if they're constants (as you use them), they are either public static final or private static final with the name in ALL_CAPS_WITH_UNDERSCORES.  For an understanding of static, you can see this StackOverflow Q&A.

So... private static final String[] COLUMN_NAMES = { "Column 1", "Column 2", "Column 3" };

excel() {
    table = new JTable( dataValues, columnNames );
}

Constructors and methods should also have an explicit access modifier.  (public JTableConverter())

public void toExcel(JTable table, File file) {

Method names should generally be verbs or verb phrases (such as convertToExcel).  Also, since you're passing in the JTable to be used, it would make more sense for this to be a static method rather than an instance method.  If you want it to be an appropriate instance method, there's no need to pass in the JTable at all, since the instance will already have access to the JTable table field.

excel.close();

Releasing or closing resources should pretty much always be done in a finally block, which is guaranteed* to run.  i.e.,

FileWriter writer = new FileWriter(file);
try {
    //stuff
}
catch(IOException ioe) {
    //handling
}
finally {
    try {
        writer.flush();
        writer.close();
    }
    catch(IOException ioe) {
        //handling
    }
}

And, finally ...

public static void main(String[] o) {
    excel cv = new excel();
    cv.toExcel(cv.table,new File("H:\\cs.tbv"));
}

It's a bit nitpicky, but it's usually better to have your main method in a separate driver class (like JTableConverterDriver).


Sort dictionary by increasing length of its values

Calling a dictionary a list is very confusing
Rather than using min, you could use sorted.

This'll change the time complexity of your code from \$O(n^2)\$ to \$O(n \log n)\$, as Python uses the Timsort. And since sorted is written in C, it'll be super fast too.

Sorted also has the keyword argument key, which lets you sort by another value, rather than the value you get.

This also keeps the original dictionary intact.
You can use dict and enumerate to build your input list. And to build a list to pass to enumerate you could use str.split.

And so I'd change your code to:

def sort_dict_by_value_len(dict_):
    return sorted(dict_.items(), key=lambda kv: (len(kv[1]), kv[0]))

def sort_dict_by_value_len_without_key(dict_):
    return [(k, dict_[k]) for _, k in sorted((len(v), k) for (k, v) in dict_.items())]

dict_ = dict(enumerate('one two three four five six seven eight nine ten'.split(), start=1))
for key, value in sort_dict_by_value_len(dict_):
    print(key, value)

If you only want \$O(1)\$ memory usage, then you could use an insertion sort. But keeps the \$O(n^2)\$ time complexity. I also cheated a bit.

I used a generator comprehension, rather than a list comprehension to ensure \$O(1)\$ space. Alternately, you could invert the algorithm, and pop from one array to another.
I used bisect.insort to remove most of the logic.

def sort_dict_by_value_len(dict_):
    output = []
    while dict_:
        key, value = dict_.popitem()
        bisect.insort(output, ((len(value), key), (key, value)))
    return (i[1] for i in output)


Python hint number 1:

The pythonic way to do :

n = 1
while n < 1000:
    # something using n
    n = n + 1

is :

for n in range(1,1000):
    # something using n

Python hint number 2:

You could make your code a one-liner by using list comprehension/generators :

print sum(n for n in range(1,1000) if (n%3==0 or n%5==0))

Your code works fine but if instead of 1000, it was a much bigger number, the computation would take much longer. A bit of math would make this more more efficient.

Math hint number 1 :

The sum of all the multiples of 3 or 5 below 1000 is really the sum of (the sum of all the multiples of 3 below 1000) plus (the sum of all the multiples of 5 below 1000) minus the numbers you've counted twice.

Math hint number 2 :

The number you've counted twice are the multiple of 15.

Math hint number 3 :

The sum of the multiple of 3 (or 5 or 15) below 1000 is the sum of an arithmetic progression.


It's hard to suggest simplifications without a greater understanding of the problem being solved.  However, this is perhaps a bit more readable:

$dates = array(
    array('type' => 'age',        'start' => $birthday,   'stop' => 'now' ),
    array('type' => 'membership', 'start' => $datejoined, 'stop' => 'now' ),
    array('type' => 'promoted',   'start' => $lastpromo,  'stop' => 'now' ),
);

foreach($dates as $date)
{
    $start = date_create($date['start']);
    $stop  = date_create($date['stop']);
    $interval = date_diff($start, $stop);

    switch($date['type'])
    {
        case 'age':
            $age = $interval->format('%y');
            break;

        case 'membership':
            $years      = $interval->format('%y');
            $months     = $interval->format('%m');
            $membership = floor(($years*12)+$months);

            if($membership >  1) { $suffix = 'Months'; }
            if($membership == 1) { $suffix = 'Month'; }
            if($membership <  1) { $suffix = 'Month'; $membership = '< 1'; }
            break;

        case 'prompted':
            $years    = $interval->format('%y');
            $months   = $interval->format('%m');
            $test     = $interval->format('%a');
            $promoted = floor(($years*12)+$months);

            if ($promoted  > 1) { $suffix = 'Months ago'; }
            if ($promoted == 0) { $suffix = 'Month ago';  }
            if ($promoted  < 1) { $suffix = 'ago'; $promoted = '< 1'; }
            break;
    }
}

?


How can I make this code safer against XSS attacks?

XSS attacks affect the whole web, regardless of the stack you're using, you always have to be careful. Based on the redirect url you provided and the queries you execute, I'm assuming you're building an on-line address book. If a client were to fill in the form, saying his name were:

">Gotcha

Your code would simply insert that in the database, properly escaped, of course. The escaping is what mysqli_real_escape_string does. It doesn't sanitize, it protects the Database, not the site. I can't, for example, post something like "bobby'; -- DROP TABLE contacts;", which is a basic example of an injection attack. But storing markup in a DB isn't wrong or dangerous as far as MySQL is concerned, so the data above can be safely inserted, and queried later on. However, when you request a list of contact names, you would get an alert, showing you your cookies. That's annoying, but not that bad. However, Check these examples to get a basic idea of how XSS attacks work, and what they can be used for.
They're used to bypass login systems, send client data to a third party or even inject/alter your page links to link to another, even more mallicious site:

All your links have now changed to link to another site. Your entire site navigation has been compromised.
The first step to prevent this is to sanitize your data:

$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    //don't insert, redirect back, with a GENERIC error message
    die('Not all input fields contained the expected data');
}

Why, you might ask, not point out to the client which bit of data failed the checks? Simply because if you were to say "Please fill in valid emai", the attacker knows to not to use that input field, and fill in something like bill.gates@microsoft.com, and try his luck with the other fields.

Another useful thing to do is to avoid actual script tags from being send to the client when using user-supplied data:

echo htmlspecialchars(strip_tags($someUserData));
//or if some markup is allowed:
echo strip_tags($someUserData, '

');

In case some markup is allowed, though, best go about that like wiki does: using custom markup like [paragraph]text[/paragraph], to avoid having to parse the supplied DOM and filter-out all attributes that contain what might be JS.

Here's another site with an array of attack examples, and a how to defend against them.
Here's a list of XXS weak-spots, introduced by HTML5


Python: Combing two programs that analyze strings

Firstly, a quick review of what you've done:

import string is unnecessary really. You utilize string.find, but you can simply call the find method on your first argument, that is, seq.find(sub, n, len(seq)).

In your second method, you have:

if str1[i] == str2[i]:
    x = x + 1
else:
    x = x

The else statement is completely redundant here, you don't need it.

I think we can simplify the logic quite a bit here. I'm going to ignore raw_input and take the strings as arguments instead, but it doesn't change the logic (and is arguably better style anyway). Note that this is not fantastically optimized, it can definitely be made faster:

def similar_strings(s1, s2):
    '''Fuzzy matches s1 with s2, where fuzzy match is defined as
    either all of s2 being contained somewhere within s1, or
    a difference of only one character. Note if len(s2) == 1, then
    the character represented by s2 must be found within s1 for a match
    to occur.

    Returns a list with the starting indices of all matches.

    '''
    block_size = len(s2)
    match = []
    for j in range(0, len(s1) - block_size):
        diff = [ord(i) - ord(j) for (i, j) in zip(s1[j:+block_size],s2)]
        if diff.count(0) and diff.count(0) >= (block_size - 1):
            match.append(j)
    if not match:
        return None
    return match

How does this work? Well, it basically creates a "window" of size len(s2) which shifts along the original string (s1). Within this window, we take a slice of our original string (s1[j:j+block_size]) which is of length len(s2). zip creates a list of tuples, so, for example, zip(['a','b','c'], ['x','y','z']) will give us back [(a, x), (b, y), (c, z)].

Then, we make a difference of all the characters from our s2 sized block of s1 and our actual s2 - ord gives us the (integer) value of a character. So the rather tricky line diff = [ord(i) - ord(j) for (i, j) in zip(s1[j:+block_size],s2)] will give us a list of size len(s2) which has all the differences between characters. As an example, with s1 being abcdefefefef and s2 being cde, our first run through will give us the slice abc to compare with cde - which gives us [-2, -2, -2] since all characters are a distance of 2 apart.

So, given diff, we want to see how many 0's it has, as two characters will be the same when their ord difference is 0. However, we need to make sure there is at least 1 character the same in our block (if you simply pass in z, or any string length 1, diff will always have length 1, and block_size - 1 will be 0. Hence diff.count(0) >= 0 will always be True, which is not what we want). Thus diff.count(0) will only be true if it is greater than 0, which protects us from this. When that's true, look at the block size, make sure it is at least len(s2) - 1, and if so, add that index to match.

Hopefully this gives you an idea of how you'd do this, and I hope the explanation is detailed enough to make sense of some python constructs you may not have seen before.


Manual attack

First of all, your encryption scheme is very weak and easily exploitable. Given a few hundred characters of ciphertext, even a novice cryptanalyst can crack this cipher in less than 30 minutes with only pen and paper. I recommend you stick to industrial-strength ciphers.

Security by obscurity

The obfuscations you are talking about (making a .pyd file and so on) will do little if anything to stop a serious attacker. The closest analogy I can think of is putting your door mat over the key, instead of just leaving the key in plain sight outside your door. It doesn't work very well. Any true encryption scheme needs to adhere to Kerchhoff's Principle, which states that a cryptosystem must be secure even if all parts of it (apart from the encryption key) are known by the attacker.

Wrong approach

In other words, you are approaching the problem from the wrong angle. For example, obfuscating the files won't help, because if an attacker has access to the computer the program is run on, he/she can access the memory directly to view the cleartext and/or key. Even worse, the attacker may even have a keylogger running. You need to design an algorithm that is so secure that having a completely open-source program isn't a problem. That is exactly what the people behind e.g. GPG have done. However, securing such a program against a malicious user isn't practically possible.

The problem is that cryptography is really, really hard. Some of the brightest people on the planet are continuously working to create new, unbreakable ciphers -- and still those ciphers are often broken.

What to do instead

I recommend reading about common cryptography principles and theory, and how basic ciphers are often broken. Don't bother with securing your program against a user - instead presume the program is running on a secure computer and make the ciphertext as secure as possible instead. Instead, write a cipher that is resistant to common techniques like frequency analysis and similar lexical attacks.

Finally, if you want easy and completely uncrackable encryption, I recommend looking into one-time pads. They are cryptographically secure, but they require a key that is at least as long as the plaintext.


Chomp the new line

    scan.nextLine();                // But why?

Nothing to do with performance, but Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()? explains this.

Remove unnecessary data structure

    String[] numbers = new String[total];

You never use numbers as an array.  You could get rid of it entirely.

        numbers[i] = scan.nextLine();
        numbers[i] = convert(numbers[i]);
        if(!dict.containsKey(numbers[i])) {
            dict.put(numbers[i], 1);
        } else {
            dict.put(numbers[i], dict.get(numbers[i]) + 1);
        }

Replace numbers[i] with a single String.

        String number = convert(scan.nextLine());

        Integer count = dict.get(number);
        if (count == null) {
            count = 0;
        }
        count++;

        dict.put(number, count);

Now we don't keep an array around for nothing.

I also changed the get/put pattern.  This saves having to do both the containsKey check and the get.

Consider other data structures

    Map<String, Integer> dict = new TreeMap<String, Integer>();

I would expect a TreeMap to be slower than a HashMap for most applications that depend on insert and read efficiency.  This is especially so since it sorts on keys and what you want is to find all with at least value 2.  You'd need to override the comparison to get that behavior.

You don't use the read behavior that would be helpful.  And you accept the slower writes.

        Map<String, Integer> dict = new HashMap<>();

This should perform faster for larger inputs.

Pick the right method

    for(String number: dict.keySet()) {
        if(dict.get(number) > 1) {
            hasDuplication = false;
            System.out.println(number + " " + dict.get(number));
        }
    }

This is the use case for an entrySet.

    for (Map.Entry<String, Integer> entry : dict.entrySet()) {
        if (entry.getValue() > 1) {
            hasDuplication = true;
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }

Now we don't have to do an expensive get lookup operation on each iteration.

I'd also switch the meaning of hasDuplication to match the name.  Don't forget to switch it the other two places as well.

    boolean hasDuplication = true;

to

    boolean hasDuplication = false;

and

    if(hasDuplication) {

to

    if (!hasDuplication) {

Other possibilities

If this doesn't help, consider splitting reading the input from processing it.  So something like

    for (int i = 0; i < numbers.length; i++) {
        numbers[i] = scan.nextLine();
    }

    scan.close();

    for (String number : numbers) {
        number = convert(number);

        Integer count = dict.get(number);
        if (count == null) {
            count = 0;
        }
        count++;

        dict.put(number, count);
    }

I didn't test this, so you may have to declare a new variable rather than reusing number.


Stored procedure to describe the reason that a particular employee is unsuitable for a particular task

A handful of critiques:

As mentioned in the comments, this is undefined behavior: SELECT @val = @val + ColumnName FROM AnyTable. As such, you should avoid it. If you need to, use STUFF or STRING_AGG instead
When creating a temp table, (n)varchar columns should specify their collation (e.g. COLLATE DATABASE_DEFAULT ) to avoid errors in case server collation and database collation differ.
Using RETURN or a chain of IF ELSE IF etc is going to raise fewer eyebrows than GOTO
Don't just blindly insert into a table; always specify a column list.
Its cheaper to use table variables than temp tables; SQL Server doesn't need to do as much work for statistics and fewer latches of creation are required.
You generally don't need to drop the temp table (assuming this is called from a stored procedure) as that'll get done automatically by SQL Server
You could probably just return the list of disciplines + an error code, and let the consuming application handle presenting it in a friendly way. This also makes I18N someday in the future much easier.


Since this checksum function is only used for TCP packets, there is no need for supporting packets larger than 65535 bytes. Rather than adding needless overflow checks, you should restrict the bytes parameter by making that a uint16_t.

Note that both the original code and your improvement only work on big endian implementations, unless some outside code byteswapped the whole TCP packet, in which case the code only works on little endian implementations. The + 1 for accessing the last byte makes the latter more probable. This + 1 was not present in the original code, so chances are high that you introduced a bug. Did you test with odd-sized packet length?

You should make the spacing of the code consistent, either by removing all spaces around binary operators (not recommended) or inserting spaces at the appropriate places. Currently it is a mixture of both.

Since you don't modify the incoming buffer, you should declare that. Make the data const void *.

You don't need to write 1 == bytes, since any decent compiler will emit a warning if you would ever accidentally use a single = here. You should write the natural bytes == 1 instead, or if you fear typos, bytes > 0.

The bytes -= 1 is unnecessary and can be left out.


Getting JSON with jQuery, creating a function that displays the data from two separate feeds

Code Cohesion

A great way to simplify code is to break things up so that each section focuses primarily on one specific task. I think your biggest problems with this are in your $.forEach(networkGroup.list loop, in which it appears you are mixing three separate tasks:

getting the symbol
getting the data limit
producing html

Price: getting the symbol

Here's a quick tip to simplify converting the currencyLetter to the currencySymbol. Instead of using a list of if else blocks, it would be best to factor this part of the code out into its own function and use an object to map the keys:

function getCurrencySymbol(currencyLetter) {
  return {
    "USD": "$",
    "GBP": "£",
    "JPY": "¥",
    "EUR": "€"
  }[currencyLetter];
}

This shortens the code, makes it easy to add other currencies, and allows the function to be used in other places.

$.each(dataPlan.list, function (i, list) {
  var currencySymbol = getCurrencySymbol(list.currency); // note you misspell curencySymbol

  //Price
  content = '
';
  content += '' + curencySymbol + list.price + '	';
  //Data Limits
  // ...

Data Limits: getting the data limit

I'd also recommend breaking out the part of code where you find the data limit into its own function for similar reasons:

function getDataLimit(list) {
  if (list.dataUnlimited) {
    return = 'Unlimited';
  }
  else {
    var dataLimitInKB = list.dataLimitInKB;
    var measure;
    var data;

    if ((dataLimitInKB / (1024.0 * 1024.0)) >= 1.0) {
      measure = " GB";
      data = dataLimitInKB / ((1024.0) * (1024.0));
    }
    else if (dataLimitInKB / 1024.0 >= 1.0) {
      measure = " MB";
      data = dataLimitInKB / 1024.0;
    }

    data = Math.round(data * 100) / 100;
    return data + measure;
  }
}

Now the code in the $.forEach loop is focused primarily on generating the HTML which makes it much easier to see what's going on:

$.forEach() {
  //Price
  content += '' + getCurrencySymbol(list.currency) + list.price + '	';

  //Data Limits
  content += '' + getDataLimit(list)+ '	';

  //Data Length
  content += '' + list.validityPeriodInDays + '&nbsp;Days	';
  content += '
';
  $(content).appendTo("#dataplan_list");
}

It would be a good idea to break up the code even more to limit how far the indentation gets. Currently, there are too many things nested inside of each other which adds a lot of complexity.

That all said, this is some pretty intense code for some of your first JavaScript. Nice work!


One speed tweak is to search to only the square root of the 'possiblePrime'.  This will reduce computation by a significant order of magnitude.

Another tweak is to add 2, instead of 1 to 'possiblePrime' as you know that all even numbers > 2 are not prime.


There are quite some things you can improve here, this list may not cover everything that could be improved though:

Adhere to the Java naming conventions. Classes are named in PascalCase for example, so it would be public class Meow. On other places it seems fine.
Use proper indentation everywhere, this definately applies to the main method inside public class meow, as all items should be intended one to the right. This may also apply to the while loops, I would prefer to write while(sc1.hasNext()){ as while (sc1.hasNext()) { for readability.
Variable names are not expensive. sc1, sc2 are dubious, but could be ok. However inW and inL are plain alarming, the fact that you need to comment to explain them is a bad sign. My suggestions are wordIndex and lineIndex.
Consider using a StringBuilder over dealing with raw strings. This means for example that:

String text = "", code = "";
while(sc1.hasNext()){
     text += sc1.next() + " ";
}

could be rewritten as:

StringBuilder sb = new StringBuilder();
while (sc1.hasNext()) {
        sb.append(sc1.next()).append(' ');
}
String text = sb.toString();

You have a bug in your second while-loop. You check for sc2.hasNext() and you take two times sc2.nextInt(). Your hasX() and nextX() calls should always match. This means that in the loop per iteration in total there should be two hasNextInt() calls with two nextInt() calls.
The same deal about StringBuilder applies here to your second while-loop for building code.
In the future you can consider switching to using the java.nio.Path API, over the old java.io.File API. I will not show more code here on how to do it, as it would completely change the structure of the program and is best used in conjunction with Java 8, which is not in the scope of this answer.


With the list comprehension you are filling a whole list with your values, and then you are sending that list to join.

Instead of a generating a list and then sending it, you can send a generator instead: similar to the list comprehension, but generates the values on-demand. With your old approach, if you had 10000 dates you would have them all at a list; with a generator it generates one at a time, so at least you will be consuming less memory.

With a generator, you would directly do:

dates = "('" + "'),('".join(str(start_date + dt.timedelta(d)) for d in range(day_diff)) + "')"

On a side note, the parameter names date1, date2 are not very explicit; it should be clear from the names which is the start and which is the end date.


Make a perfect Split based on absolute difference between max of two arrays

local_diff = abs(max(a[:i+1]) - max(a[i+1:]))

For every i the entire aray is walked through to find left and right maxima.
This is complexity O(N²).

One could have two arrays with left_maxima and right_maxima, O(N), so

local_diff = abs(left_maxima[i] - right_maxima[i])

Then the entire complexity is O(N).

The maxima can be filled with a loop over i, either increasing or decreasing, using:

left_maxima[i] = max(left_maxima[i-1], a[i])         // ++i
right_maxima[i] = max(right_maxima[i+1], a[i])       // --i

It is even so, that one array (left or right) is not needed in the final local_diff loop.

What makes this problem so devious is that at index i an evaluation has to happen from past < i and from the "future" > i.


NO. NO. NO. NO.

This does not do you any good none at all. In fact I think this is worse than doing nothing. All you have done is created a new layer that provides no advantages over the old and exposed a new set of error codes (that are not standard).

This is definitely NOT C++ code. You have just written another C layer that has all the same disadvantages of C and absolutely none of the benefits provided by C++.

The main thing to learn about C++ (in fact the overriding absolutely essential thing) is RAII. Resource acquisition is initialization. When you create an object it gets the resource, if it fails to get the resource during initialization you throw and the object does not exist and thus can not be used. Because the object only exists if it was correctly constructed most of the runtime checking to make sure the object is in the correct state disappears (because we know it is in the correct state because it exists).

I would expect the interface to a socket class to look like this:

Socket   webserver(8080);

while(webserver.accept(connection))
{
    InBoundConnection connection(webserver.buildConnection());

    connection.send(HttpObject(404, "Miss404 not found"));
}


HTML

The headline elements (h1-h6) are meant to be used only for headlines.  You have 3 of them, 2 of which only contain punctuation.  That's a misuse of the element.  If you need markup that's purely for styling purposes, use a span.

(
    envelop
    )

CSS

There's almost no reason to use min-device-width over min-width.  Ever.  There's also no good reason to specify a minimum bound on your "handheld" media query.  The following media query is just as effective, but significantly smaller:

@media only screen and (max-width : 480px) {
    // stuff
}

In a vast majority of cases, going mobile first with your media queries, rather than desktop first is going to get you smaller CSS.

// stuff all devices share
@media only screen and (min-width: 480px) {
    // stuff handheld devices don't need
}

You've got a significant amount of code duplication in your CSS because you're failing to take advantage of the cascade.  For instance, you're including your mLogoEffect_pre mixin 4 times, when you only need it once:

.logoeffect-left, .logoeffect-right {
    @include mLogoEffect_pre;
}

Your entire hover section has way more code than it needs because you're setting/unsetting/resetting properties.  It can be simply expressed like this:

&:hover
{
    .logoeffect-left
    {
        margin-right: -50px;
        margin-left: 40px;
        opacity: 1;
    }
    .logoeffect-right
    {
        margin-left: -50px;
        opacity: 1;
    }
}

I really must caution against splitting up your media queries like that.  It really increases the size of your compiled CSS.

@media (min-width: 480px) {
    .one-selector { }
}

@media (min-width: 480px) {
    .another-selector { }
}

@media (min-width: 480px) {
    .yet-another-selector { }
}

Seems a little silly, don't you think?  Media query bubbling is a fine feature of Sass, but it should be used conservatively.  Much better:

@media (min-width: 480px) {
    .one-selector { }
    .another-selector { }
    .yet-another-selector { }
}

Learn to love shorthand:

.foo {
    margin-left: 70px;
    margin-right: -80px;
    margin-top: 0;
    margin-bottom: 0;
}

Compared to:

.foo {
    margin: 0 -80px 0 70px;
}

On your .logocontainer, you have margin-left: 35%; for handhelds.  Why not just use text-align: right instead?  This will allow you to avoid wrapping that occurs on very narrow devices.

http://codepen.io/cimmanon/pen/JbHAC


Task scheduler for a particular application

First, I'd mention that scheduling execution of anything in Windows is better done through the Windows Task Scheduler. Scheduling your application that way would remove the "must run everyday at 4AM" requirement from the code, although I don't see how your code is enforcing that.
That said...
Magic Numbers & Configuration

DateTime scheduleTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 12, 45, 0);

"12" and "45" (and "0") are magic numbers here. These should be taken from configuration, or better yet, from command-line arguments.

The right hammer for the right nail
System.Int32 is an awesome hammer. But that doesn't make every number a nail.

int interval = 0;

You (present you - future you could be a different story) know they're seconds. But the name says nothing of it, and the type is making your life harder than it needs to be. The .NET framework has a struct specifically meant to represent a time interval, more precisely a time span - System.TimeSpan. Compare readability here:
TimeSpan interval = TimeSpan.FromSeconds(0);

Ambiguity: gone. And as a bonus, you no longer need to cast anything here:
    if (currentTime <= scheduleTime)
    {
        interval = scheduleTime.Subtract(currentTime);
    }
    else
    {
        interval = scheduleTime.AddDays(1).Subtract(currentTime);
    }

Oh, and it turns this:

_timer.Interval = (24 * 60 * 60 * 1000);

Into that:
_timer.Interval = TimeSpan.FromDays(1).TotalMilliseconds;

And that rids the code of an implicit conversion from int to double, since both TimeSpan.TotalMilliseconds and Timer.Interval are double.


Wait until all files are loaded asynchronously, then run code

1) Nah, the kids still call it JavaScript, but ECMAScript works too. More power to you for knowing both names :)

2) Yes, I'd say you should wait for a less ambiguous state to occur before considering the request done. But there's not really anything better than onreadystatechange (as far as I recall) to check for the request's success. So you still have to code a "ready-state change" handler, just make it check client.status === 200 (and possibly some headers and whatnot) before deciding what to call next.

Other than that, though, your code's good. The hardcoded 2 would need to go for this to be of general use, but the basic idea of decrementing a counter is solid.

You could take a look at the futures and promises pattern. There are several JS-implementations of this you can use.

jQuery has such an implementation (via the Deferred object) built into it's Ajax-system, allowing you to do, say:

var file1 = $.getJSON("file1.json"), // $.getJSON returns a Deferred
    file2 = $.getJSON("file2.json"),
    all   = $.when(file1, file2);    // and $.when groups several Deferreds

// example usage - you can do the same for the individual files
all.done(function () {
  // something to call when all files have been successfully loaded
});

all.fail(function () {
  // something to call in case one or more files fail
});

all.always(function () {
  // something to always call (like, say, hiding a "loading" indicator)
});

Point is that Deferred lets you attach handlers asynchronously - the requests are sent the moment you call getJSON, but you can attach handlers whenever. And you can add several handlers to the same state, if you want. If the response has already been received, the handler will simply be called immediately.

Now, I know this is all jQuery, and perhaps you don't want to use that. If so, more power to you (again). It is however a neat approach and a simple API - or (in my opinion) one to emulate if you so choose.

Seeing @Kevindra's simple answer (go upvote!), I'm reminded of a different pattern I've used before:

 // a simple factory function
 function makeCounter(limit, callback) {
   return function () {
     if( --limit === 0 ) {
       callback();
     }
   }
 }

 // ....

 // make a "done" function set up to expect 2 invocations
 // before calling its callback
 var done = makeCounter(2, function () {
   // all done!
 });

 getAsync("file1.json", function () {
   // process file and call the done() function
   done();
 )};

 getAsync("file2.json", function () {
   // process file and call the done() function
   done();
 )};


Printing a K-ary tree stored in level-order in an array

Your biggest performance problem is the repeated string concatenation using the + operator.  Since Java strings are immutable, every += operation requires allocating a new string and copying the previous contents.  Use a StringBuilder instead.

Math.pow() should be avoided, since it performs floating-point arithmetic, and this task should be accomplished using just integer arithmetic.  Why not keep track of the desired width of the current row, and use an inner loop to print each row?

public static void main(String[] args) {
    int k = 3;
    Integer[] arrInt = {0,1,2,3,null,null,null,7,8,9,10,11,12};

    StringBuilder ans = new StringBuilder();
    for (int i = 0, width = 1; i < arrInt.length; i += width, width *= k) {
        for (int j = i, end = Math.min(i + width, arrInt.length); j < end; ++j) {
            ans.append((j > i) ? " " : (j > 0) ? "\n" : "")
               .append(arrInt[j]);
        }
    }
    System.out.println(ans);
}


About the code:

List& operator =(const List<T>&)=default; and List(const List<T>&)=default; provide excellent opportunity to get double delete with 100% chance of success.
Your linked list required data to be copyable and it copies it on usage. It is bad, since now you cannot store data like std::unique_ptr that are not copyable. Also it is inefficient as it will have to copy large data structures like std::vector instead of moving their internal data around. Utilize std::move in functions like push_back/push_front.
Functions front()/back() should return data by reference so user can modify them. Also you ought to implement their const versions that return data by const reference (or by value for trivial enough data types).
std::list stores also the size of the list so the function call is lazy unlike your implementation. People generally assume that size() is a fast operation which is not the case in your implementation.
Normally in a linked-list you store both head and tail as otherwise all operations regarding the other end are ridiculously slow.
std::cout is not exactly thread safe. It doesn't crash or cause malfunctions but it might can mingle the characters you print. In a multi-threaded environment you need a logger.
Wait... your linked-list doesn't provide any options for iterating over elements. Only adding / deleting / exploring elements at the head/tail and even those are slow. You need iterators or something. One important aspect of a linked list is ability to move elements from one list to another efficiently. This functionality doesn't exist in this implementation.
Your mutex m is shared across all your linked lists-instances and types. If you want any sensible implementation of multi-threaded linked with mutexes list you ought to privately store a std::unique_ptr<std::mutex> for each instance of the linked-list.
Honestly, I don't know why you want to use a linked list or implement one - it is one of the slowest and most inefficient data structures.

In general, I don't think that it is a good idea to make a thread-safe linked-list. Make a concurrent linked-list at most I'd say (I not too familiar on this topic as far as I am aware it is still being researched). Just use std::list and have an associated mutex nearby so whenever user wants to do something with the list - they have to lock the mutex. It might be annoying to write and relying on the user to use it right is problematic but frequently user needs to make composite operations (several in a row without interruptions) which will result in program errors if another users locks the list in between these operations and does something with it.


Factory hierarchy for creating GoogleMap and its elements

I think your conception of the factory pattern is a little off.  Throughout your classes, you seem to want to deal with concrete factory objects, which doesn't seem to make sense.  Typically, a factory would be invoked statically and would not store local references (i.e. in properties) to the dependencies it is acting upon.

Your MarkerFactory class is close, just needing to have create() method defined as static and possibly defining the class itself as abstract since there would not seem to be any reason to ever instantiate it.

But getting into your other classes, there seem to be issues with where logic lies.  The InfoWindowFactory probably should not have a method such as renderWindowContent() on it.  That would seem to be a method that should perhaps exist on the InfoWindow itself.  Now, if the factory needs to call that method on a concrete window object to get it set up properly before returning it, that might be OK (though I might suggest the InfoWindow constructor is changed to trigger this action).

I would like to see InfoWindowFactory be something like:

namespace YourNamespace;

abstract class InfoWindowFactory
{
    public static final function create(
        Place $place,
        Twig_Environment $twig,
        $template
    ) {
        return new InfoWindow($place, $twig, $template);
    }
}

Note that we are pushing the render operation down into the InfoWindow object where it probably belongs.  Also note that we have removed the hard-coded template names from this class.  Maybe they truly belong here, in which case maybe they should be class constants rather than buried in a method. But, depending on how you are using these InfoWindows, perhaps this should be passed through as configuration.

My comments on MapFactory would be similar to those for the InfoWindowFactory.  Namely, I would rather see a class like structured like this:

namespace YourNamespace;

use MarkerFactory;
use InfowindowFactory;

abstract class MapFactory
{

    public static final function create(Coordinate $mapCenter, array $places = [], array $mapOptions = [], $isEditableMap = false)
    {
        $map = new Map();

        $map->setCenter($mapCenter);
        $map->setMapOptions($mapOptions);

        $markers = [];

        foreach ($places as $place) {
            $position = new Coordinate($place->getLatitude(), $place->getLongitude());

            $marker = MarkerFactory::create($position);
            $infoWindow = InfoWindowFactory::create($place, $isEditableMap);

            $marker->setInfoWindow($infoWindow);

            $markers[] = $marker;
        }

        $map->getOverlayManager()->setMarkers($markers);

        return $map;
    }
}

A comment about validation...

You are doing a good job of trying to enforce typehints on your methods, however I do wonder if it might make sense for you to have classes defined which deal with say a collection of Place objects.  These seem to be critical dependencies that can only be enforced to be an array via type-hinting, meaning that if you truly wanted to be able to validate that you have valid place objects in your array, you might have to go into undesirable approach of inspecting each array item to validate it.  If instead of passing simple array, you passed PlaceCollection or similar, you could be ensured that everything in that collection is a valid Place object.   Certainly, this adds yet another bit of code to the overall system, so really only you can determine if it is worthwhile to do this depending on how you are planning to use this code.  But it is something to consider when these are key items you are working with (vs. say optional configurations or similar).

Do you need any error or exception handling here?  Typically one of the things a factory would do is raise an exception if the dependencies that are passed are not valid (typehinting can do a lot of this for you) or to handle any underyling exceptions that might happen within method execution (i.e. can instantiation of a Map, InfoWindow, etc. object throw an exception?).  I don't really see any consideration here in your code for error or edge conditions.  It seems as if this is considering happy path only.


OO shopping cart class + product class interaction

I would have done it in the following way:

<?php
    class Product {
        private $id;
        private $type;
        private $price;

        public function __toString() {
            return  "your way to display the Product object ie:
 The id is: $this->getId
 ";
        }

        public function getId()
        {
            return $this->id;
        }

        public function setId($id)
        {
            $this->id = $id;
        }

        public function getType()
        {
            return $this->type;
        }

        public function setType($type)
        {
            $this->type = $type;
        }

        public function getPrice()
        {
            return $this->price;
        }

        public function setPrice($price)
        {
            $this->price = $price;
        }

    }

    class Cart {
        private $products;
        private $id;

        public function getProducts()
        {
            return $this->products;
        }

        public function addProduct(Product $product)
        {
            $this->products[] = $product;
        }

        public function getId()
        {
            return $this->id;
        }

        public function setId($id)
        {
            $this->id = $id;
        }

        /**
         * Returns the sum off all products prices
         * array_reduce docs: http://php.net/manual/en/function.array-reduce.php
         */
        public function total(){
            return array_reduce($this->getProducts(), function($carry, $product){
                return $carry + $product->getPrice();
            });
        }

    }

It's important to note here that you are managing objects, so you will need some Object Relational Mapper to persist objects on a DB, such as Doctrine.

You need to separate concerns in a MVC architecture, the logic of your domain the 'M' of MVC (in this case the shopping cart) reside in a object model (Product + cart) . Then you need the 'C' here you tell the cart that you want to add a new product:

class Controller {
        public function someAction(){
            $product = new Product();
            $product->setId(1);
            $product->setPrice(100.00);
            $product->setType(3); //Id of the type

            $cart = new Cart;
            $cart->addProduct($product);

            $cart->total(); //Will return 100.00
            //Logic to obtain twig engine
            return $twig->render('Template', ['cart' => $cart]); //returns HTML
        }
    }

And finally the V of the MVC there is where you build your HTML:

Using a template engine like Twig:

        Total: {{cart.total()}}

              {% for product in cart.products %}

{{product}}

              {% else %}

Empty cart

              {% endfor %}

Of course building this architecture on your own could be really complicated there is when frameworks like symfony kick in http://symfony.com/. It's just a personal recommendation.

Also, take a look at OOP patterns. They will make your life easier and you will learn how to program good architectures for models.


Are the returns within my session function actually needed?

As for your question, at least Get should not return false if the value is not set, now the caller will not know whether the actual value is false or whether the value is not set.

Other than that,

I would suggest you use PHP_SESSION_DISABLED , PHP_SESSION_NONE and PHP_SESSION_ACTIVE instead of 1, 2 and 3
To have Status_Session call session_status is confusing, maybe call it session_status_string ? Also, this should not return false, but maybe "Session status could not be determined"
I dont understand this : if (session_status() === 1){ $this->Session_Started = true; if session_status() == 1, then sessions are disabled, why would you set Session_Started to true ?
session_start() will return a boolean that indicates whether the session actually started, you should check that boolean instead of assuming success with $this->Session_Started = true;
session_start() also can resume a session, I am not a PHP master, but it seems to me you could replace init() with

public function init(){
    /* Start or Resume a session */
    $this->Session_Started = session_start();
    return $this->Session_Started;
}

Finally, if you are adamant about checking whether the session is started or not in set, would it not make sense to start the session for the caller, so that your code works auto-magically ?

public function Set ($Key = false, $Value){
  if (!isset($_SESSION)) {
    init();
  }
  $_SESSION[$Key] = $Value;
}

Also, as mini-tech commented, if you expect a session, and it is not there, then you might want to throw an exception instead of returning false.


Replacing MIN and MAX macros with type-safe, recursive templates of variable arity

Your implementation will work nicely for integers, however, it might be doing a lot of copies which could hurt you for more expensive types.

An edge case that might sometimes be useful in case of calling this via a template: the min/max of 1 number.

Your noexcept is wrong in case of throwing copy constructors. You could change this to noexcept(std::is_nothrow_copy_constructable<T>) or fix the remark above and prevent copies.

Looking at the template arguments, you do allow T1 and T2 to be of a different type. I don't see much added value in that, as you would get an obscure error about the ?: operator.

And to end with a positive note: I really like the constexpr. This allows you to write a unit test as a static_assert.


It appears that the file ConfigLoader.cpp is unnecessary unless you are just providing an example of usage.
The keyword inline is obsolete, it is really only a suggestion these days. Modern C++ compilers will make the decision on whether the code should be inlined or not when using the -O3 switch.
If you are going to let the user define the config file name, then pass the name into the constructor and default it at a higher level.


Docstrings with every method: Way to go, document MinHeap, too and revisit PEP257 for details.
Your MinHeap tackles the same task as module heapq using much the same strategy, and you express dissatisfaction with run time - a side by side comparison:

in many places, you compute something like node_number or parent_node to repeatedly index __items - not using that variable, but something like parent_node - 1
(Code the way you think about it: if there are multiple places where you want the element at index i-1, write a[i-1], b[i-1]…, if you think same index happening to be i-1, write j = i-1, a[j], b[j]…)
(An optimising compiler can be expected to eliminate common sub-expressions; that is more difficult for an interpreter to justify (and I seem to remember why it might be hard for python).)
insert() assigns the new value to every candidate position, while heapq._siftdown()/heappush() just moves down items of lesser priority and puts the new item once/twice.
extract_min() swaps the items at both ends instead of just replacing the top priority item (see heapq.heappop())
heapify() conditionally assigns None to left_child and right_child to go on and conditionally execute statements comparing these values to None (using != instead of is&not)

heapq._siftup() uses the realistic approach of not comparing values "on the way down": half the nodes are leaf nodes, it is much more likely that the new item will end up near the bottom of the heap.

heapq introduces heappushpop() as a "Fast version of a heappush followed by a heappop."

You seem to be bent on thinking of nodes numbered starting from 1 - nothing wrong with that, and coding the way you think about a solution/problem is the only sane way to start:
for a shot from the hip, allocate one more array element, don't use index 0 and drop all of "the - 1".


Proper cellForRowAtIndexPath cell return in Swift

First note that

func dequeueReusableCellWithIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath) -> UITableViewCell

is preferred over

func dequeueReusableCellWithIdentifier(identifier: String) -> UITableViewCell?

because – according to the documentation –

  This method uses the index path to perform additional configuration based on the cell’s position in the table view.

and because it returns a non-optional UITableViewCell.

If you just want to return one of the two possible prototype cells
then you don't need to cast at all.

But there is no need to make cell an optional. You can even
declare it as a constant, this allows the compiler to verify that it is assigned a value exactly once
on each code path.

let cell: UITableViewCell
if condition {
    cell = tableView.dequeueReusableCellWithIdentifier("AddSetCell", forIndexPath: indexPath)
} else {
    cell = tableView.dequeueReusableCellWithIdentifier("SetCell", forIndexPath: indexPath)
}
// ... set up common properties ...
return cell

If you want to assign specific properties to the different cell types
then you need to cast to the respective type.
Since  you define the  custom class SetTableViewCell for the prototype cell with identifier "SetCell" in the Storyboard,

tableView.dequeueReusableCellWithIdentifier("SetCell", forIndexPath: indexPath)

is guaranteed to return an instance of SetTableViewCell, either by
re-using a cell or by instantiating a new one from the prototype.
This is one of the legitimate use-cases of the
forced cast operator as!. Or to put it differently: The cast can only
fail if you did not define the prototype cell correctly. That would be
a programming error and should be detected early.

let cell: UITableViewCell
if condition {
    let aCell = tableView.dequeueReusableCellWithIdentifier("AddSetCell") as! AddTableViewCell
    // ... set up specific properties ...
    cell = aCell
} else {
    let sCell = tableView.dequeueReusableCellWithIdentifier("SetCell") as! SetTableViewCell
    // ... set up specific properties ...
    cell = sCell
}
// ... set up common properties ...
return cell

or alternatively with "early return":

if condition {
    let aCell = tableView.dequeueReusableCellWithIdentifier("AddSetCell") as! AddTableViewCell
    // ... set up properties ...
    return aCell
} else {
    let sCell = tableView.dequeueReusableCellWithIdentifier("SetCell") as! SetTableViewCell
    // ... set up properties ...
    return sCell
}

that is a matter of personal choice.

Finally, if you write your condition as

indexPath.row == tableView.numberOfRowsInSection(indexPath.section) - 1

then it will work for all sections, not only the first one.


Improve the wrap-around logic
There's obvious inefficiency in:
head %= bufferSize;

% uses division, but because we're incrementing, we know that head / bufferSize is at most 1.  Instead, we can:
if (++head >= bufferSize)
    head -= bufferSize;

On architectures such as ARM, there's no branch here, as any decent compiler will just use a condition flag on the subtraction.

Consider checking for overrun and underrun
At the moment, this buffer has no checking for the read and write positions crossing each other.  Perhaps that's what you need, but it's quite unusual to have an unchecked circular buffer, and if you were holding (e.g.) audio data, you can imagine how it would sound, given the output you show.

Match new and delete
Since you create buffer using new[], you must use the array form delete[] in the destructor:
CyclicBuffer::~CyclicBuffer()
{
    delete[] buffer;
}

Style points
Prefer initializers to assignment
A constructor should initialize all the members of the class:
CyclicBuffer::CyclicBuffer(std::size_t buffSize)
  : buffer(new char[bufferSize]),
    bufferSize(buffSize),
    head(0),
    tail(0)
{
}

A good compiler will warn you if you have uninitialized members (e.g. g++ -Wall -Wextra).
Note that I've also changed the argument to be a size_t, as a negative size is meaningless.  The int members should all be size_t, too.
Avoid numeric character constants
What's special about the number 45?  If you care about its character value, (and if you're using an ASCII-like system), it's clearer to write '-' instead.
Drop the commented-out code
I don't want to see using std::namespace;, ever.  Not even in a comment.