It is possible to make the application faster (but I am not sure that you will notice the difference unless you call the application with many arguments and have many drives). The main problem with the code is that you iterate through all the arguments, and for each argument you iterate through all the drives until you find the matching drive-letter.

So if the the application is called with an unknown drive-letter 10 times (as in "PATHTOEXE\drivespace.exe" drive-X drive-X drive-X drive-X ... and if you have 15 drives mounted, then DriveInfo.GetDrives() will be called 10 times and the line if (drive.Name == parts[1] + ":\\") will be executed 150 times. To avoid this you could store the drive information in a dictionary and then just lookup the matching drive in near constant time.

Notice below that I have changed the format of the arguments to the application to DriveSpace.exe C D X to avoid the parsing of the individual argument.

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Drivespace
{
    class Program
    {
        static void Main(string[] args)
        {
            var allDrives = DriveInfo.GetDrives().ToDictionary(drive => drive.Name);

            foreach (String arg in args)
            {
                DriveInfo driveInfo;
                if (allDrives.TryGetValue(arg + @":\", out driveInfo))
                {
                    if (driveInfo.IsReady)
                    {
                        WriteOutput(driveInfo.TotalSize, driveInfo.TotalFreeSpace, "READY");
                    }
                    else
                    {
                        WriteOutput(0, 0, "NOTREADY");
                    }
                }
                else
                {
                    WriteOutput(0, 0, "NOTFOUND");
                }
            }
        }

        private static void WriteOutput(long totalSize, long freeSpace, string status)
        {
            Console.WriteLine(String.Format("{0},{1},{2}", totalSize, freeSpace, status));
        }
    }
}


MVC binding list of values to checkboxlist in an efficient way

In my opinion, your view is doing too much work. This is happening because your model is missing a property.

If you add an IsSelected property to your model, I think we can simplify the view a bit.

public class DeliveryAddress()
{
    public int ID { get; set; }
    public string Location { get; set; }
    public bool IsSelected { get; set; }
}

Now this single model contains all the information you need to bind to the view. You no longer even need the DeliveryAddressSelectionModel. The controller would look something like this (untested, I'm typing in the browser):

[HttpGet]
public ActionResult Edit()
{
    var selectedAddressIDs = new List<int>() { 1, 2, 4 };

    List<DeliveryAddress> model = AddressDetails.GetAvailable();

    foreach(var address in model.Where(a => selectedAddressIDs.Contains(a.ID)))
    {
        address.IsSelected = true;
    }

    return View(model);
}

Create a partial view for your DeliveryAddress.

@Model DeliveryAddress

@Html.CheckBoxFor(m => m.IsSelected)
@Html.LabelFor(m => m. Location)

Then, from your main view, render the partial view.

@Model System.Collections.Generic.List<DeliveryAddress>

<form method="post">

        @foreach(var address in Model)
        {

            @Html.RenderPartial("DeliveryAddress", address)

        }

    <input type="submit" value="Save Address"/>
</form>


I won't add to @mtj's comment (I totally agree that an array defined as a means to exchange information is a code smell).

I agree with @RobAu that you should stay far a away from those magic numbers and arrays. That would avoid bugs like:

this.counts[APPLE_INDEX] += other.getCounts()[ORANGE_INDEX];

Now to my comments.

Strategy is not the name of the Pattern applied here. It is more like a Composite Pattern, because several Strategies can be applied at the same time (although no method is available to add further discounts, but I suppose it was the intent).

In general I don't advise naming Objects by the Design Pattern they implement. Objects should be named as per what they do, not how you thought about making an architecture around them. It's useful in a tutorial, not in actual code. Carrying XXXStrategy everywhere gets real annoying, and lead to confusions (like a WallObserverListener : does it listen to an observer, or observe a listener?).

The solution to keep people to the page about you using a particular Pattern is Javadoc. This allows for cleaner code with method names that are more business-oriented, like:

public void apply(Discount discount);

Which is more obvious than:

public void addStrategy(CheckoutStrategy strategy);

A Better way to combine deals

You could use a Decorator pattern for your deals.

First clean up your interface:

public interface Checkout {
    double calculateTotal(List<String> shoppingCart);
}

Then make a simple price calculator (Note there is no hard-coded pricing, it can be created at runtime:

public class SimpleCheckout implements Checkout {

    private final Map<String, Double> basePrice = new HashMap<>();

    public void addPrice(String item, double price) {
        basePrice.put(item, price);
    }

    @Override
    public double calculateTotal(List<String> shoppingCart) {
        // Your own code, very good use of Streams, here
        return shoppingCart.stream().mapToDouble(basePrice::get).sum();
    }
}

Now we simply need to add discounts as a decoration layer:

public class DiscountValue implements Checkout {

    private final Checkout baseCheckout;
    private final String discountedItem;
    private final int minimumAmount;
    private final double discountValue;

    public DiscountValue(Checkout base, String item, int min, double discount) {
         this.baseCheckout = base;
         this.discountedItem = item;
         this.minimumAmount = min;
         this.discountValue = discount;
    }

    @Override
    public double calculateTotal(List<String> shoppingCart) {
        int count = Collections.frequency(shoppingCart, discountedItem);
        // Integer division gives the number of times the discount is applied
        double deduction = (count / minimumAmount) * discountValue;
        return baseCheckout.calculateTotal(shoppingCart) - deduction;
    }
}

Now this is how you use it:

public static void main(String[] argc){
    Checkout pricing = new SimpleCheckout();
    pricing.addPrice("Apple", 0.25);
    pricing.addPrice("Orange", 0.6);
    pricing = new DiscountValue(pricing, "Apple", 2, 0.25); // I'm using a straight-up refund here
    pricing = new DiscountValue(pricing, "Orange", 3, 0.60); // I'm using a straight-up refund here
    List<String> shoppingCart = new ArrayList<>();
    shoppingCart.add("Apple");
    shoppingCart.add("Orange");
    shoppingCart.add("Apple");
    shoppingCart.add("Apple");
    System.out.prinln(pricing.calculateTotal(shoppingCart));
}


There is some code duplication for the cases “greeting date has never been set” and “last greeting was yesterday or earlier.” This can be avoided if you use the nil-coalescing operator ?? to set the last greeting date to a default value in the past:

let defaults = UserDefaults.standard
let lastGreeting = defaults.object(forKey: "greetingDate") as? Date ?? .distantPast
let now = Date()
if Calendar.current.compare(now, to: lastGreeting, toGranularity: .day) == .orderedDescending {
    defaults.set(now, forKey: "greetingDate")
    presentWelcomeScreen(tabbar: tabbar)
}


The code you posted contains no error-recovery at all. It's a bit off-topic on this site to ask how to implement a new feature (error-recovery); but I'll try.
It's not clear what your communication protocol looks like. It might be:

A continuous stream of bytes, to be split into packets of 10
10-byte packets, with a measurable delay between packets, no reply expected
10-byte packets, after which silence until there is a reply, perhaps with a retry if there no reply

I'll assume it isn't 1. because that has little opportunity for error-recovery: if a byte were ever lost then you wouldn't know where the boundary is between "packets", if it's a continuous stream of bytes, unless you use 'framing' and 'escape sequences' in the data.
So I'll assume that it's 2. or 3.. In either case, what's important is:

There are 10 bytes received (probably received quickly with little or no delay between bytes)
There is then a delay (no bytes received) after those 10 bytes.

Setting Read Timeouts looks interesting. It may be your best algorithm: set VMIN to say that you want to receive no more or less than exactly 10 bytes when you read.
However that may have a problem:

However, the timeout only applies to the first character read, so if for some reason the driver misses one character inside the N byte packet then the read call could block forever waiting for additional input characters.

You don't say why you want error-recovery after losing a character: perhaps you sometimes get overruns in the driver, or bit parity errors from the serial port?
"Setting Input Parity Options" talks about handling the parity errors:

Replace/mark the byte with an error byte
If you do this then you can be more sure that you will get 10 bytes; but you can only do it if the protocol allows you to recognize an illegal byte value.

Or remove the error byte
If you do this then you must be able to recover from getting 9 bytes sometimes.

The data I receive should be always 10 bytes in length but I want to be sure that, if there is any error (more or less bytes received), reading will clear buffer before the next data arrive, so that there is always proper data in the buffer to be processed.

Reading should empty the buffer, if your sizeof(tmp_buffer) is bigger is the number of bytes queued in the driver. However:

It depends on the read mode (e.g. a read may block forever instead of clearing the buffer, if VMIN is set to non-zero)
If there are, somehow, very many received bytes enqueued in the driver, then you may have to read repeatedly until the driver is empty.
Immediately after you read, there may be more bytes in the driver: for example if the serial port is flow-controlled, reading from the driver allows the device to send again / send more.

Whether you can clear the buffer "before the next data arrive" is difficult to say: I don't know when the next data is supposed to arrive.
Depending on how you handle parity errors, maybe bytes are never lost. If bytes are sometimes lost then you may want to implement logic like:
read_10_bytes:
  read (waiting forever) until some bytes are returned
  if 10 bytes were read then return
  if less than 10 bytes were read, then:
    set an expiry timer
    loop doing the following
  read more bytes
  if you read 10 bytes before the timer expires, then clear the timer and return
  if the timer expires before you read 10 bytes, then discard the bad bytes and return

Instead of actually setting a timer, above, perhaps loop doing a blocking-read-with-timeout (which either reads the bytes, or expires).
As well as handling too few bytes (above), you could modify the above to check for receiving more than 10 bytes: after you receive 10 bytes, do another blocking-read-with-small-timeout to verify that there are no more bytes to receive. If there are extra bytes, then read them all before returning to the 'waiting-for-next-10-bytes' state (otherwise, these extra bytes will mess up your next 10-byte packet).

I think there's an obvious bug in the code. After you read 16 bytes, you completely clear your serial_buffer by zeroing si_processed, and you then think "success!" after each next 10 bytes you read.
Instead you should:

If you read too much data, don't discard the extra bytes: instead use memmove to move them to the beginning of the buffer (assuming they're the start of the next packet), and then read the subsequent bytes into the vacant space after them.

Something like:
// after reading and processing a 10-byte packet
if (si_processed > 10) // already have the start of the next packet
{
     // move start of next packet to start of buffer
     memmove(serial_buffer, serial_buffer+10, si_processed - 10);
     // not 0: remember how many start bytes we already have
     si_processed -= 10;
}

After you read any bytes, verify whether the start byte is your 0xA5 value, and discard the bytes if not.

Something like:
if (si_processed > 0) // have some bytes
{
    int i;
    for (i = 0; i < si_processed; ++i)
        if (serial_buffer[i] == 0xA5) // found start of packet
            break;
    if (i > 0)
    {
        // start of packet is not start of buffer
        // so discard bad bytes at the start of the buffer
        memmove(serial_buffer, serial_buffer+i, si_processed - i);
        si_processed -= i;
    }
}


First off, I'd like to mention, that my Scala experience is limited, so please do point out any errors.

You should implement your algorithm in it's own class implementing an appropriate interface/trait (probably Iterator, but there may be better ones).

That would also avoid having the awkward hard-coded limit to 11 elements in the main algorithm.

I'm not a fan of the repeated code for the three base numbers. Off the top of my head I'm not sure how to avoid it, but would assume it would include using case classes.

You should also have a look at your variable names. You have a mixture of short cryptic names (n, i3, etc.) and two different styles (camel case and underlines). You should always use descriptive names (maxIterations, index3) and use a single style (preferably camel case as this is the convention for Scala).

BTW, List has a min method, so there is no need to roll your own:

val nextUglyNumber = List(next_multiple_2, next_multiple_3, next_multiple_5).min;


You should always try to program against an interface instead of against an implementation.

List<T> elements;

should be

IList<T> elements;

Restrict the scope of fields and methods to the smallest possible.
So public void Heapify() should be private instead.
The swapping of elements inside the Heapify() method can be extracted to a private method.

private void SwapElements(int firstIndex, int secondIndex)
{
    T tmp = elements[firstIndex];
    elements[firstIndex] = elements[secondIndex];
    elements[secondIndex] = tmp;
}

Former Heapify() method now

private void Heapify()
{
    for (int i = elements.Count - 1; i > 0; i--)
    {
        int parentPosition = (i+1) / 2 - 1;
        parentPosition = parentPosition >= 0 ? parentPosition : 0;

        if (elements[parentPosition].CompareTo(elements[i]) > 1)
        {
            SwapElements(parentPosition, i)
        }
    }
}

Potential bug
You are checking if the CompareTo() method returns a value > 1 but you miss ==1 as the documentation states

value < 0 => This instance precedes obj in the sort order.
value == 0 => This instance occurs in the same position in the sort order as obj.
value > 0 => This instance follows obj in the sort order.

//relook at this - should we just throw exception?
If you want to simulate a Stack then you should throw an InvalidOperationException but only if you also provide a property Count so that a user of your class can evaluate if he can call PopMin safely.


no need to loop as you are using find method and find method always give single result

$result = TheEpisode::find($id);
$result->TheParts->makeHidden("title");
dd($result->toArray());


You have done the optimization of removing multiples of 2 (by incrementing by 2).

There is another slight improvement that removes multiples of 2 and 3 from the test.

bool IsPrime (int n) {
   if (n == 2)     return true;
   if (n == 3)     return true;
   if (n < 5)      return false;
   if (n % 2 == 0) return false;
   if (n % 3 == 0) return false;

   int inc = 4;
   int dec = -2;
   for (int i = 5; i <= int(sqrt(n)) + 1; i += inc)
   {
       if (n % i == 0)
               return false;
       inc = inc + dec;  // makes inc go 2/4/2/4/2/4/.....
       dec = dec * -1;
   }
   return true;
}

Another optimization for IsPrime() is that you only need to test using primes. ie no pointing in testing with 6 (its not prime) as all values that are divisible by 6 are also divisible by 3 (is prime). So if your loop only tested by using other primes:

// Assumes you are calling this function with monotimically inreassing
// values of n so that the `foundPrimes` vector will be constructed in order.
bool IsPrime (int n) {

   static std::vector<int>   foundPrimes = { 2, 3, 5, 7, 11 };

   for(std::size_t loop = 0; loop <  foundPrimes.size(); ++loop)
   {
       if (n == foundPrimes[loop])     { return true;}
       if (n % foundPrimes[loop] == 0) { return false;}
   }
   start = foundPrimes.last() + 2;

   for (int i = start; i <= int(sqrt(n)) + 1; i += 2)
   {
       if (n % i == 0)
               return false;
   }
   foundPrimes.push_back(n);
   return true;
}

The next optimization is called the Sieve of Eratosthenes. This needs a minor re-write but is very efficient. You would use the sieve to calculate all the primes you need first. Then just look up the values be checking if they are in the sieve.


Project Euler problem 11, finding adjacent numbers with the greatest sum

The code I have written works fine but seems extremely verbose for what it's doing ... Would be great for there to be a way to make the numberPairs function to be more DRY.

I agree that there's a fair bit of repetition happening. This makes things very explicit, but at the cost of more boilerplate, as you said.

I suggest that the movement patterns for each direction be separated from the actual functionality of extracting a "line" of adjacent numbers from the board. That way, it's easier to see the differences between each direction:

quads :: Direction -> [[Int]]
quads UpDown
    = getLines 4 [0..16] [0..19] succ id
quads SideWays
    = getLines 4 [0..19] [0..16] id succ
quads LeftStartDiagonal
    = getLines 4 [0..16] [0..16] succ succ
quads RightStartDiagonal
    = getLines 4 [0..16] [3..19] succ pred

I've renamed numberPairs to quads because "pair" usually refers to a 2-tuple. succ and pred are just equivalent to (+ 1) and (- 1).

Now you can define getLines more generally (albeit with an uglier signature), in terms of iterating the row and column position with the supplied rowFn and colFn:

getLines :: Int -> [Int] -> [Int] -> (Int -> Int) -> (Int -> Int) -> [[Int]]
getLines n rows cols rowFn colFn =
    [line |
     row <- rows,
     col <- cols,
     let coordPairs = zip (iterate rowFn row) (iterate colFn col),
     let line = take n $ map gridGet coordPairs]

gridGet :: (Int, Int) -> Int
gridGet (row, col) = listifyGrid !! row !! col

This is just rearranging your code, except that I've used [Int] instead of (Int,Int,Int,Int) as the type of each number line. I'm not an experienced Haskeller, but I think that, here, the list is considerably easier to deal with than the tuple, at the expense of giving up an explicit length guarantee.

Using a list also makes it easy to adapt to other lengths than 4, since it's just a take n. The tuple code, at least structured as you have it right now, would grow linearly.

  Also get the sense that I don't use function composition enough . and instead use $ for most nested function calls. Is this bad practice? How could I rewrite some of the functions in this using composition?

Again, keeping in mind that I haven't done a whole lot of Haskell: I don't see anywhere in your code where $ looks out of place.

One place where composition is nice, though, is with map and nested lists. This:

listifyGrid :: [[Int]]
listifyGrid = map (map read) doubleListOfStrings
    where doubleListOfStrings = map (S.split " ") $ lines gridOfNumbers

could use composition if you want, as well as the words function:

listifyGrid = (map . map) read $ map words $ lines gridOfNumbers

(map . map) is so elegant that the equivalent in Python, for example, just seems obtuse. Oh, Haskell, you charmer.

Anyway, the main problem_11 function:

problem_11 :: Direction -> Int
problem_11 dir =
    maximum $ map (\(x1,x2,x3,x4) -> product $ x1:x2:x3:x4:[]) $ numberPairs dir

can also be defined as a pointfree composition, if that's your style, especially now that we can use map directly without unwrapping the tuple:

problem_11 = maximum . (map product) . quads


Find two numbers that equal to target value

Few suggestions:

Naming: array is not an array, a more appropriate name can be numbers. Also unique_number_set can be just unique_numbers, the name already tells that there are no duplicates.
Unnecessary else: the else is not required so it can be removed.
Type hints: @Linny already pointed this out. I add that, if the result doesn't need to be modified, consider returning a tuple. Additionally, it tells the caller that the result will only contain two numbers.

from typing import List, Tuple, Union

def two_number_sum(numbers: List[int], target: int) -> Union[Tuple[int, int], Tuple[()]]:
    unique_numbers = set()
    for num in numbers:
        required_value = target - num
        if required_value in unique_numbers:
            return num, required_value
        unique_numbers.add(num)
    return ()

Thanks to @KellyBundy and @AJNeufeld for the feedbacks in the comments.


Basic PHP MVC setup for form submissions

Templates

Your HTML code should be separated out into a template file. You should do your best to avoid mixing HTML into your PHP, as your HTML will inevitably grow, and your PHP will get messier as a result.

Post/Get/Redirect

The pattern you are looking for is Post/Get/Redirect. You should always follow this pattern. When a user submits a form using POST, you should process the form, and then if it was successful, redirect them back to some page (possibly the form page again) with an added URL parameter.

E.g. http://example.com/contact-us?submitted=true

Then in your form code, you can check if the URL parameter is present, and show a success message.


Resository Pattern and Unit of Work with ADO.net

It's a good start. Here are the changes I suggest:

I think you should be able to execute the queries without sharepoint. To make it possible we'll remove the sharepoint stuff from the repository and put it in another one. We then combine them with a decorator pattern like this:

The first step is to extract an interface (or an abstract class):

public interface IResourceRepository
{
    Resource GetByLoginname(string loginname);
}

Then we implement it in the first repository that will get resources from the database:

public class ResourceRepository : IResourceRepository
{
    public Resource GetByLoginname(string loginname)
    {
        return ExecuteSql(cmd =>
        {
            cmd.CommandText = @"SELECT convert(nvarchar(36), ResourceUID) AS ResourceUID, UserClaimsAccount, ResourceName FROM MSP_EpmResource_UserView WHERE UserClaimsAccount = @userclaimsaccount";
            cmd.Parameters.AddWithValue("@userclaimsaccount", SqlDbType.NVarChar).Value = loginname;

            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var resource = Resource.From(reader);
                    if (resource != null)
                    {
                        resource.Teams = GetResourceTeams(resource);
                    }
                    return resource;
                }
                return null;
            }
        });
    }

    private static void ExecuteSql(Action<SqlCommand> action)
    {
        string connectionString = Connectivity.GetConnectionString();

        using (var conn = new SqlConnection(connectionString))
        {
            conn.Open();
            var cmd = conn.CreateCommand();

            action(cmd);
            cmd.ExecuteNonQuery();
        }
    }

    private static T ExecuteSql<T>(Func<SqlCommand, T> action)
    {
        T result;

        string connectionString = Connectivity.GetConnectionString();

        using (var conn = new SqlConnection(connectionString))
        {
            conn.Open();
            var cmd = conn.CreateCommand();

            result = action(cmd);
            cmd.ExecuteNonQuery();
        }

        return result;
    }
}

Now you need the elevated privilages for sharepoint. So lets create a decorator for this one:

public class ElevatedPrivilegesResourceRepository : IResourceRepository
{
    private readonly IResourceRepository _resourceRepository;

    public ElevatedPrivilegesResourceRepository(IResourceRepository resourceRepository)
    {
        _resourceRepository = resourceRepository;
    }

    public Resource GetByLoginname(string loginname)
    {
        var result = default(Resource);

        Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(
            () => result = _resourceRepository.GetByLoginname(loginname));

        return result;
    }
}

You will pass an instance of the first repository to this one and it will execute the query with sharepoint's elevated privilages.

var repo = new ElevatedPrivilegesResourceRepository(new ResourceRepository());

var resource = repo.GetByLoginname("foo");

There is one more change that I've made. I put the cretion of a resource into a factory method of this class:

public class Resource
{
    public string RessourceUID { get; set; }
    public string RessourceName { get; set; }
    public List<Team> Teams { get; set; }
    public string Loginname { get; set; }

    public static Resource From(SqlDataReader reader)
    {
        var resource = new Resource
        {
            RessourceUID = SqlReaderHelper.GetValue<string>(dr, "ResourceUID"),
            RessourceName = SqlReaderHelper.GetValue<string>(dr, "ResourceName"),
            Loginname = SqlReaderHelper.GetValue<string>(dr, "UserClaimsAccount")
        }

        return resource;
    }
}

and I also modified the query itself:

using (var reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        var resource = Resource.From(reader);
        if (resource != null)
        {
            resource.Teams = GetResourceTeams(resource);
        }
        return resource;
    }
    return null;
}

As you are looking for only one resource the reader won't proceed if there is none so you don't have to check whether it has any rows. You can just return the result after the first one.


Comparing long lists of strings for the closest match

The painless solutiuon is to use the fastest levenstein distance algorithm :) For example extracted from GWT! I've created two 5 KB strings using your example, load them and produce 16000 calculations. Done in 3 seconds only. The source:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {

private static String readString(String filename) throws IOException {
    StringBuilder result = new StringBuilder();
    String temp;
    BufferedReader in = new BufferedReader(new FileReader(filename));
    while ((temp = in.readLine()) != null) result.append(temp);
    return result.toString();
}

public static void main(String[] args) throws IOException {

    String line1 = readString(args[0]);
    String line2 = readString(args[1]);
    GeneralEditDistance ed = GeneralEditDistances.getLevenshteinDistance(line1);

    long time = System.currentTimeMillis();
    int best = Integer.MAX_VALUE;
    for (int i = 0; i < 80*200; i++) {
        best = Math.min(best, ed.getDistance(line2, best));
    }
    System.out.println("Best distance = " + best + " Total time (ms): " + (System.currentTimeMillis() - time));
}}

abstract class CharIndex {

static class FullHash extends CharIndex {

    static class Char {
        char c;

        @Override
        public boolean equals(Object x) {
            return (x != null) && (((Char) x).c == this.c);
        }

        @Override
        public int hashCode() {
            return c;
        }

        @Override
        public String toString() {
            return "'" + c + "'";
        }
    }

    static final int NULL_ELEMENT = 0;
    protected int lastUsed = NULL_ELEMENT;
    final java.util.HashMap<Char, Integer> map;

    FullHash(CharSequence s) {
        int len = s.length();
        int power = Integer.highestOneBit(len);

        map = new java.util.HashMap<Char, Integer>(
                power << ((power == len) ? 1 : 2));

        Char test = new Char();                   /* (re)used for lookup */
        for (int i = 0; i < s.length(); i++) {
            test.c = s.charAt(i);
            if (map.get(test) == null) {
                map.put(test, new Integer(++lastUsed));
                test = new Char();
            }
        }
    }

    @Override
    public int lookup(char c) {
        final Char lookupTest = new Char();
        lookupTest.c = c;
        Integer result = map.get(lookupTest);
        return (result != null) ? result.intValue() : 0;
    }

    @Override
    public int[] map(CharSequence s, int[] mapped) {
        /* Create one mutable Char, and reuse it for all lookups */
        final Char lookupTest = new Char();

        int len = s.length();
        if (mapped.length < len) {
            mapped = new int[len];
        }

        for (int i = 0; i < len; i++) {
            lookupTest.c = s.charAt(i);
            Integer result = map.get(lookupTest);
            mapped[i] = (result != null) ? result.intValue() : NULL_ELEMENT;
        }
        return mapped;
    }

    @Override
    public int nullElement() {
        return NULL_ELEMENT;
    }

    @Override
    public int size() {
        return lastUsed + 1;
    }
}

static class Masked extends CharIndex {
    static final int SIZE = 0x100;
    static final int MASK = (SIZE - 1);
    static final int NULL_ELEMENT = SIZE;

    static Masked generate(CharSequence s) {
        char[] contains = new char[SIZE];
        contains[0] = (char) 1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int index = c & MASK;
            if (contains[index] != c) {
                if ((contains[index] & MASK) == index) {
                    return null;
                }
                contains[index] = c;
            }
        }
        return new Masked(contains);
    }

    final char[] contains;

    private Masked(char[] contains) {
        this.contains = contains;
    }

    @Override
    public int lookup(char c) {
        int index = c & MASK;
        return (c == contains[index]) ? index : NULL_ELEMENT;
    }

    @Override
    public int[] map(CharSequence s, int[] mapped) {
        int len = s.length();
        if (mapped.length < len) {
            mapped = new int[len];
        }
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            int index = c & MASK;
            mapped[i] = (c == contains[index]) ? index : NULL_ELEMENT;
        }
        return mapped;
    }

    @Override
    public int nullElement() {
        return NULL_ELEMENT;
    }

    @Override
    public int size() {
        return NULL_ELEMENT + 1;
    }
}

static class Straight extends CharIndex {
    static final int MAX = 0x80;
    static final int MASK = ~(MAX - 1);
    static final int NULL_ELEMENT = MAX;

    static Straight generate(CharSequence s) {
        for (int i = 0; i < s.length(); i++) {
            if ((s.charAt(i) & MASK) != 0) {
                return null;
            }
        }

        return new Straight();
    }

    private Straight() {
    }

    @Override
    public int lookup(char c) {
        return ((c & MASK) == 0) ? c : NULL_ELEMENT;
    }

    @Override
    public int[] map(CharSequence s, int[] mapped) {
        int len = s.length();
        if (mapped.length < len) {
            mapped = new int[len];
        }
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            mapped[i] = ((c & MASK) == 0) ? c : NULL_ELEMENT;
        }
        return mapped;
    }

    @Override
    public int nullElement() {
        return NULL_ELEMENT;
    }

    @Override
    public int size() {
        return NULL_ELEMENT + 1;
    }
}

public static CharIndex getInstance(CharSequence s) {
    CharIndex result;

    if ((result = Straight.generate(s)) != null) {
        return result;
    }

    if ((result = Masked.generate(s)) != null) {
        return result;
    }

    return new FullHash(s);
}

public abstract int lookup(char c);

public abstract int[] map(CharSequence s, int[] mapped);

public abstract int nullElement();

public abstract int size();
}

interface GeneralEditDistance {

GeneralEditDistance duplicate();

int getDistance(CharSequence target, int limit);

}

class GeneralEditDistances {

private static class Levenshtein implements GeneralEditDistance {
    private ModifiedBerghelRoachEditDistance berghel;
    private MyersBitParallelEditDistance myers;
    private final CharSequence pattern;
    private final int patternLength;

    private Levenshtein(CharSequence pattern) {
        this.pattern = pattern;
        this.patternLength = pattern.length();
    }

    public GeneralEditDistance duplicate() {
        Levenshtein dup = new Levenshtein(pattern);
        if (this.myers != null) {
            dup.myers = (MyersBitParallelEditDistance) this.myers.duplicate();
        }
        return dup;
    }

    public int getDistance(CharSequence target, int limit) {
        if (limit <= 1) {
            return limit == 0 ?
                    (pattern.equals(target) ? 0 : 1) :
                    atMostOneError(pattern, target);
        }
        if ((patternLength > 64)
                && (limit < (target.length() / 10))) {
            if (berghel == null) {
                berghel = ModifiedBerghelRoachEditDistance.getInstance(pattern);
            }
            return berghel.getDistance(target, limit);
        }

        if (myers == null) {
            myers = MyersBitParallelEditDistance.getInstance(pattern);
        }

        return myers.getDistance(target, limit);
    }
}

public static int atMostOneError(CharSequence s1, CharSequence s2) {
    int s1Length = s1.length();
    int s2Length = s2.length();
    int errors = 0;             /* running count of edits required */

    switch (s2Length - s1Length) {
        /*
        * Strings are the same length.  No single insert/delete is possible;
        * at most one substitution can be present.
        */
        case 0:
            for (int i = 0; i < s2Length; i++) {
                if ((s2.charAt(i) != s1.charAt(i)) && (errors++ != 0)) {
                    break;
                }
            }
            return errors;

        case 1: /* s2Length > s1Length */
            for (int i = 0; i < s1Length; i++) {
                if (s2.charAt(i) != s1.charAt(i)) {
                    for (; i < s1Length; i++) {
                        if (s2.charAt(i + 1) != s1.charAt(i)) {
                            return 2;
                        }
                    }
                    return 1;
                }
            }
            return 1;

        /* Same as above case, with strings reversed */
        case -1: /* s1Length > s2Length */
            for (int i = 0; i < s2Length; i++) {
                if (s2.charAt(i) != s1.charAt(i)) {
                    for (; i < s2Length; i++) {
                        if (s2.charAt(i) != s1.charAt(i + 1)) {
                            return 2;
                        }
                    }
                    return 1;
                }
            }
            return 1;

        /* Edit distance is at least difference in lengths; more than 1 here. */
        default:
            return 2;
    }
}

public static GeneralEditDistance
getLevenshteinDistance(CharSequence pattern) {
    return new Levenshtein(pattern);
}

private GeneralEditDistances() {
}
}

class ModifiedBerghelRoachEditDistance implements GeneralEditDistance {

private static final int[] EMPTY_INT_ARRAY = new int[0];

public static ModifiedBerghelRoachEditDistance
getInstance(CharSequence pattern) {
    return getInstance(pattern.toString());
}

public static ModifiedBerghelRoachEditDistance
getInstance(String pattern) {
    return new ModifiedBerghelRoachEditDistance(pattern.toCharArray());
}

private int[] currentLeft = EMPTY_INT_ARRAY;

private int[] currentRight = EMPTY_INT_ARRAY;

private int[] lastLeft = EMPTY_INT_ARRAY;

private int[] lastRight = EMPTY_INT_ARRAY;

private final char[] pattern;

private int[] priorLeft = EMPTY_INT_ARRAY;

private int[] priorRight = EMPTY_INT_ARRAY;

private ModifiedBerghelRoachEditDistance(char[] pattern) {
    this.pattern = pattern;
}

public ModifiedBerghelRoachEditDistance duplicate() {
    return new ModifiedBerghelRoachEditDistance(pattern);
}

public int getDistance(CharSequence targetSequence, int limit) {
    final int targetLength = targetSequence.length();

    final int main = pattern.length - targetLength;
    int distance = Math.abs(main);
    if (distance > limit) {
        /* More than we wanted.  Give up right away */
        return Integer.MAX_VALUE;
    }

    final char[] target = new char[targetLength];
    for (int i = 0; i < targetLength; i++) {
        target[i] = targetSequence.charAt(i);
    }
    if (main <= 0) {
        ensureCapacityRight(distance, false);
        for (int j = 0; j <= distance; j++) {
            lastRight[j] = distance - j - 1;  /* Make diagonal -k start in row k */
            priorRight[j] = -1;
        }
    } else {
        ensureCapacityLeft(distance, false);
        for (int j = 0; j <= distance; j++) {
            lastLeft[j] = -1;                 /* Make diagonal +k start in row 0 */
            priorLeft[j] = -1;
        }
    }

    boolean even = true;

    while (true) {

        int offDiagonal = (distance - main) / 2;
        ensureCapacityRight(offDiagonal, true);

        if (even) {
            lastRight[offDiagonal] = -1;
        }

        int immediateRight = -1;
        for (; offDiagonal > 0; offDiagonal--) {
            currentRight[offDiagonal] = immediateRight = computeRow(
                    (main + offDiagonal),
                    (distance - offDiagonal),
                    pattern,
                    target,
                    priorRight[offDiagonal - 1],
                    lastRight[offDiagonal],
                    immediateRight);
        }

        offDiagonal = (distance + main) / 2;
        ensureCapacityLeft(offDiagonal, true);

        if (even) {
            lastLeft[offDiagonal] = (distance - main) / 2 - 1;
        }

        int immediateLeft = even ? -1 : (distance - main) / 2;

        for (; offDiagonal > 0; offDiagonal--) {
            currentLeft[offDiagonal] = immediateLeft = computeRow(
                    (main - offDiagonal),
                    (distance - offDiagonal),
                    pattern, target,
                    immediateLeft,
                    lastLeft[offDiagonal],
                    priorLeft[offDiagonal - 1]);
        }

        int mainRow = computeRow(main, distance, pattern, target,
                immediateLeft, lastLeft[0], immediateRight);

        if ((mainRow == targetLength) || (++distance > limit) || (distance < 0)) {
            break;
        }

        /* The [0] element goes to both sides. */
        currentLeft[0] = currentRight[0] = mainRow;

        /* Rotate rows around for next round: current=>last=>prior (=>current) */
        int[] tmp = priorLeft;
        priorLeft = lastLeft;
        lastLeft = currentLeft;
        currentLeft = priorLeft;

        tmp = priorRight;
        priorRight = lastRight;
        lastRight = currentRight;
        currentRight = tmp;

        /* Update evenness, too */
        even = !even;
    }

    return distance;
}

private int computeRow(int k, int p, char[] a, char[] b,
                       int knownLeft, int knownAbove, int knownRight) {
    assert (Math.abs(k) <= p);
    assert (p >= 0);

    int t;
    if (p == 0) {
        t = 0;
    } else {
        t = Math.max(Math.max(knownAbove, knownRight) + 1, knownLeft);
    }

    int tmax = Math.min(b.length, (a.length - k));

    while ((t < tmax) && b[t] == a[t + k]) {
        t++;
    }

    return t;
}

private void ensureCapacityLeft(int index, boolean copy) {
    if (currentLeft.length <= index) {
        index++;
        priorLeft = resize(priorLeft, index, copy);
        lastLeft = resize(lastLeft, index, copy);
        currentLeft = resize(currentLeft, index, false);
    }
}

private void ensureCapacityRight(int index, boolean copy) {
    if (currentRight.length <= index) {
        index++;
        priorRight = resize(priorRight, index, copy);
        lastRight = resize(lastRight, index, copy);
        currentRight = resize(currentRight, index, false);
    }
}

private int[] resize(int[] array, int size, boolean copy) {
    int[] result = new int[size];
    if (copy) {
        System.arraycopy(array, 0, result, 0, array.length);
    }
    return result;
}
}

abstract class MyersBitParallelEditDistance
    implements GeneralEditDistance, Cloneable {

static class Empty extends MyersBitParallelEditDistance {
    Empty(CharSequence s) {
        super(s);
    }

    @Override
    public GeneralEditDistance duplicate() {
        return this;      /* thread-safe */
    }

    @Override
    public int getDistance(CharSequence s, int k) {
        return s.length();
    }
}

static class Multi extends MyersBitParallelEditDistance {
    int count;
    final int lastBitPosition;
    final int[][] positions;
    int[] verticalNegativesReusable;
    int[] verticalPositivesReusable;
    final int wordMask = (-1 >>> 1);
    final int wordSize = Integer.SIZE - 1;

    Multi(CharSequence s) {
        super(s);
        count = (m + wordSize - 1) / wordSize;
        positions = PatternBitmap.map(s, idx, new int[idx.size()][], wordSize);
        lastBitPosition = (1 << ((m - 1) % wordSize));
        perThreadInit();
    }

    @Override
    public int getDistance(CharSequence s, int k) {
        indices = idx.map(s, indices);

        int[] verticalPositives = verticalPositivesReusable;
        java.util.Arrays.fill(verticalPositives, wordMask);
        int[] verticalNegatives = verticalNegativesReusable;
        java.util.Arrays.fill(verticalNegatives, 0);

        int distance = m;
        int len = s.length();

        int maxMisses = k + len - m;
        if (maxMisses < 0) {
            maxMisses = Integer.MAX_VALUE;
        }

        outer:
        for (int j = 0; j < len; j++) {
            int[] position = positions[indices[j]];

            int sum = 0;
            int horizontalPositiveShift = 1;
            int horizontalNegativeShift = 0;

            for (int i = 0; i < count; i++) {
                int verticalNegative = verticalNegatives[i];
                int patternMatch = (position[i] | verticalNegative);
                int verticalPositive = verticalPositives[i];
                sum = (verticalPositive & patternMatch)
                        + (verticalPositive) + (sum >>> wordSize);
                int diagonalZero = ((sum & wordMask) ^ verticalPositive)
                        | patternMatch;
                int horizontalPositive = (verticalNegative
                        | ~(diagonalZero | verticalPositive));
                int horizontalNegative = diagonalZero & verticalPositive;

                if (i == (count - 1)) {            /* only last bit in last word */
                    if ((horizontalNegative & lastBitPosition) != 0) {
                        distance--;
                    } else if ((horizontalPositive & lastBitPosition) != 0) {
                        distance++;
                        if ((maxMisses -= 2) < 0) {
                            break outer;
                        }
                    } else if (--maxMisses < 0) {
                        break outer;
                    }
                }

                horizontalPositive = ((horizontalPositive << 1)
                        | horizontalPositiveShift);
                horizontalPositiveShift = (horizontalPositive >>> wordSize);

                horizontalNegative = ((horizontalNegative << 1)
                        | horizontalNegativeShift);
                horizontalNegativeShift = (horizontalNegative >>> wordSize);

                verticalPositives[i] = (horizontalNegative
                        | ~(diagonalZero | horizontalPositive))
                        & wordMask;
                verticalNegatives[i] = (diagonalZero & horizontalPositive) & wordMask;
            }
        }
        return distance;
    }

    @Override
    protected void perThreadInit() {
        super.perThreadInit();
        verticalPositivesReusable = new int[count];
        verticalNegativesReusable = new int[count];
    }
}

static class TYPEint/*WORD*/ extends MyersBitParallelEditDistance {
    final int/*WORD*/ lastBitPosition;
    final int/*WORD*/[] map;

    @SuppressWarnings("cast")
    TYPEint/*WORD*/(CharSequence s) {
        super(s);
        /* Precompute bitmaps for this pattern */
        map = PatternBitmap.map(s, idx, new int/*WORD*/[idx.size()]);
        /* Compute the bit that represents a change in the last row */
        lastBitPosition = (((int/*WORD*/) 1) << (m - 1));
    }

    @Override
    public int getDistance(CharSequence s, int k) {
        int len = s.length();

        /* Quick check based on length */
        if (((len - m) > k) || ((m - len) > k)) {
            return k + 1;
        }

        /* Map characters to their integer positions in the bitmap array */
        indices = idx.map(s, indices);

        /* Initially, vertical change is all positive (none negative) */
        int/*WORD*/ verticalPositive = -1;
        int/*WORD*/ verticalNegative = 0;
        int distance = m;

        /* We can only miss the "distance--" below this many times: */
        int maxMisses = k + len - m;
        if (maxMisses < 0) {
            maxMisses = Integer.MAX_VALUE;
        }

        for (int j = 0; j < len; j++) {
            /* Where is diagonal zero: matches, or prior VN; plus recursion */
            int/*WORD*/ diagonalZero = map[indices[j]] | verticalNegative;
            diagonalZero |= (((diagonalZero & verticalPositive) + verticalPositive)
                    ^ verticalPositive);

            /* Compute horizontal changes */
            int/*WORD*/ horizontalPositive = verticalNegative
                    | ~(diagonalZero | verticalPositive);
            int/*WORD*/ horizontalNegative = diagonalZero & verticalPositive;

            /* Update final distance based on horizontal changes */
            if ((horizontalNegative & lastBitPosition) != 0) {
                distance--;
            } else if ((horizontalPositive & lastBitPosition) != 0) {
                distance++;
                if ((maxMisses -= 2) < 0) {
                    break;
                }
            } else if (--maxMisses < 0) {
                break;
            }

            /* Shift Hs to next row, compute new Vs analagously to Hs above */
            horizontalPositive = (horizontalPositive << 1) | 1;
            verticalPositive = (horizontalNegative << 1)
                    | ~(diagonalZero | horizontalPositive);
            verticalNegative = diagonalZero & horizontalPositive;
        }
        return distance;
    }
}

static class TYPElong/*WORD*/ extends MyersBitParallelEditDistance {
    final long/*WORD*/ lastBitPosition;
    final long/*WORD*/[] map;

    TYPElong/*WORD*/(CharSequence s) {
        super(s);
        /* Precompute bitmaps for this pattern */
        map = PatternBitmap.map(s, idx, new long/*WORD*/[idx.size()]);
        /* Compute the bit that represents a change in the last row */
        lastBitPosition = (((long/*WORD*/) 1) << (m - 1));
    }

    @Override
    public int getDistance(CharSequence s, int k) {
        int len = s.length();

        /* Quick check based on length */
        if (((len - m) > k) || ((m - len) > k)) {
            return k + 1;
        }

        /* Map characters to their integer positions in the bitmap array */
        indices = idx.map(s, indices);

        /* Initially, vertical change is all positive (none negative) */
        long/*WORD*/ verticalPositive = -1;
        long/*WORD*/ verticalNegative = 0;
        int distance = m;

        /* We can only miss the "distance--" below this many times: */
        int maxMisses = k + len - m;
        if (maxMisses < 0) {
            maxMisses = Integer.MAX_VALUE;
        }

        for (int j = 0; j < len; j++) {
            /* Where is diagonal zero: matches, or prior VN; plus recursion */
            long/*WORD*/ diagonalZero = map[indices[j]] | verticalNegative;
            diagonalZero |= (((diagonalZero & verticalPositive) + verticalPositive)
                    ^ verticalPositive);

            /* Compute horizontal changes */
            long/*WORD*/ horizontalPositive = verticalNegative
                    | ~(diagonalZero | verticalPositive);
            long/*WORD*/ horizontalNegative = diagonalZero & verticalPositive;

            /* Update final distance based on horizontal changes */
            if ((horizontalNegative & lastBitPosition) != 0) {
                distance--;
            } else if ((horizontalPositive & lastBitPosition) != 0) {
                distance++;
                if ((maxMisses -= 2) < 0) {
                    break;
                }
            } else if (--maxMisses < 0) {
                break;
            }

            /* Shift Hs to next row, compute new Vs analagously to Hs above */
            horizontalPositive = (horizontalPositive << 1) | 1;
            verticalPositive = (horizontalNegative << 1)
                    | ~(diagonalZero | horizontalPositive);
            verticalNegative = diagonalZero & horizontalPositive;
        }
        return distance;
    }
}

public static MyersBitParallelEditDistance getInstance(CharSequence s) {
    int m = s.length();
    return (m <= Integer.SIZE) ?
            ((m == 0) ? new Empty(s) : new TYPEint(s)) :
            (s.length() <= Long.SIZE) ?
                    new TYPElong(s) :
                    new Multi(s);
}

final CharIndex idx;

int[] indices = new int[0];

final int m;

protected MyersBitParallelEditDistance(CharSequence s) {
    m = s.length();
    idx = CharIndex.getInstance(s);
}

public GeneralEditDistance duplicate() {
    try {
        return (MyersBitParallelEditDistance) clone();
    } catch (CloneNotSupportedException x) { /*IMPOSSIBLE */
        throw new IllegalStateException("Cloneable object would not clone");
    }
}

public abstract int getDistance(CharSequence s, int k);

@Override
protected Object clone() throws CloneNotSupportedException {
    Object obj = super.clone();

    /* Re-initialize any non-thread-safe parts */
    ((MyersBitParallelEditDistance) obj).perThreadInit();

    return obj;
}

protected void perThreadInit() {
    indices = new int[0];
}
}

class PatternBitmap {

public static int[] map(CharSequence s, CharIndex idx, int[] result) {
    int len = s.length();
    assert (len <= Integer.SIZE);
    for (int i = 0; i < len; i++) {
        result[idx.lookup(s.charAt(i))] |= (1 << i);
    }
    return result;
}

public static int[][] map(CharSequence s, CharIndex idx,
                          int[][] result, int width) {
    assert (width <= Integer.SIZE);
    int len = s.length();
    int rowSize = (len + width - 1) / width;

    /*
    * Use one zero-filled bitmap for alphabet characters not in the pattern
    */
    int[] nullElement = new int[rowSize];
    java.util.Arrays.fill(result, nullElement);

    int wordIndex = 0;          /* Which word we are on now */
    int bitWithinWord = 0;      /* Which bit within that word */

    for (int i = 0; i < s.length(); i++) {
        int[] r = result[idx.lookup(s.charAt(i))];
        if (r == nullElement) {

            /* Create a separate zero-filled bitmap for this alphabet character */
            r = result[idx.lookup(s.charAt(i))] = new int[rowSize];
        }
        r[wordIndex] |= (1 << bitWithinWord);

        /* Step to the next bit (and word if appropriate) */
        if (++bitWithinWord == width) {
            bitWithinWord = 0;
            wordIndex++;
        }
    }
    return result;
}

public static long[] map(CharSequence s, CharIndex idx, long[] result) {
    int len = s.length();
    assert (len <= Long.SIZE);
    for (int i = 0; i < len; i++) {
        result[idx.lookup(s.charAt(i))] |= (1L << i);
    }
    return result;
}

private PatternBitmap() { /* Prevent instantiation */ }
}


Regex for finding After Effects files in scene code format

root should be capitalized as it is a constant.
You can shorten the code by using sorted that returns a new list instead of working in place.
IGNORE in my opinion reduces readibility as it is less obvious than IGNORECASE.
Your regexes are pretty hard, I would extract them into constants and give them a name.
You make good use of list comprehensions, they shorten and simplify code, good job!
Performance may not be a primary concern here, but it is a good habit to use lazy generators: putting round parenthesis instead of square brackets outside the match comprehension will not build the list, saving memory and time. The same goes for scene_floders.


Combine lists from two lists of list into a single list of lists

I would write something like that:

def combine(first, second):
    ret_list = []
    for i, j in zip(first, second):
        add = []
        if i is not None:
            add.extend(i)
        if j is not None:
            add.extend(j)
        ret_list.append(add)
    return ret_list

I don't know if it is the most python-ish way but it is ok I think...

I mean you can also write something like this:

def combine(first, second):
    return [(i.extend(j) if not (i is None or j is None) else i if j is None else j) for i, j in zip(first, second)]

But you cannot read and debug that. So I would strongly recommend against it.

Btw: Did not test the last one so I hope I did not forget a closing bracket ;)

Edit:

In order to keep all elements you have to add something to the end. The zip() function stops iterating after the shortest element reached its end.
This is why the following method is needed instead of zip:

def combine(first, second):
    ret_list = []
    for i, j in itertools.zip_longest(first, second):
        add = []
        if i is not None:
            add.extend(i)
        if j is not None:
            add.extend(j)
        ret_list.append(add)
    return ret_list

Note: Itertools simply must be imported first. (For Python2 it is itertools.izip_longest()...)


As already mentioned by Anders, the second approach is better, however there are several problems when implementing async Tasks that run within an IIS worker process:

1) unhandled exceptions in the async threads/tasks kill the entire process. This should not be a problem in your code, since you catch all exceptions and normally, NLog handle does not have unhandled exception.

2) worker process may suddenly stop for various reasons such as web.config, binaries, idle recycling and the task might be stopped in the middle of its work. This should not happen in your case, since the operation seems pretty short and ASP.NET will try to delay the shutdown of the process to allow background workers to finish their jobs.

I also remark the possible optimization brought by using an Async function along with await on the same instruction.

A small improvement is to use UnitOfWork pattern for your database context, but the benefit comes when more complex things happen in your worker:

/// <summary>
/// unit of work store
/// </summary>
public static class UnitOfWorkStore
{
    public static object GetData(string key)
    {
        if (HttpContext.Current != null)
            return HttpContext.Current.Items[key];
        return CallContext.GetData(key);
    }

    public static void SetData(string key, object data)
    {
        if (HttpContext.Current != null)
            HttpContext.Current.Items[key] = data;
        else
            CallContext.SetData(key, data);
    }
}

public partial class EFDbContext
{
    #region Members
    private static readonly object objSync = new object();
    private static readonly string DATACONTEXT_KEY = "EFDbContext_UserInstance";
    #endregion

    /// <summary>
    /// Uses a UnitOfWorkStore to return the same instance of Context, that is unique
    /// per user, per postback (or CallContext, if not in an HttpContext environment, such as unit tests or console apps)
    /// </summary>
    public static EFDbContext Instance
    {
        get
        {
            // Dirty (non thread-safe) check
            if (UnitOfWorkStore.GetData(DATACONTEXT_KEY) == null)
            {
                lock (objSync)
                {
                    // Thread-safe check
                    if (UnitOfWorkStore.GetData(DATACONTEXT_KEY) == null)
                    {
                        var context = new EFDbContext();
                        UnitOfWorkStore.SetData(DATACONTEXT_KEY, context);
                    }
                }
            }
            return (EFDbContext)UnitOfWorkStore.GetData(DATACONTEXT_KEY);
        }
    }
}

So, that generating a new context can be done using EFDbContext.Instance and unit of work pattern will take care to return the same instance if called in the same "context". Also, it looks like database context disposal is not really necessary.

[later edit]

Just remembered a couple of things:

3) AsNoTracking() is a good option when fetching read-only data. It is faster and allocates less memory, so its usage is welcomed (however, I rarely see it used).

4) Idle timeout - by default, IIS will stop the application pool if it has not activity. This means that no processing will be made during some periods (e.g. during week-ends)


Pig Latin game resolved with a regex in Java

Your code looks fine. I would write this with a different approach. It is up to you, which is better.

public static String pigLatin(String word) {
    Pattern firstVowelPattern = Pattern.compile("^([aeiouAEIOU])");
    Matcher matcher = firstVowelPattern.matcher(word);
    if (matcher.find()) return word + "way";
    return word.replaceAll("^([^aeiouAEIOU]*)(.+)", "$2$1ay");
}

I do not use any arrays and splitting a string, but I solve it with more regex expressions.  The key element of this solution is how replaceAll works. In the first parameter, I pass two regex expression and in second parameter I switch results of them using $2$1.

As you can see I did not use if-else statement, only if. In your solution else also is redundant.


Euler 35 - python solution taking too long

Your p is a list.  Then you do p.count(x) to see if x is a prime.  This does a linear search of the list, and in fact, has to examine every element of p, not just those up to the occurrence of x.  Instead, change p to a set.  It will run much faster.  Also, once you see that a rotation is not prime, you can stop checking all the rotations.


Graceful JavaScript fallback for external web service failure

I like the idea, from a once over:

Since you use an IIFE I would declare sencha_path_identifier and sencha_path_regex outside of the constructor, then you can access them without specifying this.
I would do either function SenchaSRCFallback() { or var SenchaSRCFallback = function SenchaSRCFallback() {, anonymous functions are a pain to troubleshoot
Why do you require the caller to call init()? In my mind this call should be done within the constructor.

This is something I might borrow at some point.


Suggestion 1

This block of code does not seem clean:

    // Check whether the parameter is already full
    if (data != 0){
        // Reset the output
        data->clear();
        data = 0;
    }

If data used to point to non-NULL, then you are just making it NULL. You should delete data before pointing it to NULL:

    if (data != 0){
        // Reset the output
        data->clear();
        delete data;
        data = 0;
    }

Suggestion 2

Still better, if you have the option, change the interface to

void readNParseData(const char* filePath, vector<double>& data);

Suggestion 3

There is nothing in your code to indicate to the calling function that you were able or unable to read the data from the file. There is no else to go with

if (ifs) {

One way of indicating whether the function was successful in reading the data is to change the return type of the function to bool. Then, you can add

return true;

at the end of the if block and then add an else block:

else {
   return false;
}

Suggestion 4

To remove the redundant memory allocation and deallocation to fileBuffer, simply use std::vector::data:

data.resize(sizeOfBuffer);
ifs.read(reinterpret_cast<char*>(data.data()), fileSize);

Suggestion 5

Add a check to make sure that ifs.read was successful:

ifs.read(reinterpret_cast<char*>(data.data()), fileSize);
if ( !ifs )
{
   return false;
}


Monkey-patching Jasmine's it() function to log errors

Just factor it out into a closure

function patchJasmineForAsyncError(method: string) {
    let oldFn = window[method];
    function create_logger(fn: Function) {
        return (done) => {
            let p = fn();
            if (p instanceof Promise) {
                p.then(done).catch(e => {
                    console.error(e);
                    done.fail(e);
                });
            }
        }
    }

    if (method === 'it' || method === 'fit') {
        window[method] = function(desc: string, fn: Function) {
            oldFn(desc, create_logger(fn));
        }
    } else {
        window[method] = function (axn: Function) {
            oldFn(create_logger(axn));
        }
    }
}

We can clean this up a bit more by getting rid of some magic. I also got rid of the () => done() because that's the same as done.

function patchJasmineForAsyncError(method: string) {
    let oldFn = window[method];
    function create_logger(fn: Function) {
        return (done) => {
            let p = fn();
            if (p instanceof Promise) {
                p.then(done).catch(e => {
                    console.error(e);
                    done.fail(e);
                });
            }
        }
    }

    let allowed_methods = ['it', 'fit'];
    if (allowed_methods.includes(method)) {
        window[method] = function(desc: string, fn: Function) {
            oldFn(desc, create_logger(fn));
        }
    } else {
        window[method] = function (axn: Function) {
            oldFn(create_logger(axn));
        }
    }
}

We can also reduce some of the duplication in assigning to window[method] if we're okay with adding a slight slow-down to the function, which should be fine.

function patchJasmineForAsyncError(method: string) {
    let oldFn = window[method];
    function create_logger(fn: Function) {
        return (done) => {
            let p = fn();
            if (p instanceof Promise) {
                p.then(done)
                 .catch(e => {
                    console.error(e);
                    done.fail(e);
                });
            }
        }
    }
    let allowed_methods = ['it', 'fit'];
    window[method] = function() {
        if (allowed_methods.includes(method)) {
            oldFn(arguments[0], create_logger(arguments[1]));
        } else {
            oldFn(create_logger(arguments[0]));
        }
    }
}


Read through a log file to find "Fail" lines

The standard indentation for Python, specified by PEP 8, is four spaces.  This is a pretty strong convention for Python, since indentation matters a lot.

You almost always want to call open() in the context of a with-block, so that the file will get closed automatically when exiting the block.

This task does not require you to read the entire file at once.  I recommend working line by line so that you can handle large files better.  (You also don't need to make a copy of myResList at the end using myResList[:].)

You don't need a regular expression to search for a fixed literal string.  A substring search will do just fine.  This also means that your function is misnamed.  In general, you should name functions after the task that they accomplish, rather than how they accomplish the task.

I'd generalize your function to search for any text.

def search(filename, text):
    with open(filename) as f:
        for line in f:
            if text in line:
                print(line)

if __name__ == '__main__':
    search('/home/nick/python/chap8ReadingWritingFiles/15Jan2016_000000.txt', 'Fail')

If you're interested more in passing back the results, a better way would be to yield the results back to the caller.

def search(filename, text):
    with open(filename) as f:
        for line in f:
            if text in line:
                yield line

if __name__ == '__main__':
    for result in search('/home/nick/python/chap8ReadingWritingFiles/15Jan2016_000000.txt', 'Fail'):
        print(result)

The if __name__ == '__main__': boilerplate is optional, but considered standard practice.


Python is not Java (or C++, or ...). There is no need to have a getter and setter for every attribute.

Instead of calling card.modify_weight(new_suit_weight=3), you can just do card.suit_weight = 3, so that method is not needed at all.
Instead of calling card.get_suit(), just use card.suit, so all those get_* methods are superfluous.

The rest looks fine to me, except for the closing part of the docstring of Card, those """ should be indented the same distance the opening """ are.


Save parameters in a "key: value" format

There are many things deeply wrong with this method:

It does too much. It seems completely unaware of the single responsibility principle. It's extremely important that every method has one clear main responsibility. This method has so many it's not even clear which one is the most important:

Parse a config file?
Update a config file?
Update an internal hashmap?

You really need to split this up.
The entire method body is wrapped in one giant try-catch block. This is a bad practice. There are many points inside where an exception can be thrown, and by wrapping the entire method like this, you cannot distinguish the failure point and respond gracefully. And since you catch all exceptions and just print on the console (another bad practice by the way), the method will appear to have succeeded, even if it actually failed. As such, the method cannot be trusted.
The way you use MyFormatException is absolutely awful. You throw this poorly named custom exception just to catch it yourself. A simple if statement is the right tool for this, better in every way.
Methods shouldn't be too long in general. Even when they really have a single responsibility. Long methods are hard to understand, test and debug.

A general purpose utility like the one you described and hinted by this implementation can be certainly accomplished in a simpler way.
After you split up this method to smaller functions where each has a clear single responsibility,
the resulting code will be longer than this method.
But it will be composed of smaller component that are easier to understand and test.

There are many other smaller practical problems too:

Declare variables with interface type instead of implementation when possible. For example List instead of ArrayList, like this: List<String> file = new ArrayList<>();
file is a very poor name for a list. It's a list, so name it that way. When I saw file at many places in the code my instinct was that it's probably a File instance, but it's far from it. Very confusing.
The usage this.COMMENT_PREFIX suggests that COMMENT_PREFIX is an instance variables, despite the all capital name which is a convention reserved for static final constants.

I suggest to completely rework this class, splitting up this one big method to smaller methods where each has precisely one responsibility, and post it for another review.


Simple bank-account application using composition

Don’t write using namespace std;.

You can, however, in a CPP file (not H file) or inside a function put individual using std::string; etc.  (See SF.7.)

Balance(double amount, std::string currency)
    : d_amount(amount), d_currency(currency) {}

std::string d_currency;

You are taking the currency parameter by value, and then copying it to the member, then you don’t need the first copy anymore.  I think you were trying to use the “sink” parameter idiom?

 : d_amount{amount}, d_currency{std::move(currency)} {}

You forgot the move!  Also, you were using old syntax for the initializers: use uniform initialization style now (since C++11).  (Later) I see you did move in another class, so that was your intent here I think.

I see you are using initializers, which is good.  Likewise, using exactly one of virtual/override/final on a virtual function, and using unique_ptr.

void print_balance() { std::cout << d_balance << ":" << *d_interest_rate; }

That’s exactly the same for CurrentAccount and SavingsAccount.  I thought at first you were overriding a virtual function with no need, but looking closer I see that these classes are not related, and yet they are identical!  I don’t want to do a diff to find out if there is a few chars different somewhere, so that is a concern for understandibility.

Likewise, AccountFactory is duplicating the same code for both creation functions.  What is the deal here?  If you need “strong types”, just add a template parameter.  Don’t duplicate the entire code for the class manually!

Why is InterestRate a polymorphic interface?  Is what’s shown here just as example, or is there really nothing more to it than different values of a field?  Because in that case, you should just use a value.  This is especially odd since you always use the same Interest Rate class with a corresponding Account class — there is no need to make it polymorphic at all, even if they were really different.


DRYing two very similar SQL conditional inserts

You'll want to create a stored procedure that takes your setting ID

    CREATE OR REPLACE FUNCTION InsertUserProfile(id INTEGER)
RETURNS void AS $$
 BEGIN
   INSERT  INTO user_profile
     ( user_id ,
       setting_id ,
       value
     )
     SELECT  id ,
       id ,
       true
     FROM    users
     WHERE   NOT EXISTS ( SELECT user_id ,
            setting_id
           FROM   user_profile
           WHERE  id = id
            AND setting_id = @ID );
 END;
 $$ LANGUAGE plpgsql;

You'll then want to call it like this:

SELECT usp_InsertUserProfile(16)


Recursive Django filter to output a list from user hierarchy

First of all, you can move the first
 out of the first if condition. That allows you to totally get rid of the last else:

html = "
" + user.name
if len(user.subusers.all()) > 0:
    # ...
elif len(user.comment_set.all()) > 0:
    html += "

Comments
"
    # ...
    # don't add the last
 here
html += "
" # add it there instead
return html

Then, _output_comments should handle the whole comment stuff, including the heading:

def _output_comments(comment_list):
    output = "
Comments
"
    for comment in comment_list:
        output += "
" + comment.name + "
"
    output += "

"
    return output

I think that the way you add

 and

 tags does not reflect the structure of the page. You should improve this:

def _output_comments(comment_list):
    output = ("
" +
              "Comments" +
              "
")

    for comment in comment_list:
        output += "
" + comment.name + "
"

    output += ("
" +
               "
" +
               "
")
    return output

Overall, you should try to write Python code whose structures more or less reflects the structure of the HTML code you are writing. That will avoid tricky mistakes and tag mismatches. When I read your code as is, I have trouble knowing whether there are tags mismatches or not.


Find numbers between 1 and 10000 whose sum of digits are prime

The sum of the digits is such a small number (9+9+9+9=36 the maximum in your case) that you can even hard-code the values which are prime or not:

//number:         1  2  3  4  5  6  7
char isPrime[] = {0, 1, 1, 0, 1, 0, 1, ...}

But lets assume you don't go that far. The next best thing would be to generate such an array at run-time before your main loop (also based on the fact that the largest number you need to check if it's a prime is very small). A popular method for doing this is the Sieve of Eratosthenes.

Thus, you can now look up if the sum of the various digits is a prime or not in constant time:

if (isPrime[sum_of_digits(i)])
{
    //...
}

As to writing the results to a file, I would keep the file open for the duration of the loop. This improves efficiency by sending bigger chunks of data to the disk thanks to buffering.


To replace the elements in-place without building a new list,
you would need to reassign the elements at each index, that is,
essentially zorglubs[i] = zorglubs[i].transform() for each index i in the list.

A perhaps elegant way to do this is using the eachWithIndex function,
which gives you access to each element and its index:

zorglubs.eachWithIndex { it, index -> zorglubs[index] = it.transform() }


A recursive solution, originally seen here, but modified to fit your requirements (and look a little more JavaScript-y):

function combinations(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest)
            return;
        if (!rest) {
            a.push(active);
        } else {
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
        return a;
    }
    return fn("", str, []);
}

Test:

combinations("abcd")

Output:

["abcd", "abc", "abd", "ab", "acd", "ac", "ad", "a", "bcd", "bc", "bd", "b", "cd", "c", "d"]

Regarding the name: Don't name it permutations; a permutation is an arrangement of all the original elements (of which there should be n! total). In other words, it already has a precise meaning; don't unnecessarily overload it. Why not simply name it combinations?


If you're trying to speed up the code, I would do a couple of things.  You have some redundant processing, such as this:

cumulative_weight = zeros(1, num_weight + 1);
for j=1:num_weight
   cumulative_weight(j+1) = sum(weight(1:j));
end

which is performed 1000 times inside weighted_dice, but you really only need to do it once.  I would also get rid of the face labels altogether, because you don't care what the 6 faces are called, you just care about the distribution of results.  Finally, you can use the MATLAB builtin histc to generate the results in a vectorized fashion.

function face_index = new_weighted_dice(cumulative_weight)
    % cumulative_weight = cumulative distribution function to draw against
    % output: face_index is the discrete face after tossing a virtual dice with given
    % faces and weight.

% pick a random value unif. distrib. betw. 0 and the sum of the weights.
rand_w = unifrnd(0, cumulative_weight(end));
% check in which interval of the cumulative_weight is this element
for j=1:num_weight
   if rand_w >= cumulative_weight(j) && rand_w < cumulative_weight(j+1)
       break
   end
end

% assign the interval found to the value of the face
face_index = j;
end

%%%--------------main script

cumulative_weight = zeros(1, num_weight + 1);
for j=1:num_weight
   cumulative_weight(j+1) = sum(weight(1:j));
end
val = zeros(1,1000);
for i=1:1000
    val(i) = new_weighted_dice(cumulative_weight)
end

beans = histc(val, cumulative_weight);

Short, clean, fast.


First of all the name, Compare doesn't explain what this method does (and I had to read all the code to have an idea). Don't be afraid of longer names like GetMatchedPropertiesWithDifferentValues() (or something like that...).

Maybe you have a reason for that, in code you're not showing, but there is no requirement for T1 to implement IComparer (I'd guess IComparable but...IComparer?)

Names reloaded. Usually local variables (and parameters) are camelCase.

Both Object1 and Object2 can be null, check for both. You should never ever throw NullReferenceException, if a function argument is null and it should not then you have to throw ArgumentNullException.

This code:

Type TypeOfObject1 = typeof(T1);
PropertyInfo[] Object1Properties = TypeOfObject1.GetProperties(BindingFlags.Public | BindingFlags.Instance);

Can be simplified to:

var object1Properties = typeof(T1).GetProperties();

However if caller specifies the generic types like this (just an example...):

Compare<Base, Base>(new Derived(), new Derived());

You may get the wrong result (what do you expect here? To get properties of Base or of Derived?) Just be aware of this (and document it).

You call Count() on PropertyInfo[]. LINQ implementation is smart enough but it really has no sense to avoid using Length property. Again do not throw NullReferenceException. Is there any null object? No, just an object without public properties then you can throw ArgumentException (possibly specialized for the two parameters).

You may want to filter properties to feed Join() (what you're doing later in Where() clause) before the Join(). Also, move it to a separate GetEligiblePropertiesForComparison() method.

Only when T1 and T2 coincide (maybe a separate overload?): if you just get the intersection of the two lists you can skip creating the temporary objects.

Is there a reason you do not compare reference types? Checking TypeCode works pretty well but moving this check to a separate method is even better. Also consider x.PropertyType.IsPrimitiveType || x.PropertyType == typeof(string) (if it's what you meant, comparison of DBNull can be tricky).

You might want to move comparison to a separate method where you check for IEquatable<T> or IComparable<T> or IComparable implementation (defaulting to EqualityComparer<T> if types coincide).

Name selection can be simplified:

x.Object1Property.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName
    ?? x.Object1Property.Name;

Why don't you move it into a separate method string GetPropertyDisplayName(PropertyInfo)?

Here you do not need AsEnumerable().


RegEx

In character class, 0123456789 can be written as range 0-9. Although, this has no effect on working of RegEx, it saves some keystrokes and looks consistent with alphabets range a-z.

toLowerCase after replace

First remove the special characters and then convert the string to lower case. This, in my opinion will run fast than other way round as the number of characters to work on are reduced.(Not Tested)

When doing this, don't forget to add i flag on the RegEx.

str.replace(/[^a-z0-9]+/gi, "").toLowerCase();

return boolean;

if (str == reversedStr) {
    return true
}
return false

can be written as return str == reversedStr. It is also recommended to use strict equality operator.

return str === reversedStr;

See Which equals operator (== vs ===) should be used in JavaScript comparisons?

Caching DOM element reference

In the click handler of button, #notification is referenced four times. All times, it is read again from DOM. This can be slower. The element can be cached and used whenever required.

var notification = document.getElementById('notification');
...
...
notification.innerHTML = 'Hello World!';

Complete Code

Updated after suggestions from Ismael Miguel

// After DOM is completely loaded
document.addEventListener("DOMContentLoaded", function() {
    "use strict";

    // Cache
    var palindromeInput = document.getElementById("inputPalindrome");
    var notification = document.getElementById("notification");

    function isPalindrome(str) {
        str = str.replace(/[^a-z0-9]+/gi, "").toLowerCase();
        return str.split("").reverse().join("") === str;
    }

    document.getElementById("checkPalindrome")
        .addEventListener("click", function() {

            if (isPalindrome(palindromeInput.value)) {
                notification.innerHTML = "Yay! You've got yourself a palindrome";
                notification.className = "alert alert-success";
            } else {
                notification.innerHTML = "Nay! Ain't no palindrome";
                notification.className = "alert alert-danger";
            }
        });
});


When you catch yourself using nested ifs, that's usually a sign you'd be better served by the cond form. (which is actually way more powerful than nested if due to a few quirks)
Here's how I'd clean that up
(define (filter-lst fn lst)
  (cond ((null? lst) '())
        ((fn (car lst))
         (cons (car lst)
               (filter-lst fn (cdr lst))))
        (else (filter-lst fn (cdr lst)))))

The above isn't entirely idiomatic (which would be to implement it as a one-liner fold with a lambda.) but does show off a few style notes. Of your choices I'd say #1 is closest to the preferred style.
First is where you may be tempted to tab, a double space will do as I do on the second line, its usually appropriate to distinct parts separate certain special forms particularly (define, let, cond). You really want to avoid creeping to the right any faster than necessarily.
(define (merge l1 l2)
  (if (null? l1) l2
      (if (null? l2) l1 (cons (car l1) (cons (car l2) (merge (cdr l1) (cdr l2)))))))

Second is that if you split a function, there should be one argument per line, aligned to the start of the first argument
(define (merge l1 l2)
  (if (null? l1)
      l2
      (if (null? l2)
          l1
          (cons (car l1)
                (cons (car l2)
                      (merge (cdr l1) (cdr l2)))))))

And you see why cond is preffered again
(define (merge l1 l2)
  (cond ((null? l1) l2)
        ((null? l2) l1)
        (else (cons (car l1)
                    (cons (car l2)
                          (merge (cdr l1) (cdr l2))))))

And if a spot seems unwieldy there are often algorithmic simplifications that are worth considering
(define (merge l1 l2)
  (if (null? L1)
      l2
      (cons (car l1)
            (merge l2 l1))))


The complexity of your algorithm is \$O(n^2)\$, since IndexOf has complexity \$O(n)\$. You can get a \$O(n\log n)\$ by sorting the two strings and comparing them.


You've got a using namespace std; in your code. Don't do that. (No, really).

gets is dangerous; don't use it. Streams are so much more convenient anyway! For instance, you could write:

std::string sourcefile, targetfile, endung;
std::cout << "Welcome! You are using UNIVERSAL-DATEI-DUPLIKATOR v1.0\n"
          << "Filename? (Example: test.txt)\n";
std::cin >> sourcefile;
std::cout << "New Filename without ending? (Example: filename)\n";
std::cin >> targetfile;
std::cout << "Ending? (Example: .txt)\n";
std::cin >> endung;

int anzahl;
std::cout << "How many times do you want to create the file?\n";
std::cin >> anzahl;

Opening the input file only once and resetting the stream to the beginning for each copy may allow the stream to make better use of buffering, reducing the number of seeks required.

Also, streams can be copied directly to streambufs using operator>>.

std::ifstream Quelldatei(sourcefile, std::ios::binary);
for (int i = 0; i < anzahl; ++i) {
    Quelldatei.seekg(0);
    std::ostringstream output_filename(targetfile);
    output_filename << i << endung;
    std::ofstream Zieldatei(output_filename, std::ios::binary);
    Quelldatei >> Zieldatei.rdbuf();
    Zieldatei.close();
}
std::cout << "SUCCESS!" << std::endl;
system("pause");


(kind of nitpicking here, it looks quite solid to me)

Code:

    /* Discard up until the last `0xFF`, then that is the marker type. */
    do { if(fread(f, 1, 1, fp) != 1) return 0; } while(f[0] != 0xFF);
    do { if(fread(f, 1, 1, fp) != 1) return 0; } while(f[0] == 0xFF);

While we might have extra 0xff fill to read, I'm not sure we should be reading and discarding non-0xff bytes. If the data in the file doesn't follow the expected format our assumptions about the marker / chunk structure might be wrong too, which could lead to invalid results.

Outputting the wrong size could cause more problems than returning an error, so I'd be inclined to pick the latter instead.

        if((skip = (f[0] << 8) | f[1]) != 8u + 3 * f[7])
            return errno = EDOM, 0;

No need to set skip here, since we return in both branches.

We're checking the SOF chunk length matches with the number of image components? It might be nice to have a comment or something to mention this.

Using errno seems unnecessary if we return success / failure in the return value (and the only error code used  EDOM).

Style:

Some of the compound statements seem a bit forced. e.g.

e.g.:

if(argc != 2 || !(fp = fopen(argv[1], "rb"))
    || !jpeg_dim(fp, &width, &height)) goto catch;

If we split this up, the flow becomes much simpler, we can introduce local variables later, and we don't need multiple branches in the error handling:

int main(int argc, char **argv) {

    if (argc != 2) {
        fprintf(stderr, "Use with jpeg filename to see the size.\n");
        return EXIT_FAILURE;
    }

    FILE* fp = fopen(argv[1], "rb"); // note: we only need this if argc was correct
    if (!fp) {
        perror("jpeg size"); // note: fopen() may not set errno on non-POSIX platforms
        return EXIT_FAILURE;
    }

    unsigned width, height; // note: we only need these if fopen worked
    if (!jpeg_dim(fp, &width, &height))
    {
        perror("jpeg size"); // note: errno isn't very helpful here... we could return an error code instead
        return EXIT_FAILURE;
    }

    printf("Jpeg width: %u, height: %u.\n", width, height);

    fclose(fp);

    return EXIT_SUCCESS;
}

There are quite a few repeated statements in jpeg_dim (fread and stuff like ((f[5] << 8) | f[6]). These are quite concise, but should probably still be factored into separate functions.

I'd suggest something like a jpeg_read_u8, jpeg_read_u16 and jpeg_skip:

static int jpeg_read_u8(FILE *const fp, unsigned char *const u8) {
    assert(u8);

    unsigned char b;
    if (fread(&b, 1, 1, fp) != 1)
        return 0;

    *u8 = b;
    return 1;
}

static int jpeg_read_u16(FILE *const fp, unsigned short *const u16) {
    assert(u16);

    unsigned char b[2];
    if (fread(&b, 1, 2, fp) != 2)
        return 0;

    *u16 = (b[0] << 8) | b[1];
    return 1;
}

static int jpeg_skip(FILE *const fp, unsigned bytes) {
    return fseek(fp, bytes, SEEK_CUR) == 0;
}

static int jpeg_dim(FILE *const fp, unsigned *const width, unsigned *const height) {
    assert(fp);
    assert(width && height);

    /* The start of the file has to be an `SOI`. */
    unsigned char soi0; if (!jpeg_read_u8(fp, &soi0) || soi0 != 0xff) return 0;
    unsigned char soi1; if (!jpeg_read_u8(fp, &soi1) || soi1 != 0xd8) return 0;

    for (; ; ) {
        /* Read first byte of next marker */
        unsigned char m0; if (!jpeg_read_u8(fp, &m0) || m0 != 0xff) return 0;
        /* Discard fill characters */
        unsigned char m1; do { if (!jpeg_read_u8(fp, &m1)) return 0; } while (m1 == 0xff);

        switch (m1) {
        case 0xC0: case 0xC1: case 0xC2: case 0xC3: case 0xC5: /* _sic_ */
        case 0xC6: case 0xC7: case 0xC9: /* _sic_ */ case 0xCA: case 0xCB:
        case 0xCD: /* _sic_ */ case 0xCE: case 0xCF: {
            /* `SOF` markers. */
            unsigned short Lf; if (!jpeg_read_u16(fp, &Lf)) return 0;
            if (!jpeg_skip(fp, 1)) return 0; /* skip Precision */
            unsigned short Y;  if (!jpeg_read_u16(fp, &Y)) return 0;
            unsigned short X;  if (!jpeg_read_u16(fp, &X)) return 0;
            unsigned char Nf;  if (!jpeg_read_u8(fp, &Nf)) return 0;
            /* Check that the chunk length (Lf) matches the number of image components (Nf) */
            if (Lf != 8u + 3 * Nf) return 0;
            *width = X; *height = Y;
            return 1;
        }
        case 0xD8: case 0xD9:
            /* Image data `SOS, EOI` without image size. */
            return 0;
        default: {
            /* Skip the rest by reading it's size. */
            unsigned short Lf;
            if (!jpeg_read_u16(fp, &Lf) || Lf < 2) return 0;
            if (!jpeg_skip(fp, Lf - 2)) return 0;
        }
        }
    }
}


SYNTAX QUERY - HTML and CSS responsive navigation bar using FlexBox

Here are a few thoughts:

The universal selector to reset the margin and padding is slow and unnecessary in the case since none of the elements you're using have default margin or padding.
The use of hover by itself is not mobile friendly, and if the user expects to click Home to go to the homepage, a more robust design would be better. For example:

  It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard
  For situations when the parent menu item needs to carry out a function, such as linking to a web page, a separate button can be added to the parent item, to open and close the submenu. This button can also act as a visual indicator for the presence of a submenu.

For accessibility, add aria-role=menubar to the ul and aria-role=menuitem to each anchor tag.

References

Fly-out Menus • Menus • WAI Web Accessibility Tutorials
Navigation Menubar Example | WAI-ARIA Authoring Practices 1.1
Handling common accessibility problems - Learn web development | MDN


Decompress files files in a directory recursively

The docstring is empty. What is this function supposed to do? What does it return?
A bare except: is a bad idea, because it catches all exceptions, including KeyboardInterrupt and SystemExit. If you have some particular exception that you want to catch, then name it. But do you really need to catch any exceptions here? By catching exceptions you conceal information about what happened — instead of an error message and a traceback, all you get is the number 1, which tells you nothing.
The result of the recursive call to decompress_all is discarded and so is lost. If there were an exception inside the recursive call you'd never find out about it.
In POSIX, it's conventional for functions to return 0 for success and non-zero for failure. But in Python, it's conventional for functions either to return True for success and False for failure, or to return nothing for success, and raise an exception for failure.
The function calls itself with the same arguments. Why does it do this? What prevents this from recursing forever? I guess the idea here is that multiple layers of decompression might need to be undone, for example if one .zip file contains another .zip file. But I think this is not at all obvious and deserves a comment.
Instead of recursing, use a loop.

Revised code:

def decompress_all(directory_path, remove_after):
    """Repeatedly decompress all files under directory_path until no more
    files can be decompressed. The argument remove_after is passed to
    decompress.

    """
    # Decompression may extract more compressed files, so loop
    # until no more files need to be decompressed.
    while sum(decompress(filename, remove_after) == 0
              for filename in files_within(directory_path)):
        pass


The code does not implement the permuted index. Instead of

      The quick     brown fox
The quick brown     fox
            The     quick brown fox
                    The quick brown fox

it produces

                   The quick brown fox
      The quick    brown fox
The quick brown    fox
            The    quick brown fox

Notice that the order is wrong. The permuted index shall be sorted by the second column.
using namespace std; is considered bad practice.
Never #include a .cpp file. See for example this discussion for details.
Try not use so many strings. It hurts both memory usage and performance. In fact there is no need to break the initial string into words and reconstruct left and right strings. A vector of whitespace locations in the original string suffices.


You absolutely can use a Dictionary solution.  Here is what it would look like.

In some initialization code, maybe the form's constructor, write the following code:

// global mapping
private Dictionary<TextBox, TextBox> nextTextboxMap = new Dictionary<TextBox, TextBox>();

private void InitNextTextBoxMap()
{
    this.nextTextboxMap[keyText1] = keyText2;
    this.nextTextboxMap[keyText2] = keyText3;
    this.nextTextboxMap[keyText3] = keyText4;
    // add the other mappings here
    // where key = current textbox, and value = next textbox.
}

And then, your SelectNextTextBox() method can be simplified to this:

private void SelectNextTextBox()
{
    TextBox newTextBox = null;
    if (this.nextTextboxMap.TryGetValue(this._currentTextBox, out newTextBox))
    {
        newTextBox.SelectAll();
        newTextBox.Focus();

        // Maybe you also want to reset this._currentTextBox at this point?
        // this._currentTextBox = newTextBox;
    }
}


package biz.tugay.caesarcipher;

import java.util.Locale;

/*
    Encyrpts a clear text using Caeser Cipher (https://en.wikipedia.org/wiki/Caesar_cipher)
    with given shift amount.

There is a typo in "Encrypts", and the URL should be a hyperlink, like Caesar Cipher.

    Provided shift amount (i.e. key) must be a positive integer less than 26.

Depending on who you ask, the word positive may exclude the 0. You should just say must be between 0 and 25.

But even more important: the documentation must match the code. Currently the code says <= 26.

    Only English alphabet is supported and encyrpted text will be in uppercase.

The same typo as above. And, the Turkish lowercase dotless i (ı) is also "supported", although not intentionally.

    Shift amount 0 will return the same clear text.
 */
public final class CaesarCipher {

    private final String clearText;

There is no reason that the Cipher class ever stores the clear text. Therefore this field should be replaced with a method parameter.

    private final int key;

    public CaesarCipher(final String clearText, final int key) {
        if (clearText == null) {
            throw new UnsupportedOperationException("Clear text to be encrypted can not be null!");
        }

        if (key < 0 || key > 26) {
            throw new UnsupportedOperationException("Key must be between 0 and 26");
        }

        this.clearText = clearText;
        this.key = key;
    }

    public String encryptText() {
        final StringBuilder cipherTextBuilder = new StringBuilder();

        final String clearTextUpperCase = clearText.toUpperCase(Locale.US);
        final char[] clearTextUpperCaseCharArray = clearTextUpperCase.toCharArray();

        for (final char c : clearTextUpperCaseCharArray) {
            if (c < 65 || c > 90) { // If the character is not between A .. Z, append white space.

This comment is redundant if you write c < 'A' || c > 'Z'.

                cipherTextBuilder.append(" ");
                continue;
            }
            final Character encryptedCharacter = encryptCharacter(c);
            cipherTextBuilder.append(encryptedCharacter);
        }

        return cipherTextBuilder.toString();
    }

    private Character encryptCharacter(final char c) {
        final int initialShift = c + key;
        final int finalShift;

        if (initialShift > 90) {
            // This is the case where we go beyond Z, we must cycle back to A.
            finalShift = (initialShift % 90) + 64;
        } else {

This can never happen since you already check the condition in the encryptText method.

            // We are in the boundries so no need to cycle..
            finalShift = initialShift;
        }

        return (char) finalShift;
    }
}

I would write the encryptCharacter method as follows and remove the bounds check from the encryptText method:

private char encryptCharacter(char c) {
    if ('A' <= c && c <= 'Z') {
        int position = c - 'A';
        int shiftedPosition = (position + shift) % 26;
        return (char) ('A' + shiftedPosition);
    } else {
        return c;   // Or ' ', as in your code
    }
}

The tests

package biz.tugay.caesarcipher;

import org.junit.Assert;
import org.junit.Test;

public class CaesarCipherTest {

    @Test
    public void shouldReturnBCDForClearTextABCAndKey1() {
        final String clearText = "abc";
        final CaesarCipher caesarCipher = new CaesarCipher(clearText, 1);

        final String encryptedText = caesarCipher.encryptText();

        Assert.assertTrue(encryptedText.equals("BCD"));
    }

I usually split each test into three paragraphs. The first prepares everything, the second does the interesting work, and the third asserts that the result is correct. When you follow this style, you can easily see which part of the code is worth stepping through with a debugger.

Instead of assertTrue, you should call assertEquals("BCD", encryptedText). Because when that assertion fails, the error message is much nicer, giving you the expected and the actual result.

    @Test
    public void shouldReturnAForZAndKey1() {
        final String clearText = "Z";
        final CaesarCipher caesarCipher = new CaesarCipher(clearText, 1);
        final String encryptedText = caesarCipher.encryptText();
        Assert.assertTrue(encryptedText.equals("A"));
    }
}

You forgot to test lowercase letters and non-alphabetic characters. And emojis, which by the way would result in two spaces per emoji.


Input checking

If the caller passes in a base greater than 17, you will read past the end of rep.
If the caller passes in a base of 0, you will divide by zero.
If the caller passes in a base of 1, your code will infinite loop.
If the caller passes in a negative value but the base is not 10, you will read past the front of rep because your modulus will be negative.  You should always make value positive before proceeding with your loop.

Insufficient buffer size
On a system with 64-bit ints and a base of 2, you will need a buffer of size 65 instead of 50.  (Or 66 if you allow negative values for all bases).
Code simplification
This code:

if (value == 0)
    *--ptr = rep[value % base];
while (value != 0)
{
    *--ptr = rep[value % base];
    value /= base;
}

could be simplified to:
do {
    *--ptr = rep[value % base];
    value /= base;
} while (value != 0);

I'm not sure from your question whether you were allowed to use a do loop or not.  Also, your question says you are supposed to return an allocated buffer but you intentionally didn't, so I'm not sure how to review that part of it.