Besides the obvious code repetition that you mentioned, a few salient issues deserve mentioning:

Your main() function is not really the main code of your program.  Rather, you have some free-floating code outside of any function, and the main function is actually called endMenu(), which is surprising.
The endMenu() function is improperly recursive.  The while True loop should suffice.
You use global variables a lot.  While firstName and lastName are somewhat excusable (they are entered once by the user, and never change subsequently), you really shouldn't use globals for transient state like ans, question, etc.
function is the least-informative name possible for a function.

To address those issues, as well as the code repetition you mentioned, I'd write the program like this:

import operator
import random

OPERATIONS = [
    ('+', operator.add),
    ('-', operator.sub),
    ('*', operator.mul),
]

def random_question(binary_operations, operand_range):
    """Generate a pair consisting of a random question (as a string)
    and its answer (as a number)"""
    op_sym, op_func = random.choice(binary_operations)
    n1 = random.randint(min(operand_range), max(operand_range))
    n2 = random.randint(min(operand_range), max(operand_range))
    question = '{} {} {}'.format(n1, op_sym, n2)
    answer = op_func(n1, n2)
    return question, answer

def quiz(number_of_questions):
    """Ask the specified number of questions, and return the number of correct
    answers."""
    score = 0
    for _ in range(number_of_questions):
        question, answer = random_question(OPERATIONS, range(0, 21))
        print('What is {}'.format(question))
        try:
            user_input = float(input("Enter the answer: "))
        except ValueError:
            print("I'm sorry that's invalid")
        else:
            if answer == user_input:
                print("Correct!\n")
                score += 1
            else:
                print("Incorrect!\n")
    return score

def identify_user():
    # TODO, as an exercise for you
    pass

def display_score(first_name, last_name, class_name):
    # TODO, as an exercise for you
    pass

def menu():
    # TODO, as an exercise for you
    pass

def main():
    first_name, last_name, class_name = identify_user()
    while True:
        menu_choice = menu()
        if menu_choice == 1:        # Display score
            display_score(first_name, last_name, class_name)

        elif menu_choice == 2:      # Run quiz
            QUESTIONS = 10
            score = quiz(QUESTIONS)
            print('{first_name} {last_name}, you scored {score} out of {QUESTIONS}'.format(**locals()))

        elif menu_choice == 3:      # Exit
            break

        else:
            print("Sorry, I don't understand. Please try again...")
            print()

if __name__ == '__main__':
    main()

Observe how there are no global variables: each function accepts parameters and returns specific output values.


White Elephant Gift Exchange game using object-oriented design

Technical issues

In your WhiteElephant class, turnCompletedUsers is unused. Is this expected?
For the purposes of this site*, I think it'll be better if you can actually fill in the implementation for WhiteElephant.stealGift() and WhiteElephant.pickGift() (which happens to be unused, too).
You do not need to make all your methods in WhiteElephant public, probably only play() should remain public and the rest can be private.
openedGifts.add(gift) is actually a syntax error*, as openedGifts is a Map. Perhaps you were looking for openGifts.put(gift, currentUser)?
stealGift() returns a boolean value, but what does that indicate?

Gameplay

  The first person opens a wrapped gift and the turn ends.

Your implementation does not take care of the first player, where the turn ends immediately after opening a gift.

Gift gift = currUser.pickOrSteal(unopenedGifts, openedGifts.keySet());
if (isGiftAvailableForStealing(gift)) {
    ...
}

This two lines seem a bit weird, as I don't think the game rules makes a separate decision concerning whether a gift is available for stealing after a player picks/steals a gift.

An alternative approach

I'll leave this as an exercise for the reader, how about considering adding a new field inside Gift that represents the current holder of the item? In that case, the same isOpened() method will read something like:

public boolean isOpened() {
    return holder != null;
}

The other operations to complete the 'stealing' of gifts, i.e. swapping the players holding the gift, becomes slightly easier, I would think...

* In fact, we only review complete and working code, I am letting these slide because it's not too far a stretch to assume what might be the underlying implementation... but only just.


You can only use the To syntax with Case statements inside a Select block, and you can nest Select Blocks....

Note that indentation helps enormously, so I've changed the indentation to 2 spaces, although 4 is more typical, but doesn't always suit StackExchange rendering.

Sub q2country_and_q2country_other()

   Dim i As Long, c4 As Range, c5 As Range

   For i = 2 To 456
      Set c4 = Range("D" & i)
      Set c5 = Range("E" & i)

      Select Case c4.Value
        Case 94
          Select Case c5.Value
            Case "", " ", "0", -99, -66, -77
              c4.Interior.color = vbRed
              c5.Interior.color = vbRed
            Case Else
              c4.Interior.color = vbGreen
              c5.Interior.color = vbGreen
          End Select

        Case 1 To 92
          Select Case c5.Value
            Case -99, ""
              c4.Interior.color = vbGreen
              c5.Interior.color = vbGreen
            Case Else
              c4.Interior.color = vbRed
              c5.Interior.color = vbRed
          End Select
      End Select
    Next i
End Sub


Your first concern is performance, so let's start there. The way you're including and processing your content is going to slow you down. Because you're buffering it, then putting it to a variable, then doing a search replace, you're going to end up working through the content several times before you get your end result. If the content is small then don't even worry about it, but if you have embedded base64 images or just tons of content, then you're going to want a different approach.

From a code point a view I think you're on the right track with your object design. It's always good to break things out to make them easier to maintain. One thing you want to consider though is to take a more MVC style approach by separating processing from the visuals. This makes code easier to read and much easier to maintain. The long story short of this point is to change the echo of the output to a return so that your calling (visual) code can output it. It sounds minor but as your application becomes more complex, it can be a headache saver.

Back to your first point, how to improve getting of the content. My approach would be to make the included content an object file. The file could then include a get method of sorts that returned the html in a string with your titles and parameters already in place. That would allow you to have your content file be built just like a concatenated string (saving the find and replace work). Pass your values as parameters and you're good to go.

Here's how I would do this. I didn't include code for the content class as the code in this Template class should be enough to go on. Note that based on my example, all include files should have the class ContentObj with the method getOutput. I simplified your include path code to make things much easier to read. I also added an exit after your header redirect as there's no need for further processing (usually) after a redirect.

<?php
defined("SECURE") or exit('Please define SECURE keyword to continue.');
class Template
{
    private $configClass;
    private $templateParams;

    public function Template($configClass)
    {
        $this->configClass = $configClass;
        $this->templateParams = array();
    }

    public function loadTemplate()
    {
        $this->organiseParams();
        $this->displayContent();
    }

    private function organiseParams()
    {
        $values = $this->configClass->getAll();

        while(list($title, $value) = each($values))
            $this->addParameter('[config ' . $title . ']', $value);
    }

    private function displayContent()
    {
        if (strlen($_GET['page']) >= 1)
        {
            $contentPath = ROOT . $this->configClass->getConfig("style.folder") . '/' . $this->configClass->getConfig("style.name");

            if (file_exists($contentPath . '/' . $_GET['page'] . '/public_html/content.php'))
                include $contentPath . '/' . $_GET['page'] . '/public_html/content.php';
            else
                include $contentPath . '/error/public_html/content.php';

            $contentObj = new ContentObj($paramTitle, $paramValue, $htmlOutput);
            $htmlOutput = $contentObj->getOutput($this->templateParams);

            return $htmlOutput;
        }
        else
        {
            header("location: " . $configClass->getConfig("website.url") . "/index");
            exit;
        }
    }

    private function addParameter($title, $value)
    {
        $this->templateParams[$title] = $value;
    }
}
?>


Course Statistics Using Arrays and Files

Exception handling

It is not customary to let the main method throw an exception. At the very least you can catch the base Exception class and use printStackTrace() to print the error message and related debug info.

IO handling

This program only deals with one file.  However, it is good practice to remember to close every external resource.  That includes files, database connections (and other related resources, like prepared statements and result sets), network sockets, etc. not closing resources may result in resource leaks that can escalate to JVM crash. Java 7 introduced the try-with-resources construct that allows the compiler to automatically handle resource closure as well as error handling.
Java 7 also introduced the "new io" java.nio package that improves IO handling in Java.   the Files.readAllLines() is a convenient method that reads whole file into List of Strings (and also internally handles the external resource). (alas, no equivalent writeAllLines())

Naming conventions

gradesString is a List of Double items. the name is very confusing.


Strategy design pattern with various duck type classes

The devil’s in the _details

Your suggestion is good, but you don’t need a property; you can just use a normal attribute. All your setter does is set the variable, so just do that instead. So, this:

self.set_fly_behavior(fly_instance)

Can become this:

self._fly_behaviour = fly_instance

Note my use of self._fly_behaviour. Since it’s is an implementation detail of the class, the best practice is to prefix the variable name with an underscore. This tells programmers that it’s not designed to be used externally.

Aside: naming behaviours

The names perform_quack() and perform_fly() are very un-Pythonic. Why not just quack() and fly()? The perform tells us nothing—except, maybe leaking an implementation detail to the outside (that these delegated). This isn't something a caller needs to care about.

ABCs

Other than that, you could make your base classes Abstract Base Classes:

from abc import ABCMeta, abstractmethod

...

class QuackBehavior(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def quack(self):
        pass

    @classmethod
    def __subclasshook__(cls, Check):
        required = ["quack"]
        rtn = True
        for r in required:
          if not any(r in vars(BaseClass) for BaseClass in Check.__mro__):
            rtn = NotImplemented
        return rtn

This allows you to have a more Pythonic interface for your class.

(Also, note the removal of the empty constructor. Python provides an empty constructor anyway, so don’t bother defining one if you do nothing with it. It’s just useless extra code.)

A functional approach

This is a pretty heavyweight solution for Python. If you know that these behaviours are always just one function, I would argue classes aren’t needed.

Instead, recall that Python functions are first-class objects:

def quack(self):
    print("Quack")

def mute_quack(self):
    print "<< Silence >>"

some_duck = Duck()
some_duck.quack = mute_quack

A hybrid approach

We can make this work with one small modification: by using a property to convert functions into methods, so that they can be called normally.

(I’m assuming you need access to self in the method; if not, leave out that argument, and it’ll work as-is, like a static method.)

import types

class Duck(object):
    ...

    @property
    def fly(self):
        return self._fly

    @fly.setter
    def fly(self, value):
        self._fly = types.MethodType(value, self)

    @property
    def quack(self):
        return self._quack

    @quack.setter
    def quack(self, value):
        self._quack = types.MethodType(value, self)

One step further...

Hmm...we’re doing the same thing for both properties.  If you want, we can take it a step further.

Let’s generalise it instead:

import types

def method_property(name):
    def getter(self):
        return getattr(self, name)
    def setter(self, value):
        setattr(self, name, types.MethodType(value, self))
    return getter, setter

class Duck(object):
    ...
    quack = property(*method_property("_quack"))
    fly = property(*method_property("_fly"))

Just assign the function as needed—perhaps in the constructor of subclasses. Obviously, if you need more complicated behaviours, this might not do. But for simple things, I’d say it’s the better solution.

Constructors for subclassing

Since a duck is useless without a quack and fly behaviour, and all subclasses assign them, it makes sense for the constructor to deal with this:

class Duck(object):
    def __init__(self, fly, quack):
        self.fly = fly
        self.quack = quack

    ...

class ModelDuck(Duck):
    def __init__(self):
        Duck.__init__(self, fly_no_way, squeak_quack)
        print "I'm a Model Duck"

Or, if you were using your original class’s implementation:

class Duck(object):
    def __init__(self, fly, quack):
        self._fly_behaviour = fly
        self._quack_behaviour = quack

    ...

class ModelDuck(Duck):
    def __init__(self):
        Duck.__init__(self, FlyNoWay(), SqueakQuack())
        print "I'm a Model Duck"

Conclusion

If we wrap all this together, we end up with two implementations:

function based, and
class based.

These implementations remove repetition, and will make this sort of thing much easier to work with in Python overall.


In general, passing controls to the BackgroundWorker should not be necessary at all. Think about it as it simply has some job to do and that's all. However, it can of course report about progress of its job. Those two ideas were taken into account when designing BackgroundWorker class and are reflected by DoWork and ProgressChanged events respectively. There is also a dedicated BackgroundWorker.ReportProgress method which raises ProgressChanged event.

This event should be handled on GUI level so it has access to the controls without passing them down to worker. Draft of solution:

private void prepareToRun()
{
    if (!backgroundWorker1.IsBusy)
    {
        backgroundWorker1 = new BackgroundWorker();
        backgroundWorker1.DoWork += backgroundWorker_DoWork;
        backgroundWorker1.ProgressChanged += backgroundWorker_ProgressChanged;
        backgroundWorker1.RunWorkerAsync();
    }
}

public static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    // use worker.ReportProgress(percent, someData) somewhere here

}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // Update your statusStrip1 here according to data passed in e.ObjectState
}


You can apply forall to most containers to test if every element in the container satisfies some property. forall will only evaluate x + 1 if x is true. This type of evaluation is known as short-circuit evaluation. So basically we can use this property to perform the same behavior as the if-then statement in the original code.

Notice also that I've used pattern matching to get rid of the isInstanceOf[T].

def isFull: Boolean =
  getGrid.indices.forall(x =>
    getGrid(x).indices.forall(y =>
      getGrid(x)(y).getState match {
        case xyState: Undecided => False
        case _ => True
      }
    )
  )


Dynamically create a table with values from an object

I rewrite in my style with only loop. It maybe easier to read.

perCurrency = {
  USD: { 0:100, 1:200, 2:9200, 3:1500, 4:1500 },
  CAD: { 0:250, 1:7600, 2:150, 3:3000 }
};
var numOfCurrency = Object.keys(perCurrency).length + 1;
var donation_table;
donation_table = $('<table>').attr('id', 'donation_table').addClass('table table-condensed'));

$.each(perCurrency, function(index, currency) {
  var lowestInCurrency  = Infinity,
      highestInCurrency = 0,
      totalInCurrency   = 0;
  $.each(currency, function(k, v){
    totalInCurrency = totalInCurrency + v;
    if (v < lowestInCurrency) lowestInCurrency = v;
    if (v > highestInCurrency) highestInCurrency = v;
  });

  donation_table.append(
    $('<tr>').append(
      $('<td>').css('font-weight', 'bold').css('width', '160px').html('&nbsp;')
    ).append(
      $('<td>').css('width', '150px').text(index)
    )
  ).append(
    $('<tr>').append(
      $('<td>').css('font-weight', 'bold').css('width', '160px').text('Smallest Donation')
    ).append(
      $('<td>').text(lowestInCurrency)
    )
  ).append(
    $('<tr>').append(
      $('<td>').css('font-weight', 'bold').css('width', '160px').text('Largest Donation')
    ).append(
      $('<td>').text(highestInCurrency)
    )
  ).append(
    $('<tr>').append(
      $('<td>').attr('colspan', numOfCurrency).html('&nbsp;')
    )
  ).append(
    $('<tr>').append(
      $('<td>').css('font-weight', 'bold').css('width', '160px').text('Total Donation')
    ).append(
      $('<td>').text(totalInCurrency)
    )
  );
});

$("#giving_capacity").html(donation_table);


Deeply nested search through Document tree

I find recursion complicated You can use a while loop:

private string SearchDocument(Document doc)
{
    while (doc != null)
    {
        if (!string.IsNullOrEmpty(doc.Ordnungsbegriff))
        {
            return doc.Ordnungsbegriff;
        }
        doc = doc.ParentDocument;
    }
    return null;
}

Edit: As a further point - it's better not to mix languages in your code: Ordnungsbegriff should be Keyword (according to Google).


Calculate date for ordinal day of week in month

For the parameter, may I suggest nthOccurrence? Alternatively, anything that communicates what exactly it means should be alright, given that it's at a pretty contained location - even nthTimeDayOfWeekOccursInMonth wouldn't be terrible, especially since dayOfWeek and month are also parameters.

The method is harder, mainly because the thing you're calculating doesn't have a great name. "Return the nth occurrence of a weekday in a given month of a given year" doesn't lend itself to brevity. I would take one of two routes:

Does the assignment / class / professor have a term for this functionality? "Weekday oracle" or something equally obscure works perfectly if it's the way that everyone else who will see this code knows to refer to this thing.

If not, I would name it what it is; something like getDateOfNthTimeDayOfWeekOccursInMonth - this would pair well with naming that first parameter nthOccurrence. In this case, I think information (what exactly can I expect this to do) trumps brevity, because what it does is not very common / intuitive.


Sorting an array to match the order of values of another array

Based on the comments I'm not entirely sure what you ended up doing so I thought I'd provide a general example in case other folks drop by.

Sample Code and Output

<?php

function random_finish()
{
  $list = array();
  $list[2001] = array(200,'result for URL ID 2001');
  $list[2002] = array(200,'result for URL ID 2002');
  $list[2003] = array(200,'result for URL ID 2003');
  $list[2004] = array(200,'result for URL ID 2004');
  $list[2005] = array(200,'result for URL ID 2005');

  $used = array();
  while ( count($used) < count($list) )
  {
    $r = mt_rand(2001,2005);
    if ( !isset($used[$r]) )
    {
      echo "... result for URL ID $r retrieved
\n";
      $used[$r] = $list[$r];
    }
  }

  return $used;
}

echo "
\n";
echo "Randomized result order...
\n";
$result = random_finish();

The above is meant to emulate random API response order and provides a result similar to the following:

Randomized result order...
... result for URL ID 2005 retrieved
... result for URL ID 2004 retrieved
... result for URL ID 2001 retrieved
... result for URL ID 2003 retrieved
... result for URL ID 2002 retrieved

Here, we emulate "using" the data as returned by using the key value to know which URL apply the response to. The key could be a globally unique URL ID or it could be a request sequence number:

echo "
\n";
echo "Use as is via request key...
\n";
foreach ($result as $key => $val)
  echo "... URL ID $key with result code " . $val[0] . " and text '" . $val[1] . "'
\n";

This matches the random response order above:

Use as is via request key...
... URL ID 2005 with result code 200 and text 'result for URL ID 2005'
... URL ID 2004 with result code 200 and text 'result for URL ID 2004'
... URL ID 2001 with result code 200 and text 'result for URL ID 2001'
... URL ID 2003 with result code 200 and text 'result for URL ID 2003'
... URL ID 2002 with result code 200 and text 'result for URL ID 2002'

If a reordering was needed it can be done efficiently by using the built in function ksort:

echo "
\n";
echo "If needed, list after ksort...
\n";
ksort($result);
foreach ($result as $key => $val)
  echo "... URL ID $key with result code " . $val[0] . " and text '" . $val[1] . "'
\n";

Which gives us an array (or list) of results sorted on the array key.  This could be a request ordering value though it would be nice to have a unique ID for each URL to be processed so that the ordering would not matter.

If needed, list after ksort...
... URL ID 2001 with result code 200 and text 'result for URL ID 2001'
... URL ID 2002 with result code 200 and text 'result for URL ID 2002'
... URL ID 2003 with result code 200 and text 'result for URL ID 2003'
... URL ID 2004 with result code 200 and text 'result for URL ID 2004'
... URL ID 2005 with result code 200 and text 'result for URL ID 2005'

Some key points from a code review standpoint:

Using a unique ID for URLs can eliminate the need to do any sorting.
Sorting using a simple built-in function is likely to be more efficient than repeated lookup activities (especially for larger lists).
Choosing a key for an array instead of accepting the default numeric keys can provide a lot of value in various situations.

In a nutshell, solution design can have a huge impact on solution complexity and efficiency.


What are you Returning

This function is adding a new member variable, self.dict. Presumably you want to just return a new temporary variable. Also, dict() is actually less efficient than {}, so you might want to start with:

member_dict = {} # or however you want to name it

Iterating over a Dict

In python, iterating over a dict is the same as iterating over the keys, so we can just save that step:

for key in self.__dict__:

But really, you don't just want the keys, you want the values too, so let's just get both:

for key, val in self.__dict__.items():

getattr

Use getattr() only for variable attribute names. Otherwise, just reference the attribute directly. getattr(x, 'getDict')() is more verbose and harder to parse than x.getDict().

Catching Exceptions

Don't just catch every exception - catch the one you expect to see. In this case, AttributeError:

member_dict = {}
for key, val in self.__dict__.items():
    if key not in self.NOT_INCLUDE:
        try:
            member_dict[key] = val.getDict()
        except AttributeError:
            member_dict[key] = val
return member_dict

Add a Free Function

def getDictIfExists(obj):
     try:
         return obj.getDict()
     except AttributeError:
         return obj

This lets you write the whole thing as a generator expression

return {key: getDictIfExists(val)
        for key, val in self.__dict__.items()
        if key not in self.NOT_INCLUDE}


Way to check if a byte array contains another byte Array

The biggest improvement would be to keep track of potential matches while you are finding if the current match is valid.  As Raymond mentioned, in his comment, you could look at KMP or Boyer Moore algorithms but you trade performance for complexity.

Searching though 900000000 Byte will just take some time.  There is no magic answer for that but I did a couple of test one with just searching while keeping track of potential matches and one using producer/consumer pattern so I could use the TPL and not block the main threads.  Neither one of these was actually faster than the other - in the end it was a wash and both ran anywhere between 7.5 seconds to 8 seconds to run on my machine.  The async version was a little better as it didn't just "hang" the system while it ran but I don't know if you can use Task in your solution.   I did try to bench your code on my machine but it had index out of bound issues.  I fixed them with what I thought would be correct but never got a bench mark because I got tired of waiting for the result.

Here is a example of searching that keeps track of potential matches.  There is more optimization that could happen.  Like not checking rest of source if no matches found and it is past the length of the search.  Also could do a pattern match but I'm just checking the first character.

Word of warning I did not do extensive testing on this

public class ByteSearch
{
    public static IEnumerable<int> Search(byte[] source, byte[] searchByteArray)
    {
        if (source == null)
        {
            throw new ArgumentNullException(nameof(source));
        }
        if (searchByteArray == null)
        {
            throw new ArgumentNullException(nameof(searchByteArray));
        }

        var searchLength = searchByteArray.Length;
        var sourceLength = source.Length;
        if (searchLength > sourceLength || searchLength == 0)
        {
            yield break;
        }

        var matches = new List<ByteSearchStore>(searchLength);
        for (var i = 0; i < sourceLength - 1; i++)
        {
            var currentByte = source[i];

            // found a potential match
            if (currentByte == searchByteArray[0])
            {
                if (searchByteArray.Length == 1)
                {
                    yield return i;
                }
                else
                {
                    matches.Add(new ByteSearchStore
                    {
                        StartingIndex = i,
                        Index = -1
                    });
                }
            }

            // check matches
            var count = matches.Count;
            var m = 0;
            while (m < count)
            {
                var potentalMatch = matches[m];
                if (searchByteArray[potentalMatch.Index + 1] == currentByte)
                {
                    potentalMatch.Index++;
                    if (potentalMatch.Index == searchLength - 1)
                    {
                        yield return potentalMatch.StartingIndex;
                        count = 0;
                        matches = new List<ByteSearchStore>(searchLength);
                    }
                    else
                    {
                        m++;
                    }
                }
                else
                {
                    matches.RemoveAt(m);
                    count--;
                }
            }
        }
    }

    private class ByteSearchStore
    {
        public int Index { get; set; }
        public int StartingIndex { get; set; }
    }
}

The program builds up a list of matches each time it hits the first character of the search string then ejects them once they stop matching the search string.  We only check the top match to see if it's the search string because it would be the longest and if it matches we wipe the list as we don't want matches inside our current match.

Example how I ran the program

var random = new Random();
var source = Enumerable.Range(0, 900000000).Select(_ => (byte)random.Next(byte.MinValue, byte.MaxValue)).ToArray();
var search = Enumerable.Range(0, 9000).Select(_ => (byte)random.Next(byte.MinValue, byte.MaxValue)).ToArray();
var test = ByteSearch.Search(source, search).ToArray();

If you want the TPL Producer/Consumer one I can post that but again it will be As Is


typedef std::wstring::npos tnpos;

std::string::npos and std::wstring::npos are static constant integer members of std::string and std::wstring, respectively. They are not types and they cannot be typedef'd.

unsigned int len = str.length();

This is incorrect. std::string::length() has a return type of size_t std::string::size_type which may be larger than an unsigned int depending on your platform and compiler. Other class methods will use the same type for length/position/indexing, so you should make this change for all the other uses of unsigned int.

// or use lower.reserve(len);

No, please don't. That reserves space for the string, but it does not resize it. There is a resize() method.

Since you said you're able to use C++11 features, as long as they're enabled, the first version of the function (the one that returns a string) will work without copying. It will use the move constructor. So you don't have to use the cumbersome version with an input and output parameter. For more information see http://blog.smartbear.com/c-plus-plus/c11-tutorial-introducing-the-move-constructor-and-the-move-assignment-operator/


Loop whose endpoint (?) change during the loop

It's generally not a good idea to alter the iterator variable in a for/next loop.  While your code works, it's just not a good practice.  Also, your initializing i to 8 is redundant since your loop starts at 8 as well.  Here's how I would handle it:

Sub AddRows()

    Dim i As Integer
    Dim LastRow As Integer
    Dim counter As Integer

    LastRow = Cells(8, 2).End(xlDown).Row
    counter = 8

    For i = counter To LastRow
        If Cells(counter, 1) <> "" Then
            counter = counter + 1
            Range(counter & ":" & counter).Insert CopyOrigin:=xlFormatFromRightOrBelow
        End If
        counter = counter + 1
    Next i

End Sub


Add numbers in array without adding adjacent number

Your indentation is inconsistent, and it looks like you got confused yourself, since you are computing and printing "real sum" many times.

The code organization could use improvement as well.  The valueadd() function does a lot of stuff:

Populating the array with random members
Printing the array
Summing the array using streams, and printing that sum
Summing the array by working from the ends towards the middle, and printing that sum

There is no way to figure out what it does without reading all of the code.  Ideally, each function should be limited to a single responsibility.

There are a lot of instance variables, all cryptically named, and all public:

public int a;
public int b[];
public int sum=0;
public int sum1=0;
public int k=0;
public int m=0;

Only the array should be an instance variable here; all of the others could be local variables.

The output looks a bit sloppy as well.  For example, I would expect there to be a newline after printing the array contents, and a space after "real sum".

Suggested solution

Notice how each method has a one-sentence JavaDoc summary of what it does.  (If you can't write such a summary for a function, then it would be an indication that the function is poorly designed.)

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ArrayAdder {
    private int[] array;

    /**
     * Randomly populates an array of integers of the specified size.
     */
    public ArrayAdder(int size) {
        this.array = new int[size];
        for (int i = 0; i < size; i++) {
            this.array[i] = (int)(9 * Math.random());
        }
    }

    /**
     * The elements of the array, delimited by spaces.
     */
    public String toString() {
        return IntStream.of(this.array)
                        .mapToObj(String::valueOf)
                        .collect(Collectors.joining(" "));
    }

    /**
     * Sums the array using IntStream.
     */
    public int streamSum() {
        return IntStream.of(this.array).sum();
    }

    /**
     * Sums the array by working from the ends toward the middle.
     */
    public int nestedSum() {
        int i, j, sum = 0;
        for (i = 0, j = this.array.length - 1; i < j; i++, j--) {
            sum += this.array[i] + this.array[j];
        }
        if (i == j) {
            sum += this.array[i];
        }
        return sum;
    }

    /**
     * Demonstrates the equivalence of two addition methods on a 5-element array.
     */
    public static void main(String[] args) {
        ArrayAdder demo = new ArrayAdder(5);
        System.out.println(demo);
        System.out.println("Sum using stream: " + demo.streamSum());
        System.out.println("Nested sum: " + demo.nestedSum());
    }
}


While ZeroOne's answer has the good idea to use an enum, the enum itself is not implemented very well. Java enums are a powerful system, and using a switch statement inside the getFileName() method is very unnecessary. Furthermore, the naming conventions are a bit off. Here's a better implementation of the same enum:

private enum FileType {
    QUESTION("question.html"),
    ANSWER("answer.html");

    private final String fileName;

    FileType(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() {
        return fileName;
    }
}

This uses the unique capabilities of Java enums to store individual parameters. This also changes the names of the enum and its values. Java enum names should be upper camel-case (same as class names), while enum values should be all caps.


Update any controls' Text for the specified language

Try using the dynamic keyword (.NET 4.5). Since you just updated the question with information that you are limited to 3.5, I suggest using reflection to get the Text property of the control.

var textAwareControl = (dynamic)control;
try
{
    textAwareControl.Text = SPContext.Current.Web.Locale.LCID == 1033 ?
    DataBinder.Eval(keys.en, control.ID).ToString() :
    DataBinder.Eval(keys.sv, control.ID).ToString();
}
catch (RuntimeBinderException) {
    // throw;
    // throw, or ignore, or make sure to only dispatch compatible controls to this method
}
catch (Exception)
{
    textAwareControl.Text = "Key not found: " + control.ID;
}


Comparing performance between thread, task, parallel

The Console uses synchronization:

  I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams.

This synchronization ensures that all sentences are printed and nothing gets lost due to a data race.

However, synchronization kills multithreading, because the threads will stop at the synchronization object. Don't use Console.WriteLine() for performance comparisons.

Another thing to consider: at the moment you have 3 tasks, each printing 1000 lines. That way, scheduling cannot be done in small pieces. What you typically want is 3000 tasks, each printing 1 line. (read "printing" == "doing work").


Emit different text and sound when each of three buttons is pressed

Slightly modified (using array):

var appearingInPhoto = ["omar", "john", "thomas"]

@IBAction func buttonPressed(_ sender: UIButton) {

    guard let soundName = sender.currentTitle else {
        return
    }
    if appearingInPhoto.contains(soundName) {
        print("pressed \(soundName)")
        label.text = soundName
        playSoundFile(soundName)
    }

}


There are a few issues with the code:

Do not check for == nil when it is not specified as a valid value for the method. Here,checking for it and returning 0 might mask another problem.
Do not use return statements unless necessary. In ruby, almost everything is an expression, and methods return the value of the last expression. Here you can use if...elsif, or case instead of a series of if statement.
Do not modify parameters that come into your function (dice.sort!).
Do not use recursion if it makes the code less readable.

Here is a version of the code with the advice above applied:

def score(dice)
  score = 0
  counts = dice.each_with_object(Hash.new(0)) { |x, h| h[x] += 1 }
  (1..6).each do |i|
    if counts[i] >= 3
      score += (i == 1 ? 1000 : 100 * i)
      counts[i] = [counts[i] - 3, 0].max
    end
    score += counts[i] * (i == 1 ? 100 : 50)
  end
  score
end


For me the main semantic question is whether you should have a section containing articles or an article containing sections. Or perhaps even an article containing other sub-articles.

From the HTML spec:

  The article element represents a complete, or self-contained, composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

It really comes down to the content of your articles and sections.

If each slide could be viewed as an independent thing, then marking them with article seems fine.
If however, you'd expect the slides to be viewed in sequence as in slide show, I'd say the slides should be sections instead.


Batch rename files recursively, and number the directory index

With this code and your example data, both a/c/0.png and b/0.png get renamed to 1_0.png.  This happens because changes to $n inside ( ) get lost when you leave the subshell.

Use bash's "globstar" feature to recurse for you, and assign numbers as normal.  **/ matches all subdirectories.  You want the current directory too, so add . to the list.

This doesn't exactly match your example (A/C will be numbered before B) but it's close:

shopt -s globstar
n=0
for d in ./ **/ ; do
    (
        cd $d &&
            for f in *.png; do
                [[ -f $f ]] && mv "$f" $n"_$f"
            done
    )
    (( n++ ))
done


Reducing a large array of objects to a simple object with 8 properties

I'd flip the field-id-to-name lookup around, and give it some more detail; e.g.

function defaultConverter(values) {
  return values[0].value;
}

var mappings = {
  "89107336": { name: "title", converter: defaultConverter },
  "89107340": { name: "price", converter: defaultConverter },
  "89107344": { name: "desc", converter: defaultConverter },
  "89107337": {
    name: "date",
    converter: function (values) {
      return new Date(values[0].start_date);
    }
  },
  "89107348": {
    name: "img",
    converter: function (values) {
      return values[0].value.file_id;
    }
  },
  "89107415": {
    name: "attendees",
    converter: function (values) {
      var items = values.map(function (v) { return v.value.item_id });
      return JSON.stringify(items);
    }
  }
};

This way you declare how each piece of data should be treated, and you can easily extend it.

Your reduce can then become this:

var output = data.reduce(function (output, obj) {
  var mapper = mappings[obj.field_id];
  if(map) {
    output[map.name] = map.converter(obj.values)
  }
  return output;
}, {});

You can make the mapping declaration a little less repetitive like so:

function Mapping(name, converter) {
  this.name = name;
  this.converter = converter || function (values) { return values[0].value };
}

var mappings = {
  "89107336": new Mapping("title"),
  "89107340": new Mapping("price"),
  "89107344": new Mapping("desc"),
  "89107337": new Mapping("date", function (values) {
    return new Date(values[0].start_date);
  }),
  "89107348": new Mapping("img", function (values) {
    return values[0].value.file_id;
  }),
  "89107415": new Mapping("attendees", function (values) {
    var items = values.map(function (v) { return v.value.item_id });
    return JSON.stringify(items);
  })
};

and still use the same reduce function.


An array of char* is not a great data structure for storing AA or codon sequence data.  A pointer takes 4 or 8 bytes per codon, but there are only 64 possible codons so you could easily store one codon per byte as a uint8_t.  And with only about 22 amino acids, that's close to being able to fit 2 AAs per byte, but it doesn't quite work and it's definitely easier to still use a uint8_t.

Then when you want to print, use that integer as an index into a table of strings.

Or if all you want to do is print out a string, then don't construct an array of strings at all, and just printf as you convert.  Or memcpy 4-byte strings like "Phe " into a buffer to construct a string yourself instead of calling printf separately for each AA name.

(Compilers are good at 4-byte copies, because that's the size of an integer register.  Especially from constant data, because they can inline the data as an immediate if that's optimal.  So make your codon table static const)

slow_i is an odd variable name.  Use aa_idx or something else meaningful, or maybe j.  Or use one i variable and use i*3 + 0, i*3 + 1, and i*3 + 2 to let the compiler figure out what it wants to do.

This very long line: for(nucleobase_count = 0; nucleobase_string[nucleobase_count] != '\0'; nucleobase_count+=1); should be nucleobase_count = strlen(nucleobase_string);.  Use library functions instead of re-inventing the wheel in a hard-to-read long line.  The libc string functions usually have hand-optimized asm implementations that will be fast especially for long strings.

Or even better, have your nucleotide checking function return a count if it doesn't find problem!  You're already looping over the whole string; you don't need to do it again to count the length.

Or even better than that, have your caller pass you the length so you can allocate memory right away and combine checking with converting.  You could have the caller pass you an already-allocated output buffer as well as the length, so it has the option of using a C99 variable-length-array, reusing a buffer it already has allocated, or whatever, instead of baking malloc into your conversion routine.

 codon_table[  // your code
    nucleobase_string[i] == 't' ? 0 :
    nucleobase_string[i] == 'c' ? 1 :
    nucleobase_string[i] == 'a' ? 2 :
    nucleobase_string[i] == 'g' ? 3 : -1
  ][...][...]

If a bad nucleotide did slip through the cracks and make it to this code, you'd have undefined behaviour from reading codon_table[-1][0][0]; out of bounds access.  You could remove the == g part and just have 3 be the last step in the ternary operator, with a comment to indicate that it's g if it wasn't one of the other 3.  Also, that block of ternary operators should go in a tiny helper function like int base_to_idx(char base); instead of being repeated 3 times.

Then you can re-implement it with a table lookup or a perfect hash function.  e.g.

// probably not faster than a table lookup, unless you make a SIMD version
/*
 'a'    0b1100001 -> 0b00
 'c'    0b1100011 -> 0b10
 'g'    0b1100111 -> 0b01
 't'    0b1110100 -> 0b11
*/
unsigned nuc_to_idx(unsigned base) {
    if (base == 'a' || base == 'c' || base == 'g' || base == 't')
        return (base*3 & 0x3<<2)>>2;
    return -128U;
}

or a table lookup version that does a whole codon and returns an integer code.  I used C designated-initializer syntax, plus a GNU extension to for ranges to make the table static const.  You could also init it at runtime with memset(table, -1,  UCHAR_MAX); and then assign the 4 valid values.

#include <stdint.h>
#include <limits.h>

// int8_t sign extends to the width of int / unsigned int
// so all the high bits get set before treating as unsigned (assuming 2's complement), for BAD_NUC inputs.
// But we don't depend on that: we still get an unsigned value > 64
// on sign/magnitude or one's complement machines if any of the 3 chars is bogus.

#define BAD_NUC -128
static const int8_t nuc_table[UCHAR_MAX+1] = {
    [0 ... 255] = BAD_NUC,  // ranges are a GNU extension
    // last init takes precedence  https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html
    ['a'] = 0,
    ['c'] = 1,
    ['g'] = 2,
    ['t'] = 3,
};
// Fun fact: doesn't depend on ASCII encoding because of the designated-initializers.

// unsigned char* so high-ASCII -> 128..255, not negative,
// and works as an index into a 256 entry table
unsigned codon_to_idx_LUT(unsigned char *p) {

    unsigned idx = nuc_table[p[0]];
    idx = idx*4 + nuc_table[p[1]];
    idx = idx*4 + nuc_table[p[2]];
    return idx;
    // 0..63 for in-range values, otherwise has higher bits set
    // so you only have to range-check once per codon, speeding up the common case of no error.

    // to map to AA codes, maybe use a lookup table on this 0..63 value
}

The table version compiles really efficiently on x86 with gcc -O3  (on the Godbolt compiler explorer), or hopefully with any sane compiler.  (The if condition in the perfect-hash version does compile to an immediate bitmap, which is neat, but it still has to test/branch multiple times for every character instead of just doing 2 loads.)

codon_to_idx_LUT:                # gcc7.3 -O3 for x86-64 System V calling convention: pointer arg in RDI
    movzx   eax, BYTE PTR [rdi]
    movsx   edx, BYTE PTR nuc_table[rax]
    movzx   eax, BYTE PTR [rdi+1]
    movsx   eax, BYTE PTR nuc_table[rax]
    lea     edx, [rax+rdx*4]              # this is why I wrote it as idx*4 + nuc_table[...] instead of some other way of multiplying and adding the results.
    movzx   eax, BYTE PTR [rdi+2]
    movsx   eax, BYTE PTR nuc_table[rax]
    lea     eax, [rax+rdx*4]
    ret

This would run even faster if the compiler did one wider load and unpacked it with ALU instructions instead of loading each string byte separately.  Running this in a loop is going to bottleneck on 2 loads per clock on mainstream Intel/AMD CPUs, so about 1 nucleotide per clock cycle, which is not bad.  The overhead of checking the index for in-range (to detect bogus nucleotide characters) should be negligible compared to the string loads + table lookups.  Especially on CPUs that can only do one load per clock.

(Related this Q&A for more about tweaking your C source to hand-hold the compiler into making better asm.  You could do that here, but only at the cost of readability, I think.  You'd probably have to do a dodgy pointer-cast or a safe memcpy and read 4 bytes as a uint32_t and unpack that.)

You can use this 0..63 codon as an index into a table of strings for printing.  (Just flatten your current 3D array, although I didn't make any effort to be consistent with which numbers go with which DNA base in the hash or table vs. your version.)


C++ compile-time checked switch 'statement'

That seems like an awful lot of boilerplate code to replace a single diagnostic that already exists in a lot of compilers. You're replacing

switch (fruit) {
  case APPLE: return "apple"; break;
  case PEAR: return "pear"; break;
  case PLUM: return "plum"; break;
}

with

<at file scope>
NEWSWITCH(uniqueID, std::string);
DEFCASE(uniqueID, APPLE) { return "apple"; }
DEFCASE(uniqueID, PEAR) { return "pear"; }
DEFCASE(uniqueID, PLUM) { return "plum"; }
DEFDEFAULT(uniqueID) { assert(false); }

...
Switch<NumTypes>(uniqueID(), fruit);

The most onerous requirement there is putting all the switch logic at file scope; you can't localize it to the actual codepath where it's going to be used. The second most onerous requirement is coming up with uniqueID, a global identifier which must be different for each switch that you convert using this pattern.

A much better solution to your original problem would be to use an array:

int main() {
    MyType iType = TypeB;

    std::string typenames[NumTypes] = { "TypeA", "TypeB", "TypeC" };

    assert(0 <= (int)iType && (int)iType < NumTypes);
    std::string zTypeName = typenames[iType];

    std::cout << "Type name: " << zTypeName << std::endl;
}

This code statically enforces that each index in 0..NumTypes-1 is associated with a std::string in the array; and (just like your original code) it dynamically asserts that iType is in the proper range.


Interface

Why return the value added? That's unusual and unexpected.

Bug

It's unusual to allow adding duplicate values.
It would be better to ignore.

Avoid flag variables when possible

The flag variable inserted is unnecessary.

while (true) {
    if (item > currNode.value) {
        if (currNode.rightNode) currNode = currNode.rightNode;
        else {
            currNode.rightNode = {
                value: item
            };
            return;
        }
    } else {
        if (currNode.leftNode) currNode = currNode.leftNode;
        else {
            currNode.leftNode = {
                value: item
            };
            return;
        }
    }
}

I replaced the insert = true statements with return.
If you really want to return item, then you can either use that instead of return, or use break.


Other algorithms

Wikipedia has an article which lists other Factoring algorithms.

Your algorithm

Re. your algorithm, I see you're checking all odd numbers, which includes non-prime numbers such as 9.

Your sieve would be faster if you only checked prime numbers, for example by using a list like this one or this one.

Furthermore you're checking all the way to subject. Your last time through the loop would be faster if you give up as soon as nextFactor > sqrt(subject).

Your C# code

As for your C# code:

What type is nextFactor when you declare it as var nextFactor = 2;? I fear that it might be int not long.
Your code might be very slightly faster if you used the Capacity property of List.
There's something very strange (and slow) about your loop: after you find a nextFactor value such as 7, then you begin your search from 2 again! You code would be faster if you moved your long nextFactor = 2; initialization to do it only once, before/outside the while loop, and changed your nextFactor = 3; statement to nextFactor += (nextFactor == 2) ? 1 : 2;. You could then also eliminate your maxFactor variable, because the largest factor value would be left/stored in nextValue after you exit the while loop.
It might be better to use System.Numerics.BigInteger instead of long (because long.MaxValue is only about 10^18, whereas some people want to factorize larger numbers than that).


Determine if points are within a rotated rectangle

Code Review

Main guard

When running code outside a function / class, it is a good practice to put the code inside the main guard. See here for more explanation.

Docstrings

It is a good practice to provide docstrings for functions. See here for more details. In Python 3.5+, adding type hints to function parameters and return values is also a good habit. (As a side remark, Python 2 has officially reached the end of life. It is recommended to move to Python 3.)

Variable & function names should be clear, descriptive, and unambiguous

For example, check_point could be named as is_inside_rectangle.

Function definition should include all necessary parameters

vertices should be a parameter of the function check_point.

Other minor improvements

By exploiting the fact that vertices[-1] is the same as vertices[len(vertices)-1], the explicit modulo operation vertices[(i + 1) % len(vertices)] could be avoided.
The for-loop logic can be simplified using an all statement.
Here is an improved version of the code:
def dot_prod_with_shared_start(start, end1, end2):
    """
    Compute the dot product of the vectors pointing from start to end1 and end2

    Parameters
        start: starting point of both vectors
        end1: end point of first vector
        end2: end point of second vector

    Returns
        dot product of (end1 - start) and (end2 - start)
    """
    return (end1[0] - start[0]) * (end2[0] - start[0]) + (end1[1] - start[1]) * (end2[1] - start[1])

def is_inside_rectangle(vertices, point):
    """
    Given the vertices of a rectangle, determine whether a point is inside it.

    Parameters
        vertices: a list of tuples representing rectangle vertices in clockwise or
                  counter-clockwise order
        point: a tuple representing the point to check

    Returns
        True if the point is inside the rectangle. False otherwise.
    """
    return all(dot_prod_with_shared_start(vertices[i - 1], v, point) > 0 for i, v in enumerate(vertices))

if __name__ == "__main__":
   rect_vertices = [(670273, 4879507), (677241, 4859302), (670388, 4856938), (663420, 4877144)]
   test_point = (676455.270, 4861545.437)

   print(is_inside_rectangle(rect_vertices, test_point))

Another Solution
An alternative solution is to represent the vertices and the point as complex values, and apply complex number arithmetics to solve the problem.
def is_directed_angle_acute(start, end1, end2):
    """
    Check whether the directed angle from (end1 - start) to (end2 - start) is an acute angle,
    i.e. within (0, pi / 4).

    Parameters
        start: a complex value representing the starting point of both vectors
        end1: a complex value representing the end point of first vector
        end2: a complex value representing the end point of second vector

    Returns
        True if the directed angle from (end1 - start) to (end2 - start) is within (0, pi / 4).
        False otherwise.
    """
    q = (end2 - start) / (end1 - start)
    return q.real > 0 and q.imag > 0

def is_inside_rectangle(vertices, point):
    """
    Given the vertices of a rectangle, determine whether a point is inside it.

    Parameters
        vertices: a list of complex values representing rectangle vertices in clockwise order
        point: a complex value representing the point to check

    Returns
        True if the point is inside the rectangle. False otherwise.
    """
    v0, v1, v2, v3 = vertices
    return is_directed_angle_acute(v0, point, v1) and is_directed_angle_acute(v2, point, v3)

if __name__ == "__main__":
   rect_vertices = [670273 + 4879507j, 677241 + 4859302j, 670388 + 4856938j, 663420 + 4877144j]
   test_point = 676455.270 + 4861545.437j

   print(is_inside_rectangle(rect_vertices, test_point))


Find 2 numbers that multiply to a number and add to another number

Code Review

while solved == False: is an awkward way of writing the loop condition.  while not solved: would be clearer and more Pythonic.

You never set solved = True anywhere.  Instead, you unconditionally break out of the loop.  This means your loop could actually be written while True:, but I don't think this is clearer.  Using solved = True instead of break would terminate the loop in an expected way.

This is verbose:

    nums = random.sample(range(-100, 150), 2)
    if (nums[0] + nums[1] == add_to) and (nums[0] * nums[1] == multiply_to):

You could unpack nums into to individual variables, and avoid the [0] and [1] indexing operations, for more performant code:

    x1, x2 = random.sample(range(-100, 150), 2)
    if x1 + x2 == add_to and x1 * x2 == multiply_to:

If you give values which can never work with integers, like add to 2 and multiply to 3, you have an infinite loop.  You should have a "give up after so many attempts" procedure.

Monte Carlo

As pointed out by Peilonrayz, there is an \$O(1)\$ solution to the problem.

However, if your goal is to utilize a Monte Carlo simulation method ...

If multiply_to is:

positive, then the numbers must be the same sign, both positive or both negative, which you could determine by looking at the add_to sign,
negative, then one number must be greater than zero, and the other must be less than zero,
zero, then one number must be zero.

eg)

if multiply_to > 0:
    if add_to > 0:
        r1 = range(1, add_to)
        r2 = range(1, add_to)
    else:
        r1 = range(add_to + 1, 0)
        r2 = range(add_to + 1, 0)

elif multiply_to < 0:
    r1 = range(1, 150)   # A positive value in your initial range bracket
    r2 = range(-100, 0)  # A negative value in your initial range bracket

else:
    r1 = range(add_to, add_to + 1)
    r2 = range(0, 1)

for _ in range(10_000):
    x1 = random.choice(r1)
    x2 = random.choice(r2)
    if x1 + x2 == add_to and x1 * x2 == multiply_to:
        print(f"Solved: {x1} + {x2} = {add_to}, {x1} * {x2} = {multiply_to}")
        break
else:
    print("Couldn't find a solution")


Is there a better, more object oriented way to write this Finder method?

If you're going to hard-code conditions for each class you want to support, there isn't much point to using a generic type. You don't even reference T within the method body, so it isn't any different from:

private static String nameById(Class whatClass, int id) {
    if(ProjectCode.class == whatClass) {
        // ...
    } else if(TransactionType.class == whatClass) {
        // ...
    }
    else if(CurrencyType.class == whatClass) {
        // ...
    }
    return null;
}

To write this method so it's reusable with a generic type, you'll need to also abstract both your methods for obtaining a collection, and your getters for obtaining instances' name and Id.

e.g.

Some getObjects<T> method, called like getObjects<TransactionType>() instead of getTransactionTypes()
The ability to access object properties polymorphically, through some interface that requires each class to have getId() and getName() instead of separate methods such as getTransactionTypeId(), getProjCdId(), etc.

Then your code could be rewritten to take advantage of a generic type parameter:

public static <T extends IInterfaceName> String nameByID(int id) {
    for (T obj : getObjects<T>()) {
        if(obj.getId().equals(id)) {
            return obj.getName();
        }
    }
    return null;
}


A web scraper that looks for pre-defined words in news articles

At first glance, I'd say that this code isn't bad.  I am particularly impressed by this line:

regex = r"\b"+ re.escape(word) + r"\b"

because you took the care to escape the word, and to ensure that it is starts and ends at word boundaries.  (You might want to do case-insensitive searches, though?  Also, you might want to treat all whitespace as equivalent, in case a newline occurs in the middle of a phrase.)

You do have a bug, though, in that the on-screen output reports all hits as coming from the last title in the RSS feed.

Code organization

This program is starting to be long enough that you should break it up into functions.  In particular, when the code gets long, all of the variables (hit_article, links_list, hits, hit_link, d, etc.) act as global variables, making it hard to keep track of how they are used.  That is the root cause of your title bug.

Wasted work

The silliest mistake is that tree = html.fromstring(page.content) is never used, so you used the lxml library to parse the HTML a second time for no reason.

Less obviously, you have a problem if one article contains multiple search terms.  The on-screen printout will report all terms that were found.  However, when you do dict(zip(hit_link, hits)), you will only store the last hit per link.  You'll need to decide whether you want to:

report all search terms that are found in each article (in which case you need to modify the data structure to store more results, or eliminate the dictionary entirely)
report only the first search term in your list that appears in each article (in which case you can break from the if match: block)
report only the first occurrence in the article of any of the search terms (in which case you should construct the regex to look for any of the search terms: regex = r'\b(?:' + '|'.join(re.escape(word) for word in words) + ')\b', instead of looping)

Comprehensions

In general, whenever you see the pattern:

output_list = []
for item in input_list:
     output_list.append(transform(item))

… you can write it more elegantly using a list comprehension.

For example, instead of:

list_list = []
d = feedparser.parse('http://www.dailymail.co.uk/articles.rss')
for item in d.entries:
    link = ( item[ "link" ] )
    links_list.append(link)

You should write (with a bit of renaming for clarity):

 rss_url = …
 links = [entry['link'] for entry in feedparser.parse(rss_url).entries]

Suggested solution

Here, I've elected to report all terms found in each article, by eliminating the match_dictionary altogether.  I've used two generator functions.

from bs4 import BeautifulSoup
import csv
import feedparser
import re
import requests

def search_article(url, phrases):
    """
    Yield all of the specified phrases that occur in the HTML body of the URL.
    """
    response = requests.get(url)
    text = BeautifulSoup(response.text, 'html.parser').find('body').text
    for phrase in phrases:
        if re.search(r'\b' + re.escape(phrase) + r'\b', text):
            yield phrase

def search_rss(rss_entries, phrases):
    """
    Search articles listed in the RSS entries for phases, yielding
    (url, article_title, phrase) tuples.
    """
    for entry in rss_entries:
        for hit_phrase in search_article(entry['link'], phrases):
            yield entry['link'], entry['title'], hit_phrase

def main(rss_url, phrases, output_csv_path, rss_limit=None):
    rss_entries = feedparser.parse(rss_url).entries[:rss_limit]
    with open(output_csv_path, 'w') as f:
        w = csv.writer(f)
        for url, title, phrase in search_rss(rss_entries, phrases):
            print('"{0}" found in "{1}"'.format(phrase, title))
            w.writerow([url, phrase])

if __name__ == '__main__':
    rss_url = 'http://www.dailymail.co.uk/articles.rss'
    phrases = ['divorce', 'custody battle', …]
    main(rss_url, phrases, 'output.csv', 100)


One of the nice things with recursion is that you can use it for argument handling.

Where you have a conditional to handle the b > a condition, you could instead use recursion.....

def gcd(a, b):
    """Returns the greatest common divisor of a and b.
    Should be implemented using recursion.

    >>> gcd(34, 19)
    1
    >>> gcd(39, 91)
    13
    >>> gcd(20, 30)
    10
    >>> gcd(40, 40)
    40
    """
    if b > a:
        return gcd(b, a)

    if a % b == 0:
        return b

    return gcd(b, a % b)


Is there a better way to traverse an inheritance tree?

One way to only have one yield statement would be to recursion instead of a loop:

def root(&blk)
  yield self if blk
  if root?
    self
  else
    parent.root(&blk)
  end
end

Of course the usual caveats regarding recursion in ruby apply, so this isn't necessarily a good idea: It is somewhat expensive and can lead to stack overflows if you recurse deep enough (though it's rather unlikely, you'd encounter a tree deep enough to reach that limit).

Unrelated to this, the name until_root seems somewhat clunky to me. I would recommend each_ancestor instead. In fact I think it would be good idea to have the method return an enumerable of ancestors when no block is given. Then it could just be called ancestors. Of course that would require separating ancestors and root into two separate methods. root could then just be defined as ancestors.last:

# Returns an Enumerable containing the ancestors of this node, starting with
# the node itself and ending with the root.
# If a block is supplied, each ancestor will be yielded to the block instead
# of returning an enumerable.
def ancestors
  return enum_for(:ancestors) unless block_given?

  element = self
  until element.root?
    yield element
    element = element.parent
  end
  yield element
end

def root
  ancestors.last
end

If you do it that way, you can also leave out the if block_given? part of the yield statements because it will return early when no block was given.

As a matter of fact, you can now remove the second yield completely by changing the loop to loop while element is not nil instead of until the root is reached (assuming element.parent will return nil if the element is the root):

def ancestors
  return enum_for(:ancestors) unless block_given?

  element = self
  while element
    yield element
    element = element.parent
  end
end


I'm aware that you are a beginner. So I will try to improve your code starting from the most obvious problems and try advance step by step.

Variable names

Names like x, y, z are an absolute no-go (unless naming coordinates). This is like naming them guesswhat. Names should describe what the variable holds as close to natural language as possible. So legal names for x, y, z would be long, short, none. Aloso other names are far from perfect. for SingLetter in LetterInput: should read for letter in message:. You generate a lot of temporary variables which requires you to invent a lot of names. Try avoid some temporaries and/or name temporaries 'less important' than variables you want to use later on. SingLetUp = SingLetter.upper() could read letter = letter.upper(). When reading SingLetUp I do think of 'singing', 'letting' and 'up'. There is no need to save letters in names, if a long name is needed, let it be. But a letter is always a single one, a group of letters shall be named 'word' or 'message' anyway.

Temporaries

As already said, you tend to use too many of them. one case where it makes the code bloated and thus less readable is

x = 'short'
y = 'long'
z = 'none'

and the only later use

if sing == x:

this useless. if named correctly this would read

short = 'short'
# ...
if symbol == short:

which shows the redundancy. it could simply read

if symbol == 'short':

saving some lines without any negative implications.

Do not repeat yourself

This is one of the most important rules to consider. In

if sing == x:
    GPIO.output(18, GPIO.HIGH)
    time.sleep(0.2)
    GPIO.output(18, GPIO.LOW)
    time.sleep(0.5)

if sing == y:
    GPIO.output(18, GPIO.HIGH)
    time.sleep(1)
    GPIO.output(18, GPIO.LOW)
    time.sleep(0.5)

you have two code blocks differing by just one value. all the other parts are required(!) to be identical. this is asking for a function definition (I'm not sure if you already learned that). We do something like (still not perfect)

def gpio_out(length):
    GPIO.output(18, GPIO.HIGH)
    time.sleep(length)
    GPIO.output(18, GPIO.LOW)
    time.sleep(0.5)

and use it like

if symbol == 'short':
    gpio_out(0.2)

if symbol == 'long':
    gpio_out(1)

Do not use 'magic values' in the code but define named constants

The most obvious use cases is to change the GPIO pin. The value 18 is appearing 7 times in your source and must be maintained to match. forgetting to change one will lead to subtle errors. So we do

morse_gpio = 18

and use this name throughout the code. the same applies to all other constants, especially the time values.

About morse code and your implementation

the most frequent letters in western languages are 'e', 't', 'n', ... that is why Morse assigned short codes to these letters. you are outputting many 'none' instead of a single pause separating letters. we fix this by not outputting anything on 'none' but inserting a single pause.

for symbol in pos:
    if symbol == 'short':
        gpio_out(0.2)
    if symbol == 'long':
        gpio_out(1)
    if symbol == 'none':
        pass
time.sleep(1)

Reading the csv file

While this might have been part of your assignment - csv is a little heavy here. this is implicitely shown in your code as you never use the header names. Another hint is that you have to use fill values of none. However you could read such a simple file in python directly. Also we get rid of this superfluous 'none' immediately. Nowhere in the code we are expecting a fixed length code, quite contrary we have special handling for it.

letters = []    #a new list with letters only
codes = []      #a new list with morse code only
with open('Morse.csv') as codefile:
    next(codefile)  #jump over the column description line and an empty line
    next(codefile)
    for line in codefile:
        words = line.strip().split(',')
        letters.append(words[0])    # append letter
        code = [x for x in words[1:] if x != 'none']
        codes.append(code)          # append effective code only

here i used list [comprehension https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions]

Use the right data structures

If you want to look up code for a letter you want to write code = codes[letter] which is clean and readable. so we use a dict for storing our codes

codes = dict()
with open('Morse.csv') as codefile:
    next(codefile)  #jump over the column description line and an empty line
    next(codefile)
    for line in codefile:
        words = line.strip().split(',')
        code = [x for x in words[1:] if x != 'none']
        codes[words[0]] = code          # append effective code only

and rewrite the access

MorseCode = [] #a new list where the final code for the LED input is saved

for SingLetter in LetterInput: #iterate through the input

    SingLetUp = SingLetter.upper() #capitalize letters so they can be found in csv

    if SingLetUp not in letters: #jump over spaces and special characters
        continue

    MorseDex = letters.index(SingLetUp) #find code that corresponds with letter by matching indices
    SingCode = codes[MorseDex]
    MorseCode.append(SingCode) #fill up list

to

morse_code = [] #a new list where the final code for the LED input is saved

for letter in message.upper(): #iterate through the input

    if letter in codes:     # ignore spaces and special characters
        morse_code.append(codes[letter])    # fill up list

Structure your code

Avoid so called spaghetti code, that is many lines of code at the same name space. As already stated about your variable names, have good names and make clear what scope they have. when using functions local variables are not visible outside. this improves readability and avoids name collisions. so we define some functions of already identified code blocks

def read_codes():
    #[...]
    return codes

def encode(message, codes):
    #[...]
    return code

def output_code(code):
    #[...]

and use it them like

codes = read_codes()
message = input('what do you want to morse? ')
code = encode(message, codes)
output_code(code)

Thas limits visibility of name like code or letter. also it adds testability. we can now call encode from some testcases without needing interactive user input.

Further down on internal data representation

When doing debugging you most probably do not want to print [['short', 'long'], ['short'], ['long']] more likely you want to print .- . -. So why not represent the symbols as shorter characters througout the code? We improve our existing function

def read_codes():
    codes = dict()
    with open('Morse.csv') as codefile:
        next(codefile)  #jump over the column description line and an empty line
        next(codefile)
        for line in codefile:
            words = line.strip().split(',')
            code = [x for x in words[1:] if x != 'none']
            codes[words[0]] = code          # append effective code only
    return codes

to

for line in codefile:
    words = line.strip().split(',')
    shortcode = {'long':'-', 'short':'.'}
    code = [shortcode[x] for x in words[1:] if x != 'none']
    codes[words[0]] = ''.join(code)          # append effective code only

here we do not only replace longer strings by characters but also join this characters to a string. this string allows better logging. For print(encode("Hello world!", codes)) we get ['....', '.', '.-..', '.-..', '---', '.--', '---', '.-.', '.-..', '-..']. Wouldn't it be nice to have '.... . .-.. .-.. --- .-- --- .-. .-.. -..' where the blanks represent the pause between letters? this would make the output loop better as it would not do an additional pause at the end. So somewhere in the code we should do ' '.join(code), either just before outputting or in encoding. your choice. for debugging I'd prefer to have it in encoding.

def encode(message, codes):
    code = []    # a new list where the final code for the LED input is saved
    for letter in message.upper(): #iterate through the input
        if letter in codes: #jump over spaces and special characters
            code.append(codes[letter]) #fill up list
    return ' '.join(code)

of course we now have to fix the output

def output_code(code):
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.OUT)

    for symbol in code:
        print(symbol, end='', flush=True) # debug output

        if symbol == '.':
            gpio_out(0.2)
        elif symbol == '-':
            gpio_out(1)
        else:
            time.sleep(1)

    GPIO.output(18, GPIO.LOW)
    GPIO.cleanup()

Note that we also encapsulated all GPIO stuff in this function. there is no neet to initialize GPIOs before outputting.

Main guard

In python modules may be run directly or they may be imported by some other module e. g. a unit test. So there is a pattern to avoid hassle on import

if __name__ == '__main__':
    # stuff only executed on direct execution but not on import

current state of our module now

import RPi.GPIO as GPIO
import time

symbol_long = 1
symbol_short = 0.2
symbol_pause = 0.5
letter_pause = 1
morse_gpio = 18

def read_codes():
    codes = dict()
    with open('Morse.csv') as codefile:
        next(codefile)  #jump over the column description line and an empty line
        next(codefile)
        for line in codefile:
            words = line.strip().split(',')
            shortcode = {'long':'-', 'short':'.'}
            code = [shortcode[x] for x in words[1:] if x != 'none']
            codes[words[0]] = ''.join(code)          # append effective code only
    return codes

def encode(message, codes):
    code = []    # a new list where the final code for the LED input is saved
    for letter in message.upper(): #iterate through the input
        if letter in codes: #jump over spaces and special characters
            code.append(codes[letter]) #fill up list
    return ' '.join(code) #

def gpio_out(length):
    GPIO.output(morse_gpio, GPIO.HIGH)
    time.sleep(length)
    GPIO.output(morse_gpio, GPIO.LOW)
    time.sleep(symbol_pause)

def output_code(code):
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(morse_gpio, GPIO.OUT)
    for symbol in code:
        print(symbol, end='', flush=True) # debug output

        if symbol == '.':
            gpio_out(symbol_short)
        elif symbol == '-':
            gpio_out(symbol_long)
        else:
            time.sleep(letter_pause)
    GPIO.output(morse_gpio, GPIO.LOW)
    GPIO.cleanup()

if __name__ == '__main__':
    codes = read_codes()
    print(codes) # debug output
    message = input('what do you want to morse? ')
    code = encode(message, codes)
    print(code) # debug output
    output_code(code)

Still to do

Better comments - comment what is not obvious.
Docstrings - explain what your functions do. Better encapsulation - avoid globals and pass parameters to functions.
unit testing - worth to look at.


There are two issues you should watch out for:

This will block the current thread while it's running. For a large file, this could be a substantial amount of time. You should consider moving this code out to a Sidekiq (or similar) worker, so that you aren't blocking threads in your web app.
When you rescue exceptions, you just puts them, which you're likely to ignore in production. You should be logging that exception to a place that you can get ahold of it later. I would personally just not rescue it and use BugSnag or similar in my application to ensure that errors are collected and kept for resolution.


I think the place where recursion is least appropriate is when you advance a queen until it is safe from all queens with a lower index (i.e. the last line of the method placeQueen(Queen[], int)). This doesn't really seem like a recursive process to me, but rather like something that calls for a loop.

private static void placeQueen(Queen[] queens, int index) {
    while (!queens[index].isSafe(queens) && queens[index].canAdvance()) {
        queens[index].advance();
    }

    if (!queens[index].canAdvance()
            && (!queens[index].isSafe(queens)
            || index != 7)) {
        while (index > 0 && !queens[index].canAdvance()) {
            --index;
        }
        queens[index].advance();
        placeQueen(queens, index);
    } else if (index != 7) {

        // next queen is set to position of current queen
        queens[index + 1].matchPosition(queens[index]);
        ++index;
        placeQueen(queens, index);
    }
}

This advances a queen until it is either safe or can no longer be advanced, which is basically what your code did, but here, this is achieved without recursion, saving a lot of stack memory.


Counting Bouncy Numbers: Project Euler #113

Project Euler problems generally can be computed with a calculator or manually.
So, take a different approach:

For ascending numbers, choose the transitions (digits 0-9; 9 transitions).
For descending numbers, choose the transitions (initial zeros, digits 9-0; 10 transitions).
Subtract those where initial zeros are followed only by a non-empty string of a single repeated digit (0-9) (1 transition, but the last place cannot be chosen).
Subtract the case of only the initial zeros.

In the end you have to calculate:

$$\binom{100+9}{9} + \binom{100 + 10}{10} - 10 * \binom{100}{1} - 1 = \binom{109}{9} + \binom{110}{10} - 1001$$


split-string can be simplified

You're defining a function that takes an argument s and applies the composite of 3 different clojure.string functions to s within the body of the function. You could simplify this in 2 ways:

(require '[clojure.string] :as s) -- now you can call all three functions in a much more concise way, e.g. s/split.
(comp fn1 fn2 fn3 s) is already a function, so you could actually define split-string as just that, without needing to repeat s as part of the function. See below:

(require '[clojure.string :as s])

(def split-string
  (comp #(s/split % #"\s+") s/upper-case #(s/replace % #"," "")))

This is just a matter of preference, but I would find it easier to read if you used a threading macro instead:

(defn split-string [s]
  (-> s (s/replace #"," "") s/upper-case (s/split #"\s+")))

defn should only be at the top level

In your code, you have the equivalent of this:

(letfn [(foo [x] (bar x))]
  (defn baz [y] (foo y)))

(To be more specific, I'm talking about (letfn [(find-last-occurrence-index-of ...) (split-string [s] ...)] (defn extract-us address [s] ...)))

Having a defn inside of a let form is un-idiomatic, and can be a little bit confusing at first glance. The general rule is to only have def forms (including defn, defmacro, etc.) at the top level of your code. You can fix this by simply flipping it so that the letfn part is inside the defn part, like this:

(defn baz [y]
  (letfn [(foo [x] (bar x))]
    (foo y)))

This way, it is more clear that the functions being "let'd" are internal to the function.

Combine when/let bindings when possible

The main thing I notice, looking at your extract-us-address function, is that there are multiple let and when statements. Sometimes this is unavoidable, but often you can tidy up your code by combining multiple bindings into a single let form. You could do something like the code below. Notice also that I've included your "letfns" find-last-occurrence-index-of and split-string as anonymous functions within the let bindings.

(defn extract-us-address [s]
  (let [find-last-occurrence-index-of
        (fn [lookup-map coll]
          (last (keep-indexed #(when (contains? lookup-map %2) %1) coll)))

        split-string
        (fn [s]
          (-> s (s/replace #"," "") s/upper-case (s/split #"\s+")))

        parts (split-string s)]
    ...

Use helper functions

The other thing I notice is that you have one fairly complex function, where you could have one "main" function (extract-us-address) which relies on a handful of seperate "helper" functions. Doing it that way generally makes your code easier to read. Here's an idea of how you could refactor your code into several smaller functions:

; (to make it clearer which functions are helper functions, mark
; them as private functions by using defn- instead of defn)

(defn- find-last-occurrence-index-of [lookup-map coll]
  (last (keep-indexed #(when (contains? lookup-map %2) %1) coll)))

; You could rename split-string to parts, then refer to (parts s),
; thereby avoiding needing to bind (split-string s) to parts in a
; let binding. I think this more clearly describes what the function
; is doing, as well.
(defn- parts [s]
  (-> s (s/replace #"," "") s/upper-case (s/split #"\s+")))

(defn- zip-code [s]
  (re-matches #"^\d{5}$" (last (parts s))))

(defn- street-index [s]
  (find-last-occurrence-index-of street-suffix-lookup (parts s)))

(defn- state-index [s]
  (find-last-occurrence-index-of state-abbreviation-lookup (parts s)))

(defn extract-us-address [s]
  ; this let binding is here to help performance -- we only want to evaluate
  ; each of these once, and bind it to a symbol
  (let [zip-code (zip-code s)
        street-index (street-index s)
        state-index (state-index s)]
    (when (and zip-code street-index state-index)
      (UsAddress.
        (clojure.string/join " " (take (inc street-index) (parts s)))
        (clojure.string/join " " (drop (inc street-index) (take state-index (parts s))))
        (state-abbreviation-lookup (nth (parts s) state-index))
        zip-code))))

Is there a better way to do this?

I noticed that there are a couple of potential flaws with your algorithm:

It relies on the fact(/assumption?) that there are no street suffixes that overlap with state abbreviations. This might be OK (I can't think of any examples that would break this), but it seems like a potential problem. This is a really contrived idea, but what if the street suffix "Ca" for "calle" catches on? Your code wouldn't know how to tell apart CAlle from CAlifornia.
It doesn't return nil if the state is missing from where it's supposed to be, but present somewhere else, like in the street address. For example, try running your program on an address like "1000 NC HWY 70, RALEIGH, 27602." Assuming you have "HWY" listed as a suffix, you would expect nil (because the state is missing), but you would get #user.UsAddress{:street "1000 NC HWY", :city "", :state "NC", :zipcode "27602"}. The problem is that you're working with indices and the state-index has the potential to fall within the street address rather than after the city where you would expect it. This is only a problem if the state is missing from where it belongs, but it's still a problem.

I can think of two potential approaches that might be better:

A. Iterate through the address "parts" in reverse -- look at the last thing and see if it qualifies as a zip code -- if so, move on and look at the next-to-last thing -- does it qualify as a state or state abbreviation? if so, hang onto the state abbrevation and move on. Then you can separate the street address from the city by looking for the last thing that qualifies as a street suffix.

B. Use a parsing library such as Instaparse. This would be my preferred approach. I've found that using a parsing library tends to greatly simplify things, as the library does all of the hard work for you. All you have to do is specify a grammar and wrap it in a parser, then do (your-parser address-string) and it will return a structure (called a "parse tree") something like this:

[:address
  [:street-address "3526 HIGH" [:suffix "ST"]]
  [:city "SACRAMENTO"]
  [:state "CA"]
  [:zip "95838"]]

If you're new to defining a PEG grammar, there is a small learning curve, but it's actually surprisingly simple once you get the hang of it. Your grammar would look something like this:

address        = street-address <ows> city <ows> state <ows> zip
street-address = word+ suffix
city           = word+
word           = !suffix \w+ <ows>
suffix         = "ST" | "STREET" | "DR" | "DRIVE" (* etc. *)
state          = "AK" | "AL" | (* etc. *)
zip            = #"\d{5}"
ows            = #"[\s,]*"   (* optional whitespace / commas *)

(Note: I haven't tested the above, so it may or may not work properly.)

From there, it's easy to transform your parse tree into whatever form you'd like to represent each address. Personally I find this method easier, and it definitely makes your code look a lot cleaner and simpler.


Toy Vector Library - Magnitude & Unit Vector Functions

It is custom/industry de facto standard to place the parameter to be changed first, as done in memcpy, strcpy etc (this tradition goes all the way back to assembler).

So you should do void vec2_unit (vec2_t* dst, const vec2_t* src);.
Regarding in-place or not, it is mostly a matter of style in this case.

Functions/APIs working on "immutable" objects (objects not modified by the function) are often considered better style when that option is available, since that minimizes the chance of caller-side bugs.

The discussion about in-place vs immutable mostly makes sense for larger data types, where taking a copy of the data object is regarded as costly. A struct with 2 double isn't really that heavy to copy(note 1), so you could design this API with an immutable object interface. You could even get away with passing the structs to/from the functions by value, which is otherwise normally frowned upon.

Note: if these functions will reside in the same translation unit as the caller code (which doesn't seem likely here?), the whole discussion about performance is pointless since they will be inlined anyway in that case.
If you go for the immutable version, it could be written as

void vec2_unit (vec2_t* restrict dst, const vec2_t* restrict src);

This tells the compiler and the caller both that these two objects shall not be the same one. That will in turn increase performance, but it will not allow you to pass the same object as both source and destination.

(note 1) We can assume that systems using double are able to copy it in a few instructions. Systems where copying a double would be lots of work, such as small microcontroller systems, shouldn't be using double (or float) in the first place, since they lack a FPU. I would safely assume that any program using floating point is meant to run on a Cortex M3 or bigger.


Review

Your final return statement is redundant.
The use of const is correct here (rawObjectKey, rawObjectValue) because you only assign these variables once. Many developers tend to use let or var here incorrectly.
Your method is a bit convoluted with those almost-equal code blocks. convertedObject = {...convertedObject, ...

Alternative

You could write this more compact, DRY and using built-in function reduce. We start with an empty object {} and inject each entry with the flattened data to obtain the result.

 const convertedObject = Object.entries(rawObject).reduce(
  (acc, item) => {
    acc[item[0]] = item[1] != null ? item[1].value : null;
    return acc;
  }, {});

Future Releases

There is a thing called optional chaining aka null propagation aka the Elvis operator. It's not standard Typescript (yet?), but is already supported in babel-plugin-proposal-optional-chaining.

This is a feature request to track. If ever implemented, it would allow us to call something like item[1]?.value:null instead of item[1] != null ? item[1].value : null.


Well, better and more elegant are quite opinion based and depend on different things: a code can be better regarding performance but worse regarding clarity.

That being said, I'd like to drop my two cents: since you just want to know if a given word begins with the input string (which is different from containing the input string) you can use lastIndexOf, setting fromIndex as 0. That way, you don't search the whole string, but just its beginning:

var searchString = 'ma';
var names = ['Mark Kennel', 'Hellen Smith', 'Jane Mary Annet', 'Peter'];

function filterNames(arr, str) {
  return arr.filter(function(thisName) {
    return thisName.toLowerCase().split(" ").some(function(d) {
      return d.lastIndexOf(str.toLowerCase(), 0) === 0
    })
  })
}

console.log(filterNames(names, searchString))

Another obvious option here is using startsWith. However, unlike lastIndexOf, startsWith don't wok on IE (if you care for that).


Find the smallest regular number that is not less than N (Python)

from itertools import ifilter, takewhile
from Queue import PriorityQueue

def nextPowerOf2(n):

Python convention says that function should be named with_underscores

    p = max(1, n)
    while p != (p & -p):

Parens not needed.

        p += p & -p
    return p

I suspect that isn't the most efficient way to implement this function. See here for some profiling done on various implementations. http://www.willmcgugan.com/blog/tech/2007/7/1/profiling-bit-twiddling-in-python/

# Generate multiples of powers of 3, 5
def oddRegulars():
    q = PriorityQueue()

So this is a synchronized class, intended to be used for threading purposes. Since you aren't using it that way, you are paying for locking you aren't using.

    q.put(1)
    prev = None
    while not q.empty():

Given that the queue will never be empty in this algorithm, why are you checking for it?

        n = q.get()
        if n != prev:
            prev = n

The prev stuff bothers me. Its ugly code that seems to distract from your algorithm. It also means that you are generating duplicates of the same number. I.e. it would be better to avoid generating the duplicates at all.

            yield n
            if n % 3 == 0:
                q.put(n // 3 * 5)
            q.put(n * 3)

So why don't you just push n * 3 and n * 5 onto your queue?

# Generate regular numbers with the same number of bits as n
def regularsCloseTo(n):
    p = nextPowerOf2(n)
    numBits = len(bin(n))

These two things are basically the same thing. p = 2**(numBits+1).  You should be able to calculate one from the other rather then going through the work over again.

    for i in takewhile(lambda x: x <= p, oddRegulars()):
        yield i << max(0, numBits - len(bin(i)))

I'd have a comment here because its tricky to figure out what you are doing.

def nextRegular(n):
    bigEnough = ifilter(lambda x: x >= n, regularsCloseTo(n))
    return min(bigEnough)

I'd combine those two lines.

  Is there a convention for indicating what version of the language you are targeting (like > require  in perl?) This program only works in 2.6.

Honestly, much programs just fail when trying to use something not supported in the current version of python.

  I know it is possible to implement lazy lists in Python but they are not in 2.6 are they?

Lazy lists? You might be referring to generators. But they are supported in 2.6, and you used one in your code.


Reverse an integer, find the absolute difference, then reverse again

You write unsigned int enough times that it's probably worthwhile to typedef it, in caseunsigned int turns out to be too small. (Keep in mind that it is only guaranteed to go up to 65535.)

typedef unsigned int number;
#define NUMBER_FMT "%u"

The reverseInteger() function is fine.  I'd rename it for clarity, then remove the superfluous comments.

/**
 * Reverse the digits of a number
 */
number reverseDigits(number input) {
    number output = 0;

    while (input != 0) {
        output = output * 10 + input % 10;
        input /= 10;
    }

    return output;
}

The code in generateMagicNumber() was really hard to follow.  The call reverseInteger(input) appears five times in that function.  One codepath has four of those calls, and the other has three.  Not only is that suboptimal1, it's also confusing because the input refers to a different number each time even though they all look the same.  Please avoid repurposing variables like that.

/**
 * The reverse of the absolute difference between a number and its reverse
 */
number magic(number input) {
    number rev = reverseDigits(input);
    number absDiffWithReverse = (rev > input) ? rev - input : input - rev;
    return reverseDigits(absDiffWithReverse);
}

The ugly part of the problem is the requirement to keep track of the largest \$\lvert R(A) - A \rvert\$.  I see four unpalatable options:

As you have done, insert code inside generateMagicNumber() to capture the intermediate computational result.

The disadvantages are that you are doing this as a side-effect, and using static (or global) state.  That kind of statefulness would become a maintenance headache on larger projects.  You also had to use a funny hack of calling largestAbsoluteDifference(0) to read out the maximum.
Instead of defining generateMagicNumber(), define absDiffWithReverse() to calculate \$\lvert R(A) - A \rvert\$.  Then, let main() be responsible for tracking the maximum of those.

To get the magic numbers, main() would need to finish the job by reversing them.  It's a bit dissatisfying that, for a program whose primary purpose is to compute "magic numbers", there is no magic-number-computing function.
Define a function to compute both the magic number and the \$\lvert R(A) - A \rvert\$ intermediate result.

Since C only allows one return value, you could either return a struct with two numbers or pass back one of the values as an out-parameter.  I find both techniques aesthetically unpleasing, especially since those two results can be trivially derived from each other.
Define a function to compute the magic number.  To get the \$\lvert R(A) - A \rvert\$, reverse the magic number again.

As @MatthieuM has pointed out, reversing the digits twice could change the result, due to the possibility of trailing or leading zeroes.

I think I would prefer option 3:

number magic(number input, number *absDiffWithReverse) {
    number rev = reverseDigits(input);
    *absDiffWithReverse = (rev > input) ? rev - input : input - rev;
    return reverseDigits(*absDiffWithReverse);
}

number max(number a, number b) {
    return a > b ? a : b;
}

int main() {
    int inputs;
    printf("Enter number of inputs: ");
    scanf("%d", &inputs);
    printf("Enter space separated: ");

    number maxDiffRev = 0;
    for (int i = 0; i < inputs; i++) {
        number n, nMagic, absDiffRev;
        scanf(NUMBER_FMT, &n);
        // Print label only on first iteration
        if (i == 0) { printf("\nOutput: "); }

        nMagic = magic(n, *absDiffRev);
        printf(NUMBER_FMT " ", nMagic);
        maxDiffRev = max(maxDiffRev, *absDiffRev);
    }

    printf("\nLargest Absolute Difference: " NUMBER_FMT "\n", maxDiffRev);
}

To address your specific concerns:

Yes, calling largestAbsoluteDifference(0) to read the maximum is slimy.  Ideally, static state should be avoided altogether.
Calling functions inside printf() calls is fine if they are pure functions with no side-effects.  It's not as good a practice if the function being called has side-effects.  I wouldn't worry about it in your case.  What I wrote above, with a variable assignment inside a printf() call, is probably far more controversial.
Your technique is arithmetically correct, but not recommended due to the input variable shifting its meaning.

1 Not that performance really matters here.  What I'm pointing out is silliness more than a serious efficiency problem.