Data item prototype in a Javascript data structure where object instance functions see own data

Naming Things

The class name dataItem doesn't communicate what it is, or how it is meant to be used:

  There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors. - Martin Fowler

What is a dataItem? From the code, it is a number value and a currency symbol. Perhaps CurrencyFormat might be more appropriate because what you are doing is formatting a number as currency.

Furthermore, naming conventions in JavaScript require that constructor functions should begin with a capital letter (DataItem vs dataItem). This naming convention is reflected in the native JavaScript API as well (String, Number, XMLHttpRequest, ...).

Principle of Single Responsibility

Being that you could format multiple numbers as the same currency, you might want to limit the instances that are available and use them to format any number, rather than keeping track of the number as an instance variable. This is the principle of Single Responsibility (do one thing, and do it well).

You can then provide an instance for each supported currency type, and a factory function that returns the proper formatter based on the currency name (e.g. "USD"):

function CurrencyFormat(symbol, name) {
    this.symbol = currencySymbol;
    this.name = currencyName;
}

CurrencyFormat.prototype = {
    name: null,
    symbol: null,

    constructor: CurrencyFormat,

    format: function(n, decimalPlaces) {
        decimalPlaces = typeof decimalPlaces == "number" ? decimalPlaces : 2;

        return this.symbol + n.toFixed(decimalPlaces) + " " + this.name;
    }
}

CurrencyFormat.AUD = new CurrencyFormat("$", "AUD");
CurrencyFormat.CAD = new CurrencyFormat("$", "CAD");
CurrencyFormat.GBP = new CurrencyFormat("£", "GBP");
CurrencyFormat.USD = new CurrencyFormat("$", "USD");

CurrencyFormat.getFormatter = function(currencyName) {
    if (CurrencyFormat[currencyName] && CurrencyFormat[currencyName] instanceof CurrencyFormat) {
        return CurrencyFormat[currencyName];
    }

    throw new Error("Currency format not implemented: " + currencyName);
};

Given the values you posted, this is how you would use the class:

var taxes = 60;
var expenses = 199.5;
var canadaIncome = 0;

console.log(CurrencyFormat.GBP.format(expenses));
console.log(CurrencyFormat.CAD.format(canadaIncome));
console.log(CurrencyFormat.USD.format(taxes));

If you know the currency name, you can use CurrencyFormat.getFormatter(...) to get the proper object:

// Get a formatter object by name:
var formatter = CurrencyFormat.getFormatter("USD");

// Throws an error because the currency name is not implemented:
var formatter = CurrencyFormat.getFormatter("XYZ");

This allows you to inject a currency formatter into other objects:

function ShoppingCartItem(price, currencyFormatter) {
    this.price = price;
    this.currencyFormatter = currencyFormatter;
}

ShoppingCartItem.prototype.formatPrice = function() {
    return this.currencyFormatter.format(this.price);
}

var item1 = new ShoppingCartItem(105.95, CurrencyFormat.getFormatter("USD"));
var item2 = new ShoppingCartItem(105.95, CurrencyFormat.GBP);

console.log(item1.formatPrice());
console.log(item2.formatPrice());

Removing unnecessary dependencies

There is no need to use jQuery.extend for just a couple of properties. This is an unnecessary dependency. For something as simple as a currency symbol and name, just pass those values in as constructor arguments. Passing in an object of key-value pairs is like hitting a thumb tack with a sledge hammer in this case.

Even if you needed to set a dozen properties by passing in an object of key-value pairs, I still wouldn't use jQuery.extend. It's not magic. It's just a for-in loop. You are better off writing half a dozen lines of code in order to remove a dependency on a large JavaScript library when this one class uses a fraction of what jQuery offers.


Preliminaries

Your compiler should have warned you that in main(), you never use list2.  You do compile with warnings turned on, I hope?

Usually, the first node of a linked list is called the head.  "Root" usually refers to the top of a tree.

mergeList() and findMid() are helper functions, which are designed to be used exclusively to support mergeSort().  It's a good habit to declare helper functions with the static modifier, so that they will be invisible to code in other .c files.

findMid()

The function could be better named, I think.  "Find" sounds like a passive action, so you wouldn't expect that it might modify its inputs (which it does at the end: slow->next = NULL).  I suggest calling it bisectList() instead.

Calling the function will always result in setting *list1 to root, so why bother making list1 an out-parameter?  Going a step further, if there's only one output (list2), you can just return it normally.

So, the function could become static struct node *bisectList(struct node *head).  Here's a more compact implementation.

/**
 * Returns a pointer to a node near the middle of the list,
 * after having truncated the original list before that point.
 */
static struct node *bisectList(struct node *head)
{
    /* The fast pointer moves twice as fast as the slow pointer. */
    /* The prev pointer points to the node preceding the slow pointer. */
    struct node *fast = head, *slow = head, *prev = NULL;

    while (fast != NULL && fast->next != NULL)
    {
        fast = fast->next->next;
        prev = slow;
        slow = slow->next;
    }

    if (prev != NULL)
    {
        prev->next = NULL;
    }
    return slow;
}

mergeList()

The function signature looks fine.  There is altogether too much code, though.

One major problem, which @rolfl alluded to, is that you are duplicating every node that you encounter.  Rather, you should be able to merge the lists just by manipulating the next pointers of the existing nodes.

To start with, you can eliminate the two special cases before the loop.  (That meant, by the way, that your function not only leaked memory, it also had an inconsistent memory management policy: sometimes it would duplicate the list, and sometimes not.)

Once we have decided not to duplicate the nodes, the epilogue becomes trivial, and the last two loops can go away.

The code duplication within the main loop can be reduced by using a pointer to a pointer (which I call **min), referring to whichever list a head with the smaller value.  The if (root == NULL) special case can be removed by initializing a pointer to a dummy head node.

static struct node* mergeList(struct node *list1, struct node *list2)
{
    struct node dummy_head = { 0, NULL }, *tail = &dummy_head;

    while ( (list1 != NULL) && (list2 != NULL) )
    {
        struct node **min = (list1->element < list2->element) ? &list1 : &list2;
        struct node *next = (*min)->next;
        tail = tail->next = *min;
        *min = next;
    }
    tail->next = list1 ? list1 : list2;
    return dummy_head.next;
}

mergeSort()

It would be more natural to accept a struct node * and return a struct node *, I think.

You left in some printf() calls for debugging.  Why not take advantage of the existing printList() function for that?

Most of the improvements are just natural consequences of the changes suggested above.

struct node *mergeSort(struct node *head)
{
    struct node *list1 = head;
    if ( (list1 == NULL) || (list1->next == NULL) )
    {
        return list1;
    }

    struct node *list2 = bisectList(list1);

    printf("\nList1 = "); printList(list1);
    printf("\nList2 = "); printList(list2);

    return mergeList( mergeSort(list1), mergeSort(list2) );
}

Conclusion

Your understanding of the mergesort algorithm is generally sound.  However, there were some massive memory leaks, and the implementation was verbose.  Try to look for opportunities to design more natural function interfaces and reduce special cases.


Bowling game Kata in Scala - pattern match

Some tips:

When pattern matching and inspecting multiple values of a sequence type (Seq, List, Array, etc) you can reduce the length of your expression by using sequence patterns instead of explicitly breaking the sequence up with the :: operator. So instead of a :: b :: c :: d :: Nil you can more concisely use Seq(a, b, c, d).

When you want to check for explicit values while pattern matching on an object you can use those values instead of replacing them with variables that are then checked with an if statement. For example case Seq(a, b, c) if a == 10 => ...  can be more concisely expressed as case Seq(10, b, c) => ...

When using pattern matching on sequences (especially when the case expression goes beyond the standard head :: tail) it can enhance legibility to use single letter variable names and comments instead of long variable names. I think that we would both agree that good code should describe itself through both value and function names. However, in this case there is no way of adding intuition with function names and so all of the description ended up in your value names.
Like I said before, do what works for you. If legibility was our only metric then maybe pattern matching isn't the ideal way to implement your function. It could still be recursive, but instead of cases you could use functions. Do whatever suits you the best but when possible I would recommend short variable names accompanied by comments over long variable names.

Some code:
object BowlingGame {
  def count(points: Seq[Int]): Int = {
    def helper(ps: Seq[Int], acc: Int): Int = ps match {
      case Nil =>
        acc

      case Seq(a) =>
        acc + a

      // strike or spare in last round
      case xs @ Seq(a, b, c) =>
        acc + xs.sum

      // strike
      case Seq(10, a, b, _*) =>
        helper(ps.tail, acc + 10 + a + b)

      // spare
      case Seq(a, b, c, _*) if a + b == 10 =>
        helper(ps.drop(2), acc + a + b + c)

      // neither a spare or a strike
      case Seq(a, b, _*) =>
        helper(ps.drop(2), acc + a + b)
    }
    helper(points, 0)
  }
}


Project Euler 67 | Maximum sum path II reading from file

I tried to solve the Problem Euler 67 with Go, because I started to
study Go recently.
What could be a better approach? Could I use goroutines to increase
performance?

Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.
I'm going to skip a full code review and narrowly focus my code review on the use of performance benchmarks. Go has several tools to measure performance, including the Go standard library testing package Benchmark type.

The elapsed time for the program is somewhat interesting but not very useful. Some results from running my program code and your program code several times to prime the Linux file buffer cache:
peterGo:
$ go run euler67.go
7273
175.641µs

Mdsp:
$ go run mdsp.go
Total sum: 7273, Elapsed time: 277.556µs

Here's how I benchmarked your Project Euler Problem 67 maximum sum path algorithm using p067_triangle.txt as input.
BenchmarkEuler67 measures overall (load and sum) performance while ignoring the effects of hardware (for example, HDD I/O), operating system (for example, cached disk data), and other extraneous effects. The triangle has 100 rows with a total of 5050 (= 100 * (100 + 1) / 2) elements.
$ go test euler67_test.go euler67.go -bench=. -benchmem
BenchmarkEuler67-4   13299   89766 ns/op   68440 B/op   210 allocs/op

These are benchmarks for BenchmarkEuler67 components.
$ go test euler67_test.go euler67.go -bench=. -benchmem
BenchmarkLoad-4      16959   70742 ns/op   68440 B/op   210 allocs/op
BenchmarkRow-4     1000000    1137 ns/op   896 B/op       1 allocs/op
BenchmarkSum-4       60830   19595 ns/op   0 B/op         0 allocs/op

BenchmarkLoad measures loading the in-memory text triangle values into a triangle of int slices.
BenchmarkRow measures parsing the text for the maximum (100 integer) triangle row into to a slice of Go ints. parseInts, a specialization, provides an improvement over strings.Fields for the loadTriangle function.
strings.Fields:
BenchmarkLoad-4      10000  114958 ns/op  153304 B/op   310 allocs/op

parseInts:
BenchmarkLoad-4      16959   70742 ns/op   68440 B/op   210 allocs/op

BenchmarkSum measures the fundamental maximum sum path algorithm performance: 19.6 microseconds. The maxPathSum function reduces memory bytes and allocations to zero by reusing the input for intermediate results.
Clearly, the major expense is loading the inefficient input into an efficient data structure for the maximum sum path algorithm.
To see how the code scales, here are benchmarks for a triangle with 1000 rows with a total of 500500 (= 1000 * (1000 + 1) / 2) elements.
BenchmarkEuler67-4     174   6810618 ns/op   5941675 B/op   2015 allocs/op
BenchmarkLoad-4        186   6399151 ns/op   5941685 B/op   2015 allocs/op
BenchmarkRow-4       93747     12505 ns/op      8192 B/op      1 allocs/op
BenchmarkSum-4        1916    622193 ns/op         0 B/op      0 allocs/op

6.8 milliseconds for 1000 rows is not unreasonable.
Improving performance is an iterative process and there is more that we can do, but is it worth it. The CPU, memory, and allocation numbers are small. Unless we expect many iterations, it doesn't seem like further optimization is worth much time, effort, and loss of readability.

euler67.go:
package main

import (
    "bufio"
    "flag"
    "fmt"
    "io"
    "os"
    "strconv"
    "time"
)

func parseInts(s string, buf []int) ([]int, error) {
    buf = buf[:0]
    inInt := false
    i := 0
    for j := 0; j <= len(s); j++ {
        if j == len(s) || ('0' > s[j] || s[j] > '9') {
            if inInt {
                n, err := strconv.Atoi(s[i:j])
                if err != nil {
                    return buf[:0], err
                }
                buf = append(buf, n)
            }
            inInt = false
        } else if !inInt {
            inInt = true
            i = j
        }
    }
    return buf, nil
}

func loadTriangle(r io.Reader) ([][]int, error) {
    var ta [][]int
    s := bufio.NewScanner(r)
    for s.Scan() {
        buf := make([]int, 0, len(ta)+1)
        row, err := parseInts(s.Text(), buf)
        if err != nil {
            return nil, err
        }
        if len(row) != len(ta)+1 {
            err := fmt.Errorf(
                "triangle: %d cols for row %d",
                len(row), len(ta)+1,
            )
            return nil, err
        }
        ta = append(ta, row)
    }
    if err := s.Err(); err != nil {
        return nil, err
    }
    return ta, nil
}

func maxPathSum(ta [][]int) int {
    for r := len(ta) - 2; r >= 0; r-- {
        r0, r1 := ta[r], ta[r+1]
        for c0 := range r0 {
            left, right := r1[c0], r1[c0+1]
            if left >= right {
                r0[c0] += left
            } else {
                r0[c0] += right
            }
        }
    }
    if len(ta) == 0 || len(ta[0]) == 0 {
        return 0
    }
    return ta[0][0]
}

func euler67(r io.Reader) (int, error) {
    ta, err := loadTriangle(r)
    if err != nil {
        return 0, err
    }
    return maxPathSum(ta), nil
}

func since(start time.Time) { fmt.Println(time.Since(start)) }

func main() {
    defer since(time.Now())

    flag.Parse()
    // https://projecteuler.net/project/resources/p067_triangle.txt
    // 100 rows 15.2 kB (15,150 bytes)
    filename := `p067_triangle.txt`
    if len(flag.Arg(0)) > 0 {
        filename = flag.Arg(0)
    }
    f, err := os.Open(filename)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    defer f.Close()

    sum, err := euler67(f)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println(sum)
}

euler67_test.go:
package main

import (
    "bufio"
    "bytes"
    "io/ioutil"
    "strings"
    "testing"
)

func BenchmarkEuler67(b *testing.B) {
    for N := 0; N < b.N; N++ {
        _, err := euler67(bytes.NewReader(benchData))
        if err != nil {
            b.Fatal(err)
        }
    }
}

func BenchmarkLoad(b *testing.B) {
    for N := 0; N < b.N; N++ {
        _, err := loadTriangle(bytes.NewReader(benchData))
        if err != nil {
            b.Fatal(err)
        }
    }
}

func BenchmarkRow(b *testing.B) {
    var last string
    s := bufio.NewScanner(bytes.NewReader(benchData))
    for s.Scan() {
        last = s.Text()
    }
    if err := s.Err(); err != nil {
        b.Fatal(err)
    }
    cols := len(strings.Fields(last))
    b.ResetTimer()

    for N := 0; N < b.N; N++ {
        buf := make([]int, 0, cols)
        _, err := parseInts(last, buf)
        if err != nil {
            b.Fatal(err)
        }
    }
}

func BenchmarkSum(b *testing.B) {
    for N := 0; N < b.N; N++ {
        b.StopTimer()
        ta, err := loadTriangle(bytes.NewReader(benchData))
        if err != nil {
            b.Fatal(err)
        }
        b.StartTimer()
        _ = maxPathSum(ta)
    }
}

var benchData = func() []byte {
    // https://projecteuler.net/project/resources/p067_triangle.txt
    // 100 rows 15.2 kB (15,150 bytes)
    filename := `p067_triangle.txt`
    data, err := ioutil.ReadFile(filename)
    if err != nil {
        panic(err)
    }
    return data
}()


First off, you should always close a file in Python.
There are two ways to do that.

The old style way:

file_handler = open('/proc/cpuinfo')
// Your code here
file_handler.close()
The 'new' way with with.

with open('/proc/cpuinfo') as file_handler:
    // Your code here

The second is more recommended as then it's both clear when the file is open, and you don't forget to close it.

While /proc/cpuinfo is unlikely to have more than one : per line, it could happen. As it seems model name can be whatever the model is called. If a vendor were to put a : in their name, your code won't work. with the exception:

ValueError: dictionary update sequence element #1 has length 3; 2 is required

To avoid this as an issue, you can use the optional second argument to str.split(':', 1).

If you want to use a dictionary comprehension at all cost. Then it's the same as your above code, but it will have a dictionary comprehension surrounding it.

with open('/proc/cpuinfo') as file_handler:
    cpuinfo = {
        key: value
        for key, value in (
            map(str.strip, line.split(':', 1))
            for line in file_handler
            if ':' in line
        )
    }

This is in my opinion worse than your above code, as it's common knowledge that dict([['key', 'value']]) can be used to make a dict, which was added in 2.2. Where dictionary comprehensions were added in 2.7.
And your original code is a lot less verbose.

You could however use a functional approach to this. Which has the drawback of needing to define line twice, and is more verbose than the original code.

with open('/proc/cpuinfo') as file_handler:
    cpuinfo = dict(map(
        lambda line: map(str.strip, line.split(':', 1)),
        filter(lambda line: ':' in line, file_handler)
    ))

Overall I would recommend using your original code, but with with and line.split(':', 1)) added.

Just to note, ':' in line returns false every time the CPU core changes.
For example from my /proc/info. (note I removed the flags)

processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 42
model name  : Intel(R) Core(TM) i5-2500 CPU @ 3.30GHz
stepping    : 7
microcode   : 0x28
cpu MHz     : 1728.761
cache size  : 6144 KB
physical id : 0
siblings    : 4
core id     : 0
cpu cores   : 4
apicid      : 0
initial apicid  : 0
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
bugs        :
bogomips    : 6800.31
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

processor   : 1
vendor_id   : GenuineIntel
cpu family  : 6
model       : 42
model name  : Intel(R) Core(TM) i5-2500 CPU @ 3.30GHz
stepping    : 7
microcode   : 0x28
cpu MHz     : 1686.609
cache size  : 6144 KB
physical id : 0
siblings    : 4
core id     : 1
cpu cores   : 4
apicid      : 2
initial apicid  : 2
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
bugs        :
bogomips    : 6800.31
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

This also shows that the information can change. E.g. cpu MHz:1728.761 and cpu MHz:1686.609. So you may not want to overwrite some of this information. Also if you have more than one CPU (say you are using a sever) then you could return false on one CPU and true on another, but as the last core overwrites all the previous data it's somewhat up to chance to know.

Due to this I would recommend that you change your function to make cpuinfo a list of dicts.

Finally as far as I know unless you read the entire file and split on \n\n then there is no way to make it a comprehension.
And so I would recommend:

def is_hyperthreading_enabled():
    with open('/proc/cpuinfo') as file_handler:
        cpuinfo = []
        temp_dict = {}
        for line in file_handler:
            try:
                key, value = map(str.strip, line.split(':', 1))
            except ValueError:
                cpuinfo.append(temp_dict)
                temp_dict = {}
            else:
                temp_dict[key] = value

    return any(map(lambda core: core['siblings'] != core['cpu cores'], cpuinfo))

Note, the above works as I make the assumption that the file always ends with an empty line. Otherwise you would be missing one of the cores. This assumption seems to be true, as I tested if /proc/cpuinfo ends with an empty line on all a single; quad-core, dual-core and single core, CPU.
If you think this is too small a test case, you can add the following after the for loop.

if temp_dict:
    cpuinfo.append(temp_dict)

So if you only care about one core, your way is best. If you want to test if any CPU can, then you would want to use the above. And if you want to know if all of them can then you should change any to all in the above.


Loop Through bitarray to retrieve subsets of that bitarray

You're definitely on the right track by using a "Numbers" table, rather than a loop or cursor. Given the small size and the fact that you know up front that you only need 24 rows, there's no need to calculate it. You can also save a bit my creating the numbers table on the fly.

What you have now should already be reasonably fast but the in-line tally table and hard coded number of rows should beat it... If only by a small margin.

DECLARE @Ba NVARCHAR(48) = '000011110000000001110000000011111111000011110000'
DECLARE @numberOfIntervals INT = 24;
DECLARE @intervals TABLE(
    SequenceId INT,
    [Periods] NVARCHAR(24)
);

WITH
    cte_n (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1) ) n (n)),
    cte_Tally (n) AS (
        SELECT TOP (24)
            ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
        FROM
            cte_n a CROSS JOIN cte_n b
        )
INSERT INTO @intervals
SELECT
    t.n - 1 AS [SequenceId],
    SUBSTRING(@Ba, t.n, @numberOfIntervals) AS [Values]
FROM
    cte_Tally t
WHERE
    SUBSTRING(@Ba, (t.n - 1)  + @numberOfIntervals, 1) = '1';

SELECT
    *
FROM
    @intervals;


Check this function which returns the mid point X,Y in WKT format. Please note this function uses the SDO_LRS of Oracle which is part of Oracle Spatial.

create or replace function get_line_midpoint
   (line_in IN sde.st_geometry)
  -- RETURN sde.st_geometry
  RETURN VARCHAR2
IS
wkt_geometry clob;
ora_geometry sdo_geometry;
mid_x number(10,6);
mid_y number(10,6);
mid_point_geom sde.st_geometry;
BEGIN

SELECT  sde.ST_AsText(line_in) INTO wkt_geometry FROM DUAL;
ora_geometry := SDO_UTIL.FROM_WKTGEOMETRY(wkt_geometry);

--mid_x:= sdo_cs.transform(SDO_LRS.CONVERT_TO_STD_GEOM(SDO_LRS.LOCATE_PT(SDO_LRS.CONVERT_TO_LRS_GEOM(ora_geometry, 3), SDO_GEOM.SDO_LENGTH(ora_geometry,3)/2)),8307).SDO_POINT.X;
mid_x:= SDO_LRS.CONVERT_TO_STD_GEOM(SDO_LRS.LOCATE_PT(SDO_LRS.CONVERT_TO_LRS_GEOM(ora_geometry, 3), SDO_GEOM.SDO_LENGTH(ora_geometry,3)/2)).SDO_POINT.X;

--mid_y:= sdo_cs.transform(SDO_LRS.CONVERT_TO_STD_GEOM(SDO_LRS.LOCATE_PT(SDO_LRS.CONVERT_TO_LRS_GEOM(ora_geometry, 3), SDO_GEOM.SDO_LENGTH(ora_geometry,3)/2)),8307).SDO_POINT.Y;
mid_y:= SDO_LRS.CONVERT_TO_STD_GEOM(SDO_LRS.LOCATE_PT(SDO_LRS.CONVERT_TO_LRS_GEOM(ora_geometry, 3), SDO_GEOM.SDO_LENGTH(ora_geometry,3)/2)).SDO_POINT.Y;

ora_geometry := SDO_UTIL.FROM_WKTGEOMETRY('point ('|| mid_x || ' ' || mid_y ||')');

return 'point ('|| mid_x || ' ' || mid_y ||')';

EXCEPTION
WHEN OTHERS THEN
   raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END;


I'm not really a VB.Net'er but you appear to be able to achieve what you're after using the Widening Operator.  It allows you to make your value property a Friend so that it can only be accessed from within your module.  However, it's not ideal, as you have to create the widening operator in your FundDetail class and any inheritted classes.  Depending on the number of different field types you may end up with more typing.  I found that I had to change the isValid method to Overridable, rather than Shared in order to get it to be called on derived classes, but that might be because of my lack of VB.Net experience.  It also works by creating new instances of objects so there is some overhead.  An example of what it looks like is below:

Public Class FundElement
    Public Name As New FundDetail
    Public Price As New FundDetail
    Public Code As New CodeDetail
End Class

Public Class FundDetail

    Protected _value As String

    Friend Property value As String
        Get
            Return _value
        End Get

        Set(valueToAssign As String)
            If isValid(valueToAssign) Then
                _value = valueToAssign
            Else
                Throw New ArgumentException
            End If
        End Set
    End Property

    Overridable Function isValid(detail As String) As Boolean
        Return True
    End Function

    Public Shared Widening Operator CType(ByVal val As String) As FundDetail
        Dim retVal As New FundDetail
        retVal.value = val
        Return retVal
    End Operator
    '
    Public Shared Widening Operator CType(ByVal val As FundDetail) As String
        Return val.value
    End Operator
End Class

Public Class CodeDetail
    Inherits FundDetail

    Public Overrides Function isValid(value As String) As Boolean
        Dim intPattern As Regex = New Regex("[a-zA-Z]{3}[0-9]{12}")
        Return intPattern.IsMatch(value)
    End Function

    Public Shared Shadows Widening Operator CType(ByVal val As String) As CodeDetail
        Dim retVal As New CodeDetail
        retVal.value = val
        Return retVal
    End Operator

    Public Shared Shadows Widening Operator CType(ByVal val As CodeDetail) As String
        Return val.value
    End Operator

End Class

And Usage:

    Dim fe As New FundElement
    fe.Name = "Google Inc"
    fe.Code = "USD451234151234"

    Dim val As New String(fe.Name)

    Console.WriteLine("{0}:{1}", CStr(fe.Name), CStr(fe.Code))

You'll notice from the usage example that whilst it can be used for String targets directly, it also doesn't default cast the object to a string when passed to something that expects an unknown / object such as the WriteLine call.  So there are some definite downsides to this approach, it's whether or not the benefits are sufficient for your case.

Bug?

As I've said, I rarely write VB.  However, this feels like a bug to me:

Shared Function isValid(detail As String) As Boolean
Shared Shadows Function isValid(value As String) As Boolean

You're using shared functions to determine if the strings are valid.  So, if you do this:

CodeDetail.isValid("USD45123415~~~~~~~~~~1234")

The shadowing works, and the correct implementation is invoked.  However, because you're invoking the implementation from the base class:

If isValid(valueToAssign) Then

Then as the base class only knows about the isValid it's implemented, it's invoking that version, not the newer version on the child.  As I've said in the comments, if I do this:

fe.Code.value = "USD45123415~~~~~~~~~~1234"

No error is thrown, however if I do this:

If CodeDetail.isValid("USD45123415~~~~~~~~~~1234") Then

Then I know the error should be thrown.

If you want it to behave the way you're expecting, you need to use Overridable functions (as in my example) so that dynamic dispatch from the base class works.


Backwards stepwise regression code in R (using cross-validation as criteria)

Your code is good. I could not find important corrections to be made. I could find only some small cosmetic improvements - nothing serious.

For example. You do not need the caret package loaded for this task. You do not need to use next at the end of the while loop. It is good practice to keep your code in width of 80 characters. It improves readability a lot. See my code attached.

rm(list=ls())
gc()

library(forecast)
library(fpp)

set.seed(1)
x1 <- c(1:500) * runif(20, min=0, max=200)
x2 <- c(1:500) * runif(20, min=0, max=200)

data(credit)
score <- credit$score
log.savings <- log(credit$savings+1)
log.income <- log(credit$income+1)
log.address <- log(credit$time.address+1)
log.employed <- log(credit$time.employed+1)

##################################

#Input
full.model <- score ~ log.savings + log.income + log.address +
  log.employed + x1 +x2

# 1. Start with the full model
counter <- 1L
full <- lm(full.model)

scopevars <- attr(full$terms, "predvars") # list of model predicotrs
n <- length(full$residuals)  # sample size
current_best <- full #what is the currenly the best model?
 # that would be our full model for now

while(T) { #process until we break the loop

  best_cv <- CV(current_best)[1] #the CV of the current_best model
  temp <- summary(current_best) #summary output of the current_best model
  p <- dim(temp$coefficients)[1]  # current model's size

  rnames <- rownames(temp$coefficients)  # list of terms in the current model

  compare <- matrix(NA,p,1) # create a matrix to store CV information
  rownames(compare) <- rnames #name the matrix

  # create a loop that drops one predictor at a time and calculates
  # the CV of the regression when that predictor is dropped
  # put all the information into "compare"
  # drop the variable that has the lowest CV when it is dropped.

  for (i in 2:p) {
    drop_var <- rnames[i] #variable to be deleted
    f <- formula(current_best) #current formula
    f <- as.formula(paste(f[2], "~", paste(f[3], drop_var, sep=" - ")))
    # modify the formula to drop the chosen variable (by subtracting it)
    new_fit <- lm(f)  # fit the modified model
    compare[i] <- CV(new_fit)[1]
  }

  remove_var <- rownames(compare)[which.min(compare)]
  # drop is the varibale that is associate with the lowest CV
  update_cv <- compare[which.min(compare)]

  if (update_cv > best_cv) break # we should not continue
  # if dropping a variable will not improve CV

  write(paste("--- Dropping", counter, remove_var , update_cv, "\n"), file="")
  # output the variables we are dropping

  f <- formula(current_best) #current formula
  f <- as.formula(paste(f[2], "~", paste(f[3], remove_var , sep=" - ")))
  # modify the formula to drop the chosen variable (by subtracting it)
  current_best <- lm(f) # we now have a new best model
  counter <- counter + 1L # update our counter
} #end the while loop

print(current_best)
CV(current_best)


I think here a small class would help to keep track of all things related to a Button:

class Button(DigitalInOut):
    def __init__(self, name, pin, direction=Direction.INPUT, pull=Pull.UP):
        self.name = name
        super().__init__(pin)
        self.direction = direction
        self.pull = pull

    def wait_for_press(self):
        while self.value:
            pass

(Untested, since I obviously don't have your hardware lying around.)

With your initialization code can be shortened a bit:

names = ["A", "B", "C"]
pins = [board.D9, board.D6, board.D5]
buttons = {name: Button(name, pin) for name, pin in zip(names, pins)}

As for your printing to the oled, they always follow the same format, so just define a function for that:

def print_page(oled, strings):
    oled.fill(0)
    for i, s in enumerate(strings):
        oled.text(s, 0, i * 8, 1)
    oled.show()

After which your main code becomes:

messages = [
"""
Adafruit Feather
Program selector

Press A to continue
""",
"""
Instructions:
Use A and C to move
up and down
Press A to continue
""",
"""
Instructions (cont.):
Press B to select a
program.
Press A to continue
""",
...
]

for message in messages:
    print_page(oled, message.splitlines()[1:])
    buttons["A"].wait_for_press()
oled.fill(0)
oled.show()

Note that I used triple-quoted strings so you can just write your message in plaintext, line-breaks included. You might want to outsource that part to another file and just load / import from that.


Troublesome Frog (AIO Intermediate 2013) 3.x

Without going into the algorithm I see a few things that could be improved upon

Use with open(...) as ... instead of manually opening and closing
Use max() instead of the ... if ... else ... structure
Improve naming of your variables, PEP8 is a good guideline
Use if __name__ == __main__:
List comprehension at reading input

def froggin(fences):
    maximum = 0
    for idx in range(1, N - 1):
        left = min(fences[0: idx])
        right = min(fences[idx + 1:])
        middle = fences[idx]

    if left < middle and right < middle:
        new_max = middle - left + middle - right
        maximum = max(new_max, maximum)
    return maximum

if __name__ == '__main__':
    with open('frogin.txt', 'r') as infile:
        N = int(infile.readline())
        fences = [int(infile.readline()) for _ in range(N)]

    result = froggin(fences)

    with open('frogout.txt', 'w') as frogout:
        frogout.write(str(result))


Refactoring from .. in .. select to more compact one

Idon't see why you would want to shorten that piece of code but here's the same result in one line and using a LinQ method-chain instead of query-syntax:

var response = otherClass.SomeMethod(contract.Contact.PartnerNumbers.Select(p => p.Pnr), DateTime.Now.Date);

Edit:

Since you have no parameters that have influence on the calculation of the response, here's a method for re-usability:

public int GetResponse()
{
    var collection = from partnerNumbers in contract.Contact.PartnerNumbers select partnerNumbers.Pnr;
    var response = this.otherClass.SomeMethod(collection, DateTime.Now.Date);
    return response;
}

or with LinQ method-chain:

public int GetResponse()
{
    return otherClass.SomeMethod(contract.Contact.PartnerNumbers.Select(p => p.Pnr), DateTime.Now.Date);
}


Here's a shot at it: (Requires PowerShell v3 or higher)

The idea here is to get all non-reparsepoint directories first.
For each directory, recurse into the subdirectory and then output the files at the current level.

In it's simplest form, it looks like this:

function Get-ChildItemNoReparsePoint($Path)
{
    Get-ChildItem -Path $Path -Attributes !ReparsePoint -Directory | foreach {
        Get-ChildItemNoReparsePoint $_.Fullname
    }
    Get-ChildItem -File $Path
}

A more full example is shown below:

We hook into the powershell help system by adding specially formatted comment.

By adding the [CmdletBinding()] attribute, we get access to the powershell common parameters (Get-Help about_Common_Parameters).

By adding the OutputType attribute, you get tab completion after the command in the pipeline. (try 'Get-ChildItemNoReparsePoint| Foreach <tab>')

The Parameter attribute enables usage of the function in a pipeline (together with the PSPath alias).

function Get-ChildItemNoReparsePoint
{
<#
.SYNOPSIS
    Gets all files of a directory recursivly, excluding reparse points
.OUTPUTS
    System.IO.FileInfo
.EXAMPLE
dir | Get-ChildItemNoReparsePoint
.EXAMPLE
Get-ChildItemNoReparsePoint ~/Documents | Foreach FullName | Set-Content thefiles.txt
.EXAMPLE
Get-ChildItemNoReparsePoint ~/Documents -OutVariable files | Foreach FullName | Set-Content thefiles.txt
$files | Group-Object Extension
#>
[CmdletBinding()]
[OutputType([System.IO.FileInfo])]
param(
    [Parameter(ValueFromPipelineByPropertyName)]
    [Alias('PSPath')]
    # Specifies a path to one or more locations.
    [string[]]$Path=$pwd
)
process
{
    Get-ChildItem -Path $Path -Attributes !ReparsePoint -Directory | Get-ChildItemNoReparsePoint
    Get-ChildItem -File $Path
}

Set-Content can be used instead of Out-File to bypass PowerShell's formatting step.

Get-NonReparsePointDirectoryFiles | foreach FullName | Set-Content -PassThru thefiles.txt


Longest substring with 2 unique characters in a given string at linear time

Corner cases

You correctly handle the corner cases of too short input and null input.
But you forgot to handle the case of all same characters, for example "aaa".
On such input the program throws StringIndexOutOfBoundsException on line secondUnique = s.charAt(i);.

Variable scope

The variable c is only needed within the main for loop,
so it would be best to declare it inside the loop.

Style

This is fine:

for (; (i < len) && (s.charAt(i) == firstUnique); i++);

But it looks a bit strange.
A for loop is easiest to read in its most classing form a counting loop:
it performs some initialization,
then on each iteration it does its main work in the body.
Here, the main work to do is the counting.
So if you transform this to a while loop with a body,
it becomes slightly easier to read.


The compiler doubles as a code-analysis tool

Compiling your file like: gcc usename.c -Wall -pedantic Warns you of a bad practice in your code:

usename.c:12:5: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
     fgets(userName, NAME_LEN, stdin);

You should use the return value to check if input reading happened correctly.

Small helper function to increase readibility

The line

userInitials[++pos] = userName[i] - ('a' - 'A');

is not so immediate to understand, I suggest writing a tiny function:

char to_uppercase(char letter) {
    return letter - ('a' - 'A');
}

and calling it like:

 userInitials[++pos] = to_uppercase(userName[i]);

The C99 Standard and variable scope

All major C compiler support C99, I suggest using the appropriate flag to enable it and write:

for(int i = 0; userName[i] != '\n' && userName[i] != '\0'; i++)

to shorten the scope of i.

Excellent parametrization

You defined a constant for NAME_LEN and named it meanigfully instead of sprinkling a random number all over your code, excellent!

For further improvement I suggest using a

static const int NAME_LEN = 80 + 1

For reasons discussed here.


Improving time complexity of finding the longest palindrome in Python

[EDIT] I believe the time-out occurs if you are not fast enough typing your code in the website where this challenge is posted. I believe it is not about optimizing code to run faster, but how quickly you can come up with working code. The following is still true in regards to Code Review:

I might not have all improvements, but here are some I would do

from re import sub

you could rewrite this function:

def clean_string(self, string):
    return sub(r'[^a-zA-Z0-9]', '', string)

and rewrite this function:

def is_palindrome(self, string):
    return string[::-1]==string

Then the first if statement in def longestPalindrome(self, A) would change too:

def longestPalindrome(self, A):
    if self.is_palindrome(A):
        return A

No need for this:

    if len(A)==1:
        return A

You can replace the while loops with for loops, something like this:

def longestPalindrome(self, A):
    if self.is_palindrome(A):
        return A
    cleaned = self.clean_string(A)
    for l in range(len(cleaned)-1,0,-1):  ## l = lenght to check high to low
        for i in range(0, len(cleaned)-l+1):  ## i is position in A to check
            if self.is_palindrome(A[i:l+i]):
                return A[i:l+i]
    return None

Those changes would be faster then your original code, but I did not do any scientific tests, so the obligatory: "YMMV"

[EDIT]

In fact you can shorten the code further:

from re import sub

class Solution:

    def longest_palindrome(self, a):
        if a[::-1] == a:
            return a
        a = sub(r'[^a-zA-Z0-9]', '', a)
        for l in range(len(a)-1, 0, -1):
            for i in range(0, len(a)-l+1):
                if a[i:l+i][::-1] == a[i:l+i]:
                    return a[i:l+i]
        return None

s = Solution()
print(s.longest_palindrome("abbcccaaadaaakl"))

and you really don't need a class here:

from re import sub

def lp(a):
    if a[::-1] == a:
        return a
    a = sub(r'[^a-zA-Z0-9]', '', a)
    for l in range(len(a)-1, 0, -1):
        for i in range(0, len(a)-l+1):
            if a[i:l+i][::-1] == a[i:l+i]:
                return a[i:l+i]
    return None

print(lp("abbcccaaadaaakl"))


Android LiveData Shared between activities by Application Session

Is a good practice to share LiveData?
Yeah

Here as you are using the data in databridge as a single source of truth and it is used hold data which is needed to be shared across multiple screen with live updates, Livedata is a really good option as it will also handle the lifecycle for you.

Android docs also has sample on Extending LiveData to create your own singleton data source which you may find helpful.

Also you can leverage the feature of Object declarations in kotlin to lazy initialize your DataBridge rather than in Application class.


The first thing is when you use parenthesis it means that you pass a tuple to a function instead of single parameters. So you can ditch them.

The second thing is that bool supports pattern matching

The third thing is that you can use recursion instead of mutable variables. Note the usage of rec which enables tail call optimisation.

The code would look something like this.

let rec private WaitForData2 (client : TcpClient) (dataLength : int) (loopBreaker : bool) (result: bool) : Async<bool>=
    async {
        match loopBreaker with
        | true ->
            let isConnectionAlive : bool = IsConnectionEstablished client && client <> null
            match isConnectionAlive, client.Available >= dataLength with
            | true, true ->
                Task.Delay(500)
                |> Async.AwaitTask
                |> ignore
                return! WaitForData2 client dataLength false true
            | false, _ ->
                Task.Delay(500)
                |> Async.AwaitTask
                |> ignore
                return! WaitForData2 client dataLength false false
            | _, _ ->
                Task.Delay(500)
                |> Async.AwaitTask
                |> ignore
                return! WaitForData2 client dataLength true false
        | false -> return result


The line with from only defines the enumeration, but it doesn't actually run over the list and apply your select clause. In your case, that one is only applied when you call FirstOrDefault.

Therefore, to speed up the call to FirstOrDefault you need to speed up your where condition. I mean this one:

s.Field<string>(Cols.Samplenumber) == sourceRow.Field<string>(Cols.Samplenumber)
      && s.Field<string>(Cols.ElementName) == elementTest[0].Trim()
      && s.Field<string>(Cols.AnalysisNumber) == elementTest[1].Trim()

The most expensive parts about this are probably the calls to s.Field<string>(...), followed by the Trim() calls. All of these can be cached. Just convert the maindata into something that's cheap to access, and only do the conversion once, outside of the for loop. Something more or less like this (this won't run as is, only use it as inspiration):

struct TempItem
{
    public string Samplenumber;
    public string ElementName;
    public string AnalysisNumber;
    public string AnalysisStatus;
}
string sourceSampleNumber = sourceRow.Field<string>(Cols.Samplenumber);
var lookUpList = mainData.AsEnumerable().Where(i => i.Samplenumber == sourceSampleNumber).Select(i=> new TempItem {
        Samplenumber = s.Field<string>(Cols.Samplenumber),
        ElementName = s.Field<string>(Cols.ElementName),
        AnalysisNumber = s.Field<string>(Cols.AnalysisNumber),
        AnalysisStatus = s.Field<string>(Cols.AnalysisStatus)
    }).ToList(); // the ToList() part here forces application of the linq expressions

for (int i = pivotStartIndex; i < sourceTable.Columns.Count; i++)
{
    string[] elementTest = sourceTable.Columns[i].ColumnName.Split('-');
    string elementName = elementTest[0].Trim();
    string analysisNumber = elementTest[1].Trim();
    var mChars = lookUpList.Where(i => i.ElementName == elementName && i.AnalysisNumber == analysisNumber).Select(i=>i.AnalysisStatus);
    retList.Add(mChars.FirstOrDefault());
}


Strict types decorator (works only with Python 3.5)

You should change this part a bit:

    for key in all_args:
        if key in hints:
            if type(all_args[key]) != hints[key]:
                raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))

Here, you are silently ignoring missing type hints, but if the user went as far as to use this decorator, you should raise an exception instead, like this:

    for key in all_args:
        try:
            if type(all_args[key]) != hints[key]:
                raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))
        except IndexError:
                raise TypeError('The formal parameter {} was not given a type'.format(key))

Specific Errors & Exceptions

Exception is hilariously un-informative, use TypeError to convey more information.

Order of conditionals

    if type(res) == hints['return']:
        return res
    else:
        raise Exception('Type of result is {} and not {}'.format(type(res), hints['return']))

Here, the real logic is in the else, but I prefer seeing the main logic after the if, like this:

if type(res) != hints['return']:
    raise Exception('Type of result is {} and not {}'.format(type(res), hints['return']))
return res

Now it looks more like a simple perturbation of an almost linear function, than a full-blown logic statement.

Please do not abbreviate

res -> result
func -> function

It takes 0.5 seconds more to type and a tenth of the time to read.


Class and Static practice, IDS and a max instance count

Why don't you initialize created in the definition?

What does JAM stand for?

Why do you calculate length but never use it?

I'm not 100% sure on this one but I think you don't need the for loop calling the constructor. new should construct every object in the array separately.


Based on personal experience as well as this blog post, I'd recommend that you use an unordered list ul versus div and p, because it's a more accurate representation of the actual content you're marking up (semantic markup).

Here's a modified (div replaced with nav) snippet of the HTML from the article I linked to above:

Home

Tutorials

About

Newsletter

Contact

For the CSS to create a horizontal list, you could either use display: inline-block; or float: left; on the li items. If you need to support older browsers, like IE7, then you'll most likely want to use float. For more information on how to decide which technique to use, I'd take a look at this Stack Overflow question.


It detects a cycle very nicely. However, I've got a few remarks:

Personally I would rename your heads to slowHead and fastHead. The expression slowHead == fastHead makes more sense then.

Your else block will always return false though. So you can get rid of that and replace it with return false. If you do that, the return false after the while loop can be removed as well.


Implementation of the binary search algorithm

Variable names

The name x is a very bad name in this case. You should change it to found or something. Even better instead of

x = true;
break;

just do:

return true;

and change the last: return x; to return true;. It is always good to eliminate variables if you can.

Don't modify parameters/arguments

It is confusing when you change the value of the input parameters for example with n = n/2;. This makes the code hard to follow. Instead choose mid as mid = min + (max - min + 1)/2. This makes your intent much clearer.

Avoid while(true) when possible

Some times it is impossible to avoid an infinite loop such as while(true) this is not the case. You should avoid formulating infinite loops like this because it makes it harder to analyze the termination condition of the loop to verify that it will terminate.

while(true)

should be:

while(max - min > 0 )

Simplify branches by realising invariants

Realize that mid is always defined by the min and max variables hence we can define it inside of the loop as a temporary. By doing so and keeping in mind that the array is sorted we can simplify the code as follows:

bool search(int value, int values[], int n) {
  int *min = values;
  int *max = min + n; // Max is exclusive

  while (max - min > 1) {
    int* mid = min + (max - min)/2;
    if(value < *mid){
        max = mid; // Max still exclusive as value < *mid
    }
    else if( value > *mid){
        min = mid;
    }
    else{ // Its not smaller and not larger. Must be equal.
        return true;
    }
  }
  return *min == value;
}


With this solution there is a danger that somebody accidentally change MyApplication.current to null or an invalid reference.

I'd override the getApplication method in the MyActivity class with a covariant return type:

@Override
public MyApplication getApplication() {
    return (MyApplication) super.getApplication();
}

According to the Code Conventions for the Java Programming Language, Current should be current.


Here are my observations

NOTE I did all this via stream-of-conscientiousness and I haven't tested any of these changes (or your original code) so take these as guidance and not exact changes :)

router.php

<?php
class Router
{
    // TODO You need to use `private` a lot more for encapsulation
    private $routeMaps = [];

    // TODO This function needs to document the expected format of inputs
    // TODO is initial controller format supposed to be 'full:class:path:method' ?
    public function add($name, $pattern, $controller, array $params = [])
    {
        // TODO What if it is already set?
        if(!isset($this->routeMaps[$name]))
        {
            $this->routeMaps[$name] =
            [
            'pattern'    => $pattern,
            'controller' => $controller,
            'params'     => $params,
            // Build the regex now so we ensure we only build it once
            'regex'      => $this->buildRegex($pattern, $params),
            ];
        }
        else
        {
            throw new Exception("Route '{$name}' already defined");
        }
    }

    // TODO Document function

# why the '$route = null'?  It is not used
#?? public function run($uri, array $route = null)
    public function run($uri)
    {
        $routeMap = $this->findMatch($uri);
#       Utils::var_dump($routeMap);
        // TODO check to see if we actually found a match
        if (null !== $routeMap)
        {
            // TODO we should probably parse the parms before calling dispatch
            $this->dispatch($routeMap, $uri);
        }
        // TODO probably want to notify user somehow
        else
        {
            ; // ??
        }
    }

    // TODO Why are you calling this parm $uri instead of $pattern?
    private function buildRegex($uri, array $params)
    {
        // FInd {params} in URI
        if(preg_match_all('/\{(?:[^\}]+)\}/', $uri, $matches, PREG_SET_ORDER))
        {
            foreach($matches as $isMatch)
            {
                // Swap {param} with a placeholder
# matching $uri and setting $this->uri means only the last match is saved
# Is that what you want?  If so, document it
#??             $this->uri = str_replace($isMatch, "%s", $uri);
                $uri = str_replace($isMatch, "%s", $uri);
            }
            // Build final Regex
            $finalRegex = '/^' . preg_quote($this->uri, '/') . '$/';
            $finalRegex = vsprintf($finalRegex, $params);

            return $finalRegex;
        }
        // TODO Need to throw error if uri doesn't match
        else
        {
            throw new Exception("Invalid uri: '{$uri}'");
        }

    }

    // TODO Why does (did) this return an array of one element, containing just the
    //      controller?
    // TODO Shouldn't this return the routemap instead of just the controller?
    private function findMatch($url)
    {
        foreach($this->routeMaps as $routeMap)
        {
            // Let's test the route.
            if(preg_match($routeMap['regex'], $url))
            {
                return $routeMap;
            }
        }

        return null; // TODO We should return something if no match
    }

    // TODO This should take the already parsed $parms
    private function dispatch($routeMap, $url)
    {
        $parts = explode(':', $routeMap['controller']);
        $action = array_pop($parts);
        $clazz = implode('\\', $parts);
        $params = $this->parseParams($url);
        call_user_func_array([new $clazz, $action], $params);
    }

    // TODO This needs to be based on the pattern in the rout map
    // TODO Since it appears that the 'params' in the route map have to
    //      match in order for the url to match, we should propably use
    //      the length of those in our parsing here.
    // TODO Perhaps we could even use the regex to tell these values at
    //      match time?
    private function parseParams($url)
    {
        return  array_slice(explode('/', $url), 4);
    }

}


Your code fails if you pass an empty vector because in this case array.end()-1 is incorrect
Keep const correctness, key should be const too
You have kind of strange code formatting, you should rather create an indent after every opening bracket, and not keep function body on a same level
Consider imitating STL approach and returning iterator instead of std::pair
You limit yourself to std::vector<int> type. Read about templates and try to make code that accept different types as well, for example std::vector<double>.
Calling std::vector an array is confusing, note that there's also std::array in C++11 and C-style arrays. vec would be better name there.
Size of std::vector<int> is not actually std::size_t but std::vector<int>::size_type


TODO throw documentation

Throw documentation TODO? E. g. here:

/// \throw TODO

this pointer

Usage of this as in here is unnecessary.

this->Read(buffer, buffersize);

Calling the method without it is more common.

Read(buffer, buffersize);

endiannes

Endianness systemendianness = General::GetEndianness();

I would speculate that system endianness is not going to change during runtime.

Therefore I would probably use "more constant" representation something like

static const variable
template parameter
maybe even MACRO

read & swap

It doesn't look quite efficient to always read memory and swap if endiannesses don't match. What about having alternative version of Read() method already reversing the order during read?


All in all, this looks okay to me, proper naming, nothing bizarre, ( no commenting ).

The only thing that bothers me is that you call .setId(id); on the editView.

editView should have a data model with 1 person, and the .setId() should be called on that data model ( perhaps your function setId() does exactly that ? )

(Deleted race conditions, it not relevant)


Comments
This is not really C++.
It is just some C code.
Code Review
Everything @matsjoyce said:

Don't need 'head'
Always use '{}' around sub block statements.

Naming conventions
In C++ it is common convention that names of objects (anything that can have its address taken) begins with a lower case letter (this includes function and method names). So I would rename Remove to remove. This is so it is easier to spot the names of user defined types (which should begin with an upper case letters).
Design
Encapsulation is your friend.
A free function to delete elements from a list is the wrong way to go. You should have created a list class that contains nodes. Then add a member function to delete the node.
Query
By the way, why a singly linked list? That sounds like premature optimization to me. Code is much simpler using a doubly linked list (with a sentinel). Of course you are writing in C so you are probably trying to write optimal code down as close to the metal with no help from language semantics.
Without double indirection
Double indirection is horrible. It is hard to read and hard to use in the code. If you want to pass something that needs to be updated pass a reference to the object. Then it will be updated in the function.
A simple technique for traversing a singly linked list is to use two pointers. A pointer to the current element and a pointer to the previous element. Unlinking the element then becomes a simple assignment to the previous element.
class SinleLinkedList
{
    public:
        void remove(int value)
        {
            remove(head, value);
        }
    private:
        Node*     head;
        void remove(Node*& ptr, int value)
        {
            Node*   prev    = NULL
            Node*   current = ptr;

            while(current && current->data != value)
            {
                prev    = current;
                current = prev->next;
            }

            // If current is not NULL then we fell out of the
            // above loop because the != failed so it must be equal
            if (current /*&& current->data == value*/ )
            {
                // Set the value we are going to update after delete.
                // If prev == NULL its the head, otherwise we update
                // next pointer from the prev element.
                Node*&  result = (prev == nullptr) ? ptr : prev->next;

                // Save the next value.
                // Delete the old node and update.
                Node* next = current->next;
                delete current;
                result = next;
            }
        }
};


Converting duplicate JS code into a higher order function

From a short review;

Why hardcode the batch length to 500 ?
Why not have the batch length be a nice constant ?
You have even hard coded the length in the function name, which is really unfortunate
batchNumber++ is more canonical than batchNumber += 1
I would have gone for maxIndex = Math.min(startingIndex + 500, dataArray.length); because now you have a lot of calls to func with undefined as a document value
await requires runFunctionInBatchesOf500 to be async (it is missing now)
I would use Array.prototype.slice() to create batches as an array, and then use forEach on each slice/batch
const doc = getDocFromPath(key); <- where does key come from, an evil global?

I personally would be mildly evil by adjusting the Array prototype so that I can keep chaining, FP style;
Array.prototype.mapSlice = function arrrayMapSlice(n){
  //Just return `this` if we get a non-sensical parameter
  if(isNaN(n) || n <= 0){
    return this;
  }
  let start = 0, out = [];
  while(start < this.length){
    out.push(this.slice(start, start+=n));
  }
  return out;
}

async function runBatches(list, f, batchSize){
   batchSize = batchSize || 500;
   list.mapSlice(batchSize).forEach(batch => {
     const firestoreBatch = this.firestore.batch();
     batch.forEach(document => f(document, firestoreBatch ));
   });
   await batch.commit();
}


Too many indirections:

activate just calls addLevel
addLevel just adds a level

And, at least in the posted code, these functions are not used anywhere else.
Is there a merit in having these functions?
You could remove these functions and replace with the simple code that adds one level.

These local variables are just noise in the code:

var level = this;

Inside a Level class, if you use this it's perfectly understandable that you're working with a "level", no need for the extra local variable that just makes your code longer for no apparent benefit.

The name deep might be better as depth.


smallest number divisible by all numbers from 1 to 20? Project Euler question 5

The most optimal solution would be to calculate the LCM of 1 to 20 directly using the standard Euclidean algorithm.

// calculate GCD using Euclidean algorithm
public long GCD(long a, long b) {
    if (b == 0)
        return a;
    else
        return GCD(b, a % b);
}

// calculate LCM using simple formula based on GCD
public long LCM(long a, long b) {
    var gcd = GCD(a, b);
    return a * b / gcd;
}

// iteratively calculate LCM of 1 through 20
public static void Main(string args[]) {
    long result = 1;

    // loop through each value 1 to 20, and LCM with previous result
    for (long n = 2; n <= 20; n++) {
        result = LCM(result, n);
    }

    // print out the result
    Console.WriteLine(result);
}

In terms of complexity, this algorithm is roughly O(n) for small n.


Returning an IEnumerable using Linq-to-SQL which is then bound to a GridView

First, the fact that your methods are static, and accessing what appears to be a static, disposable field, scares me: your application quite possibly has structural problems much more important than a slow query - but you haven't included nearly enough code for us to review that aspect.

All I can say, is that db instances should be as short-lived as possible, and properly disposed once you're done with them; you might want to look into patterns like Repository and Unit-of-Work, to wrap up your LINQ-to-SQL dependencies.

As you may or may not know, LINQ-to-SQL queries don't hit the database immediately; deferred execution makes the provider translate your expressions into proper SQL when the results are iterated... which means... your UI is actually what's triggering query execution.

Let's see...

var pingresult = from p in db.GetTable<tblTBHealthPing>()
                 group p by p.ComputerAsset into g
                 select g.OrderByDescending(t => t.HealthPingTime).FirstOrDefault();

I had to read twice and think more than I should have done so, to parse exactly what's going on here and make sure I was reading it right - the FirstOrDefault applies to each grouping, right?

Sometimes method notation is easier to read:

var pingResult = db.GetTable<tblTBHealthPing>()
                   .GroupBy(p => p.ComputerAsset)
                   .Select(g => g.OrderByDescending(t => t.HealthPingTime)
                                 .FirstOrDefault());

If I read this correctly (did I?), pingResult is an IGrouping<tblTBHealthPing> where each group contains the greatest HealthPingTime, and each group represents a ComputerAsset.

I would materialize this query immediately, into a dictionary:

var pingResults = db.GetTable<tblTBHealthPing>()
                    .GroupBy(ping => ping.ComputerAsset)
                    .AsEnumerable()
                    .ToDictionary(
                        grouping => grouping.Key,
                        grouping => grouping.OrderByDescending(t => t.HealthPingTime)
                                            .FirstOrDefault());

I'd do the same for the other one:

var healthResults = db.GetTable<tblTBHealthHeartbeat>()
                      .GroupBy(beat => beat.ComputerAsset)
                      .AsEnumerable()
                      .ToDictionary(
                          grouping => grouping.Key,
                          grouping => grouping.OrderByDescending(t => t.HealthHeartbeatTime)
                                              .FirstOrDefault());

Now you have two materialized dictionaries, and you're armed for \$O(1)\$ lookups that you don't need to query anymore - I believe your code makes a bunch of \$O(n)\$ lookups for every single row.

var query = db.GetTable<tblTrackingBoardPC>()
              .Where(t => t.TrackingGroup == groupName)
              .ToList()
              .Select(t => CreateTrackingComputerItem(t, pingResults, healthResults)
              .OrderBy(t => t.Pingable);

Keep things clean, make a separate function for the messy projection:

private TrackingComputer CreateTrackingComputerItem(
    tblTrackingBoardPC row,
    IDictionary<string,tblTBHealthPing> pingResults,
    IDictionary<string,tblTBHealthHeartbeat> healthResults)
{
    tblTBHealthPing pingResult = null;
    pingResults.TryGetValue(row.ComputerAsset, out pingResult);

    tblTBHealthHeartbeat healthResult = null;
     healthResults.TryGetValue(row.ComputerAsset, out healthResult);

    return new TrackingComputer
        {
            ComputerName = row.ComputerAsset,
            IPAddress = row.ComputerIP,
            Location = row.Location,
            Pingable = pingResult != null
                ? pingResult.HealthPingResult
                : false,
            PingTime = pingResult != null
                ? pingResult.HealthPingTime
                : DateTime.Now.AddDays(-100),
            Username = healthResult != null
                ? healthResult.HealthCurrentUser
                : null,
            CurrentWindow = healthResult != null
                ? healthResult.HealthCurrentWindow
                : null,
            Uptime = healthResult != null
                ? healthResult.HealthUptime
                : null
        };
}

Calling ToList will materialize the query - yes, server-side sorting is generally faster, but you have complex projections going on here, and it's not because LINQ-to-SQL can do it all SQL-side that it should.

With SQL doing the filtering, and LINQ-to-Objects doing the complex projection, IMO you're getting the best of both worlds, and you're returning materialized query results to your UI.

That said - avoid exposing IQueryable<T> (and unmaterialized queries in general) outside your data access code. The reason is deferred execution: because the query didn't run yet, your client code is "free" to extend the query and potentially add things that the LINQ provider can't translate into SQL, resulting in unexpected exceptions


While your performance limits may be satisfied by producing your results as they are available, there are also other issues in your code which you should consider altering.

First up, 1-liner solutions are convenient for saving some typing, but often make compromises that affect other aspects of your code. In your case, the 1-liner for reversing the number:

  num.to_s.reverse.to_i

That line takes a number, converts it to a string, and then reverses the string, and then converts the string back to a number.

Note that in each conversion, you need to convert between base-2 and base-10 number systems, and that you need to allocate space for the String, etc. While the following takes more code, it actually does less work:

def reverse_num(num)
  rev = 0
  while num > 0 do
    rev *= 10
    rev += num % 10
    num /= 10
  end
  rev
end

There are no strings in the above, the loop iterates one time for each decimal digit, and well, just works.

A second issue I want to point out is with your line-by-line algorithm. You read an entire line, split on the spaces, and from the list of strings, you create a list of numbers with to_i. You then iterate this list, and sum the reverses.

A much neater solution is to do a map->reduce operation:

sum = input_str.split(' ').map{ |n| reverse_num(n.to_i) }.reduce(:+)

Then you can eliminate the entire rev_add method. The end result is:

cases = gets.chomp.to_i

def valid_numeric_input?(input)
  input.zero?
end

def reverse_num(num)
  rev = 0
  while num > 0 do
    rev *= 10
    rev += num % 10
    num /= 10
  end
  rev
end

valid_numeric_input?(cases)

cases.times do |index|
  input_str = gets.chomp
  sum = input_str.split(' ').map{ |n| reverse_num(n.to_i) }.reduce(:+)
  puts reverse_num(sum)
end


1)

    if (CompareDelegate == null || motorcycle2 == null)
    {
        throw new ArgumentNullException();
    }

This exception is misleading. First, it does not specify which parameter is null. Second, strictly speaking CompareDelegate is not a parameter.

2) I would set the default value for CompareDefault:

public Comparison<Motorcycle> CompareDefault { get; set; } =
    other => Name.CompareTo(other.Name);

this way you can probably remove some of the null checks and simplify CompareTo implementation.

3) Overall, I don't like this approach.

it scales poorly.
it hides comparison logic: there is no way to learn how two objects are going to be compared just by reading the code, the comparison logic is hidden inside some delegate.
most importantly, you break asymmetric property of comparison. If a.CompareTo(b) > 0 then I expect that b.CompareTo(a) < 0. But it is not the case, since nothing in your code prevents two objects from using different delegates for comparison. This alone looks like a huge source of problems to me.

IMHO, just write a bunch of regular IComparer<T> implementations and be done with it. It has none of the problems I mentioned above:

//custom comparers are implemented as stand alone classes,
//they are not part of Motorcycle class.
public class Motorcycle
{
    public string Name { get; }
    public int Speed { get; set; }
    public int Price { get; set; }

    public Motorcycle(string name, int price, int speed)
    {
        Name = name;
        Price = price;
        Speed = speed;
    }
}

//It also guarantees asymmetry:
//if SpeedComparer.Compare(a,b) < 0 then SpeedComparer.Compare(b,a) > 0 is also true
class SpeedComparer : IComparer<Motorcycle>
{
    public int Compare(Motorcycle first, Motorcycle second)
    {
        //add null checks

        return first.Price.CompareTo(second.Price);
    }
}

class NameComparer : IComparer<Motorcycle>
{
    public int Compare(Motorcycle first, Motorcycle second)
    {
        //add null checks

        return first.Name.CompareTo(other.Name);
    }
}

Usage:

public void Test()
{
    var motorcycle1 = new Motorcycle("harley", 1000, 120);
    var motorcycle2 = new Motorcycle("yamaha", 1900, 130);
    var motorcycle3 = new Motorcycle("susuki", 1800, 150);
    var motorcycles = new List<Motorcycle>() { motorcycle1, motorcycle2, motorcycle3 };

    IComparer<Motorcycle> selectedComparer = new NameComparer();
    //compares by name
    TestComparison();

    selectedComparer = new SpeedComparer();
    //selectedComparer is changed, so now speeds are compared
    TestComparison();

    void TestComparison()
    {
        Debug.WriteLine($"Using {selectedComparer.GetType().Name}...");
        Debug.WriteLine(selectedComparer.Compare(motorcycle1, motorcycle2));
        motorcycles.Sort(selectedComparer);
        motorcycles.ForEach(m => Debug.WriteLine($"name {m.Name}   price {m.Price}   speed {m.Speed}"));
    }
}


This is not OOP.

Observe how your class contains only static functions.  There are no class properties.  This can be written equivalently:

namespace Router;

function getPath($uri = null){
    // Same implementation (I have just cut it out for readability).
}

function getQuery($uri = null){
    // Same implementation.
}

function follow($uri = null){
    // Same implementation.
}

Usage from anywhere can be compared (First your code):

Router::getPath($uri);
Router::getQuery($uri);
Router::follow($uri);

Then the equivalent:

Router\getPath($uri);
Router\getQuery($uri);
Router\follow($uri);

Note how no object is required to be used (that is a good hint that its not OO).

The following question would be worth reading:

User class design

I have an answer to that question which covers in more detail some of the problems with using static in OOP.


Inheritance and forcing methods to be called inside another method

You could achieve that like this:

class Parser:
    def __init__(self):
        self.parse = self._validated_parsing(self.parse)

    def parse(self, text):
        raise NotImplementedError

    def pre_validate(self, text):
        raise NotImplementedError

    def post_validate(self, text):
        raise NotImplementedError

    def _validated_parsing(self, parse_func):
        def parse_wrapper(text):
            self.pre_validate(text)
            parse_func(text)
            self.post_validate(text)
        return parse_wrapper

class ParserChild(Parser):
    def parse(self, text):
        print('parsing')

    def pre_validate(self, text):
        print('pre-validating')

    def post_validate(self, text):
        print('post-validating')

ParserChild().parse('spam')
# pre-validating
# parsing
# post-validating

I recommend doing it with an extra method that is called from parse though, like the _parse method you wrote.  It should not be called directly from outside, so it should be written with a leading underscore.  You might want to want to call it something more explicit, such as (in lack of a better name) _core_parse.

While we're at it, maybe pre_validate and post_validate should be preceded with an underscore too (depending on whether you want them to be called from outside the class).

Instead of raising NotImplementedError in the base class, you should use abc.ABCMeta for an abstract base class.  This is better for two reasons:

You can't create a subclass that doesn't implement all abstract methods.
It will work together properly with the super function which delegates calls to superclasses (base classes).

So, I think I would implement the class like this:

import abc

class Parser(object):
    __metaclass__ = abc.ABCMeta

    def parse(self, text):
        self._pre_validate(text)
        self._core_parse(text)
        self._post_validate(text)

    @abc.abstractmethod
    def _pre_validate(self, text):
        pass

    @abc.abstractmethod
    def _core_parse(self, text):
        pass

    @abc.abstractmethod
    def _post_validate(self, text):
        pass

class ParserChild(Parser):
    def _core_parse(self, text):
        print('parsing')

    def _pre_validate(self, text):
        print('pre-validating')

    def _post_validate(self, text):
        print('post-validating')

ParserChild().parse('spamspam')
# pre-validating
# parsing
# post-validating

(I'm assuming you use Python 3, but if you're using Python 2, you should let Parser inherit from object. In Python 3, this happens automatically.)


Detecting a cycle in a linked list using Java

The method should be public.

Testing for the current.next != null condition is unnecessary. Also, consider writing the loop as a for loop for clarity:

for (Node current = head; current != null; current = current.next) {
    …
}

You don't need to call seen.contains(), because seen.add() will return false if the item you are adding is already in the set.


Remove list of files from another list of files by their name

Groovy is weakly typed, so you could save a some cruft using def for local variables. Typing can give nice hints (great on an API), but it can also be ignored, leading to code lies and confusion. Final is also a pretty pointless keyword in Groovy.

There's also a shortcut to collecting properties: the spread operator *, which allows you to do removalFiles*.name. It's also more groovy to cast to a set with as Set.

If you really need to do an in-place change, what you want to do is collect all the file objects from the files collection that you want to remove in order to remove them. This way, you are removing using the exact same object:

void removeByNameInPlace(def files, def removalFiles) {
    def removalNames = removalFiles*.name as Set
    files.removeAll( files.findAll { removalNames.contains(it.name) } )
}

However this isn't very groovy and it's typical to return modified copies of Collections instead. This makes your code pretty close to ideal, functionally speaking. With some stylistic changes to your original code:

List<File> removeByName(List<File> files, List<File> removalFiles) {
    def removalNames = removalFiles*.name as Set
    files.findAll { ! removalNames.contains(it.name) }
}


Layout

Put your main method on the top, since it tells main purpose of the application. And, C# isn't like C++, you don't have to define the method ahead, before calling them.

class Program
{
    uint bitSize, shiftCount, mask, partionSize;

    static void Main(string[] args);

    void setValue(ref uint var, uint k, uint i, uint val);
    uint getValue(uint var, uint k, uint i);
}

 // Even in c++, you can declare a method signature first
 // This part could also go into header file
 void setValue(PUINT var, UINT k, UINT i, UINT val);
 uint getValue(UINT var, UINT k, UINT i);

 int main(int argc, char *argv[]) { /* ... */ }

 // And, implement them later
 void setValue(PUINT var, UINT k, UINT i, UINT val) { /*...*/ }
 uint getValue(UINT var, UINT k, UINT i) { /*...*/ }

Mark the class variables and methods static, so you can call them directly.

// Instead of awkward hack/patch like this
Program p = new Program();
p.setValue(...);

Declare the local variables as you need them. Except when the assignment is inside a code block, but you also need to use them outside of that.

Naming

PascalCasing for any method, class, public property. And, camelCasing for private and local variable.
Avoid using keywords as variable name, especially var the most used one.
Avoid single letter variable, other than for for loop, lambda expression...

Misc

Avoid magic numbers.

// What is 8? numbers of bits in a byte
//var maxValue = (uint)((1 << (int)(sizeof(uint) * 8 / k)) - 1);

const uint BitsPerByte = 8;

//maxValue = 2147483647;
maxValue = int.MaxValue;

You messed up big here...

A uint should be capable to store uint.MaxValue and not int.MaxValue.
You are mixing up partition size and partition count. With a partition size of 1 (k = 1), you should be able to enter 32 values (BitSize / k = 32 / 1).

// And, not just 1 (`k`) value
for(uint i = 0; i < k; i++)

The hard coded conditions k == 1 and getValue are huge red flags!

//  why?
if(k == 1)
{
    maxValue = 2147483647;
}
Console.WriteLine("Maximal Value for Partion of Size {0} is 0 to {1}", k, maxValue);

// hack..
bool getValue = true;
for(uint i = 0; i < k; i++)
{
    Console.WriteLine("Input a Value");
    value = Convert.ToUInt32(Console.ReadLine());

    // more hack
    if (k == 1)
    {
        Console.WriteLine("Value at Index 0 is: {0}", value);
        getValue = false;
    }
    else
    {
        p.setValue(ref var, k, i, value);
    }
}

for(uint i = 0; i < k; i++)
{
    // hack++
    if (getValue)
    {
        value = p.getValue(var, k, i);
            Console.WriteLine("Value At Index {0} is: {1}", i, value);
    }
}

Let's fix this...

class Program
{
    const int BitsPerByte = 8, BitSize = sizeof(uint) * BitsPerByte;

    static void Main(string[] args)
    {
        Console.WriteLine("C++ Lab to C#, Practice Using Pass by Ref");

        Console.WriteLine("Valid Partition K size are: 1, 2, 4, 8, 16, 32.");
        Console.WriteLine("Enter Partition Size :");
        var size = int.Parse(Console.ReadLine());

        // using 1L (long) for computation to avoid overflow
        var maxValue = (uint)((1L <<  size) - 1);
        Console.WriteLine("A valid value for a Partion of Size {0} is between 0 and {1}.", size, maxValue);

        var data = default(uint);
        for (var i = 0; i < BitSize / size; i++)
        {
            Console.WriteLine("Input a Value :");
            var value = uint.Parse(Console.ReadLine());

            SetValue(ref data, size, i, value);
        }

        for (var i = 0; i < BitSize / size; i++)
        {
            Console.WriteLine("Value At Index {0} is {1}", i, GetValue(data, size, i));
        }
    }

    static void SetValue(ref uint data, int size, int index, uint value)
    {
        data |= value << (size * index);
    }
    static uint GetValue(uint data, int size, int index)
    {
        var mask = (uint)((1L << size) - 1);

        return data >> size * index & mask;
    }
}

EDIT: Explanation on the bit operation :

static void SetValue(ref uint data, int size, int index, uint value)
{
    /*  :: Given that size = 8 and index = 2 (3rd), value = 10000001, data = 10101010 00000000 00000000 00000000
        00000000 00000000 00000000 10000001 // value
        00000000 10000001 00000000 00000000 // value left-shifted by 16 (size * index)

        00000000 10000001 00000000 00000000 // value left-shifted by 16 (size * index)
        10101010 00000000 00000000 00000000 // data
        ----------------------------------- // OR
        10101010 10000001 00000000 00000000 // result */
    data |= value << (size * index);
}
static uint GetValue(uint data, int size, int index)
{
    var mask = (uint)((1L << size) - 1);
    /*  :: Given that size = 8 and index = 2 (3rd), value = 0b10000001, data = 10101010 10000001 00000000 00000000
        00000000 00000000 00000001 00000000 // (1L << size)
        00000000 00000000 00000000 11111111 // (1L << size) - 1 -> mask

        10101010 10000001 00000000 00000000 // data
        00000000 00000000 10101010 10000001 // data right-shifted by 16 (size * index)

        00000000 00000000 10101010 10000001 // data right-shifted by 16 (size * index)
        00000000 00000000 00000000 11111111 // mask
        ----------------------------------- // AND
        00000000 00000000 00000000 10000001 // result */
    return data >> size * index & mask;
}


Extending basic differentiator to handle more kinds of expressions

Your definitions are correct except for one minor detail.  The cond clause:

((= m2 1) m1)

should be:

((=number? m2 1) m1)

since one needs to test first whether m2 is a number.

Stylistically, I would prefer to define base and exponent as:

(define base cadr)
(define exponent caddr)

although there is certainly nothing wrong with your definitions.


Efficient date-based lookup function in R

Have a look at the function findInterval. It is vectorized so it can treat all your dates in a single (fast) call. Your code should look something like this:

eastern.profile <- function(birthday) {
   bad <- !is.na.POSIXlt(birthday)
   birthday[bad] <- strptime(birthday[bad], format = "%Y-%m-%d", tz = "Asia/Chongqing")
   ind <- findInterval(birthday, lunarCal$START_DATE)
   cbind(birthday = birthday, lunarCal[ind, ])
}

Note that I was not able to test because of some issues I had with your data. So it may need some tweaks.


Your implementation is as efficient as it can be in python. Because python is an interpreted language, every statement that is executed takes a long time compared to something like c.

At the bottom of this answer is an altered version of your code that times 1000 evaluations of both of the functions. It also records the total amount of time spent evaluating the first three lines of the binary algorithm.

Below is the output of the code:

Euler:             0.0010025501251220703
Binary1:           0.2012491226196289
First three lines: 0.04787778854370117

The amount of time spent checking for a==b, a==0, and b==0 takes longer than the entire Euler algorithm. It should be noted that the binary algorithm is only supposed to be faster when dealing with "regular" arithmetic. From the Wikipedia page on the binary gcd algorithm:

"For arbitrary-precision arithmetic, neither the Euclidean algorithm nor the binary GCD algorithm are fastest, as they both take time that is a quadratic function of the number of input digits."

first_three_lines = 0

def gcd_euclid_recursive(a, b):
    if b == 0: return a
    return gcd_euclid_recursive(b, a % b)

def gcd_binary_recursive(a, b):
    global first_three_lines
    t = time()
    if a == b: return a
    if a == 0: return b
    if b == 0: return a
    first_three_lines += time() - t

    if a & 1 == 0: # a is even
        if b & 1 == 1: # b is odd
            return gcd_binary_recursive(a >> 1, b)
        else: # both a and b are even
            return gcd_binary_recursive(a >> 1, b >> 1) << 1

    if b & 1 == 0: # a is odd and b is even
        return gcd_binary_recursive(a, b >> 1)

    if (a > b):
        return gcd_binary_recursive((a-b) >> 1, b)
    return gcd_binary_recursive((b-a) >> 1, a)

a = 5**100 - 1
b = 5**120 - 1

from time import time
euler_time = 0
for i in range(1000):
    t = time()
    x = gcd_euclid_recursive(a,b)
    euler_time += time() - t

bin_time = 0
for i in range(1000):
    t = time()
    x = gcd_binary_recursive(a,b)
    bin_time += time() - t

print("Euler:            ",euler_time)
print("Binary1:          ",bin_time)
print("First three lines:",first_three_lines)
```


Clever way to build a extension method that ordenate my IQueryable?

You definitely could use DynamicLinq to solve this problem.  See Scott Guthries blog post about it at:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx


Python 3: Why is my prime sieve so slow?

while True:
        for i, prime in enumerate(is_prime):
            if prime and i > p:
                p = i
                break
        else:
            break

This is the cause of the slowness: track the state between loops and the 25 seconds drop to 0.05 seconds.

        multiple = p + p

        while multiple <= n:
            is_prime[multiple]= False
            multiple = multiple + p

It's probably more Pythonic to use range here:

        for multiple in range(p + p, n + 1, p):
            is_prime[multiple] = False

When handling larger inputs, it becomes worthwhile starting at p * p instead of p + p (on the basis that every composite multiple of p smaller than p * p also has a smaller prime factor).

    r = []
    for i, prime in enumerate(is_prime):
        if prime: r.append(i)
    return r

IMO it makes more sense to inline this into the main loop.

Edited code at this point:

def sieve_of_eratosthenes(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False

    primes = []

    for p in range(2, n+1):
        if is_prime[p]:
            primes.append(p)

            for multiple in range(p * p, n + 1, p):
                is_prime[multiple] = False

    return primes

Now if you want more speed at the cost of complicating things ever so slightly, you can apply a simple wheel by special-casing the only even prime:

def sieve_of_eratosthenes(n):
    is_prime = [True] * (n+1)
    primes = [2]

    for p in range(3, n + 1, 2):
        if is_prime[p]:
            primes.append(p)

            for multiple in range(p * p, n + 1, p + p):
                is_prime[multiple] = False

    return primes


Improvement for std::map  double dispatch

In general your code looks good. But I have some little annotations (improvements) for you.

1. I'd prefer direct initialization of itr for sake of readability:

myMapType::const_iterator itr = myMap.find(2);

instead of

myMapType::const_iterator itr;
itr = myMap.find(2);

That said you could also avoid

typedef std::map<int, runFunc> myMapType;

completely using the auto keyword:

auto itr = myMap.find(2);

2. Make use std::function and lambda bindings

For the callable value parameter of the std::map I'd prefer to use an appropriate std::function value type and lambda function bindings to the instance to operate on.

testClass t1;

std::map<int, std::function<void()>> myMap;
myMap.emplace(1, [&t1](){t1.testFunc1();});
myMap.emplace(2, [&t1](){t1.testFunc2();});

This will give you greater flexibility for later changes and use of other classes than just testClass. Also you can get rid of that other type definition then:

typedef void(testClass::*runFunc)(void);

As soon you want to use your map for the general case you can clearly see the benefits:

class A {
public:
     void print() { std::cout << "print() from class A.\n"; }
};

class B {
public:
     void print() { std::cout << "print() from class B.\n"; }
};

// ...
int main() {
    A a;
    B b;

    std::map<int, std::function<void()>> myMap;
    myMap.emplace(1, [&a](){a.print();});
    myMap.emplace(2, [&b](){b.print();});

}

Here's my set of changes in whole (you can check it's still working as intended here):

#include <map>
#include <string>
#include <iostream>
#include <functional>

class testClass
{
public:
    void testFunc1() { std::cout << "func1\n"; }
    void testFunc2() { std::cout << "func2\n"; }
};

int main() {
    testClass t1;

    std::map<int, std::function<void()>> myMap;
    myMap.emplace(1, [&t1](){t1.testFunc1();});
    myMap.emplace(2, [&t1](){t1.testFunc2();});

    auto itr = myMap.find(2);

    if (itr != myMap.end()) {
        (itr->second)();
    }
}


std::vector of pointers with the rule of three

Is it safe? To a point.
Naming
I hope the name Pointer is just for illustration purposes as otherwise that is a pretty terrible name.
The changes I would make are:
Accepting pointers must indicate ownership.
Your current interface does not indicate that it is taking ownership of the pointers. So as a user of your class I need to dig inside and find out if you are taking ownership or not before I can use it.
void push_back(Pointer * pointer);

I would change the interface to specifically take a unique_ptr that way people know that you are taking ownership of the object.
void push_back(std::unqiue_ptr<Pointer> pointer);

No confusion here.
Storage of pointers.
I have no problem with you storing a vector of pointers or a vector of smart pointer. Either makes sense. As long as you define the Copy Constructor/ Assignment Operator and Destrtuctor if you use pointer (like you have). You could argue that keeping an array of smart pointers will save you some work in coding (tiny (probably insignificant cost1  of managing the data). Alternatively you can use a container specifically designed to hold pointers.
 std::vector<Pointer*>                 data;  // Add Rule of Three.
 std::vector<std::unique_ptr<Pointer>> data;  //
 boost::ptr_vector<Pointer>            data;  // Takes ownership of pointers.
                                              // Only exposes members as references
                                              // to actual object (not pointer) and thus
                                              // makes using it with standard algorithms
                                              // much easier and intuitive.

To Clarify because of comments: I suspect for most compilers the cost of std::unique_ptr will be zero at runtime. But it is something worth validating with your compiler before assuming.
Access from derived types.
Personally I would not give direct access to the vector from derived class like that.
protected:
      std::vector<Pointer *> pointers;

Even if you have a vector of unique_ptr it is still to easy for the derived class to break encapsulation and do something you don't intend. You should provide them with a safer interface. How you do that depends.
If you know none of the members will be NULL then I would provide them with a function that returns a reference.
 protected:
       // Anybody that wants to access the data gets a reference.
       Pointer&    data(std::size_t index) {return *pointers[index];}

       // Note: the above code just uses the original code as a base line.
       //       If you change the storage medium I would probably still
       //       provide this as an interface layer so that I don't
       //       break encapsulation.
       //
       //       Of course there are a lot of caviats that depend on how
       //       this will be used. But without further context this is
       //       the best I can do at the moment.

 private:
       std::vector<Pointer*> pointers;

If you want derived classes to modify the class you may need to think of something else. But you have not provided enough context for me to go further.
Iterator
Based on comments just showing how easy it would be to throw an iterator together that can be used without exposing implementations details. Note: this one is not complete but shows enough of how it would work (and I was slightly bored at the time and wanted to write some code).
class MyIterator
{
    Keeper* parent;
    int     index
    public:
        MyIterator(Keeper& parent, int index)
           : parent(&parent)
           , index(index)
        {}
        MyIterator& operator++()
        {
            ++index;
            return *this;
        }
        MyIterator operator++(int)
        {
            MyIterator result(*this);
            ++(*this);
            return result;
        }
        Pointer& operator*()
        {
            return parent->data(index);
        }
}


Counting pairs of elements in a circular ArrayList containing -1, 0, and 1

The 2nd way is to use the array with unique index calculated from current and next value:

public void test() {

    List<Integer> slopeChanges = new ArrayList<Integer>();
    slopeChanges.add(0);
    slopeChanges.add(0);
    slopeChanges.add(1);
    slopeChanges.add(0);
    slopeChanges.add(1);

    /*
    static final int count_neg10 = 2; // -1 + 3 * (0 + 1);
    static final int count_neg11 = 5; // -1  + 3 * (1 + 1);
    static final int count_10 = 4; // 1 + 3 * (0 + 1);
    static final int count_1neg1 = 1; // 1 + 3 * (-1 + 1);
    static final int count_0neg1 = 0; // 0  + 3 * (-1 + 1);
    static final int count_01 = 6; // 0  + 3 * (1 + 1);*/

    int[] count = {0, 0, 0, 0, 0, 0, 0};
    String[] count_names = {"count_0neg1", "count_1neg1", "count_neg10", "", "count_10", "count_neg11", "count_01"};

    List<Double> sixProbabilites = new ArrayList<Double>();

    for(int i = 0, j = slopeChanges.size() -1; i<slopeChanges.size(); i++) {
      if (slopeChanges.get(i) != slopeChanges.get(j)) {
        count[slopeChanges.get(i) + 3 * (slopeChanges.get(j) + 1) ]++;
      }
      j = i;
    }

    System.out.println(slopeChanges);

    for(int i = 0; i<7; i++) {
      if(count[i] != 0) {
        System.out.println(count_names[i] + " = " + count[i]);
        sixProbabilites.add((double)count[i] / ((double)slopeChanges.size()));
      }
    }
}


Parsing key-value pairs to fill a struct

I like to go data driven, so I can write a single loop for processing. First, let's factor out the three if blocks that are so similar into a helper function:

void fillField(pElemP p, char* match, char* message, float* pf)
{
    if (strcmp(match, p->k)==0)
    {
        printf(message, p->v);
        *pf = atof(p->v);
    }
}
void fillFields(ticP t, pElemP p)
{
    fillField(p, ASK, "ASK %s\n", &t->ask);
    fillField(p, BID, "BID %s\n", &t->bid);
    fillField(p, CLOSE, "CLOSE >>>%s<<<\n", &t->close);
}

Now that we have this split out, we're repeating a lot less code, and have identified what information we'd need in order to make this data driven. I'm not sure going pure data driven is much better in this case, but let's look at one way it might be done:

struct FieldSpec {
    char *match;
    char *message;
    int offset;
};

struct FieldSpec field_specs[] = {
    { ASK, "ASK %s\n", offsetof(tic, ask) },
    { BID, "BID %s\n", offsetof(tic, bid) },
    { CLOSE, "CLOSE >>>%s<<<\n", offsetof(tic, close) },
};

void fillFields(ticP t, pElemP p)
{
    for (int i = 0; i < sizeof(field_specs) / sizeof(*field_specs); ++i)
    {
        fillFieldBySpec(field_specs[i], p, t);
    }
}

I'll leave the implementation of fillFieldBySpec up to you if you want to go this route (feel free to put it inside the for loop instead of its own function). I don't think it helps significantly over the first refactoring, and the gynmastics to use the value from offsetof aren't pretty.


Using 2 threads to compute the nth Fibonacci number (with memoization)

Don't parallelize serial problems

  In theory, I'd expect using 2 threads on a tree-recursive algorithm to work faster than a single-threaded implementation, however it seems this is clearly not the case. What am I missing here?

You are duplicating work.  The problem is that generating the Fibonacci sequence is not a tree.  It's a vector.  This is because you don't actually care what the children are.  All you care about is what the current node's two children are.  But you need one of those children to generate the other.  I.e. the n - 2 subtree is actually part of the n - 1 subtree.

So you take an essentially serial operation and you try to split it over two processes.  Unsurprisingly, it takes longer as it tries to synchronize the processes.

Turning it into parallel problems

Is all hope lost?  No.  If you look at solutions to Project Euler #2:  Even Fibonacci Numbers, you will find that

$$F_n = 4 \cdot F_{n-3} + F_{n-6}$$

For example, the 7th Fibonacci number:

$$F_7 = 4 \cdot F_4 + F_1$$
$$F_7 = 4 \cdot 2 + 0 = 8$$

How does that help us?  Think about the 8th, 9th, and 10th Fibonacci numbers:

$$F_8 = 4 \cdot F_5 + F_2$$
$$F_9 = 4 \cdot F_6 + F_3$$
$$F_{10} = 4 \cdot F_7 + F_4$$

Notice anything?  No overlap.  The 7th and 10th overlap, but 7-9 don't and 8-10 don't.  This will continue.  In general, now you have three serial sequences.  So you can parallel process into three threads.

You may also be able to come up with similar equations for two threads or more than three threads.  But I knew about this problem and there's already the mathematical derivation available inside the link.

Another issue is that you are searching from n down.  You might find it easier to generate the sequences from 1, 2, and 3 up with n as an upper bound.  You can do that iteratively rather than recursively, which should avoid the heavy stack usage.

This will only be faster if the system can really parallelize work.  If you were limited to a single core and can now use three, you gain.  If you're just switching between the three threads on the same processor, it will probably still be slower than the serial solution.

Calculate just one element

If all you want to do is generate the nth Fibonacci number, there is a formula to do that directly:

static int fib(int n) {
    double sqrt_5 = Math.sqrt(5);
    double phi = (1 + sqrt_5) / 2;

    double fib_n = Math.pow(phi, n) / sqrt_5;
    return (int) (fib_n + 0.5);
}

That would be the fastest solution for a single value without precalculating the numbers.  Of course, that won't parallel well.


Finding the number in a list that differs in parity

Well, one way we can do it is by counting the first three elements. If more than one is odd, it means the sequence is odd, and we should look for an even number. If one or less is odd, the sequence is even, and we should look for an odd number.

a1 = "2 4 6 7 8 10"
a2 = "3 5 7 9 10"

def index_of_outlier(string)
  array = string.split(' ').map(&:to_i)
  count_of_odd = (array[0..2]).count { |i| i.odd? }
  if count_of_odd > 1
    array.index { |i| i.even? }
  else
    array.index { |i| i.odd? }
  end
end

puts index_of_outlier(a1) #=> 3
puts index_of_outlier(a2) #=> 4

This looks messy, but it gets the job done quickly. The lower bound is \$3 + 1\$ iterations, and the upper bound is \$3 + n - 1\$. This makes it \$O(n)\$.

You need three iterations to determine the nature of the sequence and up to \$n - 1\$ more to find the solution.

I'm not sure how partition works under the hood, but I assume it traverses the array at least once. This means my solution will perform better if the target index is lower than \$n - 5\$.

If you want the char position in the string and not the array index, just add one to the result (as you are doing in your own solutions).