Find the longest zigzag sequence in a array of integers

You can do this in \$O(n)\$ rather than \$O(n^3)\$. To force this, change input to an iterator. I'd also make a function that returns all the zigzags, so for [9, 8, 8, 5, 3, 5, 3, 2, 8, 6] it'd return [(9, 8), (8,), (8, 5), (5, 3, 5, 3), (3, 2, 8, 6)].

The reason you'd want to do this, is as you can then make zigzag a three line function, and you know that you're building actual zigzags of the maximum size.

There's a fairly simple algorithm that you can follow to build the zigzags:

Go through the input.
If two adjacent items are the same, yield the current zigzag, and a new zigzag only containing that duplicate item.
If three adjacent items don't zigzag, yield the current zigzag, and start a new zigzag starting at the second item.

In more depth, I achieved this by doing:

Build a stack, and add the first number to it.
Loop until you run out of items in input:

Force the stack to be a size of two. If it contains three items, only keep the last two. If it has one item, add an item from the input to it.
If the first item in the stack, is the same as the second item in the stack, yield the first item, and make a stack that only contains the second item. Restart the loop.
Store the direction of the zigzag. (find if item 1 > item 2 for example.)
Infinitely do:

Copy the previous item from the stack.
Get a new item from the input.
If the previous or current item are the same, or they are the same direction as the previous zigzag, then stop looping.
Add the current item to the stack.
Store the current state of the zigzag.

yield the stack as a tuple. (Don't want people mutating the data.)
Add the current item to the stack.

If the stack has been initialized and contains items, yield the stack as a tuple.

Which can be implemented as:

def zigzags(input):
    input = iter(input)
    stack = None
    try:
        stack = [next(input)]
        while True:
            if len(stack) < 2:
                stack.append(next(input))
            else:
                stack = stack[-2:]
            a, b = stack
            if a == b:
                yield (a,)
                stack = [b]
                continue
            zig = a > b
            while True:
                prev = stack[-1]
                this = next(input)
                if prev == this or zig == (prev > this):
                    break
                stack.append(this)
                zig = not zig
            yield tuple(stack)
            stack.append(this)
    except StopIteration:
        pass
    if stack:
        yield tuple(stack)

def zigzag(input):
    item = max(zigzags(input), key=len)
    print len(item), item


Well, mysql() is being deprecated, so be aware of that. mysqli() and pdo() are the new standards. I'd say continue learning on the old one, everything you learn can be translated to the new.

When connecting to a database, it is best to give that connection a name, such as $conn so that it can be referenced later. This is so that you can specify which connection you wish to use when selecting databases, or if you need to check if the connection is successful. Same for selecting the database. So...

$conn = mysql_connect("localhost", "myusername", "mypassword");
if( ! $conn ) {
    //handle error and exit script...
}

$companyDB = mysql_select_db("companyDB", $conn);
if( ! $companyDB ) {
    //handle error and exit script...
}

You've started output buffering (ob_start()), but not done anything with it except clear it. Usually you'll want to examine the output for errors, or dump it directly onto the page before clearing it. But for a "first" script this is fine. Just be aware that there is more to it than just starting and clearing.

Try to avoid or die() short circuiting. It works but was not intended for this purpose. die() shouldn't even be in live environments, its meant as a debugging tool. Instead you should handle any errors more elegantly, such as displaying what happened, logging errors, etc...

Be careful of magic numbers. You've told us that $row[4] is the access level, but why? What if it changes? This should probably be grabbed with a more specific SQL statement. I'm not much of  SQL guy, so I can't help you out here, but I imagine there should be a better way.

Location headers should be terminated with exit afterwards to prevent the rest of the script from running.

If you don't have anything to put in an else block, then there is no need to declare one.

You also need to close connections to your mysql using mysql_close().


What you're trying to compute here is the cost of the unit to travel to each accessible square in the region. You do it by iterating over all squares in the region, computing a path to the destination square, and adding up the cost of getting there.

Suppose that this figure shows the cost of traversing each square, and you have a unit in the square marked A:

┌───┬───┬───┬───┐
│ 1 │ 2 │ 1 │ 1 │
├───┼───┼───┼───┤
│ 2 │ 2 │ 2 │ 1 │
├───┼───┼───┼───┤
│ 1 │ 3 │ 1 │ 1 │
├───┼───┼───┼───┤
│ 1 │ 2 │ 1 │ A │
└───┴───┴───┴───┘

Then your algorithm goes like this:

┌───┬───┬───┬───┐    ┌───┬───┬───┬───┐    ┌───┬───┬───┬───┐    ┌───┬───┬───┬───┐
│ * │ . │ . │ . │    │ . │ * │ . │ . │    │ . │ . │ * │ . │    │ . │ . │ . │ * │
├───┼───┼───┼───┤    ├───┼───┼───┼───┤    ├───┼───┼───┼───┤    ├───┼───┼───┼───┤
│ . │ * │ . │ . │    │ . │ * │ . │ . │    │ . │ . │ * │ . │    │ . │ . │ . │ * │
├───┼───┼───┼───┤    ├───┼───┼───┼───┤    ├───┼───┼───┼───┤    ├───┼───┼───┼───┤
│ . │ . │ * │ . │    │ . │ . │ * │ . │    │ . │ . │ * │ . │    │ . │ . │ . │ * │
├───┼───┼───┼───┤    ├───┼───┼───┼───┤    ├───┼───┼───┼───┤    ├───┼───┼───┼───┤
│ . │ . │ . │ A │    │ . │ . │ . │ A │    │ . │ . │ . │ A │    │ . │ . │ . │ A │
└───┴───┴───┴───┘    └───┴───┴───┴───┘    └───┴───┴───┴───┘    └───┴───┴───┴───┘
1 + 2 + 1 = 4        1 + 2 + 2 = 5        1 + 2 + 1 = 4        1 + 1 + 1 = 3

and so on. There is wasted work here, because each path starts again from scratch instead of making use of previously computed information. The point is that after computing the first path above, we already know the following costs:

┌───┬───┬───┬───┐
│ 4 │ . │ . │ . │
├───┼───┼───┼───┤
│ . │ 3 │ . │ . │
├───┼───┼───┼───┤
│ . │ . │ 1 │ . │
├───┼───┼───┼───┤
│ . │ . │ . │ A │
└───┴───┴───┴───┘

and so to compute the second path we can start from the square marked "3" instead of having to start all the way back at A.

If you make this idea into an algorithm then you get Dijkstra's algorithm.

But you may be able to do better than that. If the cost of moving over a square of terrain never changes during the game, then the cost of moving along a path never changes either. So you could pre-compute the cost of all paths (using the Floyd–Warshall algorithm) and remember them.


To fix lazy/strict shuffling you need to import Text.Regex.TDFA.Text.Lazy module. It contains TDFA-related instances for Data.Text.Lazy

Some other things to consider.

You can skip maybeToList because (=~) returns m target for some monad m.

- return $ maybeToList $ (on (=~~) T.toStrict) content pattern
+ return $ (on (=~~) T.toStrict) content pattern

This will work without any further changes because (=~) will select list monad and match failure will be represented by empty list.

Do-notation for list monad can be replaced with single map and concat . map f -- with concatMap

- matches patterns content = map (T.fromStrict) $ concat $ do
-   pattern <- patterns
-   return $ maybeToList $ (on (=~~) T.toStrict) content pattern
+ matches patterns content = map T.fromStrict
+   $ concatMap ((on (=~~) T.toStrict) content) patterns

Now it's time to add import Text.Regex.TDFA.Text.Lazy and remove text conversions

- matches patterns content = map T.fromStrict
-   $ concatMap ((on (=~~) T.toStrict) content) patterns
+ matches patterns content = concatMap (content=~~) patterns

You can swap arguments and drop patterns varaible.

As for the analyse function, it's just a matter of taste but I think it is more readable to enumerate all variants in single case:

analyze likes dislikes text
  = case (matches text likes, matches text dislikes) of
    ([], _)       -> Left []
    (liked, [])   -> Right liked
    (_, disliked) -> Left disliked

For the last step you can import Text type unqaulified to make function types look cleaner.

Here is the result:

import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import Text.Regex.TDFA.Text.Lazy
import Text.Regex.TDFA

matches :: Text -> [Text] -> [Text]
matches content = concatMap ((=~~) content)

analyze :: [Text] -> [Text] -> Text -> Either [Text] [Text]
analyze likes dislikes text
  = case map (matches text) [likes, dislikes] of
    [[], _]       -> Left []
    [liked, []]   -> Right liked
    [_, disliked] -> Left disliked


Flask web application, with handling for user login status

Despite html code indeed looks nice, is there where you want to point out your efforts

Jinja supplies conditional blocks (like in python) where you can define which buttons you want to appear on screen, depending if user is logged in or not

This is a bare example

<div>
        {%+ if something %}yay{% endif %}
</div>

Following your example, your condition for user authentication can go in the template directly

{% if current_user.is_authenticated %}
  Hi {{ current_user.name }}!
{% endif %}

Feel free to read a bit more about options on templates on the following link for Jinja documentation

http://jinja.pocoo.org/docs/2.10/templates/

Enjoy the coding :)


Simple Makefile to build and run scala program

I don't know Scala, but I do know Make, so I hope this helps.
Firstly, the makefile is missing .DELETE_ON_ERROR:, which pretty much every makefile needs, to avoid part-written output files appearing up-to-date when a compilation command fails (e.g. is interrupted).
We also want .PHONY: for those targets that don't produce files, such as all and clean.  (And clean should use $(RM) rather than rm -f, for increased portability.)
I think that we want a straightforward pattern rule that says that we can make a file called foo.compile given an input called foo.scala:
%.compile: %.scala
    scalac -cp ${SCALA_FLAGS} $<

It looks to me that -cp is one of the flags to scalac, so that should probably be in ${SCALA_FLAGS} rather than in the command.
I'm not convinced that your rules actually create the files they claim to.  For example, GrammarUtil.compile depends on grammar.generate, but then actually uses grammar.scala - should grammar.generate actually be grammar.scala there?


Controller for an Administrator User, can this be improved? (codeigniter)

the very first characters should be <? to avoid whitespace from being sent in the response. This saves you from issues with header redirects. You should also omit the closing ?> for the same reason (whitespaces).

In order for this function to work it must be used before anything is outputted to the browser since it utilizes server headers.

you can use the input class's post() to check for the post request.

The function (post()) returns FALSE (boolean) if there are no items in the POST.

Here's modified code with comments:
<?php
//should be the very first characters

class Administrators extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    //factor out the login check to isolate the common logic
    //also, for understandability, boolean checks should be prefixed
    //with "is" or "has" like phrases
    //like "is it like this?", "[something] has this?"
    private function isLoggedIn(){
       return $this->session->userdata('logged_in');
    }

    public function index() {

        //use our new "isLoggedIn()"
        if(isLoggedIn()) {
            redirect('/office/dashboard/');
        } else {
            redirect('/office/administrators/login');
        }
    }

    public function login() {

        if(isLoggedIn()) {
            redirect('/office/dashboard/');
        }

        //you can use the input class's post() to check for the post request
        if($this->input->post()) {

            //for readability, it's more appropriate to
            //assign these values to verbose variables names...
            $administrator = new Administrator();
            $username = $this->input->post('email');
            $password = $this->input->post('password');

            //...so we know what arguments were sent
            if($administrator->login($username,$password)) {
                redirect('/office/dashboard/');
            } else {
                $this->messages->add('Unable to authenticate you', 'error');
            }
        }

        $data['error_messages'] = $this->messages->get('error');
        $this->load->view('/office/administrators/login', $data);
    }

    public function logout() {
        $this->simpleloginsecure->logout();
        redirect('office/administrators/login');
    }

}

//remove the closing ?>.


Unity C# - Radar works but performance is horrible (Update & LateUpdate)

Let's review the code from bottom to top.
Remove_PositionIndicatorOnEnemies

Having an underscore in a method name doesn't fit with the .NET naming guidelines.
By reverting the first if condition you can return early if enemyListHolder.activeInHierarchy is false which saves you one level of indentation.
The next if condition can be omitted because that check is done inside the loop condition.
Instead of using a for loop I would prefer a foreach loop and would restrict the items to only them where activeInHierarchy is true by a Where() clause.

Implementing the mentioned changes will lead to
private void RemovePositionIndicatorOnEnemies()
{
    if (!enemyListHolder.activeInHierarchy) { return; }

    foreach (var enemy in enemyIndicList.Where(e=> e.gameObject.activeInHierarchy))
    {
        enemy.gameObject.SetActive(false);
    }
}

Add_PositionIndicatorOnEnemies
Here, the first three points from above apply as well.

The inner for loop can be replaced by FirstOrFDefault() which is more readable.

Implementing the mentioned changes will lead to
private void Add_PositionIndicatorOnEnemies()
{
    if (!enemyListHolder.activeInHierarchy) {return; }

    for (int i = 0; i < EnemiesManager.Count; i++)
    {
        var enemy = enemyIndicList.FirstOrDefault(e=> !e.gameObject.activeInHierarchy);
        if (enemy != null)
        {
            enemy.gameObject.SetActive(true);
            Vector3 aLocatorPos = theCam.WorldToScreenPoint(satManager.GetByIndex(i).transform.position);
            aLocatorPos.z = 0;
            enemy.transform.position = aLocatorPos;
        }
    }
}

LateUpdate

Again returning early will save one level of indentation.

Implementing the mentioned changes will lead to
private void LateUpdate()
{
    if (!showIndicators_Enemies) { return; }

    if (!enemyListHolder.activeInHierarchy)
    {
        enemyListHolder.SetActive(true);
    }

    Add_PositionIndicatorOnEnemies();
}

Update

Here we can save two levels of indentation by reverting and combining the first two if conditions.

Implementing the mentioned changes will lead to
private void Update()
{
    if (!statsView_Panel.activeInHierarchy || !showIndicators_Enemies) { return; }

    if (!enemyListHolder.activeInHierarchy)
    {
        enemyListHolder.SetActive(true);
    }

    Remove_PositionIndicatorOnEnemies();
}


Let me first do a review without getting into the logic of the method.
Before I start making changes I've commented some smelly places in your original code:

//Try to use the most generic type in your arguments. You don't really need an ArrayList<>
//a List<> will suffice.
private void printString(ArrayList<String> operations, ArrayList<String> set) {
    int numerOfStrings = 0;
    int numberOfletters = 0;
    //why take a list parameter when you only use one value (the second element?!)
    String toPrint = operations.get(1);
    outOfLoop: for (int i = 0; i < set.size(); i++) {
        String[] toFind = set.get(i).split(" ");
        for (int k = 0; k < toFind.length; k++) {
            if (toPrint.equals(toFind[k])) {
                // duplicated work: toFind == splitted
                String[] splited = set.get(i).split(" ");
                for (int j = 0; j < splited.length; j++) {
                    numberOfletters += splited[j].length();
                }
                numerOfStrings = splited.length;
                //goto is considered evil
                //Besides, goto to label is not neccessary here.
                //A simple `break` would suffice
                break outOfLoop;
            }
        }
    }
    //you should return the results and let the caller of the method
    //decide what to do with them
    System.out.println(numerOfStrings + " " + numberOfletters);
}

So, in the first refactoring iteration I've ended up with:

public static class Result {
    public final int numerOfStrings;
    public final int numberOfletters;

    public Result(int numerOfStrings, int numberOfletters) {
        this.numerOfStrings = numerOfStrings;
        this.numberOfletters = numberOfletters;
    }

    @Override
    public String toString() {
        return numerOfStrings + " " + numberOfletters;
    }
}

private Result process(String word, List<String> set) {
    int numerOfStrings = 0;
    int numberOfletters = 0;

    for (int i = 0; i < set.size(); i++) {
        String[] toFind = set.get(i).split(" ");
        for (int k = 0; k < toFind.length; k++) {
            if (word.equals(toFind[k])) {
                String[] splited = set.get(i).split(" ");
                for (int j = 0; j < splited.length; j++) {
                    numberOfletters += splited[j].length();
                }
                numerOfStrings = splited.length;
                break;
            }
        }
    }
    return new Result(numerOfStrings, numberOfletters);
}

@Test
public void run() throws Exception {
    Result result = process("foo", Arrays.asList("car tree hotel","foo lemon coffe"));
    System.out.println(result);
}

This keeps the method logic intact, but fixes all the issues I mentioned in the comments.

But actually I think the method could be a lot simpler:

private Result process(String word, Iterable<String> set) {
    for (String string : set) {
        if(string.contains(word)) {
            //" +" is a regex patten for "one or more spaces"
            int numberOfWords = string.trim().split(" +").length;
            int numberOfLetters = string.replace(" ", "").length();
            return new Result(numberOfWords,  numberOfLetters );
        }
    }
    return new Result(0, 0);
}

This version is more readable, but could be optimized for performance. As always with performance you should first check if optimizing here would make any impact on the application as a whole. Sacrificing readability might not be worth it.

Optimizations might include:

avoid new string creation using trim()
avoid new string array creation using split()
avoid new string creation using replace()
avoid iterating over string multiple times - count letters and words while looking for word (instead of contains)


SQL (and thus SQLite) support a variety of operators suitable (amongst others) in UPDATE statements.

This means that you can simplify your whole loop into a single statement:

query = '''
    UPDATE Test SET Test2 = (Test2 + ?), Test3 = (Test3 + ?)
    WHERE Test1 >= 0 AND Test1 < 200
'''
c.execute(query, (200, 400))

Also you should take the habit to use perf_counter instead of time to measure elapsed time. Or use the dedicated timeit module.


Make helper functions private
Member functions that are not part of the public API should be marked private.
You should know that by now :)
Use uint64_t instead of size_t
There is no guarantee that size_t is big enough for the calculations you are doing. While you might only need 32 bits to store the results, you need to do the calculations using 64 bit integers (because you are multiplying two numbers that are each up to 30 bits in size). So to be safe, I would use uint64_t. You could use uint32_t as well, but then you need to explicitly cast to uint64_t before doing the multiplications inside numDecodings().
Use size_t for sizes and counts, but not for other purposes.
Make the decode() functions constexpr
I see you made MOD constexpr, which is great, but you can make the decode() functions constepxr as well.
Naming things
a_num_ast and b_num_ast are weird looking names. I'm guessing by a_num_ast you mean "a variable that can hold a number or an asterisk". But you shouldn't try to encode the type in the variable name. Just use a and b here.
What does decodes_dp mean? I would try to give it a better name. Use nouns for variables. Perhaps number_of_possibilities, or num_decodings (although that almost clashes with the function name).
Use std::array for fixed-length vectors
This avoids unnecessary heap allocations. So:
std::array<uint64_t, 3> decodes_dp{1, decode(message[0]), 0};

Remove unnecessary modulo operations
In the following expression:
decodes_dp[index % 3] = (
        decodes_dp[(index - 1) % 3] * decode(message[index - 1]) % MOD +
        decodes_dp[(index - 2) % 3] * decode(message[index - 2], message[index - 1]) % MOD
    ) % MOD;

Since you already need to use uint64_t for the result of the multiplications to not wrap, you don't need the modulo operations inside the outermost parentheses.
Consider using switch-statements
Your decode() functions can be rewritten as follows:
inline uint64_t Solution::decode(const char a) {
    switch(a) {
        case '0':
            return 0;
        case '*':
            return 9;
        default:
            return 1;
    }
}

inline uint64_t Solution::decode(const char a, const char b) {
    switch(a) {
        case '0':
            return 0;
        case '1':
            return b == '*' ? 9 : 1;
        case '2':
            switch(b) {
                case '0'...'6':
                    return 1;
                case '*':
                    return 6;
                default:
                    return 0;
            }
        case '*':
            return decode('1', b) + decode('2', b);
        default:
            return 0;
    }
}

It's more compact and avoids repeating a lot of if (a_num_ast ...), making it easier to see the structure of your code.


The only purpose of this script appears to be to illustrate the use the Array.prototype.slice.call "idiom" and the forEach function. So it's hard to make "improvements" when the purpose of the code isn't its actual result (which is trivial).

What the code actually does can be done in a number of ways, some of which won't (directly) use forEach and/or NodeList and/or slice.call. In that case, is it still an improvement? Conversely, sticking to forEach etc. doesn't leave much room for change, since the code seems designed as a minimal example of those things.

I'm hesitant to write any code, because I'm not sure what the point would be.

With that said,

Don't rely on W3 Schools (this site lists several reasons and better alternatives)
Avoid document.write() - or use it with open eyes (see why here)
I'd also avoid forEach in favor of a standard for loop, since forEach is not universally supported in browsers (see caniuse.com)
The page's text appears to betray some confusion. Yes, the DOM is useful, and yes, the code demonstrates forEach. But forEach isn't part of the DOM. The whole point is that a NodeList object is a DOM object and not a normal array. It must therefore be converted to one by way of Array.prototype.slice.call. Then one can use forEach which is an array function but which, in and of itself, has nothing to do with the DOM.

Update after reading @PM77-1's comment:

There's nothing inherently wrong with this code. It is true, that
A) for...in doesn't behave like it does in Java and shouldn't be used here, and that
B) getElementsByTagName doesn't return a "real" array. The slice.call trick is indeed the "standard" way of converting an "array-like" object (which you find a lot of, unfortunately) to a real array. A very useful trick to know.

So all in all, the code is basically fine. Yes, improvements can be made, as @Palacsint points out in his answer, but there's nothing terrible going on.

However, while a NodeList object isn't a real array, one can still use a regular old for loop:

var nodes, i;

nodes = document.getElementsByTagName("p");
for(i = 0 ; i < nodes.length ; i++) {
  document.write(nodes[i].innerHTML);
  document.write("
");
}

This removes the need for the slice.call trick, and it works on old browsers (where forEach doesn't exist).

In general, though, when working with the DOM, it's useful to use a library to iron out the otherwise frustrating differences between browsers. jQuery is the king of the hill these days, and with that, you'd do something like this to find and iterate over some elements:

$("p").each(function () {
  document.write(this.innerHTML);
  document.write("
");
});

(Of course, jQuery also makes it easy to do "proper" DOM insertion without resorting to document.write, but this is just for illustration)

However, I do think it very wise to learn the nitty-gritty of JS, and not just run straight for jQuery or its ilk. And dealing with those "array-like" is one of those nitty-gritty things indeed.


Generate a nested structure based on a list of file paths

You can split each path at / using split and then use reduce() to build that object.

var paths = [
  'RootFolder/FolderA/FolderB/FileA',
  'RootFolder/FolderA/FolderB/FileB',
  'RootFolder/FolderA/FolderB/FolderC/FileA',
  'RootFolder/FolderA/FolderB/FolderC/FileB'
]

var obj = {}
paths.forEach(function(path) {
  path.split('/').reduce(function(r, e) {
    return r[e] || (r[e] = {})
  }, obj)
})

console.log(obj)

Here is how you can use this approach to read some directory and all of its nested content and create object from that. This approach is synchronous.

var fs = require('fs');
var path = require('path');

var p = path.resolve('C:\\your\\path\\here')
var result = {}

function buildObject(startPath) {
  var dir = fs.readdirSync(startPath)
  dir.forEach(function(e) {
    var newPath = path.join(startPath, e)

    var stat = fs.statSync(newPath);
    if (stat && stat.isDirectory()) buildObject(newPath)
    if (stat.isFile()) {
      newPath.split('\\').reduce(function(r, a) {
        return r[a] || (r[a] = {})
      }, result)
    }
  })
}

buildObject(p)
console.log(result)


new Pen(y)

This should be disposed.

Graphics g = Application.OpenForms["Client"].CreateGraphics();

I wonder why are you getting the Graphics object like this? To redraw something you should actually handle the Paint event or override the OnPaint method where you get a ready to use Graphics object from the system. And of course like @Cody Gray said, you need to dispose a graphics object acquired this way.

Those try/catch blocks are suspicious too. There is nothing that could throw an exception. If this runs every 100ms there is no room for exception handling. This would be very bad for the performance.


I think you are trying to do some pattern matching on strings.

So I did this:

def escape(s: String): String = Seq("{", "}", "whatever").foldLeft(s)((x, y) => x.replaceAllLiterally(y, "\\" + y))

def removeBlocks(text: String, open: String, close: String): String = {
    val startReg = (s"${escape(open)}(.*)$$").r
    val endReg = (s"${escape(close)}(.*)$$").r
    val otherText = "(.)(.*)$".r

    @tailrec
    def removeBlocksAux(text: String, acc: String = "", lvl: Int = 0): String = {
        assume((text.length() > 0 || lvl == 0) && lvl >= 0)
        (text, lvl) match {
            case (startReg(text), lvl)     => removeBlocksAux(text, acc, lvl + 1)
            case (endReg(text), lvl)       => removeBlocksAux(text, acc, lvl - 1)
            case (otherText(c, text), 0)   => removeBlocksAux(text, acc + c)
            case (otherText(c, text), lvl) => removeBlocksAux(text, acc, lvl)
            case ("", _)                   => acc
        }
    }
    removeBlocksAux(text)
}

I tried to find a way to define the regular expressions inside the match group, but I failed at that, it may not be a good idea after all, but I would like to have a more compact and efficient representation for it. The escape function should escape all special cases of operators in Scala regex, that sounds boring, so there may be already a method for that.

I'm also not a big fan of having a function inside a function, but I kept that design decision. Finally, I'd simply use parser combinators for this, but I guess that's not the point.


Too many for-loops and conditional operators

If you have not done so. I recommend picking up the book Refactoring: Improving the Design of Existing Code by Martin Fowler. It is an excellent book on exactly this topic.

One thing you can start with is to split the method by extracting each operation into a separate method. So that instead of doing everything at once you end up with a method per operation.

Doing so will let you examine what your code is actually doing and helps you see the patterns. Something like this:

private void checkForOverage(List<GoogleUsageMapping> records) {
    long allocatedSize = sumAllocated(records);
    long logicalSize = sumLogical(records);
    checkAllocated(records,allocatedSize, logicalSize);
    checkLogical(records,allocatedSize, logicalSize);
}

private long sumAllocated(List<GoogleUsageMapping> records) {
    long sumOfAllocatedSize = 0L;
    for (GoogleUsageMapping record : records) {
        if (record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {
            sumOfAllocatedSize += record.getUsage().getQuantity().longValue();
        }
    }
    return sumOfAllocatedSize;
}

private long sumLogical(List<GoogleUsageMapping> records) {
    long sumOfLogicalSize = 0L;
    for (GoogleUsageMapping record : records) {
        if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
            sumOfLogicalSize += record.getUsage().getQuantity().longValue();
        }
    }
    return sumOfLogicalSize;
}

private void checkAllocated(List<GoogleUsageMapping> records, long allocatedSize, long logicalSize) {
    for (GoogleUsageMapping record : records) {
        if (allocatedSize >= logicalSize && record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
            record.setState(GoogleTrackingState.IGNORED_OVERAGE);
        }
    }
}

private void checkLogical(List<GoogleUsageMapping> records, long allocatedSize, long logicalSize) {
    for (GoogleUsageMapping record : records) {
        if (logicalSize > allocatedSize && record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {
            record.setState(GoogleTrackingState.IGNORED_OVERAGE);
        }
    }
}

As you can see both pairs of methods are nearly identical. All you have to do to unify them is to extract the difference as parameter.

private void checkForOverage(List<GoogleUsageMapping> records) {
    long allocatedSize = sumByType(records, MeasuredType.ALLOCATED_SIZE);
    long logicalSize = sumByType(records, MeasuredType.LOGICAL_SIZE);
    check(records, allocatedSize >= logicalSize, MeasuredType.ALLOCATED_SIZE);
    check(records, logicalSize > allocatedSize, MeasuredType.LOGICAL_SIZE);
}

private long sumByType(List<GoogleUsageMapping> records, MeasuredType type) {
    long sumOfAllocatedSize = 0L;
    for (GoogleUsageMapping record : records) {
        if (record.getUsage().getMeasuredType() == type) {
            sumOfAllocatedSize += record.getUsage().getQuantity().longValue();
        }
    }
    return sumOfAllocatedSize;
}

private void check(List<GoogleUsageMapping> records, boolean condition, MeasuredType type) {
    for (GoogleUsageMapping record : records) {
        if (condition && record.getUsage().getMeasuredType() == type) {
            record.setState(GoogleTrackingState.IGNORED_OVERAGE);
        }
    }
}


strings of any length as binary numbers

Why are they strings? Something like bool[] would fit much better and it would also make your code simpler.

string a, string b

Those are not very good names. maybe use something like left and right or first and second?

In production code, you should verify that parameters fit your requirements (in your case, that the string contains only '0's and '1's) and throw an exception otherwise.

if (a.Length < b.Length)
{
    string c = a;
    a = b;
    b = c;
}

A simpler way to write this would be to use recursion:

if (a.Length < b.Length)
{
    return BinAdd(b, a);
}

bool addLeft = false;

A better name for this variable would be carry.

char c = '1';
bool add = addLeft;
addLeft = false;

if (j >= 0)
{
    if (a[i] == '1' && b[j] == '1')
    {
        c = '0';
        addLeft = true;
    }
    else if (a[i] == '0' && b[j] == '0')
    {
        c = '0';
    }
    else if (add)
    {
        addLeft = true;
    }
}
else
{
    if (a[i] == '0')
    {
        c = '0';
    }
    else if (add)
    {
        addLeft = true;
    }
}

sb.Append(add ? (c == '1' ? '0' : '1') : c);

All this logic could be simplified by a lot by using a variable to count the ones (including carry). Something like (not tested):

int sum = 0;

if (j >= 0 && b[j] == '1')
    sum++;

if (a[i] == '1')
    sum++;

if (addLeft)
    sum++;

sb.Append(sum % 2);

addLeft = sum / 2 == 1;

char[] cx = new char[sb.Length];
sb.CopyTo(0, cx, 0, sb.Length);
Array.Reverse(cx);

return new string(cx);

Instead of this, you could start with List<char> instead of StringBuilder, Reverse() that and then create a string out of it (possibly using string.Join(null, digits), assuming you name the list digits).


Finding the distance between every indices in an array that contain odd numbers

Code organisation

You've separated the input/output from the actual algorithm and that's a very nice thing that is not done as often as it should be in questions tagged with programming-challenge.

The only thing I'd change about the way you've done this is that the min_bread function does not need to be provided the N value as it should correspond to the length of the breads argument.

Loop like a native

I highly recommand Ned Batchelder's excellent talk called "Loop Like A Native". Among other things, it tells you that in general, you should not use a combination of range (or xrange) and len to iterate over something.

At this stage, the code looks like:

def min_bread(breads):
    oddcount = 0
    oddindices = []
    for i, val in enumerate(breads):
        if val % 2:
            oddcount += 1
            oddindices.append(i)
    # Odd number of odd loaves make it impossible to distribute
    if oddcount % 2:
        return "NO"
    # All are odd (return that number) or even (return 0)
    if oddcount==len(breads) or oddcount == 0:
        return oddcount
    loaves = 0
    for idx in xrange(0, oddcount, 2):
        loaves += (oddindices[idx+1] - oddindices[idx])*2
    return loaves

Details

You don't need to compute oddcount as you build oddindices, you can simply do oddcount = len(oddindices) after the loop.

Also, now you have a nice way to initialise oddindices. Indeed, in Python, the pattern l = []; for i in iter: if filter(i): l.append(func(i)) can be rewritten using a structure called "list comprehension" to get : l = [func(i) for i in iter if filter(i)].

In your case, you get:

oddindices = [i for i, val in enumerate(breads) if val % 2]
oddcount = len(oddindices)

Multiply once

You multiply by 2 each value you add to loaves. You could do it only once at the very end.

Sum builtin

You could use the sum builtin to perform the sums efficiently.

You'd get something like:

return 2 * sum(oddindices[idx+1] - oddindices[idx] for idx in xrange(0, oddcount, 2))

Then, the whole code looks like:

def min_bread(breads):
    oddindices = [i for i, val in enumerate(breads) if val % 2]
    oddcount = len(oddindices)
    # Odd number of odd loaves make it impossible to distribute
    if oddcount % 2:
        return "NO"
    # All are odd (return that number) or even (return 0)
    if oddcount==len(breads) or oddcount == 0:
        return oddcount
    return 2 * sum(oddindices[idx+1] - oddindices[idx] for idx in xrange(0, oddcount, 2))

Avoiding the additional array

A different way to write this without an additional array is to see that the different indices of odd values are substracted, then added, then substracted, etc. Also, you have to perform as many additions as substractions. We could use a simple flag to handle both the alternance of sign and the check that we've performed the same number of additions and substractions. For instance (highly not tested):

def min_bread(breads):
    sign = -1
    loaves = 0
    for i, val in enumerate(breads):
        if val % 2:
            loaves += sign * i
            sign *= -1
    return "NO" if sign == 1 else 2 * loaves


It's not exactly well-documented. You can sort of determine what the "Knapsack problem" is by looking at a few comments and some variable names, but if I were the developer, I'd probably add a comment block to describe how it works in case someone else came upon this code later and needed to understand it quickly.

I'm not quite sure why they didn't just use Math.Max instead of creating their own function (maybe they ported it from some other language that didn't have that function handy?).

Aside from those things, if it's functional and returns accurate results, then I don't see a huge problem with it.


Printing a list of items to the console is inherently imperative. But keeping track of lots of state between iterations using higher-order functions is often inelegant. Regardless, there are some things you can do to clean this up and (if you're compelled) get rid of mutables. Most notably, you can use tuples instead of arrays/lists with an assumed width.

I'm not familiar with this algorithm, so I've merely translated what you have. You can implement it using a pair of mutually recursive functions. This allows you to "persist" the weight values between iterations.

let rate = 0.2
let threshold = 2.0

let inline output a b weightA weightB = if threshold > a * weightA + b * weightB then 0.0 else 1.0
let inline display output real = printfn <| if output = real then "yes" else "no"
let inline computeWeight weight c out = weight + rate * (c - out)

let matrix =
  [|
    0.0, 0.0, 0.0
    0.0, 1.0, 1.0
    1.0, 0.0, 1.0
    1.0, 1.0, 1.0
  |]

let rec iter n weightA weightB =
  if n > 0 then
    loop n 0 weightA weightB
and loop n i weightA weightB =
  if i < matrix.Length then
    let a, b, c = matrix.[i]
    let out = output a b weightA weightB
    let weightA = computeWeight weightA c out
    display out c
    let out = output a b weightA weightB
    let weightB = computeWeight weightB c out
    display out c
    loop n (i + 1) weightA weightB
  else iter (n - 1) weightA weightB

Usage:

let initialWeightA = 0.4
let initialWeightB = 0.6
iter 100 initialWeightA initialWeightB

loop could be implemented as a fold, but fold is not typically used with side-effects.


The Rss helper functions are inside the parse function, even though they don't use any of the state inside that scope. Consider moving these up to the module level, even though they are not used anywhere else. By doing this the main function is shorter and easier to follow. You could also make those functions private when you pull them out.
Seq.cast can throw an exception. Even though you know that every item will be an XmlNode in this case, it can be safer to filter out objects that are not of the required type while casting. Unfortunately, F# doesn't have a function for this in the Seq module but you can always use the one already in .NET: channelNode.ChildNodes |> System.Linq.Enumerable.OfType<XmlNode>

You fetch the RSS feed in the constructor of BlogController. This will happen once for each request. Using Async.RunSynchronously will block a thread, so you lose the benefit of using Async in the first place. You should avoid Async.RunSynchronously whenever you can. You can pull out the RSS fetching and parsing into another function that returns an async. Call this function from each controller method, do more async processing if necessary and then use Async.StartAsTask to return a task from the method. ASP.NET will then be able to run your code without unnecessary blocking.

EDIT:

I'm not too familiar with ASP.NET MVC, but based on this issue I think something like this should work:

let fetchRss() = async {
    let! content = fetchUrl "https://christopherjmcclellan.wordpress.com/feed/"
    return Rss.parse content }

type BlogController() =
    inherit Controller()

    member this.Index() = async {
        let! rss = fetchRss()
        return this.View(rss.Channel) }


Exit the check early

Basically, you have a recursive traversal operation that traverses the two input trees sort of in parallel. The advantage of that approach is that you may exit algorithm as soon as you get to a pair of corresponding nodes with different values:

def bst_trees_are_identical_impl(p, q):
    if not p and not q:
        return True
    if p and q:
        if p.val != q.val:
            return False
        if not bst_trees_are_identical_impl(p.left, q.left):
            return False
        if not bst_trees_are_identical_impl(p.right, q.right):
            return False
        return True
    return False

def bst_trees_are_identical(p, q):
    return bst_trees_are_identical_impl(p, q)

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        return bst_trees_are_identical(p, q)

Hope that helps.


Rewriting to single pipeline by using data flow blocks

Isn't it possible to rewrite the code to a single pipeline without
  creating an instance of a nested pipeline for each message?

It really seems a hard task because you are putting the pipeline building logic into the transform Method. Create a method to build your pipeline, it is really asking for it!

private static PipelineType _pipeline;
private static PipelineType BuildPipeline(Message<int> input){
    if(_pipeline != null){
        _pipeline.Post(input.Items);
        _pipeline.Complete();
        return _pipeline;
    }
    var linkOpts = new DataflowLinkOptions { PropagateCompletion = true };

    var itr = new TransformManyBlock<IList<int>, int>(x => x);
    var multiply = new TransformBlock<int, int>(x => x * 10);
    var convert = new TransformBlock<int, string>(x => "STR-" + x);

    itr.LinkTo(multiply, linkOpts);
    multiply.LinkTo(convert, linkOpts);

    _pipeline = DataflowBlock.Encapsulate(itr, convert);

    _pipeline.Post(input.Items);
    _pipeline.Complete();

    var buffer = new BufferBlock<string>();
    _pipeline.LinkTo(buffer);

    return _pipeline;
}

To be able to acess the buffer in your transform method you should set it public. But actually the best option would be that await pipeline.Completion would return the result you need.


Simple script to find the largest number palindrome

For getting integers (or any other data that needs to be validated) from the user, sometimes it's best to create a separate function that you can call. For example:

static int GetIntFromUser(string prompt)
{
    int input;

    while (true)
    {
        if (prompt != null) Console.Write(prompt);
        if (int.TryParse(Console.ReadLine(), out input)) break;
        Console.WriteLine("Sorry, {0} is not a valid integer. Please try again.", input);
    }

    return input;
}

Then you can use it like:

int max = GetIntFromUser("Enter the maximum value for these numbers: ");
int min = GetIntFromUser("Enter the minimum value for these numbers: ");


You can use Bit Twidding Hack to determine if int32 or int64 has no zero bytes: http://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord

If it has not you can copy whole int32 or int64. So it will be 4 operations for searching zero byte in 8 bytes (in int64 case). It looks like true optimization.

char * strcpy(char * dst, const char * src)
{
    char * origin = dst;

    while (!((((*(uint64_t *)src) - 0x0101010101010101ULL)
           & ~(*(uint64_t *)src) & 0x8080808080808080ULL)))
    {
        *(uint64_t *)dst = *(uint64_t *)src;
        src += 8;
        dst += 8;
    }

    while (*dst++ = *src++)
       ;

    return origin;
}

Simple strcpy implementation uses 8 compares to zero and 8 byte copyings for each 8 bytes of source string. My implementation uses 4 operation for checking for zeros and 1 operation to copy for 8 bytes. So we have 5ops vs 16ops. Not all ops have same speeds so it is not easy to compare real speedup. We need some benchmarks, is anyone free?


Creating a string from command line arguments

In the last lines of your question, what you mention is C being a procedural language. This means, you should split your semantic logic into reusable smaller logical bits and implement smaller portions of your code and implement your program by using the functions you implemented.

Although, as you come from a object-oriented language, I believe you must be familiar with the concepts I mentioned.

Coming to your example, your program consists of a fairly small codebase and it does these things:

Iterate through the argv strings
Combine the argv strings in another string

But if I did not misunderstand, your first iteration is to find the count of the arguments. That is what argc variable, therefore your first while loop is unnecessary, you can simply set size = argc - 1;

You have an unnecessary condition check and this part is unnecessary:

strcat(str, argv[1]); // putting the string together
strcat(str, " ");
strcat(str, argv[2]);
strcat(str, " ");

You should start your for loop from 1 instead of 3, and remove these lines.

Your condition check also seems unnecessary, as your for for loop would produce similar results.

Therefore, I would not say that this code is bad due to not being written in procedural paradigm, but it is bad due to overall unnecessary lines of code.

A shorter approach would be:

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

int main(int argc, char *argv[]) {
    if(argc == 1) {
        printf("ERROR: Expected at least 1 argument\n");
        return 0;
    }

    int i, v = 0, size = argc - 1;

    char *str = (char *)malloc(v);

    for(i = 1; i <= size; i++) {
        str = (char *)realloc(str, (v + strlen(argv[i])));
        strcat(str, argv[i]);
        strcat(str, " ");
    }

    printf("%s\n", str);
    return 0;
}


I am not sure how to 'review' your code in this case.... I have a sense of 'competition' here, and the moment performance enters the equation, there are things I just know are going to be slower, but I cannot always explain why.....

I think often times it simply comes down to primitives vs. Object creation.... whenever that happens things slow down.

I have put together a 'competing' solution, and it uses tricks I have learned over the years... tricks I feel, for the most part, lead to 'fast' code. I have been accused of 'premature optimization' when I do these things, but, it tends to work for me.... ;-)

printing Strings is never going to be a good measure of performance, so I have taken three solutions: the recursive solution I suggested in the earlier post. Your solution using the iterator, and then a 'competing' iterator performance.

So, in my benchmarks, this iterative process is about 5 times faster than yours.... (excluding the System.out.println()):

here are my results (times in milliseconds on my machine):

200_Success=2045.091 rolflIter=446.846=rolflRecur 2046.462011
200_Success=1737.469 rolflIter=573.900=rolflRecur 1521.951070
200_Success=1814.468 rolflIter=385.520=rolflRecur 1499.896568
200_Success=1714.592 rolflIter=333.105=rolflRecur 1372.042103
200_Success=1799.969 rolflIter=383.033=rolflRecur 1520.779467
200_Success=1676.415 rolflIter=336.651=rolflRecur 1474.669545
200_Success=1978.581 rolflIter=407.804=rolflRecur 1417.124248
200_Success=1665.783 rolflIter=343.939=rolflRecur 1375.178203
200_Success=1654.083 rolflIter=331.607=rolflRecur 1369.912767
200_Success=1654.958 rolflIter=339.234=rolflRecur 1369.170302

Edit:
New results ... note, 200_success is also running faster here....
Hate performance variances ... probably a Windows/Intel CPU frequency thing.

200_Success=1463.484 rolflIter=624.754 rolflRecur=1777.548864
200_Success=1304.401 rolflIter=302.086 rolflRecur=1492.951479
200_Success=1577.132 rolflIter=367.537 rolflRecur=1485.176134
200_Success=1230.959 rolflIter=266.068 rolflRecur=1389.742206
200_Success=1230.445 rolflIter=269.587 rolflRecur=1382.473980
200_Success=1220.637 rolflIter=269.352 rolflRecur=1376.292369
200_Success=1204.206 rolflIter=266.920 rolflRecur=1369.920239
200_Success=1201.280 rolflIter=264.481 rolflRecur=1365.711999
200_Success=1204.419 rolflIter=262.047 rolflRecur=1368.854637
200_Success=1251.656 rolflIter=264.030 rolflRecur=1416.935596

Main class:

package comp;

import java.util.Iterator;

public class RunParts {

    private static int charsIn(Iterator<String> iter) {
        int chars = 0;
        while (iter.hasNext()) {
            chars += iter.next().length();
        }
        return chars;
    }

    public static void main(String[] args) {
        final int target = Integer.parseInt(args[0]);
        long[] nanos = new long[3];
        int[] charlen = new int[3];
        for (int i = 0; i < 10; i++) {
            System.gc();
            nanos[0] = System.nanoTime();
            charlen[0] = charsIn(new Partition(target));
            nanos[0] = System.nanoTime() - nanos[0];

            System.gc();
            nanos[1] = System.nanoTime();
            charlen[1] = charsIn(new PartitionRLIter(target));
            nanos[1] = System.nanoTime() - nanos[1];

            System.gc();
            nanos[2] = System.nanoTime();
            charlen[2] = PartitionRLRecur.partitionRL(target);
            nanos[2] = System.nanoTime() - nanos[2];

            System.out.printf("200_Success=%.3f rolflIter=%.3f rolflRecur=%3f\n",
                    nanos[0] / 1000000.0, nanos[1] / 1000000.0, nanos[2] / 1000000.0);
        }

    }

}

Your solution is above (I have left it called 'Partition').

Then my iterative solution is...

EDIT:
I have edited my solution to add comments. As I was adding the comments I realized that a lot of the logic in the advance() method was related to setup of the system.
I have moved the setup to the constructor, and by verifying a couple of things, I am now able to guarantee a couple of behavioral advantages that mean I don't need a few of the loops in the system. I have updated my results now as well.

package comp;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class PartitionRLIter implements Iterator<String> {

    private final int[] stack;
    private final int[] outpos;
    private final StringBuilder outstring;
    private final int limit;
    private boolean hasnext = true;
    private int spos = 0;

    public PartitionRLIter(int n) {
        if (n <= 0) throw new IllegalArgumentException();
        limit = n;
        stack = new int[limit];
        outpos = new int[limit];
        // NOTE THAT THE CONSTRUCTOR NOW MANUALLY INITIALIZES THE SYSTEM
        outstring = new StringBuilder(limit * 2); // worst case is "1 1 1 1 1 ...";
        Arrays.fill(stack, 1);
        for (int i = 0; i < limit; i++) {
            outpos[i] = outstring.length();
            outstring.append("1 ");
        }
        hasnext = true;
        spos = limit - 1;
    }

    @Override
    public boolean hasNext() {
        return hasnext;
    }

    @Override
    public String next() {
        if (!hasnext)
            throw new NoSuchElementException();

        try {
            return outstring.substring(0, outstring.length() - 1);
        } finally {
            hasnext = advance();
        }
    }

    private final boolean advance() {
        // advance() keeps four 'stack-like' variables in sync
        // advance() will only ever be called when the current system has a valid answer
        //
        // **stack** contains the digits that get summed... It is the 'real stack'. The constructor initializes it to all 1's.
        //
        // **spos** is our depth in the stack.
        //
        // the **outstring** is a StringBuilder that is kept in sync with the actual stack...
        //     reusing the StringBuilder makes it much faster... but we need to manage it like a stack.
        //     when you go deeper in the stack, the outstring has values added to it,
        //     when you come back up, the outstring is truncated to remove unneeded characters.
        //     very much like push and pop operations (except at the end of the string, not the front)
        //
        // the **outpos** is the array of integer positions in the outstring StringBuffer that
        //     keeps track of where the outstring should be truncated at each level.
        //     this is what allows working push/pop on the outstring.
        //

        // back up..... the stack, we always know we are already at the limit.
        // pop the value off (keep sum in sync).
        int sum = limit - stack[spos];
        if (--spos < 0) {
            // we ran out of things to do, there's no more possibilities.
            return false;
        }

        // on the previous level, we increment....
        // we can never overflow the previous level because
        // of the way the math works (we would not have a next level if we can't increment this one).
        stack[spos] ++;
        sum++;

        // pop the previous value(s) off the stack representation.
        // outpos[spos] contains the character position in the output representing
        // our current depth.
        outstring.setLength(outpos[spos]);

        // check to see whether adding a new level of depth will work.....
        // the new level will have the same value as the stack's current value...
        while (sum + stack[spos] <= limit) {
            // yes, the new level will work.
            // update our string stack, sum, and record the character position of the outstring.
            outstring.append(stack[spos]).append(" ");
            sum+= stack[spos];
            stack[spos + 1] = stack[spos];
            spos++;
            outpos[spos]=outstring.length();
        }

        // take the new depth and increment it (if needed) to the limit.
        stack[spos] += limit - sum;
        outstring.append(stack[spos]).append(" ");
        return true;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

Finally, my Recursive solution is (note, it has been modified to return the string length, not the string itself):

package comp;

public class PartitionRLRecur {

    public static int partitionRL(final int n)
    {
        return recursivePartition(n, 1, new int[n], 0);
    }

    private static int recursivePartition(final int target, final int from, final int[] stack, final int stacksize)
    {
        if(target == 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < stacksize; i++) {
                sb.append(stack[i]).append(" ");
            }
//            System.out.println(sb.toString());
//          );
            return sb.toString().length();
        }
        int sz = 0;
        for(int i = from; i <= target; i++) {
            stack[stacksize] = i;
            sz += recursivePartition(target-i, i, stack, stacksize + 1);
        }
        return sz;
    }

}


Here's an O(n) solution. It replaces the Map with a char-indexed vector of the index where each char was last seen.

public static int lengthOfLongestSubstringNoRepetitions(String s) {

    if (s == null)
        return 0;

    // Trimming input even for the non-empty case is more consistent.
    final String str = s.trim();

    if (str.equals(""))
        return 0;

    int seen[] = new int[Character.MAX_VALUE+1];
    for (int i = 0; i <= Character.MAX_VALUE; ++i)
        seen[i] = -1;

    int max = 1;
    int len = 0;

    for (int j = 0; j < str.length(); ++j) {
        char ch = str.charAt(j);
        // If ch was recently seen,
        // counting must restart after the last place it was seen.
        // Otherwise, it adds 1 to the length.
        len = Math.min(j-seen[ch], len+1);
        if (len > max)
            max = len;
        seen[ch] = j;
    }
    return max;
}


Code organization

Rather than having your code in the global namespace, it's better to wrap it into a method, for example:

def gen_random_number():
    randomNumber = random.randint(1, z)
    print "first random", randomNumber
    # ...

And call the method like this:

if __name__ == '__main__':
    gen_random_number()

Magic numbers

Avoid using "magic numbers": the numbers 40, 100, 35, 93 are "magic" because it's unclear what they are and why. If you put them in capitalized constants near the top of the file with a good name, it becomes much clearer what they are and their purpose, for example:

LOWER_BOUND = 40
UPPER_BOUND = 100

z = random.randint(LOWER_BOUND, UPPER_BOUND)

For 40 and 100 it was easy enough to guess what they are and give these names. But for 35, 93 I'm not sure. If you had given them a name, I wouldn't have to wonder.

Formatting

There is an official standard Python style guide called PEP8. I suggest to read and follow that, it will make it easier for others to review your code. There is command line utility called pep8 that can detect coding style violations. You can install it with pip install pep8, and run it on your script (or even an entire directory) simply with pep8 path/to/your/code.

Your code reformatted and variables renamed to follow PEP8 would look like this:

random_number = random.randint(1, z)
print "first random", random_number

if 35 >= random_number:
    new_random = random_number * .5
    new_random += 9
    print "second random " "%.f" % new_random

elif 36 <= random_number <= 93:
    new_random = random_number + 7
    print "second random " "%.f" % new_random

else:
    new_random = random_number
    print "second random", new_random

Although PEP8 doesn't complain about this:

print "second random " "%.f" % new_random

There's no need to put a space between those two strings, so you can write it simply:

print "second random %.f" % new_random

You could further simplify this:

new_random = random_number * .5
new_random += 9

to this:

new_random = random_number * .5 + 9


Using a bool flag to determine whether in root-level or not

As you see, the method has a third parameter (inRecursion), which indicates whether the method is in recursion, or not. I use it, to remove the leading / in the path.

You need this flag because your function is doing to much. It violates the S (Single responsibility principle) in SOLID. It's not only resolving the elements but it's building the final result at the same time. The method should actually only return a List<string> with all the names (or other itmes) it found so that you can do what ever you need to do with it like:

var names = GetNames(...);
var path = string.Join("/", names);

It doesn't matter if you use recursion or a stack or any other method. The most important part is that it should only do one thing: return a collection of items.

What if you wanted to use a different delimiter such as \ or .? You'd need a new parameter for it. However, if you only have a list of names it's much easier to change it and build a different path because this is another responsibility.


The code can be structured better, so the code is more self-documenting.
Self-documenting code doesn't need as many comments, which makes it easier on everyone. Comments that aren't there can't be obsolete either.

Take input (height)
Output pyramid

Those are the only lines I want to see in main. The rest should be in functions.
You started out nicely by creating a print_hashes function, but we can do better. For example, the entire do ... while can be in a function.
int ask_height(void)
{
    // Get height input between ranges 1 to 8 inclusive
    int height;
    do
    {
        height = get_int("Height: ");
    }
    while (height < 1 || height > 8);
    return height;
}

Now, we can start the main program like this instead:
int main(void)
{
    int height = ask_height();

That turns 7 lines in main into 1 line in main. And since the function name is descriptive, the comments are almost obsolete.
We can do the same thing with the rest of the program.
void print_pyramid(int height)
{
    // Loops through each row
    for (int row = 1; row <= height; row++)
    {
        // Prints the left part of the pyramid, we need to print empty spaces before printing the hashes, so
        // the width is equal to the height, amount of hashes printed is equal to the row, so amount of empty spaces is the width - row
        print_hashes(height, height - row);
        printf("  ");
        // Prints the right part of the pyramid, we don't need to print empty spaces before printing hashes, so
        // the width is equal to the amount of hashes, i.e the row and the amount of empty space is just 0
        print_hashes(row, 0);
        printf("\n");
    }
}

And all of a sudden, we have nicely split-out code, each function has one and only 1 thing to do (you may want to read up on the SRP, the Single-responsibility principle).
Now your file starts like this:
#include <cs50.h>
#include <stdio.h>

int ask_height(void);
void print_hashes(int width, int empty_space);
void print_pyramid(int height);

int main(void)
{
    int height = ask_height();
    print_pyramid(height);
}

That's it. The rest is in functions. The function names can probably be further improved, but I'm quite awful at that myself. If you want to go a step further, you don't even need a height variable in main. This works too:
int main(void)
{
    print_pyramid(ask_height());
}

The rest is in functions, and functions can be re-used. Besides, should you ever want to call your program from an outside location, that's a lot easier now too.


Indentation. If you are using Eclipse, please select all your code and press Ctrl + I. Your entire for-loop should be indented one step further.
Use methods. One method for inputting a String, one method for making one iteration of the "decompression".
Did you forget about how to properly use indexOf suddenly? You use indexOf as a condition for your while loop, that makes sense. But then you're using a for-loop to determine the location of the ( and ) characters you are going to work with. This makes no sense to me.
Better variable names. Thanks to your comments on your question, I managed to figure out parts of what you are doing and write a review about that. However, Daniel still has a point that your code is not readable.
Close the scanner. Your scanner is a resource that needs to be closed, call sc.close(); as soon as you are done with the scanner (that is, after you have received all the required inputs from it)
Potential problems. What if I want to encrypt the string (thisWillMessWithYourCode2), how should that string be encrypted in order to be decrypted correctly? Or what would happen if I gave your program the input 42)invalid(data? I believe your code would have a hard time with that.


There is a better way, but this assume that you have an index on vid field (for example, {"vid": 1} ). If you don't, you can create one using db.data.ensureIndex({"vid": 1}). This can take several minutes to end.

The fastest solution (option 2) use $group after a $project  Here the $project stage only add overhead and does not speed up the $group stage, so we can get rid of it.

Currently, the $group operator can't take advantage of index, so it can be quite slow for such big dataset. A better solution would be to use distinct() instead

  Index Use

  When possible, db.collection.distinct() operations can use indexes.

so we can fetch withData array simply using this:

let withData = db.data.distinct("vid")

Then, the datagroup collection is filtered using map() and filter(). On really big array, this can be really expensive as javascript is quite slow. Instead, we can let mongodb do this operation with a simple query using $nin:

let withoutData = db.datagroup.distinct("_id", {"_id": {$nin: withData}})

As distinct() returns an array, we get directly the result in proper format, so we can avoid js mapping and filtering.

so the final script is:

let withData = db.data.distinct("vid")
let withoutData = db.datagroup.distinct("_id", {"_id": {$nin: withData}})

Some results

on my machine (ubuntu16.04) , with a similar dataset ( 100 000 000 docs in data, 20000 in datagroup)

New script runs in less than 5s :

time mongo test < newOption.js
0,06s user 0,00s system 1% cpu 3,534 total


Assigning browser cookies for A-B testing

That code, without indentation, is a chore to read.  The same code, with just indentation and whitespace changes, is easier to follow.

// AB testing code starts;
$abTestValues = array(1,1,0,1);
$abTestValue = 0;
$abTestCurrentValue = $abTestValues[$abTestValue];
$cookieName = 'ab-ranking-20160301';
$cookieLifeTime = time() + (86400 * 30);
$cookiePath = "/";
$abTestCookieValue = $_COOKIE[$cookieName];
if (trim($abTestCookieValue) != '' && $abTestCookieValue != null) {
    $abTestCurrentValue = $abTestCookieValue;
} else {
    $abTestFile = 'abranking.txt';
    if (is_file($abTestFile)) {
        $abTestLastValue = file_get_contents($abTestFile);
        if (($abTestLastValue + 1) == sizeof($abTestValues)) {
            $abTestValue = 0;
        } else {
            $abTestValue = $abTestLastValue + 1;
        }
        $abTestCurrentValue = $abTestValues[$abTestValue];
    }
    file_put_contents($abTestFile, $abTestValue);
    $ranking_cookieval = $abTestCurrentValue;

    setcookie($cookieName, $abTestCurrentValue, $cookieLifeTime, $cookiePath); //cookie set for 30 day
}
// AB testing code ends;


Can you send the timestamp instead? Manipulating dates in JS is a bit tedious without a library. This is probably pretty clear to you already from having to declare all the y M d h m s variables. PHP, on the other hand, has createFromFormat, which has a flexible and friendly API. For example, I believe you could pass a formatting string of 'Y m d H i s' (corresponding to the input of '2021 1 4 13 08 00') and get the timestamp out of it immediately.
Working with timestamps is easier than working with custom formatted strings anyway. I don't know the source of the original date string, but I'd turn it into a timestamp as soon as possible once your app receives it (and, for example, save the timestamp in the database instead of the string).
When you do have to pass around a string instead of a timestamp, use a standardized ISO 8601 string, which can be parsed automatically in most languages.
Ticker display Currently, the tickers are hidden via the JS if there's no timer. Consider if you could carry out this check (and this whole conditional code) in the PHP, rather than sending the HTML markup regardless and then possibly hide it if there's no timer. For example, you might change it so that the server only serves this .js if there's a timer to begin with, otherwise the


Searching for pairs of integers that satisfy primality and divisibility conditions

You are running into several performance problems.

First: if you want to generate a list of primes, you should use a sieve which is much more efficient.

Second: you are checking s+1 in primes, which is inefficient for a list. Instead you should make primes be a set, so that your lookup time is constant.
Third: Instead of for s in range(2, t**2 + 1):, you should use for s in range(floor(t**.5), t**2 + 1):, as this prevents wasting time checking values where s^2<t.

Between these two changes you should see a pretty large speed boost.


Method that return related entities using OData

GetFull() is a methodname which doesn't tell any caller anything about what the method will do. Please choose always names which are as descriptive as possible.
this loop

foreach (var prop in typeof(T).GetProperties().Where(p => p.GetGetMethod().IsVirtual))
{
    if (prop.PropertyType.IsClass && !prop.PropertyType.FullName.StartsWith("System."))
    {
        propertyList += prop.Name + ",";
    }
}

propertyList = propertyList.Remove(propertyList.Length - 1);

could be improved by either using a StringBuilder or by using a ILIst<string> together with string.Join(). This should maybe be extracted to a separate method.
if (!entities.Equals("0")) you are using entities without doing any null check, so better use if (!"0".Equals(entities)). I usually like positive checks more so I would like to suggest to revert this if..else.
by default the newed StringBuilder has a capacity of 16 which is doubled if the added value won't fit anymore. So better initialize it with a higher number by using the overloaded constructor which takes the initial size as an argument.
In addition you can take advantage of the fluent methods of the StringBuilder which return the StringBuilder itself.

All mentioned points (except for the method name) implemented leads to

public virtual HttpResponseMessage GetFull(int id, string entities)
{
    string propertyList = string.Empty;

    if ("0".Equals(entities))
    {
        propertyList = GetJoinedPropertyList();
    }
    else
    {
        propertyList = entities;
    }

    string entityName = typeof(T).Name;
    var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
    var response = Request.CreateResponse(HttpStatusCode.Found);

    StringBuilder sb = new StringBuilder(1024);

    sb.Append(baseUrl)
      .Append("/api/")
      .Append(entityName)
      .Append("/")
      .Append(id)
      .Append("?$expand=")
      .Append(propertyList);

    response.Headers.Location = new Uri(sb.ToString());
    return response;
}
private string GetJoinedPropertyList()
{
    IList<string> propertyNames = new List<string>();

    foreach (var prop in typeof(T).GetProperties().Where(p => p.GetGetMethod().IsVirtual))
    {
        if (prop.PropertyType.IsClass && !prop.PropertyType.FullName.StartsWith("System."))
        {
            propertyNames.Add(prop.Name);
        }
    }
    return string.Join(",", propertyNames);
}


Compressing a stream asynchronously, and returning a byte[]

I don't see any reason for the inner stream. Instead, you can just WriteAsync() the whole buffer directly into the (confusingly named) tinyStream.

Your code won't deadlock if used properly (i.e. asynchronously), but it will deadlock if someone synchronously waits for it (e.g. byte[] resultBuffer = CompressAsync(inputBuffer).Result;). To make sure this doesn't happen, add .ConfigureAwait(false) after every await.

You should do this for all your "library" code, that is code that doesn't need to run in the ASP.NET request context/GUI thread.

This method doesn't use any instance state. Why isn't it static?


Array-based stack data structure in Java

Auto-resize.

There's nothing saying an array-based stack has to have a fixed size. The standard library Stack doesn't have a fixed size, and it's array-based. Same with ArrayDeque, the stack you should be using instead of the Stack class.

Just make a bigger array if you run out of room. You'll want to grow the array by a multiplicative factor to make sure you don't have to resize too often; you want push to be amortized constant time.

public void push(E obj) {
    if(data.length == size())
        data = Arrays.copyOf(data, 2*data.length+2); // +2 in case data.length == 0
    data[++top] = obj;
}

Get rid of the capacity instance variable.

You literally never use it.

Are those checked exceptions?

You declare throws EmptyADTException on two of your methods, which you shouldn't have to do. throws is only necessary for checked exceptions, and EmptyADTException shouldn't be a checked exception. Checked exceptions are for things that might go wrong even if the code is correct, like FileNotFoundException. If someone tries to pop from an empty stack, that's a coding error.

If your EmptyADTException is a checked exception, make it descend from RuntimeException so it's unchecked. Making it a checked exception just bloats any code that uses your stack, and the exception-swallowing catch blocks that result will actually reduce the chances that bugs are found.

Consider throwing NoSuchElementException.

It's what the Java Collections Framework throws for cases like popping from an empty stack. There's also EmptyStackException, which is what the standard library Stack throws, but I don't recommend it. Stack is old, doesn't really fit with newer additions to the Java standard library, and has old design mistakes like built-in synchronization. You shouldn't try to copy it.

Don't use the increment/decrement operators inside of a bigger expression.

Code like data[++top] = obj; requires more thought about what happens in what order than something like ++top; data[top] = obj;.

Don't try to make generic arrays.

    this.data = (E[])new Object[capacity];

This might look like it works, but that's just because type erasure prevents Java from noticing the error. What you're doing here is storing an Object[] in a variable of type E[], even though Object probably isn't E. If you ever do anything that lets Java notice the error, for example

// Inside the Stack class, so data is accessible
Integer[] ints = new Stack<Integer>(5).data;

you'll get a ClassCastException. The correct way to make a generic array is a lot of unnecessary hassle; the best way to go is generally to just make the data variable an Object[]:

public class Stack<E>
{
    private int capacity;
    private Object[] data;

and cast elements when you retrieve them from the array:

public E top() throws EmptyADTException {
    if(isEmpty())
        throw new EmptyADTException("Nothing in the stack!");
    return (E) data[top];
}

For reference, this is how you'd make a generic array correctly:

public Stack(Class<E> klass, int capacity) {
    data = Array.newInstance(klass, capacity);
    ...

and then you'd need to pass a Class object into the Stack constructor:

Stack<Integer> stack = new Stack<>(Integer.class, 10);


I would not write this extension method for int at all since it assumes everything of type int in your project is referring to the ID of a table.

Also, as a rule of thumb, if you're using strings that contain structural metadata about your objects, it's generally a sign you might want to rethink your approach.

Instead, I would find a way to apply an interface to your tables that have this structure, so you could then make an extension method for that interface, or a method that takes in an instance that implements that interface. That way you don't have to rely on strings at all.

If you are really committed to having a method that finds a value based on an int and type inputs, I would change the method to be a static, non-extension method, passing in the int and type.

I also came up with this alternative solution. Although it doesn't behave the same as your original example, you might benefit by using a type parameter so you get a strongly-typed entity returned by your method, which your code will know has a "Title" property:

public static TEntity GetEntityById<TEntity>(int id)
{

   TEntity entity = null;

   //a using is a try finally. you have stuff you want to execute in a finally so I simplified.
   try
   {
        MyDataContext dc = new MyDataContext();

       // match and select record using "id"
       entity = dc.GetTable<TEntity>().Where(string.Format("Id.Equals({0})", id)).Cast<TEntity>().FirstOrDefault(); //not sure if Cast<TEntity> is redundant or not
    }
    finally
    {
        return entity;
    }
}

//consuming code
string myTitle = GetEntityById<MyEntity>(222).Title;

I also noticed you are instantiating a datacontext in this method--you might want to either pass it in or make this an extension method on your datacontext for testability.


Program to find the mean, median, and mode of numbers

It looks valid to me. Except you are not enforcing the '3 number minimum'.

You can use x.odd? to check odd or even.
You can total numbers with [1,2,3].inject(&:+).
The frequencies.to_a is not needed, as it's already an array after the sort_by.
You can sort_by -b so you don't have to reverse.

These are all just refactorings. No change in behaviour.


Bug
You have 2 big bugs in your method. The first is that you never ever set the count variable to 0 and the second that you are yielding the List<T>.
If I call your method with a List<int> containing 10000 ints and do a ToList() on the result I get 2 Lists both containing 9997 ints.
Although this is easy to fix like so
public static IEnumerable<IEnumerable<T>> IntoBatches<T>(this IEnumerable<T> list, int size)
{
    if (size < 1)
    {
        yield return list;
    }
    else
    {
        var count = 0;
        foreach (var item in list)
        {
            var batch = new List<T>();
            batch.Add(item);
            if (size == ++count)
            {
                yield return batch;
                batch = new List<T>();
                count = 0;
            }

        }
        if (batch.Count > 0) yield return batch;
    }
}

this solution takes for a List<int> having 10000 items with size:
  3: 0.506 ms
 13: 0.505 ms
113: 0.505 ms

whereas an array based solution like this (taken from here)
public static IEnumerable<IEnumerable<T>> Chunkify<T>(this IEnumerable<T> source, int size)
{

    using (var iter = source.GetEnumerator())
    {
        while (iter.MoveNext())
        {
            var chunk = new T[size];
            chunk[0] = iter.Current;
            for (int i = 1; i < size && iter.MoveNext(); i++)
            {
                chunk[i] = iter.Current;
            }
            yield return chunk;
        }
    }
}

takes
  3: 0.270 ms
 13: 0.270 ms
113: 0.270 ms

Edit
That Chunkify() method unfortunately has a bug, which is for a passed in IEnumerable<T> with a size which isn't dividable by the passed in chunk size will produce to many items.
E.g passed in a int[] with values 1,2,3,4 and an size argument of 3 will produce 1,2,3,4,0,0.
Fixed version
public static IEnumerable<IEnumerable<T>> Chunkify<T>(this IEnumerable<T> source, int size)
{
    int count = 0;
    using (var iter = source.GetEnumerator())
    {
        while (iter.MoveNext())
        {
            var chunk = new T[size];
            count = 1;
            chunk[0] = iter.Current;
            for (int i = 1; i < size && iter.MoveNext(); i++)
            {
                chunk[i] = iter.Current;
                count++;
            }
            if (count < size)
            {
                Array.Resize(ref chunk, count);
            }
            yield return chunk;
        }
    }
}


Generate a text file representing an email for a job application followup

You wrote a lot of boilerplate code to do a simple task. Before reading the rest of this review, scroll back up and imagine that you were given the assignment, "Make your code as simple and readable as possible." What would you change about it?

Here's what I'd do.

def determine_if_string_is_blank(stringtovalidate, parameterType):

Inconsistent style. Pick one of snake_case, amoebacase, or camelCase, and stick to it!

This function triggers my "boolean functions should be named with is_ detector. Surely, I think, this function should be named is_blank_string! But in fact your name is (currently) more appropriate, because this function does not return a boolean — it returns None or throws an exception! This is not great design, but, okay, the name isn't the worst. However, I would write this entire function as

def assert_string_isnt_blank(s)
    assert s

(notice that the name of the function now unambiguously tells what it does) and then I would eliminate it.

def prompt_user_with_question(question, parameterType):
    answer = input(question)
    assert answer, f"{parameterType} is empty"
    return answer

By the way, what did you expect this line to do?

raise ValueError ("{0} is empty", parameterType)

Did you perhaps expect it to do the same thing as

raise ValueError ("{0} is empty".format(parameterType))

? It doesn't!

(This suggests that you never tested your code, or at least you never tested its non-success paths. Make sure to test your code before running it in production — or posting it to StackExchange!)

def write_string_to_file(pathtofile,email):

The usual complaint about needing to pick a style (underscores? no underscores?) and sticking to it. But also there's a missing space here. It would be good to get in the habit of running your code through a linter like flake8 before posting it, as well.

$ flake8 --ignore=E501 x.py
x.py:26:25: E211 whitespace before '('
x.py:49:36: E231 missing whitespace after ','
x.py:81:10: E127 continuation line over-indented for visual indent
x.py:86:36: E231 missing whitespace after ','

Nothing major here... but sometimes there is something major, and then you're glad you took the time to look for warnings!

Your docstrings make it look like you're intending this as a 100% complete Python program. If so, then you should start the file with a hashbang:

#!/usr/bin/env python

For the email body itself, consider using """multi-line strings""" instead of backslash-continuations. Multi-line strings can be combined with the f prefix.

position_title = None
hiring_manager = None
company_name = None
your_name = None

You create all these variables and then you never use them again! Or, another way to put it is, you assign None to all these variables and then immediately overwrite it with some other value! Eliminate the dead writes.

In conclusion:

#!/usr/bin/env python

def prompt(question):
    answer = input(question + ": ")
    assert answer, f"{question} is empty"
    return answer

if __name__ == "__main__":
    company_name = prompt("Company Name").strip()
    position_title = prompt("Position").strip()
    hiring_manager = prompt("Hiring Manager")
    your_name = prompt("Your Name")

    with open("email.txt", "w") as f:
        f.write(f"""
Hi {hiring_manager},

I hope all is well. I know how busy you probably are, but I recently applied to the
{position_title} position, and wanted to check in on your decision timeline.

I am excited about the opportunity to join {company_name} (insert additional details here).

Please let me know if it would be helpful for me to provide
any additional information as you move on to the next stage in the hiring process.

I look forward to hearing from you,
{your_name}
        """.strip() + '\n')

Notice that I'm using a function only when it makes sense — that is, only when it eliminates repetition in the code.

Also notice that by using a multi-line string, even though it screws up my indentation, it helps to highlight an otherwise-easily-missed bug in the program!

I am excited about the opportunity to join {company_name} (insert additional details here).

Did you notice the (insert additional details here) stuffed in the middle of a string literal full of backslashes? You wouldn't want to send the email out like that, would you? :)


Things to be aware of:

array_filter() does a full loop of the array.
foreach(), of course, does a full loop of the array.
min() does a full loop of the array.
empty() does a couple of things: it checks if a variable is not set AND if it is "falsey".  Because the $dates variable will be unconditionally set, there is no need to check this -- just use !$dates if you want to check if the array is empty.
array_filter(), like empty() is a "greedy" seeker of "falsey" values.  I assume that this is a non-issue for your task because there should be no 0 or false (etc.) values -- only datetime values or nulls.
datetime objects can be compared.
you don't need to make iterated calls to getTimestamp(), nor do you need to declare a new datetime object and set its time manually -- just use the one you found.

I suppose I'll recommend that you loop the data just one time.  No array generation, no function calls, very direct and concise.  Your custom method name is descriptive.  Go with this:

Code: (Demo)

public static function minDateTime(?DateTimeInterface ...$dates)
{
    $minDate = null;
    foreach ($dates as $date) {
        if ($date && (!$minDate || $date < $minDate)) {
            $minDate = $date;
        }
    }
    return $minDate;
}


Transform a MongoDb parent reference tree into a deep nested tree

flatMap (x => x) would probably better be written as flatten.
map (x => x) is essentially a no-op, and could be removed.
map ( ... ) flatten is equivalent to flatMap (...)
It doesn't seem useful to put a type into a comment – you can specify the type for parameters of lambdas as well:

{ (childs: Seq[CategoryTreeNode]) => ...

However, this style is generally discouraged. It would be more useful to store the future from the DB in a variable which gets typed explicitly.
Higher-order method like map should not be invoked with a leading .: do collection map (x => ...) instead of collection.map(x => ...) (source).
(foo => foo match { ... }) can be simplified to (_ match { ... })
(child => collect(child)) can be simplified to (collect(_)) or even just collect

Together, I'd clean up your code to this:

def getTree(rootId: BSONObjectID): Future[CategoryTreeNode] = {
  def collect(parent: CategoryTreeNode): Future[CategoryTreeNode] = {
    // Query the database
    val ourChilds: Future[Seq[CategoryTreeNode]] = getChilds(parent._id.get)
    ourChilds flatMap { childs =>
      Future.sequence(childs map collect) map { childSeq =>
        parent.copy(childs = Some(childSeq))
      }
    }
  }

  // Find the root node and start the recursion
  findOne[CategoryTreeNode](Json.obj("_id" -> rootId)) flatMap (_ match {
    case None => throw new RuntimeException("Current node not found by id!")
    case Some(node) => collect(node)
  })
}


Beginner's exercise to ask for first names and surnames

Styling:

You have to fix the case of your identifiers to be more idiomatic. It means:

Class names should be Capitalized ("Testing", "Funcs", ...)
Class members and variables should use camel case ("firstName", "inputSn", ...)

Also:

The method names of class funcs behaves like a "setter", so it should have a name like setNames. In general, try to use action verbs in your method names.
Edit: the setXX() methods of funcs should not return anything, as they are "setters", they are there to "set".

Code quality:

Variables like "String First_Name" should not all be declared at the beginning of the method, but instead next to the place where they are first used. This way you limit their scope (which makes programming errors more clear) and the code is easier to read.
Similarily, if you don't have a compelling reason to have all the Scanner instances as class members, declare them in your main method where they are used.
Why do you use different Scanner objects for every input? You can simply use one Scanner and use its nextLine() method 3 times. That's the only "performance" tips that you can get, I think (not that you would have any performance problem with such a short program anyway).
Edit: In the line funcsObj.names( funcsObj.setFn(First_Name), funcsObj.setSn(Second_Name)); you are actually setting the members of your funcs objects twice. First in the setFn and setSn methods and then in the names method. You don't need to. Just call your setXX methods. If you want to have the members thing incremented and the data displayed, you can rename names into incrementMembers and remove all setting code from there.


Yes, it could be simpler.

Special case for first value is not needed.
Some variables could be removed.
All variables initialization could be removed.

Below, you can see your code reviewed.

    function selectionSort(inputArray) {
      for (var i = 0; i < (inputArray.length - 1); i++) {
         var minNum = inputArray[i];
         var swapElementIndex = i;
         for (var currentIndex = i + 1; currentIndex < inputArray.length; currentIndex++) {
            if (inputArray[currentIndex] < minNum) {
                swapElementIndex = currentIndex;
                minNum = inputArray[swapElementIndex];
            }
        }
        if (i != swapElementIndex) {
            var temp = inputArray[i];
            inputArray[i] = inputArray[swapElementIndex];
            inputArray[swapElementIndex] = temp;
        }
     }
     return inputArray;
    }


Calculate the lattice paths in an n*n lattice (Project Euler #15)

To move from the top left corner of an \$n\times n\$ grid to the opposite one you have to move \$n\$ times to the right and \$n\$ times down.
So in total you will do \$2n\$ moves.
If you could make those in any order there would be \$(2 n)!\$ ways of doing them.
But you don't have that freedom, because the order within the movements to the right and within the movements down is fixed, e.g. you have to move from row 4 to row 5 before you can move from row 5 to row 6.
So of the \$n!\$ ways the movements to the right can be ordered, only one is valid, and similarly with the movements down.

Summing it all up, the closed form answer to that problem is:

$$ \frac{(2n)!}{n!n!} $$

Unsurprisingly this is the same as \$C_{2n, n}\$, the combinations of \$2n\$ items taken \$n\$ at a time.
You could think of the same problem as having \$2n\$ movements and having to choose \$n\$ of those to make e.g. the movements down, leaving the others for the movements right.

With Python's arbitrary size integers you could simply calculate that as:

import math

def pe15(n):
    n_fact = math.factorial(n)
    return math.factorial(2 * n) / n_fact / n_fact

To give this answer a little more meat, in most other languages you don't have the luxury of not having to worry about integer overflows.
Even in Python it may be a good idea if you want to keep your computations fast for very large numbers.
So you would typically do the same computation as:

def pe15_bis(n):
    ret = 1
    for j in range(1, n+1):
        ret *= n + j
        ret //= j
    return ret

In Python that doesn't seem to pay off (performance wise) until n is in the many hundreds, but I find lovely that, the way that code goes, ret is always exactly divisible by j.
Figuring out why is left as an exercise for the reader...


int dp(string s,int in,int len,int pos){

Where are the comments to explain the meanings of the variables? We're forced to reverse engineer them.

    if(in == len){
        return 0;
    }
    if(pos == 0){
        if(s[in] == 'K'){
            return dp(s,in+1,len,1)+dp(s,in+1,len,0);
        }
        return dp(s,in+1,len,0);
    }
    if(pos == 1){
        if(s[in] == 'E'){
            return dp(s,in+1,len,2)+dp(s,in+1,len,1);
        }
        return dp(s,in+1,len,1);
    }
    if(pos == 2){
        if(s[in] == 'K'){
            return 1+dp(s,in+1,len,2);
        }
        return dp(s,in+1,len,2);
    }
}

This is not dynamic programming. A dynamic programming approach to this problem must work on the following basis:

  Given a structure S which summarises the prefix str, and the next character ch, we need to derive a structure S' which summarises the prefix str + ch.

We have some easy conclusions:

S must provide us with the number of the desired subsequences, because at the end of the DP run we will only have S corresponding to the entire string. So it has a field which we can call kek.
If ch is neither 'E' nor 'K' then S' = S.
If ch != 'K' then S'.kek = S.kek.
If ch == 'K', S must provide us with some way of knowing how much bigger S'.kek should be than S.kek. Obviously that must be the number of KEK subsequences ending with ch, which is the number of KE subsequences in str.

You should be able to carry this reasoning through to fill out the entire list of fields required in S and the logic to update them when reading an 'E' and when reading a 'K'.


Managing "active" and "rest" state for class name-based CSS animations

You can use the toggle method from Element.classList and the animationend event in your example:

<script>
    Array.prototype.slice.call(document.querySelectorAll(".box")).forEach(function(el) {
        el.addEventListener('click', click());
        el.addEventListener('animationend', resetBox());
    });

    function click() {
        return function(e) {
            var target = e.target || e.srcElement;

            if (target.classList.contains('box')) {
                if (target.classList.contains('box-active')) {
                    target.classList.toggle('box-rest');
                } else {
                    target.classList.toggle('box-active');
                }
            }
        };
    }

    function resetBox() {
        return function(e) {
            var target = e.target || e.srcElement;

            if (target.classList.contains('box-rest')) {
                target.className = 'box';
            }
        };
    }
</script>


Let's profile this a little bit (this is on a dual-core i7, so a bit quicker):

  Running Time  Self        Symbol Name

  3984.0ms  100.0%  0.0     Main Thread  0x2856c

  3982.0ms   99.9%  0.0      start

  3982.0ms   99.9%  1.0       main

  3936.0ms   98.7%  3081.0         crypt(char const*)

  640.0ms   16.0%   640.0           _platform_strchr

  126.0ms    3.1%   102.0           std::__1::basic_string, std::__1::allocator >::push_back(char)

  89.0ms    2.2%    89.0            strlen

  14.0ms    0.3%    14.0           DYLD-STUB$$strchr

  14.0ms    0.3%    4.0        free

  8.0ms    0.2% 1.0        szone_free_definite_size

  7.0ms    0.1% 7.0        DYLD-STUB$$strlen

  2.0ms    0.0% 2.0        operator delete(void*)

  2.0ms    0.0% 0.0      _dyld_start

Ok, so more than 98% of the time is spent in the crypt function (which isn't surprising really). Almost 16% of the time is spent in strchr, with another 3.1% spent in push_back. There's also a few percent (2.2) spent doing strlen.

Ok, so how do we cut down on these:

Firstly, we'll switch over to using std::array<char> instead of char *. These are both stack-allocated (and so we don't incur the dynamic allocation overhead of std::string or std::vector), but std::array knows its size, and will allow us to remove the strlen in the crypt function:

#include <array>

const std::array<char, 27> alpha = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
const std::array<std::array<char, 27>, 3> rotors
{
    {{"EKMFLGDQVZNTOWYHXUSPAIBRCJ"},
    {"AJDKSIRUXBLHWTMCQGZNPYFVOE"},
    {"BDFHJLCPRTXVZNYEIWGAKMUSQO"}}
};

const std::array<char, 27> reflectors = {"YRUHQSLDPXNGOKMIEBFZCWVJAT"};
const std::array<char, 4> key = {"ABC"};

The indexof function then needs to change as well (and I'm going to rename it to index_of, which is easier to read):

template <size_t N>
std::size_t index_of (const std::array<char, N>& str, int find)
{
    for(std::size_t i = 0; i < N; ++i) {
        if(str[i] == find) return i;
    }
    return -1;
}

crypt now looks like:

template <size_t N>
std::array<char, N> crypt (const std::array<char, N>& ct)
{
    // Sets initial permutation
    int L = li(key[0]);
    int M = li(key[1]);
    int R = li(key[2]);

    std::array<char, N> output;

    for ( unsigned x = 0; x < N ; x++ ) {
        int ct_letter = li(ct[x]);

        // Step right rotor on every iteration
        R = static_cast<int>(mod26(R + 1));

        // Pass through rotors
        char a = rotors[2][mod26(R + ct_letter)];
        char b = rotors[1][mod26(M + li(a) - R)];
        char c = rotors[0][mod26(L + li(b) - M)];

        // Pass through reflector
        char ref = reflectors[mod26(li(c) - L)];

        // Inverse rotor pass
        long d = mod26(index_of(rotors[0], alpha[mod26(li(ref) + L)]) - L);
        long e = mod26(index_of(rotors[1], alpha[mod26(d + M)]) - M);
        char f = mod26(index_of(rotors[2], alpha[mod26(e + R)]) - R);

        output[x] = alpha[f];
    }

    return output;
}

which is close to what it was, but with a few minor changes (no += on a string, as we know already how large it will be and simple assign directly into that index).

And we now call it like so:

int main ()
{
    for ( int i = 0; i < 1000000; i++) {
        crypt(std::array<char, 37>{"PZUFWDSASJGQGNRMAEODZJXQQKHSYGVUSGSU"});
    }

    return 0;
}

Let's profile this again:

  Running Time  Self        Symbol Name

  2873.0ms  100.0%  0.0     Main Thread  0x2c7ff

  2872.0ms   99.9%  0.0      start

  2872.0ms   99.9%  2.0       main

  2870.0ms   99.8%  2870.0         std::__1::array crypt<37ul>
  (std::__1::array const&)

  1.0ms    0.0% 0.0      _dyld_start

Ok, so everything except crypt has now been inlined. If we apply the modification from @MrSmith42, we shave even more time off:

  Running Time   Self        Symbol Name

  1855.0ms  100.0%  0.0     Main Thread  0x2ca5c

  1854.0ms   99.9%  0.0      start

  1854.0ms   99.9%  1.0       main

  1853.0ms   99.8%  1853.0         std::__1::array crypt<37ul>
  (std::__1::array const&)

  1.0ms    0.0% 0.0      _dyld_start

We have imposed a fairly large constraint however: we need to know the size of the string to be encrypted at compile-time (so no reading it from a file or stdin or the like). If this will always be the case, then this provides a fairly significant speed-up on my hardware.


Validate your fields individually so you can provide the client side with better error messages (assuming this is an AJAX script)...

$reqd_params = array('yourName', 'emailID', 'subject', 'message');
foreach($reqd_params as $param)
    !empty($_REQUEST[$param]) || die("$param parameter is required.");

The AltBody paramter is supposed to be the plaintext version of the regular body, yours has html in it. You need to do wrap it in striptags and nl2br like so... striptags(nl2br($my_html_message))

Avoid returning plain text from an AJAX script too. Set your properties in an array and return it in JSON so Javascript can read it easier.

for example:

header("content-type: application/json");
echo json_encode(array(
    "success" => true,
    "message" => "email_sent"
));

Edit.. I said nl2br but what u need is the opposite of that..