Search files from large directory and sub-directories

//not used
        int lineNum = 0;

            //not used
            lineNum++;

So it's in your code because...?

stream = new FileInputStream(pathNames.get(i));

and then later...

String path = pathNames.get(i);

You could assign to string variable first, and then make the inputstream from the string variable.

    } catch (FileNotFoundException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchFieldException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    }

Use multi-catch:

    } catch (FileNotFoundException | IOException | IllegalArgumentException | NoSuchFieldException | SecurityException ex) {
        Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
    }

Some of these might be subclasses and thus require removing. But there's no need to have the same line of code 6 times.

        Field f = br.getClass().getDeclaredField("nChars");
        f.setAccessible(true);

This field is unused as well.

                String lines = "";
                for (int t = nextChar - 200; t < nextChar + 100; t++) {
                    lines += cb[t];
                }

Consider declaring a char[] variable and using System.arraycopy. Strings are immutable, so whatever performance benefit you had with ripping open the BufferedReader, you completely waste it and then some here. You can then put the char[] into a new String.

snippets.put(pathNames.get(i), lines);

Why declare path if you're not going to use it?

Also, why do you not continue; here? HashMap.put will override any previous value, so you're only gonna see the last snippet of a file.

        stream = new FileInputStream(pathNames.get(i));
        BufferedReader br = new BufferedReader(new    InputStreamReader(stream));

None of these are getting closed.

Since you've got a try in there anyway, why not use try-with-resources?

String path = pathNames.get(i);
BufferedReader br;
try(stream = new FileInputStream(path);
        br = new BufferedReader(new InputStreamReader(stream))){
    ...
}

It works something like that.

private ArrayList<String> pathNames = new ArrayList();
private HashMap<String, String> snippets = new HashMap<String, String>();

Your variable definitions don't program to interfaces, so any setter would have to accept ArrayList only which makes your code hard to use for anyone else. Also, use diamond type inference - let the compiler get the generics from the type definition.

                char[] cb = (char[]) chars.get(br);
                int nextChar = (Integer) ff.get(br);

These reflection calls; you make them every iteration, but you only need them if the search string is found. Move them down.

Lastly, you should consider finding a way to get rid of the reflection. It's making the code slow, ugly and dangerous.

"Cleaned" version (will probably not compile; check syntax around try-with-resources and the multi-catch):

private List<String> pathNames = new ArrayList<>();
private Map<String, String> snippets = new HashMap<>();

public HashMap readFiles(String search, String dirPath) {

    snippets.clear();
    InputStream stream = null;
    BufferedReader br = null;

    //Method to get all the files in main and sub folders
    listDirectory(dirPath);

    for (int i = 0; i < pathNames.size(); i++) {
        String path = pathNames.get(i);
        try (stream = new FileInputStream(path);
            br = new BufferedReader(new InputStreamReader(stream))){

            Field chars = br.getClass().getDeclaredField("cb");
            chars.setAccessible(true);

            Field ff = br.getClass().getDeclaredField("nextChar");
            ff.setAccessible(true);

            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains(search)) {
                    //Getting through to Java Source Code - uh oh
                    char[] cb = (char[]) chars.get(br);
                    int nextChar = (Integer) ff.get(br);
                    char[] charBuffer = new char[300];
                    System.arraycopy(cb, nextChar - 200, charBuffer, 0, 300);
                    snippets.put(path, new String(charBuffer));
                    continue;

                }
            }

        } catch (FileNotFoundException | IOException | IllegalArgumentException | NoSuchFieldException | SecurityException ex) {
            Logger.getLogger(FileRead.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return snippets;
}


Just, i don't understand why?

What's wrong with (for integer):

#include <iostream>
int main() {
    int input;
    std::cout << "Enter decimal number: ";
    std::cin >> std::dec >> input;
    std::cout << '\n' << std::oct << input << '\n';
}

And about your code:

Avoid using namespace std, it's a bad practice
Just main() isn't a valid prototype for the entry point, at least use `int main()
Define variables in the closest scope possible.
Try naming variable consistently
de=de/8; can be simplified to de /= 8;
floating point conversion is a bit more tricky than just doing what you do

Edit: After testing it (and correcting main() and) : Your code just doesn't work, even for an integer value

Enter decimal no :: (0)10 = (32767.)8
Enter decimal no :: (8)10 = (32776.)8
Enter decimal no :: (10)10 = (32779.)8

Test yourself


When we use std::begin() and std::end(), we should always consider whether we actually want to use begin() and end() of the type's namespace instead (argument-dependent lookup, aka ADL), with fallback to std:
using std::begin();
using std::end();
return c.insert(std::upper_bound(begin(c), end(c), item, comp),
                std::forward<T>(item));

When we're inserting to a sorted container such as std::set, we probably want to use the container's key_compare as default, rather than std::less<T>.  I suspect that will require splitting back into two functions again.


Did I overuse / underuse threading locks in my custom list class?

While it looked like at first glance that you were missing quite a few from the normal list methods:

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Inheriting from collections.MutableSequence takes care of most of them (by using internally the re-implemented methods instead of the C methods).

>>> l = ThreadSafeList([3, 2, 1, 1])

A few are still missing, though:

>>> l.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'ThreadSafeList' object has no attribute 'sort'

>>> l = l + [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'ThreadSafeList' and 'list'

>>> l = l + l
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'ThreadSafeList' and 'ThreadSafeList'

>>> l = l * 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'ThreadSafeList' and 'int'

Although, there seem to be work-arounds for all of them, if changing mutating and non-mutating is fine:

>>> l = ThreadSafeList(sorted(l))
>>> l.extend([1])
>>> l.extend(l)
>>> l = ThreadSafeList(list(l) * 3)

Note that there is no way to add these lists without mutating them.

Otherwise, I see only one style-issue:

The output of repr should ideally include the class, so that eval(repr(obj)) returns a copy of the instance. You can define it like this:

def __str__(self):
    return str(self._list)

def __repr__(self):
    return "{self.__class__.__name__}({self._list})".format(self=self)

The latter can be slightly simplified in Python 3.6, using f-strings:

def __repr__(self):
    return f"{self.__class__.__name__}({self._list})"


Print worksheets depending on checkbox. Slower than before

(Previous code had a different sub for each worksheet thus repeating the pagesetup code block multiple times.)

Was the previous code also working directly with Worksheet objects by any chance?

You're working with an array of strings / sheet names...

'called from printer icon on activesheet
If tabs = "" Then
    arr = Array(ActiveSheet.Name)

'called via checkbox from print menu
ElseIf tabs = "PrintAll" Then
    arr = Array("Summary", "Monthly CC Sum", "Div Sal Sum", "CC Sal Sum")
Else
    arr = Array(tabs)
End If

...and then creating worksheet objects as you iterate the array:

'loop through array to print each sheet
For i = 0 To UBound(tabArr)

    Set ws = Worksheets(tabArr(i))

Why not work with an array of Worksheet objects instead, and simply iterate that array?

If tabs = vbNullString then
    arr = Array(ActiveSheet)
ElseIf tabs = "PrintAll" then
    arr = Array(SummarySheet, MonthlySummary, DivSalSumSheet, CCSalSumSheet)
Else
    sheetNames = Split(tabs, ",")
    arrLength = UBound(sheetNames)
    ReDim arr(0 To arrLength)
    For i = 0 To arrLength
        arr(i) = ThisWorkbook.Worksheets(sheetNames(i))
    Next
End If

That's still brittle though - ideally you'd have the worksheet references themselves handy, ready to be passed to that goPrint method.

The goPrint method could then simply iterate the object array with a simple For Each:

For Each ws In tabArr

This code isn't ideal either; your previous code was also a little faster because it didn't need to check this condition:

    If .Name = "Summary" Then
        area = "PRNSUMMARY"
        title = "$1:$9"
    ElseIf .Name = "Monthly CC Sum" Then
        area = "PRNMONTHLYCCSUM"
        title = "$2:$16"
    ElseIf .Name = "Div Sal Sum" Then
        area = "PRNDIVSALSUM"
        title = ""
    ElseIf .Name = "CC Sal Sum" Then
        area = "PRNCCSALSUM"
        title = "$2:$16"
    End If

If the sheet name is CC Sal Sum then you accessed and compared the worksheet's name 4 times already. And if it's something else, ...you get whatever you get.

This would be a nice case for a Select Case statement:

Select Case .Name
    Case "Summary"
        '...
    Case "Monthly CC Sum"
        '...
    Case "Div Sal Sum"
        '...
    Case "CC Sal Sum"
        '...
    Case Else
        'handle unexpected input?
 End Select

At runtime, a Select Case block pretty much amounts to a conditional GoTo jump, which means no matter how many cases you have, you'll only ever evaluate the condition once.

A note about this:

' Close Form box
End

That's the big red "NUKE 'EM ALL" button. Sure, End will close the form box. But it will also end the macro. It's very very very rare that you actually need to do this.

Compare to:

'Close form box
Me.Hide

Is that comment even needed then?

Structurally, the main issue I'm seeing is that the code is relying on side-effects: the form calls setup, and then closes. What's setup doing then? Shouldn't it set things up for printing?

Oh, it does... but it's also calling goPrint - which is a side-effect that makes it much harder to write a test for the method and see if it works as intended. Everything is coupled, and the UI is running the show.

What if you flipped things around instead, and controlled things from the outside?

Sub PromptAndPrint()

    Dim model As New SelectionModel
    model.Selection = "PrintAll"

    Dim view As New SelectionForm
    Set view.ViewModel = model
    view.Show vbModal

    If view.IsCancelled Then Exit Sub

    ConfigurePageSetup model.SelectedWorksheets
    PrintSheets model.SelectedWorksheets

End Sub

That's right: the UI becomes nothing more than a presentation tool; the execution flow is controlled by the macro, not by the UI, and then you have some SelectionModel class responsible for encapsulating the data you want to pass around, and abstract away the sheet names -> worksheet objects transformation; you can test ConfigurePageSetup without wasting a sheet of paper, and you can test the whole SelectionModel functionality without even showing the UI, without configuring page setup and without wasting a sheet of paper: VBA is much more object-oriented than people generally want to admit.

Nitpicks:

Indentation isn't always consistent. Consider using VBE add-ins like the latest MZ-Tools or Rubberduck, which offer automatic indentation (disclaimer: I'm heavily involved in Rubberduck).
Member names don't follow common naming conventions. Use PascalCase, not camelCase, for public members; that's consistent with every single type library and object model available to VBA.

Also:

Consider using explicit access modifiers. Procedures are implicitly Public by default.
Consider using explicit parameter modifiers. Parameters are passed ByRef unless specified otherwise.
Consider extracting the margins to a user-defined type, or at least a few constants.
Consider removing the Call keyword, which is obsolete/useless (and then, remove the parentheses).
Consider using the zero-footprint vbNullString built-in constant, instead of an empty string literal that eats up a whole 2 bytes for no reason.


Typo

lenght is spelled length.

Magic numbers

What does 95 signify? You'll want to put this in a named #define or a const.

Allocation failure

After calling malloc, always check that you've been given a non-null pointer. Allocation failure does happen in real life.

Indentation

You'll want to run this through an autoformatter, because your if block has wonky indentation and needs more columns to the right.

Inaccessible statement

    return random_password;

    free(random_password);

This free will never be called; delete it.

Random

The larger conceptual problem with this program is that it uses a very cryptographically weak pseudorandom number generator. This is a large and fairly complex topic, so you'll need to do some reading, but asking for random data from an entropy-controlled system source will already be better than using C rand.

That aside: you aren't calling rand, you're calling random:

  The random() function uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately 16 * ((2^31) - 1).

It's probably not appropriate for cryptographic purposes. Have a read through this:

https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626


I can only speak to the JS code - which looks pretty good, by the way... except:

You're modifying the array you're folding. In fact, you're truncating it completely due to your use of shift. So your function has destructive side-effects. After the fold, you have your answer, but you've lost the question, so to speak.

I.e.,

var question = [2, 3, 7];
var answer = foldr(function (a, b) { return a * b; }, 0, input);

console.log(answer);   // => 42
console.log(question); // => [] ... oops

Hence it'd be better to do something like this, using slice(1) to get a copy of the array starting from index 1:

function foldl(func, initial, collection) { // not foldr (see below)
    if (collection.length === 0) {
        return initial;
    }
    initial = func(initial, collection[0]);
    return foldl(func, initial, collection.slice(1));
}

By the way: You'll see I've removed the semicolon after the if block - it's not necessary (JS just ignores it, as it does the semicolon after the function body). But I've inserted a semicolon after return initial inside the block. That semicolon isn't strictly necessary either, since JS will see the close-brace following it, and insert its own semicolon. But better to do it properly yourself.

You could also write the condition as simply if (!collection.length), and it could be considered idiomatic. But I prefer your current - strict and explicit - condition myself.

Lastly, I'd prefer the Node.js style of placing function arguments at the end, like foldr(initial, collection, func) only because it avoids the dangling arguments after an inline function. On the other hand, JavaScript itself favors putting function arguments first, as in the built-in Array.prototype.reduce function... it's a tough call (no pun intended).

Update: I hadn't even noticed, until I read your comment above, but yes, your function is actually foldl, not foldr. You're reducing the array from first to last (i.e. from the left). So the first value passed to func is the first element in the array. A foldr function would pass the values in reverse order. A real foldr function could be:

function foldr(func, initial, collection) { // for real this time
    if( collection.length > 1) {
        initial = foldr(func, initial, collection.slice(1));
    }
    return func(initial, collection[0]);
}

You can check the behavior like this:

var func = function (memo, value) {
    memo.push(value);
    return memo;
};

foldl(func, [], [1, 2, 3, 4]); // => [1, 2, 3, 4]
foldr(func, [], [1, 2, 3, 4]); // => [4, 3, 2, 1] (reversed!)

Update 2: While I'm at it, here's a more memory efficient solution, that doesn't use slice and thus doesn't create n-1 arrays along the way. A similar technique can be used for foldl

function foldr(func, memo, collection) {
    var l = collection.length - 1;
    function fold(offset) {
        if( offset < l ) {
            memo = fold(offset + 1);
        }
        return func(memo, collection[offset]);
    }
    return fold(0);
}

Of course, neither this nor the functions above actually check whether the input array is empty (of if it's even an array)... not that that's terribly difficult to do, but I've complicated things enough already, I think :)


Website Navigation Bar - Potential code soup

First, I'm not sold on your use of  as a header. You can assign an aria role=banner to it or replace it with the tag intended to be a . I understand you're using your logo as a navigation link (e.g. home), however, you still have to make the browser understand what your header is.

Working off your code:

judging from the css used in your code I'm assuming IE8 support isn't required

If you're going to use a  for an icon (I'm assuming your trying to avoid using a content image), I'd recommend using an svg instead, see Fiddle (this uses natural elements to specify header/nav). There are plenty of SVG Fallbacks for browsers that don't support SVG.

If you want to forgo using a "content" image I'd use pseudo elements :before or :after to place the icon, see Fiddle. (this uses aria roles to specify header/nav)

How I'd approach it:

Your setup is, for the most part, solid. However, I'd go about it a little differently. Check this Fiddle.
(disclaimer: I wrote this up while still intoxicated from the fourth, so apologize ahead of time as it could probably be written better)

HTML

Title

A

B

         Test

Logout

CSS

* {
    margin:0;
    padding:0}
*,
*:before,
*:after{
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box }

html,
body{
    height: 100%;
    max-height: 100%}
html{
    -ms-text-size-adjust: 100%;
    -webkit-font-smoothing: antialiased;
    -webkit-text-size-adjust: 100%;
    font-family: sans-serif;
    text-shadow: 1px 1px 1px rgba(0,0,0,.004)}
body{
    font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size:13px;
    font-size:.8125rem;
    background-color:white}
a{text-decoration:none}
.visuallyhidden{
  border:0;
  clip:rect(0,0,0,0);clip:rect(0000);
  height:1px;height:.0625rem;
  margin:-1px;margin:-.0625rem;
  overflow:hidden;
  padding:0;
  position:absolute;
  width:1px;width:.0625rem}
.header{
    background-color:#9B59B6;
    padding:0 1.5625rem}
.navigation{
    display:inline-block;
    padding-left:25px;
    width:calc(100% - 80px)}
.navbar{list-style:none}
.navbar li{
    display:inline-block;
    float:left;
    position:relative}
.navbar li a:before{
    content:'';
    width:16px; width:1rem;
    height:16px; height:1rem;
    position:absolute;
    top:50%;
    left:10px;
    margin-top:-8px;
    background:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0ZWQgYnkgSWNvTW9vbi5pbyAtLT4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KPGc+CjwvZz4KCTxwYXRoIGQ9Ik05LjczMiAxMC45OGMtMC4zNDUtMC4wNTUtMC4zNTMtMS4wMDUtMC4zNTMtMS4wMDVzMS4wMTUtMS4wMDUgMS4yMzYtMi4zNTZjMC41OTUgMCAwLjk2My0xLjQzNyAwLjM2OC0xLjk0MiAwLjAyNS0wLjUzMiAwLjc2NS00LjE3Ny0yLjk4Mi00LjE3N3MtMy4wMDcgMy42NDUtMi45ODIgNC4xNzdjLTAuNTk1IDAuNTA1LTAuMjI4IDEuOTQyIDAuMzY4IDEuOTQyIDAuMjIxIDEuMzUxIDEuMjM2IDIuMzU2IDEuMjM2IDIuMzU2cy0wLjAwOCAwLjk1LTAuMzUzIDEuMDA1Yy0xLjExMyAwLjE3Ny01LjI2OCAyLjAxMC01LjI2OCA0LjAyMGgxNGMwLTIuMDEwLTQuMTU1LTMuODQzLTUuMjY4LTQuMDIweiIgZmlsbD0iI2ZmZmZmZiI+PC9wYXRoPgo8L3N2Zz4K) no-repeat}
.navbar li:last-of-type{float:right}
.navbar li:last-of-type .dropdown:before{background:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0ZWQgYnkgSWNvTW9vbi5pbyAtLT4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KPGc+CjwvZz4KCTxwYXRoIGQ9Ik0xNC41OSA5LjUzNWMtMC44MzktMS40NTQtMC4zMzUtMy4zMTcgMS4xMjctNC4xNjRsLTEuNTcyLTIuNzIzYy0wLjQ0OSAwLjI2My0wLjk3MiAwLjQxNC0xLjUyOSAwLjQxNC0xLjY4IDAtMy4wNDItMS4zNzEtMy4wNDItMy4wNjJoLTMuMTQ1YzAuMDA0IDAuNTIyLTAuMTI2IDEuMDUxLTAuNDA2IDEuNTM1LTAuODM5IDEuNDU0LTIuNzA2IDEuOTQ4LTQuMTcgMS4xMDZsLTEuNTcyIDIuNzIzYzAuNDUzIDAuMjU3IDAuODQ1IDAuNjM0IDEuMTIzIDEuMTE3IDAuODM4IDEuNDUyIDAuMzM2IDMuMzExLTEuMTIgNC4xNmwxLjU3MiAyLjcyM2MwLjQ0OC0wLjI2MSAwLjk2Ny0wLjQxIDEuNTIyLTAuNDEgMS42NzUgMCAzLjAzMyAxLjM2MiAzLjA0MiAzLjA0NmgzLjE0NWMtMC4wMDEtMC41MTcgMC4xMjktMS4wNDAgMC40MDYtMS41MTkgMC44MzgtMS40NTIgMi43LTEuOTQ3IDQuMTYzLTEuMTFsMS41NzItMi43MjNjLTAuNDUtMC4yNTctMC44MzktMC42MzMtMS4xMTYtMS4xMTN6TTggMTEuMjRjLTEuNzg5IDAtMy4yNC0xLjQ1LTMuMjQtMy4yNHMxLjQ1LTMuMjQgMy4yNC0zLjI0YzEuNzg5IDAgMy4yNCAxLjQ1IDMuMjQgMy4yNHMtMS40NSAzLjI0LTMuMjQgMy4yNHoiIGZpbGw9IiNmZmZmZmYiPjwvcGF0aD4KPC9zdmc+Cg==) no-repeat}
.navbar li a{
    display:block;
    line-height:50px;
    padding-left:37px;
    padding-right:25px;
    vertical-align: middle;
    color:white}
.navbar:after,
.navbar:before{
  content:'';
  display:table}
.navbar:after {clear:both}

.submenu{display:none}
.navbar li:last-of-type:hover>.submenu{
    display:block;
    position:absolute;
    left:0;
    background-color:#9B59B6}
.submenu li{display:block}
.submenu li a:before{background:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0ZWQgYnkgSWNvTW9vbi5pbyAtLT4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KPGc+CjwvZz4KCTxwYXRoIGQ9Ik0xMiAxMHYtMmgtNXYtMmg1di0ybDMgM3pNMTEgOXY0aC01djNsLTYtM3YtMTNoMTF2NWgtMXYtNGgtOGw0IDJ2OWg0di0zeiIgZmlsbD0iI2ZmZmZmZiI+PC9wYXRoPgo8L3N2Zz4K) no-repeat}

edit/note
This won't work well for mobile, so I suggest you work media queries into the nav and use jQuery or equivalent to handle the drop-down functionality.


For the most part, your script is quite fine.

Taming the long lines

These blocks of code have some issues:

cd gmp && ./configure --enable-shared --enable-static --prefix=/usr/local >$LOGFILE 2>&1 && make >$LOGFILE 2>&1 && make check >$LOGFILE 2>&1 && make install >$LOGFILE 2>&1 && cd ..

Issues:

The first line is too long

It's easy to be lazy to scroll to the right
Code that's less visible, is more error-prone, easy to overlook something
Long lines are harder to edit in practice

Wrapping a bunch of commands in cd somewhere; ...; cd .. is error prone:
it's an extra mental burden to make sure that you'll end up in the right directory after the chain of commands, keeping in mind possible errors too.
As much as possible, it's good to look for alternatives.
Too much repetition of >$LOGFILE 2>&1

It would be better this way:

(
    cd gmp && \
        ./configure --enable-shared --enable-static --prefix=/usr/local && \
        make && make check && make install
) >$LOGFILE 2>&1

The (...) is a sub-shell,
so directory changes won't affect the enclosing script.
Once the sub-shell is finished,
you'll be back in the original directory.
Grouping commands like this (also with {...}) makes it easier to redirect all output.
I didn't break up the lines of make a b c,
because the line was already short enough,
and quite idiomatic that way.
The exit code after the (...) will be as you would expect,
the grouping won't affect it.

Do similarly for all the long lines.

Avoid changing directories in the middle of scripts.
When you must do, consider wrapping the relevant commands within (...).

Simplifying the exit code handling

The exit code handling can be simpler:

ret="$?"
errorIf gmp $ret
echo "gmp Installed!:)"

There's no need to save $? in ret.
You could use it directly.
In fact, the function can use it directly,
no need to pass it explicitly.
You can rewrite the errorIf function like this:

errorIf() {
    if [ $? -ne 0 ]; then
        echo "Something was wrong with $1"
        exit 1
    fi
}

And then simplify the exit code handling to this:

errorIf gmp
echo "gmp Installed!:)"

ShellCheck

The http://www.shellcheck.net/# website is pretty awesome.
It points out a few additional issues I recommend to fix.


I was solving this problem at Pramp and I have trouble figuring out the algorithm for this problem.

On the contrary, you've done a very good job of coming up with a solution. There are ways to improve it though.

As you note, this is just the Longest Common Subsequence problem in a thin disguise.  The "deletion distance" between two strings is just the total length of the strings minus twice the length of the LCS.

That is, the LCS of dogs (4 characters) and frogs (5 characters) is ogs (3 characters), so the deletion distance is (4 + 5) - 2 * 3 = 3.

Therefore, all you need to do to solve the problem is to get the length of the LCS, so let's solve that problem.

Your solution is pretty good but the primary problem is that it takes O(mn) time and memory if the strings are of length m and n.  You can improve this.

The first thing to notice is that if the strings have a common prefix or suffix then you can automatically eliminate it.  That is, the deletion distance for Who let the big dogs out? and Who let the little frogs out? is the same as the deletion distance for big d and little fr. It is very cheap and easy to determine if two strings have a common prefix and suffix, and you go from having an array with 25*29 elements to an array with 5*9 elements, a huge win.

The next thing to notice is: you build the entire m*n array up front, but while you are filling in the array, m[i][j] only ever looks at m[i-1][j-1] or m[i-1][j] or m[i][j-1]. Since you never look at an array line that is two away, you don't ever need more than two lines! That is, you can:

allocate and compute the first line
allocate and compute the second line given the first line
throw away the first line; we'll never use it again
allocate and compute the third line from the second line
throw away the second line
… and so on

You still do O(mn) operations, and you still allocate in total the same amount of memory, but you only have a small amount of it in memory at the same time.  If the strings are large, that's a considerable savings.


Find largest binary gap of a number N improved

If I were in a position to be unaware of them and this is the code I
  managed to write, what's your thoughts on it?

No need to call ToCharArray() because you can iterate over the chars of a string as well
By using an else if instead of the second if you won't need to check for toChar[i] == '0' but basically you only need a else.
Using a foreach loop instead of a for loop seems more natural for this task.
The returning of the answer can be simply return answer;
Because ToString(int, 2) strips leading '0' you can remove both current and previous.

Summing up it could look like so

public static int FindGap(int number)
{
    int maxGap = 0;
    int answer = 0;

    foreach(var c in Convert.ToString(number, 2))
    {
        if (c == '1')
        {
            if (answer < maxGap)
            {
                answer = maxGap;
            }
            maxGap = 0;
        }
        else
        {
            maxGap++;
        }
    }
    return answer;
}


Does my algorithm already have a name?

It's called counting sort.

  What are the downsides to it? (Other than it is really stupid to sort { 900000, 1 } with it.)

That's exactly the major disadvantage of the algorithm: it doesn't work well if the range of values is large.

  Why is it not a good solution in general?

Because it can sort only integers. You can't use it to sort floating point numbers, strings or any other type that doesn't behave as an integer.

  Any suggestions for optimization?

The condition if (tempArr[j] != 0) is completely useless. If you leave it out, the code will work exactly the same.


In addition to the below, I recommend reading Maarten Fabré's answer.

Edge case

Consider the following scenario:

book_tracking = StudentDatabase()
book_tracking.return_book("Student A", "Moby Dick")
# KeyError: 'Student A'

However, we don't need to do a try-except block to catch the student who never handled books before trying to return a book; Python provides defaultdict in the collections module to help us with this very problem:

from collections import defaultdict

class StudentDatabase:
    def __init__(self):
        self._books = defaultdict(list)

    # ...

Now, if anything tries to access an unassigned key of _books, it will simply return an empty list. This can subsequently simplify borrow_book():

    def borrow_book(self, name, book):
        self._books[name].append(book)

Interclass operability

Library and StudentDatabase don't seem to interact at all. If they're related, the student database listing book borrows should inform the library when a book is borrowed or returned. The most versatile way to do this at this stage is to add a library parameter to relevant methods.

class StudentDatabase:
    # ...

    def borrow_book(self, name, book, library):
        if library.lend_book(book):
            self._books[name].append(book)

    def return_book(self, name, book, library):
        if book not in self._books[name]:
            print("You don't seem to have borrowed \"%s\"" % book)
        else:
            library.add_book(book)
            self._books[name].remove(book)

This will require returning False when the book is not found:

class Library:

    # ...

    def lend_book(self, requested_book):
        if requested_book in self._books:
            print("You have now borrowed \"%s\" " % requested_book)
            self._books.remove(requested_book)
            return True

        else:
            print("Sorry, \"%s\" is not there in our library at the moment" % requested_book)
            return False

The implementation you currently have is very simple, so there's not much else to discuss in terms of design: it becomes more relevant when you have more moving parts. I do find it somewhat odd that it's only tracking by student, and not by book (i.e. Library could know how many copies of each book it had (int), to whom it's checked (a list perhaps with a custom CheckedOut class to store the person and the due date), and any other information pertaining to that book. A BookStatus class could store everything related to each book; the library would then contain a list of BookStatus objects.

Checking if a sequence is empty.

(Note I previously advocated using len(self._books) > 0 until Maarten Fabré (along with three people upvoting his comment) pointed out this suggestion contradicted PEP-8) The relevant passage is excerpted below.

  For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Format string literals

You seem to be using printf-style string formatting. In Python 3, format strings are more flexible and would probably be considered more Pythonic. Python 3.6 adds format string literals, which are very compact. Here are some example uses:

Original: "You have now borrowed \"%s\" " % requested_book

With f-string: f"You have now borrowed \"{requested_book}\"."

Original: "Sorry, \"%s\" is not there in our library at the moment" % requested_book

With f-string: f"Sorry, \"{requested_book}\" is not there in our library at the moment"

Original: "You don't seem to have borrowed \"%s\"" % book

With f-string: f"You don't seem to have borrowed \"{book}\""

Original: "%s: %s" % (name, books)

With f-string: f"{name}: {books}"

Result

from collections import defaultdict

class Library:
    def __init__(self):
        self._books = []

    def add_book(self, new_book):
        self._books.append(new_book)

    def display_books(self):
        if len(self._books) > 0:
            print("The books we have made available in our library are:\n")
            for book in self._books:
                print(book)
        else:
            print("Sorry, we have no books available in the library at the moment")

    def lend_book(self, requested_book):
        if requested_book in self._books:
            print(f"You have now borrowed \"{requested_book}\".")
            self._books.remove(requested_book)
            return True

        else:
            print(f"Sorry, \"{requested_book}\" is not there in our library at the moment")
            return False

class StudentDatabase:
    def __init__(self):
        self._books = defaultdict(list)

    def get_student(self, name):
        if name not in self._books:
            return "Not Found"

        return self._books[name]

    def borrow_book(self, name, book, library):
        if library.lend_book(book):
            self._books[name].append(book)

    def return_book(self, name, book, library):
        if book not in self._books[name]:
            print(f"You don't seem to have borrowed \"{book}\"")
        else:
            library.add_book(book)
            self._books[name].remove(book)

    def display_students_with_books(self):
        for name, books in self._books.items():
            if books:
                print(f"{name}: {books}")


Variable usage

Assign cmdargs once, and get it right the first time.  Put a more insightful comment there.  Rename it to cmd_args for readability.

# Skip argv[0], which is the name of this program
cmd_args = sys.argv[1:]

The total variable is never used.

The variable name case is not descriptive enough.  Naming a variable temp is almost always a bad idea as well.  I suggest names like arg_len and decoded_value, respectively.

tolerances is a constant, and should be named TOLERANCES by convention.  Format it using one entry per line for readability.

Decoding technique

It is good practice to separate your calculations from your output routines.  Start by defining a function decode_capacitance(code):

def decode_capacitance(code):
    '''
    Decodes the capacitance as a (value, tolerance) pair.
    The value is a float representing the nominal number of picofarads.
    The tolerance is a free-form string, and may be None.
    '''
    code_length = len(code)
    if code_length == 2:
        return float(code), None
    elif code_length == 3:
        return float(code[:2]) * 10 ** int(arg[2:]), None
    elif code_length == 4:
        return float(code[:2]) * 10 ** int(arg[2:3]), TOLERANCES[code[3:].upper()]

In Python, it is idiomatic to write if conditions without parentheses.

However, there is a lot of redundancy there, and not much insight either.  An improvement would be:

def decode_capacitance(code):
    '''(Same docstring)'''
    base_pF, scale, tol = float(code[0:2]), int(code[2:3] or 0), code[3:4]
    multiplier = 10 ** scale
    return base_pF * multiplier, TOLERANCES.get(tol.upper())

You fail to interpret the third digit properly.  If the third digit is 8 or 9, it is supposed to be interpreted as a multiplier of 0.01 or 0.1, respectively.  To fix that, change the middle line to:

    multiplier = 10 ** (scale if scale <= 5 else scale - 10)

As @vnp noted, you have no validation or error handling (and I haven't added any for you).

Formatting technique

Define another function to display the capacitance and tolerance in the desired format.

It would be nice, I think, to automatically select the most natural units.

The standard symbol for the farad is F — a capital letter.

Putting it all together

With the appropriate functions defined, the main loop is quite simple.  Print results as you go; there's no need to store results.

import sys

TOLERANCES = {
    'B': '.10%',
    'C': '.25%',
    'D': '.5%',
    'E': '.5%',
    'F': '1%',
    'G': '2%',
    'H': '3%',
    'J': '5%',
    'K': '10%',
    'M': '20%',
    'N': '.05%',
    'P': '+100% to 0%',
    'Z': '+80% to -20%',
}

def decode_capacitance(code):
    '''
    Decodes the capacitance as a (value, tolerance) pair.
    The value is a float representing the nominal number of picofarads.
    The tolerance is a free-form string, and may be None.
    '''
    base_pF, scale, tol = float(code[0:2]), int(code[2:3] or 0), code[3:4]
    multiplier = 10 ** int(scale if scale <= 5 else scale - 10)
    return base_pF * multiplier, TOLERANCES.get(tol.upper())

def format_capacitance(pF, tolerance):
    if pF > 1000000:
        mantissa, unit = pF / 1000000, 'uF'
    else:
        mantissa, unit = pF, 'pF'

    output = '{} {}'.format(mantissa, unit)
    if tolerance is not None:
        output += ', ' + tolerance + ' tolerance'
    return output

# Skip argv[0], which is the name of this program
cmd_args = sys.argv[1:]

# Cycle through passed arguments and decode each capacitor
for arg in cmd_args:
    print('{} = {}'.format(arg, format_capacitance(*decode_capacitance(arg))))


Replace first occurrence of pattern in file

I think you have the error codes the other way around.  It's more common to return 0 on success and 1 (or any non-zero number) on failure, especially for debugging. If you actually need to deviate from this, then comments could help with specification.

As for the goto, it is good to avoid using it whenever possible.  Based on that little snippet, it looks like you could've used a function instead, at least if other this were needed in other places.


FrameworkPack is not a factory.
Business declares methods that automatically are public, remove the word public.
BusinessImpl looks like a ReadOnly-Class, declare the fields as final.
If FrameworkPack shall never be instanicated, create a private Constructor and make the class final so noone is able to create a instance.

You can use the Abstract-Factory and Singleton- pattern by ease.

public interface Framework {
    Business newBusiness(String name, String address, String city,
                         String zipcode, String origKey);
    Inspection newInspection(String origKey, String businessOrigKey,
                             String score, String date);
}
public interface Business {
    String getName();
    String getAddress();
    String getCity();
    String getZipcode();
    String getOrigKey();
}
public final class FrameworkPack implements Framework {
    private FrameworkPack(){};
    private static final FrameworkPack INSTANCE;
    public static final FrameworkPack getInstance(){
        if (INSTANCE==null) {
           ensureExistingInstance();
        }
        return INSTANCE;
    }
    private synchronized void ensureExistingInstance(){
       if(INSTANCE==null){
         INSTANCE = new FrameworkPack();
       }
    }

    public BusinessImpl newBusiness(String name, String address, String city,
                         String zipcode, String origKey){
      return new BusinessPack(name, address, city, zipcode, origKey);
    }
    ...
}
public final class BusinessPack {
    private final String name;
    private final String address;
    private final String city;
    private final String zipCode;
    private final String origKey;
    BusinessPack(String name, String address, String city,
                         String zipcode, String origKey) {
      this.name = name;
      this.address = address;
      this.city = city;
      this.zipcode = zipcode;
      this.origKey = origKey;
    }
    ...
}


Algorithm for Run Length Encoding - String Compression

You can eliminate that function prototype by defining main() last, but it's up to you.
It's more common to first check the command line usage and then exit with a non-zero value if it's invalid.  You should also print all errors to stderr, not stdout (the latter is always used with printf()).

if (argc != 2)
{
    fprintf(stderr, "Not correct number of inputs.");
    return -1;
}

You can probably check str right at the start, especially with the len assignment.  If there is an error, then it may be clearer to return NULL instead of 0.  At least that's what many library functions return specifically.
The while loop can instead be a for loop:

for (; str[i] == str[i+1]; i++)
{
    //to store number in char array, add the asci value
    // of 0.
    result[j] = (++counter + '0');
}

The NULL character for result is wrong; it should be '\0'.
There's actually no need to cast the return type of malloc() in C.  Although malloc() does return a void*, it's not required because any pointer type can be assigned to a void* and is done "automatically" here.

Moreover, you can avoid that aforementioned error by allocating result after making sure that the original string is valid.  This will also avoid the need to call strcpy() at the end and risk other bugs.  Since result will not be local this way, you can return it from the function without losing the data.

char* compress(char* str)
{
    // check to make sure str is valid...

    // assuming len is also valid
    char* result = malloc(len);

    // OR, use calloc() instead to get the memory zeroed
    //   thus no need for memset() or anything else
    char* result = calloc(len, sizeof(char));

    // probably also good to check for sufficient memory
    // if insufficient, print error and abort
    if (!result)
    {
        perror("malloc"); // or "calloc"
        abort();
    }

    // do the compression...

    // return it right away; no need to copy anything
    return result;
}

You never call free() on str1, so this function leaks memory.  You would have to do this in main() with the returned string, and it may be necessary to assign compress() to a const char* to display before freeing afterward.  This also means that compress() should return a const char*, not a char*, preventing it from being modified further.

It may work to have something like this in main():

int main(int argc, char** argv)
{
    if (argc != 2)
    {
        // let the user know of the correct input
        fprintf(stderr, "usage: %s string\n", argv[0]);
        return -1;
    }

    const char* original = argv[1];
    const char* compressed = compress(original);

    printf("The compression of %s is %s \n", original, compressed);

    free(compressed);
}


Whether to use React.Fragment or not depends on how you want the resulting DOM structured. Using React.Fragment avoids introducing additional elements in the DOM when they are not needed.

Fragments were introduced because only one React element can be returned from the render function, but it is pretty common and natural to need to return more than one element. Before Fragments, we had to wrap these elements in a div or other tag that really served no other purpose than to please React. This worked most of the time, but there were cases where it was not sufficient, such as when a component needed to return two tr elements. Wrapping tr's in a div and trying to place that in a tbody doesn't work. With Fragments, multiple elements can be returned and React does not have to render anything for the Fragment itself, only the children of the Fragment.

That being said, there are some situations where wrapping elements in a div or other tag makes sense. One that comes up frequently for me is when I have a component just like your products example, but I want to apply a margin, padding, border, or other style to the wrapper around the actual children. In that case, React.Fragment can't help me and I need a div or section.

A general rule-of-thumb, if you have a div or section that is doing absolutely nothing but letting you return multiple elements, you should switch it out with React.Fragment. If you are using that wrapper div in any way, keep it.

If you haven't yet, I would suggest reading the official Fragments guide. It demonstrates the table situation as an example for why Fragments were introduced.


Method for gathering the correct data to a specific user

Some notes:

Use local variables for values that are used many times.
time = Time.zone.now: This local variable prevents race conditions from occurring if the day changed in the middle of the method (unlikely, but why risk it?).
All those methods you are calling on a Time object are also available on Date. This will simplify your code.
You can send the time/date as (an optional) argument so the method works for any moment of the year (also, it will be easier to test).
time.strftime("%V").to_i is ok, but there is a better way:  Date#cweek.
There are some ways to build arrays with conditional items. I like this functional pattern: values = [value1, (value2 if condition), value3].compact.

I'd write:

def questions_for_week(date: Time.zone.today)
  frequencies = questions.frequencies
  week = date.cweek
  [
    frequencies[:weekly],
    frequencies[week.odd? ? :odd_weeks : :even_weeks],
    (frequencies[:start_of_month] if week == date.beginning_of_month.cweek),
    (frequencies[:end_of_month] if week == date.end_of_month.cweek),
    (frequencies[:start_of_quarter] if week == date.beginning_of_quarter.cweek),
    (frequencies[:end_of_quarter] if week == date.end_of_quarter.cweek),
  ].compact
end


PHP - check if array includes value and return value if true

Your function checks if an array contains a string that contains your given $needle. No, there's no such function in PHP yet. The in_array() function does something else.

You could make your function more efficient if you include the explode() inside the function, like this:

function find_parameters($needle, $parameterStr)
{
    if (strpos($parameterStr, $needle) !== false) {
        $result = [];
        foreach(explode(";", $parameterStr) as $parameter) {
            if (strpos($parameter, $needle) !== false) {
                $result[] = $parameter;
            }
        }
        return $result;
    }
    return false;
}

This function first checks whether the parameter string actually does contain the needle. It can quickly return false when it doesn't. If the needle is present it does what your code does, with the exception that it returns an array. This is done so that it can return multiple results. Suppose your parameter string looks like this:

$params = "colorgroup-a;colorgroup-b;test;abc";

and you test this:

var_dump(find_parameters("colorgroup", $paramsArr));

Then it will not return only colorgroup-a, like your function, but it will return an array with colorgroup-a and colorgroup-b.

So this new function is more efficient, when there are no matching parameters, and it is more correct in that it finds all the parameters.

Yes, it is longer, but shortness of code should not be the main aim when writing code. The use of regular expressions is also very popular for these kind of tasks, and it would result in less code. But the engine behind regular expressions is complex, and would make the code a lot less efficient.


You can use multiline sting """ and string.format

try:
    if title and url:
        sql_query = """
        INSERT INTO news (
        title, author, description, content, url, url_to_image, source_id,
        source, campaign, published_at, score, magnitude, sentiment, inserted_at
         ) VALUES (
         '{title}','{author}','{description}','{content}', '{url}',
         '{url_to_image}','{source_id}','{source}', '{campaign}',
         '{published_at}', {score}, {magnitude}, '{sentiment}', '{DB_NOW}'
         )
        """.format(
            title=title.replace("'", "''"),
            author=author.replace("'", "''"),
            description=description.replace("'", "''"),
            content=content[: settings.content_size].replace("'", "''"),
            url=url,
            url_to_image=url_to_image,
            source_id=source_id,
            source=source,
            campaign=campaign,
            published_at=published_at,
            score=score,
            magnitude=magnitude,
            sentiment=sentiment,
            DB_NOW=DB_NOW,
        )

        db = Db.Db()
        db.initialize(dsn=settings.SQLALCHEMY_DSN)
        return db.insert_content(sql_query, "news_id")
except psycopg2.ProgrammingError as exception:
    log.exception(exception)`enter code here`

If you'd use python 3.6+, you could even simpler use f-strings

string interpolation

As noted by @Ludisposed, string interpolation is not the way to go link
Since it is unclear what the Db.Db is, I assume it is something you wrote yourself. You will have to adapt the insert_content code to accept the arguments, and then do something like this:

try:
    if title and url:
        sql_query = """
        INSERT INTO news (
        title, author, description, content, url, url_to_image, source_id,
        source, campaign, published_at, score, magnitude, sentiment, inserted_at
         ) VALUES (
         %(title)s,%(author)s,%(description)s,%(content)s, %(url)s,
         %(url_to_image)s,%(source_id)s,%(source)s, %(campaign)s,
         %(published_at)s, %(score)s, %(magnitude)s, %(sentiment)s, %(DB_NOW)s
         )
        """
        arguments = dict(
            title=title,
            author=author,
            description=description,
            content=content[: settings.content_size],
            url=url,
            url_to_image=url_to_image,
            source_id=source_id,
            source=source,
            campaign=campaign,
            published_at=published_at,
            score=score,
            magnitude=magnitude,
            sentiment=sentiment,
            DB_NOW=DB_NOW,
        )

        db = Db.Db()
        db.initialize(dsn=settings.SQLALCHEMY_DSN)
        return db.insert_content(sql_query, arguments, "news_id")
except psycopg2.ProgrammingError as exception:
    log.exception(exception)


Unique nucleotide permutations, Python itertools product

To get the best performance depends on what you want.
If you want to only write to the file you should use maths.
If you want to generate them all, well that's almost the best you'll get.

And so if you want to do the latter I'd remove all of the former from the function.
And just create:

def data_count(data, dethp):
    translation = str.maketrans(data, data[::-1])
    for number in range(1, int(depth)+1):
        for product in itertools.product(data, repeat=number):
            product = ''.join(product)
            yield product, product[::-1].translate(translation)

The other bit is a little harder.
What you want to do is find a common factor.
For repeat=2, we get the bullet points in your question.
And so we should we should group them, there's:

Groups that add to seen.
Groups that aren't counted due to seen.
Groups that are the same both sides.

# group 1
('AA', 'TT')
('AC', 'GT')
('AG', 'CT')
('CA', 'TG')
('CC', 'GG')
('GA', 'TC')

# group 2
('TT', 'AA')
('GT', 'AC')
('CT', 'AG')
('TG', 'CA')
('GG', 'CC')
('TC', 'GA')

# group 3
('TA', 'TA')
('GC', 'GC')
('CG', 'CG')
('AT', 'AT')

We can then use the above function to find out more about these groups.
And so we can get the following table:

1 + 2 + 3   | 1 + 3     | 3
------------+-----------+-----
4           | 2         | 0
16          | 10        | 4
64          | 32        | 0
256         | 136       | 16
1024        | 512       | 0
4096        | 2080      | 64
16384       | 8192      | 0
65536       | 32896     | 256
262144      | 131072    | 0
1048576     | 524800    | 1024
4194304     | 2097152   | 0
16777216    | 8390656   | 4096

From this we can see that 1 + 3 is the same as (1 + 2 + 3 + 3) // 2.
We can also find a pattern for 1 + 2 + 3 and for 3.
The first number is \$4 ^ \text{num}\$. The second is almost \$2 ^ \text{num}\$.
And so we can use this to find 1 + 3:

def data_count(depth):
    for n in range(1, int(depth)+1):
        yield n, (4 ** n + (0 if n % 2 else 2 ** n)) // 2

But if you want both, then you should use both functions.


I would add some checks to make sure the date is correct. For instance your start date is on a Saturday.

-- Updated from comment that task doesn't need to start during working times.

if (startTime.TotalDays > 1)
{
    throw new ArgumentOutOfRangeException("startTime", "Start time greater than 24 hours");
}
if (endTime.TotalDays > 1)
{
    throw new ArgumentOutOfRangeException("endTime", "End time greater than 24 hours");
}
if (endTime < startTime)
{
    throw new ArgumentOutOfRangeException("endTime", "End time before start time");
}

For the logic you don't need to do a loop.

var numberOfDaystoStart = 0;
if (startOfTask.DayOfWeek == DayOfWeek.Saturday)
{
    numberOfDaystoStart = 2;
}
else if (startOfTask.DayOfWeek == DayOfWeek.Sunday)
{
    numberOfDaystoStart = 1;
}
else if (startOfTask.TimeOfDay > endTime)
{
    // Start time after the end of the work day need to move to the next day
    numberOfDaystoStart = 1;
}

var startOffset = TimeSpan.Zero;
if (numberOfDaystoStart > 0 || startOfTask.TimeOfDay < startTime)
{
    // IF started on weekend or after work hours adjust for first work day and start of working hours
    var startOfTaskDate = startOfTask.AddDays(numberOfDaystoStart);
    startOffset =
        new DateTime(startOfTaskDate.Year, startOfTaskDate.Month, startOfTaskDate.Day,
            startTime.Hours, startTime.Minutes, startTime.Seconds, startTime.Milliseconds) - startOfTask;
}

var workingtime = endTime.Subtract(startTime);
var nonWorkingTime = TimeSpan.FromDays(1) - workingtime;

// This will give long from C#
var numbersOfDays = durationOftask.Ticks/workingtime.Ticks;

// add in the duration then add in the extra time for non work hours
// add in the weekends
var endOfTask = startOfTask
    .Add(durationOftask)
    .Add(startOffset)
    .Add(new TimeSpan(numbersOfDays*nonWorkingTime.Ticks))
    // Add in the extra non-working time for each day
    .AddDays((numbersOfDays/5)*2); // Add in 2 extra days for every 5 days of work

// Need to account for starting later in the week and rolling over weekend
var extraDays = numbersOfDays%5;

var endOffset = TimeSpan.Zero;
if ((int) startOfTask.Add(startOffset).DayOfWeek + extraDays > 5)
{
    endOffset = TimeSpan.FromDays(2);
}
// If we ended after the end of the day need to account for non-worktime
if (endOfTask.TimeOfDay > endTime)
{
    endOffset = endOffset.Add(nonWorkingTime);
}

return endOfTask.Add(endOffset);

If starting before the start time or starting on the weekend if valid then there would need to be special code just for those cases but it would be at the top to just to add to the duration the extra days to move on to the start date.


Database "design" using Symfony2 and Doctrine2

IMO this is great, it's nicely normalised. You're separating things logically into models.

The only thing that's puzzling me is...what is your 'Month' entity for? None of your other Entities reference it?

I don't know if:

/**
 * @ORM\OneToMany(targetEntity="Expense", mappedBy="expense")
 */
protected $months;

Is meant to reference months? I'm guessing it is.

The only thing I can think of is that you're using one model to satisfy two different entities : the categories model.

If I were you I would split it into to things:

User_Categories

and

Expense_Categories

This is something I often do, and I've found it better than having one abstract category entity. Having more tables has almost no downsides from a programatic point of view.

The only other thing I can think of really is, even if (as above) you meant to have a month entity, what is it for? It's actually a budget entity, not a month entity.

Date/time models are already abstracted quite well in doctrine itself (just have a column [or two] specifying the date range), so having a budget entity makes much more sense, then you can specify arbitrary budget time periods instead of the monthly constraint.

Hope this helps!


Avoid nested ternary operators. It hardly ever improves readability over proper if-else conditions.

When the boolean values true and false are involved, often there's simply no need for tensors at all, like in this example:

flag = ch[i] == '\t' ? TRUE : FALSE;

This is equivalent and simpler:

flag = ch[i] == '\t';

When a condition gets complicated, another technique is to extract the complex boolean expression to a helper method with a good descriptive name.


Encapsulation and information hiding

First of all, this looks poorly conceived:

public Properties getClasspathFileAsStream() {

It seems you named the method according to how it's implemented,
which is a sign of bad design.
Following good encapsulation / information hiding principles,
users shouldn't need to know about implementation details.
A method that returns Properties is better named getProperties or loadProperties. I use the former naming style when the properties are ready to return, and the latter to imply I/O operations behind the scenes (loading from filesystem, database, remote service), hinting the possibility of slowness and failures.

Initialize in constructor use static method?

This seems to be one of your main questions:
should you pass the properties file name as constructor parameter,
or use a static method with a filename parameter?
It depends on how often you want to load the properties file.

If you need to load the properties file only once during the lifetime of the program,
then there's no need to store the filename in a class field,
a static method will be simple and straightforward.

If on the other hand you want to use getProperties multiple times,
then it makes sense to store data in class fields.
Even so, you have two alternatives:

Store the filename in a field, and use a loadProperties method to load the content of the file on every call.
Load the content of the file in the constructor, and store the Properties data in a field, returned by getProperties. In this alternative there's no need to store the filename in a field at all.

Again, the suitable alternative depends on how you want to use this class,
and if the content of the properties file is expected to change during the execution of the program.

Throw an exception or not

Throw an exception if the caller can or should handle it.
Perhaps the caller should try to load properties from a different source.
Or perhaps it should exit the program in case the properties cannot be loaded.

Don't throw an exception if properties are not essential data,
and missing data is not a problem.
In this case you can handle I/O exceptions in this class,
and return new Properties().

The right approach depends on your use case.


Abstracted email sender with content providers

public EmailMessage()
{
    ToAddresses = new List<EmailAddress>();
    CcAddresses = new List<EmailAddress>();
}

Not necessary, I can understand if you just initiate the ToAddress, however, initiating the lists like this might consume a lot of memory (imagine you have large amount of EmailMessage instances! So, I would suggest to keep them as null, and use null validation to force initiating them when it's needed (like in sender).
your overall design is good enough, however, you could do this directly :
public class EmailMessage
{
    public EmailAddress From { get; set; }
    public IEnumerable<EmailAddress> To { get; set; }
    public IEnumerable<EmailAddress> Cc { get; set; }
    public IEnumerable<EmailAddress> Bcc { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
}

public interface IEmailProvider
{
    IEmailServerSetting ServerSettings { get; set; }
}

EmailMessage should contain From(required), To(required), CC(optional),BCC(optional), Subject, and Body as a full model of the message. The reason behind that is that it will be always paired together as requirement to any message, later on, it would be also easier to implement on the database side. using IEnumerable<EmailAddress> would open to use any collection that implements IEnumerable. So, it's not restricted to List.
For IEmailProvider As an email provider should also contain its own settings as requirement. This would make things easier for you, to have each email message with it's own settings. This way, you can send multiple emails from different providers with no extra coding. IOptions is treated independently, but in reality, IOptions won't be useful by itself, and it would only used by EmailProvider, so if we add it to the contract, it'll always be implemented with the interface, this way you forced the provider to always have IOptions. Besides, IOptions should be renamed to something like EmailServerSetting or EmailProviderSetting to relate it to the main implementation. As these are settings and not options. Use IOptions to handle the email optional settings and features that can be managed like sending as text or html, disable/enable attachments, pictures ..etc.
Also, you need a middle-ware class to wrap things up, and uses SmtpClient. This would give you the advantage of increasing the flexibility of your current work and wrap them under one roof along with ease things up for reusing code (such as MimeMessage, TextPart ..etc.) instead of reimplement it on each new sender. It also would give you the ability to create a collection to store multiple providers if you're going that far. also, you will be able to add new providers, handle them, handle messages, and keep your work scoped.
Here is how I imagine the final usage :
Creating a new provider :
// creating a new email provider
    public class SomeEmailProvider : IEmailProvider
    {
        // only set the settings internally but it's exposed to be readonly
        public EmailServerSetting ServerSettings { get; private set; }

        public SomeEmailProvider()
        {
            //set up the server settings
            ServerSettings = new EmailServerSetting
            {
                ServerType = EmailServerType.POP,
                Server = "pop.mail.com",
                Port = 995,
                Encryption = EmailServerEncryption.SSLOrTLS,
                EnableSsl = true
            };
        }
       // some other related code
    }

now, creating a new mail message and sending it :
// can be single object or collection
var messages = new EmailMessage
{
    From = new EmailAddress("Test", "test@mail.com"),
    To = new EmailAddress [] {
         new EmailAddress("Test1", "test1@mail.com"),
         new EmailAddress("Test2", "test2@mail.com")
        },
    Subject = "Testing Subject",
    Body = "Normal Text Body"
};

using(var client = new EmailClient(new SomeEmailProvider()))
{
    client.Options = new EmailClientOptions
    {
        // would send it as plain text
        EnableHtml = false
    };

    client.Messages.Add(messages);

    client.Send();
}


Using static for class default properties

You could either a configuration object or a builder for this. As you probably can see yourself, using static gets complicated quite fast.

Using a builder:

class InputBuilder
{
    private $_defaults = array(
        'tag' => null,
        'type' => null,
    );

    private $_current;

    public function __construct(array $defaults = null)
    {
        foreach ($defaults as $key => $value) {
            if (array_key_exists($this->_defaults[$key])) {
                $this->_defaults[$key] = $value;
            }
        }

        $this->reset();
    }

    public function reset()
    {
        $this->_current = array();
        foreach ($this->_defaults as $key => $value) {
            $this->_current[$key] = $value;
        }
    }

    public function setTag($tag)
    {
        if (!is_string($tag)) {
            throw new InvalidArgumentException('...');
        }
        $this->_current['tag'] = $tag;
    }

    public function setType($type)
    {
        if (!is_string($type)) {
            throw new InvalidArgumentException('...');
        }
        $this->_current['type'] = $type;
    }

    public function getInput()
    {
        return new Input($this->_current);
    }
}

Usage would be:

$builder->setType('text')
        ->build();  // tag: input, type: text
$builder->setType('password')
        ->build(); // tag: input, type: password
$builder->reset(); // reset everything to defaults
$builder->setTag('textarea') // tag: textarea: type: text
        ->build();

The builder pattern is extremely strong if you want to build the object programmatically. (SQL) Query-builder are a very common use case for this.

Using a configuration object:

class InputConfiguration
{
        private $_init = array(
            'tag' => null,
            'type' => null,
        );

        private $_current;

        public function __construct(array $defaults = null)
        {
            foreach ($defaults as $key => $value) {
                if (array_key_exists($this->_defaults[$key])) {
                    $this->_defaults[$key] = $value;
                }
            }
        }

        public function configure(Input $element)
        {
            $config = $this->_init['tag'];

            if (null !== $config['tag'] && null !== $element->getTag()) {
                $element->setTag($config['tag']);
            }

            if (null !== $config['type'] && null !== $element->getType()) {
                $element->setType($config['type']);
            }
        }
}

class Input
{
     public function construct(InputConfiguration $config = null)
     {
           if (null !== $config) {
               $config->configure($this);
           }
     }

     // ...
}

Usage would be:

$configuration = new InputConfiguration(
    'tag' => 'input',
    'type' => 'text',
);

$newObject = new Input($configuration); // has defaults applied

$newObject2 = new Input(); // we don't want to use defaults
$configuration->configure($newObject2); // or decide to apply them later on

The configuration object decouples the configuration from your object. Furthermore it makes one configuration reusable and optional.


Function to convert from const char * to char**

I basically reject your code for admittance into the master branch.
This is not C++ code but primarily C and duplicates functionality that exists in the standard library.

Let's look at your interface first:

void str2arg(const char * str, std::vector<char*> & arg, std::string & memory) {

The parameter memory is only used internally to the function. It is not used externally and provides no utility. So get rid of it as a parameter. Make it an internal member of the function.

The parameter arg is used as an out parameter. You don't need to do this. Return the vector by value. This makes it very clear what you are doing. The optimizer will elide the copy and with move semantics in C++11 it will use move if it can not elide the copy. Summary: it is not an issue to return big values from functions the compiler will optimize away any issues (if for some reason it can't and you notice during benchmarking then you can have a look at using out parameters).

std::vector<char*> str2arg(const char * str);

Next issues is you are using pointers (and dropping the constness). Pointers are horrible and should only be used at the lowest level of your code for creating containers. Normally you can use normal objects to represent stuff. Here use std::string.

std::vector<std::string> str2arg(std::string const& str);
                                             ^^^^^^  Allows you to pass a literal.
                                                     That can be converted to a string.

Why are pointers horrible:
They do not provide any semantic definition of ownership. Ownership is a very important concept in C++ as it defines who is responsible for deleting an object. Normally we use containers and smart pointers to define ownership of dynamic objects and we refer to other objects via references when we don't own them.

Const correctness is a big deal in C++ this is something you should take to heart very quickly. You drop the constness on your pointers thus leading to a possibility where people incorrectly use the pointer you return (by modifying the content of the string). This is a real problem if the string is actually const and will cause the program to crash.

Algorithm:

Much improvement can be done here.
Let us examine the utilities provided by the standard.

Note 1:

The stream operator>> when applied to a std::string will read one space separated word from the stream.

  std::string word;
  stream >> word;  // drops leading space and reads a single space delimited word.

Note 2:

The std::istream_iterator<X> are iterators that treat streams as forward containers. They read X from the stream using operator>> and you can then access the object of type X with the standard iterator methods. Use this in combination with std::string and you can read words from a stream.

 std::istream_iterator<std::string> loop(stream);
 std::istream_iterator<std::string> end;

 for(;loop != end;++loop)
 {    std::cout << *loop << ".\n";
 }

Since we now have an iterator to scan through a stream of words we can also apply the standard algorithms.

 // Assuming the loop above had not drained the stream.
 // The following alternative copies a stream into the vector one word at a time.
 std::vector<std::string>  data;
 std::copy(loop, end, std::back_inserter(data));

Also note that std::vector has a constructor that takes iterators so you can build it directly, rather than using an algorithm.

 std::vector<std::string>  data(loop, end);

So now that we have gone through all that we can re-code your function like this:

#include <vector>
#include <string>
#include <sstream>
#include <iterator>
std::vector<std::string> str2arg(std::string const& str)
{
    std::stringstream  stream(str);
    std::vector<std::string>  result((std::istream_iterator<std::string>(stream)),
                                     std::istream_iterator<std::string>());
    return result;
}

Side note.

Since we mention command line args in other answers.
I like to convert the command line args into string before proceeding.

int main(int argc, char* argv[])
{
    std::vector<std::string>  args(argv+1, argv + argc);
}

main

int main()
{
    std::vector<std::string>  data = str2arg("   this is  a test   string   ");
    std::vector<char*>        ptr;
    // Doing it like this because I don't feel inclined to go look
    // up the appropriate iterator adapter to convert a string into a pointer.
    std::for_each(args.begin(), args.end(),
                  [&ptr](std::string& a){ptr.push_back(&a[0]);});

    SomeCFunctionThatNeedsPointers(&ptr[0]);
}

Main with Boost

#include <boost/iterator/transform_iterator.hpp>

int main()
{
    typedef boost::transform_iterator<std::function<char*(std::string&)>,
                                      std::vector<std::string>::iterator
                                     >    ti;

    std::vector<std::string>  data = str2arg("   this is  a test   string   ");
    std::vector<char*>        ptr(ti(args.begin(), [](std::string& x){return &x[0];}), ti(args.end()));

    SomeCFunctionThatNeedsPointers(&ptr[0]);
}


Prime sieve: improve efficiency while keeping it reasonably simple?

This is a great example of memory bound problem. If you manage to reduce the number of cache misses you can have quite a speedup.
I am providing almost identical code, only instead of boolean array I am using BitSet. Running on Server machinve, on my quite dated hardware I observe about 30% speedup without any other optimizations. Hand-optimizing the bit set functionality may speed things a little more, although I am not too much an optimist.

I am providing this example only to show how important memory (micro) management can be. I do not suggest that the original algorithm can not be optimized.

public void listPrimesThree(int maxNum) {
    long startTime = System.currentTimeMillis();

    int root = (int) Math.sqrt(maxNum);

    BitSet bs = new BitSet(maxNum+1);
    for (int m = 2; m <= root; m++) {
        for (int k = m * m; k <= maxNum; k += m) {
            bs.set(k);
        }
    }
    long endTime = System.currentTimeMillis();
    System.err.println((endTime - startTime) / 1000 + " s");
    for (int m = 3; m <= maxNum; m += 2) {
        if (!bs.get(m)) {
            System.out.println(m);
        }
    }
}


Bash script to deploy a mongodb cluster on local machine

To begin with, I agree with Jesse_b that command substitution should use $(). There's no reason to use backticks in a bash script that uses arrays (that's to say, you're not particularly aiming for portability with some obscure shell).

Indentation

I didn't notice until the end of the script that the majority of your code is in a {...} block. Indenting that portion of the code more than the braces would have helped.

Reading the config file

Continuing from the previous point, the majority of your code seems to be in the block because of the pipe used for reading the file.

Avoid the pipe

You can use process substitution to avoid the pipe:

while read -r line
do
...
done < <(sed '...' file)

This way, you eliminate the pipe and the need to keep most of your code in a subshell. You can also make the comments more friendly by allowing leading spaces:

sed '/^[[:space:]]*#/d;/^[[:space:]]*$/d'

Or:

sed '/^[[:space:]]*\(#.*\)\?$/d'

Eliminate unnecessary reads and variables

That said, the code for reading the lines seems to be unnecessarily convoluted: a read first and then again to split? Why not do it in one op? You also use an array, then immediately proceed to assign the array elements to two named variables and thereafter ignore the array completely. Just set those variables via read directly;

while IFS='=' read -r key value
do
...
done < <(sed '/^[[:space:]]*\(#.*\)\?$/d' file)

Bug, again, later on you split the values read here, because they are all host-port pairs. If so, then do the splitting now, and save them in separate arrays in the first place:

declare -a CONFIG_HOSTS CONFIG_PORTS SHARD_HOSTS SHARD_PORTS
while IFS='=:' read -r key host port
do
...
done < <(...)

Repetitive if statements

Next, the chain of ifs are so repetitive that I suggest taking out the echos, by making an array out of the labels you print:

declare -A key_labels
key_labels["config"]="mongod config server"
key_labels["mongos"]="mongos instance"
key_labels["shard"]="shard instance"

Then, a single printf should do. And the block of ifs also look like they fit the role of a case statement. So:

printf '%s: %s:%s\n' "${key_labels[$key]}" "$host" "$port"
case key in
config)
    CONFIG_HOST+=("$host")
    CONFIG_PORT+=("$port")
    ;;
mongos)
    MONGOS_HOST="$host"
    MONGOS_PORT="$port"
    ;;
shard)
    SHARD_HOST+=("$host")
    SHARD_PORT+=("$port")
    ;;
esac

So, the entire config reading section becomes:

declare -a CONFIG_HOSTS CONFIG_PORTS SHARD_HOSTS SHARD_PORTS
declare -A key_labels
key_labels["config"]="mongod config server"
key_labels["mongos"]="mongos instance"
key_labels["shard"]="shard instance"

while IFS='=:' read -r key host port
do
    printf '%s: %s:%s\n' "${key_labels[$key]}" "$host" "$port"
    case key in
    config)
        CONFIG_HOSTS+=("$host")
        CONFIG_PORTS+=("$port")
        ;;
    mongos)
        MONGOS_HOST="$host"
        MONGOS_PORT="$port"
        ;;
    shard)
        SHARD_HOSTS+=("$host")
        SHARD_PORTS+=("$port")
        ;;
    esac
done < <(sed '/^[[:space:]]*\(#.*\)\?$/d' file)

Looping with an index

Here, since you need the indices for creating the directories, you can just ask bash for the indices directly. Instead of:

index=0
for conf in "${CONFIG[@]}"
do
...
    index=$(($index + 1))
done

Do:

for index in "${!CONFIG_HOSTS[@]}"
do
    mkdir /data/config"$index"
    echo "starting config server $index"
    mongod --configsvr --port "${CONFIG_PORT[index]}" --dbpath /data/config"$index" --replSet conf > log.txt &
    sleep 1
done

Other notes on this block:

Note how I eliminated the IFS=: read ... and replaced "${config[1]}" with "${CONFIG_PORT[index]}", which immediately makes the meaning of that variable clearer.
The indentation was mixed up, both in this and the other loop. Be consistent.
The echo "" > log.txt from earlier was unnecessary, since you use > log.txt here, the file will be truncated anyway.
You are losing the output from all but the last mongod process, since you use > instead of >>.
Always quote your variables.

This index method can be applied to the other loop as well. Also, every instance of IFS=: read ... <<<"$foo" can now be eliminated, and the resultant variables replaced with the arrays we created earlier, as shown in point 1 above. So, things like config0[1] become ${CONFIG_PORT[0]}.


Angular console like window - first directive

template: [
      '
',
      '
',
      '{{event.data}}1" class="count">{{event.count}}',
      '
',
      '
'
    ].join(''),

If you have a build step with a transpiler, or don't care about old browsers, consider using template strings instead. Template strings can multi-line, making it easy to build markup.

$rootScope.$on('Log', function(event, data) {

$rootScope is great for data relay. However, when an app grows, you will be caught in a tangle of events. You don't know who fired them, what they'll execute, their payload (unless you document them, which rarely happens). Plus, $rootScope is a global and we all know what happens to globals when they get polluted. Suggesting you use a service/factory instead. That way, it isn't global plus you have some form of control.

Also, instead of separate events, why not a single event. It seems like your logic already sorts itself out by the type property.

$scope.events[0] !== undefined

Looks like you're checking if the array contains something. It would be best expressed if you checked the array length property instead.

$scope.events.splice(0, 0, {
  type: 'log',
  data: "Log :: " + data,
  count: 1
});

There's array.unshift. It's like array.push but puts the new value at the start of the array.


How can I prettify blocks with more than 2 of each block?

A couple of things I noticed:

Dir[...] and Dir.glob(...) are synonymous, but you're using both forms?
Speaking of, glob accepts fairly complex patterns, which could help narrow the search
Skip the testing_files.has_key? check; just use testing_files[event_type] ||= []
The explicit return makes little sense. You're looping through the globbed dir paths, but your explicit return means that only the first will ever be checked. Maybe there's only supposed to be one path, but that depends on what search_target is, which you don't know.
Your method will return nil, an empty hash or a populated hash. Limit the number of possible return values.

Mostly though, it seems like the filename-branching is unnecessary. In both cases you add grab the \w+ part of the name, and use it as a hash key for an array. The only difference is that
if the filename has numbers in it, it'll add the file to the array, otherwise it'll replace the array with a new 1-element array.

I'd say treat all files the same, and append them to the array. Don't ever replace the array. As far as I can figure, your method is entirely dependent on the platform/filesystem you're running it on, since glob doesn't dictate the order in which files are returned.

So given 3 files in the following order:

foobar.json
foobar_1-1.json
foobar_1-2.json

your method will return all three. But if the order's reversed, it'll only return "foobar.json". Or, if it's somehow mixed, it might return "foobar.json" and "foobar_1-1.json", but not the 3rd file.

So instead of risking inconsistent behavior, I'd suggest sticking to 1 way of treating the files, regardless of whether they're numbered or not.

def get_files_from(search_target)
  files = {}

  Dir[search_target].each do | d |
    next unless File.directory?(d) # skip if d isn't a dir

    Dir["#{d}/*.json"] do |file|
      event = File.basename(file)[/^\w+/]
      testing_files[event] ||= []
      testing_files[event] << file
    end
  end

  files
end

If you want to be more exacting, you can do this instead

Dir["#{d}/*.json"].select { |file| File.basename(file, '.json') =~ /^\w+(_\d+-\d+)?$/ }.each do |file|
  ...
end


Welcome! Here are my thoughts what could be improved:

For top-level declarations, always do include types. I'm pretty sure in a few weeks it'll be difficult to realize what

mapTuple = join (***)

means without knowing that it's type is

mapTupple :: (b' -> c') -> (b', b') -> (c', c')

Also as you don't need arrows anywhere else, it makes sense to specialize the type to avoid accidental errors and get nicer error messages.
I'd put a newline betweek 'data...' and 'label'. Keeping consistent style helps readability very much.
You don't need to nest 'let' expressions. You can write just

let midpoint = Seq.length s `div` 2
    subseq = Seq.splitAt midpoint s
    ...
in Branch label subtrees

Instead of creating a sequence and then converting it into a balanced tree, you can convert a list directly into a balanced tree in O(n). This is a nice exercise on its own!
Use Haddock markup in comments, you can then generate nice documentation very easily.

  Algorithm runs in Θ(n log n) which I believe is optimal.

Are you sure?


Read CSV with 3 columns and group some elements

The first argument to your function does not appear to be a string holding the name of a file, as its name lead me to initially assume. I would suggest you change to e.g. csv_reader (right?) to make it clear what we're getting.

i is another bad variable name, it's usually used for an integer index, and doesn't tell the reader anything useful. Also, the following is more meaningful than the current indices into i:

for date, key, val in csv_reader:

You can then apply whatever processing you need and it's still clear what's happening:

val = int(val)

I see what you're trying to do here:

if any(name in key for name in key_word):
    for name in key_word:
        if name in key:
            key = name

But won't save any time - you have to go through all name in key_word once for the any(...) is False case, and fully twice in the worst any(...) is True case. Just use:

for name in key_word:
    if name in key:
        key = name

collections.defaultdict would simplify much of that code for you, for example:

complete_dict = defaultdict(lambda: defaultdict(int))
...
for date, key, val in csv_reader:
    ...
    date = time.strptime(date, "%m/%d/%y")
    for name in key_word:
        ...
    complete_dict[date][key] += val # don't need any checks for keys

On a logical point, what should happen if a key contains more than one key_word, or if there are overlaps between key_words? At the moment the first match is used in cases where there are no further complications, but you could break to ensure this (and speed up the code).


Perform basic string compression using the counts of repeated characters

Interviewing techniques and design decisions

If you were asked a question like this in an interview, always ask your interviewer for clarification.  Not only does it avoid misunderstandings, it also demonstrates your ability to identify corner cases.  You can score points before writing a single line of code!

In this case, the question I would ask is: how should a streak of 10 or more identical characters be encoded?  An encoded string that always alternates character, count, character, count etc. would be easy to decode.  However, a two-digit count would break the pattern and make it harder to decode.  Indeed, the interpretation could even be ambiguous.  For example, does the encoded string a101c9 mean aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaccccccccc or a0ccccccccc?  I would argue that it should be interpreted as the latter, since

otherwise there would be no good way to compress a0ccccccccc, and
we could preserve the nice character-count-character-count alternation, which is a useful property for decoding.

If we make that design decision, then, it seems to follow that a string consisting of a repeated 101 times followed by c repeated 9 times would have to be encoded as a9a9a9a9a9a9a9a9a9a9a9a2c9.

That is the design decision that I would make, and I would justify it like that to my interviewer.

Critiques

Repeated string concatenation is a no-no!  In Java, strings are immutable, so every time you do + or +=, you create a new string by allocating a chunk of memory, copying the entire contents of the old string, then copying the string to be appended.  Using + once or twice is fine, but never do it many times in a loop!  Use a StringBuilder instead.  In this case, you could also just use a char[] buffer, since you know that the buffer should never grow beyond a certain limit — the length of the input string.
Speaking of the length limit… you only compare the length of the compressed string at the end, when you are basically already done.  A smarter algorithm might be able to bail out earlier if the length is exceeded.
You have redundant conditions:

for(int i = 0; i < initialLength; i++){
    char c  = chars[i];
    if(currentChar == c && i + 1 <= initialLength){
        occurances++;
    }

    else if (currentChar != c || i + 1  > initialLength){

i + 1 <= initialLength would be more idiomatically written as i < initialLength.  But that is exactly the condition of the for loop itself!  Therefore, the i + 1 <= initialLength test is always true, and superfluous.

By the same reasoning, i + 1  > initialLength can never be true, and is also superfluous.  The remaining else if (currentChar != c) could just be written as else.
The special case for the loop termination is clumsy.  This condition

if(i + 1 >=  initialLength){

can happen just once, at the very last iteration of the loop.  You can therefore just move it out of the loop.
What happens with degenerate input?  For example, if str is an empty string, then your code would crash on char currentChar = chars[0].  By my interpretation, a zero-length input should produce an empty string as output.  In fact, if you see an input of length 0, 1, or 2, you could immediately return str.
"Occurances" should be spelled "occurrences".

Suggested solution

This code would address the concerns above.  I've used just a char[] array as scratch space.  By writing directly to the buffer, I've eliminated the need to write another compressedString += currentChar + String.valueOf(occurances) at the end.

JavaDoc would be a nice touch.  If coding on a whiteboard, a "verbal" comment might be good enough, though.

/**
 * Performs run-length encoding on a string.  If the encoded string
 * would be longer than the input, then the input string is returned.
 * To make decoding simple and unambiguous, streaks are limited to
 * 9 characters long; longer streaks are broken up.
 */
public static String compress(String in) {
    if (in.length() < 3) return in;

    int n = in.length(), i = 0, o = 0;
    char[] out = new char[n + 1];
    out[o++] = in.charAt(0);
    out[o++] = '1';
    for (i = 1; i < n && o < n; i++) {
        if (in.charAt(i) == in.charAt(i - 1) && out[o - 1] != '9') {
            // Continued streak
            out[o - 1]++;
        } else {
            // New streak
            out[o++] = in.charAt(i);
            out[o++] = '1';
        }
    }
    return (i == n && o < n) ? new String(out, 0, o) : in;
}


Get Ajax request implementation without jQuery

Your ajax() function gives me a good first impression. The structure seems sound and the event handling well done - the done() event handler is called exactly once (someone else might want to confirm, though).

A few suggestions:

var opts = Object.assign({...}, options);

opts vs. options is inconsistent and carries no semantics. Reassigning to options would mutate the argument which could cause issues for the user. jQuery names the merged options and defaults settings, which might be a little bit more clear.
if (this.status >= 200 && this.status < 300) {

This line seems good for now. You might want to check 304 in a future version when allowing users to supply caching headers. However, such requests don't respond with data and are probably not within the intended use of your library right now.
xhr.send(null);

The send method accepts an optional parameter which is ignored and set to null for GET requests. Therefore, I would recommend the simpler xhr.send().
if (this.readyState === 4) {

Add more semantic by replacing 4 with XMLHttpRequest.DONE - not available in old browsers such as IE 8.
cb('error');

This seems like a design flaw to me. A user cannot distinguish between an 'error' string received from the server vs. supplied as a result of an invalid HTTP status code. You already supply false on multiple occasions - when a network level error or timeout occurs - which is easily distinguished from a valid response by type checking. Why not supply false in the above case, too? If that's not an option, supply an error status flag or object or introduce error callback(s).


private void SearchGrid(object sender, TextChangedEventArgs e)
    {
        if (!string.IsNullOrEmpty(searchBox.Text))
        {
            ICollectionView view =      CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
            view.Filter += (obj) =>
            {
                CompanyModel model = obj as CompanyModel;
                if (model == null)
                    return true;

                if (compNameRad.IsChecked == true)
                {
                    return !string.IsNullOrEmpty(model.CompanyName) && model.CompanyName.Contains(searchBox.Text);
                }
                if (compTownRad.IsChecked == true)
                {
                    return !string.IsNullOrEmpty(model.CompanyTown) && model.CompanyTown.Contains(searchBox.Text);
                }
                if (compPcodeRad.IsChecked == true)
                {
                    return !string.IsNullOrEmpty(model.CompanyPcode) && model.CompanyPcode.Contains(searchBox.Text);
                }
                return false;
            };
        }
    }

The problem with your code is that each time the text changed you are adding a new Filter to the ICollectionView by using

view.Filter += (obj) =>

this little + is doing all the harm. For each raise of the TextChanged event a new filter is added and never removed.

If you remove the + you will see that your filtering will become faster.

The problem with A1 vs a1 is that the Contains() method is case sensitive. A better way would be to use IndexOf(string, StringComparison) like so

return !string.IsNullOrEmpty(model.CompanyName)
       && model.CompanyName.IndexOf(searchBox.Text, StringComparison.OrdinalIgnoreCase) > -1;


Let’s define an extension method on Type:

public static class AttributeCache
{
    public static IEnumerable<T> Attributes<T>(this Type type)
        where T : Attribute => Cache
            .GetOrAdd(type, t => t.GetCustomAttributes(true).OfType<Attribute>().ToArray())
            .OfType<T>();

    static ConcurrentDictionary<Type, Attribute[]> Cache { get; } =
        new ConcurrentDictionary<Type, Attribute[]>();
}

Demo:

foreach (var a in typeof(MyCass).Attributes<TestAttribute>())
    Console.WriteLine(a.MyProp);


I suppose that your class is trying to simulate a shared_ptr, however, I'm missing the part of overloading the dereference methods * and ->, because without them, your class seems useless (I can't do much with the pointed object).


Is this circular linked list better than the fast & slow pointer method?

This works when you're starting from inside the cycle. However, the following is also a valid circular list:

N1 --> N2 --> N3 --> N4
       ^             v
       +-------------+

Your algorithm works when starting from N2, N3 or N4, but not when starting from N1.


Iterating and updating 35000 dictionaries

Not surprisingly, almost all time is spent on the repeated if item not in rows_list, as that takes linear time every time. Instead of doing the duplicate-check with a list, you'd better do it with a set, where that check averages constant time. That would require hashable elements, though, which your items, being dicts, aren't. But you can probably extract something hashable correctly identifying each item, no? Maybe even just item['product_name']? If not, then the tuple (item['product_name'], item['product_description'], item['cost']).


Functional Pascal triangle in Python (working version)

Your current code calls pascal_row O(n^2) times (put a print inside to see this) through recursion. You don't want to be repeating so much calculation. To cache the results:

from functools import lru_cache

@lru_cache(maxsize=None)
def pascal_row(n):

However then you can't be returning generators anymore because after one iteration they'll be exhausted and yet the caching will return the same generators repeatedly, so you won't get the right results. This is fine, there wasn't really much use in the generators. It was particularly weird to see (x for x in [1]).

You could return list(dispatch()) but there's a much better itertools way than successive yielding: chain.

return list(chain([1], starmap(operator.add, pairwise(pascal_row(n - 1))), [1]))

But really there's no need for all this. The Pythonic way would be:

return [1] + [a + b for a, b in pairwise(pascal_row(n - 1))] + [1]

which is still decently functional.

if n < 2: implies that n might also be 0, -1, etc. You want to:

Make it clear to readers that n should not be that.
Make sure the program quickly ends in an error in such a case so that you can find the bug.

Therefore add an assert n == 1 in this case.

This comes out to:

@lru_cache(maxsize=None)
def pascal_row(n):
    """
    Return a list that yields the nth row of a Pascal triangle
    """
    if n < 2:
        assert n == 1
        return [1]
    else:
        return [1] + [a + b for a, b in pairwise(pascal_row(n - 1))] + [1]

In my opinion the recursion in print_pascal is completely unnecessary and a simple for loop would be much better, but I suppose you want it that way for the exercise.

To be really functional you could ensure that your data structures are immutable and use tuples instead of lists, although it's less pretty:

if n < 2:
    return (1,)
else:
    return (1,) + tuple(a + b for a, b in pairwise(pascal_row(n - 1))) + (1,)


It's more than okay, it is nicely readable, has no problems and involves no abuse whatsoever. I sometimes do the same.