As mentioned in the comments this code is not long winded at all.  It is very clean in general.  Too clean in fact as you will see below.

You cannot create an empty linked list with your init_list.  However, in other parts of your code you assume list may be empty.  It is useful to be able to create an empty linked list since you may not know what you want your first node to be in advance.  I'd suggest changing init_list.
I personally like symmetry in linked list code.  You can always create the dual of one function by swapping all prevs with nexts and all heads with tails.  I don't think your push_back code should call push_front.  You can handle the else condition just like you did in push_front except by swapping variable names.
insert_after is incomplete.  Remember this is a doubly linked list.  Also the function doesn't handle the case when you insert after the current list->last.  You need to add the linked list to the function arguments.
remove_node does not handle all cases.  What if node was the head of the list?  What if it was the tail of the list?  What if it was both the head and the tail?  You don't actually have to write three different cases to handle this but you can.
As simply a style choice I would rename previous to prev
I am ignoring that you never check for your pointers being NULL

Edit:

This code actually can produce an empty list by passing NULL in as an argument to init_list


Random temp folder implementation for unit testing

You could easily wind up with collisions on the folder name if the method is called multiple times in very quick succession because of the new Random() being declared for each usage. It should be instantiated once, and since you mentioned it could be called on multiple threads, it should be mutexed onto one at a time. Finally, it's not a good idea to have fields be public - making it a property is luckily pretty easy. So:

public class TempFolder : IDisposable
{
    private static readonly Random _Random = new Random();

    public DirectoryInfo Folder { get; }

    public TempFolder(string prefix = "TempFolder")
    {
        string folderName;

        lock (_Random)
        {
            folderName = prefix + _Random.Next(1000000000);
        }

        Folder = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), folderName));
    }

    public void Dispose()
    {
        Directory.Delete(Folder.FullName, true);
    }
}

Now, what I don't address here is the issue of constructors or the Dispose() method possibly throwing unexpected exceptions. Just know that's a possibility and you may want to catch them and/or re-raise them depending on your use case.


I do not know SFML so here some non SFML comments.

First of all - codding style.

You need to indent the code. It is very hard to read it.
Be consistent you are mixing coding styles - you are open { on different "places"

int main(){ <== open here

   while (window.pollEvent(event))
   {  <== and now here
       if (event.type == sf::Event::Closed)
           window.close();
   }

main() function is very long.

try separate the function into several small functions,
for example init_game, play_game end_game and so on.

DRY - don't repeat yourself.

consider this code:

sf::CircleShape circle;
circle.setFillColor(sf::Color::Red);
circle.setPosition(100, 100);
circle.setRadius(20);

sf::CircleShape circle2;
circle2.setFillColor(sf::Color::Yellow);
circle2.setPosition(200, 200);
circle2.setRadius(20);

sf::CircleShape circle3;
circle3.setFillColor(sf::Color::Black);
circle3.setPosition(300, 300);
circle3.setRadius(50);

it is basically same thing three times. I would do:

// to do fix color_type
sf::CircleShape createCircleShape(color_type color, int x, int y, int r ){
   sf::CircleShape c;

   c.setFillColor(color);
   c.setPosition(x, y);
   c.setRadius(r);

   return c;
}

// ...
sf::CircleShape circle  = createCircleShape(sf::Color::Red, 100, 100, 20);
sf::CircleShape circle2 = createCircleShape(sf::Color::Yellow, 200, 200, 20);
sf::CircleShape circle3 = createCircleShape(sf::Color::Black, 300, 300, 20);

this way it is much more readable.

You can do same for controlling the keyboard:

if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Up)){
    circle.move(0, -0.5);
}

you can write a function that get four keyboard codes, event and circle and you can do something like this:

void controlPlayer(const event_key_code &keycode, sf::CircleShape &circle,
           const key_code_type up,
           const key_code_type down,
           const key_code_type left,
           const key_code_type right);
// then you do:

if (event.type == sf::Event::KeyPressed){
        controlPlayer(event.key.code, circle, sf::Keyboard::Up, sf::Keyboard::Down, sf::Keyboard::Left, sf::Keyboard::Right);
        controlPlayer(event.key.code, circle2, sf::Keyboard::W, sf::Keyboard::S, sf::Keyboard::A, sf::Keyboard::D);
}

Hope this helps for start!


Abstract class is ideal for this:

abstract class ProductsTextareaBase {

  protected abstract function getColumns();

  public function parse($productsTextarea) {
    $products = explode("\r\n", $productsTextarea); // sanitize

    $y = 0;
    $productArray = array();

    // explode and trim each product, assign values to an array
    foreach($products as $product) {
        $product = array_map('trim', explode(',', $product));
        $i = 0;
        $columns = $this->getColumns();
        foreach($product as $col) {
          $productArray[$y][$columns[$i]] = $col;
          $i++;
        }
        $y++;
    }
    return $productArray;
  }
}

class WidgetProductsTextarea extends ProductsTextareaBase {
  protected function getColumns() {
    return array('name', 'cost', 'quantity');
  }
}


Right now the program will have a problem if you use a word which has the same letter more than once. string.index will only return the index of the first occurrence. What you could do instead is use a set to check what letters still need to be guessed. If a character in the word is still in the set, it hasn’t been guessed and an underscore should be printed. If it isn’t in the set, it has been guessed and it should be printed.
The code can be simplified significantly. You only really need one function which takes a list of strings as an argument. You could do something like this:
import random

def hangman(word_list):
    word = random.choice(word_list)
    letters = set(word)
    guesses = len(word) + 3
    while len(letters) > 0 and guesses > 0:
        guess = input(str(guesses) + " guesses left\nguess something:\n")
        if guess in letters:
            print("correct")
            letters.remove(guess)
        else:
            print("wrong")
        guesses -= 1
        print(*(ch if ch not in letters else '_' for ch in word))
    print("win" if len(letters) == 0 else "lose")

if __name__ == "__main__":
    hangman(["bike", "monkey", "planet", "mississippi"])

NITPICKING
You have a function in your current code which could be replaced with a call to input. the user_input function could be replaced with this: input("Enter a guess:\n"). Also you can simplify this:
if game:
    print("Bravo")
    self.no_of_try -=  1
else:
    self.no_of_try -=  1
    print("Wrong")

into this:
self.no_of_try -=  1
print("Bravo" if game else "Wrong")

I also noticed a couple things in the __init__ method. The word list and the randomly chosen word’s length don’t need to be instance variables because they’re only used in __init__, and you don’t need to cast the length to int because it’s already an int.


Size of initial list in the following code is less:

var x = Enumerable.Range(1, 10)
                  .Select(x_ => x_ * 10)
                  .Concat(new[] {25})
                  .Distinct()
                  .OrderBy(x_ => x_)
                  .ToList();

Otherwise your original code is perfect.


Do conversions once
As written, with the example input, str(binary_value) will be called 22 times, with the same input value, and returning the same value each time.  This is very inefficient; it is wasted work.  It would be better to call it once, and store the result, and use this stored value:
def binary_to_decimal_converter(binary_value):
    binary_value = str(binary_value)
    # ... rest of function, without any more str(binary_value) calls

But ...
Representing Binary Numbers
As pointed out by harold in the comments, the literal 1111101100 is an integer value slightly larger than one billion in Python.  You should use a string to represent a binary number to be converted.
# Calling the function
binary_to_decimal_converter("1111101100")

Since we're passing a string to the function, all of the calls to str(binary_value) are now completely unnecessary.
String Constants
        if str(binary_value)[loop_var] == str(1):

Again, using the example value, the expression str(1) will be evaluated ten times; once for each digit of the input.  This will convert the numerical value one into the string "1", which will be discarded immediately after use, only to be recreated on the next iteration.  Why not just use the literal "1"?  Not only is it more efficient; it is 3 characters shorter.
Loop like a Native
See "Loop like a Native" by Ned Batchelder on YouTube for more details, motivation, etc.
Part 1
Our modified code now looks like this:
    loop_var = 0
    while loop_var < len(binary_value):
        # ...
        loop_var += 1

len(binary_value) is computed once for each iteration through the loop; 11 times, including the last pass where the condition evaluates to False and the loop terminates.  Since the string doesn't change inside the loop, the length won't change either, so this value is a constant.
    loop_var = 0
    limit = len(binary_value)
    while loop_var < limit:
        # ...
        loop_var += 1

Now that we've recognized that limit is fixed, we can see this is actually a for loop, that starts at zero, counts up by 1, and stops when it reaches limit.  Instead of manually adjusting the loop_var by 1, and manually doing the comparison, we should simply use the for loop, over the required range, which is much more efficient:
    for loop_var in range(len(binary_value)):
        # ...

Part 2
Our loop now looks like:
    for loop_var in range(len(binary_value)):
        if binary_value[loop_var] == "1":
            # ...
        # ...

Indexing is expensive in Python.  Anytime you see a for loop, using a range(len(thing)), and the loop variable is only used as a index into the thing which the range is looping over, thing[loop_var], then we want to let Python do the indexing for us in the for statement:
    for digit in binary_value:
        if digit == "1":
            # ...
        # ...

Return Value
    return print(f"Decimal: {decimal_value}")

Is this function returning a value, or is it printing the result?  Currently, it is taking the value which is returned by the print() function, and returning that.  Ie)
    temporary = print(f"Decimal: {decimal_value}")
    return temporary

But print() returns None, so this is effectively:
    print(f"Decimal: {decimal_value}")
    return None

And if the function ends without a return statement, it automatically returns None anyway.  So the return can simply be omitted.
Note: It is better to return results from a function that does a calculation, without printing anything inside the function, and have the caller do the printing.  This will create more flexible code in the future.  Left to student.
Improved code
def binary_to_decimal_converter(binary_value):
    print(f"Binary: {binary_value}")
    decimal_value = 0

    # power is power of number 2
    # power must be less than string length because computer starts counting from 0th index
    power = len(binary_value) - 1

    for digit in binary_value:
        if digit == "1":
            decimal_value += 2 ** power
        power -= 1

    print(f"Decimal: {decimal_value}")

# Calling the function
binary_to_decimal_converter("1111101100")


Keeping a search history in localStorage, with a length limit

So if I understand the code correctly:

You're keeping track of search.
You're adding the search items to local storage.
You're keeping the history to a max of 3 items.
You're displaying them in the UI.

I would suggest to leave out the UI logic out of the storage logic. The storage logic should only deal with storage and retrieval from local storage. UI updates should be separate.

Next is to not depend on the UI for maintaining state. That's the job of your data. The UI should merely be a representation of the data. That means, you shouldn't be depending on innerHTML to keep that history.

The search history is simply an array which you push in stuff, and shift out stuff when it goes beyond 3. You do not need an item in the storage for each. Since localStorage only keeps strings, you'll need to use JSON.stringify and JSON.parse to serialize and deserialize the data, respectively.

I would split the functions, one for updating the stored data, and the other to update the UI based on the existing data.

function searchHistory(searchParam) {
  const maxHistoryLength = 3;
  const history = JSON.parse(localStorage.getItem('searchHistory') || '[]');
  const isHistoryMaxed = history.length === maxHistoryLength;
  const workingHistory = isHistoryMaxed ? history.slice(1) : history;
  const updatedHistory = workingHistory.concat(searchParam);

  localStorage.setItem('searchHistory', JSON.stringify(updatedHistory));
}

function updateSearchHistoryUi(){
  const history = JSON.parse(localStorage.getItem('searchHistory') || '[]');

  $('#history').empty().append(history.map(v => `

${v}

  `).join(''));
}


Initializing an array of relative coordinates of all adjacent 2D matrix cells

Your solution relies excessively on magic numbers, such as 9 and 3.  It also obscures the Cartesian-product aspect of the problem.  Therefore, I think it could be better written as:

(< (< (< 4))) { ,/ > { ;~i:1

Derivation

(i:1) produces the list _1 0 1.
{ (i:1) ; (i:1) produces the Cartesian product:

┌─────┬────┬────┐
│_1 _1│_1 0│_1 1│
├─────┼────┼────┤
│0 _1 │0 0 │0 1 │
├─────┼────┼────┤
│1 _1 │1 0 │1 1 │
└─────┴────┴────┘

@earl points out that this reflexive expression can be written more succinctly as {;~i:1.
> unboxes it into a 3 × 3 × 2 matrix, and ,/ flattens it into a 9 × 2 matrix:

_1 _1
_1  0
_1  1
 0 _1
 0  0
 0  1
 1 _1
 1  0
 1  1

The only remaining task is to exclude the 0 0 row, which is element 4.  The (< (< (<4))) { selector seems to do this job.


Effieciently validate multiple DataRows with return early option

The if condition

if( batch == null || batch?.Count() == 0 ) { logger.Error( MSG_NO_DATAROWS ); return false; }

has some flaws:

the Null-Conditional operator ? on batch?.Count() == 0 isn't needed, because you already check for batch == null
If the passed IEnumerable<DataRow> isn't a Collection<T> the IEnumerable<DataRow> will be enumerated completely for calculating the Count.
Assume you have millions of items in that IEnumerable<T> guess how much time it takes to iterate twice (once for Count() and once for the foreach).
Having multiple statements in a single line reduces the readability of the code.

A better way would be to use the Any() method like so

if( batch == null || !batch.Any())
{
    logger.Error( MSG_NO_DATAROWS );
    return false;
}


Since 7 is prime, the following pseudo code works, although it involves some “thinking around the corner”.

[(r,c) | r<-[1..7], c<-[1..7], r * c not in [1, 3, 5, 7, 21, 35, 49]]

A more straightforward way would be

(r /= 1 && r /= 7 && c /= 1 && c /= 7) || even r || even c


VBA code that pulls information from 1000+ files in directory performance

Preamble

The first step to optimizing this code is most likely not something you'll think helpful. It's generally accepted wisdom among the regular VBA reviewers here that writing code should follow a three step-process:

Make it work
Make it right
Make it fast

The problem with the code you presented is that it's really long and hard to understand (and accordingly optimize). Basically you're jumping the gun and try to run before you walked.

Constants

Constants are values that can be known at compile time and that do not change when the macro is run. You should extract such values into module-level constants like so:

Private Const myPath As String = "C:\Users\...."
Private Const myExtension As String = "*.xlsm"
' ... ?

Variable definitions

It's great that you're declaring your variables. I didn't see an Option Explicit though. It's generally cleaner and easier to require variable declarations to prevent bugs from misspellings and other quirks. Use any security that the language can give you.

In addition to that there's a small weirdness about VBA and As-Declarations:

Dim j, r As Integer
Dim SeenPart, SeenCount As Integer

This code actually will make the types of r and SeenCount Integer, but j and SeenPart will be declared and used as Variant, which can slow your program down.

To prevent this behaviour from ruining your day, I'd recommend declaring each variable on a separate line.

Last but not least: Integer is a 16-bit signed integer. Modern CPUs are highly optimized for arithmetics on 32-bit signed (and unsigned) integers. Surprisingly often it's faster in VBA to use Long over Integer.

Submethods

To make code easier to follow, it helps to keep the lifetime of variables and constructs as small as possible. This reduces the load on the reader's short-term memory and keeps capacity free to think about what the code actually means instead of just being preoccupied with which variables are actually relevant here.

Overall you should strive to make procedures as short as possible by extracting common code into a new procedure.

Consider:

Sub LoopAllExcelFilesInFolder()
    On Error GoTo ResetSettings
    OptimizeMacroSpeed()

    AggregateData()

ResetSettings:
    ReinstituteApplicationState()
    On Error GoTo 0
End Sub

This is very easy to understand at the first reading. Of course it doesn't contain all information that you need, but it helps you understand the overall goal of the code. Now AggregateData could read something like this:

Sub AggregateData()
    Dim myFile As String
    myFile = Dir(myPath & myExtension)

    Do While myFile <> ""
        Dim workbook As Workbook
        Set workbook = Workbooks.Open(Filename := myPath & myFile)
        ' Ensure workbook has opened
        DoEvents
        CopyData(workbook)

        workbook.Close SaveChanges := False
        ' Ensure workbook has closed
        DoEvents
        myFile = Dir
    Loop
End Sub

At this point it should be fairly obvious what CopyData should be doing, so I won't elaborate further :)

Finally Optimizations

First things first: Accessing a Worksheet is slow. Accessing a Workbook also is. What you accordingly want to do is minimize the number of times you do so.

Since VBA is an interpreted language (after having been compiled to p-code), every instruction is executed independently. This means that the copy-process is terrifyingly slow:

Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2")

^^ this code is executed every single line, which means a tremendous overhead.

Luckily VBA has a builtin mechanism to help us with this:

With Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2")
    .Offset(k, 0) = ActiveCell.Offset(i, 0)
    .Offset(k, 1) = Range("D8")
    .Offset(k, 2) = Range("D11")
    ' ...
End With

Instead of executing the whole chain of Workbooks(..).Worksheets(..).Range("A2") every line, now VBA executes the chain only once and keeps a reference of that object in the with-block. This object can now be accessed directly and most of the overhead is removed.

A word of caution

The word of caution also is a possible optimization... Working with Selection and ActiveWorkbook and ActiveWorksheet is downright dangerous. In the middle of macro execution, your user could click on things, change the reference and suddenly data is not where you expect it anymore and everything breaks.

To prevent that you should always (read: whenever possible) keep a reference to a Range or Worksheet you're working with in a variable. That is pretty safe from the user and also allows for some minor optimizations.


Diagonal Movement Code for Python Chess Engine

Go through the PEP-8 style guide. You have inconsistent naming
  convention. A mixed case of camelCase and snake_case throws off
  the developer. Follow snake_case for variables and camelCase for
  class etc.

The first thing that comes to mind is a loop:

for pos in range(1, 8):
    try:
        temp = chessBoard[i + pos][j + pos]
        solutionMoves.append([i + pos, j + pos])
    except:
        break

which about covers the whole of your try-except blocks.

However, with chess; I'd suggest using coordinate system to move around the board.

Design a class Point which takes \$ (x, y) \$ position and define the __add__, __sub__, __neg__ etc. as follows (rough, modify as per your needs):

class Point(tuple):
    def __add__(self, other):
        return Point(v + w for v, w in zip(self, other))

    def __radd__(self, other):
        return Point(w + v for v, w in zip(self, other))

    def __sub__(self, other):
        return Point(v - w for v, w in zip(self, other))

    def __neg__(self):
        return -1 * self

    def __mul__(self, s):
        return Vector(v * s for v in self)

    def __rmul__(self, s):
        return Vector(v * s for v in self)

Now, define your movement direction as a point vector:

DIR_TOP_RIGHT = Point(1, 1)

when you want to move inside the board, just add a multiple of direction to the current point:

current = Point(i, j)
new = current + (distance * DIR_TOP_RIGHT)

Next, define a method (inside a class ChessBoard which checks whether a point lies inside the board or not. This should be quite easy. This ChessBoard class should also be the one responsible for converting your Point object from \$ (1, 1) \$ format to B1 etc.


Using delegates to avoid duplicate creation of resources

The problem here is that you want to be able to use a large number of unrelated objects (i.e. not implementing a common interface).  One solution would be to define a usable interface and define wrapper implementations for each of these objects.  Something like:

public interface IDataSource
{
    byte[] DownloadUrl(String url);
}

Your download class would use implementations of this interface, and you could provide implementations for HttpClient, WebClient, etc. like:

public class HttpClientDataSource : IDataSource
{
    public HttpClientDataSource(HttpClient client){}
}

All that said, this doesn't seem to really matter in your case.  I'm not convinced that allocating an HttpClient for internal use is exactly wasteful of resources.  Also, by forcing this decision onto the users of your library you've made it more complicated to use.  You'll have to explain to your users how to choose between different HTTP implementations.  Part of designing a good library is trading off flexibility and simplicity, and I would say the simpler interface is better.


Extracting parts of filenames from an array

As said before, use map instead of a foreach loop and change the regex delimiter.
If you put the array in double quote when print, a space is inserted between each element of the array in fact it is the content of the special variable $", see http://perldoc.perl.org/perlvar.html

$LIST_SEPARATOR
$"
When an array or an array slice is interpolated into a double-quoted string or a similar context such as /.../ , its elements are separated by this value. Default is a space. For example, this:
   print "The array is: @array\n";

is equivalent to this:
   print "The array is: " . join($", @array) . "\n";

Mnemonic: works in double-quoted context.

Your code becomes:
# Use ALLWAYS these two lines in every script.
use strict;
use warnings;

my @configs = glob("m4/config.*.m4");
my @outputs = map{ m~m4/(config\..*)\.m4$~ } @configs;
print "@configs\n";
print "@outputs\n";

Output:
m4/config.a2.m4 m4/config.mk.m4 m4/config.php.m4
config.a2 config.mk config.php


Get the character and its count which has highest occurrence

As per this answer, it would be wiser to use a tuple in this case. I use lowercase "t"uple as I highly recommend the built-in language support for tuples (char, int) over the explicit Tuple<T1, T2> declaration, etc. Few more points:

What should happen in a tie? Which gets returned? If any is acceptable, it's fine as-is. To be more of a determinate function, secondarily order by the character itself.
Don't need to convert it to a character array as a string already is a character array.
Re-order the OrderByDescending and the Select so that Count only has to be called once.
It can be made static since it doesn't access class instance data.
It can be made an extension method if in a static class.
It can be made into an expression-bodied method.
Maybe consider a better name; one that confers what it does rather than how it does it.

All that said, here's my take:
    public static (char, int) MaxCharacterFrequency(this string s) =>
        s.GroupBy(x => x)
         .Select(x => (x.Key, x.Count()))
         .OrderByDescending(x => x.Item2)
         .ThenBy(x => x.Item1)
         .FirstOrDefault();


Displaying a scheduled job under a scheduled time

Your script creates a temporary file unnecessarily, uses os.system which is not recommended, and other messy things. Consider this alternative:

#!/usr/bin/env python

import subprocess
import re

re_job_number = re.compile(r'\d+')

for atq_line in subprocess.Popen(['atq'], stdout=subprocess.PIPE).stdout:
    job_number = re_job_number.search(atq_line).group()
    print atq_line.strip()
    for at_line in subprocess.Popen(['at', '-c', job_number], stdout=subprocess.PIPE).stdout:
        if at_line.startswith('task '):
            print at_line.strip()
    print '-' * 40

Advantages:

No need for a temporary file to save the atq output, you can process it directly
For running shell commands, subprocess is the recommended way, os.system is discouraged
No need for a grep process, you can handle the output filtering of at -c in Python itself

Also, writing the first line this way makes the script more portable:

#!/usr/bin/env python

If you write as #!/usr/bin/python then you are effectively hard-coding the Python path, and it might not be the same in all systems.

Finally, I recommend writing print(something) instead of print something, to keep your script ready for migrating to Python 3 someday.


Function to scan input to string buffer in C

You must check the return value of scanf. If you don't, you run into an endless loop when reaching the end of the file. And, even worse, you invoke undefined behavior.

You could split the loop into two: first, skip all whitespace, then read the remaining text.

int dscan(char *buf, int bufsize) {
    int ch;

    while ((ch = getc()) != EOF && ch != '\n' && isspace(ch)) {
        continue;
    }

    int idx = 0;
    while (ch != EOF && ch != '\n' && idx < bufsize) {
        buf[idx++] = ch;
        ch = getc();
    }

    if (ch == '\n' && idx < bufsize) {
        buf[idx++] = '\n';
    }
    if (idx < bufsize) {
        buf[idx++] = '\0';
    }

    return idx;
}

I changed several things:

EOF is handled correctly. On EOF, the string is returned, properly null-terminated. (This was not the case in your code.)
Leading whitespace does not count towards the buffer, it is simply ignored, like you said in your description. Your code counted it.
Each call to an I/O function is checked for an error result.
It's easy to strip the newline character from the string by removing the corresponding if sentence. Depending on whether the calling code needs this or not.
If dscan(buf, size) < size, the buffer is a string, i.e. it is properly null-terminated.
Calling isspace does not invoke undefined behavior. In your code, if I enter a negative char, the behavior is undefined. See the <ctype.h> documentation.


Store first value of http request with rxjs but keep doing httprequest

It is really hard to solve the problem since the question is not providing all the necessary details.

Assuming you have a factory for your Http observable (call it createHttpObservable()) you may do something like this:

const observable = createHttpObservable()

  // Share the stream of events across all the subscribers.
  .publishReplay(1)
  .refCount()

  // Use `.scan()` against event stream (similarly to how we `.reduce()` against an array).
  .scan(
    (history, currentValue, valueIndex) => {
      history.push({ num: valueIndex, httpNum: currentValue });
      return history;
    },
    []
  )

  // Take the last event from the `history`
  .map(history => history[history.length - 1].httpNum)

  // Arbitrarily use `.do` for side effects.
  .do(console.log);

// Subscribe wherever you need.
observable.subscribe();
observable.subscribe();
observable.subscribe();

Here's a related, but not quite the same exact plunkr.

You can have more custom logic in the .scan() block, but frankly, I have no idea what are you trying to achieve and why is the first Http request's results are of any special interest.


Parallel brute-force solution for Project Euler 4 (Largest palindrome product)

Brute Force.
Your use of go-routines is pretty simple, but effective. The part I don't think is best, is the use of the channel. The channel itself is good, but the control structures you have to read content from the channel, could be better. In fact, you have a bug in them (although you are lucky that the data means you don't encounter the bug).
Let me describe the bug, first. You assume that every go-routine is going to add a value to the channel (there will be at least one palindrome). You also assume there is at most one palindrome. If there end up being fewer palindromes than routines, you may end up "hanging" on the channel when all routines are done, but no values are coming. If there are more palindromes than routines, you may have the "max" palindrome happen later in the channel than you read.
I would recommend using a wait-group for the go-routine, and then closing the channel in the completion. In essence, I would restructure the code:

lowerLimit := 100

upperLimit := 1000

c := make(chan int)

for i := upperLimit - 1; i >= lowerLimit; i-- {

    go getHighestPal(i, c)
}

for i := 0; i < upperLimit-lowerLimit; i++ {

    candidate := <-c

    if candidate > highestPal {

        highestPal = candidate
    }
}

to be:
lowerLimit := 100
upperLimit := 1000

count := upperLimit - 1 - lowerLimit

palindromes := make(chan int, 1024)

var wg sync.WaitGroup
wg.Add(count)
for i := 0; i < count; i++ {
    go func(val int) {
        getHighestPal(val, palindromes)
        wg.Done()
    }(i + lowerLimit)
}

go func() {
    // wait for all routines to complete
    wg.Wait()
    // close the channel to allow the terminal range
    close(palindromes)
}()

highestPal := 0
for candidate := range palindromes {
    if candidate > highestPal {
        highestPal = candidate
    }
}

Note how the internals of the getHighestPal no longer affect the reading of the channel? Also note how Ihave to create the closure parameter i + lowerLimit inside the go-routine call in order to have the right context for each routine.
A second bug you have is the elimination of square numbers. Again, it does not affect the results in this instance, but the code in getHighestPal should be for j := i and not j := i - 1. All squares of values containing only 1 digits are famously palindromes: 1111 * 1111 is 1234321 for example.
Finally, your method getHighestPal implies it gets the highest palindrome, but it gets all palindromes..... not just the highest.
Non-Brute-Force
So, a couple of other things to consider.
The fmt.Sprintf is slower than strconv.Itoa. Consider that change (it's 2 to 3 times slower in my tests).
Also, you can be creative about what you do in your algorithm to improve performance. I took your code and ran it my way.....
func isPalindrome(v int) bool {
    str := strconv.Itoa(v)
    right := len(str) - 1
    left := 0
    for left < right {
        if str[left] != str[right] {
            return false
        }
        left++
        right--
    }
    return true
}

func maxPalindrome(maxfact int) int {

    max := -1
    minlow := 0

    // establish a low and high value pair as the values that create the product.
    for low := maxfact; low >= minlow; low-- {
        for high := maxfact; high >= low; high-- {
            prod := low * high
            if prod <= max {
                // no need to keep looking for things that can't possibly be larger than previous max.
                break
            }
            if isPalindrome(prod) {
                max = prod
                // limit how far we search back to things that would exceed the smallest factor
                minlow = max / maxfact
            }
        }
    }

    return max
}

When run in the same way as your code:
func main() {
    start := time.Now()

    maxp := maxPalindrome(999)

    elapsed := time.Since(start)
    fmt.Println(maxp)
    fmt.Println("Programme execution time %s", elapsed)

}

I was substantially faster.
On my machine, your sequential code returned:

906609
Programme execution time %s 99.33103ms

your concurrent code returned:

906609
Programme execution time %s 26.010698ms

And the above code returned:

906609
Programme execution time %s 206.964µs

about 100 times faster than your concurrent code.


A C++ merge sort in the style of a Standard Library algorithm could be written as

template<class BiDirIt, class Compare = std::less<typename std::iterator_traits<BiDirIt>::value_type>>
void merge_sort(BiDirIt first, BiDirIt last, Compare cmp = Compare())
{
        auto const N = std::distance(first, last);
        if (N < 2) return;
        auto middle = std::next(first, N / 2);
        merge_sort(first, middle, cmp);
        merge_sort(middle, last, cmp);
        std::inplace_merge(first, middle, last, cmp);
}

Let's look at how this improves upon your design:

generic interface: it takes two iterators and a comparison function of arbitrary types, instead of two indices into a pointer to an array of int and the implicit but fixed < comparison.
in-place: behind the covers it calls std::inplace_merge that can allocate extra memory but it does it so that users don't have to supply this, instead of your tmplist parameter.
half-open intervals: it will split the input range [first, last) into [first, middle) and [middle, last) which automically takes care of easy to make "off-by-one" errors in code like middle + 1 (in your code it is correct, but you still have to think about it, half-open intervals are easier to get right).
named algorithms: it uses std::inplace_merge as a ready-to-use component instead of a somewhat long and certainly tricky final step in your algorithm. Not only makes this your merge_sort more compact, the inplace_merge itself is a resuable component in its own right!
heavily optimized: Standard Library experts are very likely to know about the state of the art in writing performance-optimized algorithms. A factor of 10 of performance compared to your code seems a lot, but if you forget some hidden copies, use a hand-written loop that has O(N^2) complexity instead of O(N log N) you can quickly get there.


An interesting use of the reduce function to convert tab-delimited data into JSON

So for your first question, that is not a weird way to check the existence, and it is used quite frequently to check whether certain variables/properties are set (such as checking browser compatibility, optional arguments with defaults in functions). It typically just works as a "use this value if it exists, otherwise use this value."

You could check/set it any number of ways, like the ternary operator.

customer[line[0]] = customer[line[0]] ? customer[line[0]] : {};

In the same vein, you could just use an if statement to check if it is defined.

Order definitely does matter in an OR statement. In javascript (and probably most other languages) the first condition/operation is always performed, and the 2nd condition or operation is ignored unless the first condition/operation equated to a falsy value. In your example, customer[line[0]] is only assigned as an empty object if customer[line[0]] is undefined. If you reverse the order, customer[line[0]] will always be assigned to the empty object, and the 2nd half of the statement is ignored.

Javascript is the only language I've used where OR statements are normally used outside of actual control statements, so it was definitely puzzling to look at these statements at first.

Another, similar operator is the comma , operator, which is essentially the lowest in the order of operations. It just returns the last of the comma-separated statements, but all of the statements are performed.


I won't comment on the algorithm you're using to find out if the number is prime or not. Though the way you're doing it is quite inefficient. Some people in the comments have already pointed out some possible improvements and I'd suggest looking into the sieve of Eratosthenes to get better performance. You can find a Swift implementation of it here.

First off, there is a lot of unnecessary whitespace, you should get rid of that and only use a blank line too separate logical parts of your code.

Secondly, let's look at the following part:

var number:Int = 1123
var isPrime:Bool = true

There are three issues with it. number is mutable, but you never actually change it, it is customary to have exactly one space after a colon in Swift (instead of none) and while we're at it, in Swift you don't typically explicitly state the the of a variable unless it significantly improves readability (which is almost never) or type inference gets the wrong type. (which also doesn't happen often.) So you can rewrite those two lines as:

let number = 1123
var isPrime = true

As for the meat of this answer, it would be preferable to extract the actual prime checking into a function:

func isPrime(number: UInt32) -> Bool {
    switch number {
        case 0, 1: // you can put multiple cases on one line
            return false
        case 2, 3:
            return true
        default:
            for i in 2...Int(sqrt(Double(number))) {
                if number % i == 0 {
                    return false
                }
            }
            return true
        }
    }
}

This allows you to write:

let number = 1123
if isPrime(number) {
    print("The number \(number) is prime!")
} else {
    print("The number \(number) is composite!")
}

or even:

print("The number \(number) is \(isPrime(number) ? "prime" : "composite")!")

This allows you to get rid of the mutable isPrime, which is something you should strive for in Swift. And allows you to nicely ecapsule the actrual logice and separate it from the rest.


Implementation of a simple hash function

The very idea of "if that hash is already taken, use another one" leads to bugs that are really hard to find later.

It's because your hash function (oh, it is called a function, hopefully in the mathematical sense) no longer has the signature hash(studentNumber) but instead becomes hash(studentNumber, allPreviousStudentNumbers). This means you get different hashes based on how the students are sorted.

A hash function may by definition produce collisions, and that is fine. Choosing an appropriate hash function that minimizes these collisions is often crucial. In cryptography the commonly used hashes have 256 bits, which makes a collision very unlikely. I hope your teacher plans to discuss these topics in class, as these are important.

Regarding your implementation of the basic hash function. It looks a little more complicated than necessary. An experienced Java programmer will know that there is a predefined String constructor that forms a String from part of a character array. It is new String(charray, start, count). Using this, the code becomes simple:

private static int hash(char[] studentNo) {
    int first = Integer.parseInt(new String(studentNo, 0, 3));
    int second = Integer.parseInt(new String(studentNo, 3, 3));
    int third = Integer.parseInt(new String(studentNo, 6, 2));
    return first + second + third;
}

This code is almost as simple as you would describe the algorithm to a human, and that's how it should be.

One tricky thing that bites me every time I use the String class: in general there are two ways of referring to a substring, a subarray or a subsequence: either (start, end) or (start, count). Unfortunately Java uses both of them. In the String constructor I used above, it's (start, count), while in the substring method it's (start, end). Even after 20 years of programming in Java, I still have to look at the documentation to know when each of these applies.


SRP - single responsibility principle

The Send_Email() method is responsible for to many things.
The method is

creating and configuring a SmtpClient
creating and configuring a MailMessage
composing the body of the MailMessage

This should be extracted to separate methods.

So let us refactor this method.

First we write a method to create a SmtpClient.

private SmtpClient GetSmtpClient(string serverAddress, int serverPort, bool enableSsl)
{
    SmtpClient smtpClient = new SmtpClient(serverAddress);
    smtpClient.Port = serverPort;
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtpClient.EnableSsl = enableSsl;

    return smtpClient;
}

This had been pretty easy, hadn't it ? So, next we add a method composing the Subject by using the String.Format() method.

private String ComposeSubject(LogResult logResult)
{
    return String.Format("Logs from {0} searched {1} for {2}", logResult.ComputerName, logResult.SearchDate, logResult.SearchTerm);
}

But wait, what is LogResult ? That is a class we need to create, so let us do it. As we see it should have at least the properties ComputerName, SearchDate and SearchTerm. We add also a ReadOnlyCollection<String> FileNames property.

public class LogResult
{
    public String ComputerName { get; private set; }
    public DateTime SearchDate { get; private set; }
    public String SearchTerm { get; private set; }
    public ReadOnlyCollection<String> FileNames { get; private set; }

    public LogResult(String computerName, DateTime searchDate, String searchTerm, List<String> logList)
    {
        ComputerName = computerName;
        SearchDate = searchDate;
        SearchTerm = searchTerm;
        FileNames = ToFileNames(logList);
    }

    public LogResult(DateTime searchDate, String searchTerm, List<String> logList)
        : this(Environment.GetEnvironmentVariable("COMPUTERNAME"), searchDate, searchTerm, logList)
    { }

    private ReadOnlyCollection<String> ToFileNames(List<String> logList)
    {
        IList<String> fileNames = new List<String>(logList.Count);
        foreach (String completeFileName in logList)
        {
            fileNames.Add(Path.GetFileName(completeFileName));
        }
        return new ReadOnlyCollection<String>(fileNames);
    }
}

So now we will use this class to also compose the email body. Here we are using the feature of the StringBuilder that it is returning a StringBuilder for calling the AppendXX() methods. So we can call StringBuilder.Append().Append()...we are using also the StringBuilder.AppendFormat() method.

private String ComposeMailBody(LogResult logResult)
{
    StringBuilder bodyBuilder = new StringBuilder(1024);

    bodyBuilder.Append("
")
        .AppendFormat("Here are the file(s) on  {0}", logResult.ComputerName)
        .AppendFormat(" under {0}", logResult.SearchDate)
        .AppendFormat(" that contain {0}

",logResult.SearchTerm)
        .AppendLine("

Filenames
");

    int count = 0;
    foreach (String fileName in logResult.FileNames)
    {
        if (count % 2 == 0)
        {
            bodyBuilder.AppendFormat("
{0}
",fileName);
        }
        else
        {
            bodyBuilder.AppendFormat("
{0}
",fileName);
        }
        count++;
    }
    bodyBuilder.Append("

");

    return bodyBuilder.ToString();
}

The last method we introduce is for creating a MailMessage.

private MailMessage CreateMessage(LogResult logResult, String receiver)
{
    MailMessage message = new MailMessage("from-address", receiver);
    message.Subject = ComposeSubkject(logResult);
    message.Body = ComposeMailBody(logResult);

    return message;
}

Now the former Send_Email() method would look like

private static void SendEmail(string server, int port, bool ssl)
{
    LogResult logResult = new LogResult(sDate ,sSearchTerm, logList);
    SmtpClient smtpClient = GetSmtpClient(server, port, ssl);
    MailMessage message = CreateMailMessage(sEmailAddress);

    smtpClient.Send(message);
}

EmailClass

Using auto properties will reduce your code a lot. Auto properties are properties with a hidden backing field generated by the compiler.

public class EmailClass
{
    public string Domain { get; set; }

    public string EmailAddress { get; set; }

    public string FromAddress { get; set; }

    public string Subject { get; set; }

    public List<string> Message { get; set; }

}

Naming

Based on the naming guidlines method names should be named using PascalCase casing. So Send_Email should be renamed to SendEmail.
Based on the same guidlines method parameters should be named using camelCase casing. the signature of the former Send_Email() method should look like

private static void SendEmail(string server, int port, bool ssl)


Putting called delegate into AsyncState parameter - Pros/cons?

To answer your question:

you can access the delegate instance by reading ((AsyncResult)asyncResult).AsyncDelegate property (see Executing a Callback Method When an Asynchronous Call Completes section of Calling Synchronous Methods Asynchronously). But it will be easier to cache the instance of the delegate in a readonly field and use it in both methods.
yes, you can use AsyncState however you want, and sometimes people use it for passing the delegate being invoked

Note that you're using a separate thread (on a threadpool) each time you write something to log, so there will be contention between multiple threads if you write to log quickly enough. I would recommend using existing logging frameworks like NLog or log4net to avoid inventing a wheel.


Let's go top down:

charmatch is a bad name for the function. parenMatch would make much more sense.
Judging by the one range-based for loop, you're using C++11 - so might as well use it to the full extend:

You can use range-based for loops directly on a std::string. There is no need to copy it into a vector. So the input vector can be removed.
You can initialize a std::set with an initializer list:

std::set<char> openParen = { '(', '[', '{' };

Not sure why the range based loop variable is called i just to be copied into a loop-local variable called inputChar. You might as well name the loop variable that way.

for (auto inputChar : inputArg) {
    ....

closeParen is never used and can be removed.
exprStack is not really the best name - parenStack would be more appropriate.
You should use spaces more consistently. Your indent is off here and there and you often omit a space before the opening brace which doesn't help readability. Also a lot of people prefer 4 spaces indent but YMMV.
Use a consistent bracing style. Sometimes you put the opening brace on it's own line and sometimes it's on the previous one and sometimes the entire block is on one line.
I'd return a bool from process instead of writing directly to std::out - let the caller deal with the output concern (Single Responsibility Principle).
input in main is never used and should be removed.
You don't have to explicitly return 0 from main.

Update

Regarding your question of making charmatch more efficient: charmatch is already pretty efficient - at most 8 compares and 3 ANDs. You could turn it into a switch:

bool parenMatch(char left, char right)
{
    switch (left)
    {
        case '(': return right == ')';
        case '[': return right == ']';
        case '{': return right == '}';
    }
    return false;
}

However this is a micro-optimization which will probably have close to no effect on the execution speed, in fact I wouldn't be surprised if the generated code is almost the same.


Here's what I would add if I were doing this as a peer review.

Nested For Loops:

Nested for loops are hard to read. As an alternative, split the nested loop into a separate, aptly named function, if possible. Perhaps a function that returns the next item to be swapped with? You would take your nested for loop and move it to a function that would return what is currently temp if it is there. Then, if there was a return value, you would swap the values. You could even destructure them instead of storing the previous value in a temporary variable: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Also, by moving the for loop into a different function, you only have to do this numArray[i] = MIN; if necessary.

Naming:

Your variables are lowercase, lower_case, camelCase, and UPPERCASE. I suggest standardizing on one. For one thing, MIN looks like a constant to me (from a PHP background), but it is being changed every time in the for loop. Also, what about improving the names: totalNum is unclear to me. Without looking beyond the naming is that an accumulator that stores the sum of all the items? temp could be previousItem.

Other Items:

It's typically recommended to declare variables at the top of the function. j is declared numerous times.
You initialize MIN at 0, but then reset it inside of the for loop. Why not just declare MIN and not set a value.

A completely different approach:

Finally, I wondered about using Javascript's Array.forEach(). The following is a completely different perspective, but I thought I would throw it out there for you to consider:

selectionSort();

function selectionSort(){
    var originalArray = [4, 34, 2, 5, 12],
        sortedArray = [],
        lowerSortedIndex;

  originalArray.forEach(function(item) {
    // Arrow function with implied return:
    lowerSortedIndex = sortedArray.findIndex((nextItem) => nextItem >= item);

    if (lowerSortedIndex >= 0) {
      sortedArray.splice(lowerSortedIndex, 0, item);
    } else {
      sortedArray[sortedArray.length] = item;
    }
  });

    console.log(sortedArray);
}

The arrow function could be re-written as:
function(nextItem) { return nextItem >= item; })

I wrote it here if you want to play with it: http://codepen.io/bassplayer7/pen/oBxmbW


Marking a rectangular region in a NumPy array as an image mask

It turns out that Numpy has various nifty ways of indexing. I found that my question can be solved by

clusterMask[clusterH - 2*S : clusterH + 2*S, clusterW - 2*S : clusterW + 2*S] = 1

As given in one of the comments, this link contains all information regarding numpy indexing:
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html


The docstrings are vague. Documentation needs to be precise and complete. It should answer questions like "what arguments should I pass?" and "what does it return?" For example, "go through the AST and count lines" should become something like, "Return the number of nodes in the AST rooted at node, and update the set line_nos with the line numbers of these nodes, plus the line number 0 if any node has no line number."
It's not clear that the "plus the line number 0 if any node has no line number" behaviour is needed. Instead of doing this and then having to subtract one later to compensate, why not avoid adding the line number 0 in the first place?
When traversing an AST, it's often convenient to use the ast.NodeVisitor class, like this:

class DensityVisitor(ast.NodeVisitor):
    """AST visitor that accumulates the count of nodes and the set of line
    numbers in the AST.
    """
    def __init__(self):
        self.node_count = 0
        self.line_numbers = set()

    def visit(self, node):
        self.node_count += 1
        try:
            self.line_numbers.add(node.lineno)
        except AttributeError:
            pass
        self.generic_visit(node)

    @property
    def density(self):
        """The density of code (nodes per line) in the visited AST."""
        return self.node_count / len(self.line_numbers)

and then in main you'd write:

visitor = DensityVisitor()
visitor.visit(ast.parse(source))
print('density (nodes/line) =', round(visitor.density, 4)))

Update: Why would you prefer ast.NodeVisitor over explicitly walking the tree using ast.iter_child_nodes plus recursion? Well, because of separation of concerns — the logic for walking the tree is delegated to the ast.NodeVisitor base class, and you only have to specify what happens at each node. (Another possibility would be to use ast.walk.)


Assemble network packet on stack for iovec

The iterator is not behaving correctly
There are various reasons std::copy() doesn't work on stack_stack, and it all has to do with the iterator. First, you are missing difference_type. Since your iterators do not support taking the difference, set it to void:
using difference_type = void;

Second, your comparison operators are wrong. They should take a const reference to other, and you can access member variables of other directly, so:
bool operator==(const iterator &other) const {
   return ptr == other.ptr;
}

Also, while this is a trivial comparison operator, it is good to define operator!= in terms of operator==, to avoid potential mistakes:
bool operator!=(const iterator &other) const {
    return !(*this == other); // Just invert the result of operator==
}

Last, the result of operator* should be a reference to the actual data, not a pointer, so:
reference operator*() {
    return *static_cast<pointer>(ptr);
}

Now it sort of works, and std::copy() is happy. In your own code, you need to change some use of -> to . to make it print the contents of a stack, like so:
for (auto item: stack) {
    std::cout << item.data << "\n";
}

Avoiding void* hacks
Well, you have created a problem for yourself. Each element of the stack points to the next element, but it has a different type. The cleanest solution I see without changing the type system used for stack_stack is to do this:
struct iterator {
    ...
    using pointer = const stack_stack*;
    ...
    iterator& operator++() {
        ptr = reinterpret_cast<pointer>(ptr->next);
        return *this;
    }
    ...
    reference operator*() {
        return ptr->value;
    }

    pointer ptr;
};

So we removed all of the lies, except the one about the type when following ptr->next.
The cleanest approach
If you want to do it even cleaner, then you should not have a template parameter length. Maybe also don't call it a stack, it more accurately resembles one element of a singly-linked list. To keep track of the length of this list, I would create a separate type that resembles the list as a whole, and which stores the length and a pointer to the head, both of which we will update when we add elements:
template<class T>
struct stack_list {
    struct item {
        const T value;
        const item *const next;

        // Constructor which will update the head of stack_list
        item(const T &value, const item *&head): value(value), next(head) {
            head = this;
        }

        // Delete copy constructor, move and assignment operators
        item(const item &other) = delete;
        item &operator=(const item &other) = delete;
        item &operator=(const item &&other) = delete;
    };

    struct iterator {
        ... // left as an excercise to the reader
    };

    size_t size{};
    const item *head{};

    [[nodiscard]] item push_front(T value) {
        size++;
        return {value, head}
    }
}

Then you can use it like so:
auto my_data = ...;

stack_list<ioitem> sl;
auto my_buffer = sl.push_front({my_data.begin(), my_data.size()});

std::cout << "List size: " << sl.size << "\n"
          << "First element: " << sl.head->value << "\n";

Using your class for building iovecs
As you noticed you still need to convert your stack (or list) of ioitems to an array of struct iovec. So it might be better to build this array directly. If you want to do it on the stack, then the safest option is to just go with a std::array<iovec, N>, where N is large enough to handle most or all cases. If the required size can vary a lot, then you can perhaps make a class that holds a union of a std::array and a std::vector, and switches to the vector if the array is full. You might be able to use an existing library implementing small vector optimization, but since you basically always push_front(), your own implementation that starts at the back of the array might be the most efficient. It might look like:
template<size_t N = 8>
class iovec_builder {
    std::array<struct iovec, N> iov;
    size_t iovlen{};

public:
    void push_front(struct iovec item) {
        if (iovlen == N) {
            // handle array being full
        } else {
            // add starting from the back
            iovlen++;
            iov[N - iovlen] = item;
        }
    }

    struct iovec *get_iov() {
        return &iov[N - iovlen];
    }

    size_t get_iovlen() const {
        return iovlen;
    }
};

And use it like:
iovec_builder iovb;
std::string my_data("Hello World");
iovb.push_front({my_data.data(), my_data.len()});
iovb.push_front({..., ...});

struct msghdr msg{};
msg.iov = iovb.get_iov();
msg.iovlen = iovb.get_iovlen();
...
sendmsg(fd, &msg, ...);

It might waste a bit of stack space, but you'll waste more by having a linked list and having to copy it into an array.


If your documents were actually lists of words, like your description said at one point, this would be way more efficient. But we can of course just make them, by using:

doc1 = "My sister likes to have sugar, but not my father.".split()
doc2 = "Doctors suggest that driving may cause increased stress.".split()

This has the problem that the punctuation gets in the way, so we need to remove it first, with one of the approaches from here (I chose the fastest one):

import string
doc1 = "My sister likes to have sugar, but not my father.".translate(None, string.punctuation).split()
doc2 = "Doctors suggest that driving may cause increased stress.".translate(None, string.punctuation).split()

Ok, now that they are lists, we make them into sets, so word in doc becomes \$\mathcal{O}(1)\$ instead of \$\mathcal{O}(n)\$:

documents = map(set, [doc1, doc2])

# DICTIONARY
dictionary = ["doctors", "sister", "like"]

for word in dictionary:
    for doc in documents:
        if word in doc:
            print "\n\n\nWord:",
            print word,
            print "in document:",
            print doc

This should speed this up considerable. The most speed-up will be gained if the document strings are quite long.

The output of this is now not really understandable anymore:

Word: sister in document: set(['sister', 'my', 'father', 'but', 'sugar', 'to', 'likes', 'have', 'not', 'My'])

We can get around that by carrying around both the set and the string. I also made the splitting into words a function and used a if __name__ == "__main__" guard to ensure this code is only run when calling it via e.g. python script.py, but not when doing from script import get_words.

import string

def get_words(text):
    return set(text.translate(None, string.punctuation).split())

if __name__ == "__main__":
    documents = ["My sister likes to have sugar, but not my father.",
                 "Doctors suggest that driving may cause increased stress."]

    words_in_documents = map(get_words, documents)

    for word in ["doctors", "sister", "like"]:
        for doc, words in zip(documents, words_in_documents):
            if word in words:
                print "\n\n\nWord: {} in document: {}".format(word, doc)


Code style
Your code style is certainly acceptable - everyone is entitled to their own coding habits.
To further improve readability, and readability is key, I would change the following:

put all labels in the same separate column. You didn't do this for is_even, fmt, target, list, and len.
don't just have 1 space character between the instruction/directive and its operand(s). Start all operands in their own column.
beware of redundant comments like 'mov r12, list  ; load list into register'
don't add redundant tags like dword in mov r14d, dword [r12]. The register name r14d already states this is a dword.
avoid using ambiguous terminology. I found it odd to read about sectors and widths. In case of binary searching, many people will prefer to talk about array partitions and number of elements.

The code has multiple issues
You seem to be confident that a match will always be found. No provision is made for a failure!
The comment on mov rdx, r12  ; rdx is pointer to the target is wrong. What you've got is a pointer to the matching array element.
The array list holds dword-sized elements. In mov r13, len >> 3, you only need to shift twice to get the number of elements.
In the top part of the program you first add an imaginary element to the array, then you make r12 point to behind it, and later your code also happily reads from these non-existing elements. Analyzing beyond this point becomes futile.
I think having recognized an attempt to write a uniform binary search. Although I didn't use that particular approach, you might find it interesting to read a post of mine that shows 2 ways to binary search an array. I know it was written for 16-bit, but that should not stop you from stealing from it...


Using nonlocal rather than global is certainly good, but better yet would be returning values.

def paths(m, n):
    def find_number_of_paths(x, y):
        if x == 0 and y == 0:
            return 1

        ret = 0

        if x > 0:
            ret += find_number_of_paths(x-1, y)

        if y > 0:
            ret += find_number_of_paths(x, y-1)

        return ret

    return find_number_of_paths(m-1, n-1)

That lets us elide the outer function entirely:

def paths(x, y):
    if x == 1 and y == 1:
        return 1

    ret = 0

    if x > 1:
        ret += paths(x-1, y)

    if y > 1:
        ret += paths(x, y-1)

    return ret

It's a bit strange to critique this since "no closed-form solution" basically means no good solution. There are ways of speeding this up, though, that avoid that. A trivial one is memoization:

_paths_cache = {(1, 1): 1}
def paths(x, y):
    if (x, y) in _paths_cache:
        return _paths_cache[x, y]

    ret = 0

    if x > 1:
        ret += paths(x-1, y)

    if y > 1:
        ret += paths(x, y-1)

    _paths_cache[x, y] = ret
    return ret


Why are these functions slower than BigInteger's included methods?

Your question comes in multiple parts: General code review, adding algorithms, and then performance relative to standard BigInteger

General Review

Let's focus on this method, it shows essentially all the general issues I see:

 public static BigInteger add(BigInteger x, BigInteger y)
 {
  boolean A, B, carry=false;
  BigInteger sum=BigInteger.ZERO;
  int firstBit=x.or(y).getLowestSetBit(),
      topBit=x.or(y).bitLength();
  for(int i=firstBit;i<=topBit;i++)
  {
   A=x.testBit(i);
   B=y.testBit(i);
   if((A^B)^carry)
    sum=sum.setBit(i);
   carry=(A&&B)||((A^B)&&carry);
  }
  return sum;
 }

Breathing room around operators is important for readability. The code like:

for(int i=firstBit;i<=topBit;i++)

should be:

for (int i = firstBit; i <= topBit; i++)

Java code styles use brace-at-line-end style. C, C++, C# and other C* languages use next-line style. This sort of brace style is often debated, but, all common Java code style standards require end-of-line. You will regularly be criticised when sharing Java code using this style. Your code should look like:

public static BigInteger add(BigInteger x, BigInteger y) {
    boolean ...

mixed initialization is confusing, and variables should be declared in their tightest scope:

boolean A, B, carry=false;

That declaration is redundant, and confusing. Java defaults all boolean values to false when declared (unless specifically initialized to true). So, the carry=false is redundant (since A and B are also false).

Further, A and B are horrible names for variables. For a start, they are upper case, then they have poor meanings, and finally, A is a real word that tends to create a specific meaning when read out of context.

While talking bad names, x and y are not good names either. Those names imply that the two input variables are coordinates, and not two values to be added. I would recommend names like augend and addend because those are the official names for the two terms used in addition.

Finally, A and B are only used in the context of the for-loop, and not outside that context, so they should be declared where they are used:

boolean augBit = augend.testBit(i);
boolean addBit = addend.testBit(i);

Complicated functions should not be used when creating compound variable declarations:

int firstBit=x.or(y).getLowestSetBit(),
    topBit=x.or(y).bitLength();

That should be split in three, actually. The x.or(y) is repeated twice, so should be extracted....

 BigInteger orVals = augend.or(addend);
 int firstBit = orVals.getLowestSetBit();
 int topBit = orVals.bitLength();

1-liner if-statements and other 1-liner blocks. You have the 1-liner statement:

   if((A^B)^carry)
     sum=sum.setBit(i);

1-liners are know to be a leading cause of bugs introduced during the maintenance cycle of code. The easy solution is to brace 1-liners always. The code should be:

   if( (A ^ B) ^ carry) {
       sum=sum.setBit(i);
   }

Let's take a pause at this point, and see where we are at:

public static BigInteger add(BigInteger augend, BigInteger addend) {

    boolean carry = false;
    BigInteger sum = BigInteger.ZERO;

    BigInteger orVals = augend.or(addend);
    int firstBit = orVals.getLowestSetBit();
    int topBit = orVals.bitLength();

    for (int i = firstBit; i <= topBit; i++) {
        int augBit = augend.testBit(i);
        int addBit = addend.testBit(i);
        if ((augBit ^ addBit) ^ carry) {
            sum = sum.setBit(i);
        }
        carry = (augBit && addBit) || ((augBit ^ andBit) && carry);
    }
    return sum;
}

Alright, at this point, I can see the algorithm more clearly in the code, time to move on.....

Bug

Having isolated the code like this, it is apparent that there is a big bug too. If you have a carry coming from the highest bit sum, you ignore the carry... So, for example, if you have the two values 0x0f and 0x01, I would expect the sum 0x10, but you will not carry the last 1 bit in to the next value...

Performance

With the refactored code, it is clear that there are two major performance hits. The first is that the sum is a BigInteger value that gets recreated multiple times each loop (once for each set bit). Each time you call:

sum = sum.setBit(i);

you create a new BigInteger value, with the corresponding overheads, and memory allocations, etc. This could be a lot of allocations. The native Java routine breaks out of this situation by using primitive values and arrays, and keeps a bit-vector that is mutable for the duration of the addition cycle. By doing it that way, there is no memory management penalty....

A second issue related to performance, that is not obvious, is that the real BigInteger class does things both ways ..... it does a bit-vector for large integer values, but for 'small' values it uses a simple java long primitive. In other words, it simply does long sum = augend.longVal + addend.longVal if the two inputs are small enough for long value representations, and also if the sum will fit in a primitive long. In other words, it is much faster for smaller values than for values that exceed Long.MAX_VALUE/MIN_VALUE

Algorithm

I have, in the past, tried to out-perform BigDecimal (not BigInteger), by building a mutable version of BigDecimal. It became really complicated really fast. The concept of a MutableBigInteger is nice, but the reality is that it becomes a mess, fast. There are some open source attempts at this, though I believe they are all languishing in disuse. The reason is simple.... BigInteger is, by an large, fast. The penalty of the Immutable memory hit because  you need to create new values and arrays often, is outweighed by the cost of memory management and expansion that is required otherwise.

Finally, the individual operations inside the BigInteger class are able to use the native storage mechanism directly when doing calculations, and you don't need to do the translations for each bit, for example. In other words, 'wrapping' BigInteger is never going to give you the performance that BigInteger itself can give, simply because the internals of BigInteger can access the more efficient internal data structures.


Counting the number of bits of a positive integer

The very first thing you should do to improve it is comment it. I'm reading it for almost half an hour and still can't understand what it does. I tested it, and it indeed work as intended, but I have no idea why. What algorithm are you using?

I pointed below parts of the code that aren't clear to me. Since @blufox already presented a simpler way to count bits (that works for non-zero numbers), I won't bother to suggest an improvement myself.

def bitcount(n):
    a = 1
    while 1<<a <= n:
        a <<= 1

Why is a growing in powers of two, while you're comparing 1<<a to n? The sequence you're generating in binary is 10 100 10000 100000000 10000000000000000 ... Take n=101010, and notice that

10000 < 100000 < 101010 < 1000000 < 10000000 < 100000000

i.e. there is no relation between 1<<a and the number of bits in n. Choose a=1<<2, and 1<<a is too small. Choose a=1<<3 and 1<<a is too big. In the end, the only fact you know is that 1<<a is a power of two smaller than n, but I fail to see how this fact is relevant to the task.

    s = 0
    while a>1:
        a >>= 1
        if n >= 1<<a:
            n >>= a
            s += a

This removes a bits from n, while increasing the bit count by a. That is correct, but I fail to understand why the resulting n will still have fewer bits than the next 1<<a in the sequence (since they vary so wildly, by 2**(2**n)).

    if n>0:
        s += 1

    return s

I see that the result is off by 1 bit, and your code correctly adjust for that. Again, no idea why it does that.


moving player right or left depending on swipe

I changed some local variables and make them static variables, why ? because these are created and destroyed if you use serveral times the method onFling. The main Idea is to improve the performance and decrease the space your method uses.

Also I refactorized some pieces of code

class MyGestureDetector extends SimpleOnGestureListener {
        private static DateFormat date = new SimpleDateFormat("KK:mm");
        private static Calendar cal;

        MyGestureDetector() {
            date.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00"));
            String localTime = date.format(cal.getTime());
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X -= K;
                    Y *= Math.cos(18*cal.get(Calendar.SECOND)); //18 * currentSeconds i think
                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X += K;
                    Y *= Math.cos(18*cal.get(Calendar.SECOND));
                }
            } catch (Exception e) {
                // Perhaps if the program does nothing or have an unexpected behavior
                // you are silencing the cause (it has happened to me)
                e.printStackTrace();
            }
            return false;
        }

Hope it helped.


updated version of the code, based on @MarcoTerzolo 's answer

import { Injectable } from '@angular/core';

import { Observable, Observer, ReplaySubject, Subject } from 'rxjs';
import { take } from 'rxjs/operators';

const VERSION = 2;

// good tutorial: https://code.tutsplus.com/tutorials/working-with-indexeddb--net-34673
// reference: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB

@Injectable()
export class LocalDbService {
  db: Subject<IDBDatabase> = new ReplaySubject<IDBDatabase>(1);

  constructor() {
    window['SLOCALDB'] = this;

    if (!window.indexedDB) {
      this.db.next(undefined);
      this.db.complete();
    } else {
      console.log(`localdb - requesting open of 'swbuddy' version ${VERSION}`);

      const openRequest = indexedDB.open('swbuddy', VERSION);
      openRequest.onerror = err => {
        console.error('localdb - open has error:', err);

        this.db.error(err);
        this.db.complete();
      };

      openRequest.onupgradeneeded = function(e: any) {
        console.log('localdb - upgrade needed!');

        // create object stores for 'rawLogin' and 'rawVisit'
        const db: IDBDatabase = e.target.result;
        if (!db.objectStoreNames.contains('rawLogin')) {
          db.createObjectStore('rawLogin');
        }

        if (!db.objectStoreNames.contains('rawVisit')) {
          db.createObjectStore('rawVisit');
        }

        // for testing any type of object setup
        if (!db.objectStoreNames.contains('test')) {
          db.createObjectStore('test');
        }
      };

      openRequest.onsuccess = (e: any) => {
        console.log('localdb - open success!', e.target.result);

        const db: IDBDatabase = e.target.result;
        this.db.next(db);
      };
    }
  }

  get(storeName: string, key: any): Observable<any> {
    console.log('localdb.query()');
    return Observable.create((observer: Observer<any>) => {
      try {
        console.log('localdb.query() - subscribed!');
        this.db.pipe(
          take(1)
        ).subscribe(db => {
          console.log('localdb.query() got db:', db);
          if (!db) {
            observer.error('IndexDB not supported!');
            return;
          }

          const txn = db.transaction([storeName], 'readonly');
          const store = txn.objectStore(storeName);
          const req = store.get(key);
          req.onerror = function(e: any) {
            observer.error(e.target.error);
            return;
          };
          req.onsuccess = function(e: any) {
            observer.next(e.target.result);
            observer.complete();
          };
        });
      } catch (err) {
        observer.error(err);
      }
    });
  }

  put(storeName: string, key: any, value: any): Observable<any> {
    return Observable.create((observer: Observer<any>) => {
      try {
        this.db.pipe(
          take(1)
        ).subscribe(db => {
          if (!db) {
            observer.error('IndexDB not supported!');
            return;
          }

          const txn = db.transaction([storeName], 'readwrite');
          const store = txn.objectStore(storeName);
          const req = store.put(value, key);
          req.onerror = function(e: any) {
            console.log('store error event:', e);
            observer.error(e.target.error);
            return;
          };
          req.onsuccess = function(e: any) {
            console.log('store success:', e);
            observer.next(e.target.result);
            observer.complete();
          };
        });
      } catch (err) {
        observer.error(err);
      }
    });
  }

  delete(storeName: string, key: any): Observable<any> {
    console.log('localdb.delete()');
    return Observable.create((observer: Observer<any>) => {
      try {
        console.log('localdb.delete() - subscribed!');
        this.db.pipe(
          take(1)
        ).subscribe(db => {
          console.log('localdb.delete() got db:', db);
          if (!db) {
            observer.error('IndexDB not supported!');
            return;
          }

          const txn = db.transaction([storeName], 'readwrite');
          const store = txn.objectStore(storeName);
          const req = store.delete(key);
          req.onerror = function(e: any) {
            observer.error(e.target.error);
            return;
          };
          req.onsuccess = function(e: any) {
            observer.next(e.target.result);
            observer.complete();
          };
        });
      } catch (err) {
        observer.error(err);
      }
    });
  }

  query(storeName: string): Observable<any> {
    console.log('localdb.query()');
    return Observable.create((observer: Observer<any>) => {
      try {
        console.log('localdb.query() - subscribed!');
        this.db.pipe(
          take(1)
        ).subscribe(db => {
          console.log('localdb.query() got db:', db);
          if (!db) {
            observer.error('IndexDB not supported!');
            return;
          }

          const txn = db.transaction([storeName], 'readonly');
          const store = txn.objectStore(storeName);
          const req = store.openCursor();
          req.onerror = function(e: any) {
            observer.error(e.target.error);
            return;
          };
          req.onsuccess = function(e: any) {
            const cursor = e.target.result;
            if (cursor) {
              observer.next({key: cursor.key, value: cursor.value});
              cursor.continue();
            } else {
              observer.complete();
            }
          };
        });
      } catch (err) {
        observer.error(err);
      }
    });
  }
}


Regarding the safety aspect of your question.
The reason why exec() can be dangerous is that is can allow a nefarious agent to execute code that you never intended.
Let's assume for example that somewhere in your program, you have sensitive data elements such as:
username = secret_username
password = never_share

And let's also assume that someone calls your program like this:
mmain.py -p 'parser_class1;print globals()'

Then your exec() statement would actually be:
exec("import %s" %('parser_class1;print globals()'))

And this would result in your program printing out all variables in your global space for them... including your username and password.
By making your program utilize the __import__ method as mentioned by @Jaime, you can at least prevent people from executing non-import statements in your code.
But, you should, whenever possible also examine the input from a user before using it to execute any dynamic code.


Another Conway's Game of Life in Haskell

That's a nice use of stencil2 and Repa. All in all there isn't much to review, it follows a common approach on Conway's Game of Life with Repa. No type signatures are missing, but with Repa it's more or less mandatory to add them.

Well done. But the next time, consider adding all your code, conwayCalculateAge and conwayMakeEmpty were probably interesting (I suspect conwayMakeRandomIO to be the same as conwayMakeRandom but using randomRIOs = randomRs (0, 1) <$> newStdGen).


Coding style in Ruby format in an method and variable assign

Case 1_a. Don't mix pure functions (sub) with destructive functions (sub!). Whenever possible use pure methods:

zip_file = file.sub(directory, '').sub(/^\//, '')
zipfile.add(zip_file, file)

But can't you write simply?

zip_file = File.basename(file)

Case 1_b: I prefer to set variables. Giving names to things is good.

Case 2 : It's ok. I also prefer to write a comma at the last element so it can be freely reordered. I'd also change the structure of settings so it's easier to write:

settings = [
  ["-i", params[:remote_focu][:ip]],
  ["-u", params[:remote_focu][:username]],
  ...
].map { |opt, value| [opt, value].join(" ") }

Case 3 : Use the same indentation style that you used for array. Also, use the library facilities, don't manipulate paths as strings (extremely prone to bugs):

@rf = {
  folder: File.join(Rails.root, ENV["module_remote_focus_folder_path"]),
  ...
}


Reading integers while break condition not met in C++

std::cout << "Enter two numbers." << std::endl;

You are looking to accept integers, not just numbers (i.e. \$1.0, 1e0, 0b1, 0x1\$).

Avoid std::endl.  std::endl inserts a newline character into an output sequence and flushes it as if by calling stream.put(stream.widen('\n')) followed by stream.flush().  If you just want to insert a newline character, then stream '\n'.

std::cout << "Enter two integers:\n"; // can append it on C strings

        std::cin >> _a >> _b;

Think about how you want to handle inputs.  You are expecting 2 integers, but what if they pass you one integer? No integers (or send end-of-file)? For those cases, you should check if the value was read successfull (see 10.10 in your book).

When a value cannot be extracted from the stream, the streamable types in C++ will typically set std::ios::failbit.  When std::string is the type being extracted, a failure to extract leaves the data in the string unchanged.  For other types, like the numeric types, the extraction operation will assign 0 on failure.

If the stream enters a fail state, you won't be able to extract from it until you clear() the error flag.  Not clearing the error flag would result in an infinite loop once the stream entered the error state.

        std::cin.clear();

What if the user enters more than 2 integers? Should you keep reading from the line? Doing this, you'll need to make sure both values are extracted, even if one failed.  Could you ignore() the remaining input until end of line? You were only expecting two integers, so this is an option.

        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

        a = std::stoi(_a);
        b = std::stoi(_b);
        std::cout << "You entered " << a << " and " << b << std::endl;

What happens if the extraction from std::cin fails? Either _a, _b, or both could be empty and std::stoi will throw std::invalid_argument when an empty string is encountered.

std::stoi will truncate at the decimal separator and return the number to that point.  If you want to validate that the string represents an integer, you need to make sure std::stoi reads the full buffer.

        std::size_t last_pos_read;
        a = std::stoi(_a, std::address_of(last_pos_read));
        if (last_pos_read != _a.length()) {
            throw std::invalid_argument("Not an integer.");
        }

Inexperience aside, the big lesson you should take from this review is to test! Test inputs of type integer (negatives, zero, positives, 16/32/64bit values), floating point (representable/nonrepresentable values), string/containers (empty/nonempty, small/large sizes). Test failures at different times, like an immediate failure or a failure after a successful loop.


There are a couple of issues I notice when I look at the code style of your code.

You could hide your internal variables by using the module pattern. Information hiding is a very important concept. Although you have hidden the fields already by putting everything in a function, this will allow more fine grained control. It will also remove the need to use the call function on inner functions.

There are two functions that have the same name execute (parser.execute and the function within). This confusing. It would be better if you would pick two unique names for that.

The names execute and operate are very generic and these two words have a similar meaning. By looking at the names I cannot determine what these functions do. A more clear name would be better.

Abbreviating variables is confusing. Using idx instead of index isn't a real saving, since you should optimize for reading, not for writing. (You will read your code more often than you write it) index is still vague. Describing what kind of index it is makes the variable name more clear.

Comments like

//execute it

are useless. You shouldn't use comments for these straight forward things. Explaining how the other functions work, as is done with array.splice, is also something that isn't common to do.

Using

else if ( !index ) {

for checking whether a index is 0 is confusing. Better would be

else if ( index == 0 ) {

, because then it is instantly clear you are checking whether it is zero instead of not initialized.


Moving certain items in a list to the end

Notice that what you are trying to do is a reordering of your list to put the elements of predefined_list at the end. Hence your function can be as simple as:

   def sanitize(arg):
      predefined_list = [1, 2]
      # Note that False<True and sort algorithm is stable, so:
      return sorted(arg, key=lambda x: x in predefined_list)

As an alternative to the lambda, you can use predefined_list.__contains__.

In fact the sorting key is False for elements which are not in predefined_list and True for elements which are contained. Since False<True the latter elements will be moved at the end of the list.

For this to work it is important to know that (at least from Python 2.2) the sort algorithm is guaranteed to be stable, i.e., it does not change the order of elements with the same key.

If you want to implement the algorithm yourself I would suggest, as @janos already did, to iterate first on the array to be sorted. This is better for performance and solves the issue of repeated elements.

A possible implementation could be:

def sanitize(arg):
    predefined_list = [1,2]
    pop_count = 0
    for i in range(len(arg)):
       if arg[i-pop_count] in predefined_list:
           arg.append(arg.pop(i-pop_count))
           pop_count += 1

About your code: I don't like the use of Exceptions to handle non exceptional situations... however the index method seems to force you to use exceptions so I see no alternative. Anyway I would keep the code inside the try...except block to the minimum, because otherwise you run the risk to hide exceptions caused by some other issue.

Another point is the fact that your algorithm does not handle repeated elements in the original list. You could handle them easily, see below.

Here is a possible cleaning of your implementation:

def sanitize(lst,predefined):
    """
    reorder elements of @lst by moving the elements which also
    belong to @predefined at the end of the list
    """
    for item in predefined:
        while True:
            try:
                i = lst.index(item)
            except ValueError:
                # lst does not contain any occurence of item
                break
            # move the i-th element to the end of the list
            lst.append(lst.pop(i))

    return lst

Only now I notice that the choice of the algorithm changes the resulting list. In fact you have to decide wether the elements moved at the end must keep the original order in the list (as in my suggested implementations) or must keep the order in the list of items to be removed (as in yours).


Refactor jquery (coffescript) code with checkboxes

Step 1: DRY. Encapsulate the "limit checkboxes" behavior in a function

limitCheckboxesIn = (container, limit = 3) ->
  checkboxes = $(container).find ":checkbox"
  checkboxes.on "click", (event) ->
    checked   = checkboxes.filter ":checked"
    unchecked = checkboxes.not checked
    state     = disabled: checked.length >= limit
    unchecked.prop(state).button state

Step 2: ... well, that pretty much it. Call it like so:

$ ->
  limitCheckboxesIn "div.feature_list"
  limitCheckboxesIn "div.style_list"

Here's a demo

By the way, if you just want the most compact solution, you can skip some assignments:

limitCheckboxesIn = (container, limit = 3) ->
  checkboxes = $(container).find ":checkbox"
  checkboxes.on "click", (event) ->
    disabled = checkboxes.filter(":checked").length >= limit
    checkboxes.not(":checked").prop({disabled}).button {disabled}

Personally, I find this a little less readable, but it's a matter of taste; the code's functionally identical.


How do I refactor this responsive background images code?

If the browser doesn't support the property/value combination in its entirety, it will ignore it.  There's no need to do feature detection for this.

body { background: url(<?php echo $img_med; ?>) no-repeat center center fixed; }
body { background: url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);
background-size: cover;
background-repeat: no-repeat; }

If you care about older Android devices, you'll want to provide prefixed versions of background-size.

Make use of the cascade!  The first media query is no media query at all

body {
    background: url(<?php echo $img_medium; ?>) no-repeat center center fixed;
    -webkit-background-size: cover;
    background-size: cover;
}

@media (min-width: 400px) {
    body {
        background-image: url(<?php echo $img_med; ?>);
        background-image: url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);
    }
}

@media (min-width: 1000px) {
    body {
        background-image: url(<?php echo $img_thelarge; ?>);
        background-image: url(<?php echo $img_thelarge; ?>), url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);
    }
}

/* cut out the 1800px media query since it looked identical to the 1000px one */


Is it possible to refactor these two similar methods that handle T and List?

I'm not sure I fully understand the question, but the first thing that leapt to mind is:
<T> can encompass a IList<SomeType> already.

I mean, the first 75% of GetValue() already works with using IList as the generic type:
public async Task<T> GetValue<T>(
        string cacheKey,
        Func<Task<T>> getItem,
        MemoryCacheEntryOptions memoryCacheEntryOptions = null)
{
    if (_memoryCache.TryGetValue(cacheKey, out T cacheEntry))
    {
        return cacheEntry;
    }
    else
    {
        cacheEntry = await getItem();

        return SetValue(cacheKey, cacheEntry, memoryCacheEntryOptions);
    }
}

... memoryCache.TryGetValue() works exactly the same, and will operate correctly.  cacheEntry will be the correct type (an IList of something.)  getItem() works perfectly, too, since it's a Func that returns the appropriate IList.
Literally the only thing that's different is SetValue vs SetValues.  Which, from your original post, looks to be the call into the 3rd party API.
Well, it begs the question of whether SetValue() in the vendor API will work for an IList?
If it does, your probably is immediately solved: just use GetValue for everything and call it a day.
Assuming that it doesn't, maybe the question would be whether something like this would work:
public async Task<T> GetValue<T>(string cacheKey, Func<Task<T>> getItem, MemoryCacheEntryOptions memoryCacheEntryOptions = null)
{
    return GetValue(cacheKey, getItem, x => SetValue(cacheKey, x, memoryCacheEntryOptions));
}
public async Task<T> GetValues<T>(string cacheKey, Func<Task<T>> getItem, MemoryCacheEntryOptions memoryCacheEntryOptions = null)
{
    return GetValue(cacheKey, getItem, x => SetValues(cacheKey, x, memoryCacheEntryOptions));
}

private async Task<T> GetValue<T>(string cacheKey, Func<Task<T>> getItem, Func<T, Task<T>> setItem)
{
    if (_memoryCache.TryGetValue(cacheKey, out T cacheEntry))
    {
        return cacheEntry;
    }
    else
    {
        cacheEntry = await getItem();

        return setItem(cacheEntry);
    }
}


Avoid single statement control structures

if (DecimalNumbers == null)
    writer.Write("null");
else

The one real argument in favor of the single statement version of control statements is that they save typing.  However, in this case, it increases the amount of typing, as you have to add special logic to handle the single statement case.

if (DecimalNumbers == null)
{
    writer.Write("null");
}
else

If anyone ever edits the generated code directly, the single statement form can be actively harmful.  Someone not paying attention can add a second statement and not realize that it is not part of a block.  So a statement that is only supposed to run some of the time runs all the time.

Indentation?

if (DecimalNumbers != null)
for(var i = 0; i < DecimalNumbers.Count; i++)
{
    var value = DecimalNumbers[i];
    GeneratorByteConverter.Include(value, bytes, index);;
    index += 8;
}

Shouldn't most of these lines (all but the first) have another level of indent?

Note that this is an example of when the single statement form can be confusing.  It would be more obvious that the for loop was inside a then block if it were in block form.

foreach vs. for

In .NET, which loop runs faster, 'for' or 'foreach'?

Most answers agree that for is faster than the equivalent foreach but not all.  See here.  Note that that answer is newer than others.

There is no reason why a foreach has to be slower than the equivalent for.  The compiler can certainly make that conversion for you.  Even if it is true for some case now, it may not be true in the future.

Another answer also points out that you would gain as much performance by switching from List to an array.

If performance is that important to you, then you should benchmark the various alternatives.  You might even find it useful to have the code generator run benchmarks for you.  Because apparently some situations are optimized and others not.


Calculate square of a number without multiplication

A more efficient way to do this is to keep doubling the product while you can....

So, for example, \$5^2\$ is:

$$\begin{eqnarray*}
 5 +&  5 &\longrightarrow 10 \\
 10 +& 10 &\longrightarrow 20
\end{eqnarray*} $$

then add the last 5 to get 25.

This can be done efficiently by using bit shifting:

public static int sqr (int val)
{
    int mask = 1;
    int factorsum = val;
    int sum = 0;
    while (val >= mask)
    {
        if ((val & mask) == mask)
        {
            sum += factorsum;
        }
        factorsum += factorsum;
        mask += mask;
    }
    return sum;
}

This is a \$O(\log(n))\$ solution to the problem. See it in ideone too


Increment each digit in a number to form a new number

It works, but it's a bit tricky to follow the logic and work out why. If you work from the other end then you can avoid the Log and Pow and shifting the partial result, and I find that easier to read.

Challange is not a descriptive name. What does the method do? IncrementDigits might be a better name, for example.


Renaming and moving files in a subdirectory with an index and the folder name

Quite nicely done! I only have a few minor comments.

The script is not very "safe" as it is.
There are many possible failure points which are ignored:

What if /path/to/parent/directory/* doesn't exist?
What if cd "$dir" fails? ($dir is not really a directory, or you don't have permission to enter it)
What if cd video fails? (Like $dir)
What if *.mp4 doesn't exist?
What if mkdir "${newfolder}" fails? (no permission)

If any of the above happens,
the script will continue to run regardless of any errors,
and potentially create junk files and directories you didn't intend.

Here's a safer way to protect against these failures:

for dir in /path/to/parent/directory/*; do
    cd "$dir" || continue
    result=${PWD##*/}
    cd video || continue
    echo "$result"
    a=1
    for i in *.mp4; do
        test -f "$i" || continue
        dafile="$(printf "_%02d.mp4" ${a})"
        dafolder="$(printf "_%02d" ${a})"
        newfolder="$result$dafolder"
        newfile="$result$dafile"
        mkdir "${newfolder}" || continue
        mv "${i}" "${newfolder}/${newfile}"
        cd "${newfolder}"
        ffmpeg -i "${newfile}" -r 30 -f image2 "${newfolder}-\%04d.png"
        cd ..
        ((a++))
    done
done

I also fixed the indentation, and replaced let a=a+1 with the somewhat simpler and more intuitive ((a++)).

You seem to like ${name} instead of $name. That's fine, but it's not needed anywhere in the posted code. Usually it's needed in situations like ${name}_suffix, where without the ${...} the "_suffix" would become part of the variable name.


target = ARGV[0].to_s
user = ARGV[1].to_s
wordlist_file=ARGV[2].to_s

Aren't those Strings already?

network = 0
(1..5).each do
    if icmp.ping
        network += 1
    end
end

would be more idiomatic as:

network = 5.times.count do
  icmp.ping
end

#count will count how many times block returned true, exactly what you want.

Ruby has "perlish" globals like $., but they are currently advised against, and Matz even stated how he regrets ever adding them. count could help you here as well:

total_lines = File.foreach(wordlist_file).count

Notice how without a block #count counts everything. Anyway, all stuff with counting lines and while loop in your code is unnecessarily complicated, if you want to loop through lines in a file, #foreach does just that:

File.foreach(wordlist_file).with_index do |line, idx|
  # process line(from file, you need chomp) and idx here
end

No need for linecounter, and Ruby will close the file at the end of block. In general, we let the Ruby iterate for us. Get a good grasp of iterators and Enumerable module, it makes things much easier.

Minor, less important thingies:

puts "\nThe password is #{pass}"
exit

equals:

abort "\nThe password is #{pass}"

Style issue, common Ruby agreement is too use 2 spaces indentation.

Unless I missed something, there are no obvious and reasonable optimizations, apart from getting rid of:

#Counting lines to give progression + opening wordlist file
File.foreach(wordlist_file) {}
total_lines = $.

I don't know what you expected, but this code just iterates whole file and checks where it needed to stop, so you basically process this file twice. As in my example of processing file, you can just use #foreach to process it, Ruby will know when to stop iterating.

Still, Ruby is much slower than C or Java, it's just the way it is.

Oh, I forgot the obvious last time. If you structured your code into methods, and put them in a module, this script would become much more reusable tool.

module Brute
  def self.force(target, user, wordlist_file)
    if check_connectivity(target)
      wordlist = read_wordlist(wordlist_file)
      wordlist.each do |password|
        # ...
      end
    else
      # ...
    end
  end

  def password_correct?(target, user, pasword)
    # ...
  end

  def check_connectivity(target)
    # ...
  end

  def read_wordlist(wordlist_file)
    # returns array of passwords
  end
end

if __FILE__ == $0
  if ARGV.length != 3
    abort "Please RTFM !"
  end

  Brute.force(ARGV[0], ARGV[1], ARGV[2])
end

You could than require this file and use Brute.force(,,) in any other script, but if __FILE__ == $0 is a common Ruby idiom than checks if file we are in is the file that was run, so you could also just run it from command line like it used to work.


I'm afraid this code has a few bugs.

binsearch([], 1) throws an IndexError.

binsearch([2], 1) goes into an infinite loop.