Sum of nodes at a given depth of a binary tree (String representation)

Most likely you can't improve too much on this approach, as you do need to scan the entire string, and you don't convert any unneeded values. So as I see it there are three things you could try changing, but most likely they either not make a difference, or possibly even increase running time.

Pre-calculate the length of the string – Not quite sure how Java handles this one, but in the end-condition of your for loop you do tree.length(). If this had been a costly function, then some languages would execute this function for each run through the loop, and would benefit from this being done in front of the for loop. The length of your string isn't going to change in this case, so it should be safe to just do it once before the loop.
Not using repeated calls to tree.charAt(i) – In your code, in the worst case, you call tree.charAt(i) 4 times (when calculating the value). This could possibly be done outside the if block just once. However, this function is \$O(1)\$, so the benefit wouldn't be large.
Change the value extraction – Another change which could be made, is to change the way you extract the value. An alternative approach could be that after detecting the opening paranthesis, you could scan the string for the entire value string, and then convert it.

This could be done by preserving the start index of the value string, search until you hit a new parenthesis, and then convert the substring directly into a number. However, this doesn't need to be a faster method.

I've given no code in this answer, but I think you're getting the ideas.

One comment though on chosen algorithm, is that you calculate the value when on the correct depth, but you don't actually use it before you've traversed all child trees and then hit the end parenthesis.This isn't a problem in the current specification, but if it changed to sum up all values on multiple depths, it would fail miserably.

My final comment, is that your code does look clean and tidy with good names. If I'd change anything I would possibly add a little more vertical space, and some comments as to what the method is doing.


Exercise 1-22 from K and R: line folding

Potential Buffer Overflows

You've defined from and to to hold only 10 characters apiece, but none of the code actually enforces that, and it appears that you plan on them holding 80 characters or so. You should probably pass the array size to getline, for example, so that it can stop reading either when it reaches a new-line or when it runs out of space in the destination buffer.

Formatting

Your indentation is inconsistent and in places seems rather excessive.

Variable names

Many of your variable names could use some work. Names like a, b and max (that doesn't seem to hold a maximum) could be replaced with much more meaningful names.

Inefficiency

Depending on your viewpoint, there's a fair argument to be made that your code is less efficient than there's any real need for. In particular, it works by reading data into one buffer, then copying all that data to another buffer.

I'd consider a strategy something on this general order:

Read in a line
If it's shorter than the maximum, print it out and go back to 1
Starting from line[max_width], search backward in the string to find a space.
Change that space to a new-line.
Repeat from 2, using the string following the newline you just inserted.


if ("Summary" in config) and (config["Summary"] is not None):

Can be simplified to:
if config.get("summary") is not None:

args = ["Args:"] + [f"\t{arg}: Function argument" for arg in config["Args"]]
attr = ["Attributes:"] + [f"\t{attr}: Information about parameter {attr}" for attr in config["Attributes"]]
todo = ["Todo:"] + [f"\t{star} {todo}" for todo in config["Todo"]]

Can all be moved into a function.

You always add f"{Name}:",
You always iterate through config[Name], and
You always format the value. Which can be provided as a format string (not an f-string).

def format_values(config, name, fmt):
    return [f"{name}:"] + [fmt.format(value) for value in config[name]]

format_values(config, "Args", "\t{}: Function argument")

docstring.append(config["Summary"])
raises = ["Raises: "] + [f"\t {config.get('Raises')}"]
returns = ["Returns: "] + [f"\t {config.get('Returns')}"]

Can all be moved into a function.

You add f"{Name}: " except for Summary,
You always add config[Name], and
You always format the value. (Summary would be "{}")

def format_value(config, name, fmt, head=True):
    return ([f"{name}: "] if head else []) + [fmt.format(config[name])]

format_value(config, "Summary", "{}", False)

value = config.get('Description')
wrapper=textwrap.TextWrapper(subsequent_indent= '\t', width = 120)
description = ["Description: "] + [f"\t{wrapper.fill(value)}"]
docstring += description

To be able to handle Description we can change format_value (and optionally format_values for consistency) to take a lambda to decide how to display the value.
def format_value(config, name, fmt, head=True):
    return ([f"{name}: "] if head else []) + [fmt(config[name])]

wrapper = textwrap.TextWrapper(subsequent_indent='\t', width=120)
docstring += format_value(config, "Description", lambda value: f"\t{wrapper.fill(value)}")

Lets look at how the code looks now:
import textwrap

def format_value(config, name, fmt, head=True):
    return ([f"{name}: "] if head else []) + [fmt(config[name])]

def format_values(config, name, fmt):
    return [f"{name}:"] + [fmt(value) for value in config[name]]

def gendoc(config):
    docstring = []
    if None is not config.get("Summary"):
        docstring += format_value(config, "Summary", lambda summary: summary, False)
    if None is not config.get("Args"):
        docstring += format_values(config, "Args", lambda arg: f"\t{arg}: Function argument")
    if None is not config.get("Attributes"):
        docstring += format_values(config, "Attributes", lambda attr: f"\t{arg}: Information about parameter {arg}")
    if None is not config.get("Raises"):
        docstring += format_value(config, "Raises", lambda raises: f"\t {raises}")
    if None is not config.get("Returns"):
        docstring += format_value(config, "Returns", lambda returns: f"\t {returns}")
    if None is not config.get("Description"):
        wrapper = textwrap.TextWrapper(subsequent_indent='\t', width=120)
        docstring += format_value(config, "Description", lambda value: f"\t{wrapper.fill(value)}")
    if None is not config.get("Todo"):
        star = "*"
        docstring += format_values(config, "Todo", lambda todo: f"\t{star} {todo}")

    docstring = "\n\n".join(docstring)
    return docstring

if None is not config.get({name}):
    docstring += format_value(config, {name}, ...)

We can see we are duplicating the above pseudocode.
Lets ignore the fmt and head arguments to format_value and format_values.
We could change the code to:
docstring = []
for name, fn in ...:
    if config.get(name) is not None:
        docstring += fn(config, name)

We can change format_value and format_values so we provide the fmt and head.
We then return another function which takes config and name to call in the loop.
def format_value(fmt, head=True):
    def inner(config, name):
        return ([f"{name}: "] if head else []) + [fmt(config[name])]
    return inner

format_value("{}")(config, "Summary")

Next we can define a dictionary to store the result of the first call to format_value and format_values.
And then change the code to iterate over the dictionary.
Final code:
import textwrap

def format_value(fmt, head=True):
    def inner(config, name):
        return ([f"{name}: "] if head else []) + [fmt(config[name])]
    return inner

def format_values(fmt):
    def inner(config, name):
        return [f"{name}:"] + [fmt(value) for value in config[name]]
    return inner

wrapper = textwrap.TextWrapper(subsequent_indent='\t', width=120)
star = "*"

FORMATS = {
    "Summary": format_value(lambda summary: f"{summary}", False),
    "Args": format_values(lambda arg: f"\t{arg}: Function argument"),
    "Attributes": format_values(lambda attr: f"\t{arg}: Information about parameter {arg}"),
    "Raises": format_value(lambda raises: f"\t {raises}"),
    "Returns": format_value(lambda returns: f"\t {returns}"),
    "Description": format_value(lambda value: f"\t{wrapper.fill(value)}"),
    "Todo": format_values(lambda todo: f"\t{star} {todo}"),
}

def gendoc(config):
    docstring = []
    for name, fn in FORMATS.items():
        if config.get(name) is not None:
            docstring += fn(config, name)
    return "\n\n".join(docstring)


Checking whether a number is a Smith number

class check

Java naming convention is that class names should start with an uppercase letter. Check is also not very informative: what does it check?

    static boolean a;

Is this used anywhere?

    static boolean checkprime(long n)

Again, Java naming convention is that (a) camel-case should be used (checkPrime instead of checkprime); (b) Boolean-valued properties should generally have names beginning is (isPrime instead of checkPrime). In this case isPrime reads quite naturally in context (e.g. if (isPrime(n)) ...).

        int i, factors= 0;
        for(i = 1;i<=n ;i++)
        {
            if(n%i==0)
                factors++;
        }
        if(factors == 2)
            return true;
        else
            return false;

Why give i such a wide scope?

Why use factors at all? If you find a divisor which is not 1 or n you can return false immediately.

What's going on with the whitespace in for(i = 1;i<=n ;i++)? The semicolon separates expressions: I can't understand why you'd want whitespace inside the expression i = 1 but not after the semicolon which separates the 1 from i<=n.

There are much faster ways to test primality. Aside from the comments made in another answer about only testing up to sqrt(n), look around for discussion on BPSW or just use BigInteger.isProbablePrime.

    static long sumfinder(long  n)

Again, names. If the name of a method is a noun, I expect it to describe the object returned: but the long returned is not a sum-finder. It's the sum. I suggest that a better name for this method would be digitSum.

    {
        long  sum = 0;
        while(n!=0)
        {
            sum = sum + n%10;
            n= n/10;
        }
        return sum;
    }

I understand this to be at the level of throwaway code rather than production: if it were production code, I'd expect to see either some code to handle the case n < 0 or a comment to explain why that is unnecessary.

    static boolean checksmith(long  n)

See previous comments on names.

Existing answers propose some better ways to write the body of this method; I want to focus as much on general points of style as on algorithms, although I do have one or two points to add there too.

        long  sum = 0;

Which sum? There are two relevant sums, right?

        if(checkprime(n)== true)

== true is a crime against KISS.

            System.out.println(n + " is a prime number ");

That's an unexpected side effect.

            //generate prime factors:

I'm not sure what exactly the scope of this comment is, but I wouldn't describe the following loop as generating prime factors.

            outer:

?? There's no inner loop, so what purpose does this label serve?

            for(long  i = 1; i<= num ; i++)

That should strike terror into the heart of anyone who wants their program to terminate in a reasonable time. There are three possible cases: (a) i could perfectly well be an int; (b) i gets incremented by more than 1 elsewhere; (c) this loop will execute more than \$2^{31}\$ times. Here it's not case (b), so which of the other two is it?

(Aside: the rewrites correctly observe that you only need to go up to sqrt(n), but if n is a long that could still be about \$2^{31.5}\$. It might be worth looking at faster factorisation methods, starting with Pollard's rho).

                if(checkprime(i)== true)
                {
                    if(num%i== 0)

In addition to previous comments, why check whether i is prime? That check is slower than the num % i check, and if the second check succeeds then the first one must also for basic number-theoretic reasons.

                    {
                        sum= sum+ sumfinder(i);

Here you could have an early-abort if the partial digit sum of prime factors already exceeds the digit sum of the original number. That same idea carries over into the suggested rewrites of the method.

        if (sumfinder(n)== sum)

            return true;

        else
            return false;

Those six lines could be simplified to return sumfinder(n) == sum;

    static void display()throws InputMismatchException

Um. If the method is called display, I expect it to do output. Why is it throwing an input-related exception?


SSH autokiller for connections from other systems

Replace magic numbers like 13 there line[:13] with constansts.
IMHO:

rename ids to lines
all_ids to ids
processes to pids


FASM assembly: Write a program which checks if a number is a prime number

Overall your code is very reasonable for somebody learning Assembly, I would say quite nice work.

I can produce something what will look more advanced (I hope), but it's more like tiny details improved here and there, and some of them for the price of worse readability of source.

I mean on the syntax and low level. On the algorithmic level your code can be improved considerably, as Paweł already answered, but he missed another opportunity to halve number of divisions.

My variant of code, showing:

how to use the result of DIV ebx (which has to be done anyway to test remainder) as approximation of suggested sqrt(input) test, for earlier exit.
xor reg,reg used to set zero into register (shorter opcode than mov reg,0 plus modern CPU recognizes it as idiom of "set to zero" and optimizes for it)
test edx,edx to check if remainder is zero (shorter opcode than cmp edx,0 plus modern CPU will recognize it as idiom of "test for zero value" and optimizes for it)
resolving even numbers at the beginning (even numbers have zero in least significant bit: isOdd(n) == (n&1). And the only even number being prime is 2, no need to test other even numbers by DIV.
but that means only odd divisors have to be tested in the loop, because (odd_input % even_divisor) != 0 for sure. So my loop is testing divisors 3, 5, 7, 9, 11, 13, 15, ...
some non-trivial usage of arithmetic instructions and flags to check for input values [0, 1, 2, 3] ahead of loop, as those would break the loop logic and produce invalid result. It may be nice exercise for you to "decipher" how it works.
you should try to keep things "together" (if possible). For example you set up edx:eax for DIV at the end of your loop code block, so it's A) not together with DIV, interleaved by JMP (hard to read for human, no problem for CPU) B) you have code duplicity (mov edx,0), because you have to init the register values ahead of very first DIV separately. => So I do initialize edx:eax right ahead of DIV, only single time in code, and it's easier to read IMO.

format PE console
entry start

include 'win32a.inc'

; ===============================================
section '.text' code readable executable

start:
    call    read_hex
    xor     ecx, ecx    ; return value = 0 (0 = not prime, 1 = prime)
    mov     esi, eax    ; copy provided number in esi
    shr     eax, 1      ; eax = eax div 2, remainder into CF
    jz      finish      ; 0 and 1 are not primes
    adc     ecx,ecx     ; temporarily ecx=1/0 for odd/even input
    dec     eax
    jz      input_was_prime ; 2 and 3 are primes, special test needed
                            ; because they would break loop logic
    jecxz   finish      ; other even numbers (but not 2) are *not* primes

    ; input number was odd and above 3, test odd divisors in generic loop
    mov     ebx,ecx     ; start with divisor 3 (ebx=1, loop will +2 first)
    dec     ecx         ; result = 0 (not prime)
test_divisors_loop:
    add     ebx,2       ; next odd divisor to test
    mov     eax,esi
    xor     edx,edx     ; edx:eax = input number (zero extended to 64b)
    div     ebx         ; eax = quotient, edx = remainder
    test    edx,edx
    jz      finish      ; no prime, when remainder is zero
    cmp     eax,ebx
    ja      test_divisors_loop  ; quotient > divisor -> try next
    ; when quotient <= divisor, it's safe to end loop, esi is prime number
    ; it's basically cheap "sqrt" end condition, reusing DIV result
input_was_prime:
    mov     cl,1        ; result = 1 (is prime) (ecx was 0 or 1 before)
finish:
    mov     eax, ecx    ; result was in ecx, print it
    call    print_eax

    push    0
    call    [ExitProcess]

include 'training.inc'

(I did debug it in NASM, so if I'm unlucky, something may fail in FASM due to syntax, but it should be easy to fix. But it's highly unlikely, they should have identical syntax for instructions and I don't use any macros/etc)


Google Foobar challenge: Rabbit Test Subjects

For one thing, the assignment was to define a function answer(x, y), not answer(y, x).  You could also put the built-in function sum() to use.  I believe the key point is rounded to the nearest whole number.  int() always goes down.  That is 4.9 results in 4, but rounding would result in 5.  You can use the built-in function round().  In Python3 it returns an integer, but in Python2 it returns a float.  To take care of both cases, convert the rounded version to an int:

def answer(x, y):
    return int(round((1-(sum(y)/sum(x))) * 100))


Validation is so common that I recommend generalizing it a little bit (not too much though, there are too many special cases).

One way is to create validations, schema, and data separate from each other. For example:

const validators = {
    required: (config, value) => value !== '',
    mobileNo: (config, value) => value.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && !(value.match(/0{5,}/)),
    equal: (config, value) => value === config.value
}

const validate = (data, schema) => {
    const messages = {}

    for(let [name, rules] of Object.entries(schema)){
        for(let rule of rules){
            if(!validators[rule.type](rule, data[name])){
                if(!messages.hasOwnProperty(name)) messages[name] = []
                messages[name].push(rule.msg)
            }
        }
    }

    return messages
}

const schema = {
    firstName: [{type: 'required', msg: 'Please enter a valid first name.'}],
    lastName: [{type: 'required', msg: 'Please enter a valid last name.'}],
    mobileNo: [{type: 'required', msg: 'Please enter a mobile number'}, {type: 'mobileNo', msg: 'Please enter a valid mobile number.'}],
    city: [{type: 'required', msg: 'Please enter a vaild city.'}],
    empType: [{type: 'equal', value: 'Self-Employed', msg: 'Some msg'}],
    salary: [{type: 'required', msg: 'Please enter a vaild salary.'}],
}

// In react component
validateForm(){
    const validationMessages = validate(this.state.data, schema)
    this.setState({validationMessages})
}

You can take this much further by adding templated validation messages, and fancy rules of all sorts. But I recommend keeping it simple. You can make multiple variants of the validate function for different needs as they come.


Find smallest prime number greater than given n

You can implement function isPrime to test primality in a little more efficient manner:

int isPrime(int n) // assuming n > 1
{
    int i,root;

    if (n%2 == 0 || n%3 == 0)
        return 0;

    root = (int)sqrt(n);

    for (i=5; i<=root; i+=6)
    {
        if (n%i == 0)
           return 0;
    }

    for (i=7; i<=root; i+=6)
    {
        if (n%i == 0)
           return 0;
    }

    return 1;
}


Sort, slice and rebuild new object with array data

Let's start with how I would have done it.

const data = {
  0 : {"label":"New York", "val": 20},
  1 : {"label":"Rio", "val": 10},
  3 : {"label":"Tokyo", "val": 50},
  4 : {"label":"Santiago", "val": 20},
  5 : {"label":"Hong Kooong", "val": 100},
  6 : {"label":"Munich", "val": 90},
}

const result = Object.values(data)
  .sort((a, b) => b.val - a.val)
  .slice(0, 3)
  .reduce((c, v) => {
    c.data.labels.push(v.label)
    c.data.values.push(v.val)
    return c
  }, { data: { labels: [], values: []}})

console.log(result)

Now onto your code:

let dataArray = Object.values(data).sort(compare)
dataArray = dataArray.slice(0, 3)

You were off to a good start here. One minor nitpick is to just chain the operations since you're just reassigning dataArray with sort's results.

let newLabel = []
let newValue = []
Object.keys(dataArray).map(function(key, index) {
  newLabel.push(dataArray[index]['label'])
  newValue.push(dataArray[index]['val'])
});

let newObj = {}
newObj.data = {}
newObj.data.labels = newLabel
newObj.data.values = newValue

This is where it went crazy.

Firstly, you used Object.keys() on dataArray (an array), which is not needed. If you need the array item index, all of the array methods provide the item index as second argument of the callback.

Also, this is a bad use of array.map(). array.map() is used to transform values in one array to another array of values, i.e. a 1:1 transform operation. In this case, you're merely using it for looping, something better suited for array.forEach().

Since you're "reducing"/"aggregating" an array of values into one value (turning an array of values into an object), array.reduce() is the better option.


Unless I missed something, it appears that bool rbtree<K, D>::insert(K& key, D& data) always returns true. It is quite misleading. If there is no way for this function to ever return anything but true, you could as well get rid of the bool return type.

Also, I propose a different approach than Loki's one for the default constructors of rbnode: you can use in-class members initializers for the default values:

struct rbnode
{
    node_ptr left { nullptr };
    node_ptr right { nullptr };
    rbnode *parent { nullptr };
    enum { Red, Black } color = Red;
    D data;
    K key;

    // Etc...
};

This way, your default constructor can be reduced to its simplest form:

rbnode() = default;

And the "default" values from the in-class member initializers will also be used to automatically initialize non-initialized members in the other constructors:

rbnode(K k, D d):
    data{d},
    key{k}
{}

rbnode(K k, D d, rbnode* p):
    parent{p},
    data{d},
    key{k}
{}

Note that I also used list initialization for some of the in-class members initializers and for the constructor initialization list. List initialization can help to avoid some problems related to implicit narrowing conversions of values.


#include <stdint.h>

At least officially, you're supposed to prefer to use <cstdint> instead. I have a hard time getting very excited about it though.

#include <cstring>

From the looks of the code, you really wanted to include <string> here instead. You use an std::string in one place anyway (and I don't any use of anything from <cstring>).

typedef union
{
    int16_t Value;
    struct
    {
        int8_t Lo;
        int8_t Hi;
    } Bytes; //This is all I could think of to call this. If you can think of something better, let me know.
} CRC16;

This usage is fairly typical in C, but in C++, I'd just use:

union CRC16 {
    // ...
};

Just like with class/struct, there's no need for a typedef in C++.

As you guessed, this is endian-specific. Given that this is apparently an old DEC protocol, chances are that it's also little-endian. That's good to the degree that it works fine with Intel processors, but bad to the degree that the normal ntohl, ntohs (etc.) are all defined in terms of big-endian network format, so you can't use them to easily write portable code that converts endianness when needed.

#ifdef _MSC_VER
#pragma pack(push, 1)
#endif
typedef struct

Same comment as above--no real need for a typedef in C++.

uint16_t Count : 14;
uint16_t Select : 1;
uint16_t Qsync : 1;

You probably want to be aware that the mapping from bitfields to bits can vary (even independent of endianness). Not necessarily something you want to change or can fix, but with a different compiler (even with the same CPU) this could rather suddenly break.

#ifdef _MSV_VER

Minor typo--this should almost certainly be _MSC_VER.

template<typename T>
void PrintHex(std::string Description, T Value, long Mask = -1)
{
    using namespace std;
    cout << hex
         << setiosflags(ios_base::showbase)
         << Description
         << " = "
         << (static_cast<unsigned short>(Value) & Mask)
         << resetiosflags(ios_base::showbase)
         << endl;
}

This has (IMO) a problem: after it's done, the hex flag is reset, even if it may have been set before the function was called. I'd rather use ios_base::flags() to retrieve the current flags, when again to restore then when finished. As (nearly) always when taking some action like that which you want to do, then un-do later, I'd prefer to put it into a small class that uses RAII to automate the restoring:

class flag_rest {
    std::ios_base::fmtflags original;
    std::ostream &s;
public:
    flag_rest(std::ostream &s) : original(s.flags()), s(s) {}
    ~flag_rest() { s.flags(original); }
};

Using that, printhex gets a little simpler:

template<typename T>
void PrintHex(std::string Description, T Value, long Mask = -1)
{
    using namespace std;
    flag_rest f(cout);

    cout << showbase
        << hex
        << Description
        << " = "
        << (static_cast<unsigned short>(Value) & Mask)
        << endl;
}

Probably more importantly, it also restores the flag to the state it held before the call, and does so dependably (even if the function exits via an exception). Of course, it's also nice that flag_rest is fairly reusable as well.

Of course, the cast to unsigned short means this can (will) misbehave or any type larger than a short, though I doubt you really care a lot about it.


You can simplify the zpool command, by specifying the volume name as an argument:

/sbin/zpool list tank | grep ONLINE

This will avoid cases where tank might be part of another volume's name. Better yet, use zpool get:

/sbin/zpool get -H health tank

This returns output which is more specific and easier to parse, since the status is the third, tab-separated field:

tank     health    ONLINE   -

So:

STATUS=$(/sbin/zpool get -H health tank | awk '{print $3}')

Then, you probably should test the value of STATUS, instead of the exit code:

if [ "$STATUS" != ONLINE ]; then
        echo "Problems"
        exit 1
...

Next, be consistent in indentation:

if [ "$STATUS" != ONLINE ]; then
        echo "Problems"
        exit 1
else
        echo "All systems go!"
        exit 0
fi

Also: all system go! should be All systems go!.

exit 0 is unnecessary in this case, without it, the shell will exit the else block and then the script itself, and return the exit status of the last command executed (echo, which would return 0 unless it couldn't write output, in which case you probably shouldn't have the echo there anyway).


Your code doesn't handle empty tuples gracefully.  The first version generates a compilation error, and the second version returns void.  For the first version, you can add an apply_tuple overload for empty tuples.  For the second version, you can change

return ((seed = hash_combine(std::get<I>(t), seed)), ...);

to

((seed = hash_combine(std::get<I>(t), seed)), ...);
return seed;

Is 0 really a good initial seed?  Some prime number, I guess, might be better (e.g., 672807365, which is what MSVC returns for std::hash<std::nullptr_t>{}(nullptr)).

The tuple unpacking can be simplified with std::apply, avoiding index_sequences:

template <typename... Args>
struct hash<std::tuple<Args...>> {
    std::size_t operator()(const std::tuple<Args...>& tuple) const noexcept
    {
        return std::apply([](const auto&... args) {
            auto seed = static_cast<std::size_t>(672807365);
            ((seed = hash_combine(args, seed)), ...);
            return seed;
        }, tuple);
    }
};

(live demo)


Minor

Consider using the unittest module instead of using input to test
Use a if __name__ == "__main__" guard
Make it a function
Don't print but return variables

Timing improvements

  l.count(i) == 2

It will search the entire list from the start.

Let's take a sample input (worst case) of [2, 3, 4, 5, 6, 7, 8, 1, 1, 2, 2], it will search the entire list 10 times!

This can be done in \$ O(n) \$ (worst case), because we know

  All elements of the array are in range 1 to n

You can create a list temp with length n filling it with None or 0
For every number in the array, check if the value in temp[i] is empty (0 or None)

If it is empty put the value on that position
If the number is the same as the value of the temp list, we have seen it before

Revised Code

def find_repeating(lst):
    counts = [None] * len(lst)
    for i in lst:
        if counts[i] is None:
            counts[i] = i
        elif i == counts[i]:
            yield i

Note

This has the disadvantage of continuing to loop after the numbers are found, to avoid this you could add the elements to another array and return when the length of the array is 2.

It will not make the most "beautiful" code, but it will be faster than @Peilonrayz's answer for anything but worst case, since that requires to loop through the entire array.

def find_repeating(lst, count=2):
    ret = []
    counts = [None] * len(lst)
    for i in lst:
        if counts[i] is None:
            counts[i] = i
        elif i == counts[i]:
            ret += [i]
            if len(ret) == count:
                return ret

Timing all solutions


Yes, since you are here for code review:

Never ever ignore errors: yr, _ := strconv.Atoi(f[0])

        yr, err := strconv.Atoi(f[0])
        if err != nil {
            log.Fatal(err)
        }

You may use just one strings.Split/strings.Fields this way:

    f := strings.Fields(logData)
    for i := 3; i <= len(f); i += 3 {
        yr, err := strconv.Atoi(f[i-3])
        if err != nil {
            log.Fatal(err)
        }
        amt, err := strconv.Atoi(f[i-1])
        if err != nil {
            log.Fatal(err)
        }
        r := logRec{yr, f[i-2], amt}
        p.Report(r)
    }

You are over complicating a simple sum function, You don't need channels here, just a map does the job: It is this simple:

package main

import (
    "fmt"
    "log"
    "strconv"
    "strings"
)

func main() {
    m := map[string]int{}
    f := strings.Fields(logData)
    for i := 3; i <= len(f); i += 3 {
        amt, err := strconv.Atoi(f[i-1])
        if err != nil {
            log.Fatal(err)
        }
        m[f[i-2]] += amt
    }
    fmt.Println(m)
}

const logData = `2018 apples 9
2018 oranges 5
2019 apples 27
2019 lemons 13
2019 oranges 2
2020 oranges 1
2020 apples 16
2020 lemons 3`

For concurrency sake: You only need concurrent map, nothing more:

package main

import (
    "fmt"
    "log"
    "strconv"
    "strings"
    "sync"
)

type concurrentMap struct {
    sync.Mutex
    m map[string]int
}

func (p *concurrentMap) sum(item string, amount int) {
    p.Lock()
    p.m[item] += amount
    p.Unlock()
}

var data = &concurrentMap{m: map[string]int{}}

func main() {
    f := strings.Fields(logData)
    for i := 3; i <= len(f); i += 3 {
        amt, err := strconv.Atoi(f[i-1])
        if err != nil {
            log.Fatal(err)
        }
        data.sum(f[i-2], amt)
    }
    fmt.Println(data.m)
}

const logData = `2018 apples 9
2018 oranges 5
2019 apples 27
2019 lemons 13
2019 oranges 2
2020 oranges 1
2020 apples 16
2020 lemons 3`

Long running task example:

package main

import (
    "fmt"
    "log"
    "strconv"
    "strings"
    "sync"
    "time"
)

type concurrentMap struct {
    m map[string]int
    sync.Mutex
}

func (p *concurrentMap) sum(item string, amount int) {
    p.Lock()
    p.m[item] += amount
    p.Unlock()
}
func (p *concurrentMap) show() {
    p.Lock()
    for k, v := range p.m {
        fmt.Printf("Total for %s is %d\n", k, v)
    }
    p.Unlock()
}

var data = &concurrentMap{m: map[string]int{}}

func main() {
    go data.sum("oranges", 100)
    go data.sum("apples", 100)
    go data.sum("lemons", 100)

    go func() {
        f := strings.Fields(logData)
        for i := 3; i <= len(f); i += 3 {
            amt, err := strconv.Atoi(f[i-1])
            if err != nil {
                log.Fatal(err)
            }
            data.sum(f[i-2], amt)
            time.Sleep(1000 * time.Millisecond) // e.g. slow hard disk
        }
    }()

    t := time.NewTicker(1000 * time.Millisecond)
    defer t.Stop()
    for range t.C {
        data.show()
        fmt.Println()
    }
}

const logData = `2018 apples 9
2018 oranges 5
2019 apples 27
2019 lemons 13
2019 oranges 2
2020 oranges 1
2020 apples 16
2020 lemons 3`

And finally if your tasks will finish in time, you may use sync.WaitGroup:
package main

import (
    "fmt"
    "log"
    "strconv"
    "strings"
    "sync"
    "time"
)

type concurrentMap struct {
    m map[string]int
    sync.Mutex
}

func (p *concurrentMap) sum(item string, amount int) {
    p.Lock()
    p.m[item] += amount
    p.Unlock()
}
func (p *concurrentMap) show() {
    p.Lock()
    for k, v := range p.m {
        fmt.Printf("Total for %s is %d\n", k, v)
    }
    p.Unlock()
}

var data = &concurrentMap{m: map[string]int{}}

func main() {
    finished := &sync.WaitGroup{}
    finished.Add(1)
    go func() {
        defer finished.Done()
        data.sum("oranges", 100)
        data.sum("apples", 100)
        data.sum("lemons", 100)
    }()

    finished.Add(1)
    go func() {
        defer finished.Done()
        f := strings.Fields(logData)
        for i := 3; i <= len(f); i += 3 {
            amt, err := strconv.Atoi(f[i-1])
            if err != nil {
                log.Fatal(err)
            }
            data.sum(f[i-2], amt)
            time.Sleep(100 * time.Millisecond) // e.g. slow hard disk
        }
    }()

    finished.Wait()
    data.show()
}

const logData = `2018 apples 9
2018 oranges 5
2019 apples 27
2019 lemons 13
2019 oranges 2
2020 oranges 1
2020 apples 16
2020 lemons 3`

That is all.
I hope this helps.


Performance Test and Idea: Initialize a widget

Code is not just about performance. You have to check for maintainability, scalability and readability as well.

With regards to the way code is written, I'd favor the first method because it's the module pattern and is a common convention. The second one is too full of brackets and the object notation, though flexible, is nasty especially when you forget the commas.

For extendability, I suggest you build a base set of helper functions to facilitate module loading and phase handling. Here are potential events that you might want to hook on events:

when the DOM is ready (DomContentLoaded)
when everything is loaded (window.onload)
when the page is unloading (window.onunload and onbeforeunload)
when the widget is loaded into the library
when the widget is unloaded/removed
when the widget is first run (init)
and so on...

Also, I suggest the following style of extension since:

It creates a single local scope for your widget to operate and share. You have the so called "private sandbox".
Objects are provided as an interface to attach stuff like public methods/properties, handlers and stuff. Whatever attached will be collected by your framework, sorted and executed accordingly.
It's simple and readable!

Here's a sample of a widget:

//assumung app is your framework namespace
app.addWidget('WeatherWidget',function(handles,publicStuff){

  //your local scope
  var foo = 'bar';

  function baz(){console.log('bam');}

  //handles and public are your interfaces
  //in this example, handles will be used to collect your event handlers

  handles.init = function(){/*run on init*/};
  handles.documentReady = function{/*run on DOM ready*/};

  publicStuff.getBar = function(){return foo;}

});


Style issue: Formatting and braces
Even if the language allows you to leave out the braces after an if, do not omit them. People tend to expand their code and forget to put them in when required. This creates nasty, hard to find bugs and the compiler will not complain.

Design issue: out parameters Output parameters tend to obscure the information flow in your program. They are not required in any way, you can do everything fine without them. Failing to keep track of all the funny little things a function might modify as a side effect is a constant source of bugs. Many people thus prefer to not use them at all and rather return a compound of all the things the function calculates and distribute them to the data structures after the function has returned. If this becomes hard you may have an overall design issue. (There are still valid reasons for using out-parameters e.g. in performance and memory critical low-level applications.)

Legacy code: Raw pointers Using plain raw pointers is only fun for very small and quick hacks, that will never see any real use. Become friends with the C++11 (and above) smart pointers. Seriously, they will save you a lot of trouble.

Last but not least

if(foo > max){
   foo = min;
}

Is in your case (continuous counting with clamped upper and lower value) equal to

foo = (foo % (max + 1 - min)) + min; // parenthesis for ease of reading

With max = 3 and min = 1 you get

foo = (foo % 3) + 1;

Using the modulo operator is an elegant approach for such "around the clock" counting.

Edit: The modulo operator is now named correctly. (Credits to @Cody Gray)


I've created the following performance tests to test the changes: http://jsbin.com/EqiKini/3

I'm going to start out this review by pointing out your algorithm is slightly off! Take a look at compositeNumbers after your code above and you'll see it is: {2: 1, 4: 1, 6: 1, 8: 1, 9: 1, 10: 1}. Clearly 2 is not composite but it will normally work because you exclude 1. The way I would address this is by doing a check if max is less than 3.

function findNumPrimes(max) {
  if(max <= 1) return 0;
  var compositeNumbers = {1: 1}; //1 is composite
  //if (max > 3) {//in retrospect no need for this pre condition as it will be handled by the loop
  mainLoop: for (var i = 4; i <= max; i++) {
    smallLoop: for (var j = 2; j <= Math.ceil(Math.sqrt(i)); j++) {
      if (i % j === 0) {
        compositeNumbers[i] = 1;
        continue mainLoop;
      }
    }
  }
  return max - Object.keys(compositeNumbers).length;
}

As you'll notice I slightly adapted your code so you would use it like console.log(findNumPrimes(10000)); //1229

The first notable (and obvious) speed improvement I'll point out is you should probably cache Math.ceil(Math.sqrt(i)) in a variable (2 times + speed improvement for max > 100).

An even better implementation would probably make use of the ideas from the Sieve of Eratosthenes. I added a case to the performance tests using the sieve find prime number algoritm posted here.


Retrieve annotation from a tree annotated with a Monoid

Since this is a relatively simple question, 4 days is enough waiting for a more knowledgeable answer.

Your implementation of tag is correct and there is neither much room for improvement, nor there really is other ways to do it. You can replace Append x left right with Append x _ _ like you did for Single, and that's about the change you can make.

  Originally, I had implemented the Append ... case as:

That implementation was just wrong, consider what the two implementations return for your first example: 100 != 100 * 10 * 10.

  I'm not sure if I can assume that the [a] in [B] is
  already populated.

You can assume it is populated, you cannot have instances of algebraic data types with missing elements.

What you were trying to do probably is ensuring that an invariant, namely tag (Append x left right) == tag left <> tag right, is satisfied. This is the duty of a smart constructor. In this case the other function (+++ operator) you were asked to implement in the homework.


Project Euler #2 (Even Fibonacci numbers) in Swift

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

struct FibonacciSequence : SequenceType {
    let upperBound : Int

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

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

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

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

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

struct FibonacciSequence : SequenceType {
    let upperBound : Int

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

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


Print exact value represented by float in [0,1)

Separation of Concerns
Your function is doing too much.  It is:

Converting the float to a fraction
Converting the fraction to a string of digits
Printing the string of digits

You should separate these.
Float to Fraction
First, let's move the float-to-fraction code into its own function.
from typing import Tuple

def float_to_fraction(value: float) -> Tuple[int, int]:
    """
    Convert a floating point number in the range [0, 1) into a fraction.

    >>> float_to_fraction(0.625)
    (5, 8)

    >>> float_to_fraction(0.1)
    (3602879701896397, 36028797018963968)
    """

    if not (0 <= value < 1):
        raise ValueError("Value out of range (0 <= value < 1)")

    numerator, denominator = 0, 1
    while value:
        value *= 2
        numerator *= 2
        denominator *= 2
        if value >= 1:
            value -= 1
            numerator += 1
    return numerator, denominator

Here, I've added:

type hints, describing the input and output types for the function,
a """docstring""" describing how to use the function,

including an example formatted for use with the doctest module,

input range validation, since your expectation is for the range to be within a narrow range of float values.

I've also changed num to numerator, since it would be easy to misinterpret the abbreviation to mean number.  Similarity, den became denominator and x became value.
Fraction to String
Again, converting a numerator/denominator fraction into a series of digits is logical unit of code, which could be reused elsewhere, so I've made it into a function:
def fraction_to_string(numerator: int, denominator: int) -> str:
    """
    Convert a proper fraction into a corresponding series of digits.

    >>> fraction_to_string(5, 8)
    '0.625'
    """

    if not (0 <= numerator < denominator):
        raise ValueError("Improper or negative fraction given")

    if denominator & (denominator - 1) != 0:
        raise ValueError("Denominator must be a power of 2")

    digits = '0.'
    while numerator:
        numerator *= 10
        digits += str(numerator // denominator)
        numerator %= denominator

    return digits

Note: str(0.0) returns '0.0' but your code (and my duplication of it here) returns '0.'.
Your code originally guaranteed the denominator was a power of 2.  With this new function, a caller could ask for fraction_to_digits(1, 3) which would be an infinitely long string of digits, so I've added a condition restricting the denominator to a power of 2.
Float to String
Now we can compose these two functions, as well as recreate the original function's functionality:
def float_to_string(value: float) -> str:
    numerator, denominator = float_to_fraction(value)
    return fraction_to_string(numerator, denominator)

def print_float(x):
    print(float_to_string(x))

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)

    from random import random

    for _ in range(3):
        x = random()
        print(f'{x}:')
        print(('%.2000f' % x).rstrip('0'))
        print_float(x)
        print()

Additionally, I've added a "main guard" (always a good idea), and I've added a call to doctest.testmod() so the tests embedded in the """docstrings""" are executed.
Notes
The function float_to_fraction(value) may be replaced by the built-in function value.as_integer_ratio().
>>> value = 0.625
>>> value.as_integer_ratio()
(5, 8)


The if conditions can be simplified.

fpv_list = [ item.partition("_") for item in request.POST.iteritems() ]
deletes = [ v for f,p,v in fpv_list if f == 'delete' ]
for education_id in deletes:
    whatever

edits = [ v for f,p,v in fpv_list if f == 'edit' ]
for education_id in edits:
    whatever

This removes the dependence on knowing the length of 'delete' and the length of 'edit' prefixes on the  buttons.


How to increase efficiency of matrix operation in C?

I suggest dropping the floating point and doing it fixed point.  To do this I
would make a[][] of type int or short (depending upon the input
constraints) and instead of storing values x and x * 0.5, store 2x and x
respectively.  At the end of the summation you can then divide by 2 to get the
true result.

The only issue this raises is that of integer overflow.  You don't state any
numerical constraints but the fixed size arrays (2000x2000) suggest overflow
will not occur with long long.  Alternatively the summation itself could be
floating point while the array values remain integers.  I notice that your
current summation uses float which might well be slower than double.

Another minor point where you can improve the speed is in the input loop.  You
have the conditional

if(n!=1)
    a[i][i] = num*0.5;
else
    a[i][i] = num;

As the loop variable i goes from 0 to n, if n is 1 then the loop only
fills a[0][0] and so this conditional can be removed from the loop.  But if n
is small this will make little difference.


As far as I see supplyAsync and thenAcceptAsync uses ForkJoinPool.commonPool() which does not use more than three threads on my machine (and it depends on the number of available processors). It could be a bottleneck if you have more than three clients at the same time. Both methods can have an Executor argument which would be used instead of commonPool().
The code calls completeExceptionally in the catch block here:

readerPromise.thenAcceptAsync((buffer) -> {
    if (buffer != null) {
        try {
            connection.write(buffer).get();
            connection.close();
        } catch (InterruptedException | ExecutionException | IOException e {
            readerPromise.completeExceptionally(e);
        }
    }
});

It seems to me that it does not have any effect. Javadoc of completeExceptionally says the following:

  If not already completed, causes invocations of get() and related methods to throw the given exception.

The lambda passed to thenAcceptAsync is called when the CompleteFuture (readerPromise in this case) is already completed so it doesn't change anything. Consider the following PoC:

@Test
public void test3() throws Exception {
    final CompletableFuture<String> reader = CompletableFuture.supplyAsync(() -> {
        return "data";
    });
    reader.thenAcceptAsync(x -> {
        System.out.println("reader.thenAcceptAsync: " + x);
        boolean transitionToCompleted = reader.completeExceptionally(new RuntimeException(
                "overridden Future result"));
        System.out.println(transitionToCompleted); // prints "false"
    });

    Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);
    System.out.println("reader result: " + reader.get()); // prints "data"
}

(Note that there is an obtrudeException method but I guess you don't need that either.)
The same is true for connectionPromise.completeExceptionally(e), furthermore, connectionPromise seems completely unused in the code above. I'd remove it.
thenAcceptAsync will run only when the the previous stage completes normally. The following also could be useful:

  In all other cases, if a stage's computation terminates abruptly with an (unchecked) exception or error, then all dependent stages requiring its completion complete exceptionally as well, with a CompletionException holding the exception as its cause.

Source: CompletionStage javadoc

According to that you might be able to change the reader lambda to the following:

final CompletableFuture<ByteBuffer> readerPromise = CompletableFuture.supplyAsync(() -> {
    try {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        connection.read(buffer).get();
        buffer.flip();
        return buffer;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
});

It never returns null, so you can remove the null check from writer lambda:

final CompletableFuture<Void> writerPromise = readerPromise.thenAcceptAsync((buffer) -> {
    try {
        connection.write(buffer).get();
        connection.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
});

Finally, if there's an exception, you could log that with the following:

writerPromise.exceptionally(x -> {
    x.printStackTrace(); // TODO: use logging instead
    return null;
});

(I'm not familiar with these APIs but this looks right for me.)
Note that I've removed the ugly casting with changing

return (ByteBuffer) buffer.flip();

to

buffer.flip();
return buffer;

Calling Future.get() in the lambdas does not seem to asynchronous for me too (althought they're run by another threads) but I've not idea how should it be handled. The two APIs does not seem compatible. (I guess you could get better answers on Stack Overflow with a more specific question.)


Optimising a user's-choice sorting algorithm

You'll have to excuse my javascript, which is kind of lacking, but you can use any comparison based algorithm to make the sorting happen in \$O(n \log n)\$ comparisons, where a comparison is one of your user powered tests. I think merge sort is guaranteed to need exactly \$n \log n\$, and is relatively simple to implement, so you could implement a bottom-up mergesort by doing something along the lines of:

var array = ["apple", "pear", "cherry",  "banana", "orange", "watermelon",
             "bread", "a duck"];
var temp = [];

var merge_len = 1
var merge_lo = 0;
var merge_mid = 1;
var merge_hi = 2;
var merge_ptr_1 = 0;
var merge_ptr_2 = 1;

function mergesort_step(slot) {
    if (slot == 2) { // right button pressed
        temp.push(array[merge_ptr_2]);
        merge_ptr_2++;
    }
    else {
        temp.push(array[merge_ptr_1]);
        merge_ptr_1++;
    }

    if (merge_ptr_1 == merge_mid || merge_ptr_2 == merge_end) {
        // Copy any remaining items in 1st merged subarray to temp
        for (i = merge_ptr_1; i < merge_mid; merge_ptr_1++) {
            temp.push(array[merge_ptr_1]);
        }
        // Copy any remaining items in 2nd merged subarray to temp
        for (i = merge_ptr_2; i < merge_hi; merge_ptr_2++) {
            temp.push(array[merge_ptr_2]);
        }
        // Overwrite the two subarrays with the sorted temp
        for (i = 0; i < merge_hi - merge_lo; i++) {
            array[i + merge_lo] = temp[i];
        }
        temp = []
        // Set up the next two subarrays to merge
        if (merge_hi + merge_len >= array.length) {
            merge_lo = 0;
            merge_len *= 2;
            if (merge_len >= array.length) {
                // We are finished!
                output();
                return
            }
        }
        else {
            merge_lo = merge_hi;
        }
        merge_mid = merge_lo + merge_len;
        merge_hi = merge_mid + merge_len;
        if (merge_hi > array.length) {
            merge_hi = array.length();
        }
        merge_ptr_1 = merge_lo;
        merge_ptr_2 = merge_mid;
    }
}

Here merge_ptr_1 and merge_ptr_2 have taken the place of your pos1 and pos2, and I have skipped your option1 and option2 entirely to not bloat the code up any more.


If you're going to be writing VBScript or WSScript files then you should be using VBEdit.

Allow it is not required you should still capitalize End, Function and Sub.
Wrapping each tasks in it's own Sub or Function will make it easier to read, debug and modify your code.
A Function that does not return a value should be a Sub.
Avoid editing text files line by line.  It is much more efficient to split the text into an array of lines, edit each element of the array, and then join the output.
Refactored Code
This code takes less than 1 second to trim each line of a 27 MB text file.
Dim FullFileName
FullFileName = GetSharedFileName

If FileSystemObject.FileExists(FullFileName) Then
    TrimFileContents FullFileName
    MsgBox "Done"
Else
    MsgBox "File not found: " & FullFileName
End If

Sub TrimFileContents(FullFileName)
    Dim Lines
    Lines = GetTextFileLines(FullFileName)

    Dim n

    For n = 0 To UBound(Lines)
        Lines(n) = Trim(Lines(n))
    Next

    OverWriteTextFile FullFileName, Join(Lines, vbNewLine)
End Sub

Function GetSharedFileName
    GetSharedFileName = Replace(GetParentFolderName,"jobs\SCRIPTS","shared\file") & "\DCS.txt"
End Function

Function FileSystemObject
    Set FileSystemObject = CreateObject("Scripting.FileSystemObject")
End Function

Function GetParentFolderName

    GetParentFolderName = FileSystemObject.GetFile(Wscript.ScriptFullName).ParentFolder.Path

End Function

Function GetTextFileLines(FullFileName)
    Const ForReading = 1
    Dim Text
    With FileSystemObject.OpenTextFile(FullFileName, ForReading)
        Text = .ReadAll
        .Close
    End With

    If InStr(Text, vbNewLine) = 0 Then
        GetTextFileLines = Split(Text, vbLf)
    Else
        GetTextFileLines = Split(Text, vbNewLine)
    End If

End Function

Sub OverWriteTextFile(FullFileName, Text)
    Const ForWriting = 2

    With FileSystemObject.OpenTextFile(FullFileName, ForWriting)
        .Write Text
        .Close
    End With

End Sub


RecyclerView with different ViewHolder using generic

From a quick glance, I share your concerns.

One 'smell' is that a sub-class (FeedWithoutImageHolder) provides less functionality than the parent class, i.e. it does not actually "extend" the class.

I suggest trying to align layout structure and functionality:

Create two different layouts: The first one without an image, and a second one which includes the first and extends it by adding an image. Depending on your desired layout design, you may instead want to declare only one layout which includes some empty placeholder element of the desired image display size which either stays empty or receives an image, so that all visual elements align.

I recommend against having a Feed handle the type of layout at all. Keep data objects and layout concerns separate, that's what the Adapter is for. Have the adapter check if an image needs to be displayed for an item and determine the appropriate view type in Adapter.getItemViewType().


Encoding strings using periodic table abbreviations

Any suggestions?

Yes, a few.

First off, split your function into parts (SRP), to separate the view (DOM elements and their values) from the logic (finding element names in strings).

var splits = fname.split("");
for (var i = 0; i < splits.length; i++) {
    var onevalue = fname.indexOf(splits[i]);

That doesn't make much sense to me. Don't you expect onevalue == i? If not, you might annotate this explicitly and/or make the comparison. Maybe it's inside the "some code"?

var doublev = fname.substring(onevalue, onevalue + 2);
var triplev = fname.substring(onevalue, onevalue + 3);

Notice that these will have the same value as singlev in the last [two] iterations of your loop, where the end is outside of the string.

if (ellist[splits[i]] || ellist[doublev] || ellist[triplev]) {
    value = splits[i];
    if (ellist[doublev] || ellist[triplev]) {
        value = ellist[doublev];
        if (ellist[triplev]) {
            value = ellist[triplev];

Ouch. Simplify this to

if (triplev in ellist) {
    value = ellist[triplev];
} else if (doublev in ellist) {
    value = ellist[doublev];
} else if (splits[i] in ellist) { // are you sure you don't want `singlev`?
    value = splits[i];
}


Finding all possible letter combinations from an inputted phone number

There is only one thing I really don't like:

You have the same array instantiated in two different places (the phone/ph array). Here it's fairly simple and easy to maintain, but IRL you should never do that.

You have two options to resolve this:

1) Create the phone array as a class field or property.

2) In the newest versions of C# you can place the recursive GetCombos(...) as an internal/local function inside LetterCombinations(...) and then only have string[] phone = {...} defined in the outer:

IList<string> LetterCombinations(...)
{
  string[] phone = { ... };

  void GetCombos(...)
  {
    ...
    char ch = phone[inputDigits[0] - '0'][charIndex];
    ...
  }

  int len = phone[digits[0] - '0'].Length;
  ...
}

As shown the inner function can access the variables defines in the containing method.

Other things:

public void GetCombos(string inputDigits, string curVariation, int charIndex, ref List<string> resultList, int length) { ... }

You don't need the ref keyword because a list is a reference type.

I don't think newInput will ever be empty, so you can skip this check:

  if (newInput == "") return;

I would make this test

  if (digits == null || digits.Length == 0) return result;

as the first thing to do in the method:

  if (string.IsNullOrWhiteSpace(digits)) return new List<string>();

(or maybe throw an exception?)

In GetCombos(...) you could use the yield return concept instead of the resultList argument as shown below:

public IList<string> LetterCombinations(string digits)
{
  if (digits == null || digits.Length == 0) return new List<string>();

  string[] phone = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

  List<string> result = new List<string>();

  IEnumerable<string> GetCombos(string inputDigits, string curVariation, int charIndex, int length)
  {
    if (curVariation.Length != length)
    {
      char ch = phone[inputDigits[0] - '0'][charIndex];
      curVariation += ch;
    }
    if (curVariation.Length == length)
    {
      yield return curVariation;
    }
    else
    {
      string newInput = inputDigits.Substring(1, inputDigits.Length - 1);
      int numChars = phone[newInput[0] - '0'].Length;

      for (int i = 0; i < numChars; i++)
      {
        foreach (string variation in GetCombos(newInput, curVariation, i, length))
        {
          yield return variation;
        }
      }
    }
  }

  int len = phone[digits[0] - '0'].Length;
  for (int i = 0; i < len; i++)
  {
    result.AddRange(GetCombos(digits, "", i, digits.Length));
  }

  return result;
}

The LeetCode challenge states that the return value of LetterCombinations(...) should be IList<string>, but it would be more elegant to let it return IEnumerable<string> as well and then use yield return insted of result.AddRange(GetCombos(...)) (you'll have to make it in a foreach () loop though).

Just for the exercise I made my own version:

IEnumerable<string> LetterCombinations(string digits)
{
  string[] phone = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

  int length = digits.Length;

  IEnumerable<string> Runner(int buttonIndex, int digitIndex)
  {
    if (buttonIndex < 2 || buttonIndex > 9)
      throw new ArgumentOutOfRangeException(nameof(digits));

    if (digitIndex == length)
    {
      foreach (char ch in phone[buttonIndex])
        yield return ch.ToString();
    }
    else
    {
      int newButtonIndex = digits[digitIndex] - '0';
      digitIndex++;

      foreach (char ch in phone[buttonIndex])
      {
        foreach (string tail in Runner(newButtonIndex, digitIndex))
        {
          yield return $"{ch}{tail}";
        }
      }
    }
  }

  return Runner(digits[0] - '0', 1);
}

Not to claim it to be better than yours - in fact it seems to be slightly slower - but just to show another approach.

In fact it can be done in one line using LINQ:

IEnumerable<string> LetterCombinations(string digits)
{
  string[] phone = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
  return digits.Skip(1).Select(d => d - '0').Aggregate(phone[digits[0] - '0'].Select(c => c.ToString()), (acc, i) => phone[i].SelectMany(c => acc.Select(a => $"{a}{c}")));
}


You're naming your parameters incorrectly. The naming guidelines for parameters specify camel casing.

Your method declaration should look like this:

public static bool IsWordABeforeWordB(string text, string wordA, string wordB)

Your current implementation also has a bug. You are assuming that the source text contains wordB - if it doesn't you'll get an ArgumentOutOfRangeException on the substring.

I'd suggest that performance probably doesn't matter here so you may as well just do it the long way:

public static bool IsWordABeforeWordB(string text, string wordA, string wordB)
{
    // Omitted checking text, wordA and wordB for null.
    var indexOfFirstWordA = text.IndexOf(wordA, StringComparison.OrdinalIgnoreCase);
    if (indexOfFirstWordA == -1)
    {
         // throw exception or return false.
    }
    var indexOfLastWordB = text.LastIndexOf(wordB, StringComparison.OrdinalIgnoreCase);
    if (indexOfLastWordB == -1)
    {
        // throw exception or return false.
    }

    // edited based on holroy's comment.
    // Otherwise we'd be wrong if wordB was a substring of wordA
    // e.g. wordA: hello, wordB: lo
    return indexOfFirstWordA + wordA.Length < indexOfLastWordB;

}

I've assumed that IsWordABeforeWordB("Sample text is sample", "text", "sample") should return true as "text" does appear before one of the "sample"s. If that's not the behaviour you were going for you can change the LastIndexOf to a simple IndexOf

The definition of a "word" is a bit loose here. You could do a Regular Expression match to get the indexes which would allow you to use the "\b" word anchor. I've just assumed (as your OP) that it's simply a sequence of characters.


I feel the key to generalizing your code is to store your variables into a matrix. Then let vectorized functions (colMeans, cor, *, etc.) do their magic:

A <- cbind(A1, A2, A3, A4)

VN_Normalization <- function(A) {
   m  <- colMeans(A)
   RG <- m %o% (1/m)
   scales <- colMeans(RG * abs(cor(A)))
   A_Normalized <- t(t(A) * scales)

   n <- ncol(A)
   i <- seq_len(n)
   labels <- c(sprintf("Array%i", i),
               sprintf("Array%i_Normalized", i))
   boxplot(cbind(A, A_Normalized),
           las = 2, names = labels,
           col = c(rep("white", n), rainbow(n)))
}

Please let me know if I missed anything (I assumed A1, A2, etc. were numeric vectors of equal lengths.)


Simple AngularJS controller for REST API

You can use this unexplodeWord function:

 var explodedWords = [{"0":"h","1":"e","2":"l","3":"l","4":"o"},
                       {"0":"w","1":"o","2":"r","3":"l","4":"d"}]

 var words = explodedWords.map(unexplodeWord);

 // Converts {"0":"h","1":"e"} to "he".
 function unexplodeWord(explodedWord) {
   var chars = [];
   angular.forEach(explodedWord, function(char) {
     chars.push(char);
   });
   return chars.join('');
 }

 words.forEach(function(item) { console.log("word: " + JSON.stringify(item)); });

You would call it as such:

    $scope.Products = data[0];
    $scope.Branches = data[1].map(unexplodeWord);
    $scope.Profiles = data[2].map(unexplodeWord);

You would still have some asymmetry relative to Products, but not as much.
If I understand correctly, you want some kind of advice about pagination.  If you really get too much data, maybe you could print only the branches and profiles for one product at a time.

If you have too many branches and profiles for a single product, you should probably only output either branches or profiles, and paginate those.


JavaScript - Comparing 2 arrays - Would like to check if I'm reinventing the wheel or am I good to go?

You should take a look at the Underscore javascript library, which contains a number of methods for comparing and manipulating arrays and objects.

I'm using the _.intersection and _.keys methods to compare your two objects. I've also taken the liberty of restructuring your arrays into objects, which I think makes more sense for what you're trying to do.

// Adds the values of keys that are the same between any two objects
function addObjects(a, b) {
  var sameKeys = _.intersection(_.keys(a), _.keys(b)),      // Creates array of similary keys. eg ["John", "Jenny", "Amanda"]
      sumObj = {}

  // Loop through sameKeys, and add values from both objects
  for(i=0; i < sameKeys.length; i++) {
    var thisKey = sameKeys[i];
    sumObj[thisKey] = a[thisKey] + b[thisKey];              // eg. sumbObj["John"] = a["John"] + b["John"] = 7
  }

  return sumObj;
}

var firstObj = {
  "John" : 2,
  "Jenny" : 3,
  "Beavis" : 5,
  "Toby": 6,
   "Amanda": 12
}

var secondObj = {
  "John": 5,
  "Jenny": 18,
  "Amanda": 2
}

mySumObj = addObjects(firstObj, secondObj);
/*
mySumObj = {
    "Amanda": 14,
    "Jenny": 21,
    "John": 7
}
*/

I hope this helps you. It may help if you could explain a bit more what your end goal here is.


Circular buffer implementation using linked list

Bug
When you dequeue the last element, this code will run with p_size being 1:

   if (p_size>0)
    {
        val=read->item;
        read=read->next;
        free(ptr);
        p_size--;
        printf("removed %d\n",val);
    }

The result of this code is that the last element will be freed, but read and write will still be pointing at it, because the list was circular.  Then the next time you call enqueue(), it will use those stale pointers to add to the list.
To fix this problem, you should clear the pointers to NULL when you dequeue the last element.


using (var dbTransaction = System.Data.Entity.Database.DefaultConnectionFactory.CreateConnection("MyCon").BeginTransaction())
// ...
finally
{
    dbTransaction.Dispose();
}

You're already using the transaction in a using statement which is shorthand for try/finally, where the finally block disposes the IDisposable. So you can remove your manual finally block completely, otherwise you're calling Dispose on the transaction twice.

  clsErrorHandling.WriteLog("ImportUsersHandler", "AddUsers", ex.Message.ToString());

ex.Message is already a string, no need to call ToString on it.


Statistical queries on a list of customers

If you need to do more data analysis on this afterwards, then this might be a good time to learn about pandas which has data frames, allowing you to modify whole records at a time.

First, read in your list into a data frame:

import pandas as pd

df = pd.DataFrame([[customer.active, customer.age, customer.gender]
                   for customer in filter(None, customers)],
                  columns=["active", "age", "gender"])

Here the filter(None, it) filters out all None values (and all falsey values, but an object that exists is by default truthy, so unless you overwrote Customer.__eq__ or Customer.__bool__, it should be fine).

Now we have a data frame like this:

print(df)
#   active   age gender
# 0   True  38.0      F
# 1  False  18.0      M
# 2  False   NaN      F
# 3   None  64.0   None
# 4   True  23.0   None
# 5   None  23.0      M

To make handling of the left over None values easier, we replace them with numpy.nan:

import numpy as np

df = df.replace([None], np.nan)
print(df)
#   active   age gender
# 0   True  38.0      F
# 1  False   NaN      M
# 2  False   NaN      F
# 3    NaN  64.0    NaN
# 4   True  23.0    NaN
# 5    NaN  23.0      M

Now to get to your tasks:

Number of active customers:

active_users = df.active.sum()
# 2

Number of inactive customers:

deleted_users = sum(customer is None for customer in customers)
inactive_users = len(df) + deleted_users - active_users
# 8

Any customer deleted:

deleted_users > 0
# True

Any customer with active=None:

df.active.isna().any()
# True

Average of male customers (NaNs are automatically ignored):

df[df.gender == "M"].age.mean()
# 20.5

If there are no people of that gender, it will return a numpy.nan instead of 0, though:

df[df.gender == "X"].age.mean()
# nan

From there on you can also do more fancy stuff:

Average age per gender:

df.groupby("gender").age.mean()
# gender
# F    38.0
# M    20.5
# Name: age, dtype: float64

Using this makes your code both more efficient to write (since most things you could want to do are already implemented) as well as faster to run (since the methods are usually implemented in C, instead of running in Python. So if you have lots of customers, this will certainly be better.


SICP - exercise 1.7 better end test for square root approximation

sqrt-iter

You compute (improve guess x) twice - this is a waste.
You return guess instead of the improved guess, i.e., you return a worse approximation than you could.

E.g.:

(define (sqrt-iter guess x)
  (let ((next-guess (improve guess x)))
    (if (good-enough? guess next-guess)
        next-guess
        (sqrt-iter next-guess x))))

good-enough?

0.000000000000000000000000000001 is unreadable. 1d-30 is better.
1d-30 is far too high precision. With such an epsilon, you might as well use = instead of good-enough? - the "oscillation between two adjacent floats" problem will be the same. Read up on machine epsilon.
This number should actually be an argument to sqrt.
Adding a line break would make the function more readable.


A method to capitalize the first letter of all words in a String

It appears whitespace is destroyed instead of preserved, see your "NOTE". I suspect input like " 123 456 " will output "123456" destroying outer and inner space.  Similarly "a     b" will become "A B", as split will return a lot of empty strings when splitting more than one space.  How about treating it as a stream and if the previous character is whitespace and the next character is in a-z, upper case it, and emit the character and update your previous character placeholder.  You could probably do this with a single regular expression.


The main thing to note is that your profit function only uses vectorized functions (- and *) so it is vectorized with respect to its four inputs. This means that you do not have to create loops; instead you can just feed the functions with vector(s): one vector for the variable that you are shocking, and scalars for the other three fixed inputs. Here is my suggested rewrite, having put everything into a function:

biz_sens_analysis <- function(Price      = 10,
                              Var_Cost   = 5,
                              Units      = 100000,
                              Fixed_Cost = 10000) {

  Max_Change <- 0.1
  Changes <- seq(-Max_Change, Max_Change, by = 0.01)
  shock <- function(x) x * (1 + Changes)

  # Define profit function
  Profit <- function(Price, Var_Cost, Units, Fixed_Cost)
     (Price - Var_Cost) * Units - Fixed_Cost

  # Calculating base and updated profit
  Start_Profit <- Profit(Price, Var_Cost, Units, Fixed_Cost)

  Profit_New_Price       <- Profit(shock(Price), Var_Cost, Units, Fixed_Cost)
  Profit_New_Var_Cost    <- Profit(Price, shock(Var_Cost), Units, Fixed_Cost)
  Profit_New_Unit_Sales  <- Profit(Price, Var_Cost, shock(Units), Fixed_Cost)
  Profit_New_Fixed_Costs <- Profit(Price, Var_Cost, Units, shock(Fixed_Cost))

  diff_px <- function(px) px - Start_Profit
  Diff_Profit_New_Price       <- diff_px(Profit_New_Price)
  Diff_Profit_New_Var_Cost    <- diff_px(Profit_New_Var_Cost)
  Diff_Profit_New_Unit_Sales  <- diff_px(Profit_New_Unit_Sales)
  Diff_Profit_New_Fixed_Costs <- diff_px(Profit_New_Fixed_Costs)

  # Plot the profit sensitivities
  options(scipen = 999) # Remove scientific notation from the chart axes

  fmt <- function(x) format(x, big.mark=",", scientific = FALSE)
  msg <- paste("Starting Business Conditions: Price = £", fmt(Price),
             ", Variable Cost = £",    fmt(Var_Cost),
             ", Unit Sales = ",        fmt(Units),
             ", Fixed Costs = £",      fmt(Fixed_Cost),
             ", Giving a Profit of £", fmt(Start_Profit))

  plot(100 * Changes, Diff_Profit_New_Price,
     xlab = "Change in Dependent Variable (%)",
     ylab = "Change in Profit (£)",
     main = "Profit Sensitivity Analysis of Changing One Variable at a Time, Assuming no Interaction Among Dependent Variables",
     type = "l",
     sub  = msg)

  lines(100 * Changes, Diff_Profit_New_Var_Cost,    col = "red")
  lines(100 * Changes, Diff_Profit_New_Unit_Sales,  col = "blue")
  lines(100 * Changes, Diff_Profit_New_Fixed_Costs, col = "green")

  # Building legend
  Leg_Names <- c("Price Change", "Variable Cost Change", "Unit Sales Change", "Fixed Costs Change")
  legend("bottomright",
         legend = Leg_Names,
         col    = c("black", "red", "blue", "green"),
         pch    = 15,
         bty    = "n")
}

biz_sens_analysis()

Hope it helps. Let me know if you have questions.


Accessing argparse arguments from the class

You could do this by making the test classes take args as parameter, and crafting a custom make_suite method instead of unittest.makeSuite, like this:

class ParentTest(unittest.TestCase):
    def __init__(self, methodName='runTest', args=None):
        super().__init__(methodName)
        self.args = args

class Test1(ParentTest):
    def test_if_verbose(self):
        print("Success!") if self.args.verbose else ""

class Test2(ParentTest):
    pass

if __name__ == '__main__':
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-?", "--help",     action="help",                        help="show this help message and exit" )
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose",  help="increase output verbosity" )
    parser.add_argument('files', nargs='*')
    args = parser.parse_args()

    print(args.verbose)

    def make_suite(testcase_class):
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(testcase_class)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(testcase_class(name, args=args))
        return suite

    # Add tests.
    alltests = unittest.TestSuite()
    alltests.addTest(make_suite(Test1))
    alltests.addTest(make_suite(Test2))

    result = unittest.TextTestRunner(verbosity=2).run(alltests) # Run tests.
    sys.exit(not result.wasSuccessful())

The sample output is the same as the original code:

$ python t2.py ; python t2.py -v
False
test_if_verbose (__main__.Test1) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
True
test_if_verbose (__main__.Test1) ... Success!
ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

The code in my answer was inspired by these posts:

https://stackoverflow.com/a/17260551/641955
http://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases/


Compute mean, variance and standard deviation of CSV number file

Portability

#import is a GCC extension (or perhaps a preview of C++20).

There's no good reason not to simply #include <cmath> here.

Headers and namespaces

We don't use any string-stream, so #include <sstream> can be removed.

Bringing all names in from a namespace is problematic; namespace std particularly so.  It can silently change the meaning of your program when you're not expecting it.  Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope.

In this program, the only places the std:: prefix were missing were std::ifstream and std::sqrt, so this wasn't hard to fix.

readFile()

These lines can be simplified:

std::ifstream in_file;
in_file.open(filePath);

We can ask the constructor to open the file for us:

std::ifstream in_file(filePath);

This loop has some error checking, but it's not complete:

while(std::getline(in_file,line,'\r')){
    numbers.push_back(std::stoi(line));
}

Firstly, we don't expect any carriage-return in the input file (we opened it in text mode, so on systems that use CR as line delimiter, they will be converted to \n).  Secondly, std::stoi throws exceptions when the string cannot be converted, but we probably also want to check whether there are leftover, unconverted characters after our integer (e.g. if someone thought they could supply decimal values).

computeMean()

Why return a float rather than double?  Single-precision floats are normally used only where the storage size is an important consideration, which is not the case here.  (Note that on many platforms, double is the natural (and fastest) size of floating-point.)

We should pass the vector by reference to a const object, as we don't want to make a copy or to modify the value.

Instead of returning zero when there are no members, perhaps we should return a NaN value (which is more consistent with arithmetic 0.0 / 0):

if (numbers.empty())
    return std::numeric_limits<double>::quiet_NaN();

This loop:

double total = 0;
for (int number : numbers) {
    total += number;
}

can be written (with #include <numeric>) as

double total = std::accumulate(numbers.begin(), numbers.end(), 0.0);

computeVariance()

We need to be clear which variance (sample or population) we're returning.  We're also missing a size check similar to that for the mean.

Apart from that, the comments above for computeMean() are relevant:

double computeSampleVariance(const double mean, const std::vector<int>& numbers)
{
    if (numbers.size() <= 1u)
        return std::numeric_limits<double>::quiet_NaN();

    auto add_square = [mean](double sum, int i)
        {
            auto d = i - mean;
            return sum + d*d;
        };
    double total = std::accumulate(numbers.begin(), numbers.end(), 0.0, add_square);
    return total / (numbers.size() - 1);
}

Single-pass algorithm

It is possible to compute the mean and variances in a single pass - but not using the (exact-arithmetic) methods you likely learnt in high school, which suffer from lack of precision with the inexact floating-point types we can use.  The topic is too deep for this review, but if you research Welford's Algorithm, you will find reference implementations to guide you.

That said, for your purposes, the straightforward two-pass algorithm is probably appropriate, and it's easy to read and understand, so I wouldn't recommend changing it unless you reach a point where your input set becomes too large to hold in a vector (and even then, only if you can't read the file multiple times).

My version

#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <numeric>
#include <vector>

std::vector<int> readFile(const std::string& filePath)
{
    std::ifstream in_file(filePath);
    std::istream_iterator<int> start{in_file}, end;
    std::vector<int> numbers;
    std::copy(start, end, std::back_inserter(numbers));
    return numbers;
}

double computeMean(const std::vector<int>& numbers)
{
    if (numbers.empty())
        return std::numeric_limits<double>::quiet_NaN();

    return std::accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
}

double computeSampleVariance(const double mean, const std::vector<int>& numbers)
{
    if (numbers.size() <= 1u)
        return std::numeric_limits<double>::quiet_NaN();

    auto const add_square = [mean](double sum, int i) {
        auto d = i - mean;
        return sum + d*d;
    };
    double total = std::accumulate(numbers.begin(), numbers.end(), 0.0, add_square);
    return total / (numbers.size() - 1);
}

int main()
{
#ifdef TEST
    const std::vector<int> numbers = { -2, -1, 1, 2, 100000-2, 100000-1, 100000+1, 100000+2};
#else
    std::cout << "Please enter the file path :" << std::endl;
    std::string filePath;
    std::cin >> filePath;
    const std::vector<int> numbers = readFile(filePath);
#endif

    double mean = computeMean(numbers);
    double variance = computeSampleVariance(mean, numbers);
    double standardDeviation = std::sqrt(variance);

    std::cout << numbers.size() << " numbers : ";
    auto separator = "";
    for (int number: numbers) {
        std::cout << separator << number;
        separator = ", ";
    }
    std::cout << std::endl;

    std::cout << "Mean : " << std::to_string(mean)
              << "Variance : " << std::to_string(variance)
              << "Standard Deviation : " << std::to_string(standardDeviation) << std::endl;
    return 0;
}


Convert object array to hash map using lodash

I think you are looking for _.keyBy (or _.indexBy in older versions)

_.keyBy(data, 'rel');


So, I pasted your code into my IDE and ran it in the debugger, and there isn't really any way to do exactly what you want to do. The function object doesn't appear to have any knowledge of anything other than how to call it.

Your best bet seems to be to modify the timing function to something like this:

  def time[R](f: => R, name: String): Unit = {
    val t0 = System.nanoTime()
    val r = f
    val t1 = System.nanoTime()

    val t = (t1-t0)/1000

    println(s"The result of $name is: $r time taken $t ms ")
  }

And then your call would be something like this:

   time (func, "func")

In a larger app, if you needed to pass around functions with their name, you could create a small object such as:

class Caller[R](f: => R, name: String) {
  def time(): Unit = {
    val t0 = System.nanoTime()
    val r = f
    val t1 = System.nanoTime()

    val t = (t1-t0)/1000

    println(s"The result of $name is: $r time taken $t ms ")
  }
}

Create it like so:

val a = new Caller(func, "func")

And call it like so:

a.time()


Insert missing records in a list with LINQ

Looks to me like you should create an Add method to both the OMS_Forecast_Adjustment and OMS_Receipts_Adjustment classes.

you are really adding things to the db all wrong,  you are creating new objects in your code when you don't have to, I think that you really want to add items to a collection variable inside your db object.

it should be an InsertRecord method

this:

    var modelFAF = db.OMS_Forecast_Adjustment;
    foreach (int periodID in missingFAF)
    {
        var modelItem = new OMS_Forecast_Adjustment { PeriodID = periodID, Product = item.Product, SiteID = item.SiteID, Value = 0 };
        modelFAF.Add(modelItem);
    }

Would turn into this

foreach (int periodID in missingFAF)
{
    db.Insert_OMS_Forcase_Adjustment(periodID, item.prodeuct, item.SiteID, 0);
}

so you actually do your insertion inside of a method in the class that you already have.

This removes the creation of 2 extraneous local variables and puts responsibility where it belongs inside of a method in the object that needs to perform the action.

This can be done on both Foreach Loops


Counting subscribers with matching ZIP code, interests, and sex

The first thing I notice is that you're calling map.{}.compact when you probably could be calling select{}, that is, you want to select from self.distribution. So that would replace 6 method calls with 3.

If you use select, it always returns an array and never a nil, so instead of unless X.nil or X.empty, you could use if X.any?, which would replace 6 method calls with three.

If you aren't using @matched_zips outside of this context, it makes no sense to assign a variable here. Instead of assigning, you could just use (CardSignup.all.map(&:zip_code) & @zip_codes).each do, which would spare you three variable assignments.


Design issues, tendency to write custom methods

Just a few small notes:

The method has seven parameters which isn't a good smell. Maybe some of them could be class field.
First, I'd reverse some conditions and use guard clauses to make the code flatten.

for (int i = 0; i < dtSProcList.Rows.Count; i++)
{
    if (dtSProcList.Rows[i][0].ToString() != cbSProcList.SelectedItem.ToString())
    {
        continue;
    }

    string temp = dtSProcList.Rows[i][0].ToString();
    if (dtSProcList.Rows[i][1] == DBNull.Value)
    {
        //Returns control to calling method if the parameter name is null.
        return;
    }

    inputLabels[counter].Text = dtSProcList.Rows[i][1].ToString().Remove(0, 1);
    inputLabels[counter].Visible = true;
    inputLabels[counter].Enabled = true;
    inputTxtboxes[counter].Visible = true;
    inputTxtboxes[counter].Enabled = true;

    selectedSProcInputs.Add(inputTxtboxes[counter]);
    selectedSprocDataTypes.Add(dtSProcList.Rows[i][2].ToString());

    counter++;
}

References:

Replace Nested Conditional with Guard Clauses in Refactoring: Improving the Design of Existing Code;
Flattening Arrow Code

0, 1 and 2 are magic numbers. Using named constants instead of numbers would make the code more readable and less fragile.
What does the counter count? You should give it a name which shows the intent of the variable.
dtSProcList.Rows[i] repeats five times in the code. A named local variable could remove this duplication.
The temp variable seems to be unused. If it's superfluous remove it.


Google Apps Script for finding empty days on multiple calendars

I flipped your logic a bit in the example below.  I only do one API call per calendar and then do all of the processing in the client.  It seems a bit faster for me, but I'm not seeing the 60 second processing time that you are.  So your results my vary.

var one_day = 86400000; //24 * 60 * 60 * 1000
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var startDay = nextMonday(new Date());

// Script-as-app template.
function doGet() {
  var app = UiApp.createApplication();

  var button = app.createButton('Find Blanks').setId('button');
  var loader = app.createImage('http://preloaders.net/preloaders/496/Flip%20Flop.gif').setVisible(false).setId('loader');
  var blanks = app.createHTML().setId('blanksArea').setHTML('Click button to find calendar blanks for week of ' + startDay);

  app.add(button);
  app.add(app.createHTML('
'));
  app.add(loader);
  app.add(blanks);

  var clientHandler = app.createClientHandler().forEventSource().setEnabled(false).forTargets(loader).setVisible(true).forTargets(blanks).setHTML('Processing for week of ' + startDay);
  var handler = app.createServerHandler('serverHandler');

  button.addClickHandler(clientHandler);
  button.addClickHandler(handler);

  return app;
}

function serverHandler(e) {
  var app = UiApp.getActiveApplication();

  var button = app.getElementById('button');
  var blanks = app.getElementById('blanksArea');
  var calendarsWithBlanks = getCalendarsWithBlanks();

  blanks.setHTML(calendarsWithBlanks.length ? calendarsWithBlanks.join('
') : 'There are no blanks');

  app.getElementById('loader').setVisible(false);
  button.setEnabled(true);

  app.close();
  return app;
}

function test_getCalendarsWithBlanks() {
  getCalendarsWithBlanks().forEach(function(calendarResult) {
    Logger.log(calendarResult);
  });
 }

function getCalendarsWithBlanks()
{
  var calendars = CalendarApp.getAllOwnedCalendars();
  var calendarsWithBlanks = [];
  for(var i = 0; i < calendars.length; i++)
  {
    var calendar = calendars[i];
    var calendarName = calendar.getName();
    var blankDays = checkCalendarForBlanks(calendar, startDay);
    if(blankDays.length )
    {
      calendarsWithBlanks.push(calendarName + ' has ' + blankDays.join(', ') + ' blank')
    }
  }
  return calendarsWithBlanks;
}

function checkCalendarForBlanks(calendar, startDay)
{
  var blankDays = [],
      allDayEventsPerDay = [0,0,0,0,0,0,0],
      endDate = new Date(startDay.getTime() + (4 * one_day)),
        // get all events for the next work week
      allEventsForNextWorkWeek = calendar.getEvents(startDay, endDate);

  //count number of all day events on each day
  allEventsForNextWorkWeek.forEach(function(event){
    if(event.isAllDayEvent()) {
      //count each day the event is on
      determineDaysOnWhichEventTakesPlace(event,startDay,endDate).forEach(function(eventDate){
        allDayEventsPerDay[eventDate.getDay()]++;
      });
    }
  });

  //figure out which ones have 0 (ie blank days)
  allDayEventsPerDay.forEach(function(count, offset){
    if(count === 0) {
      blankDays.push(days[offset]);
    }
  });

  return blankDays;
}

function determineDaysOnWhichEventTakesPlace(event, lowerLimit, upperLimit) {
  var startDate = new Date(Math.max(event.getAllDayStartDate().getTime(), lowerLimit.getTime())),
      endDate = new Date(Math.min(event.getAllDayEndDate().getTime(), upperLimit.getTime())),
      dates =[],
      eventDate;

    for(eventDate = startDate; eventDate< endDate; eventDate = new Date(eventDate.getTime() + (one_day))) {
      dates.push(eventDate);
    }
  return dates;
}

function nextMonday(date)
{
  var today = date;
  today.setUTCHours(0);
  today.setMinutes(0);
  today.setSeconds(0);
  today.setMilliseconds(0);
  var day = today.getDay();
  var offset = 8 - day
  var next_monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+offset);
  return next_monday;
}


Find words from dictionary method. Performance improvements

The main potential performance improvement I can see is turning the array of words into a Set of words instead. For every match in the string, you're doing:

const shouldInclude = wordsNoQuotes.find(word => knownWords.includes(word));

The .find is O(n) (it iterates over all words in the array, worst-case), and the .includes is O(n) (it also iterates through all words in its array, worst-case). So this is an O(n ^ 2) operation which is already inside a loop. That could be a bit expensive when either or both arrays are large. Using a Set for one of the arrays instead will allow you to use Set.prototype.has, which is an O(1) operation. The else part also uses .includes, which can be changed to .has:

const knownWordsSet = new Set(dictionary.toLowerCase().split(' '));
const words = text.toLowerCase().match(/\w+|"[^"]+"/gi);
const result = words.reduce((acc, word) => {
  if (word[0] == '"') {
    const wordsNoQuotes = word.replace(/"/g, "").split(' ');
    const shouldInclude = wordsNoQuotes.find(word => knownWordsSet.has(word));
    if (shouldInclude) {
      return acc.concat(wordsNoQuotes);
    }
  } else if (knownWordsSet.has(word)) {

const fn = (text, dictionary) => {
  const knownWordsSet = new Set(dictionary.toLowerCase().split(' '));
  const words = text.toLowerCase().match(/\w+|"[^"]+"/gi);
  const result = words.reduce((acc, word) => {
    if (word[0] == '"') {
      const wordsNoQuotes = word.replace(/"/g, "").split(' ');
      const shouldInclude = wordsNoQuotes.find(word => knownWordsSet.has(word));
      if (shouldInclude) {
        return acc.concat(wordsNoQuotes);
      }
    } else if (knownWordsSet.has(word)) {
      acc.push(word)
    }

    return acc;
  }, []);

  return result.length === 0 ? 0 : [...new Set(result)].join('\n');
}
console.log(fn(
  `Hi. I am a developer. A "Hello world" program was my first code.`,
  "hi developer world"
));

But Sets have a small overhead as well, so while this will definitely be the best strategy for large inputs, it might do slightly worse for tiny inputs when there are only one or a couple of words. (But for such tiny inputs, performance is not an issue to worry about anyway)

You're currently pushing to an array inside the loop, then the array only gets used to create a Set to deduplicate at the end of the function. It would be more efficient to use a Set of the result words from the beginning, instead of using an array and converting to one after the fact (converting an array to a Set and the other way around is an O(n) process). At this point, since the accumulator would be the same Set every time, .reduce would arguably not be appropriate, so use a plain loop instead.

A potential issue in your current code is that if the global .match has no matches, it will return null, not an empty array (unfortunately). So, to avoid occasionally throwing errors, you have to check to see if the match exists first before iterating over it.

You're using .find to check if there are any elements in the wordsNoQuotes array which fulfill the condition. But you don't care about which element fulfills the condition - you just want to see if any element does. So, rather than using .find (which returns the matching element), it would be more semantically appropriate to use .some (which returns true if any elements pass a callback test, and false otherwise)

When the match is a quote string, your

word.replace(/"/g, "").split(' ');

iterates over and checks every character of the string twice - once to check for "s to remove, and again to identify the positions of spaces. Since you already know the positions of the "s are the first and last character, you could use slice instead:

word.slice(1, word.length - 1).split(' ');

But your word variable isn't necessarily a word - it may well be a quoted string which contains multiple words. To improve clarity, maybe call it match instead.

Edited version in full:

const fn = (text, dictionary) => {
  const knownWordsSet = new Set(dictionary.toLowerCase().split(' '));
  const matches = text.toLowerCase().match(/\w+|"[^"]+"/gi);
  if (!matches) return 0;
  const resultSet = new Set();
  for (const match of matches) {
    if (match[0] == '"') {
      const wordsNoQuotes = match.slice(1, match.length - 1).split(' ');
      const shouldInclude = wordsNoQuotes.some(word => knownWordsSet.has(word));
      if (shouldInclude) {
        for (const word of wordsNoQuotes) {
          resultSet.add(word);
        }
      }
    } else if (knownWordsSet.has(match)) {
      resultSet.add(match);
    }
  }
  return resultSet.size === 0 ? 0 : [...resultSet].join('\n');
}
console.log(fn(
  `Hi. I am a developer. A "Hello world" program was my first code.`,
  "hi developer world"
));


Including the necessary polyfills for every combination of browser support

Something tells me that requirejs probably has some features to help with this, but I'm not finding them at the moment.  Your situation is complicated by the fact that you have to run custom code after es6-promise is loaded before fetch is loaded and by the fact that a usual tool for these kinds of problems is promises, but you can't use them here because they may not yet be loaded.

Here's a solution that is not less overall code, but is more DRY and is more general purpose and could be reused in other projects:

The code to do the custom loading would look like this:

var loaders = [];
if (!window.Promise) {
    loaders.push({modules: 'es6-promise', fn: function(promise) {
        promise.polyfill();
    }});
}
if (!window.fetch) {
    loaders.push({modules: 'fetch'});
}
loadSequential(loaders, run);

And, the implementation of the reusable loadSequential() would look like this:

function loadSequential(list, done) {
    var i = 0;

    // load the next item in the list
    function next() {
        var item;
        if (i < list.length) {
            item = list[i++];
            require(item.modules, function() {
                if (item.fn) {
                    item.fn.apply(this, arguments);
                }
                next();
            });
        } else {
            done();
        }
    }
    // start first iteration
    next();
}

If you can allow fetch to load potentially before promises are available, then you could use the fact that fetch presumably can't exist without promises in a native browser environment (because fetch returns a promise) and could use this shortcut:

if (!window.Promise) {
    // if there's no promise, there can't be a fetch either
    require(['es6-promise', 'fetch'], function(promise) {
        promise.polyfill();
        run();
    });
} else if (!window.fetch) {
    require('fetch', run);
} else {
    run();
}