Maintaining the Single Responsibility Principle with Project Euler #2

I think you are violating SRP, but not for the reason you think you are. Memoization is fine, it's definitely one approach to calculating the fibonacci values, but you have one class that is doing BOTH calculating the Fibonacci values AND summing the even ones.

If you are really worried about SRP, I would have a generator to calculate the Fibonacci numbers, and then an external function to sum them:

def sum_evens(limit):
    sum = 0
    for f in fibonacci_numbers(): # left as an exercise
        if f > limit:
            break
        elif f % 2 == 0:
            sum += f
    return sum

Otherwise, minor notes, your class is named fibonacci_Even_Sum_Calculator. The most accepted convention for class names is CamelCase, so FibonacciEvenSumCalculator is strongly preferred. Similarly, function names should be lowercase, and f is an insufficient name for code that is "get the nth Fibonacci number".


A class to generate, save and load unique transaction reference numbers for an application

The server requires a unique ID to detect replays in the case of network failures, support idempotency, and to report order confirmations in a way the client can make sense of. So yes, the server offers a sensible API.

You can send sequential numbers, or a random guid. Consider using import uuid.

Consider using a numeric prefix of yyyymmdd, with strftime('%Y%m%d') + '%06d' % num. This will help when you have issues with deleted file, backups, switching client laptops, and so on. It makes the transaction IDs more human readable. (It also makes them easier to guess, if you're concerned about a possible attacker.)

Thank you for using with for I/O. Consider acquiring a lock before saving updated counter, if you're concerned that multiple daemons or users might run instances of your code concurrently.

There's no need for default_file, as you can just put that default in the signature:

    def __init__(self, file=r"C:\Bot\Bot\trans_ref.json"):

You catch a subset of the things that can go wrong with file I/O and JSON parsing. It does not appear well motivated, given that the client doesn't try anyway, so it doesn't care whether it gets fatal exception A or B. Perhaps you have a use case which requires a custom exception, but you have not shown it. Likely you don't need it at this point. I would just let library load and open throw as they will, and caller will (correctly) receive fatal exception if one happens. Later, when caller implements an actual error recovery strategy, you will have new requirements in hand for what exception details must be returned, and you can make a better informed design decision about how UniqueTransactionRef should interact with exceptions.

Write the simplest code you can get away with (it's easier to test!). When you get a new concrete requirement in hand, make the code a little fancier.


Style: Depending on coding guidelines and preferences you may want to consider moving the declaration of r and c into the for-loops (for (int r = 0...), as these variables are not supposed to be used outside of the loop, and hence, an outside declaration kind of contradicts this contract.

Correctness: I'm afraid your greedy approach does not work out well - in other words: it gives wrong results. Consider the following matrix (or if you loop the other way round its symmetric variant) :

 0  0  0  0 -1
-1 -1 -1 -1 -1

By going through the first row first, you would create your first connected group with this intermediate result, before the row-loop switches to the second row:

 0  0  0  0  1
-1 -1 -1 -1  1

Next, the inner loop will find another -1 cell with no higher-numbered neighbors and create a second connected component, although there really is only one.

Succinctness: If the code was correct, you might as well eliminate all the if statements in the loop except for the one comparing against -1. The others are redundant in their behavior.


A few points:

Reversing the string m multiple times is unnecessary. Slicing can be done on the original string using correct indices. m[::-1][i:i+3][::-1] is equivalent to m[-i-3:len(m)-i]. Another approach is to traverse the indices in the reverse order for i in range(len(m)-1, -1, -3) and then perform slicing accordingly.
The logic can be simplified using str.join. m2.append(',') can be omitted. And you can just do

m3 = ','.join(m2[::-1])

Further improvements can be achieved by using list comprehensions and traversing the string from the beginning rather than in the reverse order. Some calculation for the indices are needed:

def formatting(n):
    m = str(n)  # Turn it into string
    num_digits = len(m)
    seg1_len = (num_digits % 3) or 3  # Calculate length of the first segment
    segments = [m[:seg1_len], *(m[i:i+3] for i in range(seg1_len, num_digits, 3))]
    return ','.join(segments)

Python 3's built-in formatting specification actually supports the thousands separator. So you can just do this to achieve the same functionality:

formatted_n = f"{n:,}"

Or equivalently:

formatted_n = "{:,}".format(n)


Calculate mean, median, and mode from list of integers

There's no main method and more importantly, there are no tests. How do you know if the code works?
It's probably an artifact of learning a new language, but the code is overly documented. There's no reason to have comments describing what the implementation of the code is. It's more important to describe why a given implementation was chosen.
I would break out smaller functions to have somewhere for names to hang off of.
Documentation aspects:

"returns a ..." in docs is not useful; the return type already says that.
It is good to say why an error can occur though. You can also create a named error type that might have a variant like Error::EmptySlice, which is more self-describing.
"structure to ..." is docs is not useful; it is a struct.
"represent" is all programs do, so is redundant.
Avoid referring to concrete implementation details ("... is a Vec ...")

You have a good use of fold, but sum exists.
Median is the mode of the middle of the sorted vector. Now that there are functions, you can reuse them.
Why convert to a floating point, divide, then back to a usize? (sorted.len() as f64 / 2.0) as usize)
Don't declare the type of mode; let the compiler's type inference handle it.
Use Iterator::filter instead of the if in the loop.
Use Iterator::map instead of the manual destructuring in the for loop for (key, value).
Use Iterator::collect to create the Vec instead of creating it and pushing to a Vec.
I'd oneline the counting with the HashMap.
Use Iterator::max and unwrap_or to find the biggest value instead of doing it by hand.
You could track the maximum value during the first loop. This would save one iteration, but it's not as pretty.
The casts to f64 wen creating the structure are redundant; the values are already f64.

use std::collections::HashMap;

/// The mean, median, and mode of some integers.
#[derive(Debug)]
pub struct Calculations {
    mean: f64,
    median: f64,
    mode: Vec<i32>,
}

fn mean(values: &[i32]) -> f64 {
    let sum: i32 = values.iter().sum();
    sum as f64 / values.len() as f64
}

/// Returns the middle element of the elements in sorted order (or the
/// average of the middle 2 elements)
fn median(values: &[i32]) -> f64 {
    let mut sorted = values.to_vec();
    sorted.sort();

    let mid = sorted.len() / 2;

    if sorted.len() % 2 == 0 {
        mean(&sorted[(mid - 1)..(mid + 1)])
    } else {
        sorted[mid] as f64
    }
}

fn mode(values: &[i32]) -> Vec<i32> {
    let mut occurrences = HashMap::new();

    for i in values {
        *occurrences.entry(i).or_insert(0) += 1;
    }

    let max_value = occurrences.values().cloned().max().unwrap_or(0);

    occurrences.into_iter()
        .filter(|&(_, v)| v == max_value)
        .map(|(&k, _)| k)
        .collect()
}

/// Calculates the mean, median, and mode of values.
/// It is an error to pass an empty slice
pub fn calculate_mmm(values: &[i32]) -> Result<Calculations, &str> {
    if values.is_empty() {
        Err("Found empty slice")
    } else {
        Ok(Calculations {
            mean: mean(values),
            median: median(values),
            mode: mode(values),
        })
    }
}

fn main() {
    println!("{:?}", calculate_mmm(&[3, 2, 1, 2]));
    println!("{:?}", calculate_mmm(&[3, 2, 1]));
}


Starting off, its not secure the way you are prompting for passwords and storing them. Instead, use the getpass module, and store the hash of the password. I'm not even certain that this way is 100% correct (I'm not a security guru), but its what the Python documentation shows for secure password hashing, and I imagine its better than plaintext.

from getpass import getpass
from hashlib import pbkdf2_hmac as pwhash

def login(users):
    username = input('please enter username: ')
    if not username in users:
        print("access denied")
        exit()

    password_hash = None
    while password_hash != users[username]:
        password_hash = pwhash("sha256", getpass().encode("ascii"), b"t4h20p8g24j", 100000)

    print("access granted")
    return username

Your roll function had a typo in it-  the third (optional) roll could only generate numbers [1, 5] inclusive. I also reordered the statements to remove an intermediate variable that didn't contribute anything.

def roll():
    die1 = random.randint(1, 7)
    die2 = random.randint(1, 7)
    points = die1 + die2
    points += 10 if (die1 + die2) % 2 == 0 else -5
    if die1 == die2:
        points += random.randint(1, 7)
    return points

I would replace your get_leaderboard body with a shorter and cleaner read call.

def get_leaderboard():
    with open('Leaderboard.txt', 'r+') as g:
        return g.read().split("\n")

And similarly for save_leaderboard

def save_leaderboard(leaderboard):
    with open('Leaderboard.txt', 'r+') as h:
        h.write("\n".join(leaderboard))

You should also try to avoid excessive use of tuples when you need to access the elements individually. Your code will be littered with thingy[0] and thingy[1] and nobody but you (if that) will know what the significance of 0 and 1 are. I revised update_leaderboard with these changes, but I'm still not quite satisfied with it.

def update_leaderboard(leaderboard, winner):
    winner_score, winner_name = winner
    for idx, item in enumerate(leaderboard):
        item_score, item_name = item.split(', ')
        if item.name == winner_name and int(item_score) < int(winner_score):
            leaderboard[idx] = '{}, {}'.format(winner_score, winner_name)
    leaderboard.sort(reverse=True)
    #leaderboard.sort(reverse=True), key=lambda x:int(x.split(', ')[0]))

The data really shouldn't be cast back and forth from strings to lists/tuples so much. It would be best to just make a dictionary of name:score pairs, and write a tiny bit of formatting logic into your get_leaderboard and save_leaderboard functions. I wasn't going to change that much though.

I also want to point out common mistake that could normally create a bug in sorting (in your case it does not because of the hard-coded ,, but still)-  you can't rely on str.sort to sort a list of strings by their numerical value. I left a comment showing how you would do this correctly if your delimiter evaluated as greater than "0".

Furthermore- you shouldn't really rely on changing leaderboard outside the function scope. I feel like this is partially why you chose to go with the (unnecessary) enumeration() logic. Instead, return the modified leaderboard and allow the caller to take it from there.

Anyways, the last major change I would make would be to move all your globals (and friends) inside your main() function.

def main():
    print("")
    print("welcome to the dice game")
    print("")

    with open('users.pickle', 'rb') as f:
        users = pickle.load(f)

    print(users)
    print("  ")

    user1 = login(users)
    user2 = login(users)
    ...


Why don't you want to leak sql.ErrNoRows outside? I find it quite explicit.

It seems that you are wrapping your errors with some context: there is a very nice package for this: https://godoc.org/github.com/pkg/errors

Using it, your code would look like this:

package db_access

import (
    "database/sql"
    "fmt"
    "my_database"
)

type TheType struct {
    Name string
}

// uses named returns
func LoadTheTypeFromDb(db *sql.DB, id uint) (row TheType, err error) {
    query := fmt.Sprintf(
        "SELECT %s FROM %s WHERE %s = ?",
        my_database.NAME,
        my_database.TABLE,
        my_database.ID,
    )

    err = db.QueryRow(query, id).Scan(&row.Name)
    return
}

And your "my_database"

package my_database

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "github.com/pkg/errors"
)

func GetDatabaseInstance(connectionString string) (db *sql.DB, err error) {
    db, err = sql.Open("mysql", connectionString)

    if err != nil {
        err = errors.Wrap("open failed", err)
        return
    }

    err = db.Ping()
    // if err is nil, errors.Wrap returns nil
    err = errors.Wrap("ping failed", err)

    return
}

Your custom error file should not be needed anymore!


Don't using namespace std;

It is considered bad practice because of possible name collisions, ... Although nobody will hurt you, as this is such a small program :)

Don't compare booleans to booleans

Things like running == true are completely unnecessary, as running is already a condition in itself. Just use running.

You don't need running

The variable running is unnecessary. You need one for nested loops (breaking out of both), but for single loops, a single break and an infinite loop is preferred.

Why are you using compare?

Seeing input.compare("exit") == 0 would send me right to the docs, as I don't know what the return value of compare is.

if (input == "exit");

is more clear.

Don't flush 2 times in a row (or at all)

std::endl prints a new line, and then flushes stdout. This results in a performance hit, so it is better to output an actual newline. In your case:

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

Note that on some platforms (or if you need to), you have to flush the steam to see the output. In this case it is better to be explicit and use std::flush.

You're not using the command line parameters

So why name them? You can just omit the names, or define a main which takes no parameters:

int main(int, char**) {} //1)
int main() {} //2)

I prefer option 2.

Your code uses implementation specific behavior

std::string is defined in the string header. Not every compiler includes string with iostream or algorithm (VS doesn't), so you have to include it explicitly. Don't rely on automatic includes.

Technically, you don't need return 0;

Only for main, if you omit return 0;, the compiler will add it for you, so technically, you don't need to specify it.


Your code looks good. It's a little hard to read, but given the context that is ok!
We can also see that if new_ending is never in needles then your code looks like it will run in \$O(f2^s)\$ time, where \$f\$ is flips and \$s\$ is streak.
Whilst I can see the code in if new_ending in needles: will reduce the the time your code takes to run.
For example when streak=2 it will allow your code to run in linear time, it's not going to help much on bigger numbers - the code will still tend to \$O(f2^s)\$.
We can see how you're performing this optimization in the following.
Since you are not searching the descendent of HH, TT, HTT, THH, etc. it cuts down how big the tree will get.

We can clearly see that tails is just the inverse of heads.
If we focus on heads and split the 'base' and 'tail' (the repeating results) we get the following:
     HH 1/2^2
H    TT 1/2^3
HT   HH 1/2^4
HTH  TT 1/2^5
HTHT HH 1/2^6

Whilst it's cool it runs in linear time, it's not really that interesting.
And so when streak=2 the total chance for \$f\$ flips is:
$$\Sigma_{n=2}^f \frac{2}{2^n}$$
However when we look at streak=3 we can see the start of a distinguishing pattern.
     HHH 1/2^3
H    TTT 1/2^4
HH   TTT 1/2^5
HT   HHH 1/2^5
HHT  HHH 1/2^6
HTH  TTT 1/2^6
HTT  HHH 1/2^6
HHTH TTT 1/2^7
HHTT HHH 1/2^7
HTHH TTT 1/2^7
HTHT HHH 1/2^7
HTTH TTT 1/2^7

If we take the count of each size then we get:
3: 1
4: 1
5: 2
6: 3
7: 5

This is cool because it's the start of the Fibonacci numbers.
I have verified that the first 30 values are the same.
And so we now can assume we have an equation for streak=3:
$$\Sigma_{n=3}^f \frac{2F(n-2)}{2^n}$$
Doing the same thing for streak=4,5,6,10 give the following sequences:

4 - Tribonacci
5 - Tetranacci
6 - Pentanacci
10 - Fibonacci 9-step

In all this is a pretty compelling pattern.
And so we can write an algorithm to run in \$O(fs)\$ time where \$f\$ is flips and \$s\$ is streaks.
import collections
import itertools
from fractions import Fraction

def fibonacci_nth(size):
    store = collections.deque([0] * size, size)
    store.append(1)
    while True:
        yield store[-1]
        store.append(sum(store))

def coin_chance(flips, streak):
    if streak <= 0 or streak % 1:
        raise ValueError("streak must be a positive integer")
    if flips < 0 or flips % 1:
        raise ValueError("flips must be a non-negative integer")
    if streak == 1:
        return Fraction(flips != 0, 1)
    sequence = (
        Fraction(2 * numerator, 2 ** exponent)
        for exponent, numerator in enumerate(fibonacci_nth(streak - 1), streak)
    )
    return sum(itertools.islice(sequence, flips - streak + 1))

# Code to get OEIS sequences
def funky_finder(depth, size):
    desired = (['H'] * size, ['T'] * size)
    stack = [iter("HT")]
    stack_value = []
    while stack:
        try:
            coin = next(stack[-1])
        except StopIteration:
            stack.pop()
            if stack_value:
                stack_value.pop()
            continue
        _stack_value = stack_value + [coin]
        if _stack_value[-size:] in desired:
            yield ''.join(_stack_value)
        elif len(stack) < depth:
            stack_value.append(coin)
            stack.append(iter('HT'))

# I know, I know. But I was using this in a REPL!
size = 3; [i // 2 for i in sorted(collections.Counter(len(i) - size for i in funky_finder(20 + size, size)).values())]

>>> 100 * fast(20, 6) / 2**20
23.687744140625
>>> 100 * float(coin_chance(20, 6))
23.687744140625

>>> 100 * fast(100, 6) / 2**100
80.68205487163246
>>> 100 * float(coin_chance(100, 6))
80.68205487163246


You should add a bounds check that k is not larger than your array, because I don't see that explicitly mentioned in the problem statement.

for( int i = 0; i <= k; i++ )
   queue.add(arr[i]);

I think you should always add braces, but that's my personal opinion.

//Store the first k+1 elements in the heap
for( int i = 0; i <= k; i++ )
   queue.add(arr[i]);

for( int i = k+1; i < arrLen; i++ )
{
  //Extract the minimum element in the priority queue
  arr[i - (k + 1)] = queue.poll();

  //Add the next element to the queue
  queue.add(arr[i]);
}

This bit would make more sense if you kept i as your arr index. Then swap the statement to get rid of the +1, ...

//Store the first k+1 elements in the heap
int i = 0;
for(; i < k; i++ )
   queue.add(arr[i]);

for( ; i < arrLen; i++ )
{
  //Add the next element to the queue
  queue.add(arr[i]);

  //Extract the minimum element in the priority queue
  arr[i - k] = queue.poll();
}

This also makes the next section pretty readable;

for( i -= k; i < arrLen; i++ ) //convert i into sorted array index by removing the k offset
  arr[i] = queue.poll();

You should also initialize the PriorityQueue with the capacity you're going to need; that's k + 1.


MCU (Embedded C): Use nested if/elses or use an ugly function?

The variable names in both of those snippets are absolutely insane! But at least it seems clear on close inspection that ENA and DIS are abbreviations of "enable" and "disable." I would write those out.

I would rewrite the instructor's code like this:

typedef uint8_t EnableStatus;

void SPI_EnablePeripheralClock1(EnableStatus status) {
    if (status) {
        RCC->APB2ENR |= (1 << 12);
    } else {
        RCC->APB2ENR &= ~(1 << 12);
    }
}

void SPI_EnablePeripheralClock2(EnableStatus status) {
    if (status) {
        RCC->APB1ENR |= (1 << 14);
    } else {
        RCC->APB1ENR &= ~(1 << 14);
    }
}

void SPI_EnablePeripheralClock(SPI_RegDef_t *pSPI, EnableStatus status) {
    switch (pSPIx) {
        case SPI1: SPI_EnablePeripheralClock1(status); break;
        case SPI2: SPI_EnablePeripheralClock2(status); break;
        default: assert(false); break;  // what goes here?
    }
}

But it really depends on how this SPI_EnablePeripheralClock function is going to be used "upstream" in the caller. For example, why is EnableStatus a typedef for uint8_t instead of bool?

In fact, I would be tempted to write two convenience functions with English names:

void EnablePeripheralClock() {
    SPI_EnablePeripheralClock(&spi, true);
}
void DisablePeripheralClock() {
    SPI_DisablePeripheralClock(&spi, false);
}

Alternatively, it might make sense to refactor along those lines from the very beginning...

void EnablePeripheralClock() {
    switch (pSPIx) {
        case 1: RCC->APB2ENR |= (1 << 12); break;
        case 2: RCC->APB1ENR |= (1 << 14); break;
        default: assert(false);
    }
}

void DisablePeripheralClock() {
    switch (pSPIx) {
        case 1: RCC->APB2ENR &= ~(1 << 12); break;
        case 2: RCC->APB1ENR &= ~(1 << 14); break;
        default: assert(false);
    }
}

Here we're breaking down the code from the top down, focusing on "what task needs accomplishing" (e.g. "disable the clock"), rather than taxonomizing from the bottom up. Of course it's hard to know if we've done it right, when we don't know what top-level tasks need accomplishing. :)


It certainly looks clean and well-written.
Just one thing, I really hate horizontal scrolling. I acknowlege this site is very restrictive there though.

Make sure your use of move-semantics is type-appropriate:

Move if it's a move-only type.
Move if moveing is noexcept.
Otherwise, don't move it.

The standard-library already has to do that in many places, and thankfully it is available to the public as std::move_if_noexcept() analogous to std::move.

I suggest adding your own helper which does that for iterators.
You know, it's itching in my fingers to modify merge() to use the conditional operator. Especially after applying the above point, which makes the common part even bigger.
One of the advantages moveing is that it allows for guaranteed success in more cases. Yes, writing flexible and comprehensive noexcept-specifications can be a pain, but your callers will thank you.

Without doing that work, a good part of the advantage of the two-range version is lost.
I would suggest renaming your iterator-ranges source and target respectively, neither is properly scratch. Also, I would use the more common temp as a name in merge_sort(begin, end).
Are you aware of the sordid tale that is std::vector<bool>?
I'm not saying it won't work in this case, though slowly.
You do know that C++17 has class template argument deduction?
It's nice to see that you only use < for comparisons, just like the standard-library. That should enable you to easily modify your code to allow for a custom comparison-object.
But there is a problem in how you do the comparisons, as your merge() is needlessly not stable: If both are equal, you should take from the left range instead.
Consider asserting that the two iterator-types fit together in the function, or testing it for SFINAE outside.


Regarding the first task, you could save a couple of queries by modifying the code to look like this:

# ....

CSV.foreach('public/update/item_categories.csv', headers: true) do |row|
  row_hash = row.to_hash
  category = categories[row_hash['category'].to_i]

  item = Item.where(id: row_hash['id'])
  item.update_attributes!(category: category) unless item.nil?
end

# ....

You can retrieve the item once and perform update_attributes! without save!. update_attributes! saves the changes to the db using save! internally. Here's the source code (update_attributes! it's an alias for update!):

def update!(attributes)
  with_transaction_returning_status do
    assign_attributes(attributes)
    save!
  end
end

Regarding the second task, since you want to raise an exception in case of invalid record, you have to save each record individually but you can save some queries by finding records in batches. The code could look like this:

Item.find_each(category: nil) do |item|
  item.update_attributes!(category: 'misc')
end


iOS tableView with two special rows of headers

Defensive programming (never force unwrap, no forced cast, ...) is good
and important to handle "runtime problems" gracefully: Unexpected user
input, failed network connections, I/O errors, and many more.

But programming errors are a different category. Example 1: If

tableView.dequeueReusableCell(withIdentifier: cellIdentifierCover)

fails, or does not return a AddBlogCoverTableViewCell, then you did
not configure the table view correctly in the Storyboard. Such cases
should be detected during development. Therefore it is better to abort
with a runtime error instead of "hiding" the problem and returning
a plain UITableViewCell. This is a valid use-case for a forced cast:

 let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifierCover) as! AddBlogCoverTableViewCell

or better:

let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifierCover, for: indexPath) as! AddBlogCoverTableViewCell

Example 2: Your table view has 2 sections, so indexPath.section must be 0 or 1, every other value would be a programming error.
Again, fail early instead of hiding the problem:

switch indexPath.section {
case 0:
    // do something ...
case 1:
    // do something ...
default:
    fatalError("Unexpected section \(indexPath.section)")
}

Note also that your final

return UITableViewCell()

is never be executed.

Now for possible simplifications. Both cell classes have some properties
in common, these can be defined in a common superclass:

class AddBlogCommonCell : UITableViewCell {
    var indexPath: IndexPath!
    var delegate: UITableViewController!
    // ...
}

class AddBlogCoverTableViewCell : AddBlogCommonCell {
    // ...
}

class AddBlogTableViewCell : AddBlogCommonCell {
    // ...
}

Then you can configure the specific properties inside the switch
statement, and the shared properties outside the switch statement,
thereby avoiding the code repetition:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: AddBlogCommonCell
    switch indexPath.section {
    case 0:
        let coverCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifierCover) as! AddBlogCoverTableViewCell
        coverCell.titleTextField.delegate = self
        coverCell.coverImageView.image = coverImage
        // ...
        cell = coverCell
    case 1:
        let storyCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! AddBlogTableViewCell
        storyCell.captionTextView.delegate = self
        storyCell.captionTextView.tag = indexPath.row
        // ...
        cell = storyCell
    default:
        fatalError("Unexpected section \(indexPath.section)")
    }

    // AddBlogCommonCell properties:
    cell.delegate = self
    cell.indexPath = indexPath
    // ...

    // UITableViewCell properties:
    cell.layer.backgroundColor = UIColor.clear.cgColor
    cell.selectionStyle = .none
    // ...

    return cell
}


A Lisp version of the Schwartzian transform

What is not enough LISP-y in your function is the style used for the parentheses (they should not be left alone as last element of a line and they should be on the last line of the enclosed form). Another minor point is that you can use the shorter mapcar instead of map 'list.

Here is a version of your function (generalized for any function applied to the data and any predicate) which follows the more conventional style used in Common Lisp.

(defun schwartzian-transform (list costly-function predicate)
"sort a list of objects over the value of a function applied to them,
by applying the Schwartzian Transform (https://en.wikipedia.org/wiki/Schwartzian_transform)
the parameters are the list, the function, and the predicate for the sort."
  (mapcar #'cdr
          (stable-sort (mapcar (lambda (x)
                                 (cons (funcall costly-function x) x))
                               list)
                       predicate
                       :key #'car)))

(require :sb-posix)
(schwartzian-transform
 (directory "/etc/*")
 (lambda (x) (sb-posix:stat-mtime (sb-posix:stat x)))
 #'<=)


There's a redundant if branch:

if not any(separator in string for separator in separators):
    return int(string)

removing it still passes all the tests, because

re.split('|'.join(separators), string)

returns a list containing the list itself if there are no separators in the string.


Stack allocator and C11's alignment features

Is this the correct way of doing this kind of stuff? Any improvements I can make?

The role of member allocation_size is unclear.  It appears to represent the  raw alignment with h->allocation_size = s;.  Later use with stack_head = (char*)stack_head + h->total_size; could then result in an unaligned stack_head.  I recommend that void* memPush (size_t s) first take s and increment it as needed to an aligned size and then save that value in  allocation_size.  This will simplify subsequent code too especially the macro aligndown()

s = (s + alignof(max_align_t) - 1) & ~(alignof(max_align_t) - 1u);

There is no protection against pushing too much.  I'd expect the size of memory available with stack_head to be provided and memPush() to code against overflow.  In any case, OP should provide documentation concerning what happens when too much memory is requested.
There is no clear functionality against popping too much.  I'd expect either an error return or a perhaps the equivalent of the top allocation having size 0.
Some compilers will warn about mixed signed/unsigned math.
As the return type from alignof() is some unsigned type, use unsigned constants throughout.

//alignof(max_align_t) - 1
alignof(max_align_t) - 1u

The name stack_head is a global object that could easily collide with other code.  Its name does not suggest that is is part of the memPop(), memPush() functions.  Recommend a name aligned with the funcitons like mem_stack_head.
A use of memPush(0) needs special consideration.  I recommend that such usage returns the same as memPush(alignof(max_align_t)) to provide unique allocations.  In any case, OP should provide documentation concerning the special case.
uintptr_t is an optional type and not the best to use here.  (char*)head - (char*)h results in type ptrdiff_t, simply cast it to the destination type.
Alternative:

//h->total_size = (uintptr_t)((char*)head - (char*)h);
h->total_size = (size_t)((char*)head - (char*)h);

Code could reduce explicit coding of cast (char *) by using char *head = stack_head;
Alternative idea to this line of code:

// struct Mem_Stack_Header *h = (struct Mem_Stack_Header*)((char*)mem - sizeof(*h));
struct Mem_Stack_Header *h = (struct Mem_Stack_Header*)mem - 1;

A simple test harness would help in evaluation of this code.
alignof is not valid without #include <stdalign.h>.  Other include files missing too.


Web scraper for parsing names and email addresses from Yellowpage

Here is the summary of the applied improvements:

keeping a visited set of links - \$O(1)\$ lookups
using collections.deque() to keep the queue of the next links to scrape - popping left from it is \$O(1)\$
reusing the same requests.Session() instance, keeping a session instance as an instance variable of your crawler class
using urljoin() to join the base url and the relative url
collecting both pizza shop links and the next page links into a single list and process that list once
removing the loop when extracting a pizza shop profile page information
put the main execution logic to under the if __name__ == '__main__':

Improved code:

from collections import deque
from urllib.parse import urljoin

import requests
from lxml import html

class YellowPage:
    base_url = "https://www.yellowpages.com"
    main_url = "https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=Los+Angeles%2C+CA"

    def __init__(self):
        self.session = requests.Session()
        self.session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}

        self.visited = set([])
        self.links = deque([self.main_url])

        self.storage = []

    def crawl(self):
        while self.links:
            link = self.links.popleft()
            self.scrape(link)

    def scrape(self, link):
        if link in self.visited:
            return

        self.visited.add(link)
        print('Scraping Now: ' + link)

        response = self.session.get(link)
        tree = html.fromstring(response.text)

        # extracting the follow up links
        pizza_shop_links = tree.xpath("//div[@class='info']//a[@class='business-name'][not(@itemprop='name')]/@href")
        next_page_links = tree.xpath("//div[@class='pagination']//li/a/@href")
        links = pizza_shop_links + next_page_links

        for link in links:
            link = urljoin(self.base_url, link)
            if link not in self.visited:
                self.links.append(link)

        # going to the main page of each pizza shop and harvest the record
        is_pizza_shop_page = tree.xpath("//*[@id='main-header']/article")
        if is_pizza_shop_page:
            name = tree.findtext(".//div[@class='sales-info']/h1")
            try:
                email = tree.xpath(".//a[@class='email-business']/@href")[0]
            except IndexError:
                email = ""
            self.storage.append((name, email))

    def __str__(self):
        return self.storage

if __name__ == '__main__':
    crawler = YellowPage()
    crawler.crawl()
    for item in crawler.storage:
        print(item)

(not tested)


This is relatively simple solution you have here and it could in theory work, but in my experience in a real word you need something more flexible. Also you dont think about redundancy of the data.
What if a doctor for example works only one day in a week. Most of the columns would then be empty. Or if a doctor can work only in the morning? Then there would be no break_start or end in any of the calendar fields. What if, for example, the doctor works every second week? Then you will not have an easy way how to store this information. Also there would be a lot of redundant information. If you will have each doctor working from 8:00 AM to 4:00 PM, you will have this data stored there redundantly. Much less space is needed, if you can store such information as a relation to some kind of duration record.
If I were you, I would create more generic design where you can store up to 365 records (for each day in the year), for each calendar. Then each day would have a relation to a list of intervals, that could later be of required activity. That way you would end up with more flexible design.
The draft could look something like this:
class Calendar(models.Model):
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)
    clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)

class CalendarDay(models.Model):
    date = model.DateField()
    calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE)

class TimeInterval(models.Model):
    activity = models.Integer(choices = [(1, 'Working'), (2,'Lunch Break'), (3, 'Afternoon Break') ...])
    start = models.TimeField()
    end = models.TimeField()
    calendar_day = models.ForeignKey(CalendarDay, on_delete=models.CASCADE)

In order to ensure data integrity, then you could add an unique constraint on the combination of date and calendar columns in the CalendarDay table. That way each calendar can have only one record for particular date in the CalendarDay table.


Entity collection best practice (separation of concerns, dependency injection, ...)

Design

Dependency injection is very useful when you have multiple implementations of a given dependency. If you don't plan implementing another Validator, then it's probably premature abstraction. I'll assume here that you have other Validator implementations.

Let me answer your questions:

The separation itself is good.
An exception is meant to be catched "whenever possible", and it is not possible in WorldCollection, since you don't know how to handle it. You need to wonder what you want your application to do when the data does not validate.

If you want WorldCollection::offsetSet to not do anything when the validation fails, then WorldValidator::validate should simply return true or false, and no exception should be thrown.

If the exception is to be catched later on in the code, then don't do anything in WorldCollection::offsetSet, since another code will take care of the issue.

You can easily mix those two approaches in order to catch some of the exception at some point, and other ones later on (which means WorldValidator::validate should always throw an exception, and return nothing).
Only if you plan on having other WorldCollections. I don't think so.
LogicException should only be launched if there is a flow in your program, ie. an exception that would never be thrown in a perfect program. RuntimeException is a base class used for errors such as OutOfBounds or Overflow. I'd use InvalidArgumentException.
I didn't understand the question. Note that instanceof is never good design, and exists to work around design errors.
ArrayAccess is a reasonable choice, it lets you do foreach on your data easily, whereas with Iterator you would have to implement a ton of methods. SplObjectStorage could be used, but only if you don't need the keys ArrayAccess provides.

Implementation

Do you want only one exception with different types, such as ERROR_CODE_INVALID_TYPE?

Why don't you use multiple exceptions?
If you want to stick with one exception, don't pass "invalid type" in the constructor, since it is always going to be the same message. Prefer to override Exception::__toString() to return "invalid type" when the type is ERROR_CODE_INVALID_TYPE.

Use offsetExists in offsetGet instead of repeating yourself?
Consider using NULL instead of null, and TRUE instead of true, even if they are case-insensitive.
$this->oValidator->validate($value) forgot a semicolon?
Don't use return if you're not going to check the return value.


Conditional jump or move depends on uninitialised value

Some general remarks to your code:

You should store the string length as a variable rather than calling it multiple times.
If you do strncpy(test, some_text, strlen(some_text) + 1) you can get rid of the strcat as strncpy will padd the remainder with \0 if src is less than n characters.
You don't need to test for NULL before free

a) because you'd get a segfault anyway before that line of code if it were NULL
b) because the standard guarantees that it is safe to call free(NULL)


Search for ways in OpenStreetMap extract

Introduction

Unfortunately imposm is just for Python 2, my project is in Python 3. I think lxml library looks promising. I wrote simple code to test it, right now it is based on just 2 nodes.

Picture of nodes

I attach picture from XML file so one can see what I am dealing with.

How it works

It is iterating over l_id (which is list of ids) using etree.parse and findall.

First inner loop gathers dictionary where given id is.

Second inner loop gathers dictionary where chosen value is.

Loop for dict_ids_all appends to new list only ids from dictionary.

Loop for dict_ids_all appends to new list only value from dictionary.

My code

tree = lxml.etree.parse(r'path to xml')
l_dict_ids_all = []
l_dict_values_all= []
l_only_id =[]
l_only_values = []
l_id = ['"35121262"', '"35121263"']
name = '"name"'

for id in l_id:
    for tag in tree.findall('//node[@id={0}]'.format(id)):
        l_dict_ids_all.append(tag.attrib)

    for tag in tree.findall('//node[@id={0}]//tag[@k={1}]'.format(id,name)):
        l_dict_values_all.append(tag.attrib)

#printing is only for review purpose

print('Full id dict')
print(l_dict_ids_all)

print('Full Value dict')
print(l_dict_values_all)

print('Only ID list')
for element in l_dict_ids_all:
    l_only_id.append(element['id'])
print(l_only_id)

print('Only Value list')
for element in l_dict_values_all:
    l_only_values.append(element['k'])
print(l_only_values)

Output

  Full id dict

  [{'id': '35121262', 'visible': 'true', 'version': '17',
  'changeset': '41419943', 'timestamp': '2016-08-12T22:24:23Z', 'user':
  'kocio', 'uid': '52087', 'lat': '52.1560439', 'lon': '21.0346808'},
  {'id': '35121263', 'visible': 'true', 'version': '16', 'changeset':
  '41419943', 'timestamp': '2016-08-12T22:24:20Z', 'user': 'kocio',
  'uid': '52087', 'lat': '52.1492285', 'lon': '21.0461042'}]

  Full Value dict [{'k': 'name', 'v': 'Stokłosy'}, {'k': 'name', 'v': 'Imielin'}]

  Only ID list  ['35121262', '35121263']

  Only Value list  ['name', 'name']

What I tried

I am aware that creating list and using it to append items to new list is wrong, but whenever I tried something like this:

l_dict_ids_all.append(tag.attrib[0]['id'])

Received an error :

  TypeError Traceback (most recent call)

  ipython-input-91-8b0a49bc5f35 in ()
        7 for id in l_id:
        8     for tag in tree.findall('//node[@id={0}]'.format(id)):
  ----> 9         l_dict_ids_all.append(tag.attrib[0]['id'])
       10
  src/lxml/etree.pyx in lxml.etree._Attrib.getitem()

  src/lxml/apihelpers.pxi in lxml.etree._getAttributeValue()

  src/lxml/apihelpers.pxi in lxml.etree._getNodeAttributeValue()

  src/lxml/apihelpers.pxi in lxml.etree._getNsTag()

  src/lxml/apihelpers.pxi in lxml.etree.__getNsTag()

  src/lxml/apihelpers.pxi in lxml.etree._utf8()

  TypeError: Argument must be bytes or unicode, got 'int'

My goal/problem

Code is working, but I want to make it better.
I need to get rid of 2 out 4 lists which I create at the begging.


As you suggested, you have a lot of redundant code. And rightfully so you want to adhere to the DRY principle.

All these input methods have the same pattern internally..

static void Main(string[] args)
{
    GetWeightInput();
    GetHeightInput();
    GetWidthInput();
    GetDepthInput();

    Console.ReadLine();
}

Road to DRY

..ideally you would like to be able to call them like this:

static void Main(string[] args)
{
    var weight = AskInteger("Enter weight of parcel: ");
    var height = AskInteger("Enter height of parcel: ");
    var width = AskInteger("Enter width of parcel: ");
    var depth = AskInteger("Enter depth of parcel: ");

    Console.WriteLine("press any key to terminate the application..");
    Console.ReadKey(true);
}

Advanced road to DRY

Or if you would provide a complex object Request with 4 properties and a lambda to provide both a message to the user as a setter expression to materialise the request:

static void Main(string[] args)
{
    var request = new Request();
    AskInteger(request, x => x.Weight);
    AskInteger(request, x => x.Height);
    AskInteger(request, x => x.Width);
    AskInteger(request, x => x.Depth);

    Console.WriteLine("press any key to terminate the application..");
    Console.ReadKey(true);
}

How you would implement AskInteger is a challenge I leave to you.

Misc

Don't pollute your code with regions that have no added value.  #region User Weight Input Validation
Try to avoid meaningless comments _isInvalidInput = true;//reset value to true


It is hard to improve on Jesse's answer (there are only so many ways to write this method), but I will add my alternative, which is a matter of style. I personally tend to not use var in place of any of the built-in types listed here: http://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx it does not save me any more space than writing "don't" instead of "do not".

I also do not like it when the lines get too long, particularly ones that involve the ternary operator, so here is my version (assuming public modifier):

public static int DefaultDaysToSynch()
{
    int month = Properties.Settings.Default.StatsMonth;
    int year = Properties.Settings.Default.StatsYear;
    var now = DateTime.Now;
    bool isTargetMonth = (year == now.Year) && (month == now.Month);
    return isTargetMonth ? now.Day : DateTime.DaysInMonth(year, month);
}

In general I highly recommend runnign StyleCop and listening to it, except for the line bool isTargetMonth = (year == now.Year) && (month == now.Month); - keep those parenthesis.
Btw, I am pretty sure that the C# compiler can handle that bool variable efficiently. The descriptive variable name also reduces (though maybe not completely) the need for a comment.

The comment would have to pass the StyleCop's standard if I wrote it out, but I am too lazy, sorry. There is not much to write really, because it does not take any arguments.

I am not a huge fan of the input values being read directly from settings - it makes this function harder to test, it makes it less "functional" as in functional style, it also allows for bad input (such as year -2598, month # 455) to go unnoticed. I would rather pass both values into the function like so:

public static int DefaultDaysToSynch(int targetYear, int targetMonth)
{
    CheckYear(targetYear);
    CheckMonth(targetMonth);
    var now = DateTime.Now;
    bool isTargetMonth = (targetYear == now.Year) && (targetMonth == now.Month);
    return isTargetMonth ? now.Day : DateTime.DaysInMonth(year, month);
}

// You will need to catch this at the right place.
// This is lengthy, I know, but makes a decent exception message.
private static CheckMonth(int monthNumber)
{
    if (monthNumber >= 1 && monthNumber <= 12)
    {
        return;
    }

    string exceptionMessage = String.Format(
        "Month number must be between 1 and 12 but it was {0}.",
        monthNumber);

    throw new ArgumentOutOfRangeException(
        paramName: "monthNumber",
        actualValue: monthNumber,
        message: exceptionMessage);
}

// Similar implementation for CheckYear


Assuming the dataToTransfer is always the same for a specific device, you can create this data in init()

class NearFieldManager {
    static let shared = NearFieldManager()
    private let dataToTransfer: Any

    private init() { //private to forbid instantiation
        self.dataToTransfer = methodToCreateDeviceData()
    }
}


As there is only two states, up and down, we can leave out .expand-up and let it be the default state. I refactored the css and js code to just add and remove the expand-down class, for the .css file,

body {
    font-size: 62.5%;
    font-family: 'Roboto', sans-serif;
    color: #FFF;
}
.filter-search {
    background-color: #a78464;
}
.filter-search .wrapper {
    width: 100%;
    text-align: center;
    height: 10em;
    transition: height linear 1s;
}
.filter-search .wrapper .title-wrapper {
    display: inline-block;
    animation-fill-mode: forwards;
    animation-duration: .5s;
    -webkit-animation-fill-mode: forwards;
    -webkit-animation-duration: .5s;
}
.filter-search .wrapper .title-wrapper.expand-down {
    -webkit-animation: moveDown ease-out 1;
    animation: moveDown ease-out 1;
}
.filter-search .wrapper .title-wrapper h2 {
    font-size: 3em;
    margin-bottom: 0;
}
.filter-search .wrapper .title-wrapper span {
    font-size: 1.4em;
    display: block;
    text-transform: uppercase;
    margin-bottom: 2em;
}
.filter-search .wrapper.active {
    height: 15em;
    transition: height linear 1s;
}
@-webkit-keyframes moveUp {
    0% {
        margin-top: 0;
    }
    to {
        margin-top: -1em;
    }
}
@keyframes moveUp {
    0% {
        margin-top: 0;
    }
    to {
        margin-top: -1em;
    }
}
@-webkit-keyframes moveDown {
    0% {
        margin-top: -1em;
    }
    to {
        margin-top: 0;
    }
}
@keyframes moveDown {
    0% {
        margin-top: -1em;
    }
    to {
        margin-top: 0;
    }
}

and for the .js file I changed click() to on(), in case the element will be added dynamically, click() would not work. Also assigning variable filterSearch earlier in the function, there should be no need to find the children with each click,

$(document).ready(function() {
    $('#filter-search').on('click', '.title-wrapper', function() {
        var filterSearch = $(this);

        filterSearch.parent().toggleClass('active').delay('1500').promise().done(function() {
            if (filterSearch.hasClass('expand-down')) {
                filterSearch.removeClass('expand-down');
            } else {
                filterSearch.addClass('expand-down');
            }
        });
    });
});


I also don't code in C#, but if I'm right the following is the same in Java:

public static int find(final String term, final String text) {
    int found = -1;
    int termIndex = 0;

    for (int textIndex = 0; textIndex < text.length(); textIndex++) {
        if (term.charAt(termIndex) == text.charAt(textIndex)) {
            if (termIndex == term.length() - 1) {
                return found;
            }
            if (termIndex == 0) {
                found = textIndex;
            }
            termIndex++;
        } else {
            termIndex = 0;
            found = -1;
        }
    }
    return found;
}

Unfortunately, it does not seem to work. Here are some test cases:

assertEquals("#0", 3, find("de", "abcde")); // OK
assertEquals("#1", 1, find("a", "ababaa")); // fails, returns -1
assertEquals("#2", 1, find("ba", "ababaa")); // OK
assertEquals("#3", 2, find("abaa", "ababaa")); // fails, returns -1
assertEquals("#4", 2, find("abaa", "ababaacc")); // fails, returns -1


That's a reasonable implementation if you want to use Writer. Keep in mind that Writer is lazy in the monoid, so you can end up with a space leak.

Also, bubblesort doesn't look at the last element after the first iteration, e.g.

for i = N to 1
  for j = 1 to i - 1                    -- <<
    if data[j] > data[j + 1]
      swap data[j] data[j + 1]

Either way, as an exercise, I suggest you to write bubblesort and bubblesort' without Writer.

Note that Mergesort is a lot simpler to implement in Haskell.


Good job!

A few notes:

It is better to check for a malloc error right away instead of going to another function to check. Just like what you did with realloc.
Your function read_until_deliminator
returns an error but your implementation never checks for this error return
value.
I will do separation of concern, where you will obtain the input and find the delimiter in different functions. This is just to aid in code maintenance so it helps with readability for you and others.

I will post my changes later in the day.


Your approach is far too complicated.

In checkEvenOrOdd() you create a ArrayList<Integer> containing
zeros or ones.
In search() you create an Integer a[] from that list.
Then you iterate over the array and count the number of zeros or ones.

You can iterate over int[] integers directly to find the number of odd (or even) entries:

    int oddCount = 0;
    for (int n : integers) {
        if (n % 2 != 0) {
            oddCount += 1;
        }
    }

Note how a "enhanced for statement" can be used to iterate over
the array elements, instead of a for-loop or a while-statement for
the array indices, as in your code.

There is also no need to use a double result or floating point literals
when doing an integer remainder calculation.

    if (counter == 1)
        return true;
    else
        return false;

can be simplified to

    return (counter == 1)

But in this case the entire logic can be put into a single function,
e.g. like this:

public static int find(int[] integers) {

    int oddCount = 0;
    for (int n : integers) {
        if (n % 2 != 0) {
            oddCount += 1;
        }
    }

    if (oddCount == 1) {
        for (int n : integers) {
            if (n % 2 != 0) {
                return n;
            }
        }
    } else {
        for (int n : integers) {
            if (n % 2 == 0) {
                return n;
            }
        }
    }
    return 0;
}

Then one could try to avoid the code repetition for the even/odd
case.

But actually I would suggest a completely different, more efficient  approach:

Check the first two array elements if they are even or odd.
If they are both even, the outlier can be found
by search for the first odd element, starting at index 2.
If they are both odd, the outlier must be even, and can be found
similarly.
If the first two array elements have different parity, one of
them is the outlier. Which one, can be determined by checking the third
array element.


Simple streaming parser to extract lines

This looks like they used to be fields and then you made them properties:

public readonly string Delimiter;
public readonly LineReader Reader;

IMHO that means they should get a getter and setter, like this:

public string Delimiter { get; private set; }
public LineReader Reader { get; private set; }

String.LastIndexOf is culture-specific, so consider using a StringComparison.


QuickSort C++ Implementation using Iterators

Templates

Sorting is pretty much the same regardless of the type of items being sorted, as long as you can compare and swap those things. Might as well implement the sorting and partitioning as templates so they can work for various containers and/or types in the containers.

Pass only what's needed

Right now, your quicksort receives the container to be sorted as a parameter. It also receives iterators referring to the beginning and end of the range to be sorted. It "uses" the container parameter only to pass it in further recursive calls--but none of the calls ever actually makes any real use of that parameter.

The parameter is never used, so you might as well not pass it.

At the same time, sorting an entire collection is common enough that it may well be worthwhile to provide that directly. For example:

// basic version that uses (only) iterators
template <class Itr>
void quicksort(Itr b, Itr e) {
    if (std::distance(b, e) > 1) {
        Itr pivot = partition(b, e);
        quicksort(b, pivot);
        quicksort(pivot, e);
    }
}

// Version to sort a whole container
template <class Container>
void quicksort(Container &c) {
    quicksort(c.begin(), c.end());
}

Don't explicitly specify std::swap

If the user has defined a swap for the type of object being sorted, you want to use it. You only want to use std::swap if they haven't defined it. To do that, you typically have a using directive to make std::swap visible in the current scope, then make an unqualified call to swap. If they've defined a swap for their type, this will find their swap via argument dependent lookup. Then, if (and only if) that fails, it will find std::swap.

if(*it<=*right)
{
    using std::swap;
    ++i;
    swap(*i,*it);
}

Decide what to support

Right now, you use std::distance to measure the distance between a pair of iterators. That lets the code work with most categories of iterators.

Unfortunately, you also use iterator + int, and that only works with random access iterators, so the code overall only works with random access iterators.

If you don't mind requiring random access iterators, then you might as well depend on them throughout, and just subtract iterators to get a distance.

Conversely, if you really want the code to work with other iterators, you should truly support that, such as by using std::advance or std::next to modify the pointers.

Minimize requirements on the contained type

Quicksort can be written so the only comparison it depends upon is operator<. Right now you use <= for no particularly good reason that I can see.


Creating unique names for uploaded images

It looks like your code works fine, so these comments are my opinion on how I would handle this if I were in your shoes.

This is a pretty standard requirement. Users upload images, and you want to save them with a filename that is (a) unique, and (b) won't cause you grief down the road with funny characters in the file name.

You also need to handle the case where people upload files with the same name over and over again, without creating duplicates.  For instance, for a certain model of camera the first photo on the "camera roll" might always have the same name. Several people might own the same model of camera. Or, dissatisfied with the results of uploading an image, the user edits it locally and uploads a fresh copy. With the same file name as before.

The simplest solution is to skip all the md5 and uniqid() stuff, and simply add a record to a database which has an auto-increment ID field. You would add the original name of the image to the database (for future reference, tooltip etc), but not the name of the file on disk. Once you get the new ID, you copy/move/rename the image file based on the new ID. This gives you nice short, simple file names.

I think this is tidier than inventing a unique file name before adding the database record. Databases have a built-in unique ID feature, so you can get a unique ID "for free!" with each new record. Why invent your own?

If the name of the image file ends up being used in URL's, so you don't want it to be easily guessable, then you want to mess up the file name to make it more complicated. If this is the case, you are better off placing the files where they are not accessible directly via URL.

If you, as an administrator, want to be able to browse through the image files and have the names make sense, or if you want the image names to appear in the URL to assist visitors or for SEO or Google Image search benefits, then you may want to name the images like blog post titles, i.e. simple lower-case-hyphen-separated words with a unique ID on the end. There is lots of code around that will do that for you. (I've got code if you can't find it elsewhere).


It runs in \$O(n)\$ time so I'm not sure there's a way to improve this.  It looks like you've implemented the algorithm pretty well, according the Fisher-Yates shuffle.

You might consider not using Object if you can use the type that's stored in the array instead.

I also thought I read somewhere that it should be safe to loop to \$n/2\$ instead of \$n\$ (because you're swapping with elements from \$1 \cdots n\$ so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)


Most efficient way to insert into ordered sequence

Fundamentally, you should probably use the array's own ordering. It'd remove the need for a sequence number that you manually have to track and update. Instead, you can simply pluck index 3 out of the array, and splice it in at index 1, and not worry about sequence numbers at all.

But if you can't/won't get the data.dashboards array to behave like that, you can take a detour.

Now, I highly, highly doubt this is the most efficient way of doing things - it's certainly not elegant - but it's straightforward to follow.

Say you have this:

var data = {
    dashboards: [ // random ordering
        {name: "Development", sequence: 3},
        {name: "Sales", sequence: 0},
        {name: "Finance", sequence: 2},
        {name: "Admin", sequence: 1}
    ]
};

Get everything sorted first:

var sorted = data.dashboards.sort(function(a, b) {
    return a.sequence - b.sequence;
});

So now we have an array where the objects are ordered according to their sequence

seq | name
------------------
0   | Sales
1   | Admin
2   | Finance
3   | Development

Then, if we can assume that the sequence numbers are indeed sequential with no gaps or repeats, we could (again) just splice & splice to get the right order.
But let's say we can be sure that index equals sequence number. In that case, loop until we find it, pluck it, and reinsert it:

var currSequence = 3, // the target's current number
    newSequence  = 1, // the target's desired number
    dashboard;

// find and move the target
for( var i = 0, l = sorted.length ; i < l ; i++ ) {
    if( sorted[i].sequence === currSequence ) {
        dashboard = sorted[i];
        sorted.splice(i, 1); // remove the target
        sorted.splice(newSequence, 0, dashboard); // re-insert it at its new position
        break;
    }
}

Now, we have the right order, but not the right sequence numbers:

seq | name
------------------
0   | Sales
3   | Development
1   | Admin
2   | Finance

Finally, reset the sequence numbers

for( i = 0, l = sorted.length ; i < l ; i++ ) {
    sorted[i].sequence = i;
}

And we get

seq | name
------------------
0   | Sales
1   | Development
2   | Admin
3   | Finance

Neatly sequential numbering and ordering, regardless of the original array's order and sequence values. The original data.dashboards array is still in the same scrambled order as before, but the sequence number of each object is now correct.

Here a jsfiddle

Actually, here's a simpler one that I believe works in all cases, regardless of array ordering, as long as the sequence numbers are sequential already:

var currSequence = 3, // the target's current number
    newSequence  = 1, // the target's desired number
    correction = currSequence > newSequence ? 1 : -1,
    lower = Math.min(currSequence, newSequence),
    upper = Math.max(currSequence, newSequence),
    dashboard;

for( var i = 0, l = data.dashboards.length ; i < l ; i++ ) {
    dashboard = data.dashboards[i];
    if( dashboard.sequence == currSequence ) {
        dashboard.sequence = newSequence;
    } else if( dashboard.sequence >= lower && dashboard.sequence <= upper ) {
        dashboard.sequence += correction;
    }
}

Here's a demo


Make the awt.Color class constructors except out of range arguments

There is nothing too bad about this, and it is an acceptable pattern to get rid of extra/boilerplate code (for example IOUtils from Apache Commons has a closeQuietly for streams that takes a way a lot of the nested try-catch-finally madness for closing streams).

However, I would argue that it is better to validate your inputs to make sure that they don't exceed the ranges, or at least change the code that generates your values to ensure that they do not generate invalid values.

For example, you could have a method called generateColor(speed) that returns a sane Color instance.

I would also suggest using Math.max and Math.min in this method  instead of using a bunch of ifs.


First of all, this class is not immutable at all. You can modify both the head and the tail at any given node in the list from calling code. Here are some quick fixes to make the list immutable:

public class ImmutableList<T> : IEnumerable<T>
{
    private static readonly ImmutableList<T> _Empty = new EmptyList<T>();

    private readonly T _Head;

    private readonly ImmutableList<T> _Tail;

    public static ImmutableList<T> Empty
    {
        get
        {
            return _Empty;
        }
    }

    public T Head
    {
        get
        {
            return this._Head;
        }
    }

    public ImmutableList<T> Tail
    {
        get
        {
            return this._Tail;
        }
    }

    protected ImmutableList(T head, ImmutableList<T> tail)
    {
        this._Head = head;
        this._Tail = tail;
    }

    public static ImmutableList<T> WithItems(IEnumerable<T> items)
    {
        return (items == null) || (!items.Any())
            ? _Empty
            : (items.Count() == 1
                ? new ImmutableList<T>(items.Single(), _Empty)
                : new ImmutableList<T>(items.First(), WithItems(items.Skip(1))));
    }

    public ImmutableList<T> Add(T item)
    {
        return this == _Empty
            ? new ImmutableList<T>(item, _Empty)
            : new ImmutableList<T>(this._Head, this._Tail.Add(item));
    }

    public IEnumerator<T> GetEnumerator()
    {
        if (this == _Empty)
        {
            yield break;
        }

        yield return this._Head;
        foreach (var elem in this._Tail)
        {
            yield return elem;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    private sealed class EmptyList<TU> : ImmutableList<TU>
    {
        public EmptyList() : base(default(TU), null)
        {
        }
    }
}

The calling code needs to change ever so slightly to accommodate:

var list2 = ImmutableList<int>.Empty.Add(1).Add(2).Add(3).Add(4);

You'll also note I added a null and empty sequence check in the WithItems static method. This simply allows any null/empty sequence call to return an empty list.


Selecting a thumbnail from among a large, medium, and small image

var thumb = (images == null)
            ? null
            : (images.small == null) || (images.small.Length == 0)
                ? (images.medium == null) || (images.medium.Length == 0)
                    ? (images.large == null) || (images.large.Length == 0)
                        ? null
                        : images.large[0]
                    : images.medium[0]
                : images.small[0];

  I understand it but

no one else does ;-)

Ternary operators are very usefull but you really exaggerated. In a production code I would never accept it.

You should break it to smaller pieces.

  is there a better (i.e. easier to understand) way to express the overall algorithm?

There might be. If the images type is under your control then you could implement the IEnumerable interface on it and return the sub-image collections:

class ImageCollection : IEnumerable<Bitmap[]>
{
    public Bitmap[] small { get; set; }
    public Bitmap[] medium { get; set; }
    public Bitmap[] large { get; set; }

    public IEnumerator<Bitmap[]> GetEnumerator()
    {
        yield return small;
        yield return medium;
        yield return large;
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

Then with a small helper lambda you can encapsulate the first-image-or-default logic and use linq to retrieve the first image found:

var images = new ImageCollection();
var getFirstImageOrDefault = new Func<Bitmap[], Bitmap>(
    bitmaps => bitmaps == null ? null : bitmaps.FirstOrDefault());
var thumb = images.Select(getFirstImageOrDefault).FirstOrDefault(bitmap => bitmap != null);


Disclaimer: I write the review as I go - I haven't performed any optimisation yet but this may be useful to you or other reviewers.

Your code is well organised, having the actual algorithm in a function on its own, away from the logic handling input/ouput. This is a great habit (usually not done properly for programming challenges) and is much appreciated :-)

Adding tests

Before doing any changes to your code, I'd rather start by writing a few tests. This can also be useful later on to use them for benchmarks and check that optimisations do make things faster.

Here, this is an easy task because of the way you've written the code and because examples are provided.

I tend not to bother with unit-tests frameworks for such small tasks but this is a good occasion to give them a try if needed.

def unit_tests_num_nonoverlapping():
    classes, exp = [(1, 3), (3, 5), (5, 7), (2, 4), (4, 6)], 12
    ans = num_nonoverlapping(classes)
    assert ans == exp
    classes, exp = [(500000000, 1000000000), (1, 500000000), (1, 500000000)], 5
    ans = num_nonoverlapping(classes)
    assert ans == exp
    classes, exp = [(999999999, 1000000000)], 1
    ans = num_nonoverlapping(classes)
    assert ans == exp

def unit_tests_format_ans():
    assert "00000000" == format_ans(0)
    assert "00000005" == format_ans(5)
    assert "00000054" == format_ans(54)
    assert "00000540" == format_ans(540)
    assert "00005400" == format_ans(5400)
    assert "00054000" == format_ans(54000)
    assert "00540000" == format_ans(540000)
    assert "05400000" == format_ans(5400000)
    assert "54000000" == format_ans(54000000)
    assert "40000000" == format_ans(540000000)
    assert "00000000" == format_ans(5400000000)

def unit_tests():
    unit_tests_num_nonoverlapping()
    unit_tests_format_ans()

def io_test():
    while True:
        n = int(input())
        classes = []
        if n == - 1:
            break

        for _ in range(n):
            start, end = map(int, input().split())
            classes.append((start, end))

        ans = num_nonoverlapping(classes)
        print(format_ans(ans))

unit_tests()
# io_tests()

Improving format_ans

This is most probably not the place where we can get much performance improvements but it is a good place to learn a few additional techniques.

First thing I did was to define the number of digits wanted as a argument with default value 8 so that we do not break already existing behavior but we do get rid of the "8" magic number everywhere.

Using modulo, you can get the last 8 digits without getting into string manipulation.

def format_ans(ans, nb_dig=8):
    s = str(ans % 10**nb_dig)
    return (nb_dig-len(s)) * "0" + s

Python already defines a few builtin functions which you can use for a more concise solution. Here, we could use: str.zfill:

def format_ans(ans, nb_dig=8):
    return str(ans % 10**nb_dig).zfill(nb_dig)

You could probably use other string formatting functions but I think this is explicit enough.

Improving num_nonoverlapping

Due to the limits provided by the problem description, we have to expect a huge numbers of classes. This means that a fast solution will probably come from a great algorithm rather than micro-optimisations.

Your algorithm seems good.

At the moment, I have nothing better to suggest.


Proper error handling

Never, ever do something like this:

try:
    ...
except:
    ...

It's a horrible idea, for a couple of reasons:

It will catch every error, even the ones you don't want to catch.
Rare, nasty errors like a SystemError, will be caught, and ignored as well. Stuff like NameErrors, and even SyntaxErrors will be caught.
It's not very clear to the reader of your code, what you're trying to prevent.

For more info, see this Stackoverflow question.

Proper error logging

You have a lot of except: passes in your code. It's never helpful to the user, or even the programmer in some cases, if you don't get output when an error is caught. You could use the logging module, or write error output to a file, while informing the user in some way, that something went wrong.

Style

From looking at your code, you only appear to have two style violations:

Function names should be in snake_case.
Lines should be limited to 79/80 characters.

If you want to be sure, you can always check PEP8, Python's official style guide, to ensure that everything is correctly styled.


Better way than setInterval to wait for an image load?

"Must wait for the image to load" ... "Is there a nicer way?"

Yes,
At first, instead of accessing the image by index el[0] - extract the image at once and give the variable meaningful name:

let img = document.querySelectorAll('#comic img')[0];

Next, you need to embed "load" event listener into Promise executor function to ensure the image has loaded:

let loadPromise = new Promise(function(resolve, reject) {
    img.addEventListener('load', function() {
       resolve();
    });
    setTimeout(() => {
        if (!img.complete) reject('Timeout');
    }, 5000)
});
loadPromise.then(() => {
    console.log(img.naturalWidth);
    let container = document.querySelectorAll('.main-wrapper > div > section > section.column.column-1.grid-left-4.grid-width-16');
    container[0].style.width = (img.naturalWidth + 420) + 'px';
});


The first thing to do is to profile your code. Hashcash is really designed to make you perform 2^20 hashes: if you do more work than those hashes, something's wrong!

Profiling

python -m cProfile -s cumtime original.py

Let's look at all the places where the algorithms spends more than 0.001 seconds (I've asked for 15 bits since 20 bits is too slow on my computer) :

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1414287    4.087    0.000    7.665    0.000 original.py:12(<genexpr>)
  1414287    2.433    0.000    2.433    0.000 {format}
   134695    1.737    0.000    9.402    0.000 {method 'join' of 'str' objects}
  1346940    1.295    0.000    1.295    0.000 {ord}
        1    0.886    0.886   12.709   12.709 original.py:5(mint)
    67347    0.536    0.000    0.969    0.000 base64.py:310(encodestring)
    67347    0.432    0.000    0.432    0.000 {posix.urandom}
    67347    0.258    0.000    1.292    0.000 base64_codec.py:13(base64_encode)
    67347    0.231    0.000    1.525    0.000 {method 'encode' of 'str' objects}
    67348    0.141    0.000    0.141    0.000 {_hashlib.openssl_sha1}
    67347    0.131    0.000    0.131    0.000 {method 'digest' of '_hashlib.HASH' objects}
   134694    0.131    0.000    0.131    0.000 {len}
    67347    0.126    0.000    0.126    0.000 {binascii.b2a_base64}
    67348    0.110    0.000    0.110    0.000 {range}
    67347    0.109    0.000    0.109    0.000 {method 'replace' of 'str' objects}
    67347    0.066    0.000    0.066    0.000 {method 'append' of 'list' objects}
        1    0.001    0.001    0.001    0.001 hashlib.py:55(<module>)
        1    0.001    0.001    0.001    0.001 base64.py:3(<module>)

This specific run took 12.7 seconds (original.py:5). It spent 4 seconds in the for x in ... generator, 2.4 seconds in format(ord(x), '08b'), 1.7 seconds in ''.join(...), and 1.3 seconds in ord(x).

That's a total of... 9.5 seconds out of 12.7 seconds spent in the out = (''.join(format(ord(x), '08b') for x in sha1(data).digest())) line. This would have been impossible to figure out without profiling (as you can see in kyle k's comment). It's the number one rule of optimizations: since you'll spent 80% of your time in 20% of the code, only optimize what you know to be slow!

Removing the 80%

So, how can we replace this line? The idea is to use hexdigest instead of digest. The issue with hexdigest is that we only see hexadecimal digits, not bits. Since 20 bits is 5 hexadecimal numbers, that's not an issue here. If you needed 21 bits, then you would ask for 6 hexadecimal numbers, which is more hashes than necessary, but still worth the speed up.

Here's the new code:

from os import urandom
from hashlib import sha1
import time
from math import ceil

def mint(name, bits):
    t = time.strftime("%y%m%d")
    out = " "
    count = 0
    digits = int(ceil(bits/4.0))

    while out[:digits] != digits*"0":
        RandomData = urandom(8).encode("base64").replace("\n", "")
        RandomData = 'AHZlx9LYMyo='
        data = "1:%d:%s:%s::%s:%s"%(bits, t, name, RandomData, format(count, 'x'))
        out = sha1(data).hexdigest()
        count += 1
    return data

print mint("email_address", 15)

And the new profiling:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.750    0.750    3.212    3.212 improved.py:6(mint)
    67347    0.529    0.000    0.959    0.000 base64.py:310(encodestring)
    67347    0.427    0.000    0.427    0.000 {posix.urandom}
    67347    0.251    0.000    1.274    0.000 base64_codec.py:13(base64_encode)
    67347    0.227    0.000    1.503    0.000 {method 'encode' of 'str' objects}
    67347    0.155    0.000    0.155    0.000 {format}
    67348    0.138    0.000    0.138    0.000 {_hashlib.openssl_sha1}
    67347    0.134    0.000    0.134    0.000 {method 'hexdigest' of '_hashlib.HASH' objects}
   134694    0.131    0.000    0.131    0.000 {len}
    67347    0.122    0.000    0.122    0.000 {binascii.b2a_base64}
    67348    0.109    0.000    0.109    0.000 {range}
    67347    0.105    0.000    0.105    0.000 {method 'replace' of 'str' objects}
    67348    0.066    0.000    0.066    0.000 {method 'join' of 'str' objects}
    67347    0.066    0.000    0.066    0.000 {method 'append' of 'list' objects}
        1    0.001    0.001    0.001    0.001 hashlib.py:55(<module>)
        1    0.001    0.001    3.213    3.213 improved.py:1(<module>)
        1    0.001    0.001    0.001    0.001 base64.py:3(<module>)

Yay! Only 3.2 seconds in mint().

Removing another 80%

But hashing is still not the most expensive part. It's now the computing of RandomData (0.5 + 0.2 seconds in base64 encoding, 0.4 seconds in urandom, and so on). @cHao is right, you only need to compute that RandomData once and find the count that provides the correct sha1 hash. Let's move it out of the while loop:

from os import urandom
from hashlib import sha1
import time
from math import ceil

def mint(name, bits):
    t = time.strftime("%y%m%d")
    out = " "
    count = 0
    digits = int(ceil(bits/4.0))
    RandomData = urandom(8).encode("base64").replace("\n", "")
    RandomData = 'AHZlx9LYMyo='

    while out[:digits] != digits*"0":
        data = "1:%d:%s:%s::%s:%s"%(bits, t, name, RandomData, format(count, 'x'))
        out = sha1(data).hexdigest()
        count += 1
    return data

print mint("email_address", 15)

The new profile is:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.414    0.414    0.795    0.795 improved.py:6(mint)
    67347    0.134    0.000    0.134    0.000 {format}
    67348    0.124    0.000    0.124    0.000 {_hashlib.openssl_sha1}
    67347    0.121    0.000    0.121    0.000 {method 'hexdigest' of '_hashlib.HASH' objects}
        1    0.001    0.001    0.001    0.001 hashlib.py:55(<module>)
        1    0.001    0.001    0.796    0.796 improved.py:1(<module>)
        1    0.001    0.001    0.001    0.001 base64.py:3(<module>)

We only took 0.8 seconds (down from 12.7). format still takes time, but only one third of the time. I don't know what to do about it, so I'll leave it as it is, but you got your 10x speedup with two simple changes.


Painting Fences - optimize for faster performance

Your logic seems badly organised. Let's try to improve this first :

Making things better organised

At the moment, when you get the input, you use them to define a and n such that, for example, a = [[2, 2, 1, 2, 1]] and n = 5. For the sake of clarity, let's try to isolate the different parts to make things easier to build. We could define a function getting the list [2, 2, 1, 2, 1] from the user and then write a function to handle this list.

Just doing this and moving your code around, here's what we get :

import sys

count = 0

def count_and_split(p):
    h = min(p)
    n = len(p)
    global count
    if h<n:
        count += h
    else:
        count += n
    p = [i-h for i in p]
    e = []
    for i in p:
        if i == 0:
            k = p[:p.index(i)]
            if k:
                e.append(k)
            p = p[(p.index(i)+1):]
    if p:
        e.append(p)
    return e

def get_nb_strokes(l):
    a = [l]
    n = len(l)
    global count
    count = 0
    for part in a:
        e = count_and_split(part)
        if count>n:
            return n
        for new_part in e:
            a.append(new_part)
    return count

def get_list_from_user():
    n = int(sys.stdin.readline())
    return map(int, sys.stdin.readline().split())

def main():
    print(get_nb_strokes(get_list_from_user()))

if __name__ == '__main__':
    main()

It already looks much better doesn't it ? Well, it's not quite over yet.
Create tests :

Here's what your main function could look like as your change the code. You can run this quickly to ensure things seem to be working fine :

def main():
    assert get_nb_strokes([2, 2, 1, 2, 1]) == 3
    assert get_nb_strokes([2, 2]) == 2
    assert get_nb_strokes([1]) == 1

Add tests :

You can easily define new tests, it can also be a good idea to check how your code behaves on bigger inputs :

for i in range(2, 10):
    # fence of constant height
    for h in range(1,3):
        fence = [h] * i
        assert len(fence) == i
        assert get_nb_strokes(fence) == min(h,i)
    # fence of constant width
    for w in range(1,3):
        fence = [i] * w
        assert get_nb_strokes(fence) == min(w,i)
    # fence going up
    fence = range(1, i+1)
    assert get_nb_strokes(fence) == len(fence) == i
    # fence going down
    fence = range(i, 0, -1)
    assert get_nb_strokes(fence) == len(fence) == i
    # fence going up then down
    fence = range(1, i) + range(i, 0, -1)
    assert len(fence) == 2*i -1
    assert get_nb_strokes(fence) == i
    # fence going down then up
    fence = range(i, 0, -1) + range(2, i+1)
    assert get_nb_strokes(fence) == len(fence) == 2*i-1
    # L-shaped fence
    fence = [i] + [1]*i
    assert get_nb_strokes(fence) == 2
    # U-shaped fence
    fence = [i] + [1]*i + [i]
    assert get_nb_strokes(fence) == 3
    # W-shaped fence
    fence = [i] + [1]*i + [i] + [1]*i + [i]
    assert get_nb_strokes(fence) == 4

Don't use global variables

Having global variables makes things impossible to track and pretty hard to test. Let's try to improve this. It seems like the logic in count_and_split related to count could be done easily from the get_nb_strokes functions.

The updated code looks like :

def count_and_split(p):
    h = min(p)
    p = [i-h for i in p]
    e = []
    for i in p:
        if i == 0:
            k = p[:p.index(i)]
            if k:
                e.append(k)
            p = p[(p.index(i)+1):]
    if p:
        e.append(p)
    return e

def get_nb_strokes(l):
    a = [l]
    n = len(l)
    count = 0
    for part in a:
        count += min(min(part),len(part))
        e = count_and_split(part)
        if count>n:
            return n
        for new_part in e:
            a.append(new_part)
    return count

Please note that at the moment, I still don't know how your code works, I've just changed the way it is organised.
A bit of cleanup

Now, we can move e = count_and_split(part) after the check about count as things are independent. We can also get rid of the temporary variable, use extend and rename the function to write :

def get_nb_strokes(l):
    a = [l]
    n = len(l)
    count = 0
    for part in a:
        count += min(min(part),len(part))
        if count>n:
            return n
        a.extend(split(part))
    return count

I'll try to have another loop ASAP.


Add getters and setters to a set of variables

You forgot the parameter type in the setter methods (including @blufox suggestion):

sed -r "s/private\s+([^; ]+)\s+([^; ]+)\s*;(.*)$/&\npublic \1 get\u\2(){return \2;}\npublic void set\u\2(\1 \2){this.\2=\u\2;}\n/" "%~1">"%~2"

which produces:

private String firstName;// Stores firstName
public String getFirstName(){return firstName;}
public void setFirstName(String firstName){this.firstName=FirstName;}

But: you better use an IDE (e.g., Eclipse) for these tasks. You are trying to parse Java code with a regex which is a bad idea.

Just some examples:

declarations could be on different lines

private String // some comment
    myVariableOnTheNextLine
    // some other comment
    ; // semicolon

the public or private modifier could be omitted

String myString;

fields can be initialized

String myString = "my string";

fields can be declared final

private final String myString;

and so on


Spark dataframes (and columns) have a distinct method, which you can use to get all values in that column. Getting the actual values out is a bit more complicated and taken from this answer to a similar question on StackOverflow:

from pyspark.sql import SparkSession

def get_distinct_values(data, column):
    return {x[column] for x in data.select(column).distinct().collect()}

spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

input_data = spark.read.csv("/tmp/sample.csv", inferSchema=True, header=True)
input_data.createOrReplaceTempView("input_data")

print({c: get_distinct_values(input_data, c) == {True, False}
       for c in input_data.columns})
# {'category': False, 'logged_in': True, 'gid': False, 'pol_id': False, 'subcategory': False}

I don't know enough about spark to know how you would cast this back into a spark dataframe, but this should get you at least halfway there and be a bit faster, since it can do the fastest implementation it can to reduce the values to sets.

# /tmp/sample.csv
pol_id,gid,category,subcategory,logged_in
1,1,A,a,1
2,1,A,b,0
1,2,B,b,1
2,2,B,a,0


Searching for pseudo-palindromes ("semordnilaps")

I'd try to break some habits, and make others in their places.

One habit to break is using while (!file.eof()) -- it's nearly always a problem (including this time).
In its place, I'd consider initializing the array of input strings from a pair of std::istream_iterators.
I'd try to form the habit of creating fstream objects initialized with the name of the name of the file you want to read/write, rather than creating an uninitialized object, then using open open the file afterwards.
I'd also try to get in the habit of using better/more efficient data structures when possible. As pointed out below, in this case it doesn't make a big difference, but it does help a little, and it actually simplifies the code--a clear win.
Finally, get in the habit of using standard algorithms where they apply. In this case, I think a non-standard algorithm really makes more sense--a transform_if, which I end up using quite a bit, as a matter of fact.

Putting these together, we could end up with something on this order:

#include <iostream>
#include <unordered_set>
#include <string>
#include <iterator>
#include <fstream>
#include <algorithm>

template <class InIt, class OutIt, class F, class P>
void transform_if(InIt b, InIt e, OutIt o, P p, F f) {
    while (b != e) {
        auto v = f(*b);
        if (p(v))
            *o++ = v;
        ++b;
    }
}

int main(){
    std::ifstream in("us.dic");
    std::unordered_set<std::string> words{
        std::istream_iterator<std::string>(in),
        std::istream_iterator<std::string>()};

    std::vector<std::string> reversed;
    transform_if(words.begin(), words.end(),
        std::back_inserter(reversed),
        [&](std::string const &s) { return words.find(s) != words.end(); },
        [](std::string const &s) { return std::string(s.rbegin(), s.rend()); });

    std::sort(reversed.begin(), reversed.end(),
        [](std::string const &a, std::string const &b) {
            if (a.length() < b.length())
                return true;
            return a < b;
        });
    for (auto const &s : reversed)
        std::cout << s << "\n";
}

I haven't tried to move much out of main, because in this case we've already reduced main to only 6 statements (though, admittedly, some of those are fairly long).

A few other miscellaneous points:

I'd prefer to see #include directives formatted with a space before the header name (as I've done in my code above).
Using an unordered_set helps the run time somewhat, but not drastically--on my machine, the CPU time is reduced from ~.35 seconds to ~.24 seconds. That's clearly faster, but not immensely so.
Another possibility to consider would be to put the inputs into a sorted vector, but use an interpolation search instead of a binary search to find the pseudo-palindromes.


Use Java's built-in functions for things like this. Specifically, Character.isDigit(char c) and String.charAt(int index).

What you have right now is a poor reimplementation that makes any maintenance programmer go "wait, what?".

It sounds mean, but consider what it actually is:

return Character.isDigit(myString.charAt(0));

That one line is all you needed.

To prevent things like this happening in the future, I suggest googling your problem ("java string starts with digit" or "java string starts with number").

You'd have arrived at this question... https://stackoverflow.com/questions/1107798/how-to-check-a-string-starts-with-numeric-number .. which also points you to Character.isDigit. A little bit of google will go a long way in your programming work.

But school said I can't use those methods!

Oh. Okay.

First, store fName.substring(0,1) in a temporary variable. No need to substring forever.
Then, instead of Character.isDigit...

String allowedChars = "0123456789";
String firstChar = fName.substring(0,1);
return allowedChars.contains(firstChar);

After all, String IS CharSequence. You can see this in the documentation of java.lang.String.

public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence

See, String implements CharSequence.

Bugs

One of the things you need to be aware of is that your function can get a null string or an empty string.

You should check if the string you get is null or empty:

if (fName == null || fName.length == 0){
    return false;
}


Implementing Iterator is the way to go in my opinion. As for your question, array_map would allow you to decode the values but not the keys. But you can combine that with other array operations to get the desired result.

public function decodeArray($array) {
    $decode = array($this, 'decode');
    return array_combine(
            array_map(array_keys($array), $decode),
            array_map(array_values($array), $decode)
        );
}


Split function using C and dynamic memory allocation

Design: Code should explain cases

Double space: "abc  xyz" --> Is that to be 2 or 3 tokens?
Leading space: " abc xyz" --> Is that to be 2 or 3 tokens?
Trailing space: "abc xyz " --> Is that to be 2 or 3 tokens?

Design : Generalization
split() only considers ' '.  Maybe all white-spaces, '\t', '\n', ...?
Or pass into the function  a list of separators: split(char *str, const char *separators)
Design: const
As data referenced by str does not change, consider char **split(const char *str) for greater applicability and self documentation.
Bug: Insufficient memory
// word_array[a] = malloc(word_len * sizeof(char));
word_array[a] = malloc((word_len + 1u) * sizeof(char));
...
word_array[a][word_len] = '\0';

Bug: Writing outside allocation
word_array = malloc((separator_count + 2) * sizeof(char *));
...
word_array[separator_count + 2] = NULL; //OOPS!

// I suspect OP wanted
word_array[separator_count + 1] = NULL;

Allocate to the size of the reference object, not the type
// word_array = malloc((separator_count + 2) * sizeof(char *));
word_array = malloc(sizeof *word_array * (separator_count + 2u));

// word_array[a] = malloc(word_len * sizeof(char));
word_array[a] = malloc(sizeof (word_array[a][0] * word_len);

It is easier to code right, review and maintain.
Leading with the widest types in the multiplication prevents overflow - though that is not so important in this case.
Robust code checks allocation success
ptr = malloc(sizeof *ptr * n);
if (ptr == NULL && n > 0) {
  HandleOutOfMemory(); // Some user code
}

Clean-up allocations
main() called split(s) which allocates, but failed to call a matching free().  Not much concern with main() as code ends anyways, but good practice.
Minor: int word_len insufficient for large strings
// int word_len
size_t word_len


Manager that collects and handles multiple tasks that run on events like window.scroll, window.resize etc

Some points.

window is the default object. You don't need to use is. It is highlighted by the fact you don't use it sometimes window.document, or window.TaskManager but then for objects you are unsure of window.addEventListener you add it.
It is not a good idea to stack requestAnimationFrame requests.

Events related to mouse movements can fire at rates much higher than the display refresh rate of 60fps.
It introduces an up to 16ms delay on the event (and yes users will notice it as a sluggish response).
If used in conjunction with standard event handlers you will be handling events out of order.
Completely decouples the handler from the event.

You have decoupled (ignoring above point) the event from the handler because you don't pass on the event object. If you are going to manage events you should pass on the event object so that the handler can access the event.
registerTask will happily push events to the stack without checking if the supplied object is a valid. When you come to handling the event eg processTasksOnScroll it will throw if task.target or task.callback do not result in a function reference. If it throws none of the following events will be handled.
If any of the tasks throws an uncaught error then all following tasks will not be called.

Without knowing more about the project its hard to say more about this approch.

I do feel personally that events should not be one to many. For each event object created there should be one unbroken execution path that completely handles the event. Having events trigger more events is just going to result in an unmanageable mess, as you add code to conditional communicate between handlers wanting priority, or exclusivity.

That is not to say you can not have one handler for many events and then selectively redirect the event to a specific handler.


Use Correct Types in the Model

This is your model:

Stopwatch stopWatch;
TimeSpan timeSpan;
string elapsedTime;
List<string> times = new List<string>();

This is an example of stringly typed programming. Store data in meaningful types and convert them to other types (string, byte[] etc) for transfer, display etc. as necessary. For example storing times as List<TimeSpan> you can convert this to a list of running totals or display a graph etc without parsing, or worse trying to parse, the strings back to a meaningful type.

Looking from another perspective, you model should depend on the requirements, and as little else as possible. reading the problem description, and not bothering with menial details, thus not putting the cart before the horse,  you would come up with some model like this:

Stopwatch stopWatch; // from (start lap stop) requirement
List<TimeSpan> times = new List<TimeSpan>(); // from (write to file) requirement

Separation of Concerns

We see here several consequences of a user action bunched up:

stopWatch = Stopwatch.StartNew();
state = StateEnum.Started;
ChangeButtonText(StartAndLapButton, "Lap");
ChangeFormTitle("Started");
timer1.Enabled = true;

Suppose you decided to change one aspect, say how times are stored, then you will have to look for every code block that refers to it, and try to judge whether the change you will make affect the behavior of the code in the same code block below the changes.

Another way of organizing things is the OO way, group data and related behavior together:

event Action OnStart = () => {};
event Action OnLap = () => {};
event Action OnStop = () => {};

void ConfigureStopWatchBehavior()
{
    OnStart += stopWatch.Restart;
    OnStop += stopWatch.Stop;
}

void ConfigureTimesBehavior()
{
    Action storeElapsedTime = () => times.Add(stopWatch.Elapsed);
    OnLap += storeElapsedTime;
    OnStop += storeElapsedTime;
}

void ConfigureViewBehavior()
{
    OnStart += () => {
        StartAndLapButton.Text = "Lap";
        this.Text = "Started";
    };

    OnStop += () => {
        StartAndLapButton.Text = "Start";
        this.Text = "Stop Watch";
    };
}

void ConfigureViewStateBehavior()
{
    OnStart += () => state = StateEnum.Started;
    OnStop += () => state = StateEnum.Stoped;
}

void ConfigureTimerBehavior()
{
    OnStart += timer1.Start;
    OnStop += timer1.Stop;
}

Which causes form event handlers to look like these:

private void StartAndLapButton_Click(object sender, EventArgs e)
{
    if (state == StateEnum.Stoped) OnStart();
    else if (state == StateEnum.Started) OnLap();
}

private void StopButton_Click(object sender, EventArgs e)
{
    if (state == StateEnum.Started) OnStop();
}


Imperative and functional-programming solutions for Jumping on the Cloud challenge

The thing about these "story" problems is that the story is often distracting, if not outright misleading, from the underlying problem to be solved.

In this case your code solves the challenge by calculating and counting the number of jumps it takes to get from the beginning to the end. More or less the way the story is layed out.  But it's worth noting:

The minimum number of jumps for a sequence of N zeros is always N/2.
At the end of every sequence of zeros is a 1 to be jumped over, except at the very end.

def jumpingOnClouds(c :Array[Int]) :Int =
  c.mkString.split("1").foldLeft(0)(_ + _.length/2 + 1) - 1

This isn't the most efficient solution possible but since the input Array is limited to no more than 100 elements I decided to go for brevity over efficiency.


There are some points I would like to address to you, but I am missing a little bit the purpose of your exercise. From what I understand, every node of your tree can have only one child and only one sibling. Is it a feature or maybe you should change the Tree class to have as type for both Child and Siblings as IEnumerable<Tree>?

One thing that usually makes reviewer happy, is to give a consistant and understandable naming through the whole application. For example, I think it would improve readability renaming the class Tree to Node, and the field Info to Value.

I would avoid, if possible, the usage of fields and I would stick with public properties. A good explanation about why can be found here. For now then, your Tree class should look like this:

public class Node
{
    public int Value { get; set; }
    public Node Children { get; set; }
    public Node Siblings { get; set; }

    public Node(int data)
    {
        Value = data;
    }
}

If you are trying to implement a N-ary tree, I guess you would like that (as by definition), you won't have more than N children for each node. As you implemented it, as I was stating in my first request, you're only implementing a 1-ary tree.
For a N-ary tree, an idea could be adding N as property of the NAryTree, and change the types accordingly to avoid having more than N children for each node.

For the NAryTree, if I only read to signatures of methods, I would get the wrong idea about what you're trying to do. Print() gives me the idea you're trying to display on screen the content of the tree, but PreOrder() leads me to think you're sorting an unsorted tree (so, this is a bad name), and CreateNArray(int[] data) makes me think you're creating a new N-Array from scratch (again, which is your purpose here? I can't understand if a better name would be Initialize(int[] data) or Add(int[] data)).
Another suggestion I would like to give you, is to extract an interface for your NAryTree: this would  Accordingly to what I was saying before, I would rename Print() to ToString() and return a string as type.
Maybe adding the AddChild(int value) to the Node class would help you to keep easier the implementation of the CreateNArray method, if I got what you're trying to do.