Convert hex encoded string to byte array

One improvement is you can use the vectorized function substring rather than substr. This way, you can precompute all hexadecimal pairs and feed them directly into paste and as.numeric which are also vectorized. This removes the need for vapply (a disguised and slowish for loop).

You could also use paste0 as a shortcut for paste(, sep = ""). paste0 has been around for what seems like a couple years. If you are concerned about compatibility with older versions of R, then yes, it is safer to stick with paste.

I could be wrong but I see no reason not to output a vector of integers instead of numerics. That integers use less memory and are not subject to floating point errors are two strong reasons to prefer them over numerics.

It is also a good idea to add input checks to test your assumptions. Here it seems that the input must be a character vector of length 1.

This comment is more subjective. You have crammed a lot of operations into a single statement. I can count 8 functions including the anonymous one you created. That really makes your code hard to understand.

In all, I would have written the function like this:

as.byte.vector <- function(hex.string) {
   stopifnot(is.character(hex.string), length(hex.string) == 1L)
   start.idx <- seq(from = 1L, to = nchar(hex.string), by = 2L)
   end.idx <- start.idx + 1L
   hex.pairs <- substring(hex.string, start.idx, end.idx)
   prefixed.pairs <- paste0("0x", hex.pairs)
   as.integer(prefixed.pairs)
}

I hope you will agree that it is easier to read when the code is broken out this way, with each statement using a very few functions, and where the names of the variables holding intermediate results help understand the process.

This should already be faster than your version, thanks to the replacement of vapply. If speed is a real concern, you could make significant improvement by replacing substring with the following regular expression trick:

hex.pairs <- strsplit(gsub("(..)", "\\1 ", hex.string), " ")[[1]]

(We insert a space every two characters, then split on white space.)


Yes and no.

As you've used it here, I don't see a memory leak, so that would be a "no."

The function itself, however allocates memory without ever freeing it, so it's pretty much a memory leak waiting to happen -- the client code has to free the memory it allocates. Worse, freeing that memory is slightly non-trivial (two separate frees that have to happen in the right order) so it's not just a matter of whoever uses it remembering to free the memory, but there's also a possibility of them doing it wrong even if they do remember. Granted, it's not terribly complex either, but I'd still probably add a little function like:

void destroy_sent_packet(pack *p) {
    free(p->message);
    free(p);
}

So it's at least back to the client just remembering to free the memory.


Settings dialog, using information from its parent window

If the SettingsDialog can only take a MainWindow as a parent in the constructor then declare it to be so:

SettingsDialog::SettingsDialog(MainWindow *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{

As for getting the type indeed passing it in explicitly is better.

void MainWindow::on_actionSettings_triggered()
{
    SettingsDialog * settings = new SettingsDialog(this, deviceType);

    settings->exec();
}

My MainWindow popups a SettingsDialog. The setting dialog need to hide certain fields if the connected device is certain type.

void MainWindow::on_actionSettings_triggered()
{
    SettingsDialog * settings = new SettingsDialog(this);

    settings->exec();
}

Now in SettingsDialog:

SettingsDialog::SettingsDialog(MainWindow *parent, DeviceType deviceType) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);

    QSettings settings;

    if (deviceType == DEVICE_TYPE_B )
    {
        ui->comboBoxIP->setVisible( false );
    }
}


How to reformat this code so I don't use 'Exit Try' and 'Exit For'?

All of your Exit Try statements follow an error condition. So why not throw an exception with the message and display it in the Catch block instead? That's the purpose of the Try..Catch.

Also, to get rid of the Exit For, just reverse the conditional. As it is, those two statements will end the loop completely on the first empty row, not just skip it.

(Ideally, you'd want to create a custom Exception class and throw it instead of a generic Exception, but this is just to give you an idea.)

So you end up with something like this

tot = CInt(BonusDGV.Rows(0).Cells(0).Value)

'Business Rules Try/Catch block
Try
    'Ensure, for all rows, Fund amount totals 100 and Bonus Percentage is between 0-85%.
    For i As Integer = 0 To BonusDGV.Rows.Count - 1
        'don't count rows that contain no data
        If BonusDGV.Rows(i).Cells(0).Value IsNot Nothing Then
          fundTot = fundTot + CInt(BonusDGV.Rows(i).Cells(2).Value)
          If tot <> CInt(BonusDGV.Rows(i).Cells(0).Value) Then
            Throw New Exception("Percentage Must Be Between 0-85%.")
          End If
        End If
    Next
    'Bonus Percentage must be between 0-85% // \\ Double check
    If tot > 85 Or tot < 0 Then
      Throw New Exception("Percentage Must Be Between 0-85%.")
    ElseIf fundTot <> 100 Then
      Throw New Exception("Fund Total Must Add to 100%.")
      'Met all the business requirements, proceed to insert record
    Else
        For i As Integer = 0 To BonusDGV.Rows.Count - 1
          'Make sure there is actually data in the row
          If BonusDGV.Rows(i).Cells(0).Value IsNot Nothing Then
            cmd.Parameters("@BonusPct").Value = BonusDGV.Rows(i).Cells(0).Value
            cmd.Parameters("@FundID").Value = CInt(BonusDGV.Rows(i).Cells(1).Value)
            cmd.Parameters("@DefPct").Value = BonusDGV.Rows(i).Cells(2).Value
            cmd.Parameters("@ElectDT").Value = BonusDGV.Rows(i).Cells(3).Value
            'nonquery because we don't expect a return value
            cmd.ExecuteNonQuery()
          End If
        Next
    End If
Catch ex As Exception
    MessageBox.Show(ex.Message, "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
'dispose of the connection
conn.Close()


Object Oriented programming in lua in a functional fashion

Even though this kind of inheritance is perfectly valid example of OOP designing in language like Lua; it is considered a bad practice of programming.
According to Programming in Lua on Object-Oriented Programming.

This kind of function is almost what we call a method. However, the use of the global name Account inside the function is a bad programming practice.

This function will work only for this particular object.
Even for this particular object the function will work only as long as the object is stored in that particular global variable; if we change the name of this object, withdraw does not work any more.

The example they've used to depict is also quite to the point and small.
You should also take a look at how they've explained creation of classes; their inheritance; public, private and protected datatypes/variables and many other OOP concepts using metamethods and tables depending on their usage.
Here's the index of OOP concepts incorporated in Lua.
Useful Links

Object Orientation Tutorial
Inheritance Tutorial
Metamethods Tutorial


In this answer I explain in details why one should not throw System.Exception. You should be throwing InvalidOperationException in the case of the astronomically unlikely situation, and probably an ArgumentException in the case of the non-existing session.

As far as thread safety is concerned, I don't write multithreaded code very often so I might be completely wrong, but I since ConcurrentDictionary is a thread-safe IDictionary implementation, sessions.TryGetValue(id, out session) is already a thread-safe call, doesn't need to be wrapped in a lock block.


how to classify tweets in python based on handful of domains

I don't see your sentiment analysis code in your tweet_sentiment.py, so I will not comment on that.

And if I understand correctly, you are trying to build a classifier for text classification based on Twitter data.

So, depending on your data size, here are two things you could try.

Small data size (several tens of thousands or lower): Tdidf + Support Vector Machine, basically convert your text to a numerical vector form representing the existence of certain words along with their importance relative to the text and the whole dataset. Then feed the data into an SVM classifier, lots of tutorials are out there, and here is a good one.
Big data size (hundreds of thousands and more)(and ready to have fun): (word embedding Or one-hot encoding) + (CNN Or RNN)
, word embedding could represent the semantic similarity with others into a vector space model and have a dense representation, a good explanation could be found here. As for using CNN to do text classification you could refer to this and this Text understanding from scratch. and another one for RNN


I see a few small issues with the code:

Method names: particularly get is quite ambiguous, I'd use something more descriptive like 'get_element_data($element_name)' or something like that. As it is now it is obvious when used but it's not clear when looking just at the class itself.
Instead of  return (!empty($_GET)) ? true : false; you can actually use just return (!empty($_GET))
You don't need to break after return. Some might, however, argue that using it anyway is a good practice that prevents errors. So choose for yourself.

Other than that, I don't see any big problems with it.


Here's how Bjarne Stroustrup did it:

// random number generator from Stroustrup:
// http://www.stroustrup.com/C++11FAQ.html#std-random
int rand_int(int low, int high)
{
    static std::default_random_engine re {};
    using Dist = std::uniform_int_distribution<int>;
    static Dist uid {};
    return uid(re, Dist::param_type{low,high});
}

The principal difference is that the random engine re is static so there is only one initialization (and therefore seed).

Also note that a sample of 10 runs is too short to conclude much. Testing random number generators (RNGs) or psuedo-random number generators (PRNGs) is quite complex.  See http://csrc.nist.gov/groups/ST/toolkit/rng/index.html for a thorough explanation of the purpose, theory and actual source-code for tools to do a good job of testing PRNGs.


I have set up something very similar with a couple changes. In __contruct() I assign the credentials to variables, then call an instance to start the PDO connection. I also use try-catch for each PDO statement to make sure that I am not getting any errors.

private $_pdo = null;
private $_host, $_dbname, $_uname, $_pass;
private $_sql, $_result;
private $_preparedStmt;

public function __construct($host, $dbname, $username, $password) {
    // You could run checks here to make sure that...
    // no values or specific values are not equal to ''
    $this->_host = $host;
    $this->_dbname = $dbname;
    $this->_uname = $username;
    $this->_pass = $password;
    $this->startPDO();
}

// ... Later on in code, under Private functions comment tag
private function startPDO() {
    try {
        $this->_pdo = new PDO('mysql:host='.$this->_host.';dbname='.$this->_dbname, $this->_uname, $this->_pass);
        $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        //$this->handleFatalErr($e->getMessage(), 'connection'); // 'die' error handling
        //$this->handleErr($e->getMessage(), 'connection'); // Non-'die' error handling
    }
}

In each function I check the connection, I would recommend something similar. You could either kill the script if there is no connection or you could re-connect using the current variables $this->_host, etc:

public function query($sql) {
    $this->checkConnection();
    $this->_sql = $sql; // This is used for logging and for a getter function
    try {
        $this->_result = $this->_pdo->query($this->_sql);
    } catch (PDOException $e) {
        //$this->handleFatalErr($e->getMessage(), 'connection');
    }
}

private function checkConnection() {
    ($this->getPDO() === null) ? die('There is no connection to the database, please re-establish connection.') : NULL;
        //$this->handleFatalErr(self::ERR_CONNECTION_LOST, 'CONNECTION_LOST');
}

private function getPDO() {
    return $this->_pdo;
}

public function close() {
    (isset($this->_pdo) && $this->_pdo != null) ? $this->_pdo = null : NULL;
}


Converting double to string without scientific notation and without losing digits

I know, it's a challenge convert your big doubles to string, but if you can use decimal instead of double, the conversion could be smooth.

static void Main(string[] args)
{
    decimal d1 = 123456789012171.23m;
    decimal d2 = 0.0000000000000001m;
    decimal d3 = 10000000000000000m;

    Console.WriteLine(d1);
    Console.WriteLine(d2);
    Console.WriteLine(d3);
}


Optimize "nearest" Element query prototype

Question

"Is there a more efficient check for siblings that I am missing?"

As done in the example code you gave. No.
You can rewrite the code to remove some of the unneeded complexity. See rewrites at bottom of answer.
Bug
The line...
    const relative = parent.querySelector(selector);

...will throw if parent is null
Unsafe prototype extension
It is a bad idea to add to an existing prototype without precautions. Element.prototype.nearest may not be used at the moment, but at any time it could be added to the DOM, breaking any code that you use it in.
There are three ways to avoid conflicts/future proof prototype extensions.
.1 100% safe. Don't!!! extending the prototype is an open trap ready to bite at any moment.
.2 Almost safe. Use a non standard naming convention eg Element.prototype.select_nearest The standard will not use this name, but this does not mean it is 100% safe as anyone else may use the name.
.3 Safe but awkward. Use a Symbol to define the prototype name. This will guarantee the uniqueness of the name. Unfortunately it does mean you will need to use bracket[notation] to access the property and share that property with code that needs access. For example
// define
const nearest = Symbol("nearest");
Element.prototype[nearest] = function() { /* ... code ... */ }   // prototype is global

// call
btn[nearest](".child");

To give access to the symbol in global scope use Symbol.for

{   // scope block
    const nearest = Symbol.for("nearest");  // find or create
    Element.prototype[nearest] = function() { log("Nearest") }  // prototype is global
}

// Access in unconnected scope
{
    Symbol.for("nearest")
    btn[nearest](".child");

    // or
    btn[Symbol.for("nearest")](".child");
}

Style
A note on style.
Its a bad habit not to delimit code blocks with {} eg if (prev?.matches(selector)) return prev; is safer as if (prev?.matches(selector)) { return prev; }
Unbound function?
Why add to the element prototype a function that calls an unbound arrow function. This just makes the code unduly complex.
You could either call the function nearest directly eg nearest(btn, '.child'); or keep it on the prototype and avoiding the secondary call and the need to pass this See rewrites.
Rewrite
Several rewrites as examples, though apart from the bugs and the points outlined above I don't see any real need for a rewrite.
As prototype
const nearest = Symbol.for("nearest");
Element.prototype[nearest] = function(selector) {
    const prev = this.previousElementSibling;
    if (prev?.matches(selector)) { return prev }
    const next = this.nextElementSibling;
    if (next?.matches(selector)) { return next }
    const parent = this.parentElement;
    if (parent) {
        if (parent.matches(selector)) { return parent }
        return  parent.querySelector(selector) ?? parent[nearest](selector);
    }
}

As function

function nearest(self, sel) {
    const prev = self.previousElementSibling;
    if (prev?.matches(sel)) { return prev }
    const next = self.nextElementSibling;
    if (next?.matches(sel)) { return next }
    const parent = self.parentElement;
    if (parent) {
        if (parent.matches(sel)) { return parent }
        return  parent.querySelector(sel) ?? parent.nearest(parent, sel);
    }
}

or
const matches = (el, sel) => el && el.matches(sel) ? el : undefined;
function nearest(self, sel) {
    const parent = self.parentElement;
    const sibling = matches(self.previousElementSibling, sel) ??
        matches(self.nextElementSibling, sel) ??
        matches(parent, sel) ??
        parent?.querySelector(selector) ??
        parent?.nearest(parent, selector);
}


Not sure if I get the problem, but one solution for reconstructing the original list (even 3.000.000 items) with a dictionary is:

public static void ReconstructList(List<PairInt> pairs)
{
    var leftRightDict = pairs.ToDictionary(p => p.Left, p => p.Rght);
    var idx = 0;
    while (leftRightDict.TryGetValue(idx, out idx))
        Console.WriteLine(idx);
}

Update:

The following code gets the ID of the left-most men:

public static void ReconstructList(List<PairInt> pairs)
{
    var rightLefttDict = pairs.ToDictionary(p => p.Rght, p => p.Left);
    // just start with any men
    var right = pairs[0].Rght;
    while (rightLefttDict.TryGetValue(right, out right)) {}
    Console.WriteLine(right);
}


Python Boto Script - Sorting based on date

The names will properly compare lexically even without converting them to datetimes, and you can just use the max function:

from boto.s3.connection import S3Connection
from boto.s3.key import Key

conn = S3Connection(XXX, YYY)
bucket = conn.get_bucket('bucketname')
rs = bucket.list("FamilyPhotos")
latest = max(rs, key=lambda k: k.name)
latest.get_contents_to_filename()


Factorial number in Rust for learning purposes

Bugs and types

You should think some about what types you want to have as input and output for factorial. Negative numbers won't ever work as input, and the output won't be negative, so you should consider using an unsigned integer, like u64. Even doing this, though, there's one input that leads to an infinite loop. See if you can find it and fix the function!

Cleaning up the error handling

match io::stdin().read_line(&mut user_input) {
    Ok(_) => (),
    Err(_e) => {
        println!("error: {}", _e);
        continue;
    }
};

A variable with a leading underscore tells readers (and linters) that the variable isn't going to be used. Since we use it (with the println!), we should just call it e.

This error message should probably be in stderr, rather than stdout. This can be done just by changing it to eprintln! instead.

When only one branch of a match actually does something, if let is both easier to write and understand. So in all, I'd change this part to

if let Err(e) = io::stdin().read_line(&mut user_input) {
    eprintln!("error: {}", e);
    continue;
}

let num: i64 = match user_input.trim().parse::<i64>() {
    Ok(n) => n,
    Err(_e) => {
        trim_newline(&mut user_input); // remove trailing newline
        println!("'{}' is not a valid number, full error: {}", user_input, _e);
        continue;
    },
};

Same thing with _e vs e. You're using the variable, so it shouldn't start with an underscore. Also the same thing with eprintln!. Errors should be printed to stderr.

Since both branches of the match are used, if let is less useful. However, you might check out the answers to this question for some ideas for making this look better. For a single use like this, you're probably fine, but if you do this "unwrap or continue" behavior a lot, it can help to encapsulate it.

The i64 annotations are unnecessary. The compiler has enough information to conclude that the type of num is i64 since it's fed into factorial. If you want to keep an annotation for explicitness, that's fine, but only one of num: i64 and parse::<i64> is needed for that.

trim_newline seems to be unnecessary. You're parsing user_input.trim() anyway, so just show that to the user if there's a parsing error.

let num = match user_input.trim().parse() {
    Ok(n) => n,
    Err(e) => {
        eprintln!("'{}' is not a valid number, full error: {}", user_input.trim(), e);
        continue;
    }
};

Using standard tools for formatting and linting

One thing that goes a long way with making your code more readable and idiomatic is running cargo fmt. You may need to install it with rustup component add rustfmt.

Clippy is another standard tool for catching errors and making your code more idiomatic. It can similarly be installed with rustup using rustup component add clippy. Running it (with cargo clippy) on your program, we get the warning

warning: unneeded `return` statement
 --> src/main.rs:4:5
  |
4 | /     return if num == 1 {
5 | |         1
6 | |     }else{
7 | |         num * factorial(num - 1)
8 | |     }
  | |_____^
  |
  = note: `#[warn(clippy::needless_return)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_return
help: remove `return`
  |
4 |     if num == 1 {
5 |         1
6 |     }else{
7 |         num * factorial(num - 1)
8 |     }
  |

Since the return statement is the last thing in the function, it's not needed since the last expression in the block is always implicitly returned. You can simply remove the return.

Some advice on overflows

The factorial function grows superexponentially, so any fixed-width integer type is going to quickly overflow. Even switching to u128 only gets you up to an input of 34. The way I see it, you have two choices. Either

Embrace this. Return an Option (or better yet, a Result) to indicate that an overflow occurred. Using something like u64::checked_mul would be helpful for that.
Avoid overflow completely (barring memory limits) by using some sort of BigInt. The crate num_bigint has an implementation with everything you'd need here, including parsing, printing, multiplying and subtracting. You should be able to replace i64 with BigUint (or BigInt) with only a few conversions from integer literals.


There's a much easier approach to this problem.

We can use NSCalendar's nextDateAfterDate:matchingComponents:options: method to find both our next 7am and 7pm.  Then it's simply a matter of comparing these values and returning the lesser of the two.

NSDate * nextSevenOClock() {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];

    components.hour = 7;
    NSDate *nextSevenAm = [calendar nextDateAfterDate:[NSDate date]
                                   matchingComponents:components
                                              options:NSCalendarMatchNextTimePreservingSmallerUnits];

    components.hour = 19;
    NSDate *nextSevenPm = [calendar nextDateAfterDate:[NSDate date]
                                   matchingComponents:components
                                              options:NSCalendarMatchNextTimePreservingSmallerUnits];

    NSDate *nextSeven = nextSevenAm;
    if ([nextSeven compare:nextSevenPm] == NSOrderedDescending) {
        nextSeven = nextSevenPm;
    }

    return nextSeven;
}

Importantly, this approach with account correctly for things like daylight savings time and leap seconds, which the original solution does not.

This method is very specific however.  It would be good if we could get a bit more utility out of it.  And rather than a simple C-style function, I've expanded it properly into an NSDate category.

@implementation NSDate (NextTimeStamp)

+ (instancetype)nextTimeStampMatchingHour:(NSUInteger)hour {
    return [self nextTimeStampMatchingHour:hour minute:0 second:0];
}

+ (instancetype)nextTimeStampMatchingHour:(NSUInteger)hour minute:(NSUInteger)minute {
    return [self nextTimeStampMatchingHour:hour minute:minute second:0];
}

+ (instancetype)nextTimeStampMatchingHour:(NSUInteger)hour minute:(NSUInteger)minute second:(NSUInteger)second {
    NSUInteger morningHour = hour % 12;
    NSUInteger eveningHour = morningHour + 12;

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];

    components.minute = minute;
    components.second = second;

    components.hour = morningHour;
    NSDate *nextAM = [calendar nextDateAfterDate:[NSDate date]
                              matchingComponents:components
                                         options:NSCalendarMatchNextTimePreservingSmallerUnits];

    components.hour = eveningHour;
    NSDate *nextPM = [calendar nextDateAfterDate:[NSDate date]
                              matchingComponents:components
                                         options:NSCalendarMatchNextTimePreservingSmallerUnits];

    return [nextAM compare:nextPM] == NSOrderedAscending ? nextAM : nextPM;
}

@end

For your original exxample of looking for the next 7 o'Clock, we can just do simply:

NSDate *nextSeven = [NSDate nextTimeStampMatchingHour:7];

But with these extra methods, we can look for more specific times:

NSDate *nextSevenFifteen = [NSDate nextTimeStampMatchingHour:7
                                                      minute:15];


TCPListener server to discover clients on a network

I would consider altering member x.ActiveConnections for the reasons I mention on the answer here: Create database connection and run the insert, delete, update queries class

Basically, consumers of your class can actually modify the ActiveConnections list (call .Remove, etc.), so you should find a way to eliminate that.

In F#, I would probably do the following:

member x.ActiveConnections = activeConnections.ToArray()

Or as Dan Lyons stated in comments:

member x.ActiveConnections = activeConnections.AsReadOnly()

This guarantees that you are exposing a non-modifiable copy of the list to the consumer of your class. You could optionally open System.Linq and use:

member x.ActiveConnections = activeConnections.ToArray().AsEnumerable()

Both of these have the same effect: the internal List<T> isn't able to be modified.

I also noticed you use x. as the prefix for all your member declarations, I'm not sure what the standard is (quick google pulled nothing) but I always try to use member this.Name for public-facing members, to remind myself that they're part of the same object. (F# doesn't seem to care much, but it still feels right.)


Perhaps:

def towerGreedImproved(bricks, numberTowers):
    # First we sort the number of bricks from greatest to smallest
    obricks = list(bricks)
    obricks.sort(reverse = True)

    # Only runs the algorithm if we have more bricks than towers to build
    if len(obricks) < numberTowers:
        return obricks

    towers = tuple([] for i in range(numberTowers))  # Empty vector ([],[],...)
    height = [0] * numberTowers  # Zero vector [0,0,...]
    avgHeight = sum(obricks)/numberTowers

    """ Loops through each tower, adds elements until that tower is just
        below the average tower height """
    for j in range(numberTowers):
        while height[0] + obricks[0] < avgHeight:
            # Deletes used bricks
            brick = obricks.pop(0)
            towers[j].append(brick)
            height[j] += brick

    for n in obricks:
        lowest = min(enumerate(height), key = lambda kv: kv[1])[0]
        towers[lowest].append(n)
        height[lowest] += n

    return towers

bricks = (8, 8, 8, 6, 6, 4, 4, 4, 4, 3, 3, 2)
print(towerGreedImproved(bricks, 5))

Of note:

Python variable names should be lowercase
It's not playing nice to chew up someone's input list - make a copy
towers can be a tuple because we don't expect the contents to change
you should do something more reasonable on brick shortage, like return the brick list
range doesn't need a first argument of 0
use pop() to both get and delete an element
use += for addition and assignment
use enumerate with min so that you can get the min's index in one shot
don't automatically print the result on the inside of the function; let the user decide


A clean tacit version of (n choose k) in J

Your initial verb is a good start. Your code could be shortened to 24 bytes

~.@(/:~@:{"1~i.)~!A.&i.]

A shorter version for 22 bytes can be found by permuting the binary string with k 1's.

[:I.@~.i.@!@]A.]{.1#~[

These are both O(n!) for C(n, k).


An efficient way to order content in controller [Spring Boot]

Well, you found a workable solution.
One thing that strikes out at me is, that you expose the inner structure of your
ContentOrderMap by accessing orderMap.categoriesByOrderType.get(categoriesOrderType) directly.
The inner map categoriesByOrderType is an implementation detail, which you should not make
known in the public interface. Rather give ContentOrderMap a direct method which returns the page (and while we are at it: change the name, as nobody should care about the class being or containing a map.)
A problem remains, which is: changes will not be local at one place. When you add a new OrderType,
you have to extend the OrderType enum and the ContentOrderMap and the CategoryRepository.
Frankly, you'll not find a way to solve this problem in a 100% clean way, as it concerns the interface
(i.e. the REST service), and the database, so if you assemble your actual definition of a type and
the data storage effect it has in one place, you will have mixed responsibilities in that place.
However, if you think this mixing of responsibilities is bearable (everything is a tradeoff in software
engineering ;-)) you might think about harnessing the power of the java enum, which can implement an
interface. Something along the lines of:
public enum OrderType {
    DEFAULT("select c.* from whatever order by whatever"),
    POST_COUNT_DESC("select c.* from whatever order by something else"),
    ....;

    private final String query;

    private OrderType(String query) {
        this.query = query;
    }

    public String getQuery() {
        return query;
    }
}

This way, you only have to extend the enum, pass the constant on into your repository, and then do
whatever you need to do with the contained query.
Another alternative is, using your container. I'm not using spring, but there must be something along
the lines of a CDI Instance<>, which gives you a list of all implementations of a given interface.
In a CDI world, you could declare an interface:
public interface OrderHandler {
    public boolean handlesType(String orderType); // no enum, in the end REST sends you a string anyway
    public Page<Category> getResult(Pageable pageable);
}

Then write your different implementations of these interfaces, and get all of them via:
@Inject
Instance<OrderHandler> orderHandlers;

...

for (OrderHandler orderHandler : orderHandlers) {
    if (orderHandler.handlesType(myParameter)) {
        orderHandler.getResult(...);
    }
}

As I said, there must be something equivalent in spring.


Creating and sending two kinds of notification messages

You could split the two decisions, for instance:

# Outside your method
EVENT_TO_USERKIND = { pending: 'shopper', handed_over: :'deliverer' }

# Now inside your method
user_kind = EVENT_TO_UID_METHOD[parse_events]
if user_kind && send_push_notification(order.send("#{user_kind}_id"), order, parse_events)
  order.send("#{user_kind}_notified_at=", now)
end

It's more compact and concise, but the usage of send might be considered ugly, and it depends on naming convention (do not dare to rename deliverer_notified_at to delivery_guy_notified_at!), so you have to choose whether or not you like it.


Naming

The meaning of some identifier names is hard to grasp:

What does Point_Dng stand for? Why not simply Point?
What is point_piece in the inner loop, and how is it different from
piece from the outer loop?
set is too generic, what does it contain?
ans stands for “answer,” but actually contains the “minimal area” found so far.

Simplifications

As of Swift 4.2, the compiler automatically creates the required methods
for Equatable and Hashable conformance for a struct if all its member
are Equatable/Hashable.

A struct also has a default memberwise initializer if you don't define your
own.

The properties of a point are never mutated, so they can be declared as constants  (with let).

This makes the struct Point as simple as

struct Point: Hashable {
    let x: Int
    let y: Int
}

The closure in

let points_new = points.map({ (point: [Int]) -> Point_Dng in
    return Point_Dng(point[0], point[1])
})

can be simplified because the compiler can infer the argument type and the
return type automatically. Since the array is only needed for creating the
set, the assignments can be combined into one:

let pointSet = Set(points.map { point in Point(x: point[0], y: point[1]) })

Performance improvements

In the nested loop it suffices to consider only those pairs where one point
is the “lower left” and the other the “upper right” corner of a potential
rectangle. That reduces the number of tests, and makes the abs() call
redundant.

Putting it together

The following version was roughly twice as fast in my tests with
random arrays of 500 points (on a 3.5 GHz Intel Core i5 iMac, compiled
in Release mode, i.e. with optimizations):

class Solution {
    struct Point: Hashable {
        let x: Int
        let y: Int
    }

    func minAreaRect(_ points: [[Int]]) -> Int {
        let pointSet = Set(points.map { point in Point(x: point[0], y: point[1]) })

        var minArea = Int.max
        for lowerLeft in points {
            for upperRight in points {
                if upperRight[0] > lowerLeft[0]
                    && upperRight[1] > lowerLeft[1]
                    && pointSet.contains(Point(x: lowerLeft[0], y: upperRight[1]))
                    && pointSet.contains(Point(x: upperRight[0], y: lowerLeft[1])) {

                    let area = (upperRight[0] - lowerLeft[0]) * (upperRight[1] - lowerLeft[1])
                    minArea = min(minArea, area)
                }
            }
        }

        return minArea == Int.max ? 0 : minArea
    }
}

Further suggestions

Sorting the point array in increasing order of x-coordinates would allow to
find “lower left/upper right” pairs faster, potentially increasing the
performance.


Optimizing variadic template pack subsequence matching algorithm

I'm going to throw out a fairly complicated solution here by breaking the problem into lots of smaller parts. The end result is that the compilation of the following:

using T = typelist<int, char, int, int, char, int, double, int, char,
                   int, char, int, int, char, int, double, int, char,
                   int, char, int, int, char, int, double, int, char,
                   int, char, int, int, char, int, double, int, char>;

static_assert(std::is_same<
    matches<T, typelist<int, char>>,
    intlist<0, 3, 7, 9, 12, 16, 18, 21, 25, 27, 30, 34>
    >::value, "!");

is still almost instantaneous.

The algorithm is actually going to come from an idea in Python's itertools. What we want to do is walk our typelist N at a time (where N is the match length), and just use std::is_same to compare. That is, taking the original problem's list:

using SRC = typelist<int, char, int, int, char, int, double, int, char>;

we want to turn it into something that looks like:

using X = typelist<typelist<int, char>,
                   typelist<char, int>,
                   typelist<int, int>,
                   ...
                   >;

And then pass that into a metafunction taking an appropriate typelist<Ts...> and std::index_sequence<Is...> do:

using type = concat<
    std::conditional_t<std::is_same<T, SUB>::value,
        typelist<std::integral_constant<std::size_t, Idx>>,
        typelist<>
        >...>;

That's the basic idea anyway. Plus, the smaller pieces are probably going to be useful in other contexts.

The Small Algorithms

These are very straightforward and I will omit them here for brevity: head, tail, size, concat (variadic!), any_of, and is_empty.

take_by

To generate the X typelist above, we need something like:

template <typename TL, int I>
using take_by = ???

The implementation of this is to make a typelist that is I copies of TL, each one dropping a steadily larger prefix off the top. Once we have that, we need to zip all the iterators together. So really, I need to start with the smaller pieces...

skip_n

Given a typelist, basically just call tail n times:

template <typename TL, int I>
struct skip_n_impl : skip_n_impl<tail<TL>, I-1> { };

template <typename TL>
struct skip_n_impl<TL, 0> {
    using type = TL;
};

template <typename TL, int I>
using skip_n = typename skip_n_impl<TL, I>::type;

There may be a better way to do this, but I'm not sure. So, skip_n<typelist<int, char, double>, 2> is typelist<double>.

zip

This is the tricky part. Basically, we have a list of lists of types. If any of those typelists is empty, we're done. Otherwise, we concat all the heads with a recursive call against all the tails. We can't use std::conditional_t here due to eager evaluation of both parts, so I'm introducing two different impl types:

template <typename TL>
struct zip_impl;

template <typename TL, bool done>
struct zip_impl2;

template <typename TL>
struct zip_impl2<TL, true> {
    using type = typelist<>;
};

template <typename... Ts>
struct zip_impl2<typelist<Ts...>, false> {
    using type = concat<typelist<typelist<head<Ts>...>>,
                        typename zip_impl<typelist<tail<Ts>...>>::type
                        >;
};

template <typename... Ts>
struct zip_impl<typelist<Ts...>>
    : zip_impl2<typelist<Ts...>, any_of<is_empty<Ts>::value...>::value>
{ };

template <typename T>
using zip = typename zip_impl<T>::type;

This gives us the pieces to get back to take_by:

template <typename TL, int I, typename = std::make_index_sequence<I>>
struct take_by_impl;

template <typename TL, int I, std::size_t... Idx>
struct take_by_impl<TL, I, std::index_sequence<Idx...>>
{
    using iters = typelist<skip_n<TL, Idx>...>;
    using type = zip<iters>;
};

template <typename TL, int I>
using take_by = typename take_by_impl<TL, I>::type;

Hopefully that makes sense. First, we built up our "iterators" - which are all offset by one from each other. Then we just zip them up. Now we have the X, and all we need is:

**matches**:

template <typename SRC, typename SUB>
struct matches_impl
{
    template <typename TL, typename = std::make_index_sequence<size<TL>::value>>
    struct impl;

    template <typename... T, std::size_t... Idx>
    struct impl<typelist<T...>, std::index_sequence<Idx...>>
    {
        using type = concat<
            std::conditional_t<std::is_same<T, SUB>::value,
                typelist<std::integral_constant<std::size_t, Idx>>,
                typelist<>
                >...>;
    };

    using type = typename impl<take_by<SRC, size<SUB>::value>>::type;
};

template <typename SRC, typename SUB>
using matches = typename matches_impl<SRC, SUB>::type;

Basically, we end up creating a meta-list internally that would look like:

intlist<0>,
typelist<>,
typelist<>,
intlist<3>,
typelist<>,
...

But concat will drop the empties, so when that gets combined, we get what we wanted - intlist<0, 3, 7>.


Looks good to me.

Ship it.

(Consider using flake8, and burying the last four lines within if __name__ == '__main__':.)


Euler's Totient Function in x86 assembly (MASM)

You're not using cdq properly.  cdq sign extends EAX into EDX usually in preparation for an idiv (signed division) instruction.  However, you're using div (unsigned division), so instead of using cdq (which can potentially fill EDX with 0xFFFFFFFF), you should zero out that register instead.  If you were doing an idiv, though, the cdq is in the wrong place since it needs to come after loading data into EAX.  And there are a couple of places where you already know that EDX will be 0 so you don't need the instruction at all.

In place of cmp edx,0, you can use test edx,edx.  It sets the zero and sign flags the same way but does so with a smaller instruction.

Your L2 loop can be shortened a bit.  If EDX is zero (no remainder after the division), you already know that EDX is zero, so you don't need to zero it out, and that x is already in EAX.  So you can loop back to the div instruction.


Passing some redundant parameters to an interface vs creating a new request object every time for the interface

Since what you want is a total transparency on how you access the propertyA then solution 1 seems better. Because with solution 2 you have to change the request object.

You should clearly identify your parameters. Some may be changing the output that is needed, other may be more related to the underlying service and can be "defaulted" into the dedicated proxy. At the end if you still have some unused parameters, this is acceptbale until the response is still correct.

It is not because the serviceB has a functionnality (param3) that you are obliged to use it. Your services should have a common behavior if you want to exchange them without any impacts.


Including references in onResume Lifecycle

You could use a loop to reduce the duplication:

List<String> extensions = Arrays.asList(
    "ve",
    "ev",
    "we",
    "wef"
    // ...
);
for (String ext : extensions) {
    intentFilter.addAction("tv.apps.v4." + ext);
}

But actually, it would be better to move hardcoded strings outside of java code.
You could create a res/values/arrays.xml file like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="actions">
        <item>tv.apps.v4.ve</item>
        <item>tv.apps.v4.ev</item>
        <item>tv.apps.v4.we</item>
        <!--
        <item>...</item>
        -->
    </string-array>
</resources>

And use it in the code like this:

for (String action : getResources().getStringArray(R.array.actions)) {
    intentFilter.addAction(action);
}

Does this work as intended?

Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1);

I don't know about this particular usage,
but I do know that low level thread operations are not recommended in Android development in general.

Unless this usage is explicitly mentioned somewhere in the official guides,
I'm not sure if this will work reliably at all.


Processing file inclusion directives using mutual recursion

parseContent() calls both re.finditer() and re.sub(), which is inefficient, because the re.sub() has to find the insertion point that re.finditer() had already found. What you want is just re.sub():

  repl can be a string or a function… If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

Going further, you should make just one substitution pass that handles both comments and includes. (You didn't show us the removeComments() code, so you'll have to adapt the regex yourself.)

The double-quotes in the regex have no special significance, and do not need to be escaped with backslashes. Also, the dot and the underscore characters do not need to be escaped within a character class.

DIRECTIVE_RE = re.compile(r'(?P<comment>#.*)|(?P<include>(\s)*include+(\s*)"(\s*)(?P<file>[a-zA-Z0-9._/]*)")')

def process_content(self, rdb_file_path, content):
    def directive_handler(match):
        if match.group('comment'):
            return ''
        elif match.group('include'):
            path = os.path.join(rdb_file_path, match.group('file'))
            with open(path) as f:
                return self.process_content(rdb_file_path, f.read())
    return DIRECTIVE_RE.sub(directive_handler, content)

open() should almost always be called using a with block to ensure that the filehandle gets closed automatically.

Note that I have used os.path.join() as a portable alternative to + "/" +.


Retry a Promise resolution N times, with a delay between the attempts

Call stack / Job queue / Event queue

Calling an async function does not use the call stack in the way you may be used to.

Rather the async call remains on the call stack only until an await is encountered. Then the call is removed from the call stack and the await (a micro task (I think it is called)) is placed in the job queue (new to ES6). Micro tasks are very similar to the events but have higher priority (micro tasks will be executed before events)

That means that async functions can not overflow the call stack if you call it recursively as long as there is an await before the recursion.

Awaiting the recursion call will not work as the code to the right of await is executed before the current context is removed from the call stack.

The following JS example shows a recursive count down from 1billion (it will take some time but will not throw a call stack overflow)

Eg

async function recursive(c = 1e9) { // 1 billion
    if (c > 0) {
        await Promise.resolve(); // removes call recursive from call stack
                                 // adds this micro task to the job queue
                                 // Execution is idle and thus the micro task
                                 // is removed from the queue and next line is
                                 // executed
        return recursive(c - 1);
    }
    return c;
}
recursive().then(console.log); // will in time display 0

Recursion

There is no danger in using a recursive and less complex style for your solution. The example below outlines the principle in JS (I am too lazy to type typescript)

const MAX_TRYS = 10; TRY_TIMEOUT = 500;
function toTry() {
    return new Promise((ok, fail) => {
        setTimeout(() => Math.random() < 0.05 ? ok("OK!") : fail("Error"), TRY_TIMEOUT);
    });
}
async function tryNTimes(toTry, count = MAX_TRYS) {
    if (count > 0) {
        const result = await toTry().catch(e => e);
        if (result === "Error") { return await tryNTimes(toTry, count - 1) }
        return result
    }
    return `Tried ${MAX_TRYS} times and failed`;
}

tryNTimes(toTry).then(console.log);

Promise resolve/reject are micro tasks

I will point out that even if you used just plain old promises rather than a async function the result is the same. A promise adds a micro task to the job queue and will not resolve or reject until the current call stack is empty.

It is therefor safe to recursively call the calling function from the resolved/rejected promise.


Manage Case Statement with (Int, long, short, double.....)

For value types (i.e. all your types except String) you can use the Convert.ChangeType method:

list.Add(Convert.ChangeType(c.Text, theType))


Is there any problem in checking PHP PDO connection this manner?

I'm not quite sure I see the purpose of this function.

It essentially checks if a PDO connection is possible.  It does not actually return a connection.  In addition to that, it has hard coded credentials, thus killing all flexibility.  Also, there's no evident reason why you made it MySQL specific.  None of your options used are MySQL specific.

Since a boolean is returned, if( $pdo_mysql = pdo_mysql() ) is redundant too:

if (pdo_mysql()) is sufficient (unless you plan on using the true/false $pdo_mysql outside of the if/else block).

You should pass the credentials into the function instead of hard coding them.  Once you've done that though, you've kind of removed any need for the function.

Personally, I don't see a purpose for this function.  Just make the connection without this function.  If you want to keep it in some kind of centralized place, just keep in it a simple bootstrap file, or even a simple bootstrapping class.

I've been vague on basically everything in this post, so if you want more detail, let me know :).

Also, I might have missed the point of your function.  Is your end goal to connect to a MySQL server, or to check if you could connect to a MySQL server?


Checking if a number is power of 2 or not

There's actually a bit hack for this :

private static boolean isPowerOfTwo(int number) {

    return number > 0 && ((number & (number - 1)) == 0);

}

(ref : Bit Twiddling hacks)

This exploits the fact, that in binary notation a power of two is a 1 followed by a number of 0's, and the number just below is all 1's equal to that number of 0's :

  100000000 // number
& 011111111 // number - 1
-----------
  000000000


Simple join between 2 tables with unusual structure

You should probably fire the Database Admin.

But seriously, a problem in your query arises if you have duplicate, but different (bank_id + branch_id)'s. For example, (22 + 202) and (2 + 2202) both equal the same thing.

Change your query to include the space, instead of replacing it on both sides.

Here's a SQL Fiddle demonstrating the issue:
http://sqlfiddle.com/#!18/3a6b9/2

Example query to match exactly, don't remove the spaces (Note won't work on SQL fiddle as I used different lengths for the colunmns):

SELECT BANK_ID, BRANCH_ID, ACCOUNT_NUM, CURRENCY, AMOUNT
FROM [ACCOUNTS]
  JOIN  [AMOUNTS]
  ON (
    CAST(
         CAST  ([BANK_ID] as  nchar(2)) + ' '
       + CAST  ([BRANCH_ID] as  nchar(3)) + ' '
       + CAST  ([ACCOUNT_NUM] as  nchar(4))
        AS varchar(255)
        )
         LIKE
        CAST ([AMOUNTS].[ACCOUNT_REC] AS varchar(255))
     )

Update, since you mentioned more about your schema:

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=f8c037b9cc9afc2e2de850011031020d

SELECT  * FROM ACCOUNTS JOIN AMOUNTS ON (
         CONCAT(CONVERT(VARCHAR(255), [BANK_ID]), ' ')
       + CONCAT(CONVERT(VARCHAR(255), [BRANCH_ID]), ' ')
       + CONVERT(VARCHAR(255), [ACCOUNT_NUM])
       ) LIKE ([AMOUNTS].[ACCOUNT_REC] )


The solution looks near optimal to me. If performance is an issue I would suggest the two following minor modifications:

The cleaning of the string regarding the special characters (&nbsp; and &#160;) is done at every calling level. You could introduce a third template called CamelCaseRecursive which would look like CamelCase but it would not contain the cleaning methods. So, CamelCase would be official external interface which would call CamelCaseRecursive which would call itself recursively. This change may save the more time the more words a text has on the average.
In CamelCaseWord you could contract the two <xsl:value-of> tags into one by using the concat() function:

<xsl:value-of
    select="concat(translate(substring($text,1,1),
                             'abcdefghijklmnopqrstuvwxyz',
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
                   ' ',
                   translate(substring($text,2,string-length($text)-1),
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                             'abcdefghijklmnopqrstuvwxyz')
                   )" />

I would assume that the performance gains will be minimal with today's highly optimized XSLT processors. However, if this actually helps it would be great to learn about it!


What is the exception you are getting?  What do you mean returns null and throws Exception?

From putting this code into a class and executing a test on it, I get back an object or null when the record exists or does not respectively.

If you're getting an exception from the above call with cmf.GetByPrimaryKey, is the exception in the call to the constructor of CategorymasterKeys?

Here is the test I used:

[TestMethod()]
public void TestWhenPassingAnIdNotInTheResultSetToSelectByPrimaryKey_ThenNullIsTheResult()
{
    var target = new Class2();
    CategorymasterKeys keys = new CategorymasterKeys { Category_id = 0 };
    Categorymaster actual = target.SelectByPrimaryKey(keys);
    Assert.IsNull(actual);
}


Basic structure for interactive single window application

The code looks decent enough.  I'd like to point out three issues, though, all related to timing/multi-threading.

GUI → EDT

All GUI operations should happen on the Event Dispatch Thread.  Java boots into the Main thread, which is different from the EDT.  Your Controller.getInstance() should be called on the EDT:

EventQueue.invokeLater(Controller::getInstance)

Controller.instance should be guarded

Currently, the instance if filled in via the Main thread.  If the GUI (on the EDT or through the timer) later requests the instance, there is no guarantee they will see it, or they might see it in an inconsistent/incomplete state.

This can be solved by either making instance volatile or, perhaps better, making getInstance() a synchronized method.

repaint() is on a best-effort basis

It looks like this is the basis for a game or other graphically heavy application (judging from FPS).  Swing (and its timers) may not give you the timing guarantees you'd need for things like game logic.

Consider using a game loop with a Canvas and a BufferStrategy, disabling redraw requests, and taking over from there.

Isn't the Timer good enough?  I'm tempted to say, yes, it might be good enough, if the game logic is simple and not intense.  Though you're no longer blocking the EDT with Thread.sleep (big win), the actions that the timer calls are still executed on the EDT.  This makes handling GUI elements and fields much simpler (no sync needed), but heavier stuff may result in jitter.  Worse: heavy stuff on the EDT may make your game loop jitter.

In short: the timer is simpler and probably good enough.  The game loop in a separate thread (say, your main thread) is more heavyweight but also more reliable and more likely to benefit from hardware acceleration.

Nitpicking

Controller.getInstance seems like an odd method to call from main to kick things off.  Maybe make it Controller.run() or Controller.getInstance().run() or some such that would better imply the side effect of running your program.
getPreferredSize returns a mutable final variable (Dimension is mutable).  Perhaps you could try this:

public Dimension getPreferredSize() {
    return isPreferredSizeSet() ? super.getPreferredSize() : new Dimension(DIMENSION);
}


Loading div sections from separate files

ngView

First of all you described ngView from angularjs

It is what it does. It just helps to organize routing code and template loading. In next section I'll show samples from my current self-learning project.

If you need strict jQuery solution, place appropriate comment.

Angular solution

Make navigation bar with virtual links and place ng-view attribute into container div.

  About
  Help
  Contact

Mark html tag with ng-app attribute and value of you app name

Load js at end of body. You can use cdn for angular libraries. app.js is your application source file.

Your app.js contains main routes

(function() {
  'use strict';
  angular.module('my_app_name', ['ngRoute'])
  .config([
    '$routeProvider', function($routeProvider) {
      $routeProvider.when('/about', {
        templateUrl: 'templates/about.html'
      });
      $routeProvider.when('/help', {
        templateUrl: 'templates/help.html'
      });
      $routeProvider.when('/contact', {
        templateUrl: 'templates/contact.html'
      });
    }
  ]);
}).call(this);

After that you will gen fast, scalable template rendering. Also you can read angular docs for more features.

jQuery solution

IMHO: there is no common solution, but some practices can be applied.

e.g. making configuration array for repeated code.

var navbar_selector = '#navbar',
    target_selector = '#target',
    nav_config = [
        {"id": "about", "text": "About", "url": "../pages/theAboutPage.html"},
        {"id": "help", "text": "Help", "url": "../pages/theHelpPage.html"},
        {"id": "contact", "text": "Contact", "url": "../pages/theContactPage.html"}
    ];

nav_config.forEach(function (config) {
    $('').attr({"id": config.id, "text": config.text}).click(function(){
        $(target_selector).load(config.url);
    }).appendTo(navbar_selector);
})

But it's steel ugly solution.


Displaying a random poem from a database

In addition to the depreciation and injection issues pointed out in the comments, I would just add that SELECT * FROM poems will fetch all columns for all rows, which is terribly inefficient. SELECT COUNT(*) FROM poems will return the number of records in the table, and you won't have to call mysql_num_rows.


You know that a mark has been placed at board[x][y]. Then you only need this to check for a win on vertical line y:

if board[0][y] == board[1][y] == board [2][y]

Your comments state "check if previous move was on the main/secondary diagonal", but you don't actually check. You can use the expressions x == y and x + y == 2 to check that.

Simplified code:

def CheckVictory(board, x, y):

    #check if previous move caused a win on vertical line
    if board[0][y] == board[1][y] == board [2][y]:
        return True

    #check if previous move caused a win on horizontal line
    if board[x][0] == board[x][1] == board [x][2]:
        return True

    #check if previous move was on the main diagonal and caused a win
    if x == y and board[0][0] == board[1][1] == board [2][2]:
        return True

    #check if previous move was on the secondary diagonal and caused a win
    if x + y == 2 and board[0][2] == board[1][1] == board [2][0]:
        return True

    return False


In addition to what @Carpsen90 said:

No get... accessor methods

Unlike some other programming languages, you don't define accessor methods for the properties, these are implicitly created by the compiler. If suit and rank are constant properties (initialized once and never mutated) then it is simply

struct Card {
    let rank: Int
    let suit: Int

    // ...
}

For properties which are publicly read-only, but internally read-write, it is

 struct Card {
    private(set) var rank: Int
    private(set) var suit: Int

    // ...
}

That makes the compareRank/Suit methods obsolete, because you can directly  test

if card1.rank == card2.rank { ... }

etc.


Rendering different view classes based on the value of a string

The obvious answer is to introduce a map:

var typeToConstructor = {
    'face' : FaceDetail,
    'voice' : VoiceDetail,
    // ...
}

Then you can simply look up your constructor function:

onShow: function() {
    var type = this.model.get('type').toLowerCase();
    var constructor = typeToConstructor[type];
    if (typeof constructor !== 'function') {
        // Unknown type... do something
    }

    // execute the constructor.
    this.regionItems.show(new constructor({
        model               : this.model,
        authRequestModel    : this.authRequestModel,
        collection          : this.model.attemptItemsDataCollection
    });
}


Redraw text on change, with automatic zooming, using fabric.js

Review and rewrite.
Code

Use strict mode by adding the directive "use strict"; to the top of the javascript file.

Use const for variables that do not change.

Don't query the DOM every time you want an element. Get it once, and store it for later use.

Don't duplicate data. You have $Eletter and letterins both of which hold the same data.

toFixed returns a string not a number so be careful with its use. You can use Math.round(value) to round a value.

Don`t create copies of variables if you only use them once.

The following are all not needed
var letterins = jQuery("#Eletter").val();
var letterLenghts = letterins.length;
var LetteringL = jQuery("#LetteringL").val();

Use arrays as lookups when you have sets of data with values attached.

Eg your zoom settings (BTW you repeated the 1200 zoom setting of 2.1 it will never be set)
// a list of the widths and associated zooms
const zoomSettings = [
    {widths: [400, 600, 1400, 1600, 1800], zoom: 1.1},
    {widths: [800, 1000, 1200], zoom: 1.2}
];

// function gets the zoom setting depending on width
// if a matching zoom can not be found then a zoom of 1 is returned
const getZoom = (width) => {
    var zoom = zoomSettings.find(arr => {
       return arr.widths.some(val => width >= val && width <= val + 30)
    });
    if (zoom) { return zoom.zoom }
    return 1;
}

Now you don't have to have the long chain of if else statements. For details on the array methods some and find go to MDN array
jQuery
Do you really need jQuery?
I have never approved of jQuery for many reasons, one of them being that it encourages bad practices. These days its primary reason for existence (cross browser compatibility) no longer applies and it is a large complex script that your clients need to download, parse, and execute, which is a cost that they must bear.
Now I have an even better argument against its use. Using jQuery opens your site to security vulnerabilities see 77% of 433,000 Sites Use Vulnerable JavaScript Libraries
Thus I remove jQuery, as it is not needed and can be done with...
function query(query){
    return document.querySelector(query);
}

This is not a cover all solution but just a short cut to the standard DOM query.
A rewrite
I have rewritten the code using the above as a guide.
I have written it to do the same as your code as I am not sure what your aim is with the zoom setting, they seem arbitrary and limited to only a small set of possible text widths.

"use strict";
const canvas = new fabric.Canvas('editor');
const textbox = new fabric.Text('Your Text', {
  left: 100,
  top: 0,
  width: 800,
  textAlign: 'center',
  fontFamily: "Impact",
  fontSize: 76,
  radius: 230,
  rotate: 0,
  selectable: false,
  hasControls: false,
  effect: "STRAIGHT",
  charSpacing: 10,
  spacing: 40
});
canvas.add(textbox).renderAll();
canvas.setActiveObject(canvas.item(canvas.getObjects().length - 1));

const zoomSettings = [
    {widths: [400, 600, 1400, 1600, 1800], zoom: 1.1},
    {widths: [800, 1000, 1200], zoom: 1.2}
];
const getZoom = (width) => {
    var zoom = zoomSettings.find(arr => {
        return arr.widths.some(val => width >= val && width <= val + 30);
    });
    if (zoom) { return zoom.zoom }
    return 1;
}
function query (query) { return document.querySelector(query) }
const eLetter = query("#Eletter");
const letteringL = query("#LetteringL");
eLetter.addEventListener("keyup", keyUpEvent);
function keyUpEvent(event) {
    const obj = canvas.getActiveObject();
    if (obj) {
        const widc = Math.round(obj.getWidth());
        if (event.target.value.length > letteringL.value) {
            canvas.setZoom(canvas.getZoom() / getZoom(widc));
        } else {
            canvas.setZoom(canvas.getZoom() * getZoom(widc));
        }
    }
    canvas.getActiveObject().setText(event.target.value);
    canvas.renderAll();
    letteringL.value = event.target.value.length;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js" ></script>
<div class="wrapper-canvas">
  <canvas class="" id="editor" width="1000" height="auto"></canvas>
</div>
<input class="text-input" type="text" id="Eletter" value="Your Text">
<input id="LetteringL" type="hidden" value="">


A class and a function to create and light up buttons in PyGame

I think your button class should do more. It should know if a point is within it's boundaries or not and what its image(s) is (are). It should probably also have an update method that can optionally be called with the mouse position. I would also rename it to singular Button, since each instance of the class is a single button and not a collection of buttons.

class Button:
    """
    This class takes the x-position and the y-position, width and height of an image.
    """
    def __init__(self, x, y, width, height, image, hover_image=None):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.image = on_image
        self.hover_image = hover_image

def point_inside(self, pos=None):
    if pos is None:
        return False
    return (self.x <= pos[0] <=  self.x + self.width \
            and self.y <= pos[1] <= self.y + self.height)

def update(self, screen, mouse_pos=None):
    if self.hover_image is not None and self.point_inside(mouse_pos):
        screen.blit(self.hover_image, (self.x, self.y, SCREEN_HEIGHT, SCREEN_WIDTH))
    else:
        screen.blit(self.image, (self.x, self.y, SCREEN_HEIGHT, SCREEN_WIDTH))

if __name__ == "__main__":
    thumbs_up_img = pygame.image.load('thumbsup.png')
    thumbs_up_lit_up_img = pygame.image.load('thumbsupred.png')
    thumbs_up = Button(60, 240, 50, 50, thumbs_up_img, thumbs_up_lit_up_img)

    # some pygame setup
    ...

    while True:
        mouse = pygame.mouse.get_pos()
        button.update(screen, mouse)
        pygame.display.flip()

This is a bit more generic, in that it allows a button not to have a hover image and it has an update method, which is quite common for objects in pygame. You could think about off-loading the point in button boundary check to a Rectangle class, which might help since you will probably encounter rectangles and checking if a point is inside quite often in pygame.

And would you look at that, there is already pygame.Rect, from which you could inherit. It even has the pygame.Rect.collidepoint method to check if a point is inside it.

class Button(pygame.Rect):
    """
    This class takes the x-position and the y-position, width and height of an image.
    """
    def __init__(self, x, y, width, height, image, hover_image=None):
        super().__init__(x, y, width, height)
        self.image = on_image
        self.hover_image = hover_image

def update(self, screen, mouse_pos=None):
    if self.hover_image is not None \
       and mouse_pos is not None \
       and self.collidepoint(mouse_pos):
        screen.blit(self.hover_image, (self.x, self.y, SCREEN_HEIGHT, SCREEN_WIDTH))
    else:
        screen.blit(self.image, (self.x, self.y, SCREEN_HEIGHT, SCREEN_WIDTH))


Form the largest number by swapping one pair of digits

Style critique

Either terminate your statements consistently with semicolons, or not at all.

If you're going to use const to define the function, then I suggest using the arrow notation as well, instead of the function keyword.

The variable names could be improved:

Why is the function's parameter called array?  It's clearly supposed to be a number.
After splitting the digits, what does array mean, and what does it contain?  I'd rename it to digits.
What are the buckets?  I suggest renaming it to lastIndex.
Instead of location and current_location, I'd just use i, which is a conventional variable name to use for an array index.  (Also, the underscore is unconventional in JavaScript.)
largest doesn't remain the largest digit of the number.  Perhaps wantDigit would be a better name, since it's the digit that we would like to put at the current index, if possible.

The nastiest line of code is the one where you perform the swap:

array[current_location] = [array[buckets[largest]], array[buckets[largest]] = array[current_location]][0]

A better way to do parallel assignment would be to use destructuring assignment:

let array = ['a', 'b', 'c'];
[array[0], array[2]] = [array[2], array[0]];
console.log(array);

But here, you don't even need to do parallel assignments, because you have already stored the values to be swapped in other variables:

array[buckets[largest]], as an rvalue, is just largest.  (With the renamings I proposed above, it would have been digits[lastIndex[wantDigit]], which might make it more obvious that it's actually just wantDigit.)
array[current_location], as an rvalue, is just current_val.

So, just write two simple and clear assignment statements instead.

If no swap occurred, then you can just return the original number.

const maximumSwap = (number) => {
    let digits = number.toString().split('');
    let lastIndex = [];
    for (let i = 0; i < digits.length; i++) {
        lastIndex[digits[i]] = i;
    }
    let wantDigit = lastIndex.length - 1;
    for (let i = 0; i < digits.length; i++) {
        for (let iDigit = digits[i]; iDigit < wantDigit; wantDigit--) {
            if (i < lastIndex[wantDigit]) {
                digits[i] = wantDigit;
                digits[lastIndex[wantDigit]] = iDigit;
                return +digits.join('');
            }
        }
    }
    return number;
};

console.log(maximumSwap(99739));
console.log(maximumSwap(9273));
console.log(maximumSwap(9732));

Complexity analysis

Your algorithm is pretty efficient, and I couldn't find any significant optimizations to make.

Be careful to specify what you mean by "n".  You probably used it to mean the length of the input number.  (If I had to choose my conventions, I'd say instead that the input number itself is n, and its length is d = log10 n.)

Creating the buckets takes O(n) time, because location loops up to array.length.  But I would say that it takes O(1) space, since the length of buckets will not exceed 10.

Walking the values clearly takes more than O(1) time, because the outer loop is O(n): current_location iterates up to array.length.  The inner loop, which executes at most 10 times, can be said to take O(1) time.

Altogether, then, the algorithm takes O(n) time and O(1) space.


Data structure to count occurrences of words

There are many ideas to speed up hashtables, or hash maps.  Some ideas appear in an article about hashtables in PHP, and a comment describing hashtables in Ruby.  I present some ideas here, but these ideas might or might not speed up your program, because I have not tested them.

Add a counter for each word.  If the word "the" appears 20 times, your code adds 20 entries for "the".  The idea is to have 1 entry for "the", with the counter set to 20.  This would be like using Java's HashMap<String, int> to map the word to the counter.

For this idea, you would add an int count; to class Node.  To add n copies of word, you would searches for the Node with word, and add n to its count.  If the Node didn't exist, you would insert a new Node and set its count.  Your table would have fewer nodes, so searches might be faster.  Also, there would be only one node for each word, so you would stop searching if you found the node.

Change the hash function.  Your hash function seems to multiply the character codes in a string.  If a string has one even-numbered character (like 'l', 'n', 'r', 't'), then the product is a multiple of 2.  If the string hash two such characters, then the product is a multiple of 4, and so on.  With 100 buckets, your hash might put most words in the multiple-of-4 buckets, and some words in the other even buckets, and almost no words in the odd buckets.  Then your program would search for most words in the power-of-4 buckets, but those buckets would have long lists of nodes.

A better hash function might use a rotation (also known as a barrel shift) to spread the bits, with addition to mix in each character.

int hash = 0;
for (int i = 0; i < a.length(); i++) {
    hash = Integer.rotateLeft(hash, 5);
    hash += (int)a.charAt(i);
}

Use power-of-2 buckets.  Division a / b and modulus a % b tend to be slow when b isn't constant.  Your hash function has sum = sum % array.length.  If the length was a power of 2, you would use sum = sum & (array.length - 1) to get the modulus.  For this idea, your constructor WordStoreImp(n) would round up n to a power of 2, with code like

if (n < 16)
    n = 16;
else
    n = Integer.highestOneBit(n - 1) << 1;

For example, if n was 100, then the highest 1-bit in 99 is 64, and 64 shifted left by 1 is 128.  Because 128 is 2 to the 7th power, so hash & 127 extracts the low 7 bits of hash as an integer from 0 to 127.

Switch from open chaining to open addressing.  Your hash table uses an open chain (or linked list) in each bucket.  You allocate memory with new Node, but memory allocation might be slow.  The idea is to switch to open addressing and remove the new Node calls.

With open addressing, each bucket holds exactly one word.  You would allocate the buckets with

words = new String[n];
counts = new int[n];

This sets each word to null and each count to zero.  A bucket is empty when its word is null.  To search for a word, if the bucket has a different word, you check the next buckets until you find the correct word, or an empty bucket.

pos = hashFunction(word);
while (strings[pos] != null && !strings[pos].equals(word))
    pos = (pos + 1) & mask;  // where mask = strings.length - 1

At this point, count[pos] is the correct count for this word.  If the bucket is empty, then the count is still zero.  If you are adding the word, then you would put strings[pos] = word and increase the count.

In open addressing, a bucket with a word can never become empty; you can only remove a word by setting its count to zero, and leaving the word in the bucket.  To be fast, at least half of the buckets must be empty.  You would keep a count of the number of words in the table.  When the count reaches n/2, you would allocate a new table with twice as many buckets, and move all the words to the new table (skipping words where the count is zero).


What if I want to put the Formatter class under test? How can I mock the Calculator dependency if it is hard-coded?

I suggest you put that into a separate public method so that it would be possible for other developers to create a partial mock and test it. It will also be clearer since you start reading the class what its dependencies are.

class Formatter
{
    /**
     * @var Calculator
     */
    private $calculator;

    /**
     * @param Calculator $calculator
     * @return $this
     */
    public function setCalculator(Calculator $calculator)
    {
        $this->calculator = $calculator;

        return $this;
    }

    /**
     * @return Calculator
     */
    public function getCalculator()
    {
        return $this->calculator;
    }

    /**
     * @return array
     */
    function getAndFormat ($n)
    {
        $table = $this->getCalculator()->doPowTable($n);

        return array_map (function($item) {
            $item['i_factor'] = $item['i'].'_'.$item['factor'];
            return $item;
        }, $table);
    }
}

This way you can either provide a different calculator or a mocked one for testing purposes.

Please consider the example below. It shows how to create a partial mock of the Formatter class to override the Calculator dependency.

$mockedCalculator = $this->getMock(Calculator::class);

// set your mocked calculator behaviour here

$formatter = $this->getMockBuilder(Formatter::class)
    ->disableOriginalConstructor()
    ->setMethods(['getCalculator'])
    ->getMock();

$formatter
    ->expects($this->once())
    ->method('getCalculator')
    ->willReturn($mockedCalculator);

$n = 123; // it's just an example
$this->assertEquals($expectedValue, $formatter->getAndFormat($n));


Finding root of strictly monotonic function by bisection

1. Use established terms to make your code more readable to others

In this case, use "increasing" instead of "raising". In such a simple context it is quite obvious what you mean by "raising", but you would be surprised how much effort and how many misunderstandings you can save by using existing, well-known terms.

2. Give clear, unambiguous names to functions

When I see a function areBothNumbersPositive(double a, double b), I assume it returns a > 0 && b > 0. A more suitable name would be areBothFuncValuesPositive(double a, double b), even though it's a bit longer.

3. Don't return true or false based on the value of a boolean expression, return the expression directly

bool isIncreasing(double a, double b)
{
    return f(a) < f(b);
}

bool areBothFuncValuesPositive(double a, double b)
{
    return f(a) > 0 && f(b) > 0;
}

4. Duplicate code in chageRanges can be reduced

void changeRanges(double &a, double &b)
{
    if (isIncreasing(a, b) == areBothFuncValuesPositive(a, b))
    {
        moveLeft(a, b);
    }
    else
    {
        moveRight(a, b);
    }
}

Although I must admit, this seems a bit confusing. Maybe it would be a good idea to define a function which would figure out whether to go left or right, and then use this function in the if. This might be an overkill in this simple case, but is quite commonly used with more complex boolean expressions.

bool shouldMoveLeft(double a, double b)
{
    return (isIncreasing(a, b) && areBothFuncValuesPositive(a, b))
         ||(isDecreasing(a, b) && areBothFuncValuesNegative(a, b));
}

void changeRanges(double &a, double &b)
{
    if (shouldMoveLeft(a, b))
    {
        moveLeft(a, b);
    }
    else
    {
        moveRight(a, b);
    }
}

5. Use functions where appropriate

Functions serve two main purposes: 1) code reuse; 2) conceptual abstraction. Even if you don't reuse them, they can make code more readable. For example, when you calculate f(a) * f(b) > 0, what you really want to know is whether the function has the same sign at both values, and neither f(a) nor f(b) are zero.

bool areBothFuncValuesNonzeroSameSign(double a, double b)
{
    return f(a) * f(b) > 0;
}

An even better idea would be to introduce the concept of a sign, and then build upon it (I copied the sign function from this SO answer).

template <typename T> int sign(T val) {
    return (T(0) < val) - (val < T(0));
}

bool areBothNumbersSameSign(double x, double y)
{
    return sign(x) == sign(y);
}

bool areBothNumbersNonzero(double x, double y)
{
    return x != 0 && y != 0;
}

bool areBothFuncValuesNonzeroSameSign(double a, double b)
{
    const double
        fa = f(a),
        fb = f(b);

    return areBothNumbersNonzero(fa, fb) && areBothNumbersSameSign(fa, fb);
}

This is not as succinct and elegantly clever as your original code. But imagine it wasn't a single line, but an entire function / class / project written in such a clever way. Then you would likely have a bit of trouble understanding it when you come back to it after some time. It would be even more trouble for someone else who has never seen your code before and now has to understand it, because you don't work at the company anymore and they inherited your code, or because they are extending your project, using your library, etc. By keeping your code simple and "stupid", you make it more readable and accessible to more people, and therefore, more maintainable.

Another two important aspects of software, besides readability and maintainability, are composability and reusability. Like readability and maintainability, these two are related. The functions sign, areBothNumbersSameSign and areBothNumbersNonzero are quite generic, so they are easily combined together (composed). This improves their reusability. Make your functions as generic as possible, so they can be reused later in different contexts, and composed to form larger abstractions. This includes the use of generic types (templates), as in the sign function. Making the function closely tailored for one specific use case prevents it from being used in other cases. You can observe that the function areBothFuncValuesNonzeroSameSign can only be used in the context of the function f, since it depends on it. We can decompose its functionality into two logically distinct parts: 1) calculating the values f(a), f(b); and 2) checking if the computed values are both non-zero and have the same sign.

bool areBothNumbersNonzeroSameSign(double x, double y)
{
    return areBothNumbersNonzero(x, y) && areBothNumbersSameSign(x, y);
}

bool areBothFuncValuesNonzeroSameSign(double a, double b)
{
    return areBothNumbersNonzeroSameSign(f(a), f(b));
}

Again, this is just a simple example. But as the code grows bigger and the functionality gets more complex, such refactoring is necessary, although very often neglected.

6. Changing range in moveLeft and moveRight

As you pointed out, it is not ideal to use a constant (2) when adjusting the range. The first naive idea that would come to my mind is to simply shift the range, without changing its size.

void moveLeft(double &a, double &b)
{
    const double diff = b - a;
    b = a;
    a = a - diff;
}

void moveRight(double& a, double& b)
{
    const double diff = b - a;
    a = b;
    b = b + diff;
}

But, as you said, this is not very efficient. What you can do is increase the size of the range exponentially. I think (but I'm not sure), that this would converge more quickly on average.

void moveLeft(double &a, double &b)
{
    const double diff = b - a;
    b = a;
    a = a - diff*2;
}

void moveRight(double& a, double& b)
{
    const double diff = b - a;
    a = b;
    b = b + diff*2;
}

Note that I have not tested any of this, so I can't guarantee it works.


First - You have numeric constants scattered all over the code.

Try to change the board width to 500 and you will immediately understand. Numeric constants like board width shall appear exactly once when assigned to a constant which is used throughout the code lateron. This applies to board size, pong size and player size.

define

board_width = 600
board_height = 600

and use it to draw the border like

for side in range(2):
    border_pen.fd(board_width)
    border_pen.lt(90)
    border_pen.fd(board_height)
    border_pen.lt(90)

Second - you have calculated dependent numeric constants

If constants depend on others you shall not evaluate these. Try to change the bong size and you will have a hell of a work to find all depending values. You are hiding the dependencies and again make your code unmaintainable. All constants that have dependencies shall be initialized not by numeric values, but by expressions using the first class constants.

replace

score_pen.setposition(-290, 310)

with

score_pen.setposition(-board_width/2 + 10, board_height/2 + 10)

Third - structure your code

Whenever you feel you need a comment to explain what a block of code is doing you probably found a function (or a class). if you chose nice function names comments may be obsolete. Also you have less name collisions on local variables leading to better names.

# set up border
border_pen = turtle.Turtle()
#[...]
border_pen.hideturtle()

should be

def set_up_border():
    pen = turtle.Turtle()
    #[...]
    pen.hideturtle()

also

#Draw score
score_pen = turtle.Turtle()
#[...]
score_pen.hideturtle()

should be

def create_score():
    pen = turtle.Turtle()
    #[...]
    pen.hideturtle()
    return pen

score_pen = create_score()

Fourth - reuse code and do not repeat yourself

When you now look at your new functions create_score() and create_timer() you will notice they are nearly identical. They only differ in position and the string displayed. But they share font, color and so on. So we add some parameters and unify these

def create_text(pos, txt):
    pen = turtle.Turtle()
    pen.speed(0)
    pen.color("white")
    pen.penup()
    pen.setposition(pos)
    pen.write(txt, False, align="left", font= ("Arial", 14, "normal"))
    pen.hideturtle()
    return pen

which we use like

score_pen = create_text(score_position, "Score %s" % score)
time_pen = create_text(time_position, "Time %s" % time)

the same way we can unify player and AIplayer. If you want to change player size there is now a single line of code to change. Actually these players, text fields and the bong should be classes but for now we leave it like that.

All the points up to now are valid for any programming language and absolutely important. Maintainability, readability and testability count.

Some algorithmic issues

Bouncing

An object bouncing on another one may not penetrate it. so it is not sufficient to reverse the direction when a collision is detected, but you also have to exit the foreign object immediately. this is done by "mirroring" the entered object to the outside again. So instead of

#move pong ball
pong.sety(pong.ycor() +pong.dy)
#[...]

#check for bounce and redirect it
if pong.ycor() < -300:
    pong.dy *= -1
#[...]

we do not draw immediately but fix penetration before updating the screen

#move pong ball
y = pong.ycor() + pong.dy
#[...]

#check for bounce and redirect it
if y < -board_height/2:
    pong.dy *= -1
    y = -board_height - y
#[...]

pong.sety(y)
#[...]

BTW: Game over is not recognised if the AI player would miss the bong.

Tower running

Setting x and y coordinates ii separate calls where the pen is down results in the pong performing tower running instead of smooth angular movement.

AIplayerspeed

Your AI player does not move with its own speed but with bong speed as it directly takes bong y position. AIplayerspeed acts as an offset to bong y position. This should be fixed to

either rename and calculated this offset from bong and player size to be center aligned
or implemented as a max speed to approach bong y position (again centeraligned)

math.sqrt

square root is an expensive function which in game design is avoided wherever possible. In your case you coud simply square the max distance

distance = math.sqrt(math.pow(t1.xcor()-    t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 20:
    #[...]

becomes

sq_distance = math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2)
if distance < math.pow(20, 2):
    #[...]


Optimizing the Sieve of Eratosthenes for prime generation

A few things to consider:

Is having the function generic really necessary? Why not just make the data type unsigned long long instead?  This way you can do some bounds checking.

I would suggest using a bitset to hold the raw data would be more efficient than using 32 bits to represent each 1 or 0.

All primes are odd except for 2.  If you add 2 to the result vector, you can start the outer loop at 3 and increment by 2.

Since the outer loop will only be odd numbers the start of the inner loop will also be odd.  Therefore in order to keep hitting the odd number multiples you can increment by i*2.

You can shorten the second loop by adding to the vector every time you find a prime in the outer loop.  This way the second loop can start where the outer loop finishes.

There is also another algorithm you can use that is more highly optimised for making a list of primes, mind you it's also more complicated( sorry I can't remember the name off hand)


Calculate the day when Date is given as input using the Doomsday algorithm

Your code is hard to understand, even after watching the video.

Make some functions. years_doomsday would help move some of the hard to understand information to be self-contained.
If you need to floor divide and get the remainder use divmod.
You can check the leap year using calendar.isleap.
You have a bug, if you ever enter a leap year then the non-leap years will return incorrect values for January and February.
You should make a function that calls years_doomsday, and returns the weekday.
You should make centdoom a global constant.
By rotating centdoom once you can remove the need for the -3.

import calendar

WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
MDOOMSDAY = [3, 28, 14, 4, 9, 6, 11, 8, 5, 10, 7, 12]
MDOOMSDAY_LEAP = list(MDOOMSDAY)
MDOOMSDAY_LEAP[:2] = [4, 29]
CDOOMSDAY = [2, 0, 5, 3]

def years_doomsday(year):
    a, b = divmod(year, 100)
    c, d = divmod(b, 12)
    e = d // 4
    return (CDOOMSDAY[a % 4] + c + d + e) % 7

def doomsday(year, month, day):
    y_doomsday = years_doomsday(year)
    mdoomsday = MDOOMSDAY_LEAP if calendar.isleap(year) else MDOOMSDAY
    return WEEKDAYS[(day - mdoomsday[month-1] + y_doomsday) % 7]

if __name__ == '__main__':
    tests = [
        (2305, 7, 13, 'Thursday'),
        (1776, 7, 4, 'Thursday'),
        (1969, 7, 20, 'Sunday'),
        (1984, 1, 6, 'Friday'),
        (1902, 10, 19, 'Sunday'),
    ]
    for test in tests:
        if doomsday(*test[:3]) != test[-1]:
            print('Broken for', test)

If you don't want any fun, you can replace your code with datetime.date.isoweekday.

import datetime

for test in tests:
    if WEEKDAYS[datetime.date(*test[:3]).isoweekday()%7] != test[-1]:
        print('Broken for', test)


A few things...

Parameter Name

bool bruteforceGenerator(string& permutationIn, ...

From what I can see, this is not an "In" parameter. It's an "InOut". It actually keeps track of the current state too.

Expressions and Spaces

for(int i = permutationIn.size() - 1; i>=0; i--)

Here I'm being picky. You have spaces around the i = ... - 1, but you lose them in the second expression: i>=0. I would suggest that you choose one or the other style. I prefer spaces because I think it makes it easier to read.

Blocks of code

else return false;

On this one, long term, I prefer to have a block like so:

else
{
    return false;
}

It's also a lot easier to not later make a mistake by adding a block after the else and forgetting to move the return false; statement. Also always having a block means you can add a second line of code and it will probably work as expected. Without the block, it probably won't work as expected. Note that applies to this statement as well:

for(auto &i : permutationIn) i = options[0];

Lighter/Clearer overall Function

Finally, as a whole, I would change the way the function if/else blocks are managed. I would actually not have an else and would have a return false; as the very last statement. There is sample skeleton:

if(condition)
{
    ...
    return true;
}

for(...;...;...)
{
    if(condition)
    {
        ...
        return true;
    }
}

if(condition)
{
    return true;
}

return false;

I think that makes it simpler to read. The cases that work are managed first and return true. If nothing works, we end up returning false.

There is a comment by @Incomputable about an std::next_permutation algorithm. I can see that your algorithm would not fit for two reasons:

The std::next_permutation requires you start with a sorted array of characters; and
It only computes permutations with a size equal to the input size when in your case you start with 1 character and grow up to maxlength which can be smaller than the input length (as in your example).

However, one interesting aspect of that algorithm is the fact that you can run through the permutations again after false is returned.

You could achieve that behavior by clearing the permutationIn variable just before returning false:

    ...
    permutationIn.clear();
    return false;
}

Of course, the pattern you have is similar to reading a file. Once the EOF is found, further reading continues to give you EOF. Either pattern has its merits...


UVa 11340 Newspaper challenge (sum of letter values in an article)

I am going to focus only on the time aspect of your code, not the style or anything else, as that is not what you have asked for. i hope there will be others who will comment on that too.
Obvious Culprits

Character and Integer. Primitive to Object boxing costs time! Plus, a HashMap only has amortized constant lookup time, not true constant lookup time. What you want here is a pure old int array, somehow indexable by chars. That's possible, pretty easily, in fact. Plus, you are reinitializing the HashMap on the turns of your test counter loop. You could just call clear() on it, if you end up using it at all. For an array, however, reinitializing it is the way to go when clearing it (reinitialization is amortized constant time (including GC), not linear like clearing the array. It's linear time in both cases for the HashMap, and there's additional GC overheads).

Lots and lots of I/O in a tight loop. That's always a bad idea, as I/O form most performance bottlenecks. Maybe you should take the input in separately before you do the processing?

(2) brings us to using separate methods. Now that your I/O and program logic have become loosely coupled, you can easily separate them into 2 functions. Trust me, a function call overhead is not too much of a problem here. (I don't do this is my "Improved (?) code below" as it's mostly a stylistic issue, but you should).

java.util.Scanner uses pattern matching and regexes under the hood. Those can be pretty slow. For faster I/O, you want java.io.BufferedReader and family.

Suggestion

You know, this is a financial calculation. doubles are liable to roundoff errors. You should be using java.math.BigDecimal for financial calculations and java.text.DecimalFormat for formatting numbers. However, in the interest of performance, I'll let this one slide. I don't do this in the code I provide below either.

You should really have some sort of Exception handling. You should also consider JDK 7's try-with-resources statement, which I use, to simplify resource cleanup.

Improved (?) Code
My implementation will trade time for space, which means that more memory will be consumed in exchange for faster execution speed. With the test input available on the UVA online debugging portal (the one for the UVA Online Judge), this code takes ~100ms (Measure-Command on PowerShell) or ~180ms (time through bash on WSL) to cover all test cases, including JVM start-up time. I use Java 1.8, like the UVA platform. The run times are safely much lower than the 1 second of runtime offered by the Online Judge.
import java.io.*;
public class UVA11340 {
    public static void main(String[] args) {
        try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
            int t = Integer.parseInt(br.readLine());
            //System.out.printf("Reading %d inputs\n", t);
            int tableSize = 0xFF;//Extended ASCII table size
            while(t-- > 0) {
                int k = Integer.parseInt(br.readLine());
                //System.out.printf("Reading %d characters for table\n", k);
                int[] table = new int[tableSize];
                for(int a = 0; a < k; ++a){
                    String in=br.readLine();
                    //System.out.println("Read map line:"+new String(in));
                    table[in.charAt(0)] = Integer.parseInt(in.substring(2/*in.indexOf(' ')+1*/, in.length()).trim()/*for bug in input*/);
                }
                int l = Integer.parseInt(br.readLine());
                //System.out.printf("Reading %d lines\n", l);
                double cost = 0.0;
                for(int b = 0; b < l; ++b){
                    String str = br.readLine();
                    int strLength = str.length();
                    //System.out.println("Read input line:"+new String(str));
                    for(int i = 0; i < strLength; ++i){
                        cost += table[str.charAt(i)];//lookup cost of char
                    }
                }
                System.out.printf("%.2f$\n", (cost / 100.0));
            }
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
    }
}

I left in the debugging print statements as I feel that they make for reasonable documentation. Side note: Please use functions and proper variable names, like the ones I introduced.
Note:
This has not been tested with the UVA Online Judge, only on my PC.
PowerShell screenshot of timed run:

Bash on WSL screenshot of timed run:


It's actually easier to do this in the database layer. It's exceedingly good at these kinds of things.

@guest_reviews = GuestReview.where(:reviewed_id => @user.id)
@host_reviews  = HostReview.where(:reviewed_id => @user.id)

@hospitality_rate = @guest_reviews.average('people_rate')
@food_rate        = @guest_reviews.average('food_rate')
@place_rate       = @guest_reviews.average('place_rate')

@average_rate = [@hospitality_rate, @food_rate, @place_rate].inject(:+).to_f / @host_reviews.count

It'll result in more database queries, but overall it's more efficient.

I've left out the round() call on the @average_rate only because that seems like a presentation concern to me. Let the controller figure out the average (decimals and all), and let the view decide how to round and display it.

You could also add a has_many :guest_reviews, :foreign_key => "reviewed_id" to the User model, so you can just call @user.guest_reviews.average(...). Same for host_reviews

If you do that, you could also consider simply moving the calculations to the User model, so you don't need to do it all in the controller. And perhaps you could cache the results on the user record and only recalculate when reviews are added/deleted/changed. Assuming this happens less often than the averages being displayed, it'll speed up things a bit.

Lastly, (and this is just small stuff) I'd probably rename some of the variables. I.e. call it @food_rate_average instead of @food_rate in order to a) indicate that it's an average, and b) so it's not confused with the database column of the same name.
Similarly, I'd call the first average people_rate_average rather than hospitality_rate; the column is called people_rate so it's probably best to keep it consistent with that name (or rename the database column, if "hospitality" is a more fitting name)

(Edit: Actually, it's more natural to prefix the average_ rather than suffixing it, i.e. average_food_rate, average_rate, etc.)

In the code above, I've also underscored the names, just to keep things consistent with general Rails/Ruby conventions (FooBar → foo_bar).

Edit: Just for fun, you could go fully meta (though it's probably more confusing than anything - the above is much more readable)

@guest_reviews = GuestReview.where(:reviewed_id => @user.id)
@host_reviews  = HostReview.where(:reviewed_id => @user.id)

@average_rate = %w(people_rate food_rate place_rate).map { |column|
  instance_variable_set(:"@average_#{column}", @guest_reviews.average(column))
}.inject(:+).to_f / @host_reviews.count

That'll set @average_people_rate, @average_food_rate and so on


Overall, I like this. To really nitpick, I don't really like the use of rules[::2]. [::2] conveys that we are picking out every even element of rules as if that was significant. But in this case, it is more like it just happens to be that the first and last rules are what we want to pick out and that happened to match up with choosing all even elements.

I would probably just name the rules as follows. If the visual grouping of the rules is important you could wrap them in a class as static methods.

from itertools import groupby

bounds = (265275, 781584)

def digits_never_decreasing(s):
    return all(int(s[i]) <= int(s[i+1]) for i in range(len(s)-1))

def adjacent_digits_equal(s):
    return any(s[i] == s[i+1] for i in range(len(s)-1))

def adjacent_digits_not_in_larger_group(s):
    return any(len(list(v)) == 2 for _, v in groupby(s))

def test(num, *rules):
    return all(f(str(num)) for f in rules)

def solve(bounds, *rules):
    return sum(1 for i in range(bounds[0], bounds[1]+1) if test(i, *rules))

def part_one():
    return solve(bounds, digits_never_decreasing, adjacent_digits_equal)

def part_two():
    return solve(bounds, digits_never_decreasing, adjacent_digits_not_in_larger_group)

print(part_one())  # 960
print(part_two())  # 626


Perform the validation first, to eliminate redundant conditionals.

def play(p1, p2):
    if p1 not in rules or p2 not in rules:
        print("Invalid input")
    elif p2 in rules[p1]:
        print("{} {} {}".format(p1, rules[p1][p2], p2))
    elif p1 in rules[p2]:
        print("{} {} {}".format(p2, rules[p2][p1], p1))


compile time template bernstein polynomial

You could check against the most common cases you expect to occur:

float a;
switch (k)
{
case 0:
    a = 1.0f;
    break;
case 1:
    a = val;
    break;
case 2:
    a = val*val;
    break;
// maybe some more common cases...
default:
    a = std::powf(val, k);
}

But I personally wouldn't do such optimizations unless you really see that there is some significant slowdown in your particular case and benchmarks show that such an optimization really does make a difference.