C++ implementation of the decorator pattern

Friend Functions.

Its a lot simpler to just place friend functions directly into the class declaration.

Rather than:

class AbstractObject {
    friend std::ostream& operator<<(std::ostream&, const AbstractObject&);
};

std::ostream& operator<<(std::ostream& os, const AbstractObject& object) {
    object.displayTo(os);
    return os;
}

Simply do this:

class AbstractObject {
    friend std::ostream& operator<<(std::ostream& os, const AbstractObject& object) {
        object.displayTo(os);
        return os;
    }
};

Avoid protected

Protected very rarely gives you any benefit. It should be avoided.

class AbstractObject {
protected:
    // All the people that use `name` are already friends.
    // So protected is not useful. Other people using name
    // should be calling `displayTo()` to get the name displayed.
    // But the real question is why does an abstract object have
    // a name? If i does you should know how to display it.
    std::string name;

    // Personally I see no reason not to make this public.
    // But you could make it private and only callable by your
    // friend the output operator.
    virtual void displayTo(std::ostream&) const = 0;
};

Classes with Virtual methods should have virtual destructor

When you create a class with a virtual method. This means you are calling that method through an object of another type. This type is usually dynamically allocated and thus will be dynamically destroyed.

If you delete it via a pointer to the base class the wrong destructor will be called (unless it it virtual).

AbstractObject*  obj = new Decorator("red jacket", shirt);

// Do stuff.

delete obj; // Here obj is an AbstractObject* so we call AbstractObject::~AbstractObject()
            // to destroy the object. This is wrong as obj points at a
            // Decorator object and we want to call Decorator::~Decorator()
            // To achieve this the AbstractObject destructor must be
            // virtual to make sure that chaining to the most
            // derived version of the function happens.

Temporary abuse:

    AbstractObject& human = Object("Alice");
    AbstractObject& shirt = Decorator("blue shirt", human);
    AbstractObject& jacket = Decorator("red jacket", shirt);

Sure that works. But I can not call any Object methods on human as all I can see is the AbstractObject interface. Same with shirt and jacked I can not see their properties or fields.

It would be better to do it like this:

    Object    human("Alice");
    Decorator shirt("blue shirt", human); // this works as Object is an AbstractObject
    Decorator jacket("red jacket", shirt);// This works as Decorator is an AbstractObject

Design

Yes decorator can be a useful pattern.
But in C++ we usually use "Duck Typing" to solve the same problem.

Duck Typing: If it quacks like a duck it must be duck like.
             If it has the same method name  with the same parameters
             then we should be able to use it in the same way.

This is usually used in conjunction with templates.

template<typename Duck>
void print(Duck const& duck, std::ostream& str) {
    duck.displayTo(str);
}

Here we have a print() method. It takes any type (don't have to be related) as long as they support the displayTo(std::ostream& str) method the above function will work.

Refactored original

#include <iostream>
#include <string>

class AbstractObject
{
    public:
        virtual ~AbstractObject() {}
        friend std::ostream& operator<<(std::ostream& os, const AbstractObject& object)
        {
            object.displayTo(os);
            return os;
        }
        virtual void displayTo(std::ostream&) const = 0;
};

class Object : public AbstractObject
{
    private:
        std::string name;
    public:
        Object(std::string name)
            : name(name)
        {}
        void displayTo(std::ostream& os) const
        {
            os << name;
        }
};

class Decorator : public Object
{
    private:
        const AbstractObject& ref_decoratedObject;
    public:
        Decorator(std::string name, AbstractObject const& ref_decoratedObject)
            : Object(name)
            , ref_decoratedObject(ref_decoratedObject)
        {}
        void displayTo(std::ostream& os) const
        {
            Object::displayTo(os);
            os << " decorates " << ref_decoratedObject;
        }
};

int main() {
    Object      human("Alice");
    Decorator   shirt("blue shirt", human);
    Decorator   jacket("red jacket", shirt);

    std::cout << human << std::endl;
    std::cout << jacket << std::endl;


Remove duplicates from array and save it to another one

Early termination
After
        dup = 1;

you should break. There's no need to execute the rest of the loop.
Booleans
Consider using <stdbool.h>, making bool dup = false, later assigning it true, and writing if (!dup).
Complexity
In practical terms, an array of five values poses no computational cost. However, if your prof cares about complexity analysis, the "proper" solution to this would need to complete in linear time (rather than your current quadratic time), using something like a hash-set, with pseudocode:
Set *seen = make_set();
for (int i = 0; i < MAX_ARRAY_SIZE; i++)
{
    int m;
    scanf(&m);
    if (!contains(seen, m))
        add(seen, m);
}

for (m in seen)
    printf(m);


Reading denormalized data using a stateful loop body

In essence your code is currently:

while (rdr.Read()) {
    if (new owner) {
       // do duplicated logic yield stuff
       // Prepare for new owner
    } else {
       // Add owner names
    }
}

if (new owner) {
    // do duplicated logic yield stuff
}

To avoid the duplicated logic, the nicest solution would be to use an extra function, but alternatively you could also change the loop logic into being an eternal loop, and breaking out of it when reaching the end.

In other words something similar to the following:

while (True) {
    if (!rdr.read()) {
        last_record == true;
    }

    if (new owner || last_record ) {
       // do duplicated logic yield stuff
       if (!last_record) {
           // Prepare for new owner
       } else {
          break; // Break out of loop
       }
    } else {
       // Add owner names
    }
}

In this way you call the duplicated logic block both if there are data and you have a new owner, and if you've read the last record. Note that the !rdr.read() will read records even though the if condition is negated afterwards.

Whether you feel this is a better approach or not, is left for you to decide, but it does avoid the duplication of logic you are concerned about.


Function to toggle between two values of an enum

Would there ever be a need to add more values to the MonitoringMode enum?

enum MonitoringMode
{
    Seek,
    Destroy,
    Something,
    SomethingElse
}

In that case, you're not "toggling" - you're mapping. And there's a data structure for that:

private static readonly IDictionary ModeMap = new Dictionary<MonitoringMode,MonitoringMode>
{
    { MonitoringMode.Seek, MonitoringMode.Destroy },
    { MonitoringMode.Destroy, MonitoringMode.Seek },
    // ...
};

Then you could switch from one value to the next simply by using that map:

void ToggleMonitoringMode()
{
    _monitoringMode = ModeMap[_monitoringMode];
}

If there's not going to be a need to ever add more values, then I'd question the use of an enum type here, because you're really toggling between true and false states of some _isSeeking Boolean, which you already know how to toggle.


Using a template to cycle through a sequence of containers

Here is how I would write it:

template<typename C>
class cycle
{
    C& mContainer;
    size_t index;
    using ref = decltype(mContainer[0]);

public:
    explicit cycle(C& container) :
        mContainer(container), index(0) {}

    ref getNext()
    {
        return mContainer[index++ % mContainer.size()];
    }
};

Notes:

The template parameter is the container, C. This not only simplifies code, but also works for containers that do not follow a specific pattern, e.g. have more parameters than just a value type and an allocator type.
The return type of getNext is automatically inferred from C. This is not just C's value_type but a (non-const) reference to it.
If I understand correctly from the title, C is supposed to be a sequence of containers? If so, the value_type is a container itself so it is even more important that a reference is returned from getNext.
Why pass a parameter to getNext? To cycle correctly, you should use mContainer.size(), exactly as you do in Processor::update, right?
index is of type size_t

With only a few changes, here is Processor:

class Processor
{
   size_t mIndex;
   std::vector<int> numbers;

public:
   cycle<std::vector<int>> cycler;
   Processor() : mIndex(0), numbers(), cycler(numbers) {}
   void update() { std::cout << numbers[mIndex++ % numbers.size()] << std::endl;}
   void addNumber(int x) { numbers.push_back(x); }
};

Notes:

again, mIndex is a size_t
cycler is a cycle<std::vector<int>>
numbers is default-initialized
cycler is safely constructed after numbers

Also, whenever you want to

using namespace std;

for convenience, only do it inside another (your own) namespace, never globally.

EDIT

I just noticed you're not using C++11. In this case, just use

    typedef typename C::value_type& ref;

instead.


The elephants in the room:

Single letter variable names are to be avoided. Each variable should have a suggestive meaningful name.
They probably expected you to write automated tests, just printing a result for visual inspection is not a real way of testing. assert is easy to use and can get you started on automated testing.


Utilizing idle socket server to do meaningful thing (timeout after sleep on epoll_wait)

Keeping the cache hot

So my initiative is to make the sleep time short and force the process to read from memory again and again until the events come.
Reason for doing this is that to keep critical (for performance) data hot in the cache.

If nothing else running on the same CPU, there is no reason for the cache to go cold. Things in the cache don't time out, they just stay there until they are evicted when necessary.
If there are other processes running, then your strategy might help your socket server, but there are several issues with this:

It is selfish; you might prevent other processes from keeping their data in the cache, thus lowering their performance.
It might not work at all, since once another process gets a time slice, their memory access patterns may evict your data from the cache again.
By not staying idle, your CPU might not get a chance to go into a low power state, thus keeping your cache literally hot.

My recommendation is to just use an infinite timeout for epoll_wait().
About memcmp_explicit()
Be aware that compilers are getting better and better at optimizing things. Even if you put memcmp_explicit() in a different translation unit than where it is called, the compiler might optimize it out if link time optimization is enabled.


Here are my suggestions:

Use Application.ScreenUpdating = False to speed up the execution of the code. See here for more details.

Declare elements where you need them. While your code is short (which is great, btw), it's a good habit to get into.

Use Option Explicit and declare that x variable appropriately. x right now is of type Variant but you're only using it like a Long, so you should declare it as Long. Also, change x to a more meaningful name like row.

Don't put two executable statements in the same line.

Having x = x + 1: Cells... is clever, but it may confuse other people later on (or even yourself if you don't touch this code for months).

Set a reference to the active sheet if that's the sheet you intend to use. When you use Cells(...) you are referring to the active sheet. However, while you are looping through your items in the For loop, if you were to click on another sheet, then your data will get messed up when you could avoid this issue pretty easily. In the code below, Cells(...) becomes activeWs.Cells(...).

Personally, I would only use With ... End With if I had many statements I needed it for (like the first use you have of it). In the second and third uses of With, I would just remove it. I would also use If ... Then ... End If so the If statement isn't so long.

I can tell that you wanted to make the code as short as possible, but sacrificing a few lines for clarity will be more beneficial in the long run, in my opinion.

Lastly, about If post.getElementsByClassName("browse-movie-year").Length Then, I would explicitly state what you really mean, which is that if the length if greater than 0. While this statement returns an array and I get that you're checking for an array length and it will always be >=0, it's best to be explicit for clarity.

EDIT: Thinking about this further, this code could be considered to do too much. If you were to follow the Single Responsibility Principle, then we could split out the work to other, private functions.

Here is my version of the refactored code (untested):

Option Explicit

Sub Torrent_Scraper()
    Application.ScreenUpdating = False

    Dim url as String
    Dim proxyServer As Variant
    Dim bypassList as Variant

    url = "https://yts.ag/browse-movies"
    proxyServer = "61.233.25.166:80"
    bypassList = "46.101.27.218:8118"

    Dim html As New HTMLDocument
    html.body.innerHTML = GetHttpResponseTextByProxy(url, proxyServer, bypassList)

    Call SetMovieData(html, ActiveSheet)

    Application.ScreenUpdating = True
End Sub

Private Function GetHttpResponseTextByProxy( _
    ByRef url as String, _
    ByRef proxyServer as Variant, _
    ByRef bypassList as Variant) As String

    Dim http As New ServerXMLHTTP60

    With http
        .Open "GET", url, False
        .setRequestHeader "Content-Type", "text/html; charset=utf-8"
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
        .setProxy 1, proxyServer, bypassList
        .send
    End With

    GetHttpResponseTextByProxy = http.responseText
End Function

Private Sub SetMovieData(ByRef html as HTMLDocument, ByRef ws As Worksheet)
    Dim post As HTMLHtmlElement
    Dim row As Long

    For Each post In html.getElementsByClassName("browse-movie-bottom")
        row = row + 1
        ws.Cells(row, 1) = post.getElementsByClassName("browse-movie-title").item(0).innerText

        If post.getElementsByClassName("browse-movie-year").Length > 0 Then
            ws.Cells(row, 2) = post.getElementsByClassName("browse-movie-year").item(0).innerText
        End If
    Next post
End Sub


I would suggest following:

Place operations to the objects that contain data for this operation. It will improve encapsulation and allow more flexible code reuse.
Also it will be easy to test such implementation because of small methods.
Use more convenient structure. In this case Map<String, LoanAccount> (map id to loanAccount) instead of List<LoanAccount>

As you can see in this case service contains only required logic (how to react on loan absence). It is easy to read, test and understand.

LoanAccountService.java

public class LoanAccountService{

    private Bank bank;

    public LoanAccountService(Bank bank) {
        this.bank = bank;
    }

    public LoanAccount update(LoanAccount loanAccount) {
        if (!bank.updateLoanAccount(loanAccount)) {
            throw new IllegalArgumentException("The object does not exist.");
        }
        return loanAccount;
    }
}

Bank.java

@Getter
@Setter
public class Bank {
    private Map<String, LoanAccount> loanAccounts;

    public boolean updateLoanAccount(LoanAccount loanAccount) {
        LoanAccount loan = loanAccounts.get(loanAccount.getId());
        if (loan != null) {
            loan.update(loanAccount);
            return true;
        }
        return false;
    }
}

LoanAccount.java

@Getter
@Setter
public class LoanAccount {
    private String id;
    private Integer numberOfInstallments;
    private LoanAccountType type;
    private Date creationDate;
    private BigDecimal loanAmount;

    public void update(LoanAccount loanAccount) {
        this.setCreationDate(loanAccount.getCreationDate());
        this.setLoanAmount(loanAccount.getLoanAmount());
        this.setNumberOfInstallments(loanAccount.getNumberOfInstallments());
        this.setType(loanAccount.getType());
    }
}

If you can't use this approach, you could made a small refactoring of the service (less code and "if conditions" are good things):

public LoanAccount update(LoanAccount loanAccount) {
    LoanAccount account = bank.getLoanAccounts()
            .stream()
            .filter(la -> la.getId().equals(loanAccount.getId()))
            .findAny()
            .orElseThrow(() ->  new IllegalArgumentException("The object does not exist."));
    account.setCreationDate(loanAccount.getCreationDate());
    account.setLoanAmount(loanAccount.getLoanAmount());
    account.setNumberOfInstallments(loanAccount.getNumberOfInstallments());
    account.setType(loanAccount.getType());
    return account;
}

Also I think you should return updated loan account.


You don't use total_tuition_increaseSum for anything other than that one print, so you may as well call sum on it in the print line:

total_tuition_increase = "${:,.2f}".format(sum(total_tuition_increase))

I would also recommend you look more at splitting the code into functions. Functions usually make code easier to read, use and change. For example, you might put your input management into one function so it's a small self contained chunk. All it needs to do that's different is return the resulting tuition cost instead of setting it directly. This is how it'd work:

def get_cost():
    while True:
        residency = raw_input('Please input your type of residency, I for in-state, O for out-of-state, and G for graduate: ')
        try:
            return RESIDENCY_COST[residency.upper()]
            break
        except KeyError:
            print ('Please enter I, G or O ONLY.')

And you could call it like this:

cost_of_tuition = get_cost()

Similarly, you could then wrap your printing into a print_tuition_table function. This one would need to take parameters, your two lists and total_tuition_increase.

def print_tuition_table(academic_year, academic_year_inc, total_tuition_increase):
    print('UNDERGRADUATE TUITION FOR THE NEXT FIVE YEARS ')
    print('ACADEMIC YEAR          TUITION       INCREASE ')
    print('-------------     ------------       -------- ')

    for i, year in enumerate(range(16, 21)):
        print('{}-{}             {}        {}'.format(year + 2000, year + 1,
                                                      academic_year[i],
                                                      academic_year_inc[i]))

    print('TOTAL TUITION INCREASE              {}'.format(total_tuition_increase))

Of course, you could change this to be more re-usable now if you didn't hard code it as being five years. Instead, you could check the length of the academic_year list and then just change the way the loop works slightly:

def print_tuition_table(academic_year, academic_year_inc, total_tuition_increase):
    length = len(academic_year)
    print('UNDERGRADUATE TUITION FOR THE NEXT {} YEARS '.format(length))
    print('ACADEMIC YEAR          TUITION       INCREASE ')
    print('-------------     ------------       -------- ')

    for i, year in enumerate(range(16, 16 + length)):
        print('{}-{}             {}        {}'.format(year + 2000, year + 1,
                                                      academic_year[i],
                                                      academic_year_inc[i]))

    print('TOTAL TUITION INCREASE              ' + total_tuition_increase)

Then you could do the same with your calculation loop. It would need to take in cost_of_tuition and return multiple values, but return multiple values is easy in Python. First, you wrap it in a function like this:

def calculate_fees(cost_of_tuition):
    for _ in range(5):
        intMath = cost_of_tuition * 0.03
        tuition_increase.append(intMath)
        fnlMath = intMath + cost_of_tuition
        years.append(fnlMath)
        cost_of_tuition = fnlMath
        academic_year.append("${:,.2f}".format(fnlMath))
        academic_year_inc.append("${:,.2f}".format(intMath))
        total_tuition_increaseSum = sum(tuition_increase)
        total_tuition_increase = "${:,.2f}".format(total_tuition_increaseSum)

    return academic_year, academic_year_inc, cost_of_tuition

Then you can set those values like this:

academic_year, academic_year_inc, cost_of_tuition = calculate_fees(cost_of_tuition)

Also, you could easily expand this function to take a years parameter so that it doesn't have to be stuck with 5 years.

def calculate_fees(cost_of_tuition, years):
    for _ in range(years):

And since our printing function checks the length of your list, now you just need to change one number to be able to adjust the whole output.

With all those functions defined, here's how you could call them to run the script:

cost_of_tuition = get_cost()
academic_year, academic_year_inc, cost_of_tuition = calculate_fees(cost_of_tuition)
print_tuition_table(academic_year, academic_year_inc, cost_of_tuition)


fix ugly initialisation in while loop over queue

It would be better to do

for (Integer element; (element = queue.poll) != null;){

}

Because you don't want element to be in the scope after the loop has ended


Too many Language Repetitions

You use the "Language" key a lot. What if you decide to rename it sometime? You'll need to search everywhere for this string. It'd be better if you encapsulated it or used a constant. I prefer extensions so it might look like this where you try to get the cookie and if it is not null ? then you get the value.

public static class HttpCookieCollectionExtensions
{
    public static string Language(this HttpCookieCollection cookies)
    {
        return cookies["Language"]?.Value
    }
}

Later in your application you can reuse it everywhere which would result in a nice short and clear code ba also getting rid of this ugly condition:

 if (cookie != null && cookie.Value != null)

Bug 1

else
{
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");

}

There is a bug in this else. Both lines are the same. Did you copy/paste them?

Setting culture

Another case for encapsulation are the four lines where you set the culture. Just write a new method and put two of them there:

public static void SetCulture(string name)
{
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(name);
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(name);
}

Default culture

Later you should also add a constant for the default cutlure

const string DefaultCulture = "en";

New event handler

Now put everything together and be happy with this pretty nice two-liner event handler:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var language = HttpContext.Current.Request.Cookies.Language() ?? DefaultCulture;
    SetCulture(language);
}

Object initializer

You can also shorten the ChangeLanguage method by using an object initializer. This means that you replace this three lines

HttpCookie cookie = new HttpCookie("Language");
cookie.Value = LanguageAbbrevation;
Response.Cookies.Add(cookie);

with simply this

Response.Cookies.Add(new HttpCookie("Language")
{
    Value = LanguageAbbrevation
});

Bug 2

There is one more bug in your application. When you check for the LanguageAbbrevation here you don't set it to any default value if it's null. Consequently setting the cookie to nothing. Why don't you use en here or skip setting the cookie by putting it inside the if?

public ActionResult ChangeLanguage(String LanguageAbbrevation)
{
  if (LanguageAbbrevation != null)
  {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(LanguageAbbrevation);
      Thread.CurrentThread.CurrentUICulture = new CultureInfo(LanguageAbbrevation);

  }
  Response.Cookies.Add(new HttpCookie("Language")
  {
      Value = LanguageAbbrevation
  });
  return RedirectToAction("Index", "Home");

}


(Codewars) Linked Lists - Remove Duplicates

The space complexity of your solution is \$O(n)\$. What if I told you that given the constraints in the question, you could solve this problem in \$O(1)\$ space?

Consider that you receive an already sorted list. This implies that all duplicates must be adjacent. This in turn means that for deduplicating these, you do not need to keep track of which values you already encountered.

Note that del is not necessary here. You never use tmp aside from assigning node.next to it in any case. del is not clearing the memory allocated to the variable (or the object it refers to), it only destroys the variable itself, the object is unaffected. As such it does not have any effect on the garbage-collection that python performs...

The following should already work just fine:

def remove_duplicates(head):
    node = Node(None, head)
    while node.next:
        if node.next.data == node.data:
            node.next = node.next.next
        else:
            node = node.next
    return head

Small sidenote: I really like the hack you used to ensure that you handle the head is None case, but you should be aware that it is just a hack. The cleaner solution to this would be:

def remove_duplicates(head):
    if not head:
        return head
    node = head
    while node.next:
        # Rest of the code...


Logging errors with the same exception type

Your log output shouldn't also be detailing the code that failed, because the JVM is going to generate a more detailed stacktrace, and you should print that instead.

LOGGER.error("..." + url, e);

Instead, it will be more beneficial to give a more descriptive message. Borrowing your original code...

try {
       connection = (HttpURLConnection) url.openConnection(proxy);
} catch (IOException e) {
       LOGGER.error("Unable to open a connection to " + proxy, e);
}
int responseCode = -1;
try {
       responseCode = connection.getResponseCode();
} catch (IOException e) {
       LOGGER.error("Could not get response code from " + proxy, e);
}


It's a small code snippet but IMO you may improve few things about style:

Usually (in .NET environment) properties are TitleCase as well as classes.
Whatever your favorite naming convention is you should be consistent, if you use title case for classes then iosLayoutXml should be renamed IosLayoutXml.
Prefixes and suffixes are generally avoided, you're using Xml suffix and it has also another disadvantage: you're exposing an implementation detail. You may, in future, change storage to Json but calling code should not be aware of that.

Some notes (without more context they're almost questions) about code:

If your classes will not be derived then you should also mark them as sealed. To open a class to inheritance requires much more work.
You do not initialize properties with default values: is it null, for example, acceptable for FieldXml.text if omitted in XML file?
From caller point of view is it null equivalent to String.Empty? Do you want to move this responsability on caller?
Will anyone use these classes for setting properties? In this case you should also add proper argument checking.
You may not need it in this moment but it may be useful (think about it) to define FieldCollection and use it instead of List<Field>. Once it has been deserialized will it change in size? If not you may also consider to use FieldXml[].
Is it valid to have a null entry for TransactionLayoutXml.fields?
I don't know which kind of values will go into FieldXml.text and FieldXml.value (and if format is fixed or you have some freedom) but if they contains characters that must be escaped you may want to use node text instead of an attribute, especially if XML may edited by hand it's much more handy to use CDATA sections.


There are a few reasons why double-checked locking does not always work in Java. There are a number of blogs with more detail, but I quite like this one and this one.

Now, your code contains a volatile declaration for cached which, in certain conditions can mitigate the problem, but it is not a complete solution. You can still have cases where the cached variable is set in one thread, but another thread reads it before it is completely initialized. Since the values in the cached are not volatile, you will have problems still. Also, they depend on orderStatusesDao which is not volatile either...

With Java5's changes to the memory model, you can probably use a 'helper' variable to initialize the data... something like:

      Map<String,String> helper = new HashMap<String, String>();
      for (OrderStatuses orderStatus : orderStatuses) {
        helper.put(orderStatus.getCode(), orderStatus.getName());
      }
      cached = helper;

Using the helper ensures that the cached instance is fully assigned before it gets set.

This all seems very complicated.... and all to save a micro-synchronization.

With the advent of Java6 and enums, there are a few really good ways to create thread-safe lazy-initialized values, but your case is somewhat more complicated by the orderStatusesDao.getAll(); required for initialization.

As an 'aside' comment, I am concerned by this line:

synchronized (OrderStatusesService) { ...

The line suggests you have a variable called OrderStatusesService which is the exact same name as the class OrderStatusesService.... or is the synchronization supposed to be on OrderStatusesService.class?

In your case above, I would probably be satisfied with a simple/standard synchronization block and no volatile declaration. The lock-wait time will be very minimal.

Alternatively, I would consider an optimistic system using AtomicReferences, for example:

Map<String, String> cached = atomicref.get();
if (cached != null) {
    return cached;
}
cached = new HashMap....;
// populate cached.....
if (atomicref.compareAndSet(null, cached)) {
    // we were the first thread to populate, great:
    return cached;
}
// return the value that the winning thread created.
return atomicref.get();

in the above system, the first thread to 'set' the cached value will have it's instance used by every other thread. It is possible that multiple threads may be initializing their values at the same time, but they will all defer back to the winning-thread instance if they don't win. Once the instance is set, all threads will use that instance and there will be only fast atomic locking.


Extends Scala iterator's drop method to allow for drop(x: Long)

You can use a (tail-)recursive method to achieve same result:

def drop[T](c: Long, i: Iterator[T]): Iterator[T] = {
  if (c > Int.MaxValue) drop(c - Int.MaxValue, i.drop(Int.MaxValue))
  else i.drop(c.toInt)
}

def dropLongAndGet[T](dropVal: Long, iteratorLong: Iterator[T]): T = {
  drop(dropVal, iteratorLong).next
}


Find part of string in array, replace entire row with that part of string if found

You can use a regular expression:

string[] names =
  Regex.Matches(sequence, @"([A-Za-z_]\w*)\(").Cast<Match>()
  .Select(m => m.Groups[1].Value).ToArray();


There's a problem with your approach: it always visits all nodes to build value lists, even when the trees aren't similar at all. By obtaining leaf-node values lazily, you'll prevent a lot of unnecessary traversal work if the trees are different.

This can be achieved by changing DFS to a generator method (using yield), and comparing the results with SequenceEqual, as janos already pointed out. You'll want to use an explicit stack instead of recursion though, to avoid incurring too much overhead.

However, for trees that are leaf-similar, the added overhead ends up making things slower. The fastest approach is probably a recursive method that does a depth-first traversal of both trees at the same time, bailing out as soon as it finds a leaf-node difference.


JavaScript multiple ajax calls but can either be one or two

As mentioned in the comments, JS uses camelCase. Even if your team suggests to use snake_case consistently, JavaScript APIs are all in camelCase making your code look weird and out of place.

'use strict';

import Cookie from 'js-cookie';
const _ = require('../helpers');

Be consistent and use one module system. Suggesting you stick to the ES6 syntax as it is the standard.

Also, ES6 modules are in strict mode by default. This means the 'use strict'; pragma is unnecessary. If you're using a bundler that follows standards, it should be putting the pragma for you so you don't have to. If it doesn't put it for you, use a better bundler.

import Cookie from 'js-cookie';
const _ = require('../helpers');
module.exports = function(cb) {...}

Since I recommend writing ES6, then this should now be

import Cookie from 'js-cookie';
import _ from '../helpers';

export default function(cb){...}

_ and cb are not good names. Give them a full name, like Helpers and callback, respectively. "Lesser keystrokes" is not a good excuse. It's not worth the hassle debugging and you'll only lose hair faster.

Also, I would suggest ditching the callback pattern in favor of returning Promises. It will still look like callbacks when used, but it provides better control flow than callbacks.

window._g = window._g || {};

If  windows._g is just a temporary storage for your function's results, then as mentioned earlier, use promises. With promises, you can retrieve and pass on results from async operations without ever needing a temporary variable to store the data. The promise holds the values for you.

  multiple ajax calls but can either be one or two

Assuming _.ajax is not jQuery.ajax and the fact that you're using a done and not then, then _.ajax might not be returning promise-like objects. I suggest you do return a promise for _.ajax because what you're essentially doing is what Promise.all is for. It accepts multiple promises, and resolves when all are in. Good for multiple, parallel AJAX calls.

In the case of your second call, which is dependent on uid, you either return the _.ajax call promise or return a pre-resolved promise using Promise.resolve.

If I were to rewrite this module, it would look like this:

// getSessionData.js

import Cookie from 'js-cookie';
import Helpers from '../helpers';

export default function(){

  // Execute both requests. However, if `uid` isn't present, `userDataRequest`
  // will immediately be a resolved promise instead of a promise of an ajax call.
  const contextRequest = Helpers.ajax({});
  const userDataRequest = Cookie.get('uid') ? Helpers.ajax({}) : Promise.resolve({});

  // Wait for both promises to resolve. If `userDataRequest` is the pre-resolved
  // promise, then we'll only be waiting for `contextRequest`.
  //
  // This will resolve to { context: {}, user: {} }
  return Promise.all([contextRequest, userDataRequest])
                .then(([context, user]) => { context, user });
}

// Usage

import getSessionData from './getSessionData';

const sessionData = getSessionData().then(sessionData => {
  // This serves as replacement to your "callback"

  const context = sessionData.context;

  // user can either be the result from the AJAX call or a blank object.
  const user = sessionData.user;

  // Do stuff with context and user
});


It looks like you could use reduce to your advantage, and extracting a function to merge two sequences. (Edit: messed up 1st version; this should be better)

Tokens.prototype.reduceSequences = function () {
  // source and destination seem like slightly better names
  function merge(source, destination) {
    // can't merge, so return false
    if( !~destination.content.indexOf( source.content ) )
      return false;

    // no need to actually merge (source included in destination),
    // so just return true
    if( destination.content != source.content )
      return true;

    // otherwise, merge
    for( var i = 0, l = source.starts.length ; i < l ; i++ ) {
      if( ~destination.starts.indexOf(source.starts[i]) ) continue;
      destination.starts.push( source.starts[i] );
      destination.ends.push( source.starts[i] + destination.tokenCount );
      destination.occurences.push( source.occurences[i] );
    }

    return true;
  }

  if(this.sequences.length < 2) return;

  this.sequences = this.sequences.reduce(function (sequences, current) {
    var merged, i, l;

    for( i = 0, l = sequences.length ; i < l && !merged ; i++ )
      merged = merge(current, sequences[i]);

    if( !merged )
      sequences.push(current);

    return sequences;
  }, []);
}

I think that should work.

Oh, and yes, I've undone your brace-on-new-line style - sorry, couldn't help myself. But I've left out braces I'd usually include, so I've met you halfway! :)

If reduce is not an option, I can't really come up with anything besides extracting a merge function (basically a "lighter" refactoring). Like so

Tokens.prototype.reduceSequences = function () {
  // source and destination seem like slightly better names to use *here*
  // but they don't make as much sense in the loops below, IMO
  function merge(source, destination) {
    for( var i = 0, l = source.starts.length ; i < l ; i++ ) {
      if( ~destination.starts.indexOf(source.starts[i]) ) continue;
      destination.starts.push( source.starts[i] );
      destination.ends.push( source.starts[i] + destination.tokenCount );
      destination.occurences.push( source.occurences[i] );
    }
  }

  var sequences = this.sequences;

  for( var outer = 1 ; outer < sequences.length ; outer++) {
    for( var inner = 0 ; inner < outer ; inner ++) {
      if( sequences[inner].content == sequences[outer].content ) {
        merge(sequences[outer], sequences[inner]);
        sequences.splice(outer, 1);
        outer = 0;
        break;
      }

      if( ~sequences[inner].content.indexOf( sequences[outer].content )  ) {
        sequences.splice(outer, 1);
        outer = 0;
        break;
      }
    }
  }
}

It's not brilliant, but either way it feels a tiny bit cleaner to encapsulate the "merge" step in a function.

By the way, var tokens = this.raw() didn't seem to be used for anything.

It might be more beneficial to simply add the merge function to your sequence objects, though. It'd clean up this particular code nicely. But you know better than I if something like that would make sense in your project.


That's very elegant looking code. bash has a builtin select statement to present a menu to the user and get a response --
the advantage of select is that the user is locked into it until a valid response is obtained. Plus, it seems that printing the menu and reading the response should be together.

My code below is not as beautiful as yours, but it allows you to localize all knowledge about the file structure into a single line: local fields=(...)

main() {
  local PS3='Enter a choice: '
  local fields=(First Last Email)

  # reverse the fields array: map field names to column numbers
  local -A column
  for (( i=0; i < ${#fields[@]}; i++)); do
    column[${fields[i]}]=$((i+1))
  done

  while true; do
    clear
    select choice in "${fields[@]}" Exit; do
      # invalid response
      [[ -z $choice ]] && continue

      # exit
      [[ $choice = "Exit" ]] && return

      # do something interesting
      view_column "${column[$choice]}"
      sleep 1.5
      break
    done
  done
}


Fisher-Yates shuffle algorithm in javascript, modern and inside-out versions

Unless you modify the inside out code to scale by (index+1)

       randomIndex = rand()*(index+1)|0;

You will not be covering all the possibilities.
For index == 0, you always generate 0 -- this is correct, but only by accident.

For index == 1, you also always generate 0 -- instead of a 50/50 split between 0 and 1

The second card in the deck misses its ONLY chance to get to be card[1].

The same problem continues for each card from then on, without the +1, randomIndex < index  when you want randomIndex <= index.

The problem may be even clearer for the last card placed in the deck. For a 52 card deck, index == 51, so randomIndex can be at most 50. So any prior card has a possibility of ending up at card[51], but not the last card. It can get no closer than card[50].

It should be reassuring that this change makes the math for the initial shuffle look more like that of the re-shuffle.


For the most part this looks like a typical way to draw geometry in OpenGL. I see a few things that could be improved.
Use structures for structured data
Currently you're storing your vertex coordinates in a 1 dimensional array of floats. But that data isn't just 6 floats. It's 3 points. So you should create a point structure:
struct Point2D {
    float x;
    float y;
};

And your vertex coordinates should be defined using that struct:
struct Point2D triangle1[] = {
    { 0.0f, 0.0f },
    { 1.0f, -1.0f },
    { -1.0f, -1.0f }
};

struct Point2D triangle2[] = {
    { 0.0f, 1.0f },
    { 1.0f, 0.0f },
    { -1.0f, 0.0f }
};

This will make it easier to read and understand. It also makes it much easier to find bugs. If your geometry looks weird, and it turns out you missed an x coordinate in one vertex, good luck figuring out that's the problem with a 1D array of floats. If you miss a coordinate with this struct, you'll get a compiler error.
And since you're working with triangles in this case, you could even make a Triangle2D structure containing 3 Point2Ds. It might be overkill for this simple example, though.
Use meaningful variable names
Names like vao and vbo tell you that those variables store the names for vertex array objects and vertex buffer objects. But they don't tell you which object in your scene they're used for, or how they differ from any other vertex array or buffer you're going to allocate later in the code. Obviously in this example, they only represent the arrays/buffers for the 2 triangles you're drawing, so suggesting a better name is difficult. But at least something like triArrayObj and triBufferObj would be more clear. In a game, for example, you might keep one set around for the scenery and another for the player's character, and another for an enemy, or something like that. They should be named as such.
The names of vec and vec2 are even worse, though. They're vectors, but vectors of what? As with the VAOs and VBOs, there's no real meaning in this particular code since it's just an example, so I'd at least name them tri1 and tri2 for "Triangle 1" and "Triangle 2".
Don't use sleep
You should not be calling sleep() in this code. It's not clear what you're trying to accomplish by doing that. It looks like you're drawing a frame with 1 triangle, then clearing it and drawing a frame with another triangle. Normally, you'd have an event driven application that takes input from the user and tells you to draw with some period, so you wouldn't want to use sleep() because you'd slow it down.
Efficiency
You ask a fair question about whether the way you're doing things is efficient or not. It's a little hard to answer given the simplicity of your example, but here are my thoughts.
In general you want to generate OpenGL objects like vertex array objects and vertex buffer objects infrequently. Allocating memory takes time. You also want to minimize sending data to the GPU. What that means in general is allocate whatever you can upfront and load it onto the GPU as infrequently as possible. In many cases you have a large amount of geometry that won't change, and a little bit of geometry that will change. You might also have a set of textures that are used throughout your rendering. If you can load all your unchanging geometry and unchanging textures onto the card at the start of your app (or assuming it's a game, the start of a level), that will help minimize the overhead of sending data to the GPU.
But you have to be careful. If you load more data onto the GPU than you have memory for, you could get VRAM swapping, or even just rendering errors. It's often the case that all the data you need to draw a scene won't fit on the GPU at once and you have no choice but to upload some of it every frame, or in severe cases, multiple times per frame.
You may find this becomes more difficult than it sounds at first as you attempt to support a wider range of possible GPUs. Your users may have hardware that ranges from extremely low-end to extremely high-end.


This technique for functional programming, and testing functional programming

or is this overkill that is easily solved another way?

_fetchUser and _fetchUsers appear to be the same function; save for the id parameter.

If interpret the question correctly, _fetchUser can be substituted for _fetchUsers (which can be removed entirely) by utilizing default parameters instead of .bind().

For example

async function _makeApiCall (uri) {
  try {
    const response = await Promise.resolve(uri);
    return response;
  } catch (err) {
    throw new Error(err.message);
  }
}

async function _fetchUsers({makeApiCall = _makeApiCall, _URI_USERS = 'abc', id = ''} = {}) {
  return await makeApiCall(_URI_USERS + id);
}

export default _fetchUsers;

<script type="module">
  import _fetchUsers from './script.js';
  (async() => {
    console.log(await _fetchUsers() // 'abc'
               , await _fetchUsers({id:'def'}) // 'abcdef'
               );
  })();
</script>

plnkr


Firstly, this could use a better description (in a comment) explaining what it does. I had to figure it out from the code. I think the description should probably be something like

// Searches $array for associative arrays which are supersets of $parameters.
// If $multipleResults it will return all matches in an array;
// otherwise just the first, in an array.

Secondly, names.

findValue isn't very descriptive. How about findSupersets?
$array would traditionally be called $haystack in PHP, since you're searching through it for matches to a predicate.
$multipleResoult is a misspelling. Correcting the spelling and adjective-noun agreement we get $multipleResults, which is ok, although I personally would prefer to communicate an action: $returnAll.
$suspicious has the wrong connotations for this native English speaker. If something is suspicious, it means that I think there's something wrong with it. My preferred variable name for something which may or may not pass an acceptance test is $candidate.

Thirdly, since PHP has a dynamic type system I think it would be more idiomatic to return just the element if !$multipleResults, rather than wrapping it in an array.

Now, you specifically ask whether there's a simpler way to do it. I think that using booleans it can be simplified quite a bit by inverting the assumption. Rather than prove it acceptable, prove it not acceptable. Taking into account various of my suggestions above and refactoring I get:

    foreach($haystack as $childArray){
        $isCandidate = true;
        foreach($parameters as $k => $p){
            if(!array_key_exists($k,$childArray) || $childArray[$k] != $p){
                $isCandidate = false;
                break;
            }
        }
        if($isCandidate){
            if(!$multipleResults){
                return $childArray;
            }
            $result[] = $childArray;
        }
    }

    return $result;

It's a couple of years now since I used PHP, and I'm not sure offhand whether there are built-in functions to test whether $childArray contains $parameters as a subset, or to filter an array by a predicate. It may be that the whole function can be reduced to two calls to built-ins. If not, you could consider whether you want to factor it out as

function findMatch(array $haystack, $predicate, $returnAll = false) {
    $results = []
    foreach ($haystack as $element) {
        if ($predicate($element)) {
            if ($returnAll) return $element;
            $results[] = $element;
        }
    }
    return $results;
}

function isSuperset(array $candidate, array $subset) {
    foreach ($subset as $k => $v) {
        if (!isset($candidate[$k]) || $candidate[$k] != $v) return false;
    }
    return true;
}

linking the two with a lambda.


You should only create subclasses for the different shapes if they are going to behave differently. If I were implementing it, I don't think they would behave differently, so I would not make subclasses for them. I think in my case every method would be the same, and each instance might have a different set of points with the blocks it covered. So an example method called public boolean canMoveDown might check the shapes points against any points on the game board below it, which would be the same implementation for each shape.

I don't think you should be passing a char to the constructor, though. I'd prefer an enum, or barring that, the set of points the particular shape you are creating covers, with that set kept in a factory. That keeps all of that data out of the class and the class is just responsible for processing the set of points it takes up. When coding try to follow the single responsibility principle where each class has one thing to do. This keeps everything much simpler and much easier to test and maintain.

Studies on software development have shown that systems with a large amount of inheritance are tougher to work on, tougher to maintain, and have more bugs. It's basically hidden functionality when you are looking at any class and it has a whole set of classes above it in an inheritance chain. So using inheritance for no reason is very bad.


iterators

You can use an iterator

def my_min(num_list):
    # empty lists
    if not num_list:
        raise ValueError('Empty list')

    list_iter = iter(num_list)
    minimum = next(list_iter)
    for num in list_iter:
        if num < minimum:
            minimum = num
    return minimum

In response to Mathias' comment, here is a version that works with an iterable:

def my_min(seq):
    seq = iter(seq)

    try:
        minimum = next(seq)

        for num in seq:
            if num < minimum:
                minimum = num

        return minimum

    except StopIteration as e:
        pass

    raise ValueError('Empty list')

Improved based on @Wombatz comment:

def my_min(seq):
    seq = iter(seq)

    try:
        minimum = next(seq)

    except StopIteration as e:
        raise ValueError('Empty list') from None

    else:
        for num in seq:
            if num < minimum:
                minimum = num

        return minimum


Is this good design for custom email template?

Don't use plain words as replacement keys since you might accidentally erase a real "name".  For example, in your template, use "Hello {{name}}," and you add "{{" and "}}" to the word you want to replace before calling replace.  It's easier to do that than to read each template carefully to make sure the keywords do not appear anywhere where they should not be changed.
Hide EmailTemplate inside EmailGenerator and make it private.  EmailTemplate is a "dirty" class that should not be exposed publicly: the method create(Map<String, String> valuesMap) must not be accessible since you need exactly the right arguments in the map.
You don't even really need EmailTemplate.  If you don't want to reread the files all the time, you can use a "lazy" map, Map<String, String> textFilesCache (file name -> file text).  When you fetch a file, you define a method that checks if textFilesCache(filename) is null and, if it is, it loads the file and adds it to textFilesCache.  It's even more efficient than the enum since the template files you never use will never be read.  An enum seems overkill here and it make the code less readable.
(If you want to have some fun, you can even take a look at WeakHashMap.  It's overkill here since you will only have a few files, but if you had very many and very large files, the JVM can drop some values of a WeakHashMap to free memory.)


Switching to next select field by class of parent

One thing you could consider is making this a little more generic and thus reusable. Currently you seem to assume, that there is only one .tab element in your document. If you had multiple (independent) .tab elements, each with their own set of select elements and you did't want to allow "tabbing" between then, then $(".tab select") will select all selects and not only the ones in the "current" .tab. So instead of

let tabs = $(".tab select");

I'd use

let tabs = $(this).closest(".tab").find("select");

Furthermore instead of hardcoding the selectors, consider making them variable, so that the script could be used with other class names and form elements:

function initArrowKeyTabbing(parentSelector, formElementSelector) {
  $(document).on('keydown', parentSelector + " " + formElementSelector, function (e) {
    $(this).closest(parentSelector).find(formElementSelector);
    // ...
  }
}

initArrowKeyTabbing(".tab", "select");

In the line

let tab = tabs.index($($(document.activeElement)));

you are calling jQuery twice. tabs.index($(document.activeElement)) would suffice. For the matter of the fact, .index() alternatively takes a DOM element as its parameter, so you even only need tabs.index(document.activeElement).

With an if ... else if ... construct you don't need the brackets around the second if:

if (e.which == 37) {
    tab -= 1;
} else if (e.which == 39) {
    tab += 1;
}

In this case instead of using if, a switch statement would be more flexible:

switch (e.which) {
    case 37:
       tab--; // Short form of tab -= 1;
       break;
    case 39:
       tab++;
       break;
}

The which event property is deprecated. The "proper" replacement is the key property, which however requires concessions towards IE and Edge, which use non-standard key names:

switch (e.key) {
  case "Left": // IE/Edge specific value
  case "ArrowLeft":
    tab--;
    break;
  case "Right": // IE/Edge specific value
  case "ArrowRight":
    tab++;
    break;
}


On the principal that functions should do one thing and do it well, consider breaking out some pieces of your filter into smaller functions for readability.

Filter

(function () {
    'use strict';

    angular.module('example')
        .filter('formatTemperature', formatTemperatureFilter);

    var degreesSymbol = '\u00B0';

    function convertCelsiusToFahrenheit(value) {
        return Math.round(value * 9.0 / 5.0 + 32);
    }

    function convertFahrenheitToCelsius(value) {
        return Math.round((value - 32) * 5.0 / 9.0);
    }

    function addDegreesSymbol(value) {
        return value += degreesSymbol;
    }

    function formatTemperatureFilter() {
        return function (input, scale, label) {
            var value = parseInt(input, 10),
                convertedValue;

            if (isNaN(value)) throw new Error('Input is not a number');

            if (scale === 'F') {
                convertedValue = convertCelsiusToFahrenheit(value);
            } else if (scale === 'C') {
                convertedValue = convertFahrenheitToCelsius(value);
            } else {
                throw new Error('Not a valid scale');
            }

            return label ? addDegreesSymbol(convertedValue) : convertedValue;
        };
    }

})();

Make sure that your tests are testing one thing!

This will fail if you changed your conversion functions. Maybe you want to add 1 decimal place in the future.

it('should append a % to the converted value', function() {
      expect(filter(37, 'F', true)).toEqual('99\u00B0');
});

Change to a matcher that looks for the degrees symbol

it('should append a degrees symbol to the converted value', function() {
     expect(filter(37, 'F', true)).toContain('\u00B0');
});

Lastly, the only acceptable values for the scale are F and C, should this be case sensitive?


Solving 'decent numbers' that follow specific division rules

At the heart of your problem you are trying to solve a single linear Diophantine equation. Because 3 and 5 are coprime, their greatest common divisor is 1, and hence your equation, \$3a + 5b = n\$, will always have an integer solution. It is easy to check that \$a = 7n\$, \$b = -4n\$ is indeed one such solution. Of course you want both \$a\$ and \$b\$ to be positive, so if we take the more general solution to your equation, \$a = 7n - 5k\$, \$b = -4n + 3k\$, and impose \$b \ge 0\$, we get \$k = \lceil 4n / 3 \rceil\$.

Let's put this into a Python function:

def partition35(n):
    k = (4*n - 1) // 3 + 1  # rounded up int division
    a = 21*n - 15*k  # (7*n - 5*k)*3
    b = 15*k - 20*n  # (3*k - 4*n)*5
    return a, b

Notice that there is a single division performed. Division and modulo operations are among the most expensive basic operations you can do on integers, so aside from the fact that this method is constant time, that time is likely going to be pretty small.

To solve your original question:

def max_decent(digits):
    a, b = partition35(digits)
    if a < 0:
        print(-1)
    else:
        print(''.join(('5'*a, '3'*b)))


Pointers and string reverse function implementation

indent your code. Indentation should normally reflect control flow:

char * reverse_string(const char *s1)
{
    int count = 0;
    char *output;
    char *o;
    while (*s1 != '\0')
        s1++;

    s1--;
    output = new char[strlen(s1)];
    o = output;

    while (*s1)
        *output++ = *s1--;

    if (*s1 == '\0')
        cout << "yes";
    return o;
}

int main()
{
    const char *s1 = "hello world";
    char *result;
    result = reverse_string(s1);
    cout << result;
}

When you're manipulating strings in C++, prefer std::string over pointers to char. Likewise, prefer standard algorithms to duplicating their functionality. Using std::string, and a standard algorithm, your core function can reduce to something like this:

std::string reverse_string(std::string in) {
    std::reverse(in.begin(), in.end());
    return in;
}

Prefer to initialize variables rather than creating them uninitialized, then assigning a value later. For example, this:

char *result;
result = reverse_string(s1);
cout<<result;

...would almost certainly be better off as:

 char *result = reverse_string(s1);

Avoid intermediate variables unless they actually contribute something useful. The sequence above would probably be just as well off being written as:

std::cout << reverse_string(s1);

Avoid using namespace std;. Although you don't actually show this in your code, using cout without std:: indicates that you probably have it elsewhere in your code. If you use this at all, you generally want to restrict it to a relatively small scope (but it's generally better to avoid it completely).
If you insist on allocating space for the string "by hand" (i.e., directly invoking new char[len], be sure to include enough space for the NUL terminator. Right now you have:

output = new char[strlen(s1)];

...which allocates space for the characters in the string, but no space for the zero-byte that signals the end of the string. Along with this, when you copy the data, you need to ensure that you put a zero-byte at the end of the result to signal where it ends. But, see point number 2 above--despite its (many) flaws, you're much better off using std::string, and avoiding this problem entirely.
A function should have a single intent. Right now, your reverse_string not only reverses its input, but also prints out "yes". This restricts that function to being using only under very specific circumstances. By strong preference, a function that reverses a string should do only that, without printing out anything (and the same applies in general, not just to this specific function).


Displaying TimeSpan as largest interval (with units) - Part II

Your code is looking good, but I find the control flow in this version a bit easier to follow:

// Defined per business rules.
private static readonly TimeSpan MinimumIntervalDeemedOneDay = TimeSpan.FromHours(22);
private static readonly TimeSpan MinimumIntervalDeemedOneHour = TimeSpan.FromMinutes(50);
private static readonly TimeSpan MinimumIntervalDeemedOneMinute = TimeSpan.FromSeconds(40);
private static readonly TimeSpan MinimumIntervalDeemedOneSecond = TimeSpan.FromMilliseconds(500);

public static string LargestIntervalWithUnits(TimeSpan interval)
{
    if (interval < TimeSpan.Zero)
    {
        throw new ArgumentOutOfRangeException("interval",
                                              "Negative Timespans are not supported.");
    }

    if (interval > MinimumIntervalDeemedOneDay)
    {
        return FormatTime(interval.TotalDays, "day");
    }

    if (interval > MinimumIntervalDeemedOneHour)
    {
        return FormatTime(interval.TotalHours, "hour");
    }

    if (interval > MinimumIntervalDeemedOneMinute)
    {
        return FormatTime(interval.TotalMinutes, "minute");
    }

    if (interval > MinimumIntervalDeemedOneSecond)
    {
        return FormatTime(interval.TotalSeconds, "second");
    }

    return "now";
}

private static string FormatTime(double value, string units)
{
    var ceiling = (int)Math.Ceiling(value);
    return string.Format("{0:#,##0} {1}{2}",
                         ceiling,
                         units,
                         (ceiling == 1 ? string.Empty : "s"));
}


Since throw interrupts the program flow, you don't need to provide an else branch. That way, you also visibly follow the good practice of using 'watchdogs':

<?php

include_once('config.php');
include_once(ROOT . 'libs/database.php');
include_once(ROOT . 'libs/models/user.php');

class Security
{

    //...

    public static function TryLogin($username, $password)
    {
        $username = strtolower($username);
        $password = sha1($password . $username);

        $conn = Database::getConnection();
        if (empty($conn)) {
            throw new Exception('The connection to the database failed.');
        }

        $result = odbc_exec($conn, '{CALL [BruPartsOrderDb].[dbo].[tryLogin]("' . $username . '", "' . $password . '")}');
        if (empty($result)) {
            throw new Exception('The execution of the query failed.');
        }

        $row = odbc_fetch_row($result);
        if (empty($row)) {
            throw new Exception('Username or password incorrect.');
        }

        if (session_id() == '') {
            session_start();
        }

        $_SESSION['user'] = new User(odbc_result($result, 'id'), $username);

        return true;
    }

    //...
}

Suddenly the code looks much more handy.


Comparing two integers without logical, relational or bitwise operators

That seems a fine solution. Some minor suggestions:

Instead of spelling out relationship as {'<', '=', '>'}, you could use simply "<=>"
Instead of printing a, the relation and b in separate statements, it will be more readable to print in a single printf
The expression !!(a/b) - !!(b/a) evaluates to -1, 0, 1, commonly returned by a cmp function. If you give the expression a name by putting it in a variable, that will ring a bell with many readers and make it easier to understand.

Something like this:

unsigned a, b;
scanf("%u %u", &a, &b);

int cmp = !!(a/b) - !!(b/a);
char relation = "<=>"[cmp + 1];
printf("%u %c %u\n", a, relation, b);


Removing exact instances of elements in one list from another

Additional to the valid point from Rick Davin:

1) You can drop the Contains because IndexOf returns -1 if the item is not contained.

2) You could use yield to get rid of the additional list

public static IEnumerable<T> ExceptExact<T>(this IEnumerable<T> source, IEnumerable<T> exceptions)
{
    var tExceptions = exceptions.ToList();

    foreach (var el in source)
    {
        var index = tExceptions.IndexOf(el);
        if (index >= 0)
        {
            tExceptions.RemoveAt(index);
            continue;
        }
        yield return el;
    }
}

After taking a look to MSDN (List.Remove), I figured out that there is even a simpler way:

  Removes the first occurrence of a specific object from the List.

  Returns true if item is successfully removed; otherwise, false.This method
  also returns false if item was not found in the List.

public static IEnumerable<T> ExceptExact<T>(this IEnumerable<T> source, IEnumerable<T> exceptions)
{
    var tExceptions = exceptions.ToList();
    return source.Where(el => !tExceptions.Remove(el));
}


Function for splitting an integer into smaller values

The first problem I see is that you're doing a right shift on a signed integer type (std::int32_t).

If a negative value is passed, the result will be implementation defined. When you're going to treat something as a collection of bits instead of treating the whole thing together as a number, you usually want to use an unsigned type, not signed.

I'd also prefer to get rid of the magic (and inter-related) numbers sprinkled throughout the code, such as the 8, 4 and the 0xf. These three are inter-related--the 8 being the number of 4-bit fields contained in a single 32-bit item, and 0xf being a mask with 4 bits set. I'd prefer to specify only one of these values in one place, and compute the others from that one.

As to the specific questions you've asked:

I don't think SplitValues does a good job of indicating a type. This has been a problem for a long time, and I don't think I have a silver bullet to finally put it to rest. In this case, I'd rather just avoid it completely (about which, more below).
If you pass a literal to a function instead of passing a variable, that literal will start with some type--in this case, since it's digits and can fit in an int, its type will be int. That will then be converted to the function's parameter type (std::int32_t). In this case, at least on a typical compiler where int is a 32-bit type, that "conversion" will really be a NOP because the source and target types are basically identical.

As to how to avoid the problem with having to define names, C++ has two mechanisms that can help quite a bit: templates (especially function templates) and auto. Both of these can deduce a result type based on input types, to avoid having to explicitly specify types throughout much of the code.

I'd also generally prefer to write splitter as a generic algorithm. While we're at it, its name should be changed from a noun to a verb. Non-functor classes should have nouns for names, but functors and functions do things, so their names should normally be verbs.

template <classs T, class OutIt>
void split(T number, OutIt result) {
    unsigned bits = 4;
    unsigned mask = (1<<bits) - 1;
    unsigned iter_count = sizeof(T) * CHAR_BIT / bits;

    for (unsigned i=0; i<iter_count; i++) {
        *result++ = number & mask;
        number >>= bits;
    }
}

This part is a little longer than the code in your answer, but most of that extra length stems from specifying the number of bits, then computing the mask and iteration count from that shift value instead of having interrelated magic numbers throughout.

With this code, we can change the type of the input (e.g., to a 64-bit unsigned long long) or the shift count (e.g., to 8 bits) independently of each other, without having to patch the rest of the code to compensate.

Although it's a rather minor point, all else being equal, I prefer to avoid creating variables with default values, then filling in the real values later. This is fairly innocuous when the values involved are at least initialized as they are in a vector, but it's still better to just initialize values when possible.

That leads us to the calling code. Since we changed the function to look like a standard algorithm, we need to change the calling code to suit.

int main() {
    std::deque<int> values;

    split(432214123, std::front_inserter(values));

    std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
}

Of course, there are a lot of other ways this job could be handled, but I guess that's enough for the moment anyway.


Even if Java and C++ display some similarities, particularly in the syntax, they are widely different languages and translating one into the other isn't automatic. Java is chiefly object-oriented, while C++ is more of a multi-paradigm language; one could even argue that it's drifting away from the object-oriented model towards a more functional approach designed to take advantage of compile-time customization and calculations.

So, it's best to take a step back and think again about your objectives and the means you have to achieve them when you transition from one to the other.

What you seem to need is a mapping between a unit, a textual representation and a floating precision proportion. Java allows for float based enums, which are thus a good candidate -even if the textual representation needs to be addressed somewhere else- but C++ doesn't. On the other hand, in the most recent version of the C++ standard, you can create and manipulate arrays at compile-time:

constexpr std::pair<std::string_view, float> weight_units[] {
    { "kg", 1. },
    { "lb", 0.45359237 },
    { "oz", 0.028349523125 },
};

constexpr auto weight_unit_value(std::string_view unit) {
    return std::find_if(std::begin(weight_units), std::end(weight_units), [unit](auto uv) {
        return uv.first == unit;
    })->second;
}

This code sadly compiles only with the latest version of clang, because gcc hasn't implemented the constexpr version of the standard algorithms yet. But writing it by hand would take 5 minutes. Or you can simply remove the constexpr qualifier.

This code has several advantages over the original Java version, the most important being that everything is defined once in one place. If you want to create a new unit in the original code, you need to modify the enum and create a new object with a custom name; here, you just extend the array.

Now, the array is also very handy if you want to parse a weight from a string, or convert a weight to a string:

// ex: float weight = parse_weight("1204.3 lb");
auto parse_weight(std::string_view weight) {
    auto coeff =  std::find_if(std::begin(weight_units), std::end(weight_units), [weight](auto uv) {
        return weight.ends_with(uv.first);
    })->second;
    return std::stof(weight.data()) * coeff;
}

auto to_string(float value, std::string_view unit_name) {
    auto result = std::to_string(value / weight_unit_value(unit_name));
    auto out = std::back_inserter(result);
    *out++ = ' ';
    std::copy(unit_name.begin(), unit_name.end(), out);
    return result;
}

Error handling could be added very easily (auto found = std::find_if(...); if (found == std::end(units)) throw unknown_unit("blabla");

Here's some code to toy with: https://wandbox.org/permlink/zj0hckfk6jR0vrXT


Implementing a queue using a linked-list

Having a separate queue structure

typedef struct {
    node * head;
    node * tail;
} queue;

will bring you several benefits:

Most important, enqueue would take a constant time (vs linear in queue length you have now).
The client would be relieved from responsibility to maintain the head node.
enqueue doesn't inform the client that it failed the allocation. fprintf is good for the human, but does nothing for the calling routine. Having the queue structure enables you to return an error code.

The specialized utility functions, like enqueue and dequeue should not print anything. They must communicate success/error to the caller, and let it act appropriately.
else in enqueue is redundant.
I don't see why do you #include <string.h>.


Three methods to serialize 7-, 6-, and 3-dimensional int arrays

An array in Java is an object, not a primitive, so you can accept the parameter as Object, without specializing it as an array (you do not do that in your current code either, so you do not lose anything by this approach). Yes, you lose some type safety this way, but you can get it back during runtime by using <argument array object>.getClass().isArray(). Overall, my approach is:
/**
* Serializes an array of arbitrary dimensions to a file
* @param array    the array to serialize
* @param filename the name of the file to serialize array to
* @throws IllegalArgumentException if array is not an array
* @throws IOException              if some error was encountered during serialization
*/
public void serializeArrayToFile(Object array, String filename) throws IOException {
    if(!array.getClass().isArray()){
        throw new IllegalArgumentException("Cannot serialize non-array object " + array.toString());
    }
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(filename));
    outputStream.writeObject(array);
}

And just in case you want this to be absolutely specific for only int arrays of arbitrary dimensions,
/**
* Serializes an array of arbitrary dimensions to a file
* @param array    the array to serialize
* @param filename the name of the file to serialize array to
* @throws IllegalArgumentException if array is not an int array
* @throws IOException              if some error was encountered during serialization
*/
public void serializeArrayToFile(Object array, String filename) throws IOException {
    Class<?> classOfArray = array.getClass();
    if(!classOfArray.isArray()){
        throw new IllegalArgumentException("Cannot serialize non-array object " + array.toString());
    }
    Class<?> componentType = classOfArray.getComponentType();
    if(!(componentType.isPrimitive() &&
         int.class.isAssignableFrom(componentType)) {
        // Can also be `UnsupportedOperationException1, depending on required semantics
        throw new IllegalArgumentException(String.format(
                                           "Serialization of non-`int` array %s of component type %s is not allowed",
                                            array.toString(), componentType.toString()));
    }
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(filename));
    outputStream.writeObject(array);
}

Note that a nice side-effect of this approach is that you can now serialize arrays of arbitrary dimensions!
Note the naming convention - I use serialize instead of send, as that is what you are actually doing. Although I do not do it here for purposes of compatibility with the existing project structure, you might consider making this method static as it does not depend on the implicit this.
Also, the first array.toString() isn't required, the string concatenation will do it implicitly, but in my policy for such cases, explicit is better than implicit.
Addendum
The OP asked in the comments as to how to determine the number of dimensions of an array if it has been casted to Object. This is possible via reflection, whether by descending the type hierarchy until the result of <array object>.getClass().isArray() is false (slow), or by counting the number of '[' characters in the result of <array object>.getClass().getName() (faster). I'll illustrate the second method, which has been suggested by @wizzwizz4 in the comments, as that is more practical in all respects (I do not consider it to be "hacky", as @wizzwizz4 does, as the result of getName() for the class of any array type is explicitly documented as here.
public static int getDimensionsOfArray(Object array) {
    return (int) array.getClass()
                                .getName()
                                .chars()
                                .filter(c -> c == '[')
                                .count();
}

I use Java 8 Streams here, but you could just as well do it with a loop (I like the declarative approach of using Streams, as my primary language is Scala). The cast to int exists because Stream.count() returns a long, as Streams are lazy and can theoretically hold an infinite number of elements.
References:
I referred to this StackOverflow answer for the array type verification code.


The above answer is fine.

The only problem I have is the extra ',' in the output:

std::cout << "[ ";
std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << " ]\n";

Generates the output:

[ 1, 2, 3, 4, 5, 6,  ]
                  ^  extra comma

You can get around this with some extra work.

auto end = data.end();
if (!data.empty()) { --end;}
std::cout << "[ ";
std::copy(data.begin(), end, std::ostream_iterator<int>(std::cout, ", "));
if (!data.empty()) {std::cout << *end;}
std::cout << " ]\n";

Generates the output:

[ 1, 2, 3, 4, 5, 6 ]

This is better but it sort of defeats the purpose of using algorithms.

If we had used the loop it would look like this:

std::cout << "[";
for(auto loop = data.begin(); loop != data.end(); ++loop)
{
     std::cout << *itr << ", ";
}
std::cout << "]";

Of course this has the same problem as the first version of the algorithm above. So if we take that into account you can re-write like this:

std::cout << "[";
auto begin = data.begin();
if (!data.empty) {std::cout << *begin;++begin}
for(auto loop = begin; loop != data.end(); ++loop)
{
     std::cout << ", " << *loop;
}
std::cout << "]";

Now it works. And because it only use one test on empty is better than the altered algorithm version in my opinion. So what we really need is a version of the output iterator that does the above.

template<typename T>
class PrefexOutputIterator
{
    std::ostream&       ostream;
    std::string         prefix;
    bool                first;
    public:

    typedef std::size_t                 difference_type;
    typedef T                           value_type;
    typedef T*                          pointer;
    typedef T                           reference;
    typedef std::output_iterator_tag    iterator_category;

        PrefexOutputIterator(std::ostream& o,std::string const& p = ""): ostream(o), prefix(p), first(true) {}

        PrefexOutputIterator& operator*()       {return *this;}
        PrefexOutputIterator& operator++()      {return *this;}
        PrefexOutputIterator& operator++(int)   {return *this;}

        void operator=(T const& value)
        {
            if (first)      {ostream << value;first = false;}
            else            {ostream << prefix << value;}
        }
};

Now we can use this and get the output we want:

std::cout << "[";
std::copy(data.begin(), data.end(), PrefexOutputIterator<int>(std::cout, ", "));
std::cout << "]";

The output is:

[1, 2, 3, 4, 5, 6]

Nowadays though I seem to be using a lot of Json.
So now I use this template librrys: https://github.com/Loki-Astari/ThorsSerializer

using ThorsAnvil::Serialize::jsonExport;
using ThorsAnvil::Serialize::jsonImport;

std::cout << jsonExport(data) << "\n"; // Serialize the array as json (looks like above)
std::cin  >> jsonImport(data);         // Reads a json array into an array.


Reading image files asynchronously and displaying them on the page

Don't use callbacks, it's hard to read and maintain, the fs.readdir function will return a promise if you didn't provide a callback function.
Use arrow functions when you could.
Respond with an error instead of throwing (unless you have a catch wrapper middleware).
Use property shorthands.
You forgot req and res.

Try this:

const express = require('express');
const router = express.Router();
const fs = require('fs');

router.get('/', async (req, res) => {
  try {
    const files = await fs.readdir('./assets/images/')
    res.render({ files })  // notice the property shorthand
  } catch (error) {
    res.status(404).json({ error })
  }
});

module.exports = router;


First to answer your specific questions:

  For storing one-dimensional data (arrays), is there usually a preference between column and row matrices?

It doesn't matter, use what is most convenient. Often horizontal vectors are used because they are easy to create: 1:10.

  Is there an easy way to deal with nested matrices?

The best way to collect matrices is using a cell array. A cell array's elements are arbitrary values (matrices, other cell arrays, objects, function handles, whatever you can assign to a variable).

  There are a ton of different ways to create matrices, and I'm not sure if the ones I am using are the most appropriate (e.g., via literals, find(), meshgrid(), ones() and zeros(), repmat(), etc.).

Yes, MATLAB has a huge library and it is impossible to know if you are using the best possible function in each case. Experience will help.

  What is there to do about arbitrary imprecision? For example, I had to put in an arbitrary value threshold to find non-zero values because using find(A > 0) wasn't working. (Since the values were on the magnitude of about 1e-12, this was larger than the value of eps() so that function didn't seem very helpful.)

Yes, you need to pick some threshold there. It depends on the source of the data what an appropriate value is. eps is the distance between 1.0 and the next representable floating-point value. That is, there are no possible values in between 1.0 and 1.0+eps. eps is not necessarily an appropriate threshold to find "approximately zero" values.

  Naming conventions -- is there one for MATLAB? I don't believe I've seen a consistent style.

Not that I know of. Early versions of MATLAB were not case sensitive, so all code was typically written in lower case. Currently some built-in functionality uses an upper case for the first letter, and some use camelCase. There is no PEP8 for MATLAB. :)

Now I'll go through the bits of code that can be improved:

clc;clear all;

Please use the MATLAB Editor, and heeds its warnings. clear all is not useful here, it not only clears variables, it also clears functions from memory. These will need to be read in and parsed again, slowing down your program. clear suffices to remove variables from your workspace.

posDps = data(find(y == 1), :);
negDps = data(find(y == -1), :);

Here you can remove find. The MATLAB Editor also warns about this.

posDps = data(y == 1, :);
negDps = data(y == -1, :);

find is usually not necessary when indexing, only when you need to store an index to an array element.

space = size(data, 2);
n = length(data);

It is always better to specify directly what size you need. length(data) is defined as max(size(data)), I consider this dangerous. Instead:

[n,space] = size(data);

or

space = size(data, 2);
n = size(data, 1);

You should also know numel, which returns the number of elements in a matrix. This is much more efficient than prod(size(data)).

[ y1, y2 ] = meshgrid(y, y);
[ i, j ] = meshgrid(1:n, 1:n);

These are not necessary at all. Since MATLAB R2016b we have implicit singleton expansion, but before that you could use bsxfun to operate on two arrays of different sizes. So none of the following indexing operations are really necessary.

P(i, j) = y1(i, j) .* y2(i, j) .* (data(i,:) * data(j,:)');

can be rewritten as

P = (y .* y.') .* (data * data.');

Note that I use .' here, where you had '. ' is the complex conjugate transpose. Unless you want to compute a dot product, you should avoid it. .' transposes the matrix without changing any of its values. For real-valued data they're the same, but it's good to get used to using the right form, it will prevent difficult to find errors down the road.

Aeq = y';

Same here: y.'.

beq = [ 0 ];

Again, the MATLAB Editor warns here about the useless [] brackets. Heed the warnings!

There is actually no difference in MATLAB between a matrix and a scalar. A scalar is a matrix with a single value. The [...] operator is for concatenation. It concatenates two or more matrices into a single matrix. Every time you have a single matrix inside [], the MATLAB Editor will warn you about it.

Similarly, I often see things like [1:10]. 1:10 is a matrix, the [] don't do anything there.

w = (data' .* repmat(y', [space 1])) * alpha;

Same here: data.', y.'.

svIndices = find(alpha > threshold);
b = y(svIndices(1)) - data(svIndices(1),:) * w;

Here you can use the second argument to find to tell it to give you only one index:

svIndex = find(alpha > threshold,1);
b = y(svIndex) - data(svIndex,:) * w;

domain = (min(data(:,1)) - margin):(max(data(:,1)) + margin);

You don't need this many parentheses here, but they don't hurt either. I actually think they help readability. But the : has a much lower precedence than + and -. This should also work:

domain = min(data(:,1))-margin : max(data(:,1))+margin;


Java code that takes user input of Zipcode and turns it into a bar code

My two cents:

I did not know about this system, so the methods don't tell me much. checkDigit calculates some kind of validation number? Perhaps name it something like calculateCheckDigit. Same for dBarCode.

Also, you only ever call checkDigit on zip once, and then keep on calling it on the checkDigit variable, although this one never changes? Could it be a bug?

Some other comments:

Close the scanner as soon as possible; it is also AutoCloseable, so you can use try-with-resources: try-with-resources
dBarCode can be implemented with a switch statement, an array of Strings or possibly a Map.
I'd extract the zip to barcode functionality of the main method, without the input/output, to a separate function

I think it is fine to leave the functions in one class, and leave them static.


The ruby style guide suggests to use 2 spaces per indentation level.
You can use heredocs for multi-line strings, keep in mind that they preserve white space, here is a nice trick that could be used:

help = <<-END.gsub(/^\s+\|/, '')
  |Should be used in the form:,
  |<invocation of name_gen.rb> | <ruby> name_gen_test.rb -d<delimiter>,
  |The delimiter MUST be specified in name_gen.rb and it MUST NOT be ``.
          END
help.each_line { |line| puts line }

for multiline blocks please use do...end instead of {...}:

individual_syllables.each_with_index do |from, index|
start[from] += 1 if index == 0
connections[from][individual_syllables[index + 1] || !!false] +=
end

I don't understand why you use !!false, since !!false == false. Also I don't think it is needed here.
Do not put a space between a method name and the opening parenthesis:

max_len = start.keys.inject (0)

Avoid nested ternary operators, it makes the code hard to understand.

((cur ? cur : '').length > memo) ? cur.length : memo
# becomes
cur ||= ''
[cur.length, memo].max


Compose valid subtractions using all digits from a set

first of all try use middlenumber as set. Than adding numbers no by extends but something as middlenumber.add(x < y - x and (x, y-x) or (y-x, x)). You have strange duplicates number
naive brute force algorithm use 9^6 checking as you mentioned
something better when you change to permutations (9!/3! checking). There example for simpler 3-digit version

from itertools import permutations

def permutations_solver():
    digits = set('987654321')
    numbers = (''.join(x) for x in permutations(digits, 6))
    for x in numbers:
        a = int(x[0 : 3])
        b = int(x[3 : 6])
        c = a - b
        if b > c and c > 0 and set(str(c) + x) == digits:
            yield a, b, c

print(len(list(permutations_solver())))

checking b > c and c > 0 and set(str(c) + x) == digits above still is very ineffective
you can try write iterator on digits, something as

"""           set('abcdefgh') == set('123456789') and set('zxyr') == set('01')
zxyr          abc < def (enough a < d)
 abc          z == 0
+def          x + a + d == g + 10 * z
----          y + b + e == h + 10 * x
 ghi          r + c + f == i + 10 * y
 zxy          r == 0 // it looks like logic programming problem
"""
from itertools import product

def digits_solver():
    column = [(x, a, d, (x + a + d) % 10, (x + a + d) // 10)
              for x, a, d in product(range(2), range(1, 10), range(1, 10))
              if len(set([a, d, (x + a + d) % 10])) == 3 and (x + a + d) % 10 != 0]
    first_column = [(x, a, d, g) for x, a, d, g, z in column if z == 0 and a < d]
    for x, a, d, g in first_column:
        second_column = [(y, b, e, h) for y, b, e, h, xx in column if xx == x and not set([a,d,g]) & set([b,e,h])]
        for y, b, e, h in second_column:
            third_column = [(r, c, f, i) for r, c, f, i, yy in column
                            if yy == y and not set([a,d,g,b,e,h]) & set([c,f,i]) and r == 0 ]
            for _, c, f, i  in third_column:
                yield (100 * g + 10 * h + i, 100 * d + 10 * e + f, 100 * a + 10 * b + c)

in above example for by for by for is bad idea, you can remove it by recursion. The code will be much less messy
if you want try 6-digits number, you can change check unique digits (using set at examples) to multiset (at python you can use Counter class from collections library to emulate it)


Sorting seems to be slower with 2 threads instead of 1

This looks like a case of GIL. For actual multiprocessing you should use the multiprocessing module.

  multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.


What I found out by simply taking the time the calculation takes, is that casting to Decimal is a very costly operation. Dropping that in certain places (see my code) brings down the overall runtime to ~ 30-40%.
Besides, the Leibnitz terms can easily be precomputed (another Best Practice of optimization) as the list will be comparatively short. Surprisingly, this does not save much.
Using a module method with a local name save some time as well (import xxx from this_module as local_name instead of using this_module.xxx multiple times).
In EulerAccelerate(), the loop variable i does not need to be of type Decimal which saves a lot. Replacing 2**(i+1) with a simple addition yields another (small) saving.
Stepping back from the code analysis, I think changing the algorithm from recursive to iterative would speed up the calculation a lot, much more than those micro-optimizations.
results on my notebook: maxdepth=24, accurate to 8 places: pi=3.1415926, runtime=10 s
    import functools
    from decimal import Decimal
    import time

    ## @functools.lru_cache(maxsize = 12800)
    def ndifference(n, depth):
        if depth == 0:
            return LT[n]  #   = 1.0/(2*n + 1)
        a = ndifference(n, depth-1)
        b = ndifference(n+1, depth-1)
        return (a - b)

    def EulerAccelerate(n):
        pi = 0
        ith_power_of_2 = 2                # 2**(i+1)
        for i in range(n):
            pi += Decimal(ndifference(0, i)) / ith_power_of_2
            ith_power_of_2 += ith_power_of_2
        return pi

    # ---------------------------------
    maxdepth = 24
    # create Leibnitz terms beforehand; LT is global
    LT = [(1.0/(2.0*i+1.0)) for i in range(maxdepth+1)]

    t = time.time()
    print 4 * EulerAccelerate(maxdepth)
    print time.time()-t


Discrete event simulation with variable intervals

Given the problem scope as I understand it (need to execute events in particular sequence, with ability to rearrange sequence at any point) I think the design seems clean and direct. I caveat that with: I don't know python, and I seem to be missing the part where you are ensuring sequence of your queue by the event's time member. I understand the event.time needs to be the sequencing key for your queue, or else the reschedule will have erratic behavior as self.time goes forward and backward if the queue isn't in order

The design wholesale seems clean though, to my eyes.


You said that only checked your code against the example on Codechef. But the example only has 5 frogs and 3 pairs! Running this tiny example won't tell you how your code will perform on the worst case, where there might be 100,000 frogs and 100,000 pairs.

So the first step is to make a test for the worst case. This is easily done, for example with a function like this:

from __future__ import print_function
import random

def frogv_test(N=10**5, P=10**5, file=None):
    """Make a test case with N frogs and P pairs; write it to file."""
    M = 10**9       # Maximum coordinate of frog
    K = 4 * M / N   # Make sure there are lots of "breaks"
    print(N, K, P, file=file)
    print(*(random.randrange(M) for _ in range(N)), file=file)
    for _ in range(P):
        print(*(1 + random.randrange(N) for _ in range(2)), file=file)

Let's see how your program performs on this test case:

$ time python2.7 cr56451.py < frogv.txt > /dev/null

real    0m48.012s
user    0m40.880s
sys     0m0.400s

48 seconds! That's bad, given that the time limit at Codechef is 1 second (and of course one would like to have a decent margin in case Codechef is running on slower hardware).

So, how can you speed it up? Well, the most important thing to look at is the time complexity of the algorithm. If you look at the structure of your code, you can see that you iterate over the pairs, and then for each pair, you iterate over the breaks:

for i in xrange(0,P):
    # ...
    for Break_Pt in Breaks:
        # ...

There are \$P\$ pairs, and there are \$O(N)\$ breaks: there might be a break between every two adjacent frogs. So the inner loop might have to be executed \$O(NP)\$ times! I put a counter in the inner loop, and sure enough, in this test case the inner loop was executed 60,897,434 times.

(That should be plenty for you to go on: I won't spoil the challenge for you by giving away the solution.)


Bash function to find contents of a file with a certain extension

You can use [[ .. ]] instead of [ .. ] to do tests.  The former is a bash builtin and saves a fork.

You don't need to eval anything since you're just building a couple of optional switches to grep.  Start with empty strings and populate variables or an array, and pass the result to an invocation of grep as variables.  This also avoids enumerating every possible combination of arguments (already 4 combos with 2 options -- that approach quickly becomes unsustainable).

There's no need to absorb searchTerm.  Just leave it in the arguments and pass all those to grep, which allows you to include grep switches too, like -i.

Use set +x to see what's going on.

Tying it all together:

findInFile() {
    :<<_comment_
        Function to be placed in bash profile
        Allows user to specify what contents of a file they are looking for
        in what file types and in what NOT file types
        Iterate over the number of scripts arugments
_comment_
    declare -a select
    while [[ "$#" -gt 0 ]]
    do
        if [[ $1 =~ ^(-ft|--fileTypes|-et|--excludeTypes)$ ]]
        then
            local type="$2"
            [[ "$type" == *,* ]] && type="{$type}"
            if [[ $1 == *-f* ]]
            then
                select+=( "--include=*$type" )
            else
                select+=( "--exclude=*$type" )
            fi
            shift 2
        else
            break
        fi
    done
    set -x
    grep -r ${select[@]} "$@" .
    { set +x; } 2>/dev/null
}

You can include long comments as here-docs piped to the null operator :.


Trailing semicolons

At many places there is a ; at the end of the line.
It's completely unnecessary in Python and you should remove those.

Appending to arrays

At several places you are appending values to arrays in a strange way, for example:

    datedict[val[0]] = datedict[val[0]] + [val[1]];

The common and shorter way to do this is using .append():

    datedict[val[0]].append(val[1])

Augmented assignment operator +=

Instead of:

l = l + 1

This is shorter and better:

l += 1

Use list comprehensions

Instead of:

datearr = []
for dat in daterange(mindate, today):
    datearr = datearr + [datedict[dat]]

You can use a list comprehension, a powerful feature of Python:

datearr = [datedict[dat] for dat in daterange(mindate, today)]


Your approach works well but it doesn't consider punctuation, for example:
@Test
public void testWordCount(){
    String str = "Hey — how are you?";

    assertEquals(4, wc.countWords(str)); // Fail
    assertEquals(4, wc.countWordsTokenizer(str)); // Fail
}

Also StringTokenizer is discouraged for new code. From the Javadoc:

StringTokenizer is a legacy class that is retained for compatibility
reasons although its use is discouraged in new code. It is recommended
that anyone seeking this functionality use the split method of
String or the java.util.regex package instead.

The split method accepts a regex as input. This is to split by non-words characters:
public int countWordsSplit(String str) {
    if (str == null || str.isEmpty()) {
        return 0;
    }
    return str.split("\\W+").length;
}

Test:
@Test
public void testWordCount(){
    String str = "Hey — how are you?\t\n";

    assertEquals(4, wc.countWords(str)); // Fail
    assertEquals(4, wc.countWordsTokenizer(str)); // Fail
    assertEquals(4, wc.countWordsSplit(str)); // Pass
}

Edge cases
wc.countWordsSplit("Bill's house"); // returns 3

wc.countWordsSplit("1 2"); // returns 2
wc.countWords("1 2"); // returns 2
wc.countWordsTokenizer("1 2"); // returns 2

// Letters with accents, umlaut etc.
// Other edge cases...

Considerations
It all depends on how you define what a "word" is in the context of your program.
Define what a word is by making some assumptions. Then find a solution that satisfies your requirements. This approach prevents you from having an over-complicated solution that your program doesn't need.
More info here
Many thanks to @RolandIllig for the helpful comments.


Work out largest prime factor of a number

There are many questions about Project Euler 3 on this site already.  The trick is to pick an algorithm that…

Reduces n whenever you find a factor, so that you don't need to consider factors anywhere near as large as 600851475143
Only finds prime factors, and never composite factors

from itertools import chain, count

def biggest_prime_factor(n):
    for f in chain([2], count(3, 2)):
        while n % f == 0:
            n //= f
            if f >= n ** 0.5:
                return f if n == 1 else n

print(biggest_prime_factor(600851475143))