Here you're using the name word but from your example you're actually working with substrings. Word is a vague concept but think about this:

var validWords = new List<string>() { "all", "to", "get", "her" };
BreakSentenceIntoWords("alltogether", validWords);

In this case you have each word from validWords but you also have another word together which is an English word but it's not in your list. Is it correct? If you're talking about words you need to consider some kind of delimiter (spaces, for example) but don't forget that it's not true in every language (Chinese, just to mention one). In your current code you're not even handling spaces.

Also note that in your current code order matters, for the above string you will get different results with { "all", "to", "together" } and this is (probably) unwanted. There are also some other corner cases you didn't handle (see answer below for other details.) I'd suggest that even before you start writing the first line of code you put in-place a huge test set (some of them also adding some randomness, I like my tests to be deterministic but working with text I always fear I forgot something then 10/20 iterations shuffling dictionaries and strings may help me to improve my test suite.)

Let's start with few general points, regardless what I said above about words.

Method name isn't best one you can choose because you're not breaking a sentence into words but you're checking if all words in that sentence are in a list of valid words. Two methods SplitStringIntoWords() and AreAllWordsKnown() might be more appropriate.

You're throwing Exception but you can do better than that, appropriate specific exception type is more informative and will help caller to handle such errors (you may have, for example, different policies for exception handling.) In this case I'd use ArgumentException. I'd also differentiate between a null input and an empty (or blank) input (using ArgumentNullException and ArgumentException respectively.) You should also check validWords to be not-null and not empty. Something like this:

if (input == null)
    throw new ArgumentNullException(nameof(input));

if (String.IsNullOrBlank(input))
    throw new ArgumentException("Input string cannot be blank", nameof(input));

if (validWords == null)
    throw new ArgumentNullException(nameof(validWords));

if (validWords.Count == 0)
    throw new ArgumentException("Known words list is empty.", nameof(validWords));

if (validWords.Any(x => x == null))
    throw new ArgumentException("Known words can't be null.", nameof(validWords));

Second step is to make this method more generic, you do not need caller to use List<string> when any IEnumerable<string> is enough to complete your task. Just change method signature.

You're also writing to console making this method not easy to reuse. Split logic and presentation, you may use a callback parameter if you need to output something or change return type to hold all the information you need. We will see more about this later.

First performance problem comes from iteration through the input string, for each character you search validWords for a match, this can be pretty inefficient when validWords or input grow to larger numbers. A small note about word searching. Linear search is not efficient for very large dictionaries (but it may be OK for 10~20 words), ordered lists and hashtables offer a huge performace gain in search (because you won't actually need to go through the entire list performing an expensive culture aware string comparison to find a match.) Later there is more about this...

Let's split your sentence into words! .NET Framework already has a function ready to use: String.Split(). If you do not specify any delimiter then it will use whitespace characters (which are many more than space and tab). For simplicity in these examples I will omit error checking (and I won't consider punctuation) but you need to do it in your code.

static string[] SplitIntoWords(string sentence)
{
    return sentence.Split(null);
}

You might want to compare with regex implementation to determine which one performs better:

static string[] SplitIntoWords(string sentence)
{
    return Regex.Split(sentence, "\\s+");;
}

Now that you have a list of words you can determine if all of them are valid. First naive implementation (don't forget what we said above about string searching in a dictionary) may be:

static bool AreAllWordsKnown(IEnumerable<string> words, IEnumerable<string> knownWords)
{
    return words.All(x => knownWords.Contains(x));
}

Note that to extract the list of not valid words you can use:

IEnumerable<string> unkownWords = words.Except(knownWords);

Above code can then be rewritten as:

return words.Except(knownWords).Any() == false;

To determine the list of valid words is straightforward (it's just the intersection between words and unknownWords.)

Things are different if you're not searching for words but for substrings. In this case, to avoid ordering problems, I'd first sort input list according to word length (to prefer longer matches):

var orderedValidWords = validWords.OrderBy(x => x.Length);

In this example I'm simply using String.Length but you know it's number of UTF-16 code units, not the number of characters of the string then you may have unexpected results. If you need a true culture aware check this is little bit more complex and slow:

var orderedValidWords = validWords.OrderBy(x => new StringInfo(x).LengthInTextElements);

Note that to perform a valid encoding-aware comparison you should enumerate text elements (which are...System.String) using StringInfo methods instead of System.Char.

What is slow in your actual code? You build a string for comparison, character by character. This wastes some time but think if all known words are at least 6 characters length (average word length in English is 5.1 characters), you will perform useless expensive searches. More than that you're copying characters (possibly increasing StringBuffer internal storage) just to create a new string each time with ToString() (twice...) You  may want to experiment with a custom ordinal comparison of char[] but you should first go with String.SubString (you may light to read this SO post about SubString). In short you just keep two indices (beginning of the word and current word length) and then you do:

validWords.Contains(input.SubString(wordBeginIndex, wordLength))

This alone will vastly improve performance but you can do better (for big dictionaries) adding some logic (experiment and measure) because now dictionary is ordered then:

You can check string length:

If shorter word has 4 characters and you current word is "get" then you don't need to perform any search.
If longer word is 5 characters and your actual word is 6 then (and you're not handling this in your actual code) you should move wordBeginIndex one character forward (note that this may be tricky if you want to keep track of unknown words, to simply report there are some is straightforward.)

You do not need to go through the whole list, if your word is "banana" and your list is "apple, cider, lemon" you can stop immediately when you see "cider". Be careful because ordering both for word length and alphabetically is tricky, you may want to keep only alphabetical order for simplicity (but measure, measure, measure...)
You can perform a bisection search.

What's a very fast way to search for a string in a list? HasShet<string>, even the generic implementation:

var dictionary = new HashSet<string>(validWords);

Note however that with hash-set ordering isn't preserved then you have the above mentioned ordering problem and you have to handle it elsewhere.


Print out number x followed by everything in the range of 1 to (x - 1)

The first is a pretty straightforward for loop with modular arithmetic, skipping 0:

The problem in this code is that you are mixing output with the algorithm logic.

  The second (and, as a disclaimer, I will almost certainly not be using this in actual production code, I wrote it more for my own learning), is based on closures:

I vouch for your decision. This code while might be interesting it has a behaviour that is hard to follow. You basically implemented something that looks like an IEnumerable. However in this code you return a function and what that function does is not documented. You don't know how many times you have to call it.

The solution is then resolving the first problem while using the IEnumerable mechanism that is understood by everyone and has a more comprehensible use:

public static IEnumerable<int> RollAround(int n)
{
    if(n < 1)
    {
        throw new ArgumentException("n must be greater or equal to 1", nameof(n));
    }

    var elems = new[] { n };
    return elems.Concat(Enumerable.Range(1, n - 1));
}

static void Main(string[] args)
{
    foreach(var elem in RollAround(3)){
        Console.WriteLine(elem);
    }
}


Algorithm to get an arbitrary perpendicular vector

The cross product of two vectors is perpendicular to both vectors, unless both vectors are parallel. So you could simply take the cross product of your first vector with (1, 0, 0), unless it is parallel to (1, 0, 0), in which case you could use (0, 1, 0). If you use lists rather than dedicated classes with attributes and are willing to use numpy, this gets ridiculously short:

import numpy as np

def perpendicular_vector(v):
    if v[1] == 0 and v[2] == 0:
        if v[0] == 0:
            raise ValueError('zero vector')
        else:
            return np.cross(v, [0, 1, 0]]
    return np.cross(v, [1, 0, 0])


Calculating the count of integer partitions of a number (uses stateful vectors internally)

You can achieve comparable performance without resorting to mutable state by using IntMap and carefully avoiding unnecessary computations. Let's start with the code below, which is actually the very first Haskell solution at your  Pentagonal Number Theorem link:

import Data.IntMap ((!), fromList, insert, findWithDefault)

partition :: Int -> Integer
partition x = if x < 0 then 0 else foldl p (fromList [(0,1)]) [1..x] ! x where
    p s n = insert n (sum [(-1)^(k+1) * (r pred + r succ) | k <- [1..n],
        let r f = findWithDefault 0 (n - div (k * f (3 * k)) 2) s]) s

This code is pretty, concise and expressive, and it's very easy to see that it does implement Euler's formula indeed. Alas, it's not very efficient - on my laptop, it takes more than 5 seconds to compute partition 5000 (I didn't measure how long partition 60000 would take). How can we improve its performance? Well, there's some low-hanging fruit:

(-1)^(k+1) looks suspect: we don't really need exponentiation actually - what we need is 1 if k is odd and (-1) if k is even.
k <- [1..n] gives us way too many ks. We should only consider those k values for which at least one of $$n - \frac{k\left(3k-1\right)}{2}$$ and $$n - \frac{k\left(3k+1\right)}{2}$$ is non-negative (because if both of them are negative, then the sum within the square brackets in the formula above is zero). The largest such k is approximately $$\sqrt\frac{2n}{3}$$ (the exact maximum can be computed easily by solving a quadratic equation).
That is, instead of n possible values for k, we only need to consider fewer than sqrt n values. And that matters a lot because the code performs a lookup (findWithDefault) in the IntMap for each k value considered.
These two (i.e., the elimination of (-1)^(k+1) and the reduction of the number of lookups) are the biggest wins, but there's some additional minor stuff you can do to improve performance, e.g., you can eliminate one multiplication and one division by noticing that $$n - \frac{k\left(3k+1\right)}{2} = n - \frac{k\left(3k-1\right)}{2} - k$$
Also, it doesn't hurt to try using a strict IntMap instead of a lazy one.

After implementing all of these suggestions, the code looks like this:

import Data.IntMap.Strict ((!), fromList, insert)

partition :: Int -> Integer
partition x = if x < 0 then 0 else foldl p (fromList [(0,1)]) [1..x] ! x where
    p s n = insert n (sum [sign k * sumOfTwoEarlierPs s n k | k <- [1..maxK n] ]) s
    maxK n = round $ 1/6 + sqrt(1/36 + 2/3 * fromIntegral n)

sign k = if odd k then 1 else (-1)

sumOfTwoEarlierPs s n k = p1 + p2 where
  i1 = n - (k *(k+k+k - 1)) `div` 2
  i2 = i1 - k
  p1 = nonNegativeIndexOnly s i1
  p2 = nonNegativeIndexOnly s i2
  nonNegativeIndexOnly s i = if i >= 0 then s!i else 0

On my laptop, this computes partition 60000 in less than 5 seconds, and its running time is only 5% or so more than that of your code.


replace digit at some positions in number

I didn't thought about the algorithm itself, but shortened the code a little bit:

decreaseList :: Num a => [a] -> a -> [a]
decreaseList b c = map (subtract c) b

listToNum :: [Int] -> Integer
listToNum = toInteger . foldl1 ((+).(*10))

numToList :: Integer -> [Int]
numToList = map digitToInt . show

remove :: [Int] -> [Int] -> [[Int]]
remove [] x = [x]
remove (x:xs) list = let (putted, unputted) = splitAt x list
                     in (init putted) : remove (decreaseList xs x) unputted

sew :: [[a]] -> a -> [a]
sew list sewer = foldr1 ((++).(++[sewer])) list

whitemask :: Integer -> [Int] -> [Integer]
whitemask num places =  let  list = map (listToNum . sew (remove places (numToList num))) [0..9]
                        in filter (((==) `on` length . show) num) list

I think there is still room for improvement...

[Edit]

A shorter version:

whitemask :: Integer -> [Int] -> [Integer]
whitemask num places = map (listToNum . replace)  [0..9]  where
  replace digit = foldr ((:).findDigit) [] $ zip (numToList num) [1..] where
    findDigit (d,i) | i `elem` places = digit
                    | otherwise = d

listToNum :: [Int] -> Integer
listToNum = toInteger . foldl1 ((+).(*10))

numToList :: Integer -> [Int]
numToList = map digitToInt . show

[Edit]

A shorter version, with fixed-length filtering:

whitemask :: Integer -> [Int] -> [Integer]
whitemask num places = map replace digits  where
  digits = if 1 `elem` places then [1..9] else [0..9]
  toList = map digitToInt $ show num
  replace digit = foldl toNum 0 $ zip toList [1..] where
    toNum r (d,i) = 10*r + (fromIntegral $ if i `elem` places then digit else d)

I can't promise that I'll end up with a one-liner, though...

To your questions:

Depends on the context. If you are unsure about the name, just explain the function with a comment.
Depends if you would ever need unfiltered output. In this case that looks pretty unlikely, so I would include the filtering.
See above.


T-SQL Getting Sequential events with first even criteria

Review

Your temporary table names don't say much about what they present. This makes it hard to figure out what they mean. Consider using better, more meaningful names.

DROP TABLE #TEMPA;
DROP TABLE #TEMPB;
DROP TABLE #TEMPC;
DROP TABLE #TEMPD;

It gets worse by aliasing these temporary tables with different letters:

FROM #TEMPA AS A  -- Fair enough

FROM #TEMPA AS B  -- Mamma mia!

There is only a need for an order by in the resulting query and the analytical functions (row over), not in the temporary tables.

There is no need for the temporary tables, you could use CTE's instead.

Refactored Query

Fiddle containing OP + Refactored Query

This only refactors the query for readability. I am sure a more compact and optimized query could be found.

with ACC as (
  SELECT Med_Rec_No
       , PtNo_Num
       , Adm_Date
       , Dsch_Date
       , hosp_svc
       , CASE WHEN B.READMIT IS NULL THEN 'No' ELSE 'Yes' END AS [Readmit Status]
       , [Event_Num] = ROW_NUMBER() over(partition by med_rec_no order by ADM_date)
       , [PSY_Flag] = CASE WHEN hosp_svc = 'PSY' THEN '1' ELSE '0' END
  FROM bmh_plm_ptacct_v AS A
  LEFT OUTER JOIN vReadmits AS B
  ON A.PtNo_Num = b.[INDEX] AND B.INTERIM < 31
  WHERE Dsch_Date >= '01-01-2018'
  AND dsch_date < '12-31-2018'
)
, EMERG as (
  SELECT ACC.* FROM ACC WHERE hosp_svc = 'PSY'
)
, PSY as (
  SELECT ACC.*
  FROM ACC
  WHERE hosp_svc != 'PSY'
  AND Med_Rec_No IN (SELECT DISTINCT Med_Rec_No FROM EMERG)
)
, ACC_REL as (
  SELECT Med_Rec_No
       , PtNo_Num
       , Adm_Date
       , Dsch_Date
       , hosp_svc
       , [Readmit Status]
       , Event_Num
       , PSY_Flag
       , [Keep_Flag] = ROW_NUMBER() OVER(PARTITION BY MED_REC_NO ORDER BY ADM_DATE)
  FROM (
    SELECT * FROM EMERG
    UNION ALL
    SELECT * FROM PSY
    WHERE PSY.Med_Rec_No IN (
        SELECT e.Med_Rec_No
        FROM EMERG AS e
        WHERE e.Med_Rec_No = PSY.Med_Rec_No
        AND PSY.Event_Num > e.Event_Num
    )
  ) AS A
)
SELECT A.Med_Rec_No
     , A.PtNo_Num
     , CAST(A.ADM_DATE AS DATE) AS [Adm_Date]
     , CAST(A.Dsch_Date AS DATE) AS [Dsch_Date]
     , A.hosp_svc
     , HS.hosp_svc_name
     , A.[Readmit Status]
     , A.Event_Num
     , A.Keep_Flag
FROM ACC_REL AS A
LEFT OUTER JOIN hosp_svc_dim_v AS HS
ON A.hosp_svc = HS.hosp_svc AND HS.orgz_cd = 'S0X0'
WHERE A.Med_Rec_No IN (
    SELECT DISTINCT rel.MED_REC_NO
    FROM ACC_REL AS rel
    WHERE Keep_Flag > 1
)
ORDER BY Med_Rec_No, Adm_Date
;


Ensure only a single instance of static template class member

I believe the following approach should work; what I would like to know is, are there any caveats to the following approach, and if so, what are they and how can I get around them?

Consider a decorator implementation, with a visitor function for method access:

template<typename V>
class threadsafe_reference // decorator
{
public:
    using reference_type = V&;
    threadsafe_reference(reference_type v, std::mutex& m): value_(v), mutex_(m) {}

    // synchronized visitor access
    void sync( std::function<void(value_type&)> functor )
    {
        std::lock_guard<std::mutex> lock{ mutex_ };
        functor( value_ );
    }

    // you may wish to provide unsynchronized reference access here
private:
    reference_type value_;
    std::mutex& mutex_;
};

template<typename V>
threadsafe_reference<V> make_threadsafe(V& value, std::mutex& m)
{
    return threadsafe_reference<V>{ value, m };
}

Client code:

struct A // agnostic to threading
{
    void do_stuff_n_things( int i ) {};
};

A a; // need to pass this on two threads
mutex m;

auto tsa = make_threadsafe(a, m); // proxy accessor

Thread access:

 tsa.sync( []( A& self ) { self.do_things_n_stuff(10); } );

The code is incomplete (you'd need a specialization of sync for const access and so on) but it should be enough to give you a picture.

Advantages:

this is a non-intrusive decorator that you can use over virtually any type
separates concerns nicely and allows you to implement and test them separately (e.g. test A, then test the synchronization code)

Minor disadvantage:

the access to A's methods requires lambdas/external functions


Can I access both RoleName and ID without fetching it in the backend?

Yes, I believe so if you want to write a bit of javascript.  You would need to create a
hidden field and on every select list change event set the value of that field.

Something like

$(body).on("change", "#selectbox", function() {
    $("#inputbox").val($(this).val());
});

I'm also unsure as to why you are creating the database connection twice but I would consider
passing that into the GetRoles method like so:

public  IEnumerable<NewLogin> GetRolesForDDL(database db)
{
    return (from r in db.UserRole
            select new NewLogin
            {
                UserRole = r.Role,
                RoleID = r.RoleID
            });
}
public  NewLogin RoleDDL()
{
    using (database db = new database())
    {
        var roles = GetRolesForDDL(db).ToList();
        // populates ddl
        return new NewLogin
        {
            RoleList = new SelectList(roles, "RoleID", "UserRole");
        }
    }
}

Or even if both of these methods are part of a class consider passing the database into the class constructor and using it as a private instance variable.


Populate Drop Down List from SQL Database

Here's a simplification of the OfficeRepository methods. Note the other IDisposable types in using blocks:

    public static IEnumerable<OfficeRollups> ListOfficeRollups(bool active, bool inactive)
    {
        var whereClause = active && !inactive
            ? @"Where Active = 1"
            : (!active && inactive ? @"Where Active = 0" : string.Empty);
        var srtQry = @"
Select OfficeRollupID, OfficeRollupName, Active
From OfficeRollups
" + whereClause + @"
Order By OfficeRollupName
";

        using (var conn = new SqlConnection(Settings.ConnectionString))
        using (var objCommand = new SqlCommand(srtQry, conn) { CommandType = CommandType.Text })
        using (var dt = new DataTable())
        using (var adp = new SqlDataAdapter(objCommand))
        {
            conn.Open();
            adp.Fill(dt);
            return dt.AsEnumerable().Select(o => new OfficeRollups
            {
                OfficeRollupID = o.Field<int>("OfficeRollupID"),
                OfficeRollupName = o.Field<string>("OfficeRollupName"),
                Active = o.Field<bool>("Active")
            }).ToList();
        }
    }

    public static IEnumerable<SelectListItem> ListOfficeRollupsForDD(bool active, bool inactive)
    {
        var listOfficeRollups = OfficeRepository.ListOfficeRollups(active, inactive);

        return listOfficeRollups
                .Where(o => !string.IsNullOrEmpty(o.OfficeRollupName))
                .OrderBy(o => o.OfficeRollupName)
                .Select(o => new SelectListItem
                {
                    Text = o.OfficeRollupName,
                    Value = o.OfficeRollupID.ToString()
                })
                .ToList();
    }


Method to count all comments in single external C# file

Naming
The first thing I notice, is inconsistency with naming.
Locals

FileLines
Filename
finalCount
something
inQuotes
x
y
r
Line

Locals should be camelCase, and should have meaningful names. x, y, r and something aren't meaningful names. Filename should be fileName.
Parameters

args
value
Filename
FileLines

Parameters are like locals - they should be camelCase. Filename should be fileName, and FileLines should be fileLines.
Methods

Main
CountComments
readInFile

Method/member names should be PascalCase. readInFile should be ReadInFile - and that's not exactly a great name either. You're reading the file into a List<string> ...that's passed as a parameter. Not the most intuitive approach.

Accessibility
Methods CountComments and readInFile have no business being public.

Constant vs Read-Only
This variable has no business being a const:

const string Filename = @"file.txt";

It should be an instance-level private static readonly string field, because a const should be strictly for something that has zero chance of ever changing in a future version. A file path is definitely something that can change, declaring it as a const is a semantic mistake.

Approach
readInFile should have a return type instead of having the side-effect of adding items to a List<string> parameter. While legal, a better way to convey that a method will have side-effects on a parameter, is to ask for an out parameter, or to pass the list by reference using the ref keyword. Your method takes its output through its input channel, and that doesn't feel right at all.
I would have gone with File.ReadAllLines instead, which returns a string[] array where each element is a line in the specified file, or better (given C# 4+), File.ReadLines, which returns an IEnumerable<string> instead: this means the whole readInFile method could have been inlined, and the FileName just specified as a hard-coded parameter value (or read from the args command-line arguments, if you wanted to get fancy).
As for the actual commend-finding logic...

if (something[x][y] == '/' && something[x][y + 1] == '/')
{
    finalCount++;
    break;
}
else if (something[x][y] == '/' && something[x][y + 1] == '*')
{
    finalCount++;
    break;
}

Can you spot the smell? Why do you need two branches, if both are going to do exactly the same thing?
I would have expected CountComments to do just that: count the comments. Yours is breaking SRP by also performing output - the method should've had an int return type, and just returned the result, leaving it up to the caller to decide what to do with it.
This one puzzles me:

List<string> something = value;

Why not work off value? Why introduce a new meaningless identifier (something? really?) to make a copy of another meaningless identifier (value would already be better as values, but lines or even content would have been sooooo much better!).
I like that you stop iterating characters in a line after you've found a comment.
But instead of nested loops, I would have written a function that takes a string and returns a bool, to encapsulate the logic that basically says "is there a comment anywhere in that string?" - assuming C# 3.5+, the whole method could have looked like this:
return lines.Count(HasComment);

If you were constrained to 2.0, you would've had to perform the loop explicitly - still (assuming a string[] lines parameter):
int result = 0;
for (int line = 0; line < lines.Length; line++)
{
    if (HasComment(lines[line]))
    {
        result++;
    }
}
return result;

And then depending on the time remaining you could have refined the HasComment logic, for example to skip lines that are inside a multiline comment.


Extract index of first unique element in large array in Swift

Your initial test

guard Set(s.characters).count > 0 && s.characters.count > 0 else { return -1 }

is not needed, the remaining code already handles the case of an
empty string.

Determining the unique characters from countedSet can simpler be done
with a filter operation instead of a for-loop:

let uniqueChars = countedSet.filter {
    countedSet.count(for: $0) == 1
} as! [String]

But actually that list is not needed at all because all you have to do
in the final loop is to find the first character which has a count
of one. The function then looks like this:

func firstUniqChar(_ s: String) -> Int {
    let stringArray = s.characters.map({String($0)})
    let countedSet = NSCountedSet(array: stringArray)
    for index in 0..<stringArray.count {
        if countedSet.count(for: stringArray[index]) == 1 {
            return index
        }
    }
    return -1
}

which is simpler and a bit faster than the original one.

This can further be improved by avoiding the conversion of each
character to a string and the array, and operating on the UTF-16
view of the given string directly:

func firstUniqChar(_ s: String) -> Int {
    let countedSet = NSCountedSet()
    for char in s.utf16 {
        countedSet.add(char)
    }
    for (index, char) in s.utf16.enumerated() {
        if countedSet.count(for: char) == 1 {
            return index
        }
    }
    return -1
}

NSCountedSet is from the Foundation library and works with
NSObject instances. The previous method works because the
UInt16 value is automatically wrapped into an object when
added to the counted set. This conversion can be avoided by
using a native Swift dictionary instead, which makes the
code much faster:

func firstUniqChar(_ s: String) -> Int {
    // Map from character to number of occurrences:
    var counts: [UInt16: Int] = [:]

    for char in s.utf16 {
        if let cnt = counts[char] {
            counts[char] = cnt + 1
        } else {
            counts[char] = 1
        }
    }
    for (index, char) in s.utf16.enumerated() {
        if counts[char]! == 1 {
            return index
        }
    }
    return -1
}

Benchmarks. Test code:

let s = String(repeating: "abcdefghijklmnopqrstuvwxy", count: 1000) + "z" + String(repeating: "abcdefghijklmnopqrstuvwxy", count: 1000)
print(s.characters.count) // 50001

let start = Date()
let i = firstUniqChar(s)
let end = Date()

print(i, end.timeIntervalSince(start))

Results (on a 3.5 GHz Intel Core i5 iMac, compiled in Release
configuration):

Your original function:  0.084 sec
First improvement:       0.058 sec
Second improvement:      0.014 sec
Last function:           0.003 sec

The last method can be more compactly written as

func firstUniqChar(_ s: String) -> Int {
    // Map from character to number of occurrences:
    var counts: [UInt16: Int] = [:]

    for char in s.utf16 {
        counts[char] = (counts[char] ?? 0) + 1
    }

    let index = s.utf16.enumerated()
        .first(where: { counts[$0.element]! == 1 })?
        .offset
    return index ?? -1
}

without changing the performance.


Your code looks functional. I quite like the idea of splitting the data in halves each time too. There are some things I would do differently, though.

First-up, the 1-liner if statement:

if len(num)==0: return None
if len(num)==1: return 0

also

   else:return mid+1

No, no no ... ;-0 That should be:

if len(num) == 0:
    return None
if len(num) == 1:
    return 0

and

    else:
        return mid + 1

Note that your pasted code is not indented correctly. You indented the class definition, but the class contents are at the same indentation level.

Additionally, I prefer whitespace between method definitions, an empty line.

Actually, I ran your code through a pep8 checker, it pointed out all the compressed-statements too (no whitespace around operators). Here's your code in a format that passes the pep8 check:

class Solution:

    # @param num, a list of integer
    # @return an integer
    def findPeakElement(self, num):
        if len(num) == 0:
            return None
        if len(num) == 1:
            return 0
        return self.findPeakHelper(num, 0, len(num) - 1)

    def findPeakHelper(self, num, start, end):
        mid = (start + end) / 2
        if mid > start and mid < end:
            if(num[mid - 1] < num[mid] and num[mid] > num[mid + 1]):
                return mid
            if(num[mid - 1] > num[mid]):
                return self.findPeakHelper(num, start, mid)
            else:
                return self.findPeakHelper(num, mid, end)
        else:
            if num[mid] > num[mid + 1]:
                return mid
            else:
                return mid + 1

Note:

spaces surrounding operators
statements on new line, not the same line as the if/else conditions

Now, about your algorithm...

Really, there's nothing wrong with it, but I believe you can simplify the logic a bit if you treat the mid-point only when needed. Consider the following helper function:

class Solution:

    # @param num, a list of integer
    # @return an integer
    def findPeakElement(self, num):
        if len(num) == 0:
            return None
        if len(num) == 1:
            return 0
        return self.findPeakHelper(num, 0, len(num) - 1)

    def findPeakHelper(self, num, start, end):
        span = end - start
        # span of 1 indicates 2 elements
        if span == 1:
            return start if num[start] > num[end] else end
        mid = start + span / 2
        if num[mid] < num[mid + 1]:
            return self.findPeakHelper(num, mid, end)
        return self.findPeakHelper(num, start, mid)

Note how you don't need the else-statements if the if-statement has a guaranteed return.


Reducing boilerplate of binary layout handling in Haskell

To add one more suggestion - building records can be simplified quite a bit by using the RecordWildCards extension, which automatically populates fields from visible names (see GHC docs). Personally, I consider it borderline essential for dealing with large records. I would probably write this like follows:

{-# LANGUAGE RecordWildCards #-}
-- ...
binGetSuperblock = do
  [sInodesCount,         sBlocksCount,
   sReservedBlocksCount, sFreeBlocksCount,
   sFreeInodesCount,     sFirstDataBlock,
   sLogBlockSize,        sLogClusterSize,
   sBlocksPerGroup,      sClustersPerGroup,
   sInodesPerGroup,      sMountTime,
   sWriteTime]                            <- replicateM 13 getWord32le
  [sMountsCount,         sMaxMountsCount,
   sMagic,               sState,
   sErrors,              sRevLevel2]      <- replicateM 6  getWord16le
  [sLastCheckTime,       sCheckInterval,
   sCreatorOS,           sRevLevel1]      <- replicateM 4  getWord32le
  [sDefaultResUID,       sDefaultResGID]  <- replicateM 2  getWord16le
  return Superblock {
    sMaxMountsCount = int sMaxMountsCount,
    sRevLevel = (sRevLevel1, sRevLevel2),
    sDynRev = Nothing,
    sPrealloc = Nothing,
    sJournaling = Nothing,
    ..
    }


My recommendation is: create a constructor for CountryPair, which takes the parameter values:

    public CountryPair(String value, String displayName) {
        this.value = value;
        this.displayName = displayName;
    }

Then, you can use an elegant map-chain:

    List<CountryPair> pairList = countryCodes.stream()
        .map(code -> new Locale("", code))
        .map(locale -> new CountryPair(locale.getCountry(), locale.getDisplayCountry()))
        .collect(Collectors.toList());

Alternatively, you could also use a constructor which uses the Locale object as a parameter.


Flexible multiple string comparision to determine variable value

You could keep an array of jobs, and the web application would send index instead of word 'small', 'medium', 'large'.

So you could have an array [3, 5, 8] and instead of "small" you send 0, instead of "medium" you send 1, and instead of "large" you send 2. You only need to check if the index received does not exceed the table size.


Your ArrayList is correctly guarded from access by multiple threads but you've got another problem. The busy wait in your run method is going to hog the CPU and might even starve the other threads that would be trying to put a message in the queue. You'll need some way of signaling that the queue is non-empty so that the run function can wait on the signal. In .NET it would be a ManualResetEvent. I don't know the java equivalent.  Or better yet, have a look at BlockingQueue.

@Override
public void run() {
    while (true) {
        queueFullEvent.waitOne();
        synchronized (messages) {
            for (Message m : messages) {
                // messages should be removed here
                messages.remove(m);
                if (messages.isEmpty)
                    queueFullEvent.reset();
            }
        }
    }
}

public static void addMessage(Message message) {
    synchronized (messages) {
        messages.add(message);
        queueFullEvent.set();
    }
}

public static void removeMessage(Message message) {
   // would require additional syncronization objects to avoid a race.
}

}


It seems odd to special-case the string "object" when preparing an object for serialization, so I came up with the following code:

var createObjectFromParam = function (o, prop, val) {
    var parts = prop.split('.');
    var last = o;
    while (parts.length) {
        var part = parts.shift();
        if (parts.length > 0) {
            last[part] = last[part] || {};
            last = last[part];
        } else {
            last[part] = val; // Add conditional expressions here
        }
    }
    return last;
}

The code does the following:

Creates a temporary variable (last) to contain the current "level" of the object hierarchy.
Loops through the array. Note that while (parts.length) will stop the loop when there are no longer parts in the array.
Take the next part of the prop. shift pulls the first element of the array out.
If we're not at the last element

If the element with the specified name exists at the level, use that
If not, create an object at that level

Otherwise, add a property with the specified value to the object.
Finally, return the created object.

Given the example in the jsFiddle (updated here), this would produce the following structure:

{
    "ready": {
        "set": "go"
    },
    "another": "object",
    "happy": {
        "happy": {
            "joy": "joy",
            "foo": "bar",
            "happy": "happy"
        }
    }
}

To keep that original special-casing, just replace the commented line with something like:

last[part] = val === 'object' ? {} : val === 'undefined' ? : undefined : val;


Substring match within a text for given keywords

Unnecessary parentheses
Switch the following:
return(...) -> return ...
if(...) -> if ...

You switch between the two, probably due to coming from another language. Just try to be consistent and don't use parentheses if you don't have to.
Type Hints
You can use type hints to display what types of parameters are accepted, and what types of values are returned, if any.
def fuzzy_extract(query_string: str, match_string: str, threshold: int, max_dist: int):
def get_match(text: str, keywords: List[str], threshold: int):

The List is imported by from typing import List
Simplify your loops
Instead of checking if len(li) > = 0, you can do that check inside the list comprehension. Also, I would move that outside of the loop into its own variable.
extracted = [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords if len(query_string) > 0]

Empty lists
Instead of checking if the length of the list is 0, simply check if the list is None. An empty list is implicitly None.
if not candidates:

Default Parameters
When passing default parameters, there shouldn't be a space before or after the =.
for word, _ in process.extractBests(query_string, (match_string,), score_cutoff=threshold):
        for match in find_near_matches(query_string, word, max_l_dist=max_dist):

Final Code
from fuzzywuzzy import process
from fuzzysearch import find_near_matches
import math

from typing import List

def fuzzy_extract(query_string: str, match_string: str, threshold: int, max_dist: int):
    matches = []
    for word, _ in process.extractBests(query_string, (match_string,), score_cutoff=threshold):
        for match in find_near_matches(query_string, word, max_l_dist=max_dist):
            word = word[match.start:match.end]
            matches.append({"kw": query_string, "word": word, "dist": match.dist})
    return matches

def get_match(text: str, keywords: List[str], threshold: int):
    keywords = [keyword.lower() for keyword in keywords]
    text = text.lower()

    canidates = []
    extracted = [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords if len(query_string) > 0]
    for item in extracted:
        for di in item:
            if di["dist"] <= math.ceil(len(di["word"]) / threshold):
                canidates.append(di)

    if not canidates:
        return []

    result = str(canidates[0]["kw"])
    return result

keywords = ["apple", "banana", "cherry"]
text = "nana is Looking for an aple."

print(get_match(text, keywords, 10))


Namespace
#include <bits/stdc++.h>
using namespace std;

The first line supposedly inserts all includes your code needs but haven't specifically included. The second line saves you a lot of typing by not having to insert std:: in front of all relevant methods and types.
Please don't use those!
Read Why is “using namespace std;” considered bad practice? on Stack Overflow for the full read, but the short version is it's a major maintainability risk and allows function conflicts to arise.
The first line combined with the second line makes it even worse, since now you are no longer in control about how your code executes. You should tell the compiler what to do, not the other way around.
You current style not only hurts maintainability, it also hurts your understanding of how the language works. Practices like these lead to programmers not understanding how to make the best of namespaces.
Style
left=right=NULL;`

This hurts readability and maintainability. It's clear you're setting something to NULL, but not why. You're probably resetting something. However, you're resetting both left and right at the same time, on the same line. If you need to reset multiple things at the same time, you usually implement a function doing so.
if(val < temp->val) {parent = temp; temp= temp->left;}`

All your if statements look like that. The more accepted (and more readable) style of bracketing in C++ goes like this:
if(val < temp->val)
{
    parent = temp;
    temp= temp->left;
}

Don't be afraid of using newlines.
int main(){
    bTree a;
}

You declare a bTree named a. You're not doing anything with it, just creating something. If you would do something with it, you'd notice a isn't a good name for a bTree. a.insert(val) doesn't tell me anything, except you're inserting something into a. In a bigger project, you'll encounter more variable names and all those names should be descriptive.
Finally:
The size of code in C++ is usually irrelevant. Space is cheap nowadays and saving a couple of bytes in the source won't bring you anywhere with compiled languages. Only the size of the resulting binary may be relevant, especially if you're working on embedded systems.


Backbone.js Dependency Injection API Design

If I had to pick, I would pick the second option.  It's the clearest to me and aligns well with how the plugin injects properties. I don't think it's "lying" to the user because it's obvious that the needs.args function is doing something with the arguments before passing back control to the actual initialize function. But like you said, long arg lists will be annoying.

My only other note would be that I'm unsure how useful injection is in a dynamic language like javascript. I've used in statically typed languages like Java where it's definitely useful, but never entertained the idea in js. I'd definitely be curious to see the final result.

Edit: After some research there looks like another alternative - reflection: http://merrickchristensen.com/articles/javascript-dependency-injection.html


Logging util with static lambda function

What is the point of adding some parameters as part of format string when others are simply passed to String.format? You might as well just do the latter:

public class ExceptionUtils {

    private static final String CUSTOM_EXCEPTION_MESSAGE_FORMAT
            = "[XXX] %s Error during process bulk %s events. Event occurrences time: %d event retry count: %d, session: %s";

    private static String formatMessage(String type, String endpoint, long timestamp, int retryCount, String sessionToken) {
        return String.format(CUSTOM_EXCEPTION_MESSAGE_FORMAT,
                type, endpoint, timestamp, retryCount, sessionToken);
    }

    public static String validationMessageException(String endpoint, long timestamp, int retryCount, String sessionToken) {
        return formatMessage("Validation", endpoint, timestamp, retryCount, sessionToken);
    }

    public static String unknownMessageException(String endpoint, long timestamp, int retryCount, String sessionToken) {
        return formatMessage("Unknown", endpoint, timestamp, retryCount, sessionToken);
    }
}

or even just:

public class ExceptionUtils {

    private static final String CUSTOM_EXCEPTION_MESSAGE_FORMAT
            = "[XXX] %s Error during process bulk %s events. Event occurrences time: %d event retry count: %d, session: %s";

    public static String validationMessageException(String endpoint, long timestamp, int retryCount, String sessionToken) {
        return String.format(CUSTOM_EXCEPTION_MESSAGE_FORMAT,
                "Validation", endpoint, timestamp, retryCount, sessionToken);
    }

    public static String unknownMessageException(String endpoint, long timestamp, int retryCount, String sessionToken) {
        return String.format(CUSTOM_EXCEPTION_MESSAGE_FORMAT,
                "Unknown", endpoint, timestamp, retryCount, sessionToken);
    }
}


Simple c# MemoryCache mechanism to reduce number of db calls

This is a really bad pattern: neither your Student nor your School class should be responsible for retrieving themselves from the DB. Imagine retrieving a list of 100 Students: that would mean 100+ queries to the DB. You can't even apply filters (e.g. get all the Students who go to one School).

Your caching mechanism is solving the wrong problem. What you should do is:

Get all Schools and store them in a Dictionary<int, School> where the key is the Id of the School.
Get all Students, and then loop through them and attach the School based on the SchoolId.

Two queries instead of hundreds or thousands.


Bugs
Try some simple test cases to find bugs:
def test_split(s):
    splitter = Splitter(s)
    print(s, "⇒", splitter.split(s))

test_split('[')        #no word, just punctuation
test_split('cat')
test_split('cattree')
test_split('cathode')  #one word, not cat-hode
test_split('muscat')   #one word, not mus-cat
test_split('onetwothree')
test_split('one1two2') #multiple numbers
test_split('2014')     #multi-digit number
test_split('xyzzy')    #unknown word
test_split('cathodemuscat') #cathode-muscat, not cathodemus-cat or cat-hodemuscat

These reveal some bugs:

Only the first call to split works (even on separate instances). This is because Splitter.words is shared between instances but is modified by separateWords, and words remain in it after each call.

Unknown words are omitted. What should separateString return when it doesn't recognize a word? The whole input?

Words containing numbers are not handled in any reasonable way. Perhaps any sequence of digits should be parsed as a word?

Brackets are treated as letters. The regex in cleanString should be "[^\da-z]*", not "[^\d[a-z]]*", unless you want to keep square brackets.

When modifying separateString, be careful with the case where the whole input as one word — it's easy to break this or have it only work by accident.
The last test case ('cathodemuscat') is particularly hard. Hint: split the string, recurse on both halves, and check that both halves succeed.
Architecture and simplification
The Splitter class does nothing useful. Its methods should be top-level functions instead. (This contributes to the Splitter.words bug.)
It's not a good idea for separateString to communicate with its recursive call by modifying input and words. This is bug-prone (it contributes to the Splitter.words bug) and hard to read. Instead, separateString should pass the appropriate substring as an argument to the recursive call, and append its word to the result. It may look something like this:
return separateString(inp[:-ind]) + [word]

Callers probably want a list of words, rather than a space-separated string, so separateString should return the list without joining.
It would be clearer (and faster) to load the dictionary once, as a set, rather than reading it repeatedly:
dictionary = set([cleanString(w) for w in open('word.txt')])

partition is unnecessary. Just write inp[len(inp)-ind:], or even inp[-ind:] if ind is never 0. (Negative indexes count from the end.)


Converting the integers to their equivalent string representations

After a bit of dabbling with the script, I've updated the line #42 to #53 with a table iterator:

for _, ext in ipairs(bases) do
    if n > ext[1] then
        table.insert( str, NumberToString(n / ext[1])..ext[2] )
        n = n % ext[1]
    end
end

where, bases has been redefined as:

{
    { 10^12, ' trillion' },
    { 10^9, ' billion' },
    { 10^6, ' million' },
    { 10^3, ' thousand' },
    { 10^2, ' hundred' },
}

that is, in descending orders of powers of 10.

I'd welcome other suggestions as well.


Optimization of a basic Sieve of Eratosthenes algorithm

After adding 2 to the list of primes you are wasting half of the array space for even numbers, even time for crossing them out. Disconnect the number from it's index in the sieve, like in testprime = sieve[2*i + 3]. Now you can step with a stepsize of 1 through the sieve.

If you take that one step further and add 3 to the list of primes, you will notice that all remaining primes are of the form 6i+1 or 6i+5. The cases 6i, 6i+2, 6i+4 are even; 6i+3 is divisible by 3. So you can loop in steps of 6 and check for elements 6i+1 and 6i+5 in one pass.
Thus, there are only 6/6 - 3/6 - 2/6 = 1/6 numbers left to check for, meaning a sixfold speedup.


Don't import tkinter twice

You are both importing individual parts of tkinter as well as the module as a whole. Don't do both. Stick with importing the whole library and then using the library as a prefix to the objects. This makes your code more self-documenting.

For example:

import Tkinter as tk
...
self.label = tk.Label(...)
self.textEntry = Entry(...)

...

Separate widget creation from widget layout

Instead of creating a widget, then calling grid, then creating a widget, calling grid, etc, create your widgets in one group and lay them out in another.

self.label = Label(master, anchor=CENTER, text="Temperature Conversion")
self.textEntry = Entry(master, text="enter temperature")
self.calculate_button = Button(master, text="Convert", command=self.calc)
self.converstion_type = Checkbutton(master, text="Farenheit",  variable=var)
self.output = Label(master, text="...")
self.outputInput = Label(master, text="Converted Temperature", borderwidth=2, relief="solid")

self.label.grid(columnspan=3, rowspan=2, sticky=W)
self.textEntry.grid(row=2, column=1)
self.calculate_button.grid(row=2, column=2)
self.converstion_type.grid(row=3, column=1)
self.output.grid(row=3, column=3)
self.outputInput.grid(row=1, column=2)

In my experience, this makes it much easier to visualize the GUI structure in the code, and also makes it easier to change the layout.

If you have multiple sections in your code (eg: a navigation area, a main area, a toolbar, etc.) you should group them by section.

Hide the main code

Even though this is a complete program rather than a reusable library, it's good to get into the habit of moving executable code to a section that won't get run when you import the file.

For example:

if __name__ == "__main__":
    root = Tk()
    var = tk.IntVar()
    my_gui = MyFirstGUI(root)
    root.mainloop()

Some people take the extra step of moving that code to a main function placed at the top of the file:

def main():
    root = Tk()
    var = tk.IntVar()
    my_gui = MyFirstGUI(root)
    root.mainloop()
...
if __name__ == "__main__":
    main()

The choice is simply one of readability. Some people like having their main logic at the top of the file.

Even if you never plan to make this a reusable library, by hiding the main logic like this you can create test cases that import the file and test individual pieces of the code. While that's overkill for this small program, it's a good habit to get into.

For more information see What does if__name__ == "main" do?


Likely what is taking up extra time is the line:

 p = map(int, re.findall('.',sys.stdin.readline()))

There are a few things here. Firstly, regular expressions are relatively expensive. Underneath, it likely needs to compile the regular expression (which in this case is very simple, but still). Further, you don't need regular expressions to do this in python. For example, assume the string was something like '343898934'. Then this is equivalent to:

p = [int(k) for k in '343898934']

The above will likely be slightly faster.

The second place here that could be optimized (memory wise) is that map in Python 2.x returns a list as opposed to a generator. So instead we could do:

p = (int(k) for k in sys.stdin.readline())

The fact that this also removes the re import may also impact timing and memory usage, depending on how they measure.


Misleading Return Type

You have:

template <typename Iterator>
decltype( auto ) divide_work( Iterator begin, Iterator end, std::size_t n )

The difference between auto and decltype(auto) is that the latter can deduce reference types as well. But you're returning a value, always, regardless of Iterator. This choice makes it seem as if you could be returning a reference. If you are going to use a placeholder return type here, use simply auto.

Even better, the return type for this function is not a complicated expression that's difficult to spell. It's simply std::vector<std::pair<Iterator, Iterator>>, so let's just use that:

template <typename Iterator>
std::vector<std::pair<Iterator, Iterator>>
divide_work( Iterator begin, Iterator end, std::size_t n )

emplace_back

The advantage of emplace_back is not having to actually construct the object to pass in. So when you write:

ranges.emplace_back( std::make_pair( std::next( begin, 0 ),
            std::next( begin, element_per_group_count ) ) );

That's inefficient (you're copy constructing a pair instead of in-place constructing it) and just a bunch of extra typing. Also next(iter, 0) is iter, so the above line is logically exactly equivalent to:

ranges.emplace_back(begin, std::next(begin, element_per_group_count));

Overly Complicated Algorithm!

I'm not sure why you have three for loops or why even division is a special case of the algorithm... Also I'm pretty sure that special case is wrong. Consider a range of size 15 dividing into 3 chunks, so it divides evenly. We'd start with element_per_group_count == 5, but then we decrement it to 4, and add the first range of:

[0, 4)

Then the next two ranges will be:

[5, 9)
[10, 14)

We successfully divided into three chunks, but we're actually missing elements! 4, 9, and 14 will not appear in any of the three chunks. The correct division would be [[0, 5), [5, 10), [10, 15)].

We're just chunking the range (begin, end) into n pieces. That implies a simple for-loop. We need n things. Each one is approximately of size distance(begin, end)/n. There will be distance(begin, end)%n remainder, which we will allocate one at a time as we go until we run out of remainder. When we already added n-1 things, we just can add the rest as the last chunk (since there's nothing else to do at that point).

This is all you need:

template <typename Iterator>
std::vector<std::pair<Iterator, Iterator>>
divide_work( Iterator begin, Iterator end, std::size_t n )
{
    std::vector<std::pair<Iterator, Iterator>> ranges;
    ranges.reserve(n);

    auto dist = std::distance(begin, end);
    auto chunk = dist / n;
    auto remainder = dist % n;

    for (size_t i = 0; i < n-1; ++i) {
        auto next_end = std::next(begin, chunk + (remainder ? 1 : 0));
        ranges.emplace_back(begin, next_end);

        begin = next_end;
        if (remainder) remainder -= 1;
    }

    // last chunk
    ranges.emplace_back(begin, end);
    return ranges;
}

Dividing up the remainder one at a time means that if we have 15 elements into 6 chunks, we end up with sizes of [3, 3, 3, 2, 2, 2] instead of any other weird alternative like the naive [2, 2, 2, 2, 2, 5].

Too many chunks? None?

What do you do in the case where n > distance(begin, end) or n == 0? I guess we should probably add some error checks:

template <typename Iterator>
std::vector<std::pair<Iterator, Iterator>>
divide_work( Iterator begin, Iterator end, std::size_t n )
{
    std::vector<std::pair<Iterator, Iterator>> ranges;
    if (n == 0) return ranges;
    ranges.reserve(n);

    auto dist = std::distance(begin, end);
    n = std::min<size_t>(n, dist);
    auto chunk = dist / n;
    auto remainder = dist % n;

    for (size_t i = 0; i < n-1; ++i) {
        auto next_end = std::next(begin, chunk + (remainder ? 1 : 0));
        ranges.emplace_back(begin, next_end);

        begin = next_end;
        if (remainder) remainder -= 1;
    }

    // last chunk
    ranges.emplace_back(begin, end);
    return ranges;
}


Analyze huge set of sentences for word presence

The logic of word extraction seems convoluted. Consider two loops instead, along the lines of

    int text_length = text.length();
    int i = 0;
    while (true) {
        while ((i < text_length) && !isEnglishLetterOrHyphen(text.charAt(i))) {
            i++;
        }

        int wordStart = i;
        while ((i < text_length) && isEnglishLetterOrHyphen(text.charAt(i))) {
            i++;
        }

        if (consumer.apply(text.substring(wordStart, i))) {
            return true;
        }
    }

BTW,

    isEnglishPiece && !isEnglishLetter || !isEnglishPiece && isEnglishLetter

is a long (and unclear) way to say

    isEnglishPiece != isEnglishLetter


Optimizing Code for Project Euler Problem 14

I think you're over complicating your solution, my approach would be something along these lines:

def recursive_collatz(n):
        if n in collatz_map:
                return collatz_map[n]
        if n % 2 == 0:
                x = 1 + recursive_collatz(int(n/2))
        else:
                x = 1 + recursive_collatz(int(3*n+1))
        collatz_map[n] = x
        return x

Basically define a memoization map (collatz_map), initialized to {1:1}, and use it to save each calculated value, if it's been seen before, simply return.

Then you just have to iterate from 1 to 1000000 and store two values, the largest Collatz value you've seen so far, and the number that gave you that value.

Something like:

largest_so_far = 1
highest = 0
for i in range(1,1000000):
    temp = recursive_collatz(i)
    if temp > largest_so_far:
        highest = i
        largest_so_far = temp

Using this approach I got:

Problem 14's answer is: 837799.
Took 1.70620799065 seconds to calculate.


If you want to use numpy, use numpy properly. Inestead of

for x in inner_values:
    s += func(x, y) * dA

use the more idiomatic, and much faster

s += dA * np.sum(func(inner_values, y))

Note: this requires rewriting f as

return np.sqrt(np.maximum(0, 4 - y**2 - x**2))

so it can accept an array as an input. This does not reduce accuracy, but brings time down to a much more accaptable .04 seconds for a 100x improvement. The takeaway here is Numpy is not magic. It provides quick vectorization.


Rather than using as e then raise e you can just omit e.

except KeyboardInterrupt as e:
    raise e

except KeyboardInterrupt:
    raise

Rather than specifying an except block for KeyboardInterrupt and SystemExit you can just specify them in the same except by passing a tuple.

except KeyboardInterrupt:
    raise
except SystemExit:
    raise

except (KeyboardInterrupt, SystemExit):
    raise

Both KeyboardInterrupt and SystemExit are not subclasses of Exception so you do not need to handle them. The exceptions will propagate like normal.
You may want to familiarize yourself with the exception hierarchy.

You can get all the information that sys.exc_info() gives from e.

exc_type, exc_obj, exc_tb = sys.exc_info()

exc_type, exc_obj, exc_tb = type(e), e, e.__traceback__

You can get the current frame from exc_tb rather than inspect.currentframe(). This makes the code more portable if you ever decide to move the code into a function to format tracebacks.

frame = inspect.currentframe()

frame = exc_tb.tb_frame

Please follow PEP 8 and name variables with snake_case. It is very easy to see the code you've taken from the Python docs and the code you've written yourself / taken from somewhere else.

If you're going to hard code the == at least use * to build it the size you want.

print('=======================================================================================================')

print('=' * 103)

Better yet just print to the size of the terminal.
print('=' * os.get_terminal_size().columns)

I would prefer to use f-strings if available.

print('Unhandled exception: ', exc_type, script_name, 'at line', exc_tb.tb_lineno)

print(f'Unhandled exception:  {exc_type} {script_name} at line {exc_tb.tb_lineno}')

if __name__ == '__main__':
    try:
        x = 42/0
    except Exception as e:
        exc_tb = e.__traceback__
        script_name = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        function_name = exc_tb.tb_frame.f_code.co_name
        print('=' * os.get_terminal_size().columns)
        print(f'Unhandled exception:  {type(e)} {script_name} at line {exc_tb.tb_lineno}')
        print(f'                      in function {function_name}')
        print(f'                      {e}')

        traceback.print_exc()
        raise SystemExit(1)


Optimised library database code for sorted array of structures

Given that the two lists are already sorted, you can do MUCH better than just the naive O(|A| * |B|) implementation. Let me reduce the problem to just intersecting lists of chars, and let's say our lists are:

A: [... a elems ..., 'C', 'D', ... ]
B: [... b elems ..., 'C', 'E', ... ]

Let's say we just in the outer looped matched A's 'C' to B's 'C'. Cool, we got that right. Now, we're going to try to check for 'D'. Do we really need to start looking at B[0]? We know that B is sorted... and we know that B[b] == 'C', so we know for sure that if there is a 'D' in B then it cannot be in the first b+1 elements.

If you change your inner loop from looping over every element in the 2nd list, to just making sure you end up only walking over the list once, you can reduce your complexity to O(|A| + |B|), which is pretty huge.


You have a number of open resoruces that you do not close properly, FileOutputStreams, BufferedWriters, etc. These should be handled with a try-with-resources block.

Additionally, the standard Java libraries contain helper methods that will make this operation almost trivial... See Files.readAllLines()

Together, this could all be done as:

private static void reverseLines(String fileName) {
    Path path = Paths.get(fileName);
    try {
        List<String> lines = Files.readAllLines(path);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            ListIterator<String> lineIterator = lines.listIterator(lines.size());
            while (lineIterator.hasPrevious()) {
                writer.write(lineIterator.previous());
                writer.newLine();
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

}


Separate an email address into its username and domain name

The general style looks good. The biggest opportunity for improvement is your use of getopt. You should use the newer and easier argparse instead. Most of your code is used to parse and use the command line arguments. All of that can be done in three lines with argparse.
import argparse

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-f", "--file", dest="file", default=False, action="store_true")
arg_parser.add_argument("input", type=str)
args = arg_parser.parse_args()

Instead of using --single or --list, I added a single flag --file (or -f), as the former choice is not only ambiguous (what happens if you specify neither or both?) as well as potentially misleading in their name.
A help option with "-h" is introduced automatically.
"-f", "--file" are the flags you can use to specify this argument. dest=file means that the created object args wil have an attribute args.file that stores the resulting value. action="store_true" means that the flag has to be specified without a value (i.e. -f instead of -f True) to set it.
After that, you can access your inputs as a strings (because type=str) by args.input (because the first argument to add_argument was "input").
open of a file should always be paired with a close when you are done using it, as is also true for other I/O objects such as network connections. Instead of manually calling close, one should prefer to use Python's context managers with the with keyword, which automatically perform any cleanup.
if args.file:
    with open(args.input, "r") as file:
        emails = file.readlines()
else:
    emails = [args.input]

Your code to split the email into username and domain can be done with str.split, assuming that there is exactly one "@". If there are not "@" or more than one, you should probably notify the user that there is an error anyway. If you want to have actual "serious" code that goes into production in a live system, see Toby Speight's comment on pointers how to properly do that.
    if email.count("@") != 1:
        ...  # Notify the user
    username, domain = email.split("@")
    print(f"Your username: {username}")
    print(f"Your domain name: {domain}")

Finally, your use of sys.exit is incorrect. You should only use sys.exit(n) with an integer n. sys.exit(0) means "successful", anything else means "failed". Unless you have specific needs, sys.exit(1) is the default choice for failure.
To give user friendly error messages, the easiest way is to use print. You can show the messages as an error by specifying file=sys.stderr (as opposed to the default file=sys.stdout).
        print(f"{email} is not a valid email.", file=sys.stderr)
        sys.exit(1)

In total, this is what I'd propose your program could look like:
import sys
import argparse

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-f", "--file", dest="file", default=False, action="store_true")
arg_parser.add_argument("input", type=str)
args = arg_parser.parse_args()

if args.file:
    with open(args.input, "r") as file:
        emails = file.readlines()
else:
    emails = [args.input]

for email in emails:
    if email.count("@") != 1:
        print(f"{email} is not a valid email.", file=sys.stderr)
        sys.exit(1)
    username, domain = email.split("@")
    print(f"Your username: {username}")
    print(f"Your domain name: {domain}")


The first big things I got on your code, are:

you could define a function instead of passing an anonymous one to setInterval
you could move the dom serarch on the main scope to avoid the repetition on each iteration.
you could optimize the setTimeout function too, defining one on main scope and refer to a variable like selectedImage, instead of using the array.

Defining function, instead of using anonymous on the fly, help to avoid repeating yourself.

The "on the fly anonymous" are very good to cut off the development time, of for very short code or for examples.

But in production, it's better to came back and refactoring it.

Here how I would refactoring:

     $(document).ready(function(){
        /*
        =====================================
            THE SLIDER SCRIPT STARTS HERE
        =====================================
        */
        var i = 0;
        var images = ["Slide/bandera_OK%202.png","Slide/CARAVANA_carta.png","Slide/KANGOO.png","Slide/mochila.png","Slide/RADICAL_OH_03_alta.png","Slide/SILVER_final.png"];
        var topDiv = $('[data-slide='+'top'+']');
        var topImg = $('[data-slide='+'top'+'] > img');
        var bottomDiv = $('[data-slide='+'bottom'+']');
        var bottomImg = $('[data-slide='+'bottom'+'] > img');
        var selectedImage = null;

        function mySlider() {

            i++;

            if(i == images.length){
                i = 0;
                bottomDiv.animate({left:'100%'},1500);
                topImg.attr('src',images[i]);
                setTimeout(raiseTopDiv,2000);

                seletectImage = images[i+1];

                setTimeout(showSelectedImage,2500);

            }
            else if(i % 2 != 0){
                topDiv.animate({left:'100%'},1500);
                bottomImg.attr('src',images[i]);
                setTimeout(raiseBottomDiv,2000);

                seletectImage = images[i+1];

                setTimeout(showSelectedImage,2500);
            }
            else if(i % 2 == 0){
                bottomDiv.animate({left:'100%'},1500);
                topImg.attr('src',images[i]);

                setTimeout(raiseTopDiv,2000);

                seletectImage = images[i+1];

                setTimeout(showSelectedImage,2500)

            }

        }

        function raiseTopDiv() {
            bottomDiv.css('z-index','0');
            topDiv.css('z-index','1');
        }

        function raiseBottomDiv() {
            topDiv.css('z-index','0');
            bottomDiv.css('z-index','1');
        }

        function showSelectedImage() {
            bottomDiv.css('left','0px');
            bottomImg.attr('src',seletectImage);
        }

        setInterval(mySlider,3000);

    });


Python script takes input of four elements and outputs a valid 4 × 4 Sudoku grid in O(n) time, but only when given non-repeating elements

Use json to simplify your input handling.
You can use str.format to simplify all the prints.
You don't handle incorrect data well. What if I enter 3 or 5 numbers?
Your code doesn't run in \$O(n)\$ time, it runs in \$O(n^2)\$ time. I recommend that you ignore \$O\$ and just get working code if you're a novice. After you get it working make it readable. Finally here you should time your code to see if you need to then optimize it.
Use functions, they make your code easier to use.

import json

def handle_input(input_):
    try:
        data = json.loads(input_)
    except ValueError:
        raise ValueError('Invalid format.')

    if len(data) != 4:
        raise ValueError(f'Incorrect amount of numbers, got {len(data)} not 4.')
    return data

def main():
    print('Enter four numbers in brackets. E.g. [1, 2, 3, 4]')
    data = handle_input(input())
    print(
        '{0} {1} {2} {3}\n'
        '{3} {2} {1} {0}\n'
        '{1} {0} {3} {2}\n'
        '{2} {3} {0} {1}\n'
        .format(*data)
    )

if __name__ == '__main__':
    main()


Updating positions of enemies every frame

Some things you could try:

Unless the waypoints change position, the objects will continue in the same direction each frame. This means

you don't have to recalculate directionToWaypoint (unless you have imperfect rotation). This includes cos(directionToWaypoint) and sin(directionTpWaypoint)
translationX and translationY become simple multiplication
distanceTravelled seems too complicated. Why isn't it just getMovementSpeed() * delta?


I'm not sure you could make this code less clunky, it seems to me the code is reasonably simple, considering what it has to do.

But I can see other problems in your code:

The comparer parameter is probably not necessary in most cases, you can use EqualityComparer<T>.Default for this. But optional comparer makes sense to me.
LINQ extension methods are usually lazy and that's what I would expect from this method too. For example, if I do something like collection.GroupBySize(3).First(), it's not necessary to create the whole (possibly very long) result, only to discard most of it. To do this, you can use yield return.
You iterate the source collection (using LINQ methods) a lot. This can have terrible performance, especially if the source collection is something like a result of a LINQ database query, because it queries the database many times, which is not necessary. To fix this, you should write your method around a single foreach (var item in source) and don't use methods like Count(), First(), or Skip().


There's no super-design-pattern that would be beneficial here, but you could definitely benefit from some basic OO concepts like encapsulation and single responsibility.

For starters, rather than making a bunch of utility methods, it's better design to allow each class a static method like:

// inside the ContestantObj class
public static ContestantObj fromID(string ID) {
   // code to retrieve ContestantObj
}

This way, each class is responsible for creating itself, which it should be (outside of cases where a builder or abstract factory is required).

Your UpdateContestantObj constructor should take in a ContestantObj. It shouldn't care about how the ContestantObj is created. A "Contestant Updater" should be a machine that takes in Contestants and outputs Contestants that have been updated.

Also, the naming convention of ContestantObj should simply be Contestant. We know it's an object.


Using Scanner input to do some basic math and format an output

Your approach is mostly correct, but it seems to be too specifically written to solve the problem as stated.

For instance, you're making the assumption that any line that doesn't start with a plus or a minus is a line containing student names.

One example case: what if a student gets no pluses or minuses? This wouldn't occur in the case as stated, but you usually don't get this "it's already handled" and it just helps to program in such a way that input which slightly deviates from normal can still be dealt with gracefully.

You're also making the assumption that when you're counting pluses and minuses, everything that is not a plus is a minus.

This works, for now. But if changes in the scoring mechanism are requested, you might want to go with a more flexible approach - one which separates the I/O and the counting, for instance.


Stack implementation using a singly linked list

This only works with int. Did you consider taking a template parameter so it can work with other types too?
Don't compare to nullptr. Instead use if (node) or if (!node).
You're very inconsistent with how you declare pointers. You have
Node* foo, Node * foo and Node *foo. Generally in C++ this is seen as part of the type so you should prefer the first variant.
You're using a member initialization list for Node but not for StackList. Why?
Prefer an early out when possible to avoid the build-up of arrow code.
Prefer prefix (++foo) over postfix (foo++) operator
Your comments add nothing to the code and can be removed.
Opinion based but you should not omit braces as it can lead to hard to find bugs.
The destructor can be implemented in terms of pop().
Node should be part of StackList as no one outside the class needs to access it. You could also simplify it by making it a struct and directly accessing the members.
You're violating the rule of three/five/zero by having a destructor/copy assignment operator but no move constructor or operator.
Your copy constructor does too much work. You can just iterate over the passed list and push(). Same for your assignment operator, look into the copy and swap idiom.


Division and multiplication are relatively computationally costly operations compared to shifts and AND operations.  Try to reformulate your answer in terms of >> and & and you will likely find a performance gain.

Other things I noticed that may help you improve your program:

Eliminate unused variables

Both len and str are unused and may be eliminated from the program.

Try to put the loop exit condition at the top of the loop

Instead of using do {...} while, prefer to use while {...} or a for loop.  in your case this will also neatly solve the problem that occurs when the user types in a negative number.

return 0 is not needed at the end of main

Any modern compiler will automatically assume that getting to the end of main means that the program has executed successfully and will generate the equivalent of return 0 at the end.  It is not necessary to write it.

Check the return value of scanf

The call to scanf can fail, in which case it will return 0.  Your code should check for that.

If your input says you will only have positive numbers, use unsigned

Instead of "%d" it would make more sense to say scanf("%u", &n) since the inputs cannot be negative.  Note that this will not prevent negative numbers from being input, but it makes the expectation clear within the code.  Alternatively, check for negative number input to make the code more robust.

Consider verifying that your data type will hold the maximum value

The input specification says that the input numbers are all in the range of \$1 \le N \le 1,000,000,000\$ but an int isn't necessarily large enough on all platforms.  Since it takes 30 bits to express that number, and because it's unsigned, it would probably make more sense to use a uint_fast32_t type defined in <stdint.h> which is a fast integer type containing at least 32 bits.


Use your monads! Your code exhibits the walking-right antipattern. You can avoid it with when and guard. Consider goToBOL. This is how I would write it:

-- Go to beginning of line
goToBOL :: Handle -> IO ()
goToBOL h = do
        bof <- isBOF h
        when (not bof) $ do
        eof <- hIsEOF h
        if eof then do hSeek h RelativeSeek (-2)
                       goToBOL h
               else do c <- hGetChar h
                       when (not $ isNL c) $ do
                       hSeek h RelativeSeek (-2)
                       goToBOL h

In your other functions, namely getPrevLine and search, you'd better use MaybeT IO x instead of IO (Maybe x) as you can use the monadic combinators better when you do so.


How might we make this Python Merge Sort implementation more Pythonic?

If you have any expression like the one below

if(x == 0)

then you can rewrite it as

if not x

You can get rid of parenthesis and can make it more pythonic by writing like this.

Similarly you an rewrite :

if(len(leftSortedSeq) == 0):
    return rightSortedSeq
elif(len(rightSortedSeq) == 0):
    return leftSortedSeq

as

if not len(leftSortedSeq):
    return rightSortedSeq
elif not len(rightSortedSeq):
    return leftSortedSeq

If I were you I would avoid using excetions for the cases which can be avoided using simple if else. This will give the code more clarity.

We can avoid the exception by changing the code a bit.

I have also avoided conversion to tuple. The concatenation of tuple and list may cause problems. So its better to avoid unnecessary conversions.

lenLeftSeq = len(leftSortedSeq)
lenRightSeq = len(rightSortedSeq)

while leftPointer < lenLeftSeq and rightPointer < lenRightSeq:

    smallestInLeft = leftSortedSeq[leftPointer]
    smallestInRight = rightSortedSeq[rightPointer]

    if(smallestInLeft < smallestInRight):
        mergedSeq.append(smallestInLeft)
        leftPointer += 1
    else:
        mergedSeq.append(smallestInRight)
        rightPointer += 1

return mergedSeq +
             leftSortedSeq[leftPointer:] +
             rightSortedSeq[rightPointer:]


As long as the variables are well-named, I think your way (subquery) will be clear and therefore quite acceptable, though I'm not quite sure whether it will affect performance or to what extent (try benchmarking).

That said, I'd still urge you to use a prepared query  or stored procedure or function, I think that would make it even more clear, and potentially faster.


a function to partition images into patches

PEP-8 Guidelines

Your code violates the PEP-8 standard in several area, including (but not limited to):

Operators should have 1 space before and after the operator (y + h instead of y+h)
One space after commas (x, y, w, h not x,y,w,h)
Slices should not have any spaces around the colon (y:y_end not y: y_end)

Spelling

Columns is spelt with an n.

Meaningful names

I don't know what cal_patches means.  Is cal short for "calculate"?  Your question title says "partition"; perhaps that should be part of the function name.

docstring

Add a doc-string to help() the user understand what the function does, and what the function returns ... without having to consult the source code.

Type Hints

With Python 3.6+, you can add type hints to the function to further improve understanding about what the function requires and what it returns:

def cal_patches(img: Image, num_colums: int) -> List[Image]:

Useful arguments

The function can partition the image into a number of vertical columns.  What if I wanted a number of rows as well?  I can't request that.

Oh wait!  It does do rows too.  But always the same number of rows and columns.  Perhaps add num_rows to the argument list too?

Integer division

int(n / d) is verbose and unnecessary.  Use the integer division operator n // d.

Unused variables

ind is never used anywhere, and could be removed.

i and j are never used anywhere, so could be replaced by the "throwaway" variable _.  Even better, you could use the w and h values as the step size for the range(), and get rid of the x += w and y += h statements:

Avoid calculating unchanging values

In the inner loop, y is not changing, so y_end results in the same value each iteration of the inner loop.  It can be moved out of the inner loop.

Bug?

The inner loop goes over the number rows, but is increase x by w, which is a column increment.  Did you accidentally swap the rows and columns?  It works as long as num_rows == num_columns, but it will cause grief when that is relaxed.

Updated code

def create_image_patches(img, num_rows, num_columns):
    """
    Partition an image into multiple patches of approximately equal size.
    The patch size is based on the desired number of rows and columns.
    Returns a list of image patches, in row-major order.
    """

    patch_list = []
    width, height = img.shape[1], img.shape[0]
    w, h = width // num_columns, height // num_rows

    for y in range(0, height, h):
        y_end = min(y + h, width)
        for x in range(0, width, w):
            x_end = min(x + w, height)
            patch = img[y:y_end, x:x_end]
            patch_list.append(patch)

    return patch_list

Add type hints using the typing module.

Generator

As suggested by @Graipher, this function could be turned into a generator, which may be useful depending on how the patches are processed downstream:

def generate_image_patches(img, num_rows, num_columns):
    """
    Generate image patches of approximately equal size from a source image.
    The patch size is based on the desired number of rows and columns.
    Patches are generated in row-major order.
    """

    width, height = img.shape[1], img.shape[0]
    w, h = width // num_columns, height // num_rows

    for y in range(0, height, h):
        y_end = min(y + h, width)
        for x in range(0, width, w):
            x_end = min(x + w, height)
            yield img[y:y_end, x:x_end]

A "helper" function could be used to turn the generator back into a list, if required for existing callers of the function:

def create_image_patches(img, num_rows, num_columns):
    """
    Partition an image into multiple patches of approximately equal size.
    The patch size is based on the desired number of rows and columns.
    Returns a list of image patches, in row-major order.
    """

    return list(generate_image_patches(img, num_rows, num_columns))


Low-level methods with temperature conversion program

Overall I think the most important thing to improve here is code clarity.

You have some code like this:

if input_type == str("c"):

"c" is already a string so doing str("c") is redundant. It's definitely easier and clearer to just write:

if input_type == "c":

There is also a lot of boilerplate to call the required functions with that big if-else block. Instead I would use a dictionary here to do this:

temp_input = int(raw_input("What is the Temperature: "))

input_type = str(raw_input("Would you like to convert to Celsius or Fahrenheit?: "))

conversion_dispatcher = {
    "c": convert_fahrenheit,
    "C": convert_fahrenheit,
    "celsius": convert_fahrenheit,
    "Celsius": convert_fahrenheit,
    "f": convert_celsius,
    "F": convert_celsius,
    "fahrenheit": convert_celsius,
    "Fahrenheit": convert_celsius,
}

try:
    conversion_dispatcher[input_type](temp_input)
except KeyError:
    print("You have not entered a valid conversion")

This way you end up with a lot less boilerplate overall and it's much easier to make changes if you find a problem.

Also I would change the conversion functions to return a value and I would print that value afterwards:

def convert_fahrenheit(x):
    x = (x - 32) * 0.556
    return x

def convert_celsius(x):
    x = (x * 1.8) + 32
    return x

try:
    new_value = conversion_dispatcher[input_type](temp_input)
    print(new_value)
except KeyError:
    print("You have not entered a valid conversion")

The reason for this is because it more clearly separates out the logic from the display code. The makes those conversion functions more reusable as you can now use them in situations where you don't just want to print to the console.

You might also have noticed that I have changed your print syntax to the new print function syntax. This is because the old print statement is going away in newer version of python (python 3.x) and you might as well get used to writing it the other way now. If this causes an error in your version of python you might need to use from __future__ import print_function at the top of your file.

Now that we are done with the Python related stuff it's probably good to improve some other elements of the code. Given the function name isn't completely unambiguous a docstring explaining which way the units conversion is being applied in the conversion functions would help future readers of your code understand what's going on better. This is especially the case because your printout at the beginning suggests different behavior to the code you wrote.

For example:

def convert_to_celsius(x):
    """Converts a temperature in Celsius to Fahrenheit"""
    x = (x * 1.8) + 32
    return x


I don't think memoization will be useful here. Any correct algorithm is going to be O(n!), nothing you do can reduce that fundamentally because you still have to output all the paths.
Trying to cache stuff you already output is just going to make the space-costs worse, it won't make the processing-time any better.
The advantages of using a generator are that the caller doesn't have to wait for the whole computation to finish before handling the early outputs, and that we never have to store the results of the whole computation at once. This is a good choice for the task at hand!
It doesn't affect the point in (1.) though.
You seem to have already found the textbook algorithm.
There are various things to make the code prettier, but you'd have to do some testing to see if they make it work better.

Types are nice. They do nothing at runtime, but they let MyPy check for many kinds of mistakes.
I don't like the redundancy of path and seen, and I don't like that you're mutating seen the way you are, but I suspect the way you've written it is actually the most efficient for larger graphs.
The expression path + [src] makes two calls to the list constructor, and it's happening inside the for loop. That can be improved!
Since you never mutate a value of path, it can be a tuple instead of a list.
The way you have it set up now, your adjacencies dict will always contain src, so you don't need to use get.

I'm ignoring your outer wrapper, and I've made no effort to test this:
from typing import Iterable, Mapping, MutableSet, Sequence, TypeVar
N = TypeVar('N')
def dfs(source: N,  # The current node
        destination: N,  # The destination node
        path: Sequence[N],  # The path taken to the current node
        seen: MutableSet[N],  # The nodes visited on the path
        graph: Mapping[N, Iterable[N]]  # The graph being explored, as an adjacency dict
) -> Iterable[Sequence[N]]:
    new_path = (*path, source)
    if source == destination:
        yield new_path
    else:
        seen.add(source)
        for n in graph[source]:
            if n not in seen:
                yield from dfs(n, destination, new_path, seen, graph)
        seen.remove(source)


Generating and printing chess board in Rust

You can define your pieces as an enum, then you don't need to box them in your squares:

#[derive(Clone, Copy)]
pub enum Piece {
    King,
    Queen,
    Rook,
    Bishop,
    Knight,
    Pawn
}

Notice that we derive Clone and Copy; this is so that we can put them in our board array later.  You now define your symbols here. Notice how they're all in one nice place now?

#[derive(Clone, Copy)]
struct Square {
    piece: Option<Piece>
}

impl Square {
    pub fn new() -> Square {
        Square { piece: None }
    }

    fn symbol(&self) -> &str {
        match self.piece {
            Some(Piece::King)   => "K",
            Some(Piece::Queen)  => "Q",
            Some(Piece::Rook)   => "R",
            Some(Piece::Bishop) => "B",
            Some(Piece::Knight) => "k",
            Some(Piece::Pawn)   => "p",
            None                => "."
        }
    }
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.symbol())
    }
}

You have also eliminated the need to have any Boxes, which could have some annoying unwrapping later.  It also eliminated some runtime errors and helps the compiler make sure your code is correct.

You can define your board using a 2D array like so:

pub struct Board {
    squares: [[Square; 8]; 8]
}

impl Board {
    pub fn new() -> Board {
        let mut squares = [[Square { piece: None }; 8]; 8];
        // ...
    }
}

Without seeing what you tried, I can't know why it didn't work before, it could be because you didn't derive Clone and Copy for your squares and pieces.  I have opted to go for a 2D array, as I feel it is easier to reason about than a single 1D array.  It also means you don't need to have lookups like myArray[x * width + y] everywhere which is just messy, I find myArray[x][y] is preferable.  I won't show it, but I updated your fmt::Display for Board code to match.

Finally your board creation.  Look upon the niceness of the enum, and rejoice!  Also see how nice the 2D array is, and pattern matching.  I really love Rust.

pub fn new() -> Board {
    let mut squares = [[Square { piece: None }; 8]; 8];

    for x in 0..8 {
        squares[x][1].piece = Some(Piece::Pawn);
        squares[x][6].piece = Some(Piece::Pawn);
        let piece = match x {
            0 | 7 => Some(Piece::Rook),
            1 | 6 => Some(Piece::Knight),
            2 | 5 => Some(Piece::Bishop),
            3 => Some(Piece::King),
            4 => Some(Piece::Queen),
            _ => unreachable!()
        };
        squares[x][0].piece = piece;
        squares[x][7].piece = piece;
    }

    Board {
        squares: squares
    }
}

It might feel as if I've really torn your code apart here, but it's not surprising given how different Rust actually is compared to what most people would call its closest competitor, C++.  Implementing Clone and Copy is very easy to miss and very important if you don't want to have a nightmare of boxed instances later.  Using the enum style I have here does mean that functionality for things like finding valid moves will be the job of the board, rather than the pieces, but you already started down that track.  Don't forget as well that Rusts "thick" enums mean that you can still attach a moveset to your enumerated type, if that ends up being the easiest way to implement it.


I do have a lot of comments, but I find your solution pretty good.  The algorithm makes sense, and your comments make it easy to follow.

The function is closer to a computation than a search, so I wouldn't call it find….  The N parameter is redundant, since it can be deduced from the dimensions of prices.  On the other hand, color_names is hard-coded (and worse, 3 is hard-coded in several places); I would make it parameterized.  The comment on the function should be a docstring.

I would prefer to return a list; the caller can join them into a string if desired.

I can understand crashing if there are 0 colors (because the problem would be ill-defined in that case), but the function should not crash if there are 0 houses.

The algorithm works by "walking up and down the street", evaluating the color choice at each house.  Therefore, the code would be more natural if you transposed the matrices,1 such that the primary axis is the house number, and the secondary axis is the color.  You can observe the benefit when writing the totals for the first house: your solution slices prices; my solution below just copies an element.

You initialize totals to a matrix of 0s and colorings to a list of 3s.  I prefer to allocate empty lists using [None] * n.

You perform set operations on colors.  I prefer to use list comprehensions with an if filter.  I suspect that that the filtered list comprehension should be faster, though your set operations might be easier to understand.

def cheapest_house_coloring(prices, color_names='ROYGBIV'):
    """
    Finds the cheapest way to color a list of N houses using C colors such that
    no two consecutive houses have the same color.

    prices is an N-by-C array containing the price to paint the house n with
    color c.

    color_names is a sequence containing the names of the colors.
    """
    num_houses = len(prices)
    if not num_houses:
        return []
    num_colors = len(prices[0])

    totals = [None] * num_houses
    totals[0] = prices[0][:]

    # After the first house, dynamic programming does its magic.
    # At each step, add the price of painting this house
    # to the minimum of the total painting of the other colors.
    for house in range(1, num_houses):
        totals[house] = [
            prices[house][color] +
            min(totals[house - 1][c] for c in range(num_colors) if c != color)
            for color in range(num_colors)
        ]

    # Now we have the totals to paint up to each house.
    # We'll just work backwards to find the coloring of the houses.
    colorings = [None] * num_houses
    colorings[-1] = min(range(num_colors), key=lambda c: totals[-1][c])
    for house in range(num_houses - 2, -1, -1):
        # Take the index of the cheapest option (infinite cost
        # prohibits consecutive houses with the same color)
        colorings[house] = min(range(num_colors),
            key=lambda c: totals[house][c] if c != colorings[house + 1]
                else float('Infinity'))

    # Convert color indexes to names
    return [color_names[colorings[house]] for house in range(num_houses)]

1 If you need to transpose a matrix, use list(zip(*matrix)).


Select box to highlight choice deviation

Maybe use a generic function to set the css on change if you don't have anything other than colors. It also helps with dry.

function evt_highlightRow() {
    row = $(this).parent().parent()
    if ($(this).val() != 0)
      row.css('background-color', 'yellow');
    else
      row.css('background-color', 'white');
}

Then use it like so:

$(some_target_nested_2_deep).on('change', evt_highlightRow);

// such as your select
$('select').on('change', evt_highlightRow);
// or a generic class applied to inputs in the same general location
$('.highlightRowTarget').on('change', evt_highlightRow);

I created the example here: https://codepen.io/anon/pen/bWraNB


Creating a wrapper function for jQuery Ajax

I heard you like wrappers
So I wrapped your wrapper (jQuery) in a wrapper (your thing) so you can do ajax.
Why do you do this again??
Instead of wrapping over (slow) jQuery you could just wrap the native ajax functionality. In general I expect that to be faster. Additionally this frees your API to be changed independently of jQuery and it removes that nasty jQuery dependency at all.
Don't wrap wrappers in wrappers, unless you add significant functionality
What significant improvement does your API provide over jQuery's?


There are a number of things you can do to improve this code.

Use const where possible

The print routine does not (and should not) alter the linked list, and so it should be declared as taking const node *list as an argument.

Check the return value of malloc before dereferencing

The primary way that the operating system uses to tell your program that it's running out of memory is to return NULL when the program requests a memory allocation.  For that reason, you must check the return value before dereferencing it to make sure it's not NULL.

Eliminate memory leak

There are calls to malloc but no calls to free so this code certainly leaks memory.

Separate I/O from core routines

It's often better to have input and output operation in a single place (or a few select places) rather than having them scattered in several places.  For this reason, I'd recommend having the enter routine simply be responsible for putting the new data into the linked list rather than having it also get the new number.

Use for loops rather than while loops where practical

Your print routine can be considerably simplified by using a for loop rather than a while loop and eliminating useless variable i:

void print(const node *list)
{
    for ( ; list; list = list->next)
        printf("%d\n",list->num);
}

Reduce memory allocations

The first number read is a count of the following numbers.  This tells you exactly how many nodes need to be allocated, so there really isn't any need to have multiple calls to malloc.  You can simply call it once, allocate an array of nodes that is large enough to hold all of the numbers and use that memory area for all of your linked list nodes.

Eliminate the need to sort

Rather than having separate enter and sort routines, you may find that peformance is better if you sort as you enter each number.

Putting it all together

Putting all of these suggestions (and more) into practice might look like this:

void enter(node *list, node *newnode)
{
    for ( ; list->next && list->next->num < newnode->num; list = list->next);
    newnode->next = list->next;
    list->next = newnode;
}

void print(const node *list)
{
    if (list == NULL)
        return;
    for ( ; list->next; list = list->next)
        printf("%d\n",list->next->num);
}

int main()
{
    int tot_num;
    scanf("%d",&tot_num);  //asking for entering total numbers
    node *head = calloc(tot_num+1, sizeof(node));
    if (head == NULL) {
        printf("ERROR: could not allocate space for %d numbers\n", tot_num);
        return 1;
    }
    for (int i=1; i <= tot_num; ++i) {
        scanf("%d",&(head[i].num));
        enter(head,&head[i]);
    }
    print(head);
    free(head);
}

Results

Even this very simple program runs approximately 3x faster on my machine (64-bit Linux machine) than the original, operating on a file of 10,000 random numbers.  It is still quite slow, however, because the enter routine only does a simple linear search.  There are better ways to do this, and I would encourage you to look into better sorting algorithms and to try to implement some to see how they work.