A comment stating that you are declaring values isn't useful.
Don't use return at the end of blocks; just let the block evaluate to the last expression.
This extends to conditionals like if/else: just let the condition evaluate, there's no reason to set a variable. Note that this allows you to avoid unneeded mutability.
Any time you find yourself writing parallel conditions in multiple places, that's an opportunity to add abstraction. In this case, an enum would be sufficient. Note that this removes the panics; we've statically removed an entire failure case!
You don't need to add parenthesis for chained functions.
Pay attention to your duplication between your conditionals. You can extract most of the duplicated code to DRY up the logic. Note how you even have comments on only one of your two conditional branches even though it should apply to both.
This even makes it so that we no longer need constants because the match prevents duplication.
Instead of looping and pushing values, use Vec:resize
Instead of calling the method key_deriv and having comments explaining that it pads it, just rename the method.
Don't needlessly make variable bindings mutable; it's completely fine to re-bind the same name with let. A good example of this is the key in hmac.
Take &[u8] if you aren't making use of the memory allocation.
Use a Cow to avoid allocating anything if the key is already correctly sized.
Creating a Vec and then manually pushing bytes is probably the slowest path. Instead, either allocate a Vec with enough space or use collect which knows how many elements there are. You could also duplicate the key twice and then mutate it in place.
Avoid indexing into a slice when feasible. Iterators tend to have less overhead.
Don't use variable names like k. Instead, type out very long words like "key".
There's no real reason to use Vec::append as you don't use the source vector until it's destroyed a few lines later. Might as well use the boring extend_from_slice.
Because you've forced hash to return a Vec, you are forcing one extra allocation (that of hash(inner_pad)) You can avoid that by returning the result of the digest and only converting to a Vec when needed.

extern crate ring;

use ring::digest;
use std::borrow::Cow;

enum Variant {
    Small,
    Big,
}

impl Variant {
    /// Return either a SHA256 or SHA512 digest of byte vector
    fn hash(&self, data: &[u8]) -> Vec<u8> {
        let method = match *self {
            Variant::Small => &digest::SHA256,
            Variant::Big => &digest::SHA512,
        };
        digest::digest(method, data).as_ref().to_vec()
    }

    fn blocksize(&self) -> usize {
        match *self {
            Variant::Small => 64,
            Variant::Big => 128,
        }
    }

    fn pad_key<'a>(&self, k: &'a [u8]) -> Cow<'a, [u8]> {
        let mut k = Cow::from(k);

        // If key k is bigger than blocksize, it should be hashed...
        if k.len() > self.blocksize() {
            k = self.hash(&k).into();
        }

        // ... and then padded with zeroes to fit the blocksize
        if k.len() < self.blocksize() {
            let mut resized_key = k.into_owned();
            resized_key.resize(self.blocksize(), 0x00);
            k = resized_key.into();
        }

        k
    }

    /// Returns an HMAC from message m and key k
    pub fn hmac(&self, key: &[u8], message: &[u8]) -> Vec<u8> {
        let key = self.pad_key(key);

        let make_padded_key = |byte: u8| {
            let mut pad = key.to_vec();
            for i in &mut pad { *i ^= byte };
            pad
        };

        let mut inner_pad = make_padded_key(0x36);
        let mut outer_pad = make_padded_key(0x5C);

        inner_pad.extend_from_slice(message);
        let inner_pad = self.hash(&inner_pad);

        outer_pad.extend_from_slice(&inner_pad);
        self.hash(&outer_pad)
    }
}

fn main() {}


Stripping out all /* */ comments from a paragraph

You didn't specify whether or not nested comments are allowed, but your code trims only the shorter comment. For example, case 4 would yield Text  Text with nesting but Text  */ Text without. It would be helpful to include some unit tests to demonstrate the intent.

Your solution is pretty straight-forward with only one real complication. I would remove the moveAheadBy incrementer and instead perform an extra increment where you're setting moveAheadBy to 2. It's minor, but it removes unnecessary state.

To help with the readability, introduce a variable for the length of the input since it's used in so many places.

Another solution would be to use indexOf to seek ahead to the next open/close. The algorithm will still be \$O(n)\$, but the fewer number of append calls could add up with very, very long strings. This is more to show an alternate method than to improve on yours.

public static String stripComments(final String input) {
    StringBuilder buf = new StringBuilder();
    int current = 0;
    int end = input.length();

    while (current < end) {
        int nextOpen = input.indexOf("/*", current);
        if (nextOpen == -1) {
            // no more comments
            buf.append(input.substring(current));
            break;
        }
        buf.append(input.substring(current, nextOpen));
        int nextClose = input.indexOf("*/", nextOpen + 2);
        if (nextClose == -1) {
            // final comment not closed
            break;
        }
        current = nextClose + 2;
    }

    return buf.toString();
}

Unit Tests

Now that the method is public, let's add some tests.

@Test
public void testNone() {
    assertThat(stripComments("No comments at all"), is("No comments at all"));
}

@Test
public void testSingle() {
    assertThat(stripComments("Single /* foo */ comment"), is("Single  comment"));
}

@Test
public void testDisjoint() {
    assertThat(stripComments("Two /* foo */ disjoint /* bar */ comments"), is("Two  disjoint  comments"));
}

@Test
public void testNested() {
    assertThat(stripComments("Two /* foo /* nested */ baz */ comments"), is("Two  baz */ comments"));
}

@Test
public void testUnclosed() {
    assertThat(stripComments("Unclosed /* foo comment"), is("Unclosed "));
}

@Test
public void testUnopened() {
    assertThat(stripComments("Unopened */ comment"), is("Unopened */ comment"));
}


Switching between view controllers that are loaded in the background

I recently created a similar layout for a project I'm working on using Apple's PageControl example as a base.

I used a UICollectionView for the top nav section and a UIScrollView for paging through view controllers. The main view controller is setup as below.

In the viewDidLoad method for the I set up the content size for the scrollView and set paging to YES.

[self.containerScrollView setContentSize:CGSizeMake(CGRectGetWidth(self.containerScrollView.frame)*self.numberOfPages,
CGRectGetHeight(self.containerScrollView.frame))];
[self.containerScrollView setPagingEnabled:YES];
[self.containerScrollView setShowsHorizontalScrollIndicator:NO];
[self.containerScrollView setShowsVerticalScrollIndicator:NO];
[self.containerScrollView setScrollsToTop:NO];
[self.containerScrollView setDelegate:self];

(Note: if you're using xibs/size classes, I ran into a problem where the scrollView's size is stated as 600x600px no matter which device is used until the ParentViewController's viewDidLayoutSubviews is called. I had to reset the scroll view's content size again.)

After this is set up, I load the first two view controllers:

- (void)loadScrollViewWithPage:(NSUInteger)page {

    UIViewController *viewController = <get your view controller>;

    if (viewController.view.superview == nil) {
        [self addChildViewController:viewController];
        CGRect frame = [self.containerScrollView frame];
        frame.origin.x = CGRectGetWidth(frame)*page;
        frame.origin.y = 0;
        [viewController.view setFrame:frame];

        [self.containerScrollView addSubview:viewController.view];
        [viewController didMoveToParentViewController:self];
    }
}

Since the first two view controllers are loaded, there is no lag when the user swipes between them. When UIScrollView is scrolled, the page is scrolls to is already loaded. Once it does, I load the next one in order:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = CGRectGetWidth(self.scrollView.frame);
    NSUInteger page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    [self loadScrollViewWithPage:page - 1];
    [self loadScrollViewWithPage:page];
    [self loadScrollViewWithPage:page + 1];
}

This way you always have the current, previous and the next view controller always ready. You could load more than 3 if the network calls you have to make take longer and the what the user is expected to scroll at.

You could unload older view controllers by calling viewController.view = nil and always only have a set number of view controllers loaded.

I created a custom protocol for the UICollectionView and set my parent controller as delegate to respond to cell clicks and navigate to the appropriate page.


How to copy and paste a filtered range more efficiently

The code as you have it is not able to be executed but once I made some revisions it seems to run just fine. On my test dataset I had no problem with performance, but if you continue to have performance issues after making edits, I would look into something called "Advanced Filter" for Excel, as it has the ability to set a destination at the onset for the filtered data to appear. You can simply look up "Advanced Filter" on your favorite search engine and find links like these, there are hundreds to pick from:

https://www.thespreadsheetguru.com/blog/2015/2/16/advanced-filters-with-vba-to-automate-filtering-on-and-out-specific-values
https://www.youtube.com/watch?v=0YNhxVu2a5s

As for my revisions to your code, see below. I've tried to comment every line I changed and change the minimum amount of lines possible.
Option Explicit

Sub FullWork()

Dim rngFullYearData  ' added to be able to reference easier later
'Dim DataRange As Range ' moved to keep all Dim statements together  ' commented out because it was not being used
Dim StartCell As Range  ' added to be able to Set later
Dim PWSelection As Variant
Dim LastRow As Long
Dim LastColumn As Long
'Dim LocationZip As Variant  ' commented out because it was not being used
'Dim dTime As Double  ' commented out because it was not being used

Dim shWorkBook As Worksheet
'Dim shPivotTable As Worksheet  ' commented out because it was not being used
'Dim shCarrierRates As Worksheet  ' commented out because it was not being used
'Dim shWholesaleLocation As Worksheet  ' commented out because it was not being used
'Dim shPWLocation As Worksheet  ' commented out because it was not being used
'Dim shSegmentation As Worksheet  ' commented out because it was not being used
Dim wkb As Workbook
'Dim shMilageMatrix As Worksheet  ' added sh to beginning to stay consistent  ' commented out because it was not being used
Dim shFullYearData As Worksheet  ' added sh to beginning to stay consistent
Dim shStartForm As Worksheet  ' added sh to beginning to stay consistent

Set wkb = ThisWorkbook
With wkb  ' indenting with block for ease of readability
    Set shWorkBook = .Sheets("Workbook")
    'Set shPivotTable = .Sheets("PivotTable")  ' commented out because it was not being used
    'Set shCarrierRates = .Sheets("CarrierRates")  ' commented out because it was not being used
    'Set shWholesaleLocation = .Sheets("WholesalerLocation")  ' commented out because it was not being used
    'Set shPWLocation = .Sheets("PWLocation")  ' commented out because it was not being used
    'Set shSegmentation = .Sheets("Segmentation")  ' commented out because it was not being used
    'Set shMilageMatrix = .Sheets("MilageMatrix")  ' commented out because it was not being used
    Set shFullYearData = .Sheets("FullYearData")
    Set shStartForm = .Sheets("StartForm")
End With

'dTime = Timer  ' commented out because it was not being used

'Call TurnOffCalc  ' commenting out because sub was not included

Set StartCell = shFullYearData.Range("A1")

'Find Last Row and Column

LastRow = shFullYearData.Cells(shFullYearData.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = shFullYearData.Cells(StartCell.Row, shFullYearData.Columns.Count).End(xlToLeft).Column

'shFullYearData.Activate  ' no need to activate if not selecting below
Set rngFullYearData = shFullYearData.Range(StartCell, shFullYearData.Cells(LastRow, LastColumn))  ' remove select, add set instead

PWSelection = shStartForm.Cells(1, 1).Value

With rngFullYearData ' simplify with new variable, add with block for easier referencing
    .AutoFilter
    If PWSelection <> "All" Then
        .AutoFilter Field:=12, Criteria1:=PWSelection  ' using new variable
    End If
    .AutoFilter Field:=26, Criteria1:=">=1"  ' using new variable
    .AutoFilter Field:=3, Operator:= _
    xlFilterValues, Criteria2:=Array(0, "12/31/2019")  ' using new variable
    .Sort Key1:=Range("G1"), Order1:=xlAscending, Header:=xlYes, Key2:=Range("B1"), Header:=xlYes

''''''Line I need looked at
    .Copy Destination:=shWorkBook.Range("A1")  ' using new variable
End With

'Call TurnOnCalc  ' commenting out because sub was not included

' release variables when finished with them
Set wkb = Nothing
Set rngFullYearData = Nothing
Set shWorkBook = Nothing
'Set shPivotTable = Nothing  ' only including as a reminder in case you use this worksheet later
'Set shCarrierRates = Nothing
'Set shWholesaleLocation = Nothing
'Set shPWLocation = Nothing
'Set shSegmentation = Nothing
'Set shMilageMatrix = Nothing
Set shFullYearData = Nothing
Set shStartForm = Nothing
Set StartCell = Nothing
End Sub
```


Filter by multiple options - also only if not empty

Is this what you're after?

criteria.filter({ _id, criteriaType } => (
    (!participantType || participantType === criteriaType)
    &&
    (!participantCriteriaId || participantCriteriaId === _id)
));

If participantType is empty, it will be coerced to true by the negation, which short-circuits the || operator, so it won't check the right-hand side of the condition. Same for participantCriteriaId.

Note: This type of condition is a common pattern in boolean logic. Generally speaking, conditions that can be phrased as:

  If A is true, then check if B is true; otherwise, ignore this condition

Can be transcribed as:

  (not A) or B

Which in code is:

!a || b

In your case, the condition is "if the search filter is populated, then check for equality, otherwise ignore", which is transcribed as !filter || property === filter.


Python arbitrary objects Serialization and Deserialization

There's a library for this dataclasses-json. Whilst it's a pretty poor library the internal code is bad, there's few tests, the documentation is quite small and the design is starting to suffer from these poor decisions. It works, and for your code it is good enough.
You should be able to see that all serialization and deserialization is performed automatically. This is good as then you can focus on using the objects rather than converting to and from them.
from __future__ import annotations

from dataclasses import dataclass

from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class Foo:
    x: int
    y: int
    bar: Bar

@dataclass_json
@dataclass
class Bar:
    z: int

raw = '{"x": 100, "y": 500, "bar": {"z": 900}}'
obj = Foo.from_json(raw)
assert obj == Foo(100, 500, Bar(900))
assert obj.to_json() == raw


Use of functions

Functions can return values.  You should do that instead of passing back results indirectly via global variables.

In get_username(), user_id = (valid_username(username)) is nonsense, since the valid_username() function never returns anything.

Worse, you are misusing functions as if they were goto labels.  get_username() and valid_username() are mutually recursive, which is inappropriate.  Furthermore, get_username() triggers all of the activity in the program, which is much more than getting the username as the function name would suggest.

Rearranging everything…

def prompt_username():
    return input("Please enter your Soundcloud username: ")

def get_account(username):
    try:
        return client.get("/resolve", url="http://soundcloud.com/{}/".format(username))
    except requests.HTTPError:
        raise ValueError("Invalid username")

def prompt_account():
    while True:
        try:
            return get_account(prompt_username())
        except ValueError:
            print("The username you entered is invalid.  Please try again")

def get_favorites(account):
    req = urllib.request.urlopen("https://api.soundcloud.com/users/{}.json?consumer_key={}",
                                 account.id, consumer_key)
    …
    return decoded_user_info['username']

def save_favorites(account, favorites):
    …

Now you can write this, which does convey what the program does, unlike your get_username() "function" which was really just a goto label:

account = prompt_account()
save_favorites(account, get_favorites(account))


Automatically scan and resize buffer in C

Missing includes

I think you need to include <stdio.h> and <stdlib.h> for successful compilation.

Always check that allocations succeed

Look at

*buffer = malloc(16);
(*buffer)[0] = 0;

If malloc() returns a null pointer, then the assignment to its first element is undefined behaviour.  Your program could crash, destroy your system, or (if you're unlucky) appear to work.

Always check that input succeeds

If getchar() returns EOF, we should stop reading.  Note that by storing the result in a char, we lose the ability to distinguish EOF from valid input.

Avoid output-only parameters

Why do we return void, and instead write our result to a supplied pointer argument?  I could understand accepting an argument if we were to re-use a buffer passed in, but we just discard it.  I'd write this as

/* caller must release allocated memory with free() */
char *scan(void)

Be careful of overflow

If an input line reaches 255*16 = 4080 characters, size++ will overflow to zero.  Then our realloc() acts as free(), and we find ourselves accessing memory out of bounds.  I recommend using size_t for the length of allocated memory - allocation will fail before we reach the limits of size_t.

Consider increasing the allocation increment

This code reallocates every 16 chars.  This makes for a lot of allocations for really long lines.  One technique to avoid that, without hugely over-allocation for short lines, is to increase the increment as the buffer gets larger.  So instead of always increasing by 16, we might double the buffer size instead, or perhaps double it and add 32.  There are various strategies that can be used, with different performance implications (though the differences are likely small compared to the overhead of reading input at all).

Improved version

#include <stdio.h>
#include <stdlib.h>

/* Read a line from standard input stream.

   Returns a buffer that must be released with free(),
   or a null pointer if none could be allocated.

   The result will end in a newline character if a
   full line was successfully read.
 */
char *scan(void)
{
    size_t capacity = 16;
    char *buffer = malloc(capacity);
    if (!buffer) {
        return NULL;
    }
    size_t i = 0;

    int c;                      /* current input character */
    while ((c = getchar()) != EOF) {
        if (i + 2 > capacity) {
            /* ensure space for c and terminating NUL */
            capacity *= 2;
            char *newbuf = realloc(buffer, capacity);
            if (!newbuf) {
                /* allocation failed - undo the read, terminate string, and return */
                ungetc(c, stdin);
                buffer[i] = '\0';
                return buffer;
            }

            buffer = newbuf;
        }

        /* We have enough space; now store it */
        buffer[i++] = (char)c;
        if (c == '\n') {
            break;
        }
    }

    if (i == 0) {
        /* we didn't read anything */
        free(buffer);
        return NULL;
    }

    buffer[i] = '\0';
    return buffer;
}

Demo

#include <string.h>
int main(void)
{
    char *s;
    while ((s = scan())) {
        printf("%04zu %s\n", strlen(s), s);
        free(s);
    }
}


That global array is indeed not good.  You'll need to pass around an array, but you shouldn't do it with a C-style array.  Doing that will cause it to decay to a pointer, which you should avoid in C++.  If you have C++11, you could use std::array, which will be set at an initial size.  But if you don't have C++11, and also want to adjust the size, use an std::vector.  You can also compare the two here.  Either way, you'll be able to pass any of them around nicely, and it's something you should be doing in C++ anyway.

To match your environment, the following code does not utilize C++11.

I'll use std::vector here, but this can be done with other STL storage containers.  Here's what a 2D vector would look like:

std::vector<std::vector<T> > matrix; // where T is the type

This type does look long, and you may not want to type it out each time.  To "shorten" it, you can use typedef to create an alias (which is not a new type):

typedef std::vector<std::vector<T> > Matrix;

With that, you can use this type as such:

Matrix matrix;

and create the 2D vector of a specific size.

However, this is where the syntax gets nasty (especially lengthy).  It's not set to a specific size, so you can just push vectors into it to increase the size.  For a fixed size (using your size and data type), you'll have something like this:

std::vector<std::vector<char> > matrix(HEIGHT, std::vector<char>(WIDTH));

This can be made shorter by having another typedef to serve as a dimension of the matrix.  This will also make it a little clearer what the vector means in this context.

typedef std::vector<char> MatrixDim;

It is then applied to the Matrix typedef:

typedef std::vector<MatrixDim> Matrix;

The 2D initialization will then become this:

Matrix matrix(HEIGHT, MatrixDim(WIDTH));

Now you can finally use this in main() and pass it to the other functions.  Before you do that, you'll need a different loop counter type.  With an STL storage container, you should use std::size_type.  With std::vector<char>, specifically, you'll have:

std::vector<char>::size_type;

You can use yet another typedef for this:

typedef MatrixDim::size_type MatrixDimSize;

Here's what the functions will look like with the changes (explanations provided).  I've also included some additional changes, which are also explained.  The entire program with my changes applied and produces the same output as yours.

setbit():

inline void set_bit(Matrix& matrix, MatrixDimSize x, MatrixDimSize y)
{
    matrix[(x) / 8][y] |= (0x80 >> ((x) % 8));
}

An additional parameter of type Matrix is added.  The matrix is passed in by reference and modified within the function.
The std::size_t parameters were replaced with the MatrixDimSize type.

print_screen():

void print_screen(Matrix const& matrix)
{
    for (MatrixDimSize y = 0; y < HEIGHT; y++)
    {
        for (MatrixDimSize x = 0; x < WIDTH/8+1; x++)
        {
            for (int i = 0x80; i != 0; i >>= 1)
            {
                std::cout << (((matrix[x][y] & i) != 0) ? '*' : ' ');
            }
        }

        std::cout << "\n";
    }
}

A parameter of type Matrix is added.  The matrix is passed in by const&, which is necessary as the function displays the matrix but does not modify it.  It's also cheaper to pass it this way as opposed to copying (passing by value).
MatrixDimSize is added for the loop counter types.
The if/else is replaced with an equivalent ternary statement.
A newline is done with "\n" as opposed to std::endl.  The latter also flushes the buffer, which is slower.  You just need the former.
i = (i >> 1) is shortened to i >>= 1.

Main():

int main()
{
    Matrix matrix(HEIGHT, MatrixDim(WIDTH));

    for (MatrixDimSize x = 0; x < WIDTH; x++)
    {
        for (MatrixDimSize y = 0; y < HEIGHT; y++)
        {
            if (x == 0 || y == 0 || x == WIDTH-1 || y == HEIGHT-1)
            {
                set_bit(matrix, x, y);
            }
        }
    }

    print_screen(matrix);
}

Both matrix vector typedefs are applied.
MatrixDimSize is added for the loop counter types.
The matrix is passed to and modified only by set_bit().

It is passed to print_screen() and is not modified.


Synchronizer for importing XML files into a database when folder content changes

I know this is a little late, but instead of the timed call to DoSync(), you could consider to use FileSystemWatcher and then subscribe to the relevant events.


Searching for bad Minecraft questions on Gaming.SE

The use of the Tags field on the Post is a poor choice for the query. It relies on a table scan, which is slow, because it has to check each question. Note, you can use the < and > characters to identify tag start and end values in the Tags column, but, as I say, don't use that column.

Instead, you should do a join with the PostTags and Tags tables. Using a CTE to simplify that query makes sense.

I really dislike the all-caps style of SQL, but realize that there is no standard. If you can change standards, please use lower-case for keywords... it makes the column and table names much easier to see (and those are the important parts). Still, you get +1 for being consistent in your capitalization. Consistency is really important, and you nailed it.

Note that the Posts table has no deleted posts, none. There's no need to check the DeletedDate at all.

So, joining Tags to PostTags gets you minecraft-tagged posts. Joining that to Posts gets you the ones you can test scores and closures on.

Here are unclosed, low-scoring, minecraft-related posts....:

WITH mctags AS (
  SELECT Id AS tid
  FROM Tags
  WHERE TagName LIKE 'minecraft%'
), mcqs AS (
  SELECT DISTINCT PostId
  FROM PostTags INNER JOIN mctags ON TagId = tid
)
SELECT
    Id AS [Post Link],
    OwnerUserId AS [User Link],
    Tags,
    Score
FROM Posts
INNER JOIN mcqs ON Id = PostId
WHERE Score <= -1
  AND ClosedDate IS NULL
  AND PostTypeId = 1

Note, I have tried to continue using your all-caps keywords.... despite myself ;-)

Hmmm, some aditional notes:

your text says you check for questions "below -1", but your code checks for questions "below 0" ... there is a difference between < and <=.
it does not check the closed-status of the post. If you want to see if a currently-open post was closed in the past, you need to check the PostHistory table.


Turning JSON objects into custom NSObjects

The correct way to check for success or failure of Cocoa (Touch) methods is
documented in
"Handling Error Objects Returned From Methods" in the "Error Handling Programming Guide":

  Important: Success or failure is indicated by the return value of the
  method. Although Cocoa methods that indirectly return error objects in
  the Cocoa error domain are guaranteed to return such objects if the
  method indicates failure by directly returning nil or NO, you should
  always check that the return value is nil or NO before attempting to
  do anything with the NSError object.

Which means that the result of

NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

should be checked with

if (fileContents == nil) { // Not: if (error) { ...
    NSLog(@"Error reading file: %@", error.localizedDescription);
}

And you should also use the error parameter and check the result of

NSArray *rawExhibits = (NSArray *)[NSJSONSerialization JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding] options:0 error:NULL];

The explicit cast to (NSArray *) is not necessary because the method
returns id and that can be assigned to any Objective-C object pointer.

Actually your method to read the JSON data is too complicated: The file
contents is first read into a string (using some encoding) and then converted to back to data (using the same encoding).
This can be simplified by reading the file into data in the first step:

NSData *jsonData = [NSData dataWithContentsOfFile:filePath];

You also have to decide what to do if reading the JSON data fails.
Just logging the error is not sufficient because then the program will
crash later.

The parameter naming in your init method

-initWithExhibitName:exhibitType:

seems a bit too verbose to me. It is clear from the class name W5BExhibit
that the object is some "exhibit", so I would shorten that too

-initWithName:type:

Adding new properties to your object class and the JSON file currently
requires a new init method with more arguments.
This can be greatly simplified using "Key-Value Coding" if you use the exact property names of your custom class as keys in the dictionary.

So assuming that W5BExhibit is defined as

@interface W5BExhibit : NSObject
@property(copy, nonatomic) NSString *name;
@property(copy, nonatomic) NSString *type;
@end

the JSON data should look like

[
  {"name":"Tennis Ball Launchers",
  "type":"Forces"},

  {"name":"Magnetic Hot Plates",
  "type":"Magnetism"},

  ...
]

Then you can create an object from a dictionary with

-(instancetype)initWithDictionary:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

self.allExhibits = [[NSArray alloc] initWithArray:myItems];

can be simplified to

self.allExhibits = [myItems copy];

The complete code then looks like this (where I have renamed some variables,
this might be a matter of personal taste):

// Read JSON data into array
NSError *error;
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
if (jsonData == nil) {
    // handle error ...
}
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonArray == nil) {
    // handle error ...
}

// Create custom objects from JSON array
NSMutableArray *items = [[NSMutableArray alloc] init];
for (NSDictionary *dict in jsonArray) {
    W5BExhibit *exhibit = [[W5BExhibit alloc] initWithDictionary:dict];
    [items addObject:exhibit];
}
self.exhibits = [items copy];


Disclaimer : most of my comments might be irrelevant as far as performance is concerned but should make your code better on different other aspects (readability for instance).

Listen to your compiler

Compiling your code with gcc -Wall your_file -lm gives me the following warning : sieve.c:7:11: warning: unused variable ‘p’ [-Wunused-variable]. I guess you know the first thing you can do :-).

Making things easier to follow

Splitting your code in small chunks is usually a good idea. Unfortunately, I am not quite convinced by setvalue because what it does is quite complicated and it makes it hard to give it a simple name, to test it out of the algorithm or to reuse it later on. Thus, from my point of view, it's easier to just remove this function.

A good habit : defining things in the smallest possible scope

It is quite common to try to define variables as late as possible and in the smallest possible scope. It prevents whoever reads the code to try to keep in mind the value of irrelevant things and to find what is used for what and it allows one to find easily when a variable becomes unused.

It makes even better if you use c99 as you can them define indices in for-loops.

Also, you can take this chance to define things that go together (such as prime_array and l) together.

Consistency

You should try to be consistent in how you write your code. You should define a way to put space in your code and try to stick to it as much as possible. Consistency is relevant also for braces (you did good), line breaks, incrementations (you used i++ and ++i).

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    int n = 100; //scanf("%i",&n);

    int sq = sqrt(n);

    int array[n];
    for (int i = 1; i <= n; i++)
    {
        array[i] = 0;
    }
    for (int i = 4; i <= n; i+=2)
    {
        array[i] = 1;
    }
    for(int i = 3; i <= sq; i+=2)
    {
        for (int j = i*i; j <= n; j+=(i*2))
        {
            array[j] = 1;
        }
    }
    array[2] = 0;

    int prime_array[n];
    int l = 0;
    for (int i = 2; i <= n; i++)
    {
        if (array[i] == 0)
        {
            prime_array[l] = i;
            l++;
        }
    }

    for (int i = 0; i <= (l-1) ; i++)
    {
        printf("%i\n",prime_array[i] );
    }
    return 0;
}

Keeping things simple

If you just want to write prime number on the standard output, you don't really need a temporary container for the numbers.

Naming things

  There are only two hard problems in Computer Science: cache
  invalidation and naming things. -- Phil Karlton

Naming is really important : here array is a pretty bad name as it doesn't convey any information about how the array is used.

Because of the way you use it, naming it not_prime would probably be a good idea. An even better idea would be to name it prime (or something like that) and use it in such a way that a true-ish value corresponds to prime number and 0 to non-prime numbers. Then you'd get something like :

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    int n = 100; //scanf("%i",&n);

    int sq = sqrt(n);

    int prime[n];
    for (int i = 1; i <= n; i++)
    {
        prime[i] = 1;
    }
    for (int i = 4; i <= n; i+=2)
    {
        prime[i] = 0;
    }
    for(int i = 3; i <= sq; i+=2)
    {
        for (int j = i*i; j <= n; j+=(i*2))
        {
            prime[j] = 0;
        }
    }
    prime[2] = 1;

    for (int i = 2; i <= n; i++)
    {
        if (prime[i])
        {
            printf("%i\n", i);
        }
    }

    return 0;
}

Algorithm

This is probably where it gets interesting : you have not properly implemented the sieve. At the moment, you apply the logic (from wikipedia) Starting from p, enumerate its multiples by counting to n in increments of p, and mark them in the list (these will be 2p, 3p, 4p, etc.; the p itself should not be marked). for p being the i in for(int i = 3; i <= sq; i+=2) but you should (or you can depending on the point of view) restrict yourself to prime values of i. This corresponds to adding if (prime[i]).  This should have a huge impact from a performance point of view.

A tiny problem

There is a variation of the quote above that goes like this :

  There are only two hard problems in Computer Science: cache
  invalidation, off-by-one errors and naming things.

It is relevant in your case because you have an array of n elements so the last index you should access is n - 1. The usual way to write the corresponding loop is with i < n (instead of the equivalent i <= n-1).

The i <= sq stays the same, I'll let you understand why on your own.

The code is now :

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    int n = 122; //scanf("%i",&n);

    int sq = sqrt(n);

    int prime[n];
    for (int i = 1; i < n; i++)
    {
        prime[i] = 1;
    }
    prime[2] = 1;
    for (int i = 4; i < n; i+=2)
    {
        prime[i] = 0;
    }
    for(int i = 3; i <= sq; i+=2)
    {
        if (prime[i])
        {
            for (int j = i*i; j < n; j+=(i*2))
            {
                prime[j] = 0;
            }
        }
    }

    for (int i = 2; i < n; i++)
    {
        if (prime[i])
        {
            printf("%i\n", i);
        }
    }

    return 0;
}

Comments

Even though you have missed an key step in the algorithm, you have tried some fancy optimisation, it would probably be worth commenting on those to explain why and how it works.


Adding  items dynamically to a to-do list

I recommend putting the script at the end of the page, just before </body> The reason is that you'll want to have scripts run when the DOM is ready (i.e. all the elements are present and ready for JS manipulation).

<center> is a deprecated stylistic element. To center an element, set left and right margins to auto. For text, use text-align: center:

.centered-element {
  display: block;
  width: 250px; /* Your desired width */
  margin-left: auto;
  margin-right: auto;
}

.element-with-centered-text {
  text-align: center;
}

This way, you have separation of concerns. HTML deals with describing the structure, CSS deals with styling your HTML.

* {
    font-family: "Times New Roman", Times, serif;
}

This is unnecessary. Applying font-family to body should be enough to apply it to all elements. Font style is inherited by all descendants until an element overrides it (and styles its own descendants).

fieldset {...}

input[type=text] {...}

button {...}

ul {..}

li {...}

I don't recommend styling elements directly because it breaks expectations. If I add a <ul> in your app for whatever purpose, I expect it to have bullets. But since your CSS removes them, my list won't have bullets. I'd have to add them back when, by default, they should have had bullets.

Instead, use classes to target app-specific styling and leave element defaults alone. The only time I would style an element directly is if it's part of a globally-applied theme or a normalizer.

As for your JavaScript, you could abstract away your element creation with a function like the following. This way, you don't have to repeat element creation scripts everywhere and you can easily describe dynamic HTML in a nested manner, like HTML.

const e = (name, properties = {}, children = []) => {
  // Create the element
  const element = document.createElement(name)

  // Apply properties
  Object.keys(properties).forEach(property => {
    element.setAttribute(property, propertyes[property])
  })

  // Append children
  children.forEach(c => {
    if(!c) return
    const node = (typeof c === 'string') ? document.createTextNode(c) : c
    element.appendChild(node)
  })

  return element
}

// Usage
const root = e('div', {}, [
  e('p', {}, [
    e('span', {}, [
      'Hello, World!',
      'Lorem Ipsum'
    ])
  ])
])

root.appendChild(e('span', {}, ['another piece of text']))

If the syntax looks familiar, it's because this is the basic premise of how most VDOM libraries work under the hood. They're just nested calls of functions that either return an actual element, or objects that represent elements (which are turned to elements later).

From there, you can describe and build your "components" like:

const LoadForm = () => {
  e('div', {}, [
    e('input', { type: 'text', name: 'user_input', placeholder: 'Enter here...' }),
    e('br'),
    e('button', { name: 'add_list' }, ['Add To List']),
    e('button', { name: 'remove_list' }, ['Remove From List']),
  ])

document.getElementById('in').appendChild(LoadForm())

You can even encapsulate this in a class if you want so that you can also add some helper methods.

class LoadForm {
  onAdd () {
    // Do something on add
  }
  onRemove () {
    // Do something on remove
  }
  render() {
    return (
      e('div', {}, [
        e('input', { type: 'text', name: 'user_input', placeholder: 'Enter here...' }),
        e('br'),
        e('button', { name: 'add_list', onclick: this.onAdd }, [
          'Add To List'
        ]),
        e('button', { name: 'remove_list', onclick: this.onRemove }, [
          'Remove From List'
        ]),
      ])
    )
  }
}

document.getElementById('in').appendChild((new LoadForm()).render())

Lastly, JavaScript is written in camelCase, not snake_case.


Scraping webpage elements with VBA script

The indentation is terribly misleading.

Compare yours:

  For n = 729 To 1000
    With IE
    Visible = False
    .navigate ws.Range("A" & n).Value
    Do
      DoEvents
        Loop Until .readyState = 4
      End With

To how Rubberduck's Smart Indenter default settings do it:

For n = 729 To 1000
    With IE
        Visible = False
        .navigate ws.Range("A" & n).Value
        Do
            DoEvents
        Loop Until .readyState = 4
    End With

If I glance at your code, I've no idea where the With block ends, and at second glance it appears to end in the middle of a Do loop body (which would be illegal) - it takes a third read to pick up the matching Loop keyword hidden in the code.

Before modifying anything, fix the indentation.

Running Rubberduck inspections reveal that variable Visible is never declared, which means Option Explicit isn't specified at the top of the module, which means VBA will happily compile typos, and that can easily lead to very hard-to-debug problems. ALWAYS specify Option Explicit, and declare all variables.

The macro is implicitly Public, n should probably be declared As Long, and the procedure name should be PascalCase, i.e. GetCountry, although the name suggests it's getting some value, which usually implies a Function that returns that value - Sub procedures do something, they don't get stuff.

On Error Resume Next will make your macro keep running in error state, which makes the assignments fail and, as you noted, the previous iteration's value gets repeated. Why not "reset" the 3 values at the end of each iteration? That way a failed getElementByID would write an empty string instead of duplicating data. That said...

    On Error Resume Next
    Country = Trim$(IE.document.getElementByID("youtube-user-page-country").innerText)
    On Error Resume Next
    Category = Trim$(IE.document.getElementByID("youtube-user-page-channeltype").innerText)
    On Error Resume Next
    Network = Trim$(IE.document.getElementByID("youtube-user-page-network").innerText)

Error handling doesn't work that way; only the first OERN changes anything, the other two are perfectly redundant. If you want to restore error handling you need to do On Error GoTo 0:

    On Error Resume Next 'suppresses run-time errors
    Country = Trim$(IE.document.getElementByID("youtube-user-page-country").innerText)
    Category = Trim$(IE.document.getElementByID("youtube-user-page-channeltype").innerText)
    Network = Trim$(IE.document.getElementByID("youtube-user-page-network").innerText)
    Err.Clear 'clears error state
    On Error GoTo 0 'restores run-time errors

As for speeding things up, assuming lightning-speed scraping this would be the bottleneck:

    ws.Range("B" & n).Value2 = Country
    ws.Range("C" & n).Value2 = Category
    ws.Range("D" & n).Value2 = Network

You know how many iterations you're making, therefore you know from the start how many rows you're going to be writing to the worksheet; the fastest way to write to a worksheet isn't one cell at a time.

Declare a 2D array, populate it in your loop, and dump the array onto the worksheet to perform all Range writes in one single, instantaneous operation. Otherwise you're having Excel raise Worksheet.Change events, repainting itself, and possibly re-calculating things every time you write to a cell.

You could "cheat" and do Application.ScreenUpdating = False at the top and set it back to True at the end of the procedure, but that wouldn't be any more efficient code. Go with the 2D array.


Return specific variable of Enum, determined by variable with the same name of another Enum?

How about (untested not near a computer at the moment)

   return (AnimalSpecies )Enum.Parse(typeof(AnimalSpecies ), categoryType.ToString());


I don't think you need MyListViewColumnData class there, I would replace it with interface and move the GetDataString implementation to MyListViewColumnData<TOut>. And you don't need dynamic here, just use object instead (yes, it will use boxing for most cases except strings, but it's more efficient than dynamics).

public class ColumnDataBuilder<T>
{
    public interface IMyListViewColumnData
    {
        string Name { get; }
        int Width { get; }
        ColumnType Type { get; }
        string GetDataString(T dataRow);
    }

    public delegate TOut FormatData<out TOut>(T dataIn);

    public class MyListViewColumnData<TOut> : IMyListViewColumnData
    {
        public string Name { get; private set; }
        public int Width { get; private set; }
        public ColumnType Type { get; private set; }
        private readonly FormatData<TOut> _dataFormatter;

        public MyListViewColumnData(string name, int width, ColumnType type, FormatData<TOut> dataFormater)
        {
            _dataFormatter = dataFormater;
            Type = type;
            Width = width;
            Name = name;
        }
        public string GetDataString(T dataRow)
        {
            object data = _dataFormatter(dataRow);

            switch (Type)
            {
                case ColumnType.String:
                case ColumnType.Integer:
                case ColumnType.Decimal:
                    return data.ToString();
                case ColumnType.Date:
                    return ((DateTime)data).ToShortDateString();
                case ColumnType.Currency:
                    return ((decimal)data).ToString("c");
                case ColumnType.Boolean:
                    return (bool)data ? "Y" : "N";
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    public IMyListViewColumnData Create<TOut>(string name, int width, ColumnType type, FormatData<TOut> dataFormater)
    {
        return new MyListViewColumnData<TOut>(name, width, type, dataFormater);
    }

    public IMyListViewColumnData Create(string name, int width, FormatData<DateTime> dataFormater)
    {
        return new MyListViewColumnData<DateTime>(name, width, ColumnType.Date, dataFormater);
    }
}

public enum ColumnType
{
    String,
    Integer,
    Decimal,
    Date,
    Currency,
    Boolean
}

Update
In comments it was asked if you can extract interface for ColumnDataBuilder. Of course you can :), and the easiest way would be to use "Extract interface" refactoring from ReSharper :). If you still don't use it you'll have to do that manually (move the IMyListViewColumnData and FormatData<TOut> declarations out of ColumnDataBuilder<T> first):

public interface IColumnDataBuilder<Tin>
{
    IMyListViewColumnData Create<TOut>(string name, int width, ColumnType type, FormatData<TOut> dataFormater);
    IMyListViewColumnData Create(string name, int width, FormatData<DateTime> dataFormater);
}


Outputting every second char in half string

Your code is slow simply because it does much more than it needs to. It copies the first half of the original string to a new StringBuilder, but then, you only use this StringBuilder to access its characters by their index, which you could also do with the original string, since the indexes of the characters in the first half of the original string and those in this new StringBuilder are identical.

So you might as well omit the variable afterAdd and use the original string in its place when you iterate over every second character:

for (int i = 0; i < rawString.length() / 2; i = i + 2) {
    finishChars.append(rawString.charAt(i));
}

Also, there is no need to handle the case afterAdd.length() <= 2 (which, after deleting afterAdd, would translate to rawString.length() <= 4) separately. The result of the method will be unaffected if you remove this extra if and simply let the for loop take care of it. In fact, I don't see anything special in this case in the first place, so I wonder why you make a special case for it.

Besides, I think it is strange that you let the main method read the number of test cases from the command line, but delegate the reading of the individual test cases to the calculate method, not least because this requires you to create a new Scanner object for every single test case. Why don't you do all the reading from the command line in one method, and then pass each test case to the method calculate as a parameter and let it do only do what its name suggest, namely calculating the result?

Anyway, I would suggest separating user interface from program logic, because right now, the method calculate not only calculates the result, but also prints it to System.out, which goes a bit against the Single Responsibility Principle. I think the code would be clearer if calculate returns a String representing the result, so that the calling method can decide what to do with the result.


Your naming conventions are a bit off. Property names (i.e. in FormClass) are commonly PascalCase.
If you are not married to the XML file structure (i.e. it's under your control) then you can simplify the de/serialization quite a lot by using the XmlSerializer. For example:

public class ClassDetails
{
    public List<FormClass> Models { get; set; }
}

public static class XmlUtils
{

    public static void Save<T>(T obj, string filename, string namespace)
    {
         using (var writer = new StreamWriter(filename))
         {
             var serializer = new XmlSerializer(typeof(T), namespace);
             serializer.Serialize(writer, obj);
         }
    }

    public static T Load<T>(string filename, string namespace)
    {
         using (var writer = new StreamWriter(filename))
         {
             var serializer = new XmlSerializer(typeof(T), namespace);
             return (T)serializer.Deserialize(writer);
         }
    }
}

then you can load/save the file with:

var details = XmlUtils.Load<ClassDetails>(@"c:\form.xml", "http://CompanyName.AppName.Service.Contracts");

...

XmlUtils.Save(details, @"c:\form.xml", "http://CompanyName.AppName.Service.Contracts");

Rather than having a big if-else cascade I'd use a dictionary to map the types:

Dictionary<string, string> ModelToFormTypeMap =
    new Dictionary<string, string> {
          { "System.String", "TextBox" },
          { "System.Enum", "DropDown" },
          ...
        };

then with an addition of a little bit of Linq you get

XmlUtils.Load<ClassDetails>((@"c:\form.xml", "http://CompanyName.AppName.Service.Contracts")
        .Models
        .Select(m => new FormStructure
                     {
                          FormStructureId = newGuid,
                          name = m.name,
                          displayname = m.displayName,
                          FormKey = m.key,
                          Required = m.required,
                          ClassName = "Incident",
                          ControlType = ModelToFormTypeMap[m.type]
                     })
         .ToList();


Firstly, given that you're using vector without namespace qualification (that is, not as std::vector), I assume you have a using namespace std; in this code. This is generally a bad idea, but especially so in this case. You use vector<unsigned char> & right (and vector<unsigned char> left), however, there is a std::right (and a std::left) defined in <ios>. This could potentially lead to some very confusing compiler errors.

Using a few tricks from <algorithm>, we can shorten the above code considerably.

void bigint::process_operands(vector<unsigned char> & left_, vector<unsigned char> & right_)
{
   auto& shorter = (left_.size() < right_.size()) ? left_ : right_;
   std::fill_n(std::back_inserter(shorter), std::abs(left_.size() - right_.size()), '0');
}

This is much more terse, but I find that using the standard library actually makes this code easier to read and more clear as to exactly what it is doing.


Standard primitive types vs custom structs in public API

custom value type

I would use this becasue the disadvantage that you name

  you need always cast values of primitive types to FourBitNumber which is inconvenient especially with literals.

can be easily overcome by implementing an implict operator for FourBitNumber to byte:

public static implicit operator byte(FourBitNumber value) => value._someValue;

and an explicit one for byte to FourBitNumber

public static explicit operator FourBitNumber(byte value) => new FourBitNumber(value);

so now it doesn't have any disadvanteges ;-)


var makeQuery = function makeQuery (id) {

There is no need to make makeQuery a local variable, just use a function declaration.

results = results[0];
results.key = radix64.fromNumber(results.id);

Your just augmenting the object, your not doing anything with it.

Other then that, your not creating new functions in a loop, your using a function constructor. This correct.

Your running all 19000 queries in parallel rather then in waterfall, which is also correct.

Edit:

Question 1:

You need to create 20000 contexts. Because there are 20000 values of i. Worrying about there being 20000 functions is a micro optimisation. v8 optimizes the hell out of your code.

It actually splits your functions into a hidden class seperate from the closure context, and in my memory you simply have 20000 values of i and one value for the function.

Just to remind you of rule 1.

  Never underestimate V8

Question 2:

makeQuery as a factory is the correct pattern to use.

The only other optimisation you can do is to write a real SQL query rather then 20000 dummy ones. But I'll ignore that because it's a dummy example.


Multiple DB record creation after a successful operation

My Suggestions are

If this class is not going to be instantiated you can remove the
      initialize method and even make it a module
Now you donot need to use instance variables , local variable passed via
params    work here
According to the book 'Object Oriented Design in Ruby - By Sandi Metz' a method need not know the order of
params and even    the
      ClassNames it is going to create objects from. Rather you can pass
      Hash of parameters and you can use like

Advantage: You can pass params in any order

def maintain_records(param)
  # set fallback/default params
  param.merge(default_params)
  customer, payment_details, response = param[:customer], param[:payment_details], param[:response]


Fist of all, the code doesn't work. here's my test method. I get an empty response.

public static void main(String... args) {

    HashSet<String> dictionary = new HashSet<>();
    dictionary.add("abcd");
    dictionary.add("abce");
    dictionary.add("abcf");
    dictionary.add("abcg");
    dictionary.add("abch");
    dictionary.add("abxd");
    dictionary.add("abxh");

    WordLadder wd = new WordLadder(dictionary);
    System.out.println(wd.findLadder("abcd abch"));

}

However, assuming you fix this, here is my review

API definition: the api you chose is counter-intuitive. why not accept two string words?
code to the interface: if you meant words to be a LIFO stack, use the Stack interface of push() and pop().  there are two reason for that: one is that it makes the usage of words clearer to another human. more importantly - how do you that LinkedList add() is doing the same as push()?
the method violates the single responsibility principle. it is parsing the input, it searches for a word in the dictionary and all the other stuff. what if you wanted to have another data structure for the dictionary? or put it in a DB?


Send multiple broadcast to multiple listeners

Concept
The basic concept of having a channel that you hand out to all receivers, and then close that channel as a signal, is a good one. The way you use that concept in your example usage, is a bit contrived, and I don't think it represents a real use-case, but it's good enough for an idea of how it could be used.
Communication
In Go, the best practice is to use "communication" over "locks". This is documented in the sync package as:

Other than the Once and WaitGroup types, most are intended for use by low-level library routines. Higher-level synchronization is better done via channels and communication.

In your code, what does this mean? It means the Mutex.Lock() code is not great, and that you should find a way to accomplish this with communication instead.
Further, there's no need for a RWMutex in your code, a simpler Mutex would be better...
For "Communication" in go, you need a go routine to communicate with. The go-routine is linked to the Broadcast instance, and it's the only routine that knows the Broadcast state, and the only go-routine that can change that state.
Now, you just need to communicate state changes to/from that go-routine using channels.
In code, it would look like:
// Broadcast allows to send a signal to all listeners
type Broadcast struct {
    poke      chan bool
    receivers chan chan struct{}
    done      chan bool
}

// NewBroadcast creates a new broadcast
func NewBroadcast() *Broadcast {
    bc := &Broadcast{
        poke:      make(chan bool),
        receivers: make(chan chan struct{}),
        done:      make(chan bool),
    }
    go bc.listen()
    return bc
}

func (b *Broadcast) listen() {

    defer close(b.done)

    notify := make(chan struct{})
    for {
        select {
        case ok := <-b.poke:
            if !ok {
                return
            }
            // all current receivers get a closed channel
            close(notify)
            // set up next batch of receivers.
            notify = make(chan struct{})
        case b.receivers <- notify:
            // great. A Receiver has our channel
        }
    }
}

// Close makes Broadcast implement the Closer interface
func (b *Broadcast) Close() error {
    select {
    case b.poke <- false:
    case <-b.done:
    }
    return nil
}

// Receive a channel on which the next (close) signal will be sent
func (b *Broadcast) Receive() <-chan struct{} {
    select {
    case r := <-b.receivers:
        return r
    case <-b.done:
        // FIXME - should probably return an error.
        return nil
    }
}

// Send a signal to all current Receivers
func (b *Broadcast) Send() {
    select {
    case b.poke <- true:
    case <-b.done:
        // FIXME - attempt to notify on a closed broadcaster... oops. Should probably return an error
    }
}

What's important in the above code? There is no sync usage, and there's a go-routine listen() for the Broadcast that manages the state. It listens for new Receivers and it listens for notification events. It is single-threaded, and as a consequence, it does not need any locking.
State changes are communicated via the receiver, poke and done channels.
Note that it now manages resources beyond the simple struct that it was, it's now got a go-routine you don't want to leak, so it should implement the Close() method, and you would do something like:
broadcaster := NewBroadcast()
defer broadcaster.Close()

It's very important to note that all the channels are unbuffered. This allows for a clean and reliable communication path, you can't have stale receivers, etc.


Count how many times a value is referenced in a grid

There is no intermediate operation that groups items by key.

But in your example there are some changes that can make code more readable.

Instead of collectiing to Map<Double, List<Point>> you could collect directly to Map<Double, Long>

.collect(groupingBy(p ->  pointGrid.get(p.x, p.y), counting()))

Instead of creating stream and performing output just use forEach on a map

.forEach((value, count) -> System.out.println("value :" + value + " count: " + count);

So together it looks like

seedPoints.stream()
    .collect(groupingBy(p ->  pointGrid.get(p.x, p.y), counting()))
    .forEach((value, count) -> System.out.println("value :" + value + " count: " + count);


From scratch pub sub definition and implementation

Error checking

Seems like you don't do all the error checking you'd need. For example, in this function

instance.sub = function(ns, fn) {
    if (!newPubSub[ns]) {
        newPubSub[ns] = [fn];
    }
    else if (Array.isArray(newPubSub[ns]) && newPubSub[ns].length > 0) {
        newPubSub[ns].forEach(function(savedFn) {
            if (fn === savedFn) throw new TypeError('This function already exists under this namespace, please provide a new method for this namespace or add a new namespace to hold this method/fn');
            else {
                newPubSub[ns].push(fn);
            }
        });
    }
    return this;
};

fn falls through the cracks if newPubSub[ns] is not an array but already exiss. Wouldn't you want to throw an error?

Similarly, you might also want to check that newPubSub[ns] has the expected form in unsub and that apply can be applied to each member of

Use closures to enforce encapsulation

All my concern about error checking relates to the fact that you are creating normal properties in these objects with your pub-sub methods, meaning that in the intervening time, a user can forget he was using a certain keyword with pub-sub and might use it for something else.

For example, here I corrupt your test variable by doing something entirely different with the alert key and forgetting I was using that for my pubsub functionality:

PubSub.init('test');

test.sub('alert', function(msg){
    alert(msg);
}).pub('alert',['bob'])

test['alert'] = "hi!"; // oops your 'alert' chain is gone

test.pub('alert', ['joe'])  //doesn't work

I think you'll want to restructure this to something like the following:

function pubsub() {
     var pub_arrays = {}
     return {
        sub: function(ns, fn){
                if(!pub_arrays[ns]) pub_arrays[ns] = [fn]
                else p
                },
        pub:  .... and so on ....

    };
}

In this way all your methods will have access to the object that holds the publishing arrays (one array for each key word) but outside users won't have access to this so they won't be able to change it.

Variable scoping in JavaScript is not a strong suit of mine, but I think something like this, using closures for encapsulation, is where you want to be if you don't trust the user, or yourself, not to accidentally...or maliciously...mess with your pub/sub methods.

Additionally, it looks like the most recent version of JavaScript may provide Class methods to encapsulate data. Read more on that in these SO posts:

https://stackoverflow.com/questions/29455692/how-does-closure-reify-the-data-encapsulation
https://stackoverflow.com/questions/8729714/closures-vs-classes-for-encapsulation


Python Decimal to Binary converter (without using bin() or output formatting)

You can remove half of you code.
You need the variables exp, total and decimal.
The rest are just noise.
You should remove all the int(decimal)s, decimal is only ever subtracted from, and so it's not going to become a float.
And so these are not needed.

You can remove all the code in if 2 ** exp == int(decimal):, instead just use exp as you do zeros.
You should split your while loop so that it only does one thing at a time.
You want an int log and then a while loop that converts the input to binary.
You can replace while zeros > 0: with Pythons way to duplicate strings. 0 * zeros.
You should make this a function.

This leads to code like:

def binary(number): # 4
    output = ''
    if number < 0:
        output = '-'
        number = -number

    exp = 1
    while 2 ** exp <= number: # 2
        exp += 1

    while number > 0:
        exp -= 1
        if 2 ** exp <= number:
            number -= 2 ** exp
            output += '1'
        else:
            output += '0'

    return output + '0' * exp # 1, 3

number = int(input("Enter a whole number: "))
print('Binary: ' + binary(number))


You can avoid specifying argument types twice by employing a constructor template:

template<typename F>
class finally
{
public:
  template<typename... Args>
  finally<F>(F action, const Args&... args) { /* business as usual */ }
  ...
};

But that's not everything. The std::bind's arguments are either copied or moved, they are never passed by reference. Thus, despite const Args&... args, you might end up copying your arguments.

To void this issue, consider using perfect forwarding (as well as ditching std::bind):

template<typename... Args>
finally<F>(F action, Args&&... args) :
    _action([action, &args...]{ action(std::forward<Args>(args)...); }) {}

Another thing worth considering is the exception safety of action. Since you're invoking it in a destructor, you're risking facing std::terminate if it throws. A small try block will fix it. Also, as of now, enabled seems redundant.

And yes, even with all these fixes, the semantics of finally seems rather unpleasant compared to more traditional scope guards. At least to me.

Edit: full code - https://ideone.com/iThn0i


"Guess a random letter" game with command line interface

You are using exceptions for flow control, and that is considered an anti-pattern.
Exceptions are meant for unhandlable conditions that would otherwise corrupt your application. Winning the game should not corrupt the application and cause undefined behavior. If it does, you are likely building a stock trading application (I'm only kidding ;-) of course).
Invalid input could certainly corrupt things or cause undefined behavior, but in this case your program should expect invalid input and handle it gracefully. Always expect the unexpected with user input.
When reading input, check that it is correct. Loop until you get correct input.
The $game-turn() method could return a "result" object, which reports back whether the game has been won, and if so who the winner is (and possibly a score). Again, handle this with a simple if statement:
$result = $game->turn($input);

if ($result->isWinningTurn()) {
    echo "Winner! {$result->winner}";
}
else {
    echo "next move";
}

If $game->turn() throws an exception, I would expect it to be an unhandled condition or something unrecoverable like an out of memory exception. As a programmer, I would be VERY surprised if winning the game crashed the program.
Now, the turn() method should throw an exception if you give it bad input. That makes sense. But you need to check for valid input before calling $game->turn($input). You likely need an isValidInput method on the game object in order to check this.
$game-turn("d"); // I expect this to throw

if ($game->isValidInput($input)) {
    $result = $game->turn($input)); // I expect this to always succeed

    if ($result.isWinningTurn()) {
        ...
    }
    else {
        ...
    }
}
else {
    echo "Bad input, try again."
}


Few thought,

You do a while loop  ( while( matcher.find() )  to find all matchs, then you do a for loop to deal with it. I think that can be done in only one loop.

in you last for loop, you could remove the first if :

   for(i = 0; i < (temp.size() -1); i++) {

     String tempL = temp.get(i);

     tempStringBuffer.append(tempL);

     tempStringBuffer.append("\n");
     lineCounter++;
     if (lineCounter == lines) {
            addPage(tempStringBuffer);
            tempStringBuffer = new StringBuilder("");
            lineCounter = 0;
            numberOfPages++;
     }

   } // End for loop

   tempDopLine = temp.get(temp.size()-1);

}

Other suggestion  the HashMap temp  got be only a array, because right now your code do a lot of autoboxing  ( from int to Integer) add and to retrieve information from your HashMap.

Edit: Here a quick example to merge your two loops:

String tempL = matcher.group();
while (matcher.find()) {

   tempStringBuffer.append(tempL);

   tempStringBuffer.append("\n");
   lineCounter++;
   if (lineCounter == lines) {
       addPage(tempStringBuffer);
       tempStringBuffer = new StringBuilder("");
       lineCounter = 0;
       numberOfPages++;
    }
    tempL =  matcher.group();

}

tempDopLine = tempL;


A few dozen teensy little things before I get to the meat of my review:

""" does not a multiline string make. It makes an empty string, a multiline string, and another empty string, all joined with newlines. Replace that with a heredoc -- this blog post goes into a good bit of detail about them.
I can't find a source for it, but console windows are typically 80 characters wide. Anything more and you get wrapping, which may look fine on *nix but on Windows it looks awful, because it's character-based wrapping, not word-based.
You made a bunch of grammar errors. I fixed 'em. Of course, most of the text could be reworked -- from the menu, you'd never guess that you can't translate to Russian, Spanish, Arabic, Pashto, or French, and you can't translate from base 64, binary, or MD5 hash. Well, maybe the last, but the rest it's not clear.
In a case statement, you can see if a number is within a range by doing when lower_bound..upper_bound. Standard range syntax applies.
You load the YAML file every time someone wants to translate something. Load it once, then either make it a $global variable or pass it in through translate's arguments.
When you say "redirecting", you probably mean "please try again", since there isn't a program in the world that "redirects" to the same menu when you mess up the input. You also don't want to use recursion to do that, since at some apparently random point they'll get a SystemStackError for recursing too deeply. There's a reason that Ruby has iterative loops.
On that note, why is it that when you enter invalid input anywhere else, you can try again, but in welcome_list, the program says the same thing but then exits? Just remove the text and have it end, or drop a loop in like everything else.
In md5, why is the hash called input_string? It's very obviously not what they inputted. That should really be called something like hash or result.
Some of your English is inconsistent -- personally, I like it all to look the same, because it gives it a more clean feel if you see 'Enter the text you want translated to [language]:' and 'abc' translated to [language] is: 'def' every time, instead of different text for each "language".
What on Earth is with this bit:

elsif input =~ /q/i
  list

Why does anything containing Q -- no, not something that's just that letter, read the documentation -- run a method, list, that doesn't exist? See, little teensy break-your-whole-program-no-matter-what bugs like that are why you have to test your code. I have no idea what you're trying to do here (i.e. go back to the welcome list or exit the program) so I assumed you wanted to exit the program. It's easier on me.
You use gets.chomp!.to_s, which makes no sense, because chomp! already returns a string, and the bang version (chomp! instead of chomp) affects nothing in this case. You use it right elsewhere, so I'm confused.

  NOTE: In refactoring the whole program according to my description below, some of these things become invalid. However, they're still worth mentioning.

Right, on to the fun stuff. Namely, why your program is absolutely terrible in one teeny tiny edge case that you should have seen a mile away: Two languages that have the same word will seriously screw each other up. See, you divide your YAML file into human-readable pieces by doing a little header with the language, but YAML doesn't see it like that. What it sees is a key, language_name, that's mapped to nothing at all. If you wanna say "These are all the words in Russian" and have YAML associate "russian" with those words, you have to indent1. For example:

russian:
    А: A
    В: V

instead of

russian:
А: A
В: V

Now, fixing this is gonna cause a few problems, because you were relying on your bad way of doing things. First off, translate is depending on everything being in the bottom level. Instead, what you're gonna have to do is change it like this:

  Add a parameter, all_words, and translations = all_words[language] before the first line.

Whew! That was an awful lot of effort. Now, that just broke all your code, because you're calling translate with only one argument, up above. What you're gonna wanna do is one of two things:

Hardcode your list into the case, sort of like it was before. I recommend against this.
Make it all super easy to change by having it sense what languages are available, update the list automatically, and put the appropriate options in the case.

Since the way I did it is pretty complicated, and involved an annoying amount of refactoring, I'm not gonna describe it in great detail. See the code if you want to know how. It's not that hard, just a different way of thinking.

There are a few remaining problems that I'm not going to fix, because I'm a lazy son of a you should practice. They are:

You mix input with calculation -- the calculation should ideally be separated from the input as much as is feasible. That is, if you're using puts and gets in the same method as the one where you perform a calculation, separate them. Note that this isn't always true -- if the calculation is solely for the purpose of dynamic text, for example, you shouldn't separate that out. Probably. It depends.
You made it almost impossible to easily loop the whole program, instead of just bits, because you focused on using recursion.

  Note: As a side effect of this, I couldn't easily figure out how to make restart work without recursion, so I left it alone.

In translate, if the word happens to be Q or q (which is unlikely but possible), you won't give the translation. You need to listen for CTRL+C (i.e. InterruptError if memory serves) and quit on that, then say that you're quitting on that.
If they enter the text in anything but all lowercase, it doesn't give them the translation, unless you put the uppercase versions in the YAML manually.
binary prints out the result as ["100001101000011010000110"] instead of 100001101000011010000110 (for the string aaa).

(mostly) Fixed code:

require 'yaml'
require 'base64'
require 'digest'

def welcome_list
  word_bank = YAML.load_file 'words.yml'
  languages = word_bank.keys
  non_language_options = 3
  i = non_language_options
  puts <<-END.gsub(/^\s*>/, '')
    >Welcome to Translation Center! Below you will find a list of as yet available features.
    >More features are being added as we speak! Have fun and enjoy!
    >
    >Translation Center can translate to:
    >
    >1: Base64
    >2: Binary
    >3: MD5
    >
    >Translation Center can translate from:
    >
    >#{languages.map { |item| "#{i+=1}: #{item}" }.join "\n"}
    >
    >Please choose from the list above by typing in the number in front of the option:
  END
  input = gets.chomp
  case choice = input.to_i
    when 1
      base64
    when 2
      binary
    when 3
      md5
    when (non_language_options+1)..(languages.length+non_language_options+1)
      translate(word_bank, languages[choice-non_language_options-1])
    else
      puts 'Invalid input.'
      return
  end

end

def translate(all_words, language)
  translations = all_words[language]
  while true
    puts "Enter word or phrase to be translated from #{language} to English, press 'Q' to quit:"
    input = gets.chomp
    if translations[input]
      puts "The translation of '#{input}' to English is: '#{translations[input]}'"
      next
    elsif input.upcase == 'Q'
      exit
    else
      puts 'Invalid word or phrase. Please try again.'
      next
    end
    break
  end
end

def binary
  while true
    puts 'Enter the text you want translated to binary:'
    text = gets.chomp
    puts "#{text} in binary is: #{text.unpack('b*')}"
    break unless restart
  end
end

def base64
  while true
    puts 'Enter the text you want translated to Base64:'
    input = gets.chomp
    new_string = "#{input}"
    puts "'#{input}' in Base64 is: #{Base64.encode64(new_string)}"
    break unless restart
  end
end

def md5
  while true
    puts 'Enter the text you want translated to MD5:'
    input = gets.chomp
    result = Digest::MD5.new
    result.update(input)
    puts "'#{input}' translated to MD5 is: '#{result}'"
    break unless restart
  end
end

def restart
  puts <<-END.gsub(/^\s*>/, '')
    >Would you like to:
    >1. Translate another
    >2. Go back to the main menu
    >3. Quit
  END
  input = gets.chomp!
  if input == '1'
    true
  elsif input == '2'
    puts 'Redirecting to menu...'
    welcome_list
  else
    puts 'Exiting...'
    exit
  end
end

welcome_list

Fixed words.yml:

spanish:
    a: to
    abajo: down

arabic:
    salam: Hi
    ana min: I'm from...

russian:
    А: A
    В: V

french:
    oui: Yes
    non: No

pashto:
    khe chare: Hello

japanese:
    yaa: Hi
    Yaa: Hi
    Konbanw: Good evening

As for a GUI, I suggest Shoes!, because it's conveniently already in Ruby.

1: Little teensy things like this are why you always, always, always, always read the documentation for everything you're using. ALWAYS.


Concurrent Queue with enqueue and dequeue using Stack as underlying data structure

Let's start by talking about the requirements.

Implement a thread-safe queue with an underlying stack. This is pretty basic, and has many ways to implement. However, the catch here is Enqueue and Dequeue need to be parallel. This is actually problematic, because as long as a lock is used, blocking will occur. So one can either not use locks, or try to limit their affects.

Your Implementation

Let's talk about your implementation. The first clear thing is that you are using locks, which means blocking is likely.

You have 2 locks, a good thought to try and separate the methods. You also have 2 stacks, each corresponding to a lock. Again, good thought, a single lock must be responsible for all the usage of a specific data source.

The usage of  the Stack class however, is a problem. Not only is Stack a outdated collection class, you must also be aware that it extends Vector and each method in it is synchronized. Luckily, as we will see, most of this doesn't have much functionality impact, but rather more of a performance issue. I would recommend using a Dequeue instead.

Another clear part is that it is an int only implementation. In reality, implementing it generically isn't that different or complicated, since an underlying data structure that supports generics is used.

Enqueue

Your enqueue is quite basic. Take the addition lock, add an element, notify about this addition, and release the lock.

The notifying part, tells us that there is waiting somewhere. I'm assuming this is a blocking queue then. This is both not defined in the requirements, and will cause blocking between the threads. Although, the use of notifyAll may cause a problem.

Otherwise, this is quite straightforward. However, it is already obvious that for the dequeue to work, addStack must be accessed, and thus addLock must be touched. This already tells us that blocking will occur.

Dequeue

Now comes the complicated part.

You start by entering a synchronized block of removeLock, this is quite expected, given how the stacks require usage of the locks.

You then check if the removeStack is empty or not. If it isn't you simply pop and return that value. This might seem like a basic example of a dequeue implementation, but that is not true. Because values are not added directly into removeStack, so it being empty means nothing about the actual queue.

Now, if removeStack is empty... then comes the problematic part. The moment addLock is used, we know blocking between the two method will occur.

If addStack is empty, you wait on addLock until it is notified. This is a blocking queue operation. Which again, is not specified as needed. A non-blocking queue operation would be simply to throw some exception indicating that no value is available. Let's return to the use of notifyAll. If multiple dequeue calls are done, all of them will reach the wait, since the locks are not actually taken while waiting. When enqueue is called and notifyAll is done, only one element was added, however all the waiting threads will wake up, and compete on getting the lone element. Perhaps it is best to just use notify.

if addStack is not empty, you copy the values from it to removeStack, and then pop from it and return a value. This still causes blocking between enqueue and dequeue. Luckily, if enqueue runs longer, the blocking will be decreased, since the values will already be in removeStack.

Catching of InterruptedException here is not really a good idea. When you have a blocking method (method that waits), throwing an InterruptedException is important, since this exception is thrown when the thread is interrupted and the user likely wants to stop the operations running.

Summary

Although it has some good logic behind it, in reality this implementation both doesn't accomplish the full requirements, and adds some complications. However, because stack is LIFO, the complexity in dequeue cannot be avoided. Luckily, this blocking is actually pretty short. So it might be even negligible enough to not care about it.

If enqueue is used more than dequeue, the blocking in dequeue will be longer for the first call, but because removeStack stores stuff, subsequent runs may be faster. If dequeue is used more than enqueue, dequeue will simply be blocked most of the time, because it is waiting.

Unfortunately using stack is not a good option for implementing a queue, because the 2 are completely reversed. There are more ways to implement, however they will all be blocking. So this really depends on how each method is used in relation to the other (frequency of calls, amount of read/write threads).

Snapshot on addStack

An example for another implementation is to use a single stack, and limit the holding of the lock by taking a snapshot of it:

private Stack<Integer> stack = new Stack<>();

public int dequeue() {
    Stack<Integer> reverse = new Stack<>();
    Stack<Integer> copy;
    synchronized(lock) {
        copy = new Stack<>(stack);
    }

    while (!copy.isEmpty()) {
        reverse.push(copy.pop());
    }

    if (reverse.isEmpty()) {
        throw new NoSuchElementException();
    }

    return reverse.pop();
}

Of course, if stack has a lot of elements, the synchronized block may take some time. However it is just a complexity of o(n).

Not using a stack

Of course not using a stack is always an option. There are many other data structures which can be used to implement a queue. However, the real problem is Enqueue and Dequeue need to be parallel.

There are 2 ways to safely deal with data in a concurrent environment:

Locks
Atomic operations

Locks, inherently can cause blocking. However, atomic operations, do not. So a true non-blocking implementation lays in using atomic operation.

Lock-free queue

The concept of a lock-free queue is to implement a queue, which is safe for use in concurrent environments, without using locks, which only leaves us with atomic operations for use.

This is actually well known, but difficult to implement. Depending on the amount of read/write threads, the difficulty can increase.

When working with a single writer thread, and a single reader thread it is actually quite simple.


Semantically structured HTML5 for a news page

As div elements have no meaning, we can ignore them for deciding which markup to use in your case. So your structure would be:

CSS contains the top image

News Title

Lorem ipsum doler si amet

    News autor, news tags, etc..

CSS contains the bottom image

If .news-section represents a section that can contain multiple article elements, this seems to be appropriate. But if it always contains a single news entry, you should omit the section.

It’s recommended to use heading elements of the appropriate rank (instead of h1 everywhere). So your h1 would at least (depending on where you include this snippet) be a h3.

Using the header is fine, but you may also omit it if you don’t need it for something specifically (e.g., for grouping some more header content for the news content).

It’s only appropriate to use CSS for including images if these images are decorative. If they represent relevant content, you should use HTML to include them (e.g., in the img element). If the images are decorative and if you need a separate HTML element to include them, you should use a div instead of p (but if you use the p for some other purpose, it’s of course good to use it for the CSS image in addition, if possible).

So a typical news section that contains several news entries could look like this:

News

Foo

Bar

If this news list represents the main content for that page, you can use the main element, e.g.:


Your code has three issues I can see.....

the stated goal is to return a new list, but your code returns one of the input lists that have been modified to have the merged results. This is buggy.
If the first two elements in each list are equals, your initialization process will fail, one of the comparisons, either the first, or the second has to have an = component, either <= or >=. As it stands, both the current and the other will point to the secondList if the first values are equals.
What's Node<int>? Why is it not Node<t>? Why use templates at all if you have only one template type that works?


General.

I notice that this question is a new expression of the other one you asked previously... but have now deleted!

In the previous question you didn't really explained something that becomes clear with this new one: you're looking for matching properties (with unknown names) successively at two nesting levels. In addition, 1st step works at level 1 of each object, while 2nd step works at level 2 for one object and level 3 for the other.

It's not a good idea to have deleted your previous question because, in the other hand, it showed an example of the involved objects structure. Since I remembered that, I could understand what your current code does (and BTW, understand what was not previously clear).
At the opposite, for somebody reading your current question, and without the knowing of the structure, it's pretty hard to see what your code is intended to.

About the current code.

The part of code you posted is inconsistent:

Its 2 last lines show that it's part of some loop, whose beginning is missing.
Yet at the beginning, it also lacks at least a declaration var aSelData = [];.
The assignation oPushedObject = {}; is out of date: this object is named oPushObj in the rest of the code.

Technically speaking, there are 3 points to notice:

Apart from its erroneous name, the above cited assignation should be var oPushObj = {}; in order not to pollute the global space.
Object.getOwnPropertyNames() is not the best way to get the involved properties, because it returns all properties, both enumerable or not, and with the prototype's one added: merely use Object.keys().
Likewise, if (oPushObj.hasOwnProperty(key) (note it lacks a closing parenthesis) is overkill where if (oPushObj[key]) is enough.

Note (thanks to @Roamer-1888 for pointing it): this last suggestion is pertinent only if the oPushObh[key] can't contain any falsy value.

Taking in account all the remarks above, here is a modified version of your code, where I also added some comments to explain how it works:

var aSelData = [];
jQuery.each(aDataCollection, function(iIndex, oData) {
    var oPushObj = {};
    // Here oPushObj gets populated
    fnAddEnt(aProperties, oData, oPushObj);
    // Look for matching properties between oPushObj and oData (1st level)
    Object.keys(oData).forEach(function(key) {
        if (oPushObj[key]) {
            // Look for matching properties between oPushObj[key] (2nd level)
            // and oData[key][iIndex] (3rd level)
            var source = oData[key].results[iIndex];
            var destination = oPushObj[key];
            Object.keys(source).forEach(function(sourceKey) {
                if (destination.[sourceKey]) {
                    // Populate oPushObj[key][sourceKey] value
                    destination[sourceKey] = source[sourceKey];
                }
            });
        }
    });
    aSelData.push(oPushObj);
});

Suggested alternate way

You currently use the simple approach of iterating through objects, for each level of the search process. And sure this works.

But you might also consider a different approach, based on extracting the intersection of the objects properties, successively for the 2 involved levels.
IMO the code is slightly more readable this way, making its main part look as a single-line one.
In the other hand, I couldn't assert it's faster.

Here is it:

var aSelData = [];
jQuery.each(aDataCollection, function(iIndex, oData) {
    var oPushObj = {};
    // Here oPushObj gets populated
    fnAddEnt(aProperties, oData, oPushObj);
    // Look for matching properties between oPushObj and oData (1st level)
    for (var key of arrayIntersect(
      Object.keys(oPushObj), Object.keys(oData)
    )) {
        // Look for matching properties between oPushObj[key] (2nd level)
        // and oData[key][iIndex] (3rd level)
        for (var sourceKey of arrayIntersect(
          Object.keys(oPushObj[key]), Object.keys(oData[key][iIndex])
        )) {
            // Populate oPushObj[key][sourceKey] value
            oPushObj[key][sourceKey] = oData[key][iIndex][sourceKey];
        }
    }
    aSelData.push(oPushObj);
});

function arrayIntersect(a, b) {
  return a.filter(key => b.indexOf(key) > -1)
}


Removing all duplicated pairs in a Python list

I think you should try re-making __removepairs_once__ only using results.
No most_recent_element.

So, you would want to retry you algorithm, most_recent_element can be results[-1].
Using this you should come to this stub code:

def _remove_pairs(list_):
    result = []
    for item in list:
        if item == results[-1]:
            # remove last item
            # don't add this item
        else:
            # add this item
    return result

Using this you should notice that it'll error if results is empty, this means you should use the else if it is.
The if block is surprisingly simple, it's results.pop(). And the else is results.append(item).

def _remove_pairs(list_):
    results = []
    for item in list_:
        if results and item == results[-1]:
            results.pop()
        else:
            results.append(item)
    return results

A quick test of this actually (unsurprisingly) returns the final list that you wanted.

Don't use __{}__ for anything! Only use it for pythons magic functions!

You should also not use list but list_ as then you can still convert something to a list.


Should methods be inside classes? in Ruby

This "global function" style works for small scripts but isn't reusable.
A more practical problem with it is if you want to have state that is shared between functions, you don't have anywhere to store it (well, you could use global variables ($var), but that's prone to conflicts).
For a more encapsulated design, create a class that does the work and move the methods into the class. See for example definition and usage.


Java conventions

In Java variables are written in "lowerCamelCase", starting with a lowercase letter, so please use getBinaryGap(int n). See also Oracle  code conventions

String conversion

The performance can be increased because you use a conversion to String, while you can solve it using bit-fiddling only.

Complexity

You code has one loop, with all constant time operations. Integer.toBinaryString(int n) has cost that is linear with n. The total performance will be O(n), that is OK.

Bit flipping

Following your logic, but all as bit-test:

public static int getBinaryGapBitFiddling(int n) {
    if (n < 5) {
        return 0;
    }
    int currentGap = 0;
    int finalGap = 0;
    int currentBit;
    for (int i=0 ; (currentBit = (1<<i))< n; i++)
    {
        int nextBit = currentBit << 1;
        if (currentGap == 0) {
            if ( ((currentBit & n) > 0 )  &&  ((nextBit & n ) == 0 )) {
                currentGap++;
            }
        } else {
            if ((nextBit & n ) == 0) {
                currentGap++;
            }
            if ((nextBit & n ) > 0) {
                finalGap = finalGap<currentGap ? currentGap:finalGap;
                currentGap = 0;
            }
        }
    }
    return finalGap;
}

More optimizations

You could probably use bitmasks for faster scanning as well. For example 10 and 01 are the start and end of a run.


Finding the shortest path (between source and destination) with the least number of edges

Naming
#define n 5
#define s 0
#define d 4

We normally use ALL_CAPS for preprocessor macros, to warn readers.
void Dijkstra(int Graph[n][n], int _n,int _s, int _d);

I'd prefer lower case for the function name and arguments (PascalCase is conventionally used for typedefs).  The identifiers beginning with underscore are risky, because they are reserved for use by your compiler and standard library; also they don't tell us anything about their meaning.  n seems to be the number of nodes; are s and d the start and target?
Separate the work from the I/O
At the moment, the Dijkstra() function both finds a route and prints it.  Well-structured code separates these two activities, so you can do other things with the route.  You'll need to define a suitable data structure to return for the route - you can start by filling in an array (remember to check bounds); perhaps move to a linked list or an allocated array.
Flexibility
At some stage, you'll want to move to supporting graphs of arbitrary size.  For that, you're going to need to change n from constant to variable, and allocate and free storage for the distances.  That will be worthy of its own review when you reach that stage.


Best practice for lining up PHP syntax in HTML page

You can use other kind of syntax:

...
...

    <?php if ($this->session->flashdata('message')): ?>

            ...
        ...

    <?php endif; ?>

So, <?php ?> can be in 1 line and I think it's beauty:)

Anyway, There are no any 'right' way to do it. You can(and should) choose your own one


Overall, it looks quite fine, with some smaller and bigger issues.

Parsing the add command

It's not so great to use the '<address>' string twice here:

    if args['<address>']:

        emails = (
                  {
                   'address': args['<address>'],
        # ...

You might mistype one of them. Or you might change something later and forget to update it everywhere. It would be better to put the value of args['<address>'] into a variable, and use that variable in evaluations and assignments.

This part is also awkward:

        emails = ( ... )
        if args['--description']:
            emails[0]['description'] = args['<description>']
        if args['--pswd']:
            emails[0]['password'] = args['<password>']

It would be much easier to use description and password variables to store defaults, then update these variables if --description or --pswd were given, and finally create the emails tuple.

Like this:

    address = args['<address>']
    if address:
        password = None
        description = None
        if args['--description']:
            description = args['<description>']
        if args['--pswd']:
            password = args['<password>']
        emails = (
            {
                'address': address,
                'password': password,
                'description': description,
            },
        )

Parsing the remove command

Here, if the second if statement is true,
it will overwrite the effect of the first:

    if args['<address>']:
        emails = (
            {
                'address': args['<address>'],
            },
        )
    if args['--file']:
        emails = fp.process_file(args['<filename>'])

That suggest that you should use an elif, and switch the order of the statements:

    if args['--file']:
        emails = fp.process_file(args['<filename>'])
    elif args['<address>']:
        emails = (
            {
                'address': args['<address>'],
            },
        )

emails might be undefined

Both the parsing of add and remove have a problem:
As their last step they do something with emails,
for example eman.add_emails(emails) and eman.remove_emails(emails),
but at that point the emails variable might be undefined.

This can be fixed by adding validation for these commands.
It looks that either of these must be true, checked in this order:

--file was specified and <filename> parameter was given
<address> parameter was given

For example:

if args['--file']:
    filename = args['<filename>']
    if filename:
        emails = fp.process_file(filename)
    else:
        raise Exception("Filename parameter missing")
else:
    address = args['<address>']
    if address:
        emails = ( ... )
    else:
        raise Exception("Address parameter missing")

# main action


Watch a directory and insert new entries into database

Naming

Nothing in the code suggests that csv files are special. Why a backup is called backup_csv?
Exception handling

The main code removes the file regardless of the insertion success. For example, if connect fails, the file is still removed. Is this an intended behaviour? I recommend to call os.remove() inside backup_csv.
misc

What is the purpose of time.sleep(1)?
I don't see a reason for if files clause. The for i in files works as expected if files is empty.


Locating the Bash history file for a user

A clearer way would be to establish a default for the user, then locate the Bash history file for that user.

You're making the assumption that the user's home directory will be in /home, and that a root user's home directory will be /root.  That's a convention for Linux, but it won't be true at larger Linux installations, and it isn't the convention for other operating systems.  Here's one way to do the lookup for systems that use GNU libc:

user="${1-root}"
histfile="$(getent passwd "$user" | cut -d: -f6)/.bash_history"

A cross-platform way is to use tilde expansion, though the eval could be dangerous if the input is untrustworthy:

histfile=$(eval echo "~${1-root}")/.bash_history

The isRoot check should be done on the username (or UID) instead of the home directory.  It feels very unconventional to assign a boolean variable in Bash.  Keep in mind that the convention is that zero statuses are considered "true" and non-zero statuses are considered "false".  I'd advise you not to write that statement at all, but can't really advise you what to do instead since you haven't shown us what you intend to do with that variable.


Existential quantification versus explicit types

Can you make Player a datatype instead of a typeclass? The datatype can have exactly the same methods but with the first argument elided. Make Player an instance of Show, and voilá, data Players = Players Player Player Player. One implications is that a bot and a human player are now both just values of the same type, Player. Thus the chooseCard, chooseCardOpen and onCardPlayed of a bot can yield a human with a hand and cards on the table mid-game, and vice versa. I'd love to have the freedom to have a bot play the first few rounds for me, yield to me when the game starts going, and play out the last couple of rounds when I feel victory is secure! And as you note, you already opted to give every player type MonadIO, anyway, so these types are not really looser.