Sorting an array in different ways with efficient output I am going through some PHP array exercises on w3resource because I want to get to grips with all the different functions PHP offers for arrays. I have just done this one:

  Write a PHP script to sort the following associative array : array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40") in

  a) ascending order sort by value

  b) ascending order sort by Key

  c) descending order sorting by Value

  d) descending order sorting by Key

And here is my code:

<?php
    echo "
";

    $people = array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");

    function display($array)
    {
        foreach($array as $p => $a)
        {
        echo "$p\t $a
";
        }
    }

    //sorted by value, ascending
    asort($people);
    display($people);
    echo"
";

    //sorted by key, ascending
    ksort($people);
    display($people);
    echo"
";

    //sorted by value, descending
    arsort($people);
    display($people);
    echo"
";

    //sorted by key, descending
    krsort($people);
    display($people);

    echo "
";
?>

I was pretty content with how I solved this, using the display() helper method to cut down on typing.

However, the example on the website is as follows:

<?php
echo "
Associative array : Ascending order sort by value
";
$array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); asort($array2);
foreach($array2 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Ascending order sort by Key
";
$array3=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); ksort($array3);
foreach($array3 as $y=>$y_value)
{
echo
"Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Descending order sorting by Value
";
$age=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");
arsort($age);
foreach($age as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Descending order sorting by Key
";
$array4=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); krsort($array4);
foreach($array4 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
?>

This came across, to me, as flawed code in some ways, because I wondered why the same array was declared multiple times when it seems unnecessary.

Am I missing something with this example code? Is there a reason I should not use a display() helper method?
Is readability improved by following echo immediately with a line, as is done in the example?
Is it good practise to use the . concatenation operator alongside ' ' (single quotation marks), as opposed to simply putting everything inside " " (doubles)? (I find the latter more readable and easier to work with.)
Is it acceptable to place more than one statement per line, as is done in the example

$array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); asort($array2);

There isn't much to say about your code, it's pretty good. You avoided duplication by extracting code to functions, and your code is pretty clean in general.

Some nitpicks:

echo"<br>";: you are missing a space here
your array would also be more readable with an extra space after , and spaces around =>. Putting each array value on it's own line will increase readability even more (the extra space it takes up is well worth it).
your echo needs to be indented a bit more.
$p and $a could be $person and $age for more clarity.

Reviewing code not written by you is off-topic, so I'll be brief about that. But yes, you are right with all your questions. There is a lot of duplication in that code (the duplicate arrays might be explained by them wanting to sort the exact same array each time, instead of one that has already been changed by another sort function; in that case, a getPerson function would avoid duplication), the formatting is pretty bad (unnecessary newlines, no paragraphs, no indentation, lack of spaces, etc), multiple statements on one line, and so on.


Counting maximum number of elements in right order There is an source and target.
example:
source:[a,b,e,d,s,t,c,v,t]
target:[a,e,v,g,r,b,c,v,t]
target and source have same number of elements.
how can I count elements in source ordered correctly according to target?
so, target means that elements in source should be ordered in target's order.
and count maximum number of properly ordered elements in source.
so the answer for example is 5 (a,b,c,v,t).
of course there are two elements in order like (a,e),(a,b) but out put should be maximum elements.
how can I do it neat and compactly?
My code
I used combinations, counting from max element number to 0.
n=len(target)
k=1
for check in range(n,-1,-1):
            while k!=0:
                for j in combinations(souce,check):
                    if j in combinations(target,check):
                        answer_co.append(check)
                        k=0
                        break

This is a classical LCS problem, which can be solved in DP as suggested by earlier post. Time Complexity of the implementation is O(mn) which is much better than the original code implementation. (An exercise for the reader to study. ;-)
The next code fragment assumes that the source/target are both strings.
Here is the DP approach:
class Solution:

def lcs(self, source: str, target: str) -> int:
    n,  m = len(source), len(target)
    dp = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(n):
        for j in range(m):
            if source[i] == target[j]:
                dp[i + 1][j + 1]= dp[i][j] + 1
            else:
                dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
    return dp[-1][-1]


Creating a PDO abstract parent class I think many people for some reason use a singleton class to handle the PDO connection (?) but I was thinking it would be nice to have a parent abstract class initializing the connection and the child DAO classes would just have to extend that class and use a $db variable. Code below (I didn't test it so sorry if there are some syntax mistakes) and more explanation below the code.

abstract class AbstractDao {
    protected static $_db = NULL;

    public function __construct() {
        if(is_null(self::$_db)) {
            throw new MyDBException('No DB connection available');
        }
    }

    public static function loadDB($config) {
        static $lastConfig = NULL;
        if($config == $lastConfig) return self::$_db;
        self::$_db = self::connect($config);
        $lastConfig = $config;
        return self::$_db;
    }

    private static function connect($config) {
        $dsn = sprintf('mysql:dbname=%s;host=%s;port=%d;', $config['database'], $config['hostname'], $config['port']);
        $db = new PDO($dsn, $user, $pass);
        $db->exec("SET NAMES utf8");
        return $db;
    }
}

The $_db variable is static because I want to avoid to open many connections if I initialize many DAO classes (and thus if the $_db variable is static, I'll have one open connection for all my DAO classes). On the other hand it confuses me a bit because I have seen no one doing something like self::$_db->prepare(...). Maybe I am doing something wrong ?

Note also that loadDB with a default config array needs to be called in the application bootstrap.

Continuing on Peter Kiss's answer, the static keyword is indeed hard to test, but you don't have to worry about it when it's in a dependency container. If you use Inversion of Control and have your objects ask for a DB connection, rather than getting one, you don't have to worry about using singletons or static class properties – you just let the dependency layer manage connections, and this can be done with a simple static variable inside a closure (see below).

This answer is verbose, because I'm going to assume ignorance and try to explain Dependency Injection in as simple terms as possible (I still haven't found a concise explanation of DI). Afterwards, I'll explain how you can use DI to ensure no more than one DB connection is created.

You need to create a very generic container object to contain dependencies. At runtime, you insert these dependencies into this container (typically before you do anything else). Then, you pass this container to the constructor of any object with a dependency. The object then retrieves the dependency it needs from the container.

This allows the dependent object to be completely ignorant of how the dependency was constructed: e.g. a database object could have been constructed from PDO rather than MySQLi (though you'd want them to share the same API). This aids in making your code much easier to test by keeping object graph construction and application logic separate.

If you're using PHP 5.3+, I'd recommend looking into PIMPLE. Here's how you'd set things up.

// Construct the container and all dependencies
// This is usually done in a separate file

$container = new Pimple();
$container['db'] = function() {
    $db = ...; // Construct the DB connection
    return $db;
}

// Define a class that depends on the DB
class SomeObjectThatUsesDB {
    function __construct($container) {
        $this->container = $container;

        // No `new` keyword – this is a good thing!
    }

    function doSomething() {
        $db = $this->container['db'];
        // Do something with the DB
    }
}

// Use the class to do some work with the DB
$obj = new SomeObjectThatUsesDB($container);
$obj->doSomething();

The advantage here is $container['db'] can be anything as long as it shares the same API.

OK, so now let's talk about ensuring only one DB connection exists at any given time. Since the DI dependencies are just anonymous functions, you can just use the static keyword inside of the dependency definition; however, Pimple makes this even easier by providing a share() method that does this for you. As per the documentation:

  By default, each time you get an object, Pimple returns a new instance
  of it. If you want the same instance to be returned for all calls,
  wrap your anonymous function with the share() method

Here's what it looks like:

$container['db'] = $container->share(function($container) {
    $db = ...; // Construct the DB connection
    return $db;
});

This will make sure that sure only one $db is ever created. Here's the source code from Pimple's share() method for demonstration purposes:

/**
 * Returns a closure that stores the result of the given closure for
 * uniqueness in the scope of this instance of Pimple.
 *
 * @param Closure $callable A closure to wrap for uniqueness
 *
 * @return Closure The wrapped closure
 */
public static function share(Closure $callable)
{
    return function ($c) use ($callable) {
        static $object;

        if (null === $object) {
            $object = $callable($c);
        }

        return $object;
    };
}


First Rust program - squares which are sum of squares I've been programming in C++ for over a decade and am thinking of learning Rust. Finding a number whose square is the sum of three different positive squares in at least two disjoint ways, which I used in test code in a C++ program, I wrote a Rust program to find out what other numbers' squares can be written as the sum of three different positive squares. Here's the program; how can it be improved?
fn main()
{
  for a in 1..101
  {
    let mut b=1;
    while a*a-b*b>=0
    {
      let mut c=1;
      while a*a-b*b-c*c>=0 && c<b
      {
        let mut d=1;
        while a*a-b*b-c*c-d*d>=0 && d<c
        {
          if a*a-b*b-c*c-d*d==0
          {
            println!("{}²={}²+{}²+{}²",a,b,c,d);
          }
          d+=1;
        }
        c+=1;
      }
      b+=1;
    }
  }
}

How can it be improved? Well, it all depends on your goals with the code. I'll assume the goal is to make it prettier and more in line with typical Rust style.
First of all, while loops are rare in Rust code and you should replace them with for. This is because while works on your hand-rolled logic, whereas for .. in .. works with external iteration that is composable and idiomatic Rust.
I see you have one for loop already. Let's turn all others into for.
You always start with 1, so the first iterator will be (1..). We keep taking elements of the range as long as a condition is satisfied, so the next element of the iteration pipeline will be .take_while(|&b| ...). This Rust standard library method best fits the situation.
fn main()
{
  for a in 1..101
  {
    for b in (1..).take_while(|&b| a*a-b*b >= 0)
    {
      for c in (1..b).take_while(|&c| a*a-b*b-c*c>=0)
      {
        for d in (1..c).take_while(|&d| a*a-b*b-c*c-d*d>=0)
        {
          if a*a-b*b-c*c-d*d==0
          {
            println!("{}²={}²+{}²+{}²",a,b,c,d);
          }
        }
      }
    }
  }
}

This code is much more idiomatic already. Next up, I noticed that the intent of the two inner loops is to iterate until we hit the number above, so let's make two simple changes:

for c in (1..b).take_while(|&c| a*a-b*b-c*c>=0)
for d in (1..c).take_while(|&d| a*a-b*b-c*c-d*d>=0)

For readability, we can Don't-Repeat-Yourself by making a tiny function.
fn square_diff(a: i32, b: i32, c: i32, d: i32) -> i32 { a*a-b*b-c*c-d*d }

For all instances of a*a-b*b or a*a-b*b-c*c or ..., we replace them with square_diff(a, b, 0, 0) etc.
One more observation: (1..).take_while(|b| square_diff(a, b, 0, 0) >= 0) is equivalent to 1..=a.
Next up, we don't do C-style indentation in Rust. We put a single space after every comma in arguments. The result so far is:
fn main() {
  for a in 1..101 {
    for b in 1..=a {
      for c in (1..b).take_while(|&c| square_diff(a, b, c, 0) >= 0) {
        for d in (1..c).take_while(|&d| square_diff(a, b, c, d) >= 0) {
          if square_diff(a, b, c, d) == 0 {
            println!("{}²={}²+{}²+{}²", a, b, c, d);
          }
        }
      }
    }
  }
}

fn square_diff(a: i32, b: i32, c: i32, d: i32) -> i32 { a*a - b*b - c*c - d*d }

I tried to test whether these abstractions really reduce to zero-cost, but
alas, Rust@godbolt failed me. Benchmarking is left as a small exercise.
Good luck on your Rust journeys.


Doubly-linked list implementation I've made an implementation of a doubly-linked list, I spend quite some time trying to get it right. I used both gdb and valgrind to make sure there was no memory leaks or errors. There's not a lot of comments in there, so sorry about that. There's still some things that bothers me in the code, like checking if 'head->prev' is null before appending to it. I'm sure there's must be a better way to implement that, like keeping a pointer to the first node. Also, I've got a list_init() function because I thought it was easier and more clean, but I may be wrong. I may be wrong a lot, so correct me if I am. I'm still not done with the implementation as I still want to add more functions to it, like a list_sort() or reverse_list(), but I'll wait for more input, just to see that I'm on the right track. Thanks!

list.c

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

#include "list.h"

node *list_init()
{
    node *node_t = calloc(1, sizeof(node));
    if (!node_t) {
        fprintf(stderr, "Allocation failed on list_init().\n");
        return NULL;
    }
    return node_t;
}

void list_append(node *node_t, char *data)
{
    /*
     * If there's no previous entry, then we're at the first item of the list.
     */
    if (!node_t->prev) {
        node_t->data = malloc(strlen(data) + 1);
        if (!node_t->data) {
            fprintf(stderr, "Allocation failed on list_add().\n");
        }
        strncpy(node_t->data, data, strlen(data) + 1);
        node_t->prev = node_t;
        return;
    }
    while (node_t->next) {
        node_t = node_t->next;
    }
    node_t->next = malloc(sizeof(node));
    if (!node_t->next) {
        fprintf(stderr, "Allocation failed on list_add().\n");
        return;
    }
    (node_t->next)->prev = node_t;
    node_t->next->data = malloc(strlen(data) + 1);
    if (!node_t->next->data) {
        fprintf(stderr, "Allocation failed on list_add().\n");
        return;
    }
    strncpy(node_t->next->data, data, strlen(data) + 1);
    node_t->next->next = NULL;
}

void list_print(node *node_t)
{
    while (node_t) {
        printf("Value: %s\n", node_t->data);
        node_t = node_t->next;
    }
}

void list_remove_last(node *node_t)
{
    if (!node_t->next) {
        free(node_t);
        node_t->data = NULL;
        return;
    }
    while (node_t->next->next) {
        node_t = node_t->next;
    }
    free(node_t->next->data);
    free(node_t->next);
    node_t->next = NULL;
}

bool list_find(node *node_t, char *data)
{
    while (node_t) {
        if (!strcmp(node_t->data, data)) {
            return true;
        }
        node_t = node_t->next;
    }
    return false;
}

void list_destroy(node *node_t)
{
    node *current = NULL;
    while ((current = node_t)) {
        node_t = node_t->next;
        free(current->data);
        free(current);
    }
}

list.h

#ifndef __LIST_H__
#define __LIST_H__

#include <stdbool.h>

typedef struct node {
    char *data;
    struct node *prev, *next;
} node;

node *list_init();
void list_append(node *head, char *data);
void list_print(node *head);
void list_remove_last(node *head);
bool list_find(node *head, char *data);
void list_destroy(node *head);

#endif /* __LIST_H__  */

list_init should initialize all the members of the allocated node before returning.  This way the caller won't have to remember to NULL out the pointers it isn't explicitly setting.

One way a doubly linked list can be implemented is to use a fake node to hold the list head and tail pointers.  In your case, that node would always have a NULL data pointer, and initially the next and prev nodes would point to itself (this could be set up in a new list_create function, which could either initialize an already allocated node, or allocate and return a new one).

This would simplify list_append, as you'd already have a pointer to the last node, and you wouldn't need any extra code to handle an empty list (your current error handling in this case doesn't return after the fprintf, which will result in a crash).  'list_remove_last` would also be simplified.

Walking the list when using that fake node (like you do in list_print and list_find) would need a slightly different end condition.  You'd start at the head, walk to the first node, then stop when you find a node with a NULL data pointer (which would mean you're back at the head node).

Your current list_destroy has one problem, where the variable that is passed to it still points at the (now deleted) list when it returns, so the caller needs to handle this.  Using the fake node scheme, this would leave just the fake head node (which can be cleaned up via a list_destroy function).


Disabling buttons on forms I have 5 different forms where I am disabling the submit button when a valid form is submitted so the form can only be submitted once. I am using a hidden field on each form to get the form Id.

function OnSubmit(buttonId) {
var disableButton = false;

if ($('#formType').val() == 1) {
    if ($('#CreateEntityName').val() != "" && $('#newAccountGroup').val() != "") {
        disableButton = true;
    }
}
if ($('#formType').val() == 2) {
    if ($('#newAccount').val() != "" && $('#lastName').val() != "") {
        disableButton = true;
    }
}
if ($('#formType').val() == 3) {
    if ($('#select2-entityId').val() != 0 && $('#contact').val() != "") {
        disableButton = true;
    }
}
if ($('#formType').val() == 4) {
    if ($('#select2-entityId').val() != 0 && $('#contact').val() != "" && $('#need').val() != "" && $('#candidates').val() != 0) {
        disableButton = true;
    }
}
if ($('#formType').val() == 5) {
    if ($('#newAccount').val() != "" && $('#country').val() != "") {
        disableButton = true;
    }
}
if (disableButton == true) {
    $('#' + buttonId + '').attr("disabled", true);
}
}

@Html.Hidden("formType", 5)

I see a few things that can be done to tweak this:

Cache your selectors instead of re-querying the DOM each time. Anything you use more than once should be cached.
Since all of the form fields use ID's you can use the native getElementById for faster performance.
Use strict equality when your are evaluating to reduce the chance of a gotcha.
Use 'use strict;' if you aren't already.
Surround your code by an IIFE, to encapsulate it and create a private scope.
Namespace your code

`

(function($){
  'use strict';
  var validateForm = {};

  //shortcut functions to simplify code below
  function isEmpty(str) { return str === ''; }
  function isNotSelected(num) { return num === 0; }
  function id(str) { return document.getElementById(str).value+''; }
  function getNum(str) { return document.getElementById(str).value-0; }

  function onSubmit( buttonId ) {
    var disableButton = false;
    var formType = getNum('formType');

    //cache selectors below
    var contact= id('contact');
    var newAccount =  id('newAccount');
    //assuming this is a dropdown
    var el = document.getElementById('select2-entityId');
    var entityId = el.options[ el.selectedIndex ].value -0;

    switch( formType ) {
       case 1:
        if ( isEmpty(id('CreateEntityName')) && isEmpty(id('newAccountGroup')) ) {
          disableButton = true;
        }
        break;

       case 2:
        if ( isEmpty(newAccount) && isEmpty(id('lastName')) ) {
          disableButton = true;
        }
        break;

       case 3:
        if ( isNotSelected(entityId) &&  isEmpty(contact) ) {
          disableButton = true;
        }
        break;

       case 4:
        if ( isNotSelected(entityId) && isEmpty(contact) && isEmpty(id('need')) && isNotSelected(getNum('candidates')) ) {
          disableButton = true;
        }
        break;

       case 5:
        if ( isEmpty(newAccount) && isEmpty(id('country')) ) {
          disableButton = true;
        }
        break;
    }

    if ( disableButton ) {
      $('#' + buttonId + '').prop('disabled', true);
    }

    return disableButton;
  }

  validateForm.init = onSubmit;
  window.validateForm = validateForm;

  //document.ready if you need to do something else
  $(function(){
    if ( validateForm.init() ) {
      //do something here
    }
  });

})( jQuery );

I am sure there are other things that can be done.  Hope that helps!


Creating simulated items sold at a store into a hash I am writing code that creates a hash for a store that has an item, price, and sku.  The hash is inserted into an array.  I also create another hash based on the sku that holds the amount of inventory for that item.  I am new to Ruby and am looking for ways to improve my code.

 class SimStore
      def item_info
        random = Random.new
        price = random.rand(1.00 ... 75.00).round(2)
        item = 1.times.map { RandomWord.nouns.next }
        sku_random = Random.new
        sku = sku_random.rand(1000 ... 1000000)
        sum_store_hash = {:item => item, :price => price, :sku => sku}
      end

  def stock array_items_stock
    stock_hash = {}
    array_items_stock.each do |inventory|
       random = Random.new
       quantity = random.rand(10 ... 100)
       stock_hash[inventory[:sku]] = quantity
     end
    stock_hash
  end
end

items = 15;
array_items = []
hash_inventory = []
while items > 0
  items = items - 1
  sim_store = SimStore.new
  items_hash = sim_store.item_info
  array_items.push(items_hash)
end

hash_inventory = sim_store.stock array_items

The SimStore class doesn't seem to do much except create a hash and create an item. These seem like separate concerns

You really could use an Item class with a static method for stubbing out an Item.

First, let's start with an "Item" class:

class Item
  attr_accessor :price, :name, :sku, :quantity

  def initialize(name, sku, price, quantity)
    self.name = name
    self.sku = sku
    self.price = price
    self.quantity = quantity
  end

  def self.stub
    price = Random.new.rand(1.00 ... 75.00).round(2)
    name = 1.times.map { RandomWord.nouns.next }
    sku = Random.new.rand(1000 ... 1000000)
    quantity = Random.new.rand(10 ... 100)

    self.new name, sku, price, quantity
  end

  def to_h
    { name: name, price: price, sku: sku, quantity: quantity }
  end
end

It has a price, name and sku that is a getter and setter. A static, or class level method called Item.stub generates a fake item based on the code you are using. Lastly, it has a to_hash method for converting the Item into a Hash.

Now we can take one step back and think about your SimStore, which at this point doesn't simulate anything so we can rename it to Store:

class Store
  def items
    @items ||= []
  end

  def self.stub(number_of_items)
    store = self.new

    number_of_items.times do |i|
      store.items << Item.stub
    end

    store
  end

  def to_h
    items.map { |item| item.to_hash }
  end

  def sku_hash
    # For Ruby < 2.1
    array = items.map { |item| [item.sku, item.quantity] }
    Hash[array]

    # For Ruby >= 2.1
    items.map { |item| [item.sku, item.quantity] }.to_h
  end
end

It has an array of Items and a to_hash method that converts the entire store into a Hash. Additionally, it also has a class method called stub, which accepts the number of items that should be stubbed out.

You wanted to convert the items into a Hash of SKUs for the keys, and quantities for the values, so explicitly creating a sku_hash method seems to be more appropriate.

And to use it:

store = Store.stub 15
store_hash = store.to_hash # => [{name: '...', sku: 123, price: 23.99}, ...]
sku_hash = stsore.sku_hash # => { 'sku1' => 2, 'sku2' => 55 }

By separating the Item from the Store and adding class methods to stub items and entire stores, you get two classes that can actually be used in a real context, but also can be used just for playing around.


Triple-type template container I made a triple-type container, that is, a single type that can store a value, under one of the three types used. It's somewhat similar to Boost::Variant.

The header file (multitype.hpp):

#ifndef MULTITYPE_HPP
#define MULTITYPE_HPP

#include <iostream>
#include <cstdlib>
#include <typeinfo>

typedef void* vp_t; // Void pointer (can contain every type)

template <typename _A,typename _B> struct is_same_type  { const static bool value = false; };
template <typename _A> struct is_same_type<_A,_A>       { const static bool value = true;  };

template <class A,class B,class C>
class TripleType
{
    protected:
        enum ct_t { _tA, _tB, _tC, _init_ }; // Type flags
        struct abc_t
        {
            A __a;         // A container
            B __b;         // B container
            C __c;         // C container
            ct_t _e; // Which type is the current one?
        };
    private:
        abc_t val;
    public:
        TripleType()
        {
            (this->val)._e = _init_;
        }
        template <class T> TripleType(T x)
        {
            vp_t yv; yv = &x;
            bool is_A = is_same_type<T,A>::value;
            bool is_B = is_same_type<T,B>::value;
            bool is_C = is_same_type<T,C>::value;
            if      (is_A) { A *t = static_cast<A*>(yv); val.__a = *t; val._e = _tA; }
            else if (is_B) { B *t = static_cast<B*>(yv); val.__b = *t; val._e = _tB; }
            else if (is_C) { C *t = static_cast<C*>(yv); val.__c = *t; val._e = _tC; }
        }
        template <class T> TripleType& operator=(T rhs)
        {
            vp_t yv = &rhs;
            bool is_A = is_same_type<T,A>::value;
            bool is_B = is_same_type<T,B>::value;
            bool is_C = is_same_type<T,C>::value;
            if      (is_A) { A *t = static_cast<A*>(yv); (this->val).__a = *t; (this->val)._e = _tA; }
            else if (is_B) { B *t = static_cast<B*>(yv); (this->val).__b = *t; (this->val)._e = _tB; }
            else if (is_C) { C *t = static_cast<C*>(yv); (this->val).__c = *t; (this->val)._e = _tC; }
            return *this;
        }
        template <class T> T get()
        {
            vp_t yv;
            bool is_A = is_same_type<T,A>::value;
            bool is_B = is_same_type<T,B>::value;
            bool is_C = is_same_type<T,C>::value;
            if      (is_A) yv = &(val.__a);
            else if (is_B) yv = &(val.__b);
            else if (is_C) yv = &(val.__c);
            T *t = static_cast<T*>(yv);
            return *t;
        }
        const std::type_info& current_type()
        {
            if      ((this->val)._e == _tA)
                return typeid(A);
            else if ((this->val)._e == _tB)
                return typeid(B);
            else if ((this->val)._e == _tC)
                return typeid(C);
        }
};

#endif

Here is an usage example:

#include <iostream>
#include <cstdlib>
#include <string>
#include "multitype.hpp" // The header file where I wrote the mentioned container

using namespace std;

int main()
{
    srand(time(NULL));
    TripleType<int,string,float> test;
    test = rand();
    cout << test.get<int>() << endl;
    test = string("TripleType test");
    cout << test.get<string>() << endl;
    test = float(1.6108);
    cout << test.get<float>() << endl;
    test = 2016;
    cout << test.get<int>() << endl;
    test = string("Bye.");
    cout << test.get<string>() << endl;
}

Any improvements, suggestions, etc. are welcome.

Don't make it possible for your container to contain nothing. It can be wrapped in a std::optional for that. Drop the _init_ type and parameterless constructor.
Use val consistently. The parentheses around this->val are unnecessary anyway, but since you're already using val in some places, just use it everywhere.
Don't allow construction or assignment with values of bad types. That fails silently right now, which is not a good way to fail. Luckily, you can do even better and keep the static typing with overloading:

TripleType(A x) { val._e = _tA; val.__a = x; }
TripleType(B x) { val._e = _tB; val.__b = x; }
TripleType(C x) { val._e = _tC; val.__c = x; }

TripleType& operator=(A x) { val._e = _tA; val.__a = x; return *this; }
TripleType& operator=(B x) { val._e = _tB; val.__b = x; return *this; }
TripleType& operator=(C x) { val._e = _tC; val.__c = x; return *this; }

Mark methods that don't modify their object – get() and current_type() – as const.
Don't allow fetching values of the wrong type. I'm not a C++ expert by any means, so there might be a better way of restricting T to A, B, or C while keeping the same .get<T> calling convention (I sure hope so), but:

private:
    A get_(A const*) const {
        if (val._e != _tA) {
            throw bad_multitype_access(typeid(A), current_type());
        }

        return val.__a;
    }

    B get_(B const*) const {
        if (val._e != _tB) {
            throw bad_multitype_access(typeid(B), current_type());
        }

        return val.__b;
    }

    C get_(C const*) const {
        if (val._e != _tC) {
            throw bad_multitype_access(typeid(C), current_type());
        }

        return val.__c;
    }

public:
    template <class T> T get() const {
        return get_(static_cast<T const*>(nullptr));
    }

where bad_multitype_access would be something along the lines of:

class bad_multitype_access : std::logic_error {
public:
    bad_multitype_access(std::type_info const& expected, std::type_info const& actual) :
        std::logic_error(std::string("Attempted to get ") + expected.name() + " from multitype containing " + actual.name()) {}
};

That's all verbose and a bit hacky, but prevents getting types outside of the expected set statically and values of the wrong type dynamically. Again, I would love to hear a better way of accomplishing the same thing from someone who actually knows the language. You can also drop the vp_t typedef at this point, which was never really a good idea, as well as is_same_type.
Use a switch for current_type().

std::type_info const& current_type() const {
    switch (val._e) {
    case _tA: return typeid(A);
    case _tB: return typeid(B);
    case _tC: return typeid(C);
    }
}

Stop it with the underscores already! =)

private:
    enum contained_type {
        tA,
        tB,
        tC,
    };

    struct {
        A a;
        B b;
        C c;
        contained_type type;
    } val;

It feels like creating a TripleType shouldn't create an instance of each of its possible types, and that writing a new value of a different type should destroy a previously existing one. unique_ptrs could work here.

private:
    ⋮
    struct {
        std::unique_ptr<A> a;
        std::unique_ptr<B> b;
        std::unique_ptr<C> c;
        contained_type type;
    } val;
    ⋮
        return *val.a;
    ⋮
        return *val.b;
    ⋮
        return *val.c;

public:
    TripleType(A x) { val.type = tA; val.a = std::make_unique<A>(x); }
    TripleType(B x) { val.type = tB; val.b = std::make_unique<B>(x); }
    TripleType(C x) { val.type = tC; val.c = std::make_unique<C>(x); }

    TripleType& operator=(A x) {
        val.type = tA;
        val.a = std::make_unique<A>(x);
        val.b.reset(nullptr);
        val.c.reset(nullptr);
        return *this;
    }

    TripleType& operator=(B x) {
        val.type = tB;
        val.a.reset(nullptr);
        val.b = std::make_unique<B>(x);
        val.c.reset(nullptr);
        return *this;
    }

    TripleType& operator=(C x) {
        val.type = tC;
        val.a.reset(nullptr);
        val.b.reset(nullptr);
        val.c = std::make_unique<C>(x);
        return *this;
    }

Avoid the double-copy-construct by accepting T const& instead of T in the constructors and operator=s.
Since TripleType is managing everything about val, move val's members into it; it's just doing namespacing right now and not representing an actual object.
Give TripleType some copy and move constructors.

TripleType(TripleType<A, B, C> const& o) {
    type = o.type;

    switch (type) {
    case tA: a = std::make_unique<A>(*o.a); break;
    case tB: b = std::make_unique<B>(*o.b); break;
    case tC: c = std::make_unique<C>(*o.c); break;
    }
}

TripleType(TripleType<A, B, C>&& o) = default;

All told, it looks like this now:

#ifndef MULTITYPE_HPP
#define MULTITYPE_HPP

#include <memory>
#include <stdexcept>

class bad_multitype_access : std::logic_error {
public:
    bad_multitype_access(std::type_info const& expected, std::type_info const& actual) :
        std::logic_error(std::string("Attempted to get ") + expected.name() + " from multitype containing " + actual.name()) {}
};

template <class A, class B, class C>
class TripleType {
private:
    enum contained_type {
        tA,
        tB,
        tC,
    };

    std::unique_ptr<A> a;
    std::unique_ptr<B> b;
    std::unique_ptr<C> c;
    contained_type type;

    A get_(A const*) const {
        if (type != tA) {
            throw bad_multitype_access(typeid(A), current_type());
        }

        return *a;
    }

    B get_(B const*) const {
        if (type != tB) {
            throw bad_multitype_access(typeid(B), current_type());
        }

        return *b;
    }

    C get_(C const*) const {
        if (type != tC) {
            throw bad_multitype_access(typeid(C), current_type());
        }

        return *c;
    }

public:
    TripleType(TripleType<A, B, C> const& o) {
        type = o.type;

        switch (type) {
        case tA: a = std::make_unique<A>(*o.a); break;
        case tB: b = std::make_unique<B>(*o.b); break;
        case tC: c = std::make_unique<C>(*o.c); break;
        }
    }

    TripleType(TripleType<A, B, C>&& o) = default;

    TripleType(A const& x) { type = tA; a = std::make_unique<A>(x); }
    TripleType(B const& x) { type = tB; b = std::make_unique<B>(x); }
    TripleType(C const& x) { type = tC; c = std::make_unique<C>(x); }

    TripleType& operator=(A const& x) {
        type = tA;
        a = std::make_unique<A>(x);
        b.reset(nullptr);
        c.reset(nullptr);
        return *this;
    }

    TripleType& operator=(B const& x) {
        type = tB;
        a.reset(nullptr);
        b = std::make_unique<B>(x);
        c.reset(nullptr);
        return *this;
    }

    TripleType& operator=(C const& x) {
        type = tC;
        a.reset(nullptr);
        b.reset(nullptr);
        c = std::make_unique<C>(x);
        return *this;
    }

    template <class T> T get() const {
        return get_(static_cast<T const*>(nullptr));
    }

    std::type_info const& current_type() const noexcept {
        switch (type) {
        case tA: return typeid(A);
        case tB: return typeid(B);
        case tC: return typeid(C);
        }
    }
};
#endif

And now there's more type safety. (I hope this isn't actually egregiously bad advice!)

Also, here are some moving constructors and operator=s you can add.

TripleType(A&& x) { type = tA; a = std::make_unique<A>(std::move(x)); }
TripleType(B&& x) { type = tB; b = std::make_unique<B>(std::move(x)); }
TripleType(C&& x) { type = tC; c = std::make_unique<C>(std::move(x)); }

TripleType& operator=(A&& x) {
    type = tA;
    a = std::make_unique<A>(std::move(x));
    b.reset(nullptr);
    c.reset(nullptr);
    return *this;
}

TripleType& operator=(B&& x) {
    type = tB;
    a.reset(nullptr);
    b = std::make_unique<B>(std::move(x));
    c.reset(nullptr);
    return *this;
}

TripleType& operator=(C&& x) {
    type = tC;
    a.reset(nullptr);
    b.reset(nullptr);
    c = std::make_unique<C>(std::move(x));
    return *this;
}


Multi-client TCP server with a thread for each client and DB connection pool I'm creating a Qt TCP (with SSL) server to which multiple clients should connect and use the DB, and this is the main task. So, I think I can use this architecture: each client has its own thread, and clients use DB via DB connection pool.

Client connection part

main.cpp:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyServer server;

    server.listen(QHostAddress::Any, 1234);

    return a.exec();
}

myserver.h:

class MyServer : public QTcpServer
{
    Q_OBJECT

    explicit MyServer(QObject *parent = 0);
    ~MyServer();

protected:
    void incomingConnection(qintptr socketDescriptor) Q_DECL_OVERRIDE;

signals:
    void stopAll();
};

myserver.cpp:

MyServer::MyServer(QObject *parent) : QTcpServer(parent)
{
    //...
}

MyServer::~MyServer(){
    emit stopAll();
}

void MyServer::incomingConnection(qintptr socketDescriptor){
    QThread* clientThread = new QThread;
    MyClient *client = new MyClient(socketDescriptor, this);

    client->moveToThread(clientThread);

    connect(clientThread, SIGNAL(started()), client, SLOT(process()));

    connect(client, SIGNAL(finished()), clientThread, SLOT(quit()));
    connect(this, SIGNAL(stopAll()), client, SLOT(stopFromServer()));
    connect(client, SIGNAL(finished()), client, SLOT(deleteLater()));
    connect(clientThread, SIGNAL(finished()), clientThread, SLOT(deleteLater()));

    clientThread->start();
}

myclient.h:

class MyClient : public QObject
{
    Q_OBJECT
public:
    explicit MyClient(int socketDescriptor, MyServer *server);
    ~MyClient();

private:
    QSslSocket* socket = NULL;

public slots:
    void process();
}

myclient.cpp:

void MyClient::process(){
    //typical connection things
    connect(this->socket, SIGNAL(encrypted()), this, SLOT(ready()));
}

void MyClient::ready(){
    connect(socket,SIGNAL(readyRead()),this, SLOT(newData()));
}

DB connection pool part

DAO which will be executed in the client threads:

.cpp:

//DAO method

QList<QMap<QString, QString>> sqlResult = DatabaseService::executeQuery(sqlCommand);

//sqlResult processing

DatabaseService:

.h:

class DatabaseService
{
public:
    //...
    static QMap<QString, QString> executeQuery(QString command);

private:
    static QThreadStorage<QSqlDatabase> mDatabasePool;
    static QSqlDatabase getDatabase();

};

.cpp:

//...
QThreadStorage<QSqlDatabase> DatabaseService::mDatabasePool;

QSqlDatabase DatabaseService::getDatabase()
{
    if(DatabaseService::mDatabasePool.hasLocalData()) {
        return DatabaseService::mDatabasePool.localData();
    } else {
        auto database = QSqlDatabase::addDatabase("QPSQL", QUuid::createUuid().toString());
        database.setHostName("hostName");
        database.setDatabaseName("databaseName");
        database.setUserName("user");
        database.setPassword("password");
        database.open();
        DatabaseService::mDatabasePool.setLocalData(database);
        return database;
    }
}

QMap<QString,QString> DatabaseService::executeQuery(QString command){

    QSqlQuery query (DatabaseService::getDatabase());
    query.exec(command);

    //...

    return result;
}

//...

This is all the code related to the subject.

You also can check my SO question about DB connection pool (please note that the code is not exactly the same).

So, how good is this architecture? What could be fixed and improved and how?

I am not sure how QThreads work:

Is it a wrapper around an OS thread?
Are QThreads pooled?

Assuming a QThread is a wrapper and not pooled.

Then this technique is actually very limiting. The trouble is that threads are relatively expensive to create, in reality you can only run a handful of them simultaneously without cost (creating more than 2x the processors is probably a bad idea), In socket programming most of the threads are idle (network is very slow compared to the speed of the processor).

There is a famous paper on the top c10k. Basically given current network speeds and processor speeds you should easily be able to support 10 thousand simultaneous connections. But using this model you will top out supporting a couple of hundred simultaneous connections.

Basically you want to design your server around a single thread model and use pselect() (though this is now outdated by better options poll(), epoll() and finally LibEvent). Don't bother experimenting with the older versions just jump to LibEvent.


How to increase efficiency of recursion algorithm? The question is:

Given a non-negative int n, compute recursively (no loops) the count
of the occurrences of 8 as a digit, except that an 8 with another 8
immediately to its left counts double, so 8818 yields 4. Note that mod
(%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/)
by 10 removes the rightmost digit (126 / 10 is 12).
count8(8) → 1 count8(818) → 2 count8(8818) → 4

My solution looked something like this:
public int count8(int n) {
  if(n == 0)  return 0;

  int faith = count8(n/10);
  int c = 0;
  if(n%10 == 8){
    n /= 10;
    if(n%10 == 8){
      c++;
    }
    c++;
  }
  return c + faith;
}

Is there any way I can remove the multiple if conditions and make this cleaner and more efficient?

Variable names. Name your variables after what they do, no exceptions.

As a sidenote, note that that you're relying on how integer division works in Java.

Having said that, you can improve the code by being explicit.
// As I've said, always name your variables and functions after
// what they are doing. Don't be afraid to use longer names,
// longer names which tell you what the class does are a good
// thing, even if they sound "funny".
public int countEights(int value) {
    // Early exit conditions are a good thing.
    if(value == 0) {
        return 0;
    }

    // We could also skip the declaration and instead return
    // the right count together with the function call. From
    // the viewpoint of the JVM it doesn't make a difference,
    // but here in the code it means that we have the logic
    // for stripping the last digit only once.
    int countedEights = 0;

    // We are testing explicitly for the mentioned "double eights",
    // this has the upside that the intent is clearly visible
    // when reading the code.
    if ((value % 100) == 88) {
        countedEights = 2;
    } else if ((value % 10) == 8) {
        countedEights = 1;
    }

    // And finally we call the function again in the return
    // statement, as it is easier to follow the recursion when
    // it is being called at the end of the function.
    return countedEights + countEights(value / 10);
}

As you can see, we can completely get rid of the nested if by being explicit about our intent.


Returning latest database ID I want my method to use a finally block so I can be ure that my EF entity is disposed after usage, even if an exception is thrown, but I would also like to not handle exceptions in that method.

The current code works but is it possible to omit the catch{} block? Would an exception from the try{} block be re-thrown or would it be forgotten?
Is it necessary to set tm_entity to null in the finally block, or will Dispose take care of everything?

Any other suggestions are welcome!

/// <summary>
/// Returns ID of the latest result database.
/// </summary>
/// <param name="managementEntity">EF Test Management entity.</param>
/// <returns>Latest result database ID.</returns>
public static int GetLatestDatabaseIteration(TEST_MANAGEMENTEntities managementEntity)
    {
        if (managementEntity == null)
        {
            throw new ArgumentNullException("Passed entity can not be null!.");
        }

        TEST_MANAGEMENTEntities tm_entity = managementEntity;
        int? latestDatabaseID = null;
        try
        {
            latestDatabaseID = (from trb in tm_entity.TestRunsDatabases
                                select trb.DatabaseID).Max();

            if (latestDatabaseID == null)
            {
                throw new Exception("Cannot evaluate latest Test Result Database ID.");
            }
        }
        catch (Exception ex) //Could I just omit this block?
        {
            throw ex;
        }
        finally
        {
            tm_entity.Dispose();
            tm_entity = null; //is it necessary?
        }
        return (int)latestDatabaseID;
    }

EDIT:

After making suggested changes my method looks like this.

public static int GetLatestDatabaseIteration(TEST_MANAGEMENTEntities managementEntity)
    {
        if (managementEntity == null)
        {
            throw new ArgumentNullException("Passed entity can not be null!.");
        }

        TEST_MANAGEMENTEntities tmEntity = managementEntity;

        int? latestDatabaseID = (from trb in tmEntity.TestRunsDatabases
                                 select (int?)trb.DatabaseID).Max();

        if (latestDatabaseID == null)
        {
            throw new NoRecordsFoundException("Cannot evaluate latest Test Result Database ID.");
        }

        return (int)latestDatabaseID;
    }

Changes I made:

I have renamed variables to match CamelCase.
I have removed .Dispose on a passed reference as it would also Dispose object in the Caller method.
I have abandoned calling generic exception and replaced it with custom one that more accurately describes this exception.

Calling .Max() if query return null may cause problems, but I will check it with UnitTests soon.

You really shouldn't rethrow caught exceptions like that.

catch (Exception ex) //Could I just omit this block?
    {
        throw ex;
    }

Erases the call stack of the exception, instead use

catch (Exception) //Could I just omit this block?
    {
        throw;
    }

However the point is moot, because the try-finally block is syntactically legal, but you should bear in mind a very major caveat (emphasis my own):

  Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up.

As such, it would be a good idea to make sure you catch any exceptions you can reasonably expect, but then that's just standard good practice.

As an aside, I really don't like your use of caps. Type names should be PascalCase, and you should avoid underscores in type names or variable names.

Lastly, you really should throw a subclass of Exception, and never the parent class.


C++ class for aligning objects on the stack I wrote a short class which allocates objects on the stack and aligns them to a specific memory address. Alignment makes sense for some objects (i.e. some SIMD intrinsics require aligned data). I wrote this mostly as an exercise. Tests are included. If someone has time to skim over this: thanks in advance, I'm looking forward to learn from your comments!

Also I'd be curious if you would add more functionality, i.e. operator== etc.

Usage

  // Allocates an int object aligned to 8 bytes, initializes it with 4
  aligned<8, int> i8(4);
  // Get a pointer to the actual value with operator&
  int *pi8 = &i8;
  // Get the actual value with operator*
  assert(*i8 == 4);

Header file

#include <cstdint>

template<size_t Align, typename T>
class aligned
{
  public:
    using value_type = T;
    using aligned_type = aligned<Align, T>;

    constexpr aligned() : ptr_(nullptr) {
    }

    aligned(const aligned_type &other) {
      *ptr_ = *other.ptr_;
    }

    aligned(const aligned_type &&other) {
      *ptr_ = std::move(*other.ptr_);
    }

    aligned_type &operator=(const aligned_type &other) {
      *ptr_ = *other.ptr_;
      return *this;
    }

    template<typename... Args>
    aligned(Args&&... args) {
      ptr_ = aligned_position();
      new (ptr_) T(std::forward<Args>(args)...);
    }

    ~aligned() {
      ptr_->~T();
    }

    T *get() const {
      return ptr_;
    }

    T *operator&() const {
      return get();
    }

    T operator*() const {
      return *ptr_;
    }

  private:
    T *aligned_position() {
      uint8_t *p = &storage_[0];
      while (reinterpret_cast<unsigned long>(p) % Align != 0)
        p++;
      return reinterpret_cast<T *>(p);
    }

    uint8_t storage_[Align - 1 + sizeof(T)];
    T *ptr_;
};

Tests

The main function has a few the tests. You can use operator& to get a pointer to the (aligned) object, or operator* to get a reference.

#include <cassert>
#include <utility>

int
main(int argc, const char *argv[])
{
  aligned<16, char> a;
  assert(&a == nullptr);

  aligned<8, int> i8(4);
  int *pi8 = &i8;
  assert(reinterpret_cast<unsigned long>(pi8) % 8 == 0);
  assert(*i8 == 4);

  aligned<7, double> d7(12.123);
  double *pd7 = &d7;
  assert(reinterpret_cast<unsigned long>(pd7) % 7 == 0);
  assert(*d7 == 12.123);

  using P = std::pair<int, int>;
  aligned<13, P> p13({1, 2}); // testing a more complex object
  P *pp13 = &p13;
  assert(reinterpret_cast<unsigned long>(pp13) % 13 == 0);
  assert(*p13 == std::make_pair(1, 2));
  return 0;
}

I use the GNU g++ compiler, version 5.4.0.

Silent bug: Bad move constructor

Your move constructor will perform a copy because your parameter is aligned_type const&&; you cannot move from a const value because moving implies modifying what you're moving from. Simply change the signature to:

aligned(aligned_type &&other);
//      ^^^^^^^^^^^^^^^ no more const

Bug: Bad dereference operator

Your dereference operator is defined like so:

T operator*() const {
// we don't really want to copy the value out every single time we deref, do we?
  return *ptr_;
}

It simply returns T, it should return T&. Note that this is a source of a bug in your code. You end up creating a temporary when you assign by using the dereference operator. This can (and did on my system) result on a crash due to the memory access violation.

Only align to alignments that are powers of 2.

Your test code aligns to 7 and 13.

From [basic.align] in the C++ Standard (emphasis mine):

  Alignments are represented as values of the type std::size_t. Valid
  alignments include only those values returned by an alignof expression
  for the fundamental types plus an additional implementation-defined
  set of values, which may be empty. Every alignment value shall be a
  non-negative integral power of two.

T* aligned_position();

This function is used in only one place. Unless you've got plans of using it elsewhere, I recommend erasing it and simply putting the code at the relevant location.

You don't have to index into the first element to get the address. You can use the fact that arrays decay to pointers.

uint8_t *p = storage_; // equivalent to uint8_t *p = &storage_[0];

However, there is a faster way than looping in order to align an address to some boundary:

auto aligned_position() const noexcept
{
    return reinterpret_cast<T*>(
        (reinterpret_cast<std::uintptr_t>(&storage_) + Align - 1) & ~(Align - 1));
}

Do we really need aligned_position(); and ptr_?

No. Here is an alternative solution:

You currently allocate Align - 1 + sizeof(T) bytes. This is wasteful. You can use exactly as much space as you need by declaring your storage any of these two ways:

alignas(Align) std::uint8_t storage_[sizeof(T)];
std::aligned_storage_t<sizeof(T), Align> storage_; // from the <type_traits> header

Option 1 might be preferable because option 2 is not guaranteed to align to your requested boundary if Align > alignof(std::max_align_t). In such a case, it will depend on the implementation of the standard library you're using; the Microsoft implementation does this.

Before: sizeof(aligned<8, double>) == 20

After: sizeof(aligned<8, double>) == 16

Wait, we're not done yet. We shouldn't align to the specified alignment blindly either because we can then specify an alignment of 4 for a double, which requires 8. Unaligned data like that becomes very slow to access (two reads instead of one) or can simply not work (crash) in certain systems.

The fix:

alignas(Align < alignof(T) ? alignof(T) : Align) std::uint8_t storage_[sizeof(T)];

Note that we no longer need ptr_ because the first byte of storage_ now corresponds to a properly aligned byte for our type.

Before: sizeof(aligned<8, double>) == 20

After: sizeof(aligned<8, double>) == 8

We save quite a bit of space. In fact, with this solution, your class takes no more space than a T when aligned to alignof(T). You have to replace all uses of ptr_ with an appropriate statement; I recommend replacing all instances of ptr_ with a call to get(). This call will almost surely be optimized away.

Provide non-const versions of your accessor/modifier functions.

You want your type to be usable in non-const contexts, so provide non-const overloads for your operations. For example, define get() like so:

T* get() noexcept {
    return reinterpret_cast<T*>(&storage_);
}

T const* get() const noexcept {
    return reinterpret_cast<T const*>(&storage_);
}

You can provide this functionality wherever needed.

Final thoughts:

The class is basically a wrapper around a aligned_storage<> like storage. However, it is a good learning experience I suppose.
I've left out basic language features advice such as declaring functions constexpr or giving them exceptions specifications through type traits. Please look into that yourself.


Improving LINQ expression with inner method call and switch statement I have the following class which returns an expression that then returns data. It seems a tad over complicated and I'm pretty sure LINQ has something to offer that makes my life much easier. But I simply cannot get it.

/// <summary>Provides methods and properties to query location details from a database.</summary>
internal sealed class LocationDatabaseDetailsRequest : DatabaseDetailsRequest<LocationContext, LocationDataContract, Guid>
{
    /// <inheritdoc />
    public override Func<LocationContext, LocationDataContract> Resource
    {
        get
        {
            return
                c =>
                c.Locations.Select(
                    l =>
                    new LocationDataContract
                    {
                        Id = l.Id,
                        Coordinates = l.Coordinates,
                        Description = l.Description,
                        Name = l.Name,
                        Type = l.Type,
                        Details = this.GetDetails(l.Type, c)
                    }).SingleOrDefault(i => i.Id == this.Identifier);
        }
    }

    private LocationDetailsDataContract GetDetails(string detailsType, LocationContext locationContext)
    {
        switch (detailsType)
        {
            case "City":
                return locationContext.Set<CityDetailsDataContract>().SingleOrDefault(i => i.Id == this.Identifier);
            case "Planet":
                return locationContext.Set<PlanetDetailsDataContract>().SingleOrDefault(i => i.Id == this.Identifier);
            case "StarSystem":
                return locationContext.Set<StarSystemDetailsDataContract>().SingleOrDefault(i => i.Id == this.Identifier);
            case "Sector":
                return locationContext.Set<SectorDetailsDataContract>().SingleOrDefault(i => i.Id == this.Identifier);
            default:
                return null;
        }
    }
}

My problem is the method call. I know which sets the data context has, but they are fluid, meaning it is certain that new sets will get added.

Can I write this query shorter and well... better?

public override Func<LocationContext, LocationDataContract> Resource
{
    get
    {
        return
            c =>
            c.Locations.Select(
                l =>
                new LocationDataContract
                {
                    Id = l.Id,
                    Coordinates = l.Coordinates,
                    Description = l.Description,
                    Name = l.Name,
                    Type = l.Type,
                    Details = this.GetDetails(l.Type, c)
                }).SingleOrDefault(i => i.Id == this.Identifier);
    }
}

This code is inefficient, because the body of your Select is being executed for every value in Locations. This is because SingleOrDefault checks every item in an enumerable for duplicates. Since you're only checking an id and the id is not changed in your Select perform your SingleOrDefault call first.

public override Func<LocationContext, LocationDataContract> Resource
{
    get
    {
        return c =>
        {
            var location = c.Locations.SingleOrDefault(i => i.Id == this.Identifier);
            return location == null ?
                null :
                new LocationDataContract
                {
                    Id = location.Id,
                    Coordinates = location.Coordinates,
                    Description = location.Description,
                    Name = location.Name,
                    Type = location.Type,
                    Details = this.GetDetails(location.Type, c)
                });
        }
    }
}

This way, the LocationDataContract is only created if there is a single location in c that matches the identifier.

Structurally, I'm wondering why you have a public read-only property returning a Func. I can see no good reason why this shouldn't be a method, although obviously the motivation for this depends on the implementation in the base class, which we cannot see in your question.

If you can modify the base class, I would recommend replacing this property with a virtual or abstract method. This property syntax instead is more obtuse for a maintenance programmer to read and is over-complex. Consider this instead:

public override LocationDataContract Resource(LocationContext context)
{
    var location = context.Locations.SingleOrDefault(l => l.Id == this.Identifier);
    return location == null ?
        null :
        new LocationDataContract
        {
            Id = location.Id,
            Coordinates = location.Coordinates,
            Description = location.Description,
            Name = location.Name,
            Type = location.Type,
            Details = this.GetDetails(location.Type, context)
        });
}

Additionally, the name Resource gives me no information. It might as well be called Foo. It looks like a function that grabs a location data contract from a location context based on the currently stored Id, so a name like "LocationContractForCurrentId" would make more sense.

Lastly, your usage of SingleOrDefault everywhere concerns me. If it's truly acceptable that nothing happens when no identifiers can be found, including in your context set methods, then fine, keep it that way, but if this is a way to hide from exceptions caused by invalid data or incorrect programming and to avoid Failing Fast, then that is a serious issue that would be better dealt with than hidden from.


Json Web Token-like implementation in Rust I am new to Rust. I am making this to help me learn better. This code has two functions: ::make() and ::get_payload(). ::make() creates a signed web token to be stored on the client. The client sends that token on every request that requires authentication, and the clients information or 'claims' are verified by the signature with ::get_payload(). If ::get_payload() returns Value::Null the token is not valid (or expired).

I need 3 types of feedback.

Are there any security holes or issues with what you can see here?
Is this Rust written well, and how can I improve it?
Am I missing some important error handling?

extern crate base64;
extern crate ring;
extern crate chrono;
extern crate serde_json;

use base64::{encode, decode};
use ring::{digest, hmac};
use chrono::prelude::Utc;
use std::str;
use serde_json::Value;

static RWT_SECRET: &str = "some secret"; // this should be from an environment variable

pub fn make(payload: &str) -> String {
    let mut token = encode(&Utc::now().to_string());
    token.push_str(".");

    let payload_base64 = &encode(payload);
    token.push_str(payload_base64);

    let key = hmac::SigningKey::new(&digest::SHA256, RWT_SECRET.as_bytes());
    let signature = &encode(&hmac::sign(&key, token.as_bytes()));
    token.push_str(".");
    token.push_str(signature);

    token
}

pub fn get_payload(token: &str) -> Value {
    let parts: Vec<&str> = token.split(".").collect();
    if parts.len() != 3 {
        return Value::Null;
    }

    // todo: check timestamp for expiration

    let signed = parts[..2].join(".").to_string();
    let key = hmac::SigningKey::new(&digest::SHA256, RWT_SECRET.as_bytes());
    let signature = &encode(&hmac::sign(&key, signed.as_bytes()));

    if signature.to_string() == parts[2] {
        let utf8 = &decode(parts[1]).unwrap();

        let json = str::from_utf8(utf8).unwrap();
        let payload: Value = serde_json::from_str(json).unwrap();

        return payload;
    }

    Value::Null
}

Run clippy to be automatically told about things like:

warning: single-character string constant used as pattern
  --> src/main.rs:30:40
   |
30 |     let parts: Vec<&str> = token.split(".").collect();
   |                            ------------^^^- help: try using a char instead: `token.split('.')`
   |
   = note: #[warn(single_char_pattern)] on by default
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#single_char_pattern

warning: this creates an owned instance just for comparison
  --> src/main.rs:41:8
   |
41 |     if signature.to_string() == parts[2] {
   |        ^^^^^^^^^^^^^^^^^^^^^ help: try `signature`
   |
   = note: #[warn(cmp_owned)] on by default
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#cmp_owned

Tests, tests, tests, TESTS! Who even knows if this code works? Who knows if the changes I made broken anything? I sure don't know, but all the provided tests passed!
Encoding and decoding have highly related parts, so I'd introduce a struct to bundle them together; this allows extracting the key and signing bits which are reused across both. It also makes it easier to start to use an environment variable.
There's a lot of allocation that doesn't seem needed. For example, you can Base-64 encode into an existing String. Splitting the string on . and then joining it back together when verifying the token also seems inefficient.
Encoding into a string introduces some duplication with the details around the encoding, so I extracted that to a new type as well.
I chose to take some generics to avoid having to call as_bytes and friends everywhere.
Construct the key once when the object is created, then you can reuse it. This also makes it easier to change how the key is constructed.
When collecting, you usually don't need to specify the type inside the collection. Instead, do Vec<_>.
Returning Value::Null conflates an error case with a valid value. Use Result instead.
The API is unbalanced; encoding takes a string, but decoding returns a JSON Value. These should be symmetrical.
The practice of putting & before a result value (let foo = &some_function();)  is not usual and it's very distracting. Usually, you'd just take the reference when you need it.
Libraries should not unwrap things unless it's the author of the libraries mistake. Panicking in a library should be very rare and highly documented. Usually, you should return an error. If you do panic, use expect to give yourself a hint what went wrong.
Since you have a Vec<u8>, you can convert it to a String, no need to make a &str. Even better though, you can parse JSON from a slice, no need to explicitly check for UTF-8.
There's no need to introduce a temporary variable for the result of serde_json::from_str, just return it directly.

extern crate base64;
extern crate ring;
extern crate chrono;
extern crate serde_json;

use base64::{encode, decode};
use ring::{digest, hmac};
use chrono::prelude::Utc;
use std::str;
use serde_json::Value;

static RWT_SECRET: &str = "some secret"; // this should be from an environment variable

#[derive(Debug, Default)]
struct Encoder {
    buffer: String,
}

impl Encoder {
    fn new() -> Self {
        Self::default()
    }

    fn encode<D>(&mut self, data: D)
    where
        D: AsRef<[u8]>,
    {
        base64::encode_config_buf(data.as_ref(), base64::STANDARD, &mut self.buffer);
    }

    fn finish_part(&mut self) {
        self.buffer.push_str(".");
    }
}

impl AsRef<[u8]> for Encoder {
    fn as_ref(&self) -> &[u8] {
        self.buffer.as_bytes()
    }
}

impl From<Encoder> for String {
    fn from(me: Encoder) -> String {
        me.buffer
    }
}

pub struct Thang {
    key: hmac::SigningKey,
}

impl Thang {
    fn new() -> Self {
        Thang { key: hmac::SigningKey::new(&digest::SHA256, RWT_SECRET.as_bytes()) }
    }

    fn sign<D>(&self, data: D) -> hmac::Signature
    where
        D: AsRef<[u8]>,
    {
        hmac::sign(&self.key, data.as_ref())
    }

    fn encoded_signature<D>(&self, data: D) -> String
    where
        D: AsRef<[u8]>,
    {
        encode(&hmac::sign(&self.key, data.as_ref()))
    }

    pub fn make(&self, payload: &str) -> String {
        let mut token = Encoder::new();

        let time = Utc::now().to_string();
        token.encode(time);
        token.finish_part();
        token.encode(payload);

        let signature = self.sign(&token);

        token.finish_part();
        token.encode(signature);

        token.into()
    }

    pub fn get_payload(&self, token: &str) -> Result<Value, Error> {
        let first_dot = token.find('.').ok_or(Error)?;
        let second_dot = first_dot + 1 + token[(first_dot + 1)..].find('.').ok_or(Error)?;

        // let header = &token[..first_dot]; // TODO: check header
        let payload = &token[(first_dot + 1)..second_dot];
        let header_and_payload = &token[..second_dot];
        let actual_signature = &token[(second_dot + 1)..];

        let expected_signature = self.encoded_signature(header_and_payload);

        if expected_signature == actual_signature {
            let payload = decode(payload).map_err(|_| Error)?;
            return serde_json::from_slice(&payload).map_err(|_| Error);
        }

        Err(Error)
    }
}

#[derive(Debug)]
pub struct Error; // TODO: implement std::error::Error, maybe promote to an enum

fn main() {
    let x = Thang::new().make(r#"{"hello": true}"#);
    println!("{}", x);
    let x = Thang::new().get_payload(&x);
    println!("{:?}", x);
}

  Are there any security holes or issues with what you can see here?

I'm not qualified to make any such judgements. I will note that you've hardcoded the signature type, which doesn't mesh with real JWT.


Do my Image Widths Exceed Limit? I needed to find whether any image's width at or higher than a certain directory folder exceeds a limit.  Is this code a good way of doing this, or is there a way in which it can be improved?  I ran it over at least a couple hundred images and several hundred other files contained in the main directory (not C:\Users, but I don't want to show my user name), and it completed so fast the time is irrelevant.

public static void Main()
{
    string[] files = Directory.GetFiles("C:\\Users", "*.png", SearchOption.AllDirectories);

    foreach (string file in files)
    {
        Image img = Image.FromFile(file);

        if (img.Width > 1100)
        {
            Console.WriteLine(file);
            Console.WriteLine(img.Width);
        }

        img.Dispose();
    }
}

Rather than opening a resource and then remembering to close it with a .Dispose() call,
I think it's good to use the using (...) { ... } idiom as much as possible.
Some questions (and again) on Stack Overflow suggest some issues with releasing image resources when opened with Image.FromFile.

I propose this alternative:

public static void Main()
{
    string[] files = Directory.GetFiles("C:\\Users", "*.png", SearchOption.AllDirectories);

    foreach (string file in files)
    {
        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
        using (Image img = Image.FromStream(fs))
        {
            if (img.Width > 1100)
            {
                Console.WriteLine(file);
                Console.WriteLine(img.Width);
            }
        }
    }
}


How to avoid echoing JavaScript from PHP? I want to use some constant in both server side and client side.

Currently, I use PHP reflection in order to synchronize PHP constants and Javascript constants. But for the maintainable reason, it's not a best practise.

For example:

interface IType{
//...
const ID_TYPE_TEXT      = 1000;
const ID_TYPE_NUMBER    = 2000;
const ID_TYPE_IMAGE     = 3000;
const ID_TYPE_VIDEO     = 4000;
//...
}

In view

$r   = new ReflectionClass('IType');
foreach( $r->getConstants() as $const => $value)
{
     echo "var $const = $value;"
}

How can I avoid doing that?

One way is to keep the constants in a database table and have a script that automatically generates both JS and PHP code by looking through it.  The advantages of this are that you can store other bits of information if you want, and the code is all generated beforehand so there is no extra overhead with each page load.  The only disadvantage is that you have to run the script every time you change the constants.  The simplest table structure you could use would store just the name and the value, but as an example mine looks like this:

mysql> explain codes;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| type        | char(3)          | YES  |     | NULL    |                |
| code        | char(3)          | YES  |     | NULL    |                |
| parent      | char(3)          | YES  |     | NULL    |                |
| long_code   | char(64)         | YES  |     | NULL    |                |
| description | char(64)         | YES  |     | NULL    |                |
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
+-------------+------------------+------+-----+---------+----------------+

The "type" field is a reference to another table, which organises the constants according to which part of the program they're relevant to.

mysql> explain codetypes;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| code        | char(3)          | YES  | UNI | NULL    |                |
| long_code   | char(64)         | YES  | UNI | NULL    |                |
| description | char(64)         | YES  |     | NULL    |                |
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
+-------------+------------------+------+-----+---------+----------------+

Here is a sample from the database behind a chess server:

mysql> select * from codetypes where code='GST';
+------+------------+-------------+----+
| code | long_code  | description | id |
+------+------------+-------------+----+
| GST  | GAME_STATE | Game state  |  1 |
+------+------------+-------------+----+
1 row in set (0.00 sec)

mysql> select * from codes where type='GST';
+------+------+--------+-------------+-------------+----+
| type | code | parent | long_code   | description | id |
+------+------+--------+-------------+-------------+----+
| GST  | PRE  | NULL   | PREGAME     | Pregame     |  1 |
| GST  | IPR  | NULL   | IN_PROGRESS | In progress |  2 |
| GST  | FIN  | NULL   | FINISHED    | Finished    |  3 |
| GST  | CAN  | NULL   | CANCELED    | Cancelled   |  4 |
+------+------+--------+-------------+-------------+----+
4 rows in set (0.00 sec)

Which generates the following PHP code:

define("GAME_STATE", "GST");

define("GAME_STATE_IN_PROGRESS", "IPR");
define("GAME_STATE_FINISHED", "FIN");
define("GAME_STATE_CANCELED", "CAN");
define("GAME_STATE_PREGAME", "PRE");

Using the extra information you can generate other useful bits of code, for example Javascript objects for looping through the constants of each type and accessing the descriptions as well as the values:

var DbEnums={};

DbEnums["GST"]={};

DbEnums["GST"]["IPR"]={Type: "GST", Code: "IPR", Parent: null, Description: "In progress"};
DbEnums["GST"]["FIN"]={Type: "GST", Code: "FIN", Parent: null, Description: "Finished"};
DbEnums["GST"]["CAN"]={Type: "GST", Code: "CAN", Parent: null, Description: "Cancelled"};
DbEnums["GST"]["PRE"]={Type: "GST", Code: "PRE", Parent: null, Description: "Pregame"};


Did you like my product? I have the following MySQL query which selects product details and whether the viewing user likes them. I feel like it could be more efficient and that there is a more practical approach than using a sub-query here.

Any suggestions?

SELECT p.*,
         pm.filename AS thumbnail,
         (SELECT COUNT(id) FROM likes WHERE productId = p.id AND
                userId = '$viewingUserId' AND isActive = '1' LIMIT 1)
            as liked
            FROM products p, productmedia pm
        WHERE p.userId = '$userId'
        AND p.id = pm.productId
        AND pm.sortOrder = '0'
        ORDER BY p.timestamp DESC

More important than the performance, your code is very likely vulnerable to SQL Injection. (I can't say for sure without looking at your PHP code)

If $viewingUserId or $userId is chosen by the user in any way, then you have a problem. And even if it is not, I would highly recommend using prepared queries.

I don't know if you're using the mysql_* methods or mysqli_* methods or the PDO extention, but you should be aware that the mysql_* methods are deprecated (That means: Don't use them) and that you should either use mysqli (note the i) or PDO.


SQL query on percentage share of different groups in total I could barely get this to work... It seems there is redundancy as the dates are repeated twice, for example. Is there a way to simplify it?

WITH total AS
  (
    SELECT COUNT(type) AS total FROM loan_loan
    WHERE
      loan_loan.created_at > '2019-08-15' and
      loan_loan.created_at < '2019-09-05'
  )
SELECT
  type,
  COUNT(*),
  (0.00 + COUNT(*)) / total.total as share
FROM loan_loan, total
WHERE
  loan_loan.created_at > '2019-08-15' and
  loan_loan.created_at < '2019-09-05'
GROUP BY
  type,
  total.total

It (correctly) returns a table like this:

|---------------------|------------------|------------------|
|         type        |       count      |       share      |
|---------------------|------------------|------------------|
|         type1       |        26        |       0.52       |
|---------------------|------------------|------------------|
|         type2       |        24        |       0.48       |
|---------------------|------------------|------------------|

CTEs

A CTE is an optimization fence. You'll want to try to avoid it and at the least convert it into a subquery.

Casting

Do an explicit cast instead of an implicit cast:

0.00 + COUNT(*)

becomes

count(*)::real

Between

Rather than writing

  loan_loan.created_at > '2019-08-15' and
  loan_loan.created_at < '2019-09-05'

write

  loan_loan.created_at between '2019-08-15' and '2019-09-05'

Joining

More broadly: are you sure this is doing the right thing? You aren't selecting type from your CTE to join to your upper query's loan_loan.type. Given the lack of this join, I fail to see how your total column will be reliably matched to your upper rows.


Project Euler #2 (Even Fibonacci numbers) in Swift I figured working through Project Euler problems in Swift would be a good way to learn any tips or tricks.  For example, tuples are something I'm not used to using, but they proved useful here.  Using things makes me more confident with them, so perhaps this will help me find other uses for them in the future.

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

Here is my solution:

func swap(inout left: Any, inout right: Any) {
    let swap = left
    right = left
    left = swap
}

func findNextEvenFibonacci(var firstFibonacci: Int = 0, var secondFibonacci: Int = 1) -> (Int, Int) {
    do {
        firstFibonacci += secondFibonacci
        swap(&firstFibonacci, &secondFibonacci)
    } while firstFibonacci % 2 != 0

    return (firstFibonacci, secondFibonacci)
}

let maxFibonacci: Int = 4_000_000
var fibonacci: (first: Int, next: Int) = (0,1)
var sumOfEvenFibonnaccis: Int = 0

while fibonacci.next < maxFibonacci {
    fibonacci = findNextEvenFibonacci(firstFibonacci: fibonacci.first, secondFibonacci: fibonacci.next)
    sumOfEvenFibonnaccis += fibonacci.first
}

let answer = sumOfEvenFibonnaccis

The following is similar to Flambino's approach, but creates a Swift
SequenceType so that you can use the Swift library functions
filter() and reduce() to iterate over
the elements:

struct FibonacciSequence : SequenceType {
    let upperBound : Int

    func generate() -> GeneratorOf<Int> {
        var current = 1
        var next = 1
        return GeneratorOf<Int>() {
            if current > self.upperBound {
                return nil
            }
            let result = current
            current = next
            next += result
            return result
        };
    }
}

let fibseq = lazy(FibonacciSequence(upperBound: 4_000_000))
let sum = reduce(fibseq.filter { $0 % 2 == 0 }, 0) { $0 + $1 }

See here for more information about sequences and generators.
This nice application made me actually understand how you can create your own sequences.

lazy() creates a LazySequence, whose filter() method returns the elements "on demand", e.g. as needed in the summation. The
filter() function would return an array of all even Fibonacci numbers
before starting the summation. (Kudos to @jtbandes for his suggestion).

Update: Due to major changes in the Swift programming language,
the above code does not compile anymore with the current Swift 2.1/Xcode 7. Here is an updated version fore anybody's convenience:

struct FibonacciSequence : SequenceType {
    let upperBound : Int

    func generate() -> AnyGenerator<Int> {
        var current = 1
        var next = 1
        return anyGenerator {
            if current > self.upperBound {
                return nil
            }
            let result = current
            current = next
            next += result
            return result
        };
    }
}

let fibseq = FibonacciSequence(upperBound: 4_000_000).lazy
let sum = fibseq.filter { $0 % 2 == 0 }.reduce(0) { $0 + $1 }


Empty Line delimiter, single line output I'm used to only processing, at most, one line of a file at a time. This is my first time changing the delimiter, and the objective here is to take a file containing lines such as:

Bubbles,
Blossom and
Buttercup

Nostalgic
Examples for the
Win.

Quick Brown Fox
Jumping Over Lazy
Dog.

and produce single line output:

Bubbles, Blossom and Buttercup.
Nostalgic Examples for the Win.
Quick Brown Fox Jumping Over Lazy Dog.

What I've done works, but it feels like a work-around to some superior alternative I'm sure exists. What do you think?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.regex.Pattern;
import java.util.Scanner;

public class TestDelim {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]))
            .useDelimiter(Pattern.compile("^\\s*$", Pattern.MULTILINE));
        Scanner output;
        StringBuilder sb = new StringBuilder();

        while (input.hasNext()) {
            output = new Scanner(input.next());

            while (output.hasNextLine()) {
                sb.append(' ').append(output.nextLine());
            }

            System.out.println(sb.toString().trim());
            sb.setLength(0);
        }
    }
}

I don't really see why you used two scanners instead of just one.
And I also don't see the need for a custom delimiter.

You can use a simpler alternative logic:

Process line by line
If the line is not empty, append it + a space
If the line is empty

Print the content buffer, except the last charater (the extra space)
Reset the buffer

At the end, if the buffer is not empty, print its content, except the last character

That is:

StringBuilder sb = new StringBuilder();

while (input.hasNextLine()) {
    String line = input.nextLine();
    if (!line.isEmpty()) {
        sb.append(line).append(' ');
    } else {
        System.out.println(sb.substring(0, sb.length() - 1));
        sb.setLength(0);
    }
}
if (sb.length() > 0) {
    System.out.println(sb.substring(0, sb.length() - 1));
}

An easy way to "test" this is by instantiating a Scanner with a string containing newlines:

Scanner input = new Scanner("Bubbles,\n" +
        "Blossom and\n" +
        "Buttercup\n" +
        "\n" +
        "Nostalgic\n" +
        "Examples for the\n" +
        "Win.\n" +
        "\n" +
        "Quick Brown Fox\n" +
        "Jumping Over Lazy\n" +
        "Dog.");

I don't know a simpler way to do this.
But I have some ideas for possibly interesting variations you could try, for example:

Instead of collecting lines in a buffer, print as you go. That will save you memory usage. To track whether to put a space or not, you would need a flag of some sort. (A simple boolean would do.)
Instead of printing paragraph by paragraph, let the buffer grow and print at the very end. This uses more memory, but it will make the implementation properly testable, as you could return the buffer, which can be used by unit tests.

Both alternatives have advantages and disadvantages.
The simplified version I gave you above is somewhere in the middle.


Console Calculator in C# This is a calculator I've made in C#. Is there any way to improve it? Surely there is a way to get rid of all the ifs that are nested inside one another.

namespace CalculatorCA
{
    using System;
    using System.Collections.Generic;
    class Program
    {
        static void Main()
        {
            Dictionary<int, Func<double, double, double>> MyDict =
                new Dictionary<int, Func<double, double, double>>();
            FillDictionary(MyDict);
            bool KeepOn = true;
            while (KeepOn)
            {
                Console.WriteLine("Enter the first number!");
                double first;
                if (double.TryParse(Console.ReadLine(), out first))
                {
                    Console.WriteLine("Please choose one of the following:\n1-Add\n2-Substract\n3-Multiply\n4-Divide");
                    int choice;
                    if (int.TryParse(Console.ReadLine(), out choice))
                    {
                        if (MyDict.ContainsKey(choice))
                        {
                            Console.WriteLine("Enter the second number!");
                            double second;

                            if (double.TryParse(Console.ReadLine(), out second))
                            {
                                Console.WriteLine("The result is : {0}", MyDict[choice](first, second));
                            }
                        }
                        else
                        {
                            Console.WriteLine("Invalid operation!");
                        }
                    }
                }
                Console.WriteLine("Continue?[Y/N]");
                KeepOn = Console.ReadKey().Key == ConsoleKey.Y;
                Console.Clear();
            }
        }
        public static void FillDictionary(Dictionary<int,Func<double,double,double>> myDictionary)
        {
            myDictionary.Add(1, (x, y) => x + y);
            myDictionary.Add(2, (x, y) => x - y);
            myDictionary.Add(3, (x, y) => x * y);
            myDictionary.Add(4, (x, y) => x / y);
        }
    }
}

That's a pretty concise routine there.
If you had to change it, I would add methods to parse the user input so now your program logic is less nested and we get back to the good old principal of each method having a single purpose.

Normally in a simple app that has a menu structure I would say use case logic instead of if statements as this will allow you to easily extend the options later, but your cleaver use of the dictionary of functions does away with this altogether.

namespace CalculatorCA
{
    using System;
    using System.Collections.Generic;
    class Program
    {
        static void Main()
        {
            Dictionary<int, Func<double, double, double>> MyDict =
                new Dictionary<int, Func<double, double, double>>();
            FillDictionary(MyDict);
            bool KeepOn = true;
            while (KeepOn)
            {
                double first = ReadInput("Enter the first number!");
                int choice = ReadInput("Please choose one of the following:\n1-Add\n2-Substract\n3-Multiply\n4-Divide", 1, MyDict.Count);
                double second = ReadInput("Enter the second number!");

                Console.WriteLine("The result is : {0}", MyDict[choice](first, second));

                Console.WriteLine("Continue?[Y/N]");
                KeepOn = Console.ReadKey().Key == ConsoleKey.Y;
                Console.Clear();
            }
        }
        private static double ReadInput(string prompt)
        {
            Console.WriteLine(prompt);
            double userInput;
            if (double.TryParse(Console.ReadLine(), out userInput))
                return userInput;

            Console.WriteLine(" - Sorry, I expected a double, try again");
            return ReadInput(prompt);
        }

        private static int ReadInput(string prompt, int? min = null, int? max = null)
        {
            Console.WriteLine(prompt);
            int userInput;
            if (int.TryParse(Console.ReadLine(), out userInput))
            {
                if (userInput >= min.GetValueOrDefault(int.MinValue) && userInput <= max.GetValueOrDefault(int.MaxValue))
                    return userInput;

                Console.WriteLine(" - Sorry, I expected an integer, between {0} and {1}", min, max);
                return ReadInput(prompt, min, max);

            }

            Console.WriteLine(" - Sorry, I expected an integer, try again");
            return ReadInput(prompt, min, max);
        }

        public static void FillDictionary(Dictionary<int, Func<double, double, double>> myDictionary)
        {
            myDictionary.Add(1, (x, y) => x + y);
            myDictionary.Add(2, (x, y) => x - y);
            myDictionary.Add(3, (x, y) => x * y);
            myDictionary.Add(4, (x, y) => x / y);
        }
    }
}


Find order to install dependencies Given a JavaScript map object of dependencies and their dependencies,
  determine order to install them:

  Example:

  Input:

{
  p1: [p2, p3],
  p2: [p3],
  p3: []
}

  Output:

[p3, p2, p1]

I really feel like there's a dynamic or recursive solution to this that I can't figure out. Is this true? Can it be done better than my approach? Here's my approach with a while loop.

function installDeps(depsList) {
    var installed = [];
    var order = [];

    while (order.length < Object.keys(depsList).length) {

        for (var depsItem in depsList) {

            if (!installed[depsItem]) {
                var installable = true;

                for (var dep = 0; dep < depsList[depsItem].length; dep++) {
                    if (!installed[depsList[depsItem][dep]]) {
                        installable = false;
                        break;
                    }
                }

                if (installable) {
                    order.push(depsItem);
                    installed[depsItem] = true;
                }
            }
        }
    }

    return order;
}

Heres how I did it properly with topological sorting. Each key of the object is a vertex on a graph, the value dependencies are the adjacent vertices. https://www.youtube.com/watch?v=ddTC4Zovtbc

var deps = {
    p1: ['p2', 'p3'],
    p2: [],
    p3: ['p3']
};

function depSort(deps) {
    var visited = [];
    var sorted = [];

    for (var dep in deps) {
        if (!visited[dep]) {
            depSortUtil(dep, visited, sorted);
        }
    }

    return sorted;
}

function depSortUtil(dep, visited, sorted) {
    visited[dep] = true;

    for (var i = 0; i < deps[dep].length; i++) {
        if (!visited[deps[dep][i]]) {
            depSortUtil(deps[dep][i], visited, sorted);
        }
    }
    sorted.push(dep);
}

console.log(depSort(deps));


Reduce time taken for VBA loop when copying multiple sets of input values, performing Excel formula calculations and recording results My VBA code currently loops for 5,000 iterations and takes about 25 minutes to collect the output data in the Output excel sheet. Is there a way to reduce the time taken for instance by improving the copying and pasting of values, collecting the output data in some kind of array etc.? Given that I will be looping it for up to 10,000 iterations when I obtain more data

Note: The calculations are excel formulas within the Calcs excel sheet, as this is a cash flow schedule with irregular cash flows and discount rates, hence I am unable to automate the cash flow calculations via VBA.

Sub x()

Dim r As Long
Dim lastrow As Long

Application.ScreenUpdating = False
Application.CutCopyMode = False

With Worksheets("MCInput")
lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
MsgBox lastrow - 1 & " Trials"
End With

With Worksheets("Calcs")
    For r = 0 To (lastrow - 2)
        .Range("CASHINPUT").Value = Worksheets("MCInput").Range("TCASHRTN").Offset(r).Value
        .Range("EQINPUT").Value = Worksheets("MCInput").Range("TEQRTN").Offset(r).Value
        .Range("FIINPUT").Value = Worksheets("MCInput").Range("TFIRTN").Offset(r).Value
        .Range("Results").Calculate
        .Range("Results").Copy
        Worksheets("Output").Range("A1").Offset(1 + r, 1).PasteSpecial xlPasteValues
    Next r
End With

Application.ScreenUpdating = True
Application.CutCopyMode = True

End Sub

Use descriptive variable names. r as a variable name tells you nothing and makes your code harder to read. rowOffset tells you what it's used for. This goes a long way to make your code readable.

Declare your variables just before you use them. You only have 2 currently but its easy for variables to increase. Instead of having a wall of declarations at the top of a Function/Sub, like below:

dim r as long
Dim i as long
dim p as range
dim sv as range

Have them declared just before they get used.

dim lastRow as long
lastRow = Worksheets("MCInput").Cells(Rows.Count,"B").End(xlUp).Row

dim rowOffset as long
For rowOffset = 0 to (lastRow - 2)
    `Code that does what you want
Next

This ultimately aids you in refactoring (restructuring) your code when you need to. It also becomes easier to tell when a variable is no longer needed. No code using the variable just after it's declared? Delete it. With a wall of declarations you have to laboriously check for usage. There are tools like Rubberduck, which I'm a contributor to, than can tell you if a variable is used.

You're using a string literal populated with a worksheets name to access the worksheet through the hidden Global object's Worksheets property IE Global.Worksheets("Calcs"). This returns an Object variable which is late-bound and doesn't give you intellisense when you use . (period) after the collection. It's preferred to use the Worksheet.CodeName. You can see this in the Project Explorer window. The CodeName of the worksheet is Sheet1 while the Name (What is shown in the tab) is Calcs.

Sheet1 isn't a helpful name, this ties into using descriptive names above, so we'll change it by double clicking on it in the Project Explorer to display the code behind for the worksheet, then pressing F4 to display the Properties Window (also found under the menu at the top View>Properties. At the top where it says (Name) change it to something more descriptive.

Now instead of using Worksheets("Calcs") use CalculationSheet to access the worksheet object. The same thing can be done to. Two added benefits:

You're no longer dependent on the literal string "Calcs" which stops working if the worksheet is renamed.
You get intellisense. Type CalculationSheet. (note the period) to show a list of accessible members.

There's more that can and probably should be done with your code. Things like worksheet properties would help to clean up and shorten the code which then leads to the realization you'd benefit from creating a proxy for accessing your data. I was nerd-sniped by this already and that can be for another review.


Sectioning element choice for main content in HTML5 Bones The new HTML5 Bones template uses the following example for the main content (I removed some parts (like ARIA, comments, aside, …) not relevant for this question):

Getting Started

    …

Introduction

Welcome to HTML5 Bones. This is a template that contains comments to aid you with setting up your HTML5 document.

Instructions

Read the comments in this template

Decide how you think your content may fit into the template

Start building your document

The whole document has the following outline:

  HTML5 BonesUntitled SectionGetting StartedUntitled SectionIntroductionInstructionsDid you know?

This outline is correct for the document. But I wonder if the use of the section element and the article elements is correct.

I think the section element should be an article element, and the two article elements should be section elements:

Getting Started

Introduction

Instructions

While there are, of course, valid cases where a section element contains article elements, I think this not the case in this example.

The "Getting started" content is without question the main content for this document. The section element can be used for that purpose, but the article element would fit, too. A simple question to ask: Could this whole "Getting started" article be an entry in a feed? If yes, use article.

"Introduction" and "Instructions" are "sub-chapters" for "Getting started". Would it make sense to create separate entries for them in a feed? I don't think so.

However, as this document is meant as a boilerplate and therefor doesn't contain much content, it is hard to decide here. If "Introdcution" and "Instructions" would contain more content, so that these chapters could stand on their own, the current sectioning element choice would be correct.

But then there is the question: What would make more sense for the "typical site" the users of the HTML5 Bones template would create?

I guess you find more documents that need "article > section" than "section > article".

Examples:

a blog: only the front page and the tag pages need section > article, but each blog entry needs article > section.
an "About us" page on a company site: article > section (or section > section)
a shop: only the product listings need section > article, but each product needs article > section

Of course, a template can't make the choice for all users/sites. The users need to know what is right for their content. But I feel like it's dangerous to "default" to this sectioning element choice. If in doubt, one should use rather section than article, because section is what you get anyway (simply by using headings), while article has special meaning.