Returning MIME types according to input filenames' extensions

You should use a list rather than a dictionary for fileNames or extensions.
You don't get any benefit for using a dictionary,
and actually makes the code slightly harder to use.
You should utilize a dictionary's \$O(1)\$ key lookup, rather than re-implement an \$O(n)\$ look up.
This is as if extensions[fileIndex] in MIMETable is already fast.
Utilize dictionary functions such as get(key, default).
You don't need three separate loops, as they are all just different sections of transforming from a file name to a MIME type.
It would also be easier to read it without the loops too.
You should follow PEP8, this means your names should be MIME_table rather than MIMEtable.
Also MIME_table looks odd, so I'd change it to mime_table.
You don't need math or sys, and so I'd remove them.
Your comments are left overs to debugging,
instead of commenting out prints when you're debugging,
I'd recommend that you use Pythons logging library.

Without merging the loops together, you can change your code to:

amount_mime_types = int(input())
amount_file_names = int(input())
mime_table = {}
for i in range(amount_mime_types):
    ext, mt = input().split()
    mime_table[ext.lower()] = mt

file_names = []
for _ in range(amount_file_names):
    file_names.append(input())

extensions = []
for name in file_names:
    if '.' in name:
        extensions.append(name.split('.')[-1].lower())
    else:
        extensions.append('unknown')

mime_types = []
for extension in extensions:
    mime_types.append(mime_table.get(extension, 'UNKNOWN'))

print('\n'.join(mime_types))

Where if you join the file_names, extensions and mime_types loops together you get:

amount_mime_types = int(input())
amount_file_names = int(input())
mime_table = {}
for i in range(amount_mime_types):
    ext, mt = input().split()
    mime_table[ext.lower()] = mt

mime_types = []
for _ in range(amount_file_names):
    name = input()
    if '.' in name:
        extension = name.split('.')[-1].lower()
    else:
        extension = 'unknown'
    mime_type = mime_table.get(extension, 'UNKNOWN')
    mime_types.append(mime_type)

print('\n'.join(mime_types))

There are still a couple ways to improve this:

You can write all this in a function.
This also improves the speed of the program.
Pre-define mime_types to an 'array' of None. mime_types = [None] * amount_file_names.
This is as lists sometimes have to move and is more a 'just in case' optimisation.


I think, there is room for some improvement:

1) You are mixing OOP with procedural code

If you choose one paradigm, you should stick with it. Besides: why are you abstracting selections into a class and not the whole menu?

2) DRY - Don't repeat yourself

print "=" * 25
print "Please Select An Option"
print "=" * 25

Why are you repeating the same task? You could refactor the "=" * 25 into a constant: separator = "=" * 25.

Everytime you need a separator, you could use separator, which is more meaningful.

3) You should separate concerns

print "4. filler\n"
menuOption = input("Select Option: ")

Here you are mixing two concerns printing the options and prompting for input. This pollutes your mainMenu. One function should only do one thing (SRP).

4) Your code lacks an overall structure

If you take every point together, this should now be clear.

I came up with the following:

#!/usr/bin/env python2

import os
from collections import namedtuple

class Menu():

    Option = namedtuple('Option', 'label')
    _separator = "=" * 25
    _options = {1: Option("option one"), 2: Option("option two"),
                3: Option("option three"), 4: Option("option four")}

    def print_header(self):
        print "{0}\n Please Select An Option\n{0}\n".format(self._separator)

    def print_mainMenu(self):
        self.print_header()
        for option in sorted(self._options.keys()):
            print "{0} {1}".format(option, self._options[option].label)

    def prompt(self):
        return input("Select Option: ")

    def handle_input(self, chosen_option):
        try:
            print self._options[chosen_option].label
        except KeyError:
            print "Wrong Option"

def main():
    menu = Menu()
    menu.print_mainMenu()
    menu.handle_input(menu.prompt())

if __name__ == '__main__':
    main()

For this example, the use of namedtuple is not necessary, but on the other hand gives you something like a lightweight object which could not only contain lables. On top options[chosen_option].label is very readable.


RouteContext as constructor parameter or method parameter in ASP.NET vNext

Since you need something that persists for the duration of request, a better place would be to add to RequestContext. So there are couple of ways to handle this more cleanly:

Add a base controller and add additional data to RequestContext:

protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
    // get additional data
    ...

    // add them to routeDate
    requestContext.RouteData.Values.Add(key, value);
    ...

    base.Execute(requestContext);
}

Add your own custom RouteHandler and add additional data to RequestContext:

public class CustomRouteHandler : MvcRouteHandler
{

    protected override IHttpHandler GetHttpHandler(RequestContext requestContext){
           // add to HttpContext
           requestContext.HttpContext.Items["Custom"] = data;

           // or RouteData
           requestContext.RouteData.Values.Add(key, value);
        }
        return base.GetHttpHandler(requestContext);
    }

}

// define route with custom handler
Route customRoute = new Route (
    url: ...,
    defaults: null,
    constraints: ...,
    routeHandler: new CustomRouteHandler()
});

routes.Add(customRoute);


List all direct and indirect employees of a manager

Review

You shouldn't put a function definition inside of another function like that. It means it has to recreate the function every time. It would be better to not get in a habit of that.
Same goes for the contants ceo, etc.
In addition, your code only works for one test case, as you manually check for each member.

Rewrite:

const [addEmployee, getEmplyeeBelows] = (function() {
   class Employee {
      constructor(name, id, manager) {
        this.name = name;
        this.id = id;
        this.manager = manager;
        this.manager = registry[manager];
    }
   }
   const registry = {};
   function addEmployee(name, number, parent) {
      if( parent === null ) {
         registry[name] = new Employee(name, number, parent);
      } else {
         parent.emplyees[number] = new Employee(name, number, parent);
         registry[name] = parent.emplyees[number];
      }
   }
   function getEmplyeeBelows(name) {
      let result = [];
      result.push(...Object.values(registry).map((emp) => {
        return emp.manager == name ? [emp, ...getEmplyeeBelows(emp)] : [];
      })
      return result;
   }
   return [addEmployee, getEmplyeeBelows]
})()
addEmployee('ceo', 1, null);
addEmployee('e1', 2, 'ceo');
addEmployee("e2", 3, 'e1');
addEmployee("e3", 4, 'e1');
addEmployee("e4", 5, 'e2');
addEmployee("e5", 6, 'e2');
addEmployee("e6", 7, 'e3');

const manager = () => {

  var name = document.getElementById("txtName").value;

  eArr = getEmplyeeBelows(name);

  if (eArr.length !== 0)
    document.getElementById("ans").innerHTML = "Ans: " + eArr;
  else
    document.getElementById("ans").innerHTML = "Ans: No reportees";
}


Project Euler #4 - Largest Palindrome Product in Java

Algorithm
Your time and complexity problems are probably the more serious ones. Your code starts small (at 100), and then works up to 1000. This is not the most efficient way of brute-forcing the problem. A better solution would be to start at 999 and work back to 100, but limit it when the result becomes impossible.... let me explain:
    int max = Integer.MIN_VALUE;
    for (int i = 999; i > 100 && i * 999 > max; i--) {
        for (int j = 999; j > i; j--) {
            ....

start high (999 x 999)
Work backwards from there where the second number is larger than the first
track your maximum
terminate the loops if the current i (or smaller) values will never beat the maximum.

Using the above logic, you will eliminate a huge number of loops.
Length check & Finding digit
The Log function is a good check for the length of the value, it's fine. On the other hand, it may not be necessary at all... same applies to the "finding digit"
Palindrome
I like the following method for identifying palindromic numbers:
private static final int reverse(int value) {
    int result = 0;
    while (value != 0) {
        result *= 10;
        result += value % 10;
        value /= 10;
    }
    return result;
}

Using that function, your palindrome check simply becomes:
boolean ispalindrome = n == reverse(n);


Are redundancy and reflection my only options here?

Some of the redundancy is accidental, and some essential to your design (not essential to problem though, if it were essential to problem reflection wouldn't help).

Accidental redundancy can be removed thus:

private static NotificationSetting GetNotificationSetting(User user, NotificationType type)
{
    switch (type) {
    case NotificationType.Followed: return user.Followed;
    case NotificationType.Unfollowed: return user.Unfollowed;
    case NotificationType.Messaged: return user.Messaged;
    default:
        throw new InvalidEnumArgumentException("Invalid Notification Type");
    }
}

public void TriggerNotification(object db, User user, NotificationType type, string content) {
    CreateNotification(db, user, GetNotificationSetting(user,type), content);
}

Note:

I changed the exception as InvalidDataContractException seems to be serialization related.
GetNotificationSetting should be moved to User (or made an extension method of that class).

Now that this is out of the way,

What can you change in the design to remove redundancy?

Your user entity is not normalized. If you really were doing code-first design, User would look like this instead:

class User: Settings
{
}

public abstract class Settings {
    public IDictionary<NotificationType, NotificationSetting> NotificationSettings { get; set; }
}

Then TriggerNotification becomes just:

public void TriggerNotification(object db, User user, NotificationType type, string content) {
    CreateNotification(db, user, user.NotificationSettings[type], content);
}

Another redundancy is in NotificationSetting. It clearly is a bitmask.

[Flags]
public enum NotificationSetting : uint
{
  Navbar = 1,
  Email = 2,
// can add more like so
  Telegram = 4,
  PersonalVisit = 8,
}

Then

if (setting.Equals(NotificationSetting.Email) || setting.Equals(NotificationSetting.Both))

becomes

if (setting.HasFlag(NotificationSetting.Email))


Checking if string characters can be arranged to form another string

The way to improve your performance is to use a better algorithm, specifically, sort both strings and compare:

function stringscrambling(str1, str2) {
 var sort1 = str1.split('').sort().join('');
 var sort2 = str2.split('').sort().join('');

 return sort1 === sort2;
}


Purchase tickets calculation with JavaScript

General advices

Separate pure functions from impure ones.
Pure functions don't have side effects and they are easy to test and reuse. If you have function, which
contain pure (some calculations) and impure (DOM access/modify) parts — split it on two functions.

Create functions, which will do only thing.
Do not force reader (primarily you) to keep in mind function side effects.

To improve code quality start by writing functions calls instead of functions definitions.
This will force you to think more about function signature and its usability.

Solve more general problem after solving few particular ones.
General solutions are more reusable, although could be more complex.

Line by line review

Comment // declare all variables is not very useful. This comment contains obvious information.
Comment // generic function that takes in quantity and multiplies with appropriate price
discloses inner working of function calcPrice().
Reader should not understand how function work in order to use it.
Your function name is calcPrice() and its second parameter is price. This is confusing.
You actually calculate total price.
Comment // generic function that outputs final price and amout it tickets purchased is redundant and contains typo.
Function getMessage() has two responsibilities.
First one is creating string message, second one is assigning it to innerHTML of HTML element. Split it.
You will get NaN if one of input fields is empty.
Don't define var variables in block scope. var has function scope. Use IIFE if you need to have a scope.
You duplicate function call calcPrice() three times, which is not really bad, but can be improved.

Suggested solution

function calcTotalPrice(quantity, price) {
    return quantity * price;
}

function getMessage(quantity, totalPrice) {
    return 'You purchased ' + quantity + ' ticket(s) and your total price is $' + totalPrice
}

function parseQuantity(val) {
    return parseInt(val, 10) || 0;
}

// Sum numbers in given list
function sum(list) {
    return list.reduce(function(acc, x) {
        return acc + x;
    }, 0)
}

(function() {
    // We use IIFE here to define a scope to initialize some variables here
    var submitBtn = document.getElementById('submitButton');
    var outputPara = document.getElementById('totalPrice');

    var config = [
        [document.getElementById('quantityAdult'), 49],
        [document.getElementById('quantityChild'), 20],
        [document.getElementById('quantitySenior'), 30]
    ];

    submitBtn.addEventListener('click', function() {
        var totalPrices;
        var quantities = config.map(function (data) { // In ES6 we could use array destructing: [el, price]
            var el = data[0];
            return parseQuantity(el.value);
        });

        if ( sum(quantities) > 0 ) {
            totalPrices = config.map(function(data) {
                var el = data[0], price = data[1];
                return calcTotalPrice(parseQuantity(el.value), price);
            });

            outputPara.innerHTML = getMessage( sum(quantities), sum(totalPrices) );
        } else {
            alert('Please purchase at least 1 ticket');
        }
    });

}());
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Purchase your tickets online!

$49 - Adult

$20 - Child

$30 - Senior

    Quantity: <input type="text" id="quantityAdult" value="0"> Adult

    Quantity: <input type="text" id="quantityChild" value="0"> Child

    Quantity: <input type="text" id="quantitySenior" value="0"> Senior

    <button type="submit" id="submitButton">Submit</button>

    <button>Proceed To Checkout</button>


Welcome to Code Review.

As stated in the comments, the code is the C programming language, not C++. C is a procedural language and C++ is an object oriented lanugage originally based on C. We can tell from the first line,

#include <stdio.h>

In C++ this file would be <cstdio> but generally we would not be using it because represents an older form of input/output that has been replaced in C++.

C++ generally uses

#include <iostream>

which provides std::cin as input and std::cout as output.

The functions printf() and scanf() generally are not used in C++. FYI scanf() and printf() are not members of the std namespace and std::scanf() does not compile in many compilers.

Complexity
It might be better if there was a function to get the input and another function to process the input. This would lead to less variables being declared in main() and functions that are shorter, easier to read debug and maintain.

Variable Declarations
The line of code:

    unsigned long int e[ne],gval,sum=0;

Is difficult to maintain, it would be better if it was multiple lines.

    unsigned long e[ne];
    unsigned long gval;
    unsigned long sum=0;

Also one should choose either long or int but not both. It would be best if gval was also initialized.

Variables should be declared as needed, for instance the variable gval should be defined inside the first inner for loop as shown below:

Variable Names
Rather than providing comments to explain what the variables are, give the variables meaningful names longer than 2 characters.

This makes the code much easier to read, debug and modify.

Spacing
The vertical and horizontal spacing of the code is all crammed together which makes it very difficult to read add vertical spacing after declarations and after logic blocks.

In expressions there should be spaces around binary operators as shown below.

int main()
{   int n,k;                   //n=height of triangle  k=height of sub-triangles   ne= number of elements
    int t1=0;
    int t2=0;

    scanf("%d %d", &n, k);

    int ne=rec(n);
    int rk=rec(k);
    int nt=ne-rk-1;

    unsigned long e[ne];
    unsigned long sum=0;

    for(int i = 0; i < ne; i++)
    {
        scanf("%ld",&e[i]);
    }

    for(int rt = 0, ior = 0; ior < nt; rt++)
    {
        for(int r=0; r<=rt && ior<nt; r++,ior++)
        {
            int ioc = 0;
            unsigned long gval = 0;
            for(int ct=0; ioc <rk; ct++)
            {
                for(int c = 0; c <= ct && ioc < rk; ioc++, c++, t2++)
                {
                    if(gval < e[t2])
                    {
                        gval = e[t2];
                    }
                }
                t2+=rt;
            }
            sum += gval;
            t1++;
            t2 = t1;
        }
    }
    printf("%ld", sum);
    return 0;
}


The code is used to add the digits in a digital clock to each other. I duplicated code and could use some help DRYing it out

For your current code:

Don't name variables float and number; name then for what they represent, not their datatype.
Don't use camelCase for methods; Ruby convention is to use snake_case

As for its functionality: There's a much easier way to get hours and minutes from a total number of minutes:

hours, minutes = total.divmod(60)

#divmod is basically a convenient shorthand for "quotient and remainder"; it's the same as this:

hours = (total / 60).floor
minutes = total % 60

just in one method.

Now, #divmod returns an array with 2 numbers in it, and in the code above I simply assign those two numbers to hours and minutes respectively.

If you then use #divmod again on those two but with 10 as the argument, you can get the "ones" and the "tens", the same way you just got "minutes" and "hours" by using 60 as your argument.

So say the total number of minutes is 119, i.e. 1h 59m, and you want to split both the hours and minutes, you can do this:

total
  .divmod(60)                    #=> [1, 59]
  .flat_map { |n| n.divmod(10) } #=> [0, 1, 5, 9]

Note however, that if you've got more than 99 hours, you could run into problems, as you'll only get the ones and tens; not the hundreds. E.g. 6000 minutes is 100 hours, but the above would return [10, 0, 0, 0] (sum 10), rather than all the individual digits, which would be [1, 0, 0, 0, 0] (sum 1).

This might be correct for the challenge still, since the readout is hh:mm, and thus doesn't say anything one way or the other about how 3-or-more hour-digits should be handled. The "digital sum" might be 10 or 1 - or zero if anything above 4 digits is just ignored. Or it could be d:hh:mm, and it'd be 4 days + 4 hours + 0 minutes = 8... there are just a lot of unknowns.

But if we assume that the input will stick to 2-digit hours, the code above will work without any ambiguity - all we need is the sum. For that you can use #reduce (aka #inject):

def late_ride(minutes)
  minutes
    .divmod(60)
    .flat_map { |n| n.divmod(10) }
    .reduce(:+)
end

and bingo.

But if the idea instead is to add up all the digits individually and the hours can have 3 or more digits, this, as mentioned, won't be quite right.

You can use #divmod repeatedly or recursively to get the digits of an arbitrary number of hours, but for this little challenge, I'll just suggest something I usually don't suggest: Convert the digital readout to a string, and get the digits that way. I usually try to avoid this, since it seems inelegant to treat a numeric value as a string only to get another numeric value. Just hey, it works, so:

total
  .divmod(60)  #=> [1, 59]
  .join        #=> "159"
  .chars       #=> ["1", "5", "9"]

From here, you can use #reduce again to get the sum (just call to_i to get actual numbers from the strings). And then this is your method:

def late_ride(minutes)
  minutes
    .divmod(60)
    .join
    .chars
    .reduce(0) { |sum, n| sum + n.to_i }
end

or, written another way:

def late_ride(minutes)
  minutes
    .divmod(60)
    .join
    .chars
    .map(&:to_i)
    .reduce(:+)
end


Docker script to set up a Python development environment with some Git projects

First off, a little theory. Docker uses most of its RUN commands very similar to what git is doing with commits. That said it makes sense to put RUN commands together that change the state of the image.

By the way, just like in git you can also go back any step in Docker.

According to the Dockerfile reference on RUN the string after RUN is appended to /bin/sh -c on Linux. This means you can chain commands using the usual semicolon (;) and double ampersand (&&) operators. Example:
RUN cmake . && make && make install

Hint: The difference between the semicolon and double ampersand is that a semicolon only separates commands on one line whereas the
latter will run the righthand side command only if the lefthand side
is successful.

Additionally commands like apt-get install allow you to install multiple packages at once, which you actually used a few times already:
RUN apt-get install pkg1 pkg2 pkg3

If the lines get too long, you can use the backslash character (\) at the end of a line to mark a line break. Example:
RUN apt-get install pkg1 pkg2 \
pkg3 pkg4 pkg5

Another way to optimise the image is getting rid of the copy statements and use symlinks instead
Aside from that your Docker file looks good.
If you expect to have variations of the process anytime in the future, consider splitting it into a base image and specialized images that rely on the base.


Processing keyboard input for player movement in a game

Assuming you've used an associative array as discussed, you'll have some sort of walkingData object containing the velocity and animation information for each direction, keyed by the same keys as the Phaser cursors object (left/right/up/down).

In an event-driven system, you would go directly from the key that was pressed to the relevant data, however since you're doing this in Phaser's main loop, you need to list the keys you're checking (which is what your if statements are doing). The dry way of doing this is to loop over walkingData:

for (var direction in walkingData) {
    var directionData = walkingData[direction];
    // update player velocity etc. using direction data
}

The slight wrinkle here is that you also need to update the animations, which happens outside your inputBlocked conditional (and depends on the velocities set).

To get around this, you'll also need to declare an animationDirection variable outside the loop and store which direction to use for animation, then use that data in your second if to set the animations.

The end result will be along the lines of:

var walkingData = {
    left: { /* velocity and animation info */ },
    ...
};

var animationData;
if (!this.inputBlocked) {
    for (var direction in walkingData) {
        if (this.cursors[direction].isDown) {
            var directionData = walkingData[direction];
            /* configure velocities */
            animationData = directionData;
        }
    }
}

//control player walking animation
if (this.player.body.velocity.x || this.player.body.velocity.y) {
    // check for direction, play appropriate animation
    this.player.play(animationData.animation);
} else {
    // stop all animation
    this.player.animations.stop();

    // determine the correct sprite frame,
    // so player stops while facing appropriate direction
    this.player.frame = animationData.stopFrame;
}

(I've removed the != 0 since it is equivalent, assuming velocity.x/velocity.y are defined.)


Queue Implementation using a Linked List

BUG:

public void removeFirst() {

        Node temp = first;
        if (first.next == null)
            last = null;
        first = first.next;

    }

This crashes if you have an empty list. Add a check for first == null. Additionally... what's that temp variable for?

Don't define the Node as T, define the List to contain T.

public class LinkList<T>

This because you use the T outside the Node class and you ended up having to add it to the addLast method.

    if (isEmpty()) {
        n.next = first;
        first = n;
        last = n;
    } else {
        last.next = n;
        last = n;
        last.next = null;
    }

You already know that n.next is null. You also know that first is null, because that's what defines isEmpty().

So instead, try this:

    if (isEmpty()) {
        first = n;
    } else {
        last.next = n;
    }
    last = n;
    last.next = null;

It does the same thing.

Design:

You have an insert (enqueue) method... but there's no way to retrieve an object that went into the Queue. removeFirst could return the object. This drastically cuts down on the uses of such an object (it's useless now).


Checking percentage of free memory using top and awk

On my test system, the output of top -b -n1 | head looks like this:

top - 09:33:08 up 9 days, 23:07,  7 users,  load average: 0.01, 0.10, 0.13
Tasks: 125 total,   1 running, 124 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.2%us,  0.0%sy,  0.0%ni, 99.7%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   4054892k total,  3938964k used,   115928k free,       56k buffers
Swap: 10485756k total,   536176k used,  9949580k free,   438836k cached

  PID USER      PR  NI  VIRT  RES  SHR S   %CPU %MEM    TIME+  COMMAND
    1 root      20   0 10548   36    8 S      0  0.0   0:02.69 init
    2 root      20   0     0    0    0 S      0  0.0   0:00.06 kthreadd
    3 root      20   0     0    0    0 S      0  0.0   0:01.22 ksoftirqd/0

I suppose yours is similar.
From your code it looks like you are extracting the values from the Mem: line,
in this example 4054892k and 115928k.
Those values are in the 2nd and 6th column (in Awk terms), so you can get them easily in one command with:

top -b -n1 | awk '/^Mem:/ {total=int($2); free=int($6);}'

Now it's easy to add the percentage calculation and print the result:

top -b -n1 | awk '/^Mem:/ {total = $2; free = $6; per = free / total * 100; print per <= 20 ? "FAIL" : "OK"; exit}'

Some additional points of interest:

After printing, we exit to stop processing unnecessarily the rest of the output coming from top
The ternary operator ?: can simplify the printing, no need for an if-else
I dropped the int(...) calls, as Awk seems to drop the trailing non-numeric values anyway
The pattern /^Mem:/ is more strict than in the original code, just to be safe

UPDATE

If you the position of free memory can be in different columns depending on the system, you have (at least) 2 options to work around that:

If you can know the position in advance (by detecting based on the system / runtime environment), you could pass that in as a variable, for example:

i=6; top -b -n1 | awk -v i=$i '/^Mem:/ {total = $2; free = $i; per = free / total * 100; print per <= 20 ? "FAIL" : "OK"; exit}'

Or, you could use regular expressions, for example:

top -b -n1 | awk '/^Mem:/ {total = $2; match($0, /[0-9]+[a-z] free/); free = substr($0, RSTART); per = free / total * 100; print per <= 20 ? "FAIL" : "OK"; exit}'


Shorter, better way to write a "query" involving virtual attributes

Some notes:

result = []: Try not to use generic names like result. Also, use plural names for collections.
init empty array + each + conditional push = select/reject. More on functional programming.
else false. In an each block the value is ignored, so this does nothing.
result[0]. People usually write result.first, but [0] is also ok.
if result.length > 1. There is a serious conceptual problem here, validations should be enforced somewhere else (this is Rails, so using a validation callback).

I'd write:

def current_invoice
  non_rescinded_invoices = invoices.select { |i| i.current_status != "rescinded" }
  if non_rescinded_invoices.size > 1 # but this should be probably an AR validation
    raise("Only one non-rescinded invoice association per contract")
  else
    non_rescinded_invoices.first
  end
end


The comments in the clearmem procedure for the Linux block look a bit confusing.  You could just have a summary of the procedure commented above, and have the individual comments for each line specify the meaning of the assembly instructions.

Specifically, the lines that describe the C++ code don't quite reflect on the assembly code.  clearmem itself doesn't take two arguments.  The for loop comment statement doesn't seem needed, and it may be clearer to specify when the loop should exit.  You also don't need the obvious comment for ret.
Since it appears the extern "C" corresponds to clearmem, I assume everything else can fully utilize C++.  If so, I'd use std::vector in place of the C-style arrays.  However, since clearmem performs pointer arithmetic, you should use std::vector::data() to pass in the underlying dynamic array.

You can then call size() for the vector object in main() instead of using sizeof.  This function returns an std::size_type, specifically std::vector<int>::size_type.
I'm not sure how print_array() is implemented, but I assume it just uses a for loop to print the array elements.  You might also not need the template argument, and with just a vector, you'll have just one argument.  In the function's loop, you should then use const_iterators for displaying the elements, although using indices is okay (but iterators are still preferred).
clearmem should take size_t instead of long; the former is the same type returned by the sizeof operator.


Functions between certain times of the day

I will comment on this part...

if (hours > 8 & hours < 15) {
    $("video").hide();
    $("video").parent().html("Can you do us all a favor and not eat up all the bandwidth with your video watching?" + "
" + "Thank you!" + "
" + "
");
    $("embed").hide();
    $("embed").parent().html("This is no time for childish games." + "
" + "Shouldn't you be studying or doing something related to school?" + "
" + "
");
} else if(hours > 15 & hours < 8) {
    $("video").show();
    $("embed").show();
}

As Hosch said, you should be using the conditional operator &&.

Also, the else if clause wouldn't work because (hours > 15 && hours < 8) is only true if hours > 15 AND hours < 8, so it's never true. What you want is the conditional "or" operator: if (hours > 15 || hours < 8). But you don't even need to specify that if what you want is just to cover all the other cases: "if it's between 8 AM and 3:15 PM do this, otherwise do that".

So...

else { ... }

looks better.

Finally, hours > 8 && hours < 15 would only be true between 9 AM and 2 PM (instead of between 8 AM and 3 PM) as you're using the "greater than" (>) and "lesser than" (<) operators instead of "greater or equal" (>=) and "lesser or equal" (<=).

In order to cover the whole range you specified, you should write something like:

if ((hours >= 8 && hours < 15) || (hours == 15 && minutes <= 15)) { ... }


Pandas updating/adding columns to rows incrementally using dictionary key values

Since there is an e missing in the input dataframe in col A provided by you, I have added it:

#input
A_list = ['a', 'b', 'c', 'd', 'f']
df = pd.DataFrame({'A': ['a', 'b', 'c', 'd','e','f'], 'B': [1,2,3,3,2,1]})

You can start by joining the list you have:

pat='({})'.format('|'.join(A_list))
#pat --> '(a|b|c|d|f)'

Then using series.str.extract() I am extracting the matching keys from the series based on the pattern we created.

s=df.A.str.extract(pat,expand=False) #expand=False returns a series for further assignment
print(s)

0      a
1      b
2      c
3      d
4    NaN
5      f

Once you have this series, you can decide what you want to do with it. For,example if I take your function:

def gen_data(key):
    #THIS FUNCTION IS JUST AN EXAMPLE THE COLUMNS ARE NOT NECESSARILY RELATED OR USE THE KEY
    data_dict = {'C':key*2, 'D':key, 'E':key*3}
    return data_dict

And do the below:

df.join(pd.DataFrame(s.apply(gen_data).values.tolist()))

We get the desired output:

   A  B    C    D    E
0  a  1   aa    a  aaa
1  b  2   bb    b  bbb
2  c  3   cc    c  ccc
3  d  3   dd    d  ddd
4  e  2  NaN  NaN  NaN
5  f  1   ff    f  fff

However I personally wouldn't use apply unless mandatory, so here is another way using df.assign() where you can pass a dictionary of the extracted series and assign it to the dataframe:

df=df.assign(**{'C':s*2,'D':s,'E':s*3})

   A  B    C    D    E
0  a  1   aa    a  aaa
1  b  2   bb    b  bbb
2  c  3   cc    c  ccc
3  d  3   dd    d  ddd
4  e  2  NaN  NaN  NaN
5  f  1   ff    f  fff


HTTP redirects after login, registration, and logout

Your RedirectInterface type doesn't redirect. It's just a URL builder. Either the name should be changed to reflect that, or RedirectInterface needs a redirect method.
You're supplying a customer ID to RedirectFactory::build, but your interface also specifies an optional $customerId parameter. If i'm ever handed a RedirectInterface, i can't make assumptions about how it was built. I don't know whether it was constructed with a customer ID, or whether i need to give it one -- or, even worse, whether the customer ID i supply will be used at all, or the one supplied to RedirectFactory::build will override it. I would get rid of the parameter in one place or the other to minimize that confusion.
RedirectFactory does one of exactly two "redirects", and uses a string to decide between them. Right now, this is false indirection. You could replace these two cases with distinct functions, and no functionality whatsoever would be lost. (Think about it...are you ever going to not know which kind of redirect you want?)

If you're going to keep this at all, then have an array mapping types to builder functions/objects for the various URL types. Provide a way to add redirect types to the array, and add your 'login' and 'register' cases in that manner.  Something like, say,

class RedirectFactory {
    private static $urlBuilders = [];

    public static function addRedirectType($type, RedirectInterface $builder) {
        if (isset(self::$urlBuilders[$type])) {
            throw new InvalidArgumentException("Type '$type' is already defined");
        }

        self::$urlBuilders[$type] = $builder;
    }

    public static function build($type) {
        if (isset(self::$urlBuilders[$type])) {
            return self::$urlBuilders[$type];
        }
        else throw new InvalidArgumentException('Invalid redirect type.');
    }

    public static function getUrl($type, $customerId) {
        return self::build($type)->getUrl($customerId);
    }

    public static function bounce($type, $customerId) {
        $url = self::getUrl($type, $customerId);
        header("Location: $url");
    }
}

Redirects::addRedirectType('login', new LoginRedirect);
Redirects::addRedirectType('register', new RegisterRedirect);

And your redirect code becomes

$redirectUrl = RedirectFactory::build('register')->getUrl(102);
header('Location: ' . $redirectUrl);

Or:

$redirectUrl = RedirectFactory::getUrl('register', 102);
header('Location: ' . $redirectUrl);

Or even better:

RedirectFactory::bounce('register', 102);

Of course, at that point, this really isn't a "factory" anymore, and should probably change its name. You probably also don't gain anything from having build be public.

I have to wonder, though, whether RedirectInterface and its relatives are overengineering. Single-method interfaces and classes like this are generally just a workaround for languages that lack any functional programming capability.


Check if 2 arrays have (exactly) the same elements recursively

Boolean return anti-pattern

It is a very common over-complication beginner make to write:

if (cond) {
    return true;
else {
    return false;
}

When all you need is:

return cond;

So the block:

if (Arr1[0] == Arr2[0])
    return true;
else
    return false;

becomes:

return Arr1[0] == Arr2[0];

Never comment when a block closes

Things like:

}//else

are not ok. If you need them to keep track of the code, your code has overly long blocks, and the problem must be fixed at its source.


Your code looks nice and is well documented.

Many details can be improved though.

num_students = int(input()) could be moved in get_students so that your code deals with input in a single place.
even though the problem talks about lists, it may be more idiomatic to use a list of tuples instead of a list of list. I'd highly recommend Ned Batchelder's excellent article "Lists vs. Tuples" to know more about this.
0 as a first argument of range is not needed as it is the default value. So you could rewrite: for s in range(0, num_students): as for s in range(num_students):.
Underscore (_) is pretty conventionnal for variable with an used value so you could write: for _ in range(num_students):.
Adding a simple print statement in get_lowest_grade shows that the function is called more often that it needs. This is a real issue when you have many students because your algorithm with go through all student for all students. Your algorithm is said to be quadratic or O(n^2). You could retrieve the lowest grade once and for all .

Your code would look like this:

def get_students() -> list:
    """Returns a list of names and grades of N students read from stdin
    where each name and respective grade is separated by a new line."""
    return [('Harry', 37.21), ('Berry', 37.21), ('Tina', 37.2), ('Akriti', 41), ('Harsh', 39),
            ('Harry', 37.21), ('Berry', 37.21), ('Tina', 37.2), ('Akriti', 41), ('Harsh', 39),
            ('Harry', 37.21), ('Berry', 37.21), ('Tina', 37.2), ('Akriti', 41), ('Harsh', 39)]
    num_students = int(input())
    students = []
    for s in range(num_students):
        name = input()
        grade = float(input())
        students.append((name, grade))
    return students

def get_lowest_grade(students: list) -> float:
    """Returns the lowest grade from a list of students[name, grade]."""
    lowest_grade_student = min(students, key = lambda x: x[1])
    return lowest_grade_student[1]

def get_students_with_grade(students: list, grade: float) -> list:
    """Returns the students with the lowest grade
    from a list of students(name, grade)."""
    return [s for s in students if s[1] == grade]

def get_students_without_grade(students: list, grade: float) -> list:
    """Returns a list of students with the lowest graded students excluded
    from a list of students(name, grade)."""
    return [s for s in students if s[1] != grade]

def get_student_names_sorted_alpha(students: list) -> list:
    """Returns a list of names sorted alphabetically from a list of students[name, grade]"""
    names = [s[0] for s in students]
    return sorted(names)

def main():
    students = get_students()
    lowest_grade = get_lowest_grade(students)
    students2 = get_students_without_grade(students, lowest_grade)
    lowest_grade2 = get_lowest_grade(students2)
    second_lowest = get_students_with_grade(students2, lowest_grade2)
    for name in get_student_names_sorted_alpha(second_lowest):
        print(name)

if __name__ == '__main__':
    main()

A different algorithm could be written using a different data structure like a dictionnary or a counter.


Unit testing a servlet in a meaningful way

Bug: You're verifying if sessionUser is different from null, but you're doing sessionUser.getId() before you're sure if it's null or not. If it was null, doing getId would have thrown a NullPointerException

int userId = sessionUser.getId();

if (sessionUser != null) {


Reviewing code for coolness is a first ;)

Some observations:

initialize : if really all you want to do there is Hello World, then you should take it out. initialize is meant for initializing your model with answers.
getCorrect and getWrong are short one-liners that are called once, you should inline them
arr1, arr2, coll and even result are pretty terrible names, how about correctAnswers, wrongAnswers, answers and not creating coll since you could return the results of new AnswersCollection immediately.
The most serious problem though is that you are not declaring the prior mentioned variables with var, that is bad.

Also, from a coolness perspective, braces on their own line is where it's at.

I would counter-propose this:

var AnswersCollection = Backbone.Collection.extend(
{
    model: Answer,

    randomSet: function(correct, wrong)
    {
        var correctAnswers = _.sample(this.where({correct: true}), correct),
            wrongAnswers = _.sample(this.where({correct: false}), wrong),
            answers = _.shuffle(correctAnswers.concat(wrongAnswers));

        return new AnswersCollection( answers );
    }
});


I want some help in tuning this script if possible cause it takes time
  if I increased my array

Yes, the script can be tuned. I will discuss optimizing you script at the end of this post.

The warnings pragma

  also if I use warnings I get a lot of warnings which I'm unable to
  handle

Yes correct, you will get many warnings in case you add the statement use warnings. Using the warnings pragma is highly recommended, see for example:

Why use strict and warnings?
Why not use strict and warnings in Perl?

In short, the warnings pragma help you find bugs in your code. If you add the use warnings to the top of your program, the first warning you get is

Argument "" isn't numeric in multiplication (*)

This happens because in the first iteration of the for loop, $_ will be equal to 1, and at line 4 of your program where you mulitply the substrings:

substr($_, 0, 1) * substr($_, 1))

the first substring will be "1" and the second will be the empty string "". When you try multiply with the empty string (and warnings are disabled) it will be converted silently to a zero, see perldata. To demonstrate:

$ perl -E 'say 1 + ""'
1

but if you turn on warnings (use the -w flag):

$ perl -wE 'say 1 + ""'
Argument "" isn't numeric in addition (+) at -e line 1.
1

you will get the warning Argument "" isn't numeric.

The next warning you get will be

substr outside of string

this happens because substr returns an undefined value
if the substring is beyond either end of the string. In this case, substr will also produce a warning (if you have enabled warnings with use warnings). The reason why you get the warning is that $_ is equal to "1" and at line 6 of your script you try call substr $_, 2. To demonstrate:

$ perl -wE '$_="1"; my $s  = substr $_, 2'
substr outside of string at -e line 1.

The next warning you will get is:

Use of uninitialized value in multiplication (*)

This happens also at line 6, where you have

substr($_, 0, 2) * substr($_, 2)

Here the first substring will be "1" ( since $_ is equal to "1" in the first iteration of the for loop), whereas the second substring will be undefined, as discussed above. Now if you try multiply 1 * undef you will get 0, and a warning (if you have enabled warnings). To demonstrate:

$ perl -wE 'say 1 * undef'
Use of uninitialized value in multiplication (*) at -e line 1.
0

The problem with the code

From the above discussion, it should be clear that the problem with the code that causes the warnings are that it does not use substr correctly when the numbers ( i.e $_ in the for loop ) are less than 8 digits long. If the numbers are more than 8 digits long another problem arises. In this case, the problem is of logical nature in that the program will fail to check all possible palindromes. For example, for a 9 digit number there is no check

if ($_ == reverse(substr($_, 0, 8) * substr($_, 8))) { ... }

Fortunately, these problems can be solved easily using nested for loops:

for (1 .. $max_integer) {
    for my $length ( 1 .. ((length $_) - 1) ) {
        say if $_ == reverse (substr ($_, 0, $length) * substr ($_, $length) );
    }
}

Here, I have defined a variable $max_integer which should be set to the highest integer to check for. For your case, it should be set to 1 billion:

my $max_integer = 1_000_000_000;

The inner for loop takes care of all the if statements in your original code.

Programming style

In Perl there is more than one way to do it (TMTOWTDI). The language was designed with this idea in mind, in that it "doesn't try to tell the programmer how to program". Still, in my experience (I started programming Perl 3 years ago) there are certain programming style guidelines that have been adopted by the community. I have seen these programming styles in practice reading source code of CPAN modules and looking at answers at the Perl tag at stackoverflow.com. Some of these guidelines are described in perlstyle, in Chapter 21 of Programming Perl and in the book Perl Best Practices.

Put all use statements at the top of your program. Since all use statements occur at compile time, it often does not matter for the Perl interpreter where in the source file you place them1. To demonstrate:

 $ perl -E 'say getcwd(); use Cwd'

The above code works fine, even if use Cwd comes after its exported function getcwd is called in the code. However, the above code will
likely confuse humans. You can read more about compile time versus run time in Chapter 16 of the book Programming Perl.

Perl pragmas are a subclass of Perl modules that can have a lexical scope. Since these pragmas only stay in effect within the scope in which they are used, their position in the code is important also to the Perl interpreter. However, these pragmas are typically used at the package scope ( to enable them in the whole source file ), so pragmas are also commonly placed at the top of the source file, to enhance readability and maintainability for a humans.

So for your use case, you should move the use strict to the top of the file, and add a use warnings below it (it also help for a human reader if you keep them in sorted order):

use strict;
use warnings;

Variable naming conventions. I think snake_case is the most common style for a lexical variable, though I have seen many CPAN authors that have used camelCase naming convention. I also prefer snake_case since I believe it easier to read.

Funny enough, I changed my habits several times during my career. I remember I used to make most of my variables camelCase in the beginning, and I could not understand why someone would prefer a variable name like $max_iterations instead of $maxIterations. Two things were disturbing me: first, I thought shorter names were better, and second, I didn't like the idea of using three keystrokes when I could use two keystrokes. However, the shift came after reading stuff and meeting other developers and seeing other people's code, I gradually realialized that code is read much more often than it is written and the benefits of improved readability far outweigh the disadvantage of typing an extra character. Also, I think it is wise to stick to the snake_case convention used by the majority of the Perl community, because consistency is a good thing.

For your case, you already follow the snake_case naming convention for lexical variable (for example in the first line you have my $start_run = time()) so in my opinion: just keep it up.
Spaces around operators. I prefer

if ($_ == gen_number()) { ... }

or even

if ( $_ == gen_number() ) { ... }

to

if ($_==gen_number()) { ... }

The reason is that I find the former easier to read. Adding spaces around most operators is also advocated in perlstyle.

For your case, you could consider adding more spaces around operators in your code.
Indent style. Placement of braces. In Perl "uncuddled elses" and "K&R" style for indenting control constructs is used and recommended almost exclusively (as far as I know). See wikipedia article on indent style and perlstyle. Example of K&R style with uncuddled elses:

if ( $a == 1 ) {
    ....
}
else {
    ....
}

For you case, you have indentation that does not conform with this style. For example:

if ($_==reverse(substr($_, 0, 1) * substr($_, 1)))
      { print $_."\n" ;}

this should be better written to conform with the style guidelines as:

if ( $_ == reverse (substr($_, 0, 1) * substr($_, 1)) ) {
    print $_ . "\n";
}

Optimization

I cannot see how the Perl script itself can be made run substantially faster, however I think the algorithm can be programmed to run much faster in C than in Perl. If the algorithm is only part of a larger program in Perl, it is not necessary to convert the whole program to C. By using the CPAN module Inline::C you can incorporate small pieces of C code into a larger Perl program.

I tested this on Ubuntu 16.04, Perl version 5.22, and found that the version using Inline::C can be approximately 25 times faster than the pure Perl version. Example:

use feature qw(say);
use strict;
use warnings;
use Benchmark qw( cmpthese );
use Inline C => './ppalin_c.c';

my $max = 10_000;

my %sub_info = (
    c    => sub { ppalin_c( $max ) },
    perl => sub { ppalin( $max ) },
);

cmpthese( -3, \%sub_info );

sub ppalin {
    my ( $max ) = @_;

    for (1 .. $max) {
        for my $length (1 .. length($_) - 1) {
            say if $_ == reverse (substr ($_, 0, $length) * substr ($_, $length) );
        }
    }
}

where ppalin_c.c is:

void ppalin_c( int max ) {
    char buf[256];

    for ( int i = 1; i <= max; i++ )
    {
        int a = i;
        char *ptr = buf;
        do {
            int b = a % 10;
            a /= 10;
            *ptr++ = b + '0';
        } while ( a );
        int len = ptr - buf;
        for ( int j = 1; j < len; j++ )
        {
            int fact1 = getfactor( buf, j );
            int fact2 = getfactor( buf+j, len - j);
            int reverse = fact1 * fact2;
            int match = 1;
            char *ptr2 = buf + len;
            for (int k = 0; k<len; k++)
            {
                int b = reverse % 10;
                reverse /= 10;
                if ( *--ptr2 != (b + '0') ) {
                    match = 0;
                    break;
                }
            }
            if ( match ) printf( "%d\n", i );
        }
    }
}

int getfactor( char *ptr, int len )
{
    int pow = 1;
    int b = 0;
    while (len--) {
        int c = (*ptr++ - '0');
        b += c * pow;
        pow *= 10;
    }
    return b;
}

The output:

       Rate  perl     c
perl 97.5/s    --  -96%
c    2544/s 2509%    --

which shows that the C version is 2509% faster than the Perl version for this particular run.

Footnotes:

1. The position of use statements in the source file could be important for the interpreter in some special cases. For example, if compile time code in one module depended on compile time code in another module.


Get file name with extension and get only extension

You are doing too much work manually. It's so much easier and more powerful to use pattern matching.

The two functions can be written as one-liners:

function GetFileName(url)
  return url:match("^.+/(.+)$")
end

function GetFileExtension(url)
  return url:match("^.+(%..+)$")
end

In the patterns, .+ matches one or more any characters as much as possible (greedy). / matches itself, %. matches the dot .. ^ and $ are the anchors for beginning and ending of a string respectively.


Bug: Only works if longs are 64-bit

I ran your program on my 32-bit machine and got the wrong answer for the 1 millionth prime: 15498907 instead of 15485863.  The problem is here:

        if (i*i > i)        // overflow test

If longs are 32 bits, then a number such as 0x10001 will pass this overflow test (because 0x10001 * 0x10001 = 0x20001 after overflowing).  This eventually causes problems because overflowed values are inserted into the map.  Actually, even if longs are 64-bit, you will still have a problem, but it will only happen after i reaches 0x100000001.

I fixed the problem by doing this:

    unsigned long max_i = std::sqrt(~0UL);
    // ...
        if (i <= max_i)      // overflow test

Slow compared to vector based solution

I found your program to be a lot slower than a traditional vector based sieve.  Here are timings for your program vs a traditional sieve that I wrote which used a vector<bool>:

Map    based,  1 millionth prime:  3.77 seconds
Map    based, 10 millionth prime: 47.91 seconds
Vector based,  1 millionth prime:  0.04 seconds
Vector based, 10 millionth prime:  0.93 seconds

Sample vector based code

Since there was a comment asking about how the vector based code would work, here is the full program I used:

#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <vector>

// This function uses the prime counting function approximation:
//
// n = x / ln(x)
//
// Where n is the number of primes below the number x.  Since we are trying
// to find the nth prime, we should solve for x here to determine an
// approximate value for the nth prime.  It turns out that for n >= 6, the
// value we solve for x will always be larger than the nth prime value.
//
// If the sieve size doesn't fit in an unsigned long, this function returns 0.
unsigned long findSieveSize(unsigned long n)
{
    // For small n, the formula returns a value too low, so we can just
    // hardcode the sieve size to 5 (5th prime is 11).
    if (n < 6)
        return 13;

    // We can't find a prime that will exceed ~0UL.
    if (n >= (~0UL / std::log(~0UL)))
        return 0;

    // Binary search for the right value.
    unsigned long low  = n;
    unsigned long high = ~0UL - 1;
    do {
        unsigned long mid   = low + (high - low) / 2;
        double        guess = mid / std::log(mid);

        if (guess > n)
            high = (unsigned long) mid - 1;
        else
            low = (unsigned long) mid + 1;
    } while (low < high);
    return high + 1;
}

unsigned long find_nth_prime(unsigned long n)
{
    if (!n) return 1;           // "0th prime"
    if (!--n) return 2;         // first prime

    unsigned long sieveSize = findSieveSize(n);
    unsigned long count     = 0;
    unsigned long max_i     = std::sqrt(sieveSize-1)+1;

    if (sieveSize == 0)
        return 0;

    std::vector<bool> sieve(sieveSize);
    for (unsigned long i = 3;  true;  i += 2) {
        if (!sieve[i]) {
            if (++count == n)
                return i;
            if (i >= max_i)
                continue;
            unsigned long j    = i*i;
            unsigned long inc  = i+i;
            unsigned long maxj = sieveSize - inc;
            // This loop checks j before adding inc so that we can stop
            // before j overflows.
            do {
                sieve[j] = true;
                if (j >= maxj)
                    break;
                j += inc;
            } while (1);
        }
    }
    return 0;
}

int main(int, char **argv)
{
    std::cout.imbue(std::locale(""));
    while (*++argv) {
        try {
            std::cout << find_nth_prime(atoi(*argv)) << std::endl;
        } catch (std::exception&) {
            std::cerr << "Invalid argument: " << *argv << std::endl;
        }
    }
}


Game boot to some operations every second

The first problem with this code is that there is too little explanation for anything. There is no documentation. There is a referenced class RedisClient for which there is no explanation of what it is and how it is being used. The variable names tend to be undescriptive. When asking other people to read code, then it is the author's responsibility to make it so that they actually can read and follow the code.

The next major problem is a classic issue for newer programmers (and something I have been guilty of myself) - big monolithic procedures, specifically checkQueue. When the size of a procedure exceeds a reasonable size (definition of reasonable vary from person to person, but certainly no more than 10 lines), then the developer should look very hard for ways to refactor it and extract out pieces of discrete functionality. In this code, everything inside the for (range <- ss) block should almost certainly be extracted into a function of its own (with a descriptive function name).

I would recommend fixing these two issues and then post a new question asking for a new review of the modified code.


How secure is my PHP registration script?

You properly protect against SQL injection, that's good.
I worry about the filtering on the password. If I choose <script>' OR 1=1 ">>> as my password, the filtering should not reduce this to just ' OR 1=1 ", just because some part of it looks like HTML tags. A password is not supposed to be displayed anywhere, it is not supposed to be stored in plain text anywhere, the only valid use is to feed it to password_validate and password_hash, and these can cope with arbitrary input (well, except that they stop processing at the first byte that is 0, that is, the byte value 0, not the digit '0'). When I enter a password, I expect this password to be used exactly, unmodified, unnormalized, just as I entered it.
I dimly remember that uniqid is not very unique at all. You should double-check the documentation whether that function provides enough randomness to protect against guessing attacks.
Your code is sending out a mail containing <a href="...">, but nowhere in the code do I see a Content-type: text/html; charset=UTF-8 header.
Your code is sending out malformed HTML. The URL contains a plain &, which in HTML must be escaped as &amp;. To do this, call htmlspecialchars($url). Most browsers accept this malformed HTML, but it's better do know how to correctly convert between plain text and HTML. Just to avoid cross-site scripting from the beginning.
What if the $fname contains an ampersand? Some companies have that in their name. I don't know of actual people with these names, but who knows? An ampersand would make the generated $activation_link invalid.


Project Euler #1: Sum of Multiples of 3 and 5 below 1000

I expect you made a typo.  You don't want (i%35)==0, you want (i%5)==0.

The PEP-8 style guide for Python requires 1 space before and after operators, and after commas.  Use PyLint or equivalent tool to ensure you follow all of the PEP-8 guidelines.

check_sum is unused, and can be omitted.

The brackets around the if( ... ): condition are unnecessary.  This is Python, not C, C++ or Java:

    if (i % 3) == 0 or (i % 5) == 0: #divisor condition

There is no need to create a list just to add up all the numbers after the fact.  You are only using each value once, so you could simply add the numbers up as you find them:

def prob_1():

    sum_of_multiples = 0

    for i in range(1, 1000):  # Take numbers up to but not including 1000
        if (i % 3) == 0 or (i % 5) == 0: #divisor condition
            sum_of_multiples += i

    return sum_of_multiples

You should add """doc_strings""" to your functions:

def prob_1():
    """
    Compute the sum of all the multiples of 3 or 5 below 1000.

    Returns:
        The sum of the multiples of 3 or 5, below 1000.
    """

    sum_of_multiples = 0

    for i in range(1, 1000):  # Take numbers up to but not including 1000
        if (i % 3) == 0 or (i % 5) == 0: #divisor condition
            sum_of_multiples += i

    return sum_of_multiples

You can use list comprehension a generator expression (thanks @Graipher) and the sum(...) function to compute the result, without ever creating the list in memory:

def prob_1():
    """
    Compute the sum of all the multiples of 3 or 5 below 1000.

    Returns:
        The sum of the multiples of 3 or 5, below 1000.
    """

    return sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)

You can also solve this problem by hand with a pen, a sheet of paper, a calculator and about 1 minute of your time.  A program is entirely unnecessary.


Is this a good way to implement a tile map from a text file?

Single responsibility principle

This class is responsible for one too many things:

Model a tile map
Parse a text file

As such it violates the single responsibility principle.
I suggest to move the file parsing code somewhere else.
For example in a TileMapFactory.fromFile method, or TileMapFileParser.

In general, you know something's not right when the constructor is too big.
If it has to do IO, which is especially troublesome because of exception handling and resource management, that's really way too much burden for a constructor.

Prefer List instead of arrays

If you don't need specifically an array, then use a List instead:

List<BufferedImage> tiles = new ArrayList<>();

It will make your life easier. For example, when adding the tiles,
you won't need to worry about correctly incrementing the array indexes:

   tiles.add(Assets.grass);
   tiles.add(Assets.dirt);
   // ... and so on

Magic numbers

The number 32 keeps coming up at many places in the code.
Declare it as a static final variable with a meaningful name.

Get rid of unused stuff

For example this method is pointless, remove it:

   public void update()
   {
   }

Coding style

Instead of y += 1, use ++y.


Generates a randomized locally-administered unicast MAC address

Interesting idea, and pretty good first Bash script.

Bash arithmetics

Instead of this:

let "byte=$RANDOM%255"

I find this more readable:

((byte = RANDOM % 255))

You can use math like this within ((...)), without $ of variables, and with spaces around operators to keep the expressions nicely readable.

You can use this in conditions too,
in fact, instead of this:

if [ $i -eq 0 ];then

It's better to write like this:

if (( i == 0 )); then

And here, this is really awkward, as you are running a sub-shell, and storing the output of echo commands:

prependZero=$([ $byte -lt 16 ] && echo 1 || echo 0)

When it could be simply:

((prependZero = byte < 16))

Padding with 0

Since you already use printf to convert from integer to hexadecimal,
you can actually use it to 0-pad too:

byte=$(printf "%02x" "$byte")

This will pad with zeros on the left to make it 2-digits wide

Suggested implementation

With the above tips, the script can be simpler and cleaner.

#!/bin/bash

macArr=( 0 0 0 0 0 0 )
for ((i = 0; i < ${#macArr[@]}; ++i))
do
    ((byte = RANDOM % 255))

    # the first byte must have the least significant bits set to "10"
    # in order to identify as a locally administered unicast MAC
    if (( i == 0 )); then
        ((byte = ((byte >> 1) | 1) << 1))
    fi

    # convert byte from decimal int to hex string
    byte=$(printf "%02x" "$byte")

    # uppercase any letters in the string
    macArr[$i]="${byte^^}"
done
printf "%s" "${macArr[@]}"


Correctness Issues

Needs dereferencing operator

There are two basic operations every iterator needs to support:

Incrementing the iterator
Dereferencing the iterator

Right now, you've covered incrementing, but not dereferencing. That means you can iterate over items, but you can't look at the items themselves, rendering the whole thing nearly useless (I would remove the "nearly", but you can compute the distance between two iterators, and once in a while that's all you really need).

reference_type operator *() { return *pointer_; }

const correctness

operator ==() and operator !=() should both be const operators.

Correct types

operator== and operator!= should take parameters of type iter_input as their parameters. When you do a comparison, you compare the iterator to another iterator, not the iterator to the type of object the iterator refers to.

These operators should look something like this:

bool operator== (iter_input rhs) const {
  return pointer_ == rhs.pointer_;
}

bool operator!= (iter_input rhs) const {
  return pointer_ != rhs.pointer_;
}

Constructor

The constructor that takes a pointer should take it by value rather than reference. This allows (for example) initializing an iterator from the name of an array:

int x[] = {1, 2, 3, 4};

iter_input<int> begin(x);
// or: iter_input<int> begin = std::begin(x);

You can normally take for granted that pointers are cheap to copy, so you don't normally want to pass pointers by reference for the sake of efficiency (but for things like linked lists, you do sometimes want to pass them by reference because you're going to modify the pointer that's passed).

Style Issues

this-> considered harmful

Using this-> for every reference to a member is (at least in my opinion) a poor idea. It adds visual noise, which hurts readability but provides no benefit.

return is an operator, not a function

When you return a value from a function, you don't need to enclose that expression in parentheses. Again, this simply adds visual noise and hurts readability without any benefit (and in a few cases that don't apply here can cause other problems as well).

Assignment operator

Unless you need compatibility with older (pre C++11) compilers I'd prefer to define the assignment operator as defaulted rather than including a function body for it.

iter_input& operator= (const iter_input& rhs) = default;

Use your own typedefs

Instead of T *pointer_;, I'd prefer pointer_type pointer_;.

Make it a proper header

If you want to do anything more than a minimal test of this code, you probably want it to be in a header. To facilitate that, you could add the (officially not exactly standard, but almost universally accepted) #pragma once at the beginning, or else add standard "header guards":

#ifndef ITER_INPUT_INCLUDED_
#define ITER_INPUT_INCLUDED_

// existing code here

#endif

Note that if you look at your standard headers, the name they use in place of ITER_INPUT_INCLUDED_ will typically start with an underscore. That gives a name that's reserved for the implementation, which means the people writing the compiler can (and in this case should) use that kind of name, but in normal code that's not part of the standard library, you should not use such a name.

Indentation

The 2-space indentation is too small for me to be certain what's supposed to line up with what. The access specifiers (public: and private:) being indented only one space makes this even worse. The days of 40-column displays are long gone. There's no need to skimp on indentation to this degree.


All your fields can be declared private. There is really no need to expose these more than necessary.

@FXML private Label systemOut;
@FXML private GridPane gridPane;
private final static int ROWS = 3;
private final static int COLUMNS = 3;
private int[][] grid;
private boolean turn;

Your initialize and newGame methods looks very much the same to me, you could change your initialize to:

public void initialize(URL location, ResourceBundle resources) {
    newGame(null);
}

public void WhoWon(int x, int[] zone){
    if (zone[x] == 3){
        systemOut.setText("Os won!");
    }else if (zone[x] == 30){
        systemOut.setText("Xs won!");
    }
}

@barq is correct that the method name can be improved, and that passing a single int value to this method should be enough, which can make it:

public void declareWinner(int value) {
    if (value == 3) {
        systemOut.setText("Os won!");
    } else if (value == 30) {
        systemOut.setText("Xs won!");
    }
}

However, these magic numbers 3 and 30 really needs to be fixed. I'd recommend an enum:

public enum Player {
    X, O;
}

And then use a Player[][] instead of int[][]. and a Player turn instead of boolean.

Your win-check approach is a bit... more complicated than necessary. You begin with:

for (int y = 0; y < 3; y++) {
    for (int x = 0; x < 3; x++) {
        zone[zoneNumber] = grid[y][x];
        zoneNumber++;
    }
}

But in reality, there is no need to transform all the positions to a number, instead you can access the 2d array directly, like this:

for (int y = 0; y < 3; y++) {
    if (zone[0][y] == zone[1][y] && zone[0][y] == zone[2][y]) {
        declareWinner(zone[0][y]);
    }
}
for (int x = 0; x < 3; x++) {
    if (zone[x][0] == zone[x][1] && zone[x][0] == zone[x][2]) {
        declareWinner(zone[x][0]);
    }
}
if (zone[0][0] == zone[1][1] && zone[0][0] == zone[2][2]) {
    declareWinner(zone[0][0]);
} else if (zone[2][0] == zone[1][1] && zone[2][0] == zone[0][2]) {
    declareWinner(zone[2][0]);
}

In ButtonCell you are doing:

hoboChess.grid[y][x] = 3;

And violà, you have flipped x and y! In other places you are doing grid[x][y] but here we have grid[y][x]. Thanks to how Tic Tac Toe works, you won't see a difference, but it is still quite important to be consistent.

Also, when changing to using an enum this can become

hoboChess.grid[x][y] = Player.X;

or

hoboChess.grid[x][y] = Player.O;

Overall it does look like you have improved over time. A little additional improvement I would recommend is to separate the game board and logic more from your Java FX controller class.

I would use one file for TicTacToeGame, containing the Player[][] array and who's turn it is, then I would use a method Player makeMove(int x, int y) that would place a mark at the specified position and return which player made the move (for the button to know what mark to set). This game logic class can be made entirely independent of your JavaFX controller, so that it can be easily used in a Java console application, a Swing application, or another framework. This is an important step and skill in programming, to be able to create re-usable classes.


Simplify ASP.Net StreamWriter for appendtext to file

Careful with naming.

UserName is an identifier for a TextBox, but it's named like a String (which contains a user's name).

I'd declare and assign UserName like this:

Dim UserName As String = DirectCast(LoginUser.FindControl("UserName"), TextBox).Text

And now the rest of the code can refer to a string that represents a user's name without any further conversions.

logLoginError is an identifier for a Thread, but it's named like a Task (which runs on a thread).

loggerThread would be a more accurate name for it.

This code:

w.WriteLine(CurrentUser.ToString & "'s (" & IPAddress & ") account is locked out - " & DateAndTime.Now)

Is using way more String instances than you'd think:

CurrentUser.ToString()
"'s ("
IPAddress
") account is locked out - "
DateAndTime.Now[.ToString]

And also:

The string resulting from CurrentUser.ToString() & "'s ("
The string resulting from CurrentUser.ToString() & "'s (" & IPAdress
The string resulting from CurrentUser.ToString() & "'s (" & IPAdress & ") account is locked out - "
The string resulting from CurrentUser.ToString() & "'s (" & IPAdress & ") account is locked out - " & DateAndTime.Now

Are you sure DateAndTime isn't supposed to be DateTime? Also there's a typo in IPAdress, should be IPAddress.

To fix the number of String objects being created, you can use String.Format instead of inline concatenations - remember that String is an immutable class, "appending to it" doesn't really append anything, it just creates a new instance.

This would be cleaner and more efficient (multiline to avoid horizontal scrolling):

w.WriteLine(String.Format("{0}'s ({1}) account is locked out - {2}",
                          CurrentUser.ToString, IPAddress, DateAndTime.Now))


Assembly: Sum up the single bytes of a 32bit-register to a checksum

Since you're still learning, I won't cheat you out of the opportunity to discover for yourself, but I will offer some words of advice on how you can improve your program.

Minimize register use

The current code uses eax, ebx, ecx, edx and ebp.  One of the most important things for an assembly language programmer is to use registers efficiently and effectively.  This particular task can easily be done with just two registers.

Prefer shift to division

As alluded to in a comment, shift instructions are typically much faster to execute than divide instructions.  For that reason, in tasks like this, it's much more common to see a shift than a divide.

Avoid loops

Branching tends to be computationally disruptive for processors.  While modern desktop machines tend to compensate for this via speculative execution and large cache sizes, code often runs faster if loops and branches are avoided entirely.  This can confer other benefits such as more predictable running time which can be important for the scheduling of Real Time Operating Systems (RTOS) and in some kinds of cryptographic code to provide some resistance to side channel attacks.


Performance of object-to-string conversion

(I've made a few assumptions, so please correct me if I'm wrong.)

Let's suppose we have the following types:

public class Foo
{
    public int Id { get; set; }

    [Signed]
    public DateTime Timestamp { get; set; }

    [Signed]
    public string Name { get; set; }

    [Signed]
    public decimal Price { get; set; }

    [Signed]
    public SomeEnum Thing { get; set; }
}

public enum SomeEnum
{
    One = 1,
    Two,
    Three
}

public class SignedAttribute : Attribute
{
}

We want to hash the Signed properties of an instance of Foo (actually, many instances of Foo).

I assume you're currently getting these properties via reflection. Something like this:

var properties = typeof(Foo)
    .GetProperties()
    .Where(p => Attribute.IsDefined(p, typeof(SignedAttribute)))
    .OrderBy(p => p.Name)
    .ToArray();

// ...

var sb = new StringBuilder();
foreach (var property in properties)
{
    sb.Append(ValueToString(property.GetValue(foo)));
}

var bytes = Encoding.UTF8.GetBytes(sb.ToString());
md5.TransformBlock(bytes, 0, bytes.Length, bytes, 0);

Let's set up a test to see how long this takes

var foo = new Foo
{
    Id = 1,
    Name = "Thing",
    Price = 123.45m,
    Thing = SomeEnum.Two,
    Timestamp = new DateTime(2015, 04, 07)
};

byte[] hash;
var sw = Stopwatch.StartNew();
using (var md5 = MD5.Create())
{
    for (var i = 0; i < 300000; i++)
    {
        var sb = new StringBuilder();
        foreach (var property in properties)
        {
            sb.Append(ValueToString(property.GetValue(foo)));
        }

        var bytes = Encoding.UTF8.GetBytes(sb.ToString());
        md5.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
    }

    md5.TransformFinalBlock(new byte[0], 0, 0);
    hash = md5.Hash;
}

sw.Stop();

Here ValueToString is the code as posted in your question. On my machine, I get a time of 0.8s.

How much better can we do? Suppose we could cheat and use the following method:

private static string FooToString(Foo foo)
{
    var sb = new StringBuilder();
    sb.Append(foo.Name);
    sb.Append(foo.Price.ToString(
        "0.############################",
        CultureInfo.InvariantCulture));
    sb.Append(((int) foo.Thing).ToString("X"));
    sb.Append(foo.Timestamp.Ticks.ToString("X"));
    return sb.ToString();
}

So now our loop looks like this:

for (var i = 0; i < 300000; i++)
{
    var value = FooToString(foo);
    var bytes = Encoding.UTF8.GetBytes(value);
    md5.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
}

I get a time of 0.36s, which I'll take as the baseline.

Great, but let's assume we can't write FooToString. We can create an equivalent method dynamically.

We introduce some helper methods:

public static string ValueToString(string value)
{
    return value ?? string.Empty;
}

public static string ValueToString(Enum value)
{
    return Convert.ToInt32(value).ToString("X");
}

public static string ValueToString(decimal value)
{
    return value.ToString("0.############################", CultureInfo.InvariantCulture);
}

public static string ValueToString(DateTime value)
{
    return value.Ticks.ToString("X");
}

And then create the method dynamically, using reflection to find the properties of Foo that have the Signed attribute.

var properties = (typeof(Foo))
    .GetProperties()
    .Where(p => Attribute.IsDefined(p, typeof(SignedAttribute)))
    .OrderBy(p => p.Name)
    .ToArray();

var getSignatureMethod = new DynamicMethod(
    "GetSignature",
    typeof(string),
    new[] { typeof(Foo) },
    typeof(Foo).Module);

var generator = getSignatureMethod.GetILGenerator();
generator.DeclareLocal(typeof(StringBuilder));
generator.Emit(OpCodes.Newobj, typeof(StringBuilder).GetConstructor(Type.EmptyTypes));
generator.Emit(OpCodes.Stloc_0);
generator.Emit(OpCodes.Ldloc_0);

var append = typeof(StringBuilder).GetMethod("Append", new[] { typeof (string) });
foreach (var property in properties)
{
    generator.Emit(OpCodes.Ldarg_0);
    generator.Emit(OpCodes.Callvirt, property.GetGetMethod());
    if (property.PropertyType.BaseType == typeof(Enum))
    {
        generator.Emit(OpCodes.Box, property.PropertyType);
    }

    generator.Emit(OpCodes.Call, typeof(Program).GetMethod("ValueToString", new[] { property.PropertyType }));
    generator.Emit(OpCodes.Callvirt, append);
}

generator.Emit(OpCodes.Pop);
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Callvirt, typeof(object).GetMethod("ToString", new Type[] { }));
generator.Emit(OpCodes.Ret);

var getSignature = (Func<Foo, string>)
    getSignatureMethod.CreateDelegate(typeof(Func<Foo, string>));

(I haven't worked with dynamically generated code before, there might be some things that could be improved.)

Now our loop looks like this:

for (var i = 0; i < 300000; i++)
{
    var value = getSignature(foo);
    var bytes = Encoding.UTF8.GetBytes(value);
    md5.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
}

And on my machine, it takes 0.39s, which is pretty close to the baseline.

I've put the code up on Github if you want to play around with it.


First thing you should do is only write the file out once, not 20,000 times ;-)

Move the wb.write(fileOut); to be outside the loop.....

Additionally, there may be some improvement by reversing the loop:

for(int i=2;i <20002;i++){

can become:

for(int i=20001;i >= 2;i--){

This may make some memory management in the API faster.


Sum array values based on conditions in other arrays

sum([w for w, p, a in zip(wgt_dif, pntl, adj_wgt) if p == 4 and a != max_wgt])

Explanation:

zip(a, b, c)

creates the list of triplets of corresponding values from the lists a, b, c - something as

[(a[0], b[0], c[0]), (a[1], b[1], c[1]), (a[2], b[2], c[2]), ...]

so the part

for w, p, a in zip(wgt_dif, pntl, adj_wgt)

loops over this triples, associating th 1st item to w, 2nd to p, and 3rd to a.


And what's wrong with :

public final class SDGIntIDGenerator {

    private static final AtomicInteger sequence = new AtomicInteger(1);

    private SDGIntIDGenerator() {}

    public static int generate(){
        return sequence.getAndIncrement();
    }

}

Atomic Integer is thread safe.
Put private constructor so no instances can be made.
Only static methods means helper class => make class final.

Edit :

While @bowmore is correct you could want more generators for each class, you could do the following :

public final class SDGIntIDGenerator {

    private static final ConcurrentHashMap<Class,AtomicInteger> mapper = new ConcurrentHashMap<Class,AtomicInteger>();

    private SDGIntIDGenerator () {}

    public static int generateId (Class _class) {
        mapper.putIfAbsent(_class, new AtomicInteger(1));
        return mapper.get(_class).getAndIncrement();
    }
}

With this implementation you could ask an id for each class.
This is because the ConcurrentHashMap is also thread safe for some methods.

Important note : Your generator will reset himself after server restart so usage for generating an id for storing in database is a bad idea.

You could also just return the AtomicInteger.
It doesn't matter if you are using a lot of threads and every thread knows that instance of the AtomicInteger.
The AtomicInteger will stay threadsafe.

Footnote : Wrote in java 6, with higher java you could refactor the instantiation of the ConcurrentHashMap.


I find the cleanest way is to replace the ugly if/else if/else with a dictionary:

private static IDictionary<string, string> FileDataTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    ["Import"] = "Source Data",
    // ..
}

The also not so pretty Contains can be replaced with a nice regex that will grow or shirnk automatically if you add/remove mappings:

private static string GetFileDataType(string fullFileNameWithPath)
{
    var fileName = Path.GetFileNameWithoutExtension(fullFileNameWithPath);
    var fileContentsMatch = Regex.Match(fileName, $"__(?<Type>{string.Join("|", FileDataTypes.Keys)})__", RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
    return
        fileContentsMatch.Success && FileDataTypes.TryGetValue(fileContentsMatch.Groups["Type"].Value, out var fileDataType)
            ? fileDataType
            : FileDataTypes[string.Empty];
}

Notice that both the dictionary and the regex are case insensitive. You should always make paths case insensitive in Windows. You are lucky that this worked for so long.

(Dislaimer: It's just an example so I was to lazy to implement all the empty/null checks)


Discover random web servers and print the index page title

Overall, the code is pretty clean. Some notes about the Python part:

be consistent about the documentation string style - enclose them with triple quotes, start with an upper-case letter, end with a dot (PEP8 reference). I also think that you can use less newline breaks there.
if we would follow PEP8 importing recommendations, there should be a newline between the "system" level imports and third-parties:

import os
import sys

import lxml.html

you should have 2 line breaks between the function definitions (reference)
use print() as a function for Python 3 compatibility
I would avoid unnecessary invert of the logic and replace:

if not len(sys.argv) >= 2:

with:

if len(sys.argv) < 2:

avoid using bare except clauses
you can use .findtext() method:

title.findtext(".//title")

which will return None if title element was not found.


Is using the result of cmp() as an index "too cryptic"?

The documentation to cmp says nothing about the return value except it being negative, zero or positive, so you rely on implementation-dependent behaviour.  This exact function will also not work in Python 3, as there is no cmp function anymore.

I'd say use the second option or shorten it a bit:

def winning_side(home_goals, away_goals):
    if home_goals == away_goals:
        return DRAW

    return HOME if home_goals > away_goals else AWAY


Pretty print uptime given seconds and omit unnecessary strings

I feel like the datetime module isn't really doing much to help you.  By using it, you avoid performing arithmetic and hard-coding constants 86400, 3600, and 60.  However, in exchange, you end up hard-coding the accessors .day, .hour, .minute, and .second, in such a way that you have to write similar code four times, with no easy way to generalize them.  Attempts at generalization are further complicated by the fact that you need d.day-1, due to the way that you have abused datetime addition as a trick to convert the timedelta object into a datetime object.

Your output includes a trailing space, which I consider to be an annoyance.  One way to avoid that would be to use ' '.join(…).  On the other hand, if sec is 0, then the function would return an empty string, which is also unintuitive.  I would prefer 0s as output in that special case.

In my opinion, you would be no worse off doing all of the arithmetic and formatting yourself, without the use of the datetime module.

def format_seconds(sec):
    def repeatedly(f, xs, n):
        for x in xs:
            m, n = f(n, x)
            yield m
    return ' '.join(
        '{}{}'.format(n, unit)
        for n, unit in zip(
            repeatedly(divmod, [86400, 3600, 60, 1], sec),
            'dhms'
        )
        if n
    ) or '0s'


(This is an extended (and formatted…) comment (don't like the repetition of the non-pair comparisons at the beginning and end of the sequence). Not having used C++ in a dozen years, I'm hopeless with move semantics, for one. (And not quite destined to review C++ postings…))

Let me try something about the non-pair comparisons:

template <typename InputIt, typename Compare>
auto minmax_input(InputIt first, InputIt last, Compare comp, std::input_iterator_tag)
{
    using ValueType = typename std::iterator_traits<InputIt>::value_type;

    auto const
        &minimum = *first,
        &maximum = minimum;

    while (++first != last) {
        auto &prev = *first;
        if (++first == last) { // left with half a pair: prev
            if (comp(prev, minimum))
                minimum = prev;
            else if (!comp(prev, maximum))
                maximum = prev;
            break;
        }
        if (comp(*first, prev)) {
            if (comp(*first, minimum))
                minimum = *first;
            if (!comp(prev, maximum))
                maximum = prev;
        } else {
            if (comp(prev, minimum))
                minimum = prev;
            if (!comp(*first, maximum))
                maximum = *first;
        }
    }

    return std::pair<ValueType, ValueType> {minimum, maximum};
}

(Come to think of it, I don't like the symmetrical pairs of comparisons in the loop…)

        auto min_max = std::minmax(one, *first);
        if (comp(min_max.first, minimum))
            minimum = min_max.first;
        if (!comp(min_max.second, maximum))
            maximum = min_max.second;


First of all, your code use Array.each() method, which is a non-standard Javascript method, added by Mootools. I would rather use a standard loop, in order to keep a vanilla JS code.

Then, instead of setting all properties every time, you should test which properties are supported by the browser and set them accordingly.

Finally, since you are moving minutes only when !seconds (i.e. seconds == 0), the clock initialization is a bit weird. On page load, you should always move minutes and hours.


Thanks for sharing the code!

pros

Naming

Finding good names is the hardest part in programming. You did a good job here.
Especially I'd like to mention:

you followed the Java Naming Conventions
Your identifier names come from the problem domain.

Visibility

You declared all your members and methods private.
This is good since it serves both, the information hiding/encapsulation principle and the interface segregation principle.

cons

Magic numbers

Your code contains some literal values.

You should create constants with descriptive names for them. e.g.:

private static final int INITIAL_MINIMUM = 0;
private static final int INITIAL_MAXIMUM = 100;
private static final int TITLE_FONT_SIZE = 30;
private static final String TITLE_FONT_NAME = "Times New Roman";

Inheritance

Your NumberGuesser extends JFrame. I know that many examples out there do this but it is wrong. Your class does not add or change any behavior of its base class. It only configures it. This could also be done with an explicitly created JFrame instance.

Only extend a base class when you have to add or change the base classes behavior.

Call of JFrame.setVisible()

This call should always be the last after completely configuring the frame.

Separation of Concerns / Single Responsibility Pattern

Each class or method in a program should have a clear responsibility.
The instantiation of objects (using the new operator) is a responsibility of its own as well as the configuration of the GUI elements.

Work in constructor

In general constructors should only initialize (final) object members with values passed in as parameters.

Yes, many online resources and even official tutorials do initialization in constructors, but it is still a bad practice

Members

Member variables define the objects state. But some of your members will never change. That means they will never get a new value during life time of the object.

You should document that by making them final.


Generating a histogram efficiently from the datasets in a Map

Summary

Fix the bugs.
Make sure your source code can be understood.
Further improve your symbol names.
Write more, shorter methods.
Use Formatter.
Use smarter algorithms.
Use Stream.collect() to create the second histogram.
Unit test.

Fix the bugs

When you have a user which consumes less than 10 bytes of data, you don't count that. I think that's a bug. I cannot conclude from the way the source code is written that this behavior is intentional. You probably want to

start definitionInBytes with 0
assert that the key in the map is >= 0

or

assert that the key in the map is >= 10

This would also be useful for testing. You would want that the sum of values (total number of users) in the map and the buckets is same, that's an invariant.

You could assert that invariant:

assert userHistogramInfo.values().mapToInt(Integer::intValue).sum() == Arrays.stream(buckets).sum();

If it's actually intentional that it doesn't start with zero, you might consider documenting that. Right now, it too much looks like programming by coincidence and as if it might fall over sooner or later.

Besides, depending on your user base, you actually might want to go for Long instead of Integer. With Integer you can use only 2 Billion users. Given a world population of soon 8 Billion, of which soon everyone has internet access, if you manage to get everyone as user, your code might overflow. Not yet very likely, but think of the COBOL (and other) code that was written with 2-digit dates (sometimes for good reason like space) and then had to be changed later to prevent Y2K trouble. Our code often lives quite long. Why not prepare it for the future if the cost for that in the present is almost nothing.

Understandable source code

This is mostly met. I had no trouble whatsoever understanding your source code.  A few things how I could have understood your source code even faster are mentioned in different points. Just there's one thing in the source code which completely puzzles me. It's this comment:

//This is for database select

I do not see any database or query in context, and I also do not see how the loop that follows this comment would be related to a database query. I'm left puzzled by that comment. Puzzlement without resolution.

Good symbol names

I find the name userHistogramInfo ambiguous and therefore confusing, because the method actually deals with two histograms.

Avoid info, data and such stuff in symbol names, it does not communicate intent, it just adds noise.
For Maps communicate the key and value in the symbol name.

Maybe usersPerSize could be a good name for the input histogram. And usersPerSizeRange could be a good name for the second histogram which is generated from the first.

Use smaller methods

Your method generateHistogram() is too long. Ideally, methods do just one thing, they do it well, and they do it only (Robert C. Martin, Clean Code). It's also known as the SRP - Single Responsibility Principle applied to methods, or "extract 'till you drop" (Robert C. Martin, Clean Code).

Let's see what this method does:

It formats the original histogram.
It prints the original histogram.
It generates a new histogram, based on ranges instead of individual sizes.
It formats the new histogram.
It prints the new histogram.

That's far too much for just one method.
Each of these things should go in a separate method.

Don't be afraid of small methods in Java. The JIT of the JVM is taking care of optimization very very well.

Use Formatter

Formatter is a very useful class for formatting Strings. You don't need to care about the platform's line ending, you use "%n" and Java takes care of the rest. And you have all the usual formatting options, like auto-filling with spaces or leading zero. Hosch250 already explained this nicely in his answer.

Use smarter algorithms

Your array definitionInBytes is sorted. The expectation of most programmers would probably be that if you have a sorted array, you use binary search to identify the location, however, you use linear search.

You could use Arrays.binarySearch() for your use case.

Here's a method which gets the bucket index for a value:

public static int getBucketIndex(final int value) {
    // assert isSorted(definitionInBytes);
    final int searchResult = Arrays.binarySearch(definitionInBytes, value);
    if (searchResult >= 0)
        return searchResult;
    // Warning: returns -1 in case value is less than definitionInBytes[0];
    return -searchResult - 2;
}

Use Stream.collect() to create the second histogram.

This is not really a must. It just might be interesting for you to see what Java can do for you.

Actually, your two arrays definitionInBytes and buckets are a histogram, a Map<Integer, Integer>, just like the input data.
You're grouping the input keys by ranges, summing the values. You could let Java do that for you.

Here's a method which creates a Map<Integer, Integer> from a Map<Integer, Integer> based on specified floors (your definitionInBytes):

import static java.util.stream.Collectors.*;

public class Histogram {
    // ...
    private static final int[] definitionInBytes = { 10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480, 40960, 81920 };

    public static Map<Integer, Integer> groupByRange(final Map<Integer, Integer> usersPerSize) {
        return usersPerSize
            .entrySet()
            .parallelStream()
            .collect(groupingByConcurrent(Histogram::getBucketFromEntry, summingInt(Entry::getValue)));
    }

    public static Integer getBucketFromEntry(final Entry<Integer, Integer> entry) {
        return getFloor(entry.getKey(), definitionInBytes);
    }

    public static int getFloor(final int value, final int[] floors) {
        final int searchResult = Arrays.binarySearch(floors, value);
        if (searchResult >= 0) return floors[searchResult];
        if (-searchResult - 2 < 0) return Integer.MIN_VALUE;
        return floors[-searchResult - 2];
    }
}

Unit Test

When you have everything in one big method, that's of course difficult. If that method is not returning any data but just printing the data, unit testing is even more difficult.

When you write small methods, and ensure that presenting the data is only done at the top-most levels of your call hierarchy, you can unit test all the methods that contain the business logic.

Also, the methods then can be reused.

For example, getFloor() above can be tested individually, whereas the parts of your big method cannot be tested individually.

Ideally, even write the tests first.

Here's an example how to test getFloor():

private static final int[] floors = { 10, 100, 1000 };

@Test
public void testGetFloor() {
    assertEquals(Integer.MIN_VALUE, getFloor(Integer.MIN_VALUE, floors));
    assertEquals(Integer.MIN_VALUE, getFloor(0, floors));
    assertEquals(Integer.MIN_VALUE, getFloor(9, floors));
    assertEquals(10, getFloor(10, floors));
    assertEquals(10, getFloor(99, floors));
    assertEquals(100, getFloor(100, floors));
    assertEquals(100, getFloor(999, floors));
    assertEquals(1000, getFloor(1000, floors));
    assertEquals(1000, getFloor(Integer.MAX_VALUE, floors));
}


I think there's no silver bullet for what you're trying to do.
To find the previous table,
it's necessary to go up the DOM tree until the first table,
and then from there find the previous table.

.closest("table") is optimal and necessary.

On the other hand, it's true that .prevAll("table").first() is a bit awkward.
Something like .closestPrevious("table") would be the best.
I searched around and couldn't find such.
So you're stuck with .prevAll("table").first().

In short, bloated it may be, I think it's the best possible way.


Scraping Clinical Studies database (via ClinicalTrials.Gov)

I hope I'm not too late.

There are a few things you could do :

Solution 1

import requests
from bs4 import BeautifulSoup
import pprint

def clinicalTrialsGov (nctid):
    data = BeautifulSoup(requests.get("https://clinicaltrials.gov/ct2/show/" + nctid + "?displayxml=true").text, "xml")
    subset = ['study_type', 'allocation', 'intervention_model', 'primary_purpose', 'masking', 'enrollment', 'official_title', 'condition', 'minimum_age', 'maximum_age', 'gender', 'healthy_volunteers', 'phase', 'primary_outcome', 'secondary_outcome', 'number_of_arms']
    tag_matches = data.find_all(subset)
    tag_dict = {'ct' + current_tag.name.capitalize(): current_tag.text for current_tag in tag_matches}
    tag_dict = multipleFields(data, 'intervention_name', tag_dict)
    tag_dict = multipleFields(data, 'intervention_type', tag_dict)
    tag_dict = multipleFields(data, 'arm_group_type', tag_dict)
    tag_dict['ctID'] = nctid
    return removeEmptyKeys(tag_dict)

def multipleFields (data, subset, tagDict):
    fields = data.find_all(subset)
    field = [each.text for each in fields]
    tagDict['ct' + subset.capitalize()] = ", ".join(field)
    return tagDict

def removeEmptyKeys (dict1):
    newDict = {k:v for (k, v) in dict1.items() if v}
    return newDict

pprint.pprint(clinicalTrialsGov("NCT01220960"))

I have used a dictionary comprehension to define tag_dict and newDict. This is similar to a list comprehension or a generator expression but specialized for dictionaries
I have removed the try … except from multipleFields because I don't see in which case an exception will be raised (especially since you didn't specify which one you were trying to catch)
I have presumed that subset in multipleFields() is a string and not a list of strings since you were looking only for one tag
I have used a list comprehension to define field in multipleFields()
I have used the pprint module to see better the answer.


"Tara's Beautiful Permutations" challenge

Well, the first and most obvious improvement is how you remove duplicates. Currently you iterate over all beautiful permutations (at least \$\mathcal{O}(n)\$) and for each check if it is already in the list (\$\mathcal{O}(n)\$ again). This is already \$\mathcal{O}(n^2)\$.

If you used a set instead, that in check would be \$\mathcal{O}(1)\$:

def print_beautiful_perms(arr, n):
    """
    Prints the number of beautiful permutations mod (10**9 + 7)

    arr: array of integers (not null)
    n: ?
    """
    permutations = set(map(tuple, get_beautiful_perms(arr, n)))
    print(len(permutations) % (10**9 + 7))

The map(tuple, ...) is needed because lists are not hashable in Python.

I also renamed your functions to adhere to PEP8, Python's official style-guide and reworked the docstring a bit to conform more to the conventions laid out in PEP257.

You should also put your main code under a if __name__ == "__main__" guard to allow importing your functions from another script without executing it:

if __name__ == "__main__":
    # main code - the problem states we'll receive this input:
    q = int(input())    # no of queries (arrays)

    for _ in range(q):
        n = int(input())    # no of elements in array
        arr = input().split()    # space separated array of n integers
        print_beautiful_perms(arr, n)

I also used _ as the unneeded loop variable, as is the convention.

I would also use try a different way to check if a permutation is beautiful and use itertools.permutations:

from itertools import permutations

def is_beautiful(arr):
    return all(x != y for x, y in zip(arr, arr[1:]))

def get_beautiful_perms(arr, arrlen):
    return filter(is_beautiful, permutations(arr))

Of course this also times out, because itertools.permutations is also \$\mathcal{O}(n!)\$.