Proper use of tail recursion while forming a list

Your algorithm is okay, but the real issue with this code is that your code style is atrocious, bordering on unreadable. Your style exhibits four main problems:

Scheme is not C, and parentheses are not curly braces. Do not put close parens on separate lines. Scheme code is intended to be read primarily by observing indentation, which brings me to the next point.
Your indentation is wrong. Again, Scheme is not C, and expressions should be indented to align subexpressions, not with a consistent 1-, 2- or 4-space indent. For an explanation of why this is so important, see this Stack Overflow answer.
This is a less significant point, but your explicit use of lambda here is unnecessary. There is a shorthand form with define that is equivalent to define paired with lambda, and it’s more idiomatic and easier to visually parse.
Identifiers in Scheme should be hyphenated (lisp-case), not separated by underscores (snake_case).

Just following the above formatting changes, your code becomes much more readable to a Schemer:

(define (is-prime1 num div)
  (if (= num div)
      #t
      (if (= (remainder num div) 0)
          #f
          (is-prime1 num (+ div 1)))))

(define (is-prime num)
  (if (< num 2) #f (is-prime1 num 2)))

(define (list-primes1 idx num)
  (if (<= idx num)
      (if (not (is-prime idx))
          (list-primes1 (+ idx 1) num)
          (cons idx
                (list-primes1 (+ idx 1) num)))
      '()))

(define (list-primes num)
  (list-primes1 0 num))

(define (print-primes primes)
  (if (null? primes)
      '()
      (list (display (car primes))
            (newline)
            (print-primes (cdr primes)))))

(print-primes (list-primes 4095))

Now we can focus on some more substantive code improvements. First of all, print-primes is an easy candidate for elimination. Not only does it needlessly produce a list, it can be trivially implemented using the for-each higher-order function. The name is also silly, since it does not print primes, it prints each element of a list. There is no reason to include the word “primes” in the name.

Instead, just replace the whole function with a simple use of for-each:

(define (displayln x) (display x) (newline))
(for-each displayln (list-primes 4095))

Next, let’s look at the bulk of the code. You have defined list-primes in terms of a helper functions, list-primes1. Since all your list-primes function is doing is calling list-primes1 with some arguments set, you can replace the helper function with a use of “named let”:

(define (list-primes num)
  (let loop ((idx 0)
             (num num))
    (if (<= idx num)
        (if (not (is-prime idx))
            (loop (+ idx 1) num)
            (cons idx
                  (loop (+ idx 1) num)))
        '())))

You also have a pair of nested ifs, which might be more readably  represented with a cond:

(define (list-primes num)
  (let loop ((idx 0)
             (num num))
    (cond
      ((> idx num)
       '())
      ((is-prime idx)
       (cons idx (loop (+ idx 1) num)))
      (else
       (loop (+ idx 1) num)))))

Taking a look at is-prime and is-prime1, we can once again replace is-prime1 with a use of named let:

(define (is-prime num)
  (if (< num 2)
      #f
      (let loop ((num num)
                 (div 2))
        (if (= num div)
            #t
            (if (= (remainder num div) 0)
                #f
                (loop num (+ div 1)))))))

However, this is still much more complicated than it needs to be. Due to how Scheme’s and and or are both short-circuiting and implement “truthiness”, where all non-#f values are truthy, we can replace most of the uses of if with and or or:

(define (is-prime num)
  (and (>= num 2)
       (let loop ((num num)
                  (div 2))
         (or (= num div)
             (and (not (= (remainder num div) 0))
                  (loop num (+ div 1)))))))

Also, we can replace (= x 0) with the zero? predicate to improve readability:

(define (is-prime num)
  (and (>= num 2)
       (let loop ((num num)
                  (div 2))
         (or (= num div)
             (and (not (zero? (remainder num div)))
                  (loop num (+ div 1)))))))

Now, it’s worth noting that list-primes is not tail recursive, since in the second cond case, a call to cons is in tail position, not loop. A way to make this function tail recursive is to build up a list iteratively, then reverse it at the end:

(define (list-primes num)
  (reverse
   (let loop ((idx 0)
              (num num)
              (acc '()))
     (cond
       ((> idx num)
        acc)
       ((is-prime idx)
        (loop (+ idx 1) num (cons idx acc)))
       (else
        (loop (+ idx 1) num acc))))))

This leaves us with the final, completely tail-recursive program:

(define (is-prime num)
  (and (>= num 2)
       (let loop ((num num)
                  (div 2))
         (or (= num div)
             (and (not (zero? (remainder num div)))
                  (loop num (+ div 1)))))))

(define (list-primes num)
  (reverse
   (let loop ((idx 0)
              (num num)
              (acc '()))
     (cond
       ((> idx num)
        acc)
       ((is-prime idx)
        (loop (+ idx 1) num (cons idx acc)))
       (else
        (loop (+ idx 1) num acc))))))

(define (displayln x) (display x) (newline))
(for-each displayln (list-primes 4095))


One thing that immediately jumped out:

def KillOld(strings):
    for _ in strings:
        if _.age > 2:
            strings.remove(_)

_ is used by convention to indicate "I won't be using this variable", e.g.:

for _ in range(5):
    do_something()

If you are using the variable, give it a better name (even just s). Also, functions' names should be lowercase_with_underscores per PEP-0008.

Next, your mutation seems odd, as it generates four new random characters then picks two from the parents. Instead, I would have done:

def create_child(parents):
    return String("".join(r.choice(c) for c in zip(*(p.chromo for p in parents))))

i.e. for each position, pick randomly between the two parents.

Note that the function returns the new String, rather than adding it to strings. I would say that:

strings.append(create_child(parents))

is clearer than adding to strings as a side-effect. Similarly, I would probably rewrite KillOld to return a new list, rather than mutate its argument (and call it kill_old).

You can simplify

string_complete = ''
for _ in range(6):
    rand = r.randint(0, 1)
    string_element = str(rand)
    string_complete = ''.join([string_complete, string_element])
string = String(string_complete)

to:

s = String("".join(map(str, (r.randint(0, 1) for _ in range(6)))))

(don't use string as a variable name; you may want to use that module later). And rather than append then remove it, check first:

if s.chromo != target:
    strings.append(s)

(Note that you define target then don't use it - replace all '111111' with target and you can change it much more easily in future!)

Rather than calculate the s.fitness for each s, then have a complex key:

parents.append(max(strings, key=operator.attrgetter('fitness')))

make the function fitness that takes a single String and returns the fitness score:

def fitness(s):
    return sum(c == t for c, t in zip(s.chromo, target))

Your key is then e.g.:

parents.append(max(strings, key=fitness))

This also decouples the fitness from the String object itself; you no longer need the s.fitness attribute.

You could also generally improve SelectParents; remove and append again is not efficient.

def select_parents(strings):
    return sorted(strings, key=fitness)[-2:]

This sorts strings in ascending fitness, then returns a sliced list of the last (up to) two items.


I would expect the generator to seed itself (using the current time) in its constructor.

Therefore, I would not use a default parameter in your set_seed method.

Also, in your current code, you treat all the negative values the same as zero. I wouldn't recommend that. Many random seeders can handle negative seeds as well, if you don't want to do that: Throw an Exception/Error!

Therefore, I would use this:

public function set_seed(s: Number): void
{
    if (s < 0) {
        throw new Error("Seed must be positive");
    }
    seed = s;
}

For comparison and inspiration, check Java's java.util.Random class. Note that it has two constructors available, one for initializing to System's seed and one for initializing to a specific seed. That is an approach I would recommend.


You are creating lots of Point() objects. For performance optimization in Java the very first thing is to avoid pressure on the garbage collector.
You are doing lots of repeated calculations just for traversing the grid (in several directions). Performance wise it would be much better to transform the whole grid in advance to simplify the traversal calculation. E.g. it is very simple to search only words in East direction in a grid. And searching words in West direction could then be done by mirroring the grid against a vertical axis and searching again in East direction only.
For just finding words, you can ignore the grid structure entirely. Take the complete first row as String, append a space, append the complete second row as String and so forth. You get one huge string representing the grid for searching in East direction. Your matching code is simply hugeString.contains(searchWord) (with a bit more complicated calculation of the original row and column information). You can do the same transformation from grid to a single String also for all other directions.


Your use of constants is a bit buggy. First of, since you call write_url_to_filename(URL, LIBRARY), you should change

def write_url_to_filename(url, filename):
    response = requests.get(URL, stream=True)

into

def write_url_to_filename(url, filename):
    response = requests.get(url, stream=True)

i.e: use the parameter instead of the constant.

Secondly, since you only use your constants in main and pass them as parameters afterwards, I feel it would be best to have them as parameters with default value instead of constants:

def main(library='library.txt',
         url='http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b',
         phonemes=3):
    if not os.path.isfile(library):
        write_url_to_filename(url, library)
    with open(library) as f:
        data = format_data(f.readlines())
    print(find_rhymes("FORCE", data, phonemes)[:20])

I would also have named write_url_to_filename simply download_into but it's not guaranteed that it is a better name.

On a stylistic note, you make extensive use of \ in your list-comprehensions where implicit line continuation are at play. You can drop them, it won't change the meaning.

You also seem to indent them one extra space after each line, try to avoid that.

find is just applying a filter and taking the first element. Since you are using Python 2, you may be insterested in itertools.ifilter instead of filter. The former being an iterator whereas the latter returns a list.

Not that your approach is bad per se, but you might want to compare the two, performance wise:

from itertools import ifilter

def find(predicate, iterable):
    return next(ifilter(predicate, iterable))

When building your ReadingData, your x.strip().replace('\n','').split()) can be replaced by x.split() as split without arguments has extra logic to clean-up a string while performing the split.

I would also change your helper function into:

def clean_line(line):
    data = line.split()
    return ReadingData(data[0], data[1:])

so that:

you can simplify format_data:

def format_data(raw_data):
    return [clean_line(x) for x in raw_data if not x.startswith(';;;')]

you let the possibility to the writer of the question that led to this code to write, in Python 3:

def clean_line(line):
    word, *phonemes = line.split()
    return ReadingData(word, phonemes)

which is even more explicit
You can use it directly in your with block without having to read the whole file into memory first:

def main(library='library.txt',
         url='http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b',
         phonemes=3):
    if not os.path.isfile(library):
        write_url_to_filename(url, library)
    with open(library) as f:
        data = [clean_line(line) for line in f if not line.startswith(';;;')]
    print(find_rhymes("FORCE", data, phonemes)[:20])

Alternatively, you could just pass the file f to format_data instead of the list of lines. It will work without modifications and will also let you build the data as you read the file instead of reading the file first and then building data.


Displaying completed and failed wuuks using one or two functions

I used to do this sort of "optimisation" 20 years ago.  I don't anymore.  Clarity of code is more important.  I would rather have fewer parameters and properly named functions.  This way, you can just read the code without worrying about how the function works.

If you do what you are proposing, then to understand the code, you have to look at the what the function is doing every time it is used !!!

EDIT
An example of what I have just finished doing at work.  The original procedure was called Launch_Client_Form with a whole bunch of parameters.  It had four functions and the parameters of all 4 functions had to be passed each time.  I created 4 procedures

View_Client
Create_Client
Edit_Client
Find_Client

Each one has only the parameters it requires.  Internally they all still call Launch_Client_Form.  Now, when you encounter Edit_Client in the code, it does not require a comment and you know what it is going to do.


Your hexArray has a static size of MAXCHAR but you never check if you didn't exceed this size when reading input. Consider what would happen if someone enters MAXCHAR+1 characters at input.
When you set last character in your hexArray to '\0', you do it on wrong position. In your while loop, you increment i after each write to hexArray so at the end i is an index of next free element. And you should write '\0' here. But you use pre-increment (++i) so you write this '\0' on next place.
This '\0' is not really needed at all since you pass array size as an argument to htoi anyway. But you pass wrong size as I already mentioned.
You are using tolower function in your htoi function but you could do this already when getting input. This saves you one loop over all values. It means that htoi will be less general since it will only work with low capital letters, though.
You could also use tolower function on all the input characters since if tolower gets argument that is not uppercase letter, it will return unchanged value. This would save you some ifs in your code for the price of overhead of running a function (and doing ifs in it since it has to do this).
if(hexArray[i] >= '0' && hexArray[i] <= '9') intArray[i] = hexArray[i]; is wrong. You set intArray[i] value to '0' (which is numerical value 48) instead of 0. So you should use intArray[i]=hexArray[i]-'0'; instead.
Your big if-elseif block for a-f characters can be much simpler. All ASCII letters have consecutive numbers so to convert 'a' to 10, 'b' to 11 etc you can use:

  else if(hexArray[i] >= 'a' && hexArray[i] <= 'f') {
      intArray[i] = hexArray[i] - 'a' + 10;
  }

This saves you a lot of ifs and you can even remove your enum.
The whole intArray array is not really needed at all since you could do your computations inside of the loop in which you create it. This way you can have only one loop inside of your htoi.
Yyou are using int type to hold computed integer. So you can really only convert sizeof(int)*2 characters long hex value inside, and your MAXCHAR=100.
You can eliminate the need of pow function if you will start your calculations from the end of intArray array. You can store powers of 16 in some variable and just multiply it by 16 (or shift left 4 bits) in each iteration.


Create a triangle arrow block dynamically

Is it an utility function or a module?

You named your function createArrow() and it contains an object with methods and at the end you just call one.

I think this is a bit of over engineered for such piece of code.

The first improvement I suggest you is to remove the plain object and method, and refactor the function to do stright forward the task.

Names are all

Please pay attention to the names you give to the functions/method.

When I use some kind of module or object, it is natural to me to call the initializer as the first thing.

But looking at your code, it would be the wrong way.

You just called a checkDiv().

Does is not just bad because it is unaspected, but aslo because if I look at your code, you didn't check the div!

    checkDiv: function () {
        if(this.parent.querySelector('.arrow-down')) {
            this.parent.removeChild(this.parent.querySelector('.arrow-down'));
        }
        this.initDiv();
    }

Here you search an element in the portion of the DOM tree of the this.parent, and if you find, you remove!

A check should be a safe action, not something that remove things.

I suggest you to call such method: reset()

This is more near to the task, and tell to other developer that if they call it they are going to loose what they have now.

Another thing is to remove from the method the last line:

 this.initDiv();

You should call reset() at the beginning of the init(), not the init() at the end of the reset().

And yes, about names: you don't need the Div part in the name in this case.

So, I would refactor your code as follow:

function createDownArrow() {
    const parent = document.querySelector('.landingItem');

    var arrow = parent.querySelector('.arrow-down');
    if (arrow) {
        parent.removeChild(arrow);
    }

    const element = document.createElement('div');

    element.classList.add('arrow-down');
    const borderWidth = parseInt(document.documentElement.clientWidth)/2;

    element.style.borderLeftWidth = borderWidth + 'px';
    element.style.borderRightWith = borderWidth + 'px';

    parent.appendChild(element);
}

window.addEventListener("load", createDownArrow);
window.addEventListener("reset", createDownArrow);
.arrow-down {
  margin-top: -2px;
  border-top: 60px solid #501a70;
  border-left: 160px solid transparent;
  border-right: 160px solid transparent;
}


JSON loader with event bus, cache, and session

The solution I developed was to inject the dependencies into the job queue instead of the jobs. This way the injection only has to happen once and can be accomplished nicely using Dagger 2 (note: because I was using the android-priority-jobqueue library I had to wrap it in my own class to allow for this functionality).

This is my Dagger module:

import android.app.Application;

import com.treemetrics.taskmanager3.util.AppCache;
import com.treemetrics.taskmanager3.work.eventbus.EventBus;
import com.treemetrics.taskmanager3.work.jobqueue.JobQueue;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module
public class AppModule {

  private final Application mApplication;

  public AppModule(final Application application) {
    mApplication = application;
  }

  @Provides
  @Singleton
  Application providesApplication() {
    return mApplication;
  }

  @Provides
  @Singleton
  EventBus providesEventBus() {
    return new EventBus();
  }

  @Provides
  @Singleton
  AppCache providesCache() {
    return new AppCache();
  }

  @Provides
  @Singleton
  JobQueue providesJobQueue(final Application app, final EventBus bus, final AppCache cache) {
    return new JobQueue(app, bus, cache);
  }

}

Dagger component:

import javax.inject.Singleton;

import dagger.Component;

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {

  void inject(MainActivity activity);

}

My wrapper class for the android-priority-jobqueue JobManager class which accepts the dependencies:

import android.content.Context;
import android.support.annotation.Nullable;

import com.birbit.android.jobqueue.JobManager;
import com.birbit.android.jobqueue.config.Configuration;
import com.treemetrics.taskmanager3.util.AppCache;
import com.treemetrics.taskmanager3.work.eventbus.EventBus;

public class JobQueue {

  private static final int DEF_PRIORITY = 1;

  private final Context mContext;
  private final JobManager mJobManager;
  private final EventBus mEventBus;
  private final AppCache mAppCache;

  public JobQueue(final Context context, final EventBus eventBus, final AppCache appCache) {
    mContext = context;
    final Configuration jobManagerConfig = new Configuration.Builder(context).build();
    mJobManager = new JobManager(jobManagerConfig);
    mEventBus = eventBus;
    mAppCache = appCache;
  }

  public void addJob(final Job job) {
    addJob(job, null);
  }

  public void addJob(final Job job, @Nullable final CharSequence groupId) {
    final String groupIdStr = (groupId != null) ? groupId.toString() : null;
    final BirbitJob birbitJob = getBirbitJob(job, DEF_PRIORITY, groupIdStr);
    mJobManager.addJobInBackground(birbitJob);
  }

  private BirbitJob getBirbitJob(final Job job, final int priority, @Nullable final String groupId) {
    return new BirbitJob(job, mContext, mEventBus, mAppCache, priority, groupId);
  }

}

I also have a new Job interface which my JobQueue wrapper class accepts instead of the Job class from the android-priority-jobqueue library. These jobs when submitted to my new JobQueue get translated to "birbit jobs" (the job class which the library accepts) and have the dependencies injected into them at that time. Here is my new Job interface and the BirbitJob class which is used to translate my jobs into the jobs accepted by android-priority-jobqueue.

(Notice the dependencies are provided in the onRun method.)

import android.content.Context;

import com.treemetrics.taskmanager3.util.AppCache;
import com.treemetrics.taskmanager3.work.eventbus.EventBus;

public interface Job {

  void onRun(Context context, EventBus bus, AppCache cache) throws Throwable;

  void onCancel(Throwable throwable, EventBus bus);

}

My translator job class BirbitJob:

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.treemetrics.taskmanager3.util.AppCache;
import com.treemetrics.taskmanager3.work.eventbus.EventBus;

class BirbitJob extends com.birbit.android.jobqueue.Job {

  private final Job mJob;

  private final Context mContext;
  private final EventBus mEventBus;
  private final AppCache mAppCache;

  public BirbitJob(final Job job,
                   final Context context,
                   final EventBus eventBus,
                   final AppCache appCache,
                   final int priority) {
    this(job, context, eventBus, appCache, priority, null);
  }

  public BirbitJob(final Job job,
                   final Context context,
                   final EventBus eventBus,
                   final AppCache appCache,
                   final int priority,
                   final String groupId) {
    super(new Params(priority).requireNetwork().groupBy(groupId));
    mJob = job;
    mContext = context;
    mEventBus = eventBus;
    mAppCache = appCache;
  }

  @Override
  public void onAdded() {
  }

  @Override
  public void onRun() throws Throwable {
    mJob.onRun(mContext, mEventBus, mAppCache);
  }

  @Override
  protected void onCancel(final int cancelReason, @Nullable final Throwable throwable) {
    mJob.onCancel(throwable, mEventBus);
  }

  @Override
  protected RetryConstraint shouldReRunOnThrowable(
      @NonNull final Throwable throwable, final int runCount, final int maxRunCount) {
    return RetryConstraint.CANCEL;
  }

}


Finding average word length in a given year

totword and totLen are not so good names.
And in any case PEP8 suggests to use snake_case for both variable and function names. So I recommend the following renames:

total_word_length instead of totLen
word_count instead of totword
average_word_length instead of avgWordLen

When you iterate over keys in a dictionary and then lookup the values in every iteration step,
then it's better to iterate over the dictionary items.
That is, instead of:

    for word in words:
        for nary in words[word]:

Do like this:

    for word, nary_list in words.items():
        for nary in nary_list:

This way you avoid unnecessary dictionary lookups.

At the end of the method, the else is unnecessary,
because the if part always returns.
It's slightly simpler this way:

    if word_count != 0:
        return total_word_length / word_count
    return 0


Your code is quite good. Simulations is hard to vectorize. The largest slowdown here is the repeated calling of rbind in loop. It is faster to crate list of vectors and concatenate the results at the end. So  I edited the necessary parts:

Est3 <- function(n, mean, sd, lower, upper, samp_min, samp_max, samp_int, nsim) {
  Data <- round(rtnorm(n, mean, sd, lower, upper), digits = 0)
  Samp_size <- seq(samp_min, samp_max, samp_int)
  Results <- list() # crate emty list
  for (i in 1:nsim) {
    Results_samp <- list() # crate emty list
    for (j in seq_along(Samp_size)) {
      Nsubj <- Samp_size[j]
      SUS_Score <- sample(Data, Nsubj, replace = TRUE)
      Mean <- mean(SUS_Score, na.rm = TRUE)
      SD <- sd(SUS_Score, na.rm = TRUE)
      Results_samp[[j]] <- c(Nsubj, Mean, SD) # add values to list
    }
    Results[[i]] <- Reduce(rbind, Results_samp) # convert list to matrix and add to main list
  }
  Results <- Reduce(rbind, Results) # 'rbind' list of matrices
  Results <- as.data.frame(Results, row.names = F) # convert to data.frame
  colnames(Results) <- c('Nsubj', 'Mean', 'SD') # add names
  Results %>% arrange(Nsubj)
}


This code reads like a story, very nice, though at times a bit verbose.

The value returned from addValueOrIncrementCount is never used,
so you could drop the return statement.

decrementCountIfPossible returns a count, or null if the count cannot be decremented. It would be simpler and more natural to use if it returned boolean, because the returned count is not used anyway.

In mapWordCounts the variable occurrences is declared but never used.

Note that the map of word counts for ransomMap is not really necessary.
It's possible to simply loop over the words, updating the magazineMap,
and return false whenever the magazineMap doesn't have the required word.

You could use the || operator to simplify addValueOrIncrementCount:

const addValueOrIncrementCount = (value, map) => {
    map.set(value, 1 + (map.get(value) || 0))
}


I would strongly recommend making name field const. Also, typeid(*this).name() won't look nice and pretty in some compilers.
You should probably try something like:

class Tool {
public:
  const std::string name;
  <...>
protected:
  Tool(const char* className) : name(className) {}
private:
  <...>
}

BTW, do NOT expect typeid(*this).name(); to be called for deriven object. Even virtual functions won't help, so you can't write something like virtual const char* getMyName() = 0;, because any kind of "virtual" behavior will not work in constructor.


Random retrievable number based on day and month

I wrote a function to get a 2-digit random number for each day, but it should be retrievable.
For example, today's random number is 72, but later I can provide "day and month" and get this 72 again.

This isn't random.  This is a hashing function.  For a given input, it always returns the same output.  The normal name for something like this is a hashing function.
You don't explain why you want to do this.  If you ask again, try to include that context.  We may suggest alternatives.

function ranDay($day,$month){

If this were a random function, I'd write out the name:  randomDay.  If you really must abbreviate, randDay would be better.  However, as I noted earlier, this isn't random.  You are just mapping one input to another, so a name like hashDay would be better.  There may be an even better name.
function hashDay($day, $month) {
    if ( ! is_numeric($day) || ! is_numeric($month) || 0 > $day || 0 > $month || 12 < $month || 31 < $day ) {
        return;
    }

I also added additional whitespace for readability.
Since this is only supposed to work for valid day and month values, I added some basic checks.  Even with these, it will still allow dates like the 31st of February, but this restricts the range somewhat.  I just return an undefined value implicitly, but you could explicitly return null (which would do the same thing) or do something like throwing an exception.  Note that this also handles if the month or day is given as a string (e.g. January) rather than a number.
Handling zero values with different returns than a value of one is possible:
    $day++;

With that, a zero and a one will return different values.

$dig1 = intval(substr($pow1,0,1));
$dig2 = intval(substr($pow2,-1));

I'd write out $digit1 and $digit2.
Also, you don't need the intval.  You immediately use string concatenation on it, which will throw it back into strings.  So the only thing that the intval can do is hide bad input from you.

echo $dig1.$dig2;

Rather than echoing the result, it would probably be better to return it.  That way you can display it or check for invalid values or whatever.  This can also be seen as a violation of the Single Responsibility Principle:  you are calculating the hash value; don't display it as well.  If you really want to display it, consider changing the name to something like printDayHash.
return $digit1 . $digit2;

Your function will have collisions.  There are only 100 possible results, but there are at least 366 valid day/month combinations.  Running it on all 416 allowed day/month combinations (including zero values and weird dates like the 31st of February) shows that some results are more likely than others.  For example, 91 and 92 (and eight others) are never returned while 16 is returned a whopping twenty times.  For most uses, it would be better for this to be more evenly distributed.
My test code:
$count_of = array();
for ( $i = 0; $i < 10; $i++ ) {
    for ( $j = 0; $j < 10; $j++ ) {
        $count_of[$i.$j] = 0;
    }
}

for ( $m = 0; $m <= 12; $m++ ) {
    for ( $d = 0; $d <= 31; $d++ ) {
         $count_of[hashDay($d, $m)]++;
    }
}

asort($count_of);
print_r($count_of);

Note how returning the value rather than displaying it makes this test much easier.


Zeckendorf Representation of positive integer

First some general review:

You should use a if __name__ == "__main__": guard around the test run to allow importing of your code from another module.
You should add docstrings to your functions to explain what they do. Docstrings are of the format:

def f(x, y):
    """Returns the sum of `x` and `y`"""
    return x + y

As you already mentioned, here is a way to use generators. This has two draw-backs compared to your code:

In find_num_smaller we have to iterate forwards (you cannot iterate backwards through an iterator, at least not without converting it to a list first).
We need to re-generate the generator every loop, because it will be partially exhausted

def fib(max_num):
    """
    Yields the fibonacci sequence until the last element smaller than `max_num`
    """
    n_1, n = 0, 1
    while n < max_num:
        yield n
        n_1, n = n, n + n_1

def find_num_smaller(num, my_list):
    """
    Iterates through an iterator until the value in the iterator is larger than `num`.
    Returns the value before that.
    """
    last_value = next(my_list)
    for value in my_list:
        if value > num:
            return last_value
        last_value = value
    return last_value

def solve(num):
    """
    Description here
    """
    x = num
    while x > 0:
        temp_value = find_num_smaller(x, fib(num))
        x -= temp_value
        yield temp_value

if __name__ == "__main__":
    print list(solve(10))

Note that your fund_num_smaller will return None if all values in my_list are smaller than num. Here I added returning the last element in that case.

However, this actually performs worse than your code (mostly because iterating reversed saves a lot of time and re-doing the fibonacci sequence wastes a lot of cycles).

As an alternative consider this code:

def find_num_smaller(num, my_list):
    for value in reversed(my_list):
        if value <= num:
            return value

def solve(num):
    l = list(fib(num))
    while num > 0:
        temp_value = find_num_smaller(num, l)
        num -= temp_value
        yield temp_value

Where I used your find_num_smaller and put the fibonacci into a list.

Here is acomparison between the three approaches for the input 123456789123456789123456789123456789123456789123456789 on my machine:

no generator     406 function calls in 0.000 seconds
only generators  10111 function calls in 0.003 seconds
mixed            407 function calls in 0.000 seconds

So using generators here will not give you a speed improvement for most inputs. For the fibonacci numbers it will, however, give you a memory improvement (which will take quite some time to matter).

For really large inputs (like 123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789) there is no improvement visible:

no generator  2947 function calls in 0.017 seconds
mixed         2948 function calls in 0.017 seconds

And for the input 123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789:

no generator  5886 function calls in 0.063 seconds
mixed         5887 function calls in 0.064 seconds

So both approaches seem to scale with the number of digits of the input.


I think you've overcomplicated the problem because you're approaching it the way you would in an imperative language. I'll describe the way I would approach the problem. Notice that I do a lot of my "thinking" in GHCi!

Your code reads the file and splits it up into lines just fine, so I'll move onto the part where we handle each line of text. First, we need to split the line up into tokens, where the tokens are separated by commas. The words function is close to what we want, but it breaks at whitespace, not commas. So we'll write our own:

tokens :: String -> [String]
tokens [] = []
tokens as =
  case break (==',') as of
    (xs,[])   -> [xs]
    (xs,_:ys) -> xs:tokens ys

I put that in the program I'm writing, load it, and try it out:

λ> tokens "wombat,7,789,tiger,33"
["wombat","7","789","tiger","33"]

Now we need to separate the words from the integers. So we need a function that will tell us if a token is an integer. The problem statement implies we only need to deal with integers. So a token is an integer if it only contains digits. (The example given didn't have any spaces, but we could allow them, and even decimal points, if we want to.)

So how do we tell if a character is a digit? Hmm... there's probably a function to do that for us.The best way to answer questions of the form "Is there a Haskell function to do X" is usually:

Figure out what the type signature of the function you want would be.
Search hoogle or hayoo. If you don't find it in one, try the other. Usually it doesn't matter much whether you get the order of the input parameters exactly right, but you may need to experiment.

What would the type of the function we're interested in be? Logically, it has to be:

Char -> Bool

Unfortunately, in the case there are a lot of functions with that signature, but eventually we find isDigit in Data.Char.

λ> import Data.Char
λ> isDigit '7'
True
λ> isDigit 'w'
False

Look at the source for that function. (You'll see that it would be easy to write our own function to allow blanks or decimal points as well as digits.)

So now we have a way to tell if an individual character is valid in an integer. How do we tell if all of the characters in a token pass the test? Again, I suspect there's a function that applies a boolean test to all elements in a sequence, and tells us if they all pass. The type signature of such a function would be one of the following:

(a -> Bool) -> [a] -> Bool
[a] -> (a -> Bool) -> Bool

Checking Hoogle, we find the all function in Data.List.

λ> import Data.List
λ> all isDigit "123"
True
λ> all isDigit "wombat"
False

We could use this expression as is, but would be more readable to define a function.

isInteger :: String -> Bool
isInteger s = all isDigit s

We could also write that last line using pointfree notation.

isInteger = all isDigit

I add that to my program, reload it, and try it out:

λ> isInteger "123"
True
λ> isInteger "wombat"
False

Next we need to divide our tokens up into those that are integers, and those that aren't. Again, there's probably a function that segregates a list into those items that satisfy a test, and those that don't. It would have this signature (possibly with the arguments switched):

(a -> Bool) -> [a] -> ([a],[a])

This time a Hayoo or Hoogle search turns up break and partition. Looking at the documentation, we see that partition is what we want. Let's try it:

λ> partition isInteger ["wombat","7","789","tiger","33"]
(["7","789","33"],["wombat","tiger"])

That preserved the order of the elements, but it gave us the integers first. That's easily fixed:

λ> partition (not . isInteger) ["wombat","7","789","tiger","33"]
(["wombat","tiger"],["7","789","33"])

Let's wrap that in a function to make it more readable:

segregate :: [String] -> ([String], [String])
segregate = partition (not . isInteger)

I'm going to move a little more quickly now, because you're probably getting the hang of how to approach these problems. Next we need to format the results. Let's focus on re-inserting the comma between tokens. I'll write a dual to the tokens function:

untokens :: [String] -> String
untokens = concat . intersperse ","

Let's try it:

λ> untokens ["wombat","tiger"]
"wombat,tiger"

Now all we need to combine the two parts:

format :: ([String],[String]) -> String
format (xs,ys) = untokens xs ++ '|' : untokens ys

Let's try it out:

λ> format (["wombat","tiger"],["7","789","33"])
"wombat,tiger|7,789,33"

Now we can put all the steps together:

parse :: String -> String
parse = format . segregate . tokens

See how simple and readable the parse function is? And it works:

λ> parse "wombat,7,789,tiger,33"
"wombat,tiger|7,789,33"

EDIT: Here's the entire program, with main.

import Data.Char
import Data.List

main = do
    args <- getArgs
    content <- readFile(args !! 0)
    mapM_ (putStrLn . lines) content

tokens :: String -> [String]
tokens [] = []
tokens as =
  case break (==',') as of
    (xs,[])   -> [xs]
    (xs,_:ys) -> xs:tokens ys

untokens :: [String] -> String
untokens = concat . intersperse ","

segregate :: [String] -> ([String], [String])
segregate = partition (not . isInteger)

isInteger :: String -> Bool
isInteger = all isDigit

format :: ([String],[String]) -> String
format (xs,ys) = untokens xs ++ '|' : untokens ys

parse :: String -> String
parse = format . segregate . tokens


Most efficient way to find an entry in a C++ vector

Header files

It's strange that this code uses the C header <string.h> but the C++ versions of <cmath>, <ctime> and <cstdlib>.  I recommend sticking to the C++ headers except on the rare occasions that you need to compile the same code with a C compiler.  In this case, I don't see anything using <cstring>, so we can probably just drop that, along with <iomanip>, <iostream> and <cmath>.  And we need to add some missing includes: <cstdint> and <cstdio>.

Avoid using namespace std

The standard namespace is not one that's designed for wholesale import like this.  Unexpected name collisions when you add another header or move to a newer C++ could even cause changes to the meaning of your program.

Use the appropriate signature for main()

Since we're ignoring the command-line arguments, we can use a main() that takes no parameters:

int main()

Remove pointless temporary string

Instead of formatting into tmpStr and immediately printing its contents to standard output, we can eliminate that variable by formatting directly to standard output (using the same format string).  For example, instead of:

std::sprintf(tmpStr, "+-------+-------+");
std::printf("%s\n", tmpStr);
tmpStr[0]='\0';

std::sprintf(tmpStr, "| TABLE | STATE |");
std::printf("%s\n", tmpStr);
tmpStr[0]='\0';

std::sprintf(tmpStr, "+-------+-------+");
std::printf("%s\n", tmpStr);

we could simply write:

std::puts("+-------+-------+\n"
          "| TABLE | STATE |\n"
          "+-------+-------+");

And instead of

    tmpStr[0]='\0';
    if ( std::find(m_availTableNums.begin(), m_availTableNums.end(), tableNum) != m_availTableNums.end() )
    {
        std::sprintf(tmpStr, "|  %02d   | EMPTY |", tableNum );
    } else {
        std::sprintf(tmpStr, "|  %02d   | USED  |", tableNum );
    }

    printf("%s\n", tmpStr);

we would have:

    if (std::find(m_availTableNums.begin(), m_availTableNums.end(), tableNum) != m_availTableNums.end()) {
        std::printf("|  %02d   | EMPTY |\n", tableNum);
    } else {
        std::printf("|  %02d   | USED  |\n", tableNum);
    }

Reduce duplication

Most of these statements are common:

        std::printf("|  %02d   | EMPTY |\n", tableNum);
    } else {
        std::printf("|  %02d   | USED  |\n", tableNum);
    }

The only bit that's different is the EMPTY or USED string.  So let's decide that first:

    const char *status =
        std::find(m_availTableNums.begin(), m_availTableNums.end(), tableNum) != m_availTableNums.end()
        ? "EMPTY" : "USED";
    std::printf("|  %02d   | %-5s |\n", tableNum, status);

Prefer nullptr value to NULL macro

The C++ null pointer has strong type, whereas NULL or 0 can be interpreted as integer.

Reduce scope of variables

randomCount doesn't need to be valid outside the first for loop, and we don't need to use the same tableNum for both loops.  Also, we could follow convention and use a short name for a short-lived loop index; i is the usual choice:

for (std::uint8_t i = 0;  i < 20;  ++i) {
    std::uint8_t randomCount = rand() % 80;
    m_availTableNums.push_back(randomCount);
}

for (std::uint8_t i = 0;  i < 80;  ++i) {

Avoid magic numbers

What's special about 80?  Could we need a different range?  Let's give the constant a name, and then we can be sure that the loop matches this range:

constexpr std::uint8_t LIMIT = 80;
...
    std::uint8_t randomCount = rand() % LIMIT;
...
for (std::uint8_t i = 0;  i < LIMIT;  ++i) {

A departure from specification

The description says

  I'm putting 20 random table numbers into the above vector such that, all the remaining 60 would be empty.

That's not exactly what's happening, as we're sampling with replacement from the values 0..79.  There's nothing to prevent duplicates being added (it's actually quite unlikely that there will be exactly 60 empty values).

Reduce the algorithmic complexity

Each time through the loop, we use std::find() to see whether we have any matching elements.  This is a linear search, so it examines elements in turn until it finds a match.  Since it only finds a match one-quarter of the time, the other three-quarters will examine every element in the list, and the time it takes will be proportional to the list length - we say it scales as O(n), where n is the size of the vector.  The complete loop therefore scales as O(mn), where m is the value of LIMIT.

We can reduce the complexity to O(m + n) if we use some extra storage to store the values in a way that makes them easy to test.  For example, we could populate a vector that's indexed by the values from m_availTableNums:

auto by_val = std::vector<bool>(LIMIT, false);
for (auto value: m_availTableNums)
    by_val[value] = true;

for (std::uint8_t i = 0;  i < LIMIT;  ++i) {
    const char *status = by_val[i] ? "EMPTY" : "USED";
    std::printf("|  %02d   | %-5s |\n", i, status);
}

If the range were much larger, we might use an (unordered) set instead of vector<bool>.  We might also choose vector<char> instead of vector<bool> for better speed at a cost of more space.

Simplified code

Here's my version, keeping to the spirit of the original (creating a list of indices, rather than changing to storing in the form we want to use them):

#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <vector>

int main()
{
    constexpr std::uint8_t LIMIT = 80;
    std::vector<std::uint8_t> m_availTableNums;

    std::srand(std::time(nullptr));

    for (std::uint8_t i = 0;  i < 20;  ++i) {
        std::uint8_t randomCount = rand() % LIMIT;
        m_availTableNums.push_back(randomCount);
    }

    std::puts("+-------+-------+\n"
              "| TABLE | STATE |\n"
              "+-------+-------+");

    auto by_val = std::vector<bool>(LIMIT, false);
    for (auto value: m_availTableNums)
        by_val[value] = true;

    for (std::uint8_t i = 0;  i < LIMIT;  ++i) {
        const char *status = by_val[i] ? "EMPTY" : "USED";
        std::printf("|  %02d   | %-5s |\n", i, status);
    }

    std::puts("+-------+-------+");
}


Scraping required fields exhausting a full website

This is quite clean and understandable.

I would pinpoint only a couple of things:

to avoid code repetition and to generalize getting search result properties, what if you would collect all the properties (genre, quality, size etc) into a dictionary:

properties = {
    label.text: label.xpath("following-sibling::text()")[0]
    for label in items.xpath(".//div[@class="mdif"]//li/b")
}

As a bonus, you would not need the try/except part at all.
as usual, you may reuse a session to boost your HTTP requests part performance

Some other minor notes:

it looks like that you make an extra request to the page number 0, adjust your range if this is the case
items variable name is probably a bit misleading, at the very least it should be item since you are iterating over search result items one by one
put get_links() call to under the if __name__ == '__main__' to avoid the code being executed if the module is ever imported
I would also return or yield from the get_links and process_docs functions instead of printing things out


Session in Struts2 and Google App Engine

Code looks good, But why not move this Part:

String email = (String) session.get("email");
if ( email == null)
    return LOGIN;

into an Interceptor? Or do you have only one relevant Action?


Password Manager UI: Populating DataGridView is Painfully Slow

What you call business logic methods is actually your data access logic. And you've put that in a bunch of static methods on what I'm assuming is a static class, which means the GUI code / "populate fields/accounts" is tightly coupled with that specific data access logic implementation (AccountLogic); I'd make them instance methods and inject an instance of AccountLogic and CredentialLogic as a dependency, into the constructor of whoever needs it.

Your data model seems to have navigation properties. Your code isn't using them:

        return (from c in context.Credential
                join f in context.Field on c.Field_id equals f.Id
                join a in context.Account on c.Account_id equals a.Id
                where c.Account_id == accountID
                where f.Id == fieldID
                select c).SingleOrDefault();

Could be:

return context.Credential
              .Where(c => c.Account_id == accountID && c.Field.ID == fieldID)
              .SingleOrDefault();

Not sure whether/how it would affect performance though, but definitely clearer.

foreach (Account account in AccountLogic.GetAccountsByCategory(categoryID))
{
    ...
}

Might have zero performance impact, but I find this cleaner:

var accounts = AccountLogic.GetAccountsByCategory(categoryID)
foreach (var account in accounts)
{
    ...
}

As for performance, I'd be tempted to blame WinForms and constant redrawing taking place - try to disable the refreshing of the DGV's as you're manipulating them; I'm pretty sure WinForms is redrawing the grid every time a column is added, and that requires quite a lot of computing that's not needed until you're done adding all the columns.


If you don't mind using a String switch, and can't use Java 8 yet (lambda expressions should greatly simplify your existing code), you could use something like the following (which replaces the use of inner classes with a single switch):

static {
    register("{worldname}", "{town}");
}

private static void register(final String... patterns) {
    for (final String pattern : patterns) {
        replacer.registerFormatReplacement(Pattern.quote(pattern), new TownyChatReplacerCallable() {
            @Override
            public String call(String match, LocalTownyChatEvent event) throws Exception {
                switch (pattern) {
                    case "{worldname}": return String.format(ChatSettings.getWorldTag(), event.getEvent().getPlayer().getWorld().getName());
                    case "{town}": return event.getResident().hasTown() ? event.getResident().getTown().getName() : "";
                    default: throw new IllegalArgumentException();
                }
            }
        });
    }
}

You would have to profile this to see whether the use of a switch made performance worse or better though (could be better, as the single registered function might be inlined and the switch should be fast).  You could also use constants variables instead of strings, but that would increase code size.


Your validation has a "major" flaw. You are validating each thing by itself, so If you user "creates" multiple validation errors, this provides a seriously bad UX. While we're at UX, your error messages could use some love: here's a little help from UX.SE
The easiest fix for this is to use binary flags, similar to the following:
[Flags]
Enum ValidatorFlags As Integer
   MonthSelect = 1 ' 0001
   YearSelect  = 2 ' 0010
   FilepathBox = 4 ' 0100
End Enum

Any combination of these flags is guaranteed to be backtraceable to the flags that are composing it (Sidenote: this is how linux permissions work).
As a sidenote: the Flags attribute as used in this enum and described more in depth in this SO question allows nice toString() magic (not that you'd need it). In the (currently) accepted answer there you also get a good lead on how you'd backtrace the original errors to the flags ;) The code also works fine without it though.
In addition to the mentined points and the very nice review by xDaevax (who also led me to the Flags question on SO), I want to mention that the names of your error message containers are gruesome.
Don't number your variables
Instead of Label1,2,3,... use descriptive names, just as you did in your InputFields
your code would then become somewhat like this:
Public Sub Validator 'leaving rest for brevity
    Dim Validator As ValidatorFlags
    If MonthSelectBox.Text = "" Then
       Validator |= ValidatorFlags.MonthSelect
       MonthErrorLabel.Text = "Please select a month."
    Else
       MonthErrorLabel.Text = ""
    End If

    If YearSelectBox.Text = "" Then
        Validator |= ValidatorFlags.YearSelect
        YearErrorLabel.Text = "Please select a year."
    Else
        YearErrorLabel.Text = ""
    End If

    If FilePathTextBox = "" Then
        Validator |= ValidatorFlags.FilepathBox
        FilepathErrorLabel.Text = "Please select a valid filepath."
    Else
        FilepathErrorLabel.Text = ""
    End If
    Return Validator
End Sub


Dynamically adding controls to a form in a WinForms project

In my eyes it is an appropriated way to build up your form that way. The *.Designer file is for designer generated code - but if you need to add custom logic to modify your GUI the *.cs file is the correct location.

Just a few points:

There are some numbers (115, 70, 35, ...) that seems to have a special meening (e.g. row height, margin, whatever). IMHO it makes sense to store that numbers as constants with a meaningful name and use that constants instead.
I am not sure if the MouseUp event is the right place to trigger that kind of logic. If there is another event (CheckBoxChanged, SelectedItemChanged, ...) I would suggest to use that.
There is some repeating logic for creating the ComboBox / Label and so on. That logic could be extracted to a separted method. For instance:

private static ComboBox CreateComboBox()
{
    return new ComboBox()
    {
        Font = new Font("Arial", 12F, FontStyle.Regular)
        Size = new Size(200, 22)
        DropDownStyle = ComboBoxStyle.DropDownList
    }
}


Finding the bounding box of a polygon array

Your code looks remarkably similar to the actual awt code used in Polygon to get the boundingBox...., start with extreme min/max values, and then go from there.

I often find that the choice to use min()/max() functions instead of if conditions is also fastest, so I agree with your code there.

What has me somewhat concerned, is the use of:

 final Rectangle polygonBounds = polygon.getBounds();

That's an interesting call, which may, or may not do a lot of work. Consider its implementation:

if (bounds == null) {
   calculateBounds(xpoints, ypoints, npoints);
}
return bounds.getBounds();

If the bounds have been previously calculated, then it will be very fast. If not, it will have to do a lot of work, and additionally create a bunch of instances of Rectangle.

In essence, if you check the bounds often and don't change the Polygons, then your bound-check is amortized quite well. If not, then you are doing a lot of unnecessary work.

In order to improve the elapsed time (execution time), about the only two things I can recommend are:

parallelism
keep primitive.

The combined parallelism/primitive would be easy to implement using Java 8 streams, and abusing that the Polygon data is public...

IntSummaryStatistics xstats = Stream.of(polygons)
     .parallel().
     .flatMapToInt(poly -> IntStream.of(poly.xpoints).limit(poly.npoints))
     .summaryStatistics();

IntSummaryStatistics ystats = Stream.of(polygons)
     .parallel().
     .flatMapToInt(poly -> IntStream.of(poly.ypoints).limit(poly.npoints))
     .summaryStatistics();

return new Rectangle(xstats.min(), ystats.max(),
     xstats.max() - xstats.min() + 1, ystats.max() - ystats.min() + 1);

The above code will be fine because it introduces the parallelism easily. If you are content with single-thread, an primitives only, I would recommend something like:

for (Polygon poly : polygons) {
    for (int i = 0; i < poly.npoints; i++) {
        xmin = Math.min(poly.xpoints[i], xmin);
        xmax = Math.max(poly.xpoints[i], xmax);
        ymin = Math.min(poly.ypoints[i], ymin);
        ymax = Math.max(poly.ypoints[i], ymax);
    }
}

The above will be faster when you would otherwise have to recalc all the poly bounds anyway....

Unfortunately, it all depends on your use case, and your ability to multithread.

If you are constrained, then you may as well stick with what you have, it's fast, neat, and otherwise fine.


Buying bunnies, eggs and elections with tax and a discount

Using from math import * is highly discouraged. Please always use either:

from math import sqrt, or
import math and use math.sqrt instead of sqrt.

You are not using math and so the import is not needed.
It is commonly recommended to use either f-strings or str.format to format your strings. This is as they make reading the format easier on more complex formats.

In your case you won't see this benefit too much but it would be a good habit to get now, rather than later.

print("Bunnies will cost {} dollars each.".format(bunnies))
print(f"Bunnies will cost {bunnies} dollars each.")

Please don't use unnecessary parentheses. This is as they add unneeded clutter to your code.
You can simplify the calculation for final_cost

$$
\begin{array}{r l}
c &= bq\\
t &= 0.089c\\
f &= c + t\\
f &= 0.089c + c\\
f &= (0.089 + 1)c\\
f &= 1.089bq
\end{array}
$$
The statement final_cost == final_cost > 57.89 is confusing and only works due to Python splitting the code into two different conditionals connected with an and.

The statement final_cost == final_cost will always be true, and so by all metrics is just bad.
Your ifs are missing if the final cost is 57.89 exactly. I assume this is a mistake.

When you have two ifs like this when one is getting half the options and the other is getting the other half it is better to use an if and an else rather than two ifs.
You don't need to store discount1 in a variable, it's just adding lines with no visible benefit.
Whilst there's nothing inherently wrong with printing the same string with a slight modification twice, you may be inclined to change it so you only define the structure of the print once.

Overall this would get:

bunnies = 30
print(f"Bunnies will cost {bunnies} dollars each.")
quantity = int(input("How many would you like to buy?: "))
final_cost = 1.089 * bunnies * quantity
if final_cost >= 57.89:
    with_discount = final_cost - 0.13 * final_cost
    print(f"Your total will be {with_discount} with a discount")
else:
    print(f"Your total will be {final_cost} without a discount")

From here we can see all the other options have almost exactly the same code. There are only three things that change:

The variable name bunnies.
The value of the variable bunnies
The name of the item you're buying.

From this we can see that a function would be good.

def price_to_buy(item, price):
    print(f"{item} will cost {price} dollars each.")
    quantity = int(input("How many would you like to buy?: "))
    final_cost = 1.089 * price * quantity
    if final_cost >= 57.89:
        with_discount = final_cost - 0.13 * final_cost
        print(f"Your total will be {with_discount} with a discount")
    else:
        print(f"Your total will be {final_cost} without a discount")

ask = input("Would you like to buy bunnies, eggs, or elections?: ")
if ask == "bunnies":
    price_to_buy("Bunnies", 30)
if ask == "eggs":
    price_to_buy("Eggs", 10)
if ask == "elections":
    price_to_buy("Elections", 20)

Advanced changes

Whilst the above is probably what your instructor expects from you, there are more ways to improve the code and make it shorter.

You can store the name and value in a dictionary, allowing you to condense those ifs into two lines of code.

You may want to use a try and except here to get the code to function the same if you don't enter valid input.
You can use str.title() to make the inputted item's name display in title case.
You can use an if __name__ == "__main__": guard to prevent the code from running when imported, normally by accident.
You can use a turnery to apply the discount, this is basically just an if and else but on one line!

By also using tuple unpacking we can get the preposition (with/without) and the discount percentage in one line.
You can use a try and except to display a nice error message.
You can use foo -= ... rather than foo = foo - ....

def price_to_buy(item, price):
    print(f"{item} will cost {price} dollars each.")
    value = input("How many would you like to buy?: ")
    try:
        quantity = int(value)
    except ValueError:
        print(f"{value} is not an integer.")
        return
    cost = 1.089 * price * quantity
    discount, prep = (0.13, "with") if cost >= 57.89 else (0, "without")
    cost -= discount * cost
    print(f"Your total will be {cost} {prep} a discount")

PRICES = {"bunnies": 30, "eggs": 10, "elections": 20}

if __name__ == "__main__":
    item = input("Would you like to buy bunnies, eggs, or elections?: ")
    price_to_buy(item.title(), PRICES[item])


Bool function in PHP to check if you run the script inside docker

For this simple method, I have a couple thoughts below. Your method seems sufficient; I don't think a completely different approach is necessary, although I question how often this method is called. If it is called more than once per page load/script run, it may be worth memoizing the value once obtained for better performance.

Good job utilizing the PHP 7 return type declaration.

Because the method utilizes no instance properties or methods, it could be declared as static, and possibly public so other code could use it, though maybe it is best to leave it as private until there is a legitimate need to make it otherwise.

While the logic would need to be reversed, substr_count() could be used instead of strpos(). The difference is likely negligible but you need to ask yourself in which case would you rather have the method return as soon as the string is or isn't found...

    foreach ($processStack as $process) {
        if (substr_count($process, 'docker')) {
            return true;
        }
    }
    return false;


Find, on a sequence of size L, the number that appears more than L/2 times

Bug / unexpected result

Focusing only on mostFrequentElement() method

Assume passing the array {2,2,3,3,3} this will result in "None" but the correct result should be "3".

To get rid of this unwanted result, we need after the loop to increment the counter by 1 and add a check

counter++;
if (counter > bigCounter) {
    big = arr[arr.length - 1];
    bigCounter = counter;
}

Simplification

Because you are incrementing counter wether the if condition is true or false this can be simplified to

for (int i = 0; i < arr.length - 1; i++) {
    counter++;
    if (arr[i] != arr[i + 1]) {
        if (counter > bigCounter) {
            big = arr[i];
            bigCounter = counter;
        }
        counter = 0;
    }
}

General

Instead of return big + ""; you should use the return String.valueOf(big); because it is more readable.
you should also check if the given array contains any element.
declaring multiple variables on one line removes readability.
you can initialize bigCounter with 0 because counter is always > 0.
big and bigCounter aren't good names. Better name them mostFrequentElement and mostFrequentElementCounter and rename the method to getMostFrequentElement.
Using verbs or verb phrases for methodnames improves readability.

Refactoring

private static String getMostFrequentElement(int[] arr) {
    if (arr.length == 0) {
        return "None";
    }

    Arrays.sort(arr);

    int counter = 0;
    int mostFrequentElement = -1;
    int mostFrequentElementCounter = 0;

    for (int i = 0; i < arr.length - 1; i++) {
        counter++;
        if (arr[i] != arr[i + 1]) {
            if (counter > mostFrequentElementCounter) {
                mostFrequentElement = arr[i];
                mostFrequentElementCounter = counter;
            }
            counter = 0;
        }
    }

    counter++;
    if (counter > mostFrequentElementCounter) {
        mostFrequentElement = arr[arr.length - 1];
        mostFrequentElementCounter = counter;
    }

    if (mostFrequentElementCounter > arr.length / 2) {
        return String.valueOf(mostFrequentElement);
    }
    return "None";
}


Is this approach correct when testing an Angular controller?

It doesn't look to me like proper Unit test.
You are injecting the real dependency but are not mocking.
Unit test is about testing your single Unit of functionality in isolation, with all it dependencies mocked.

Here is example from of my own test code.
This is a proper mock - I am producing a fake Constant:

beforeEach(module(function($provide) {
  $provide.constant('hotelsArray', [{i: 1, n: 'h1'}, {i: 2, n: 'h2'}, {n: 'h3'}, "11"]);
}));

And this is injecting the actual Service:

beforeEach(inject(function(_Hotels_) {
  Hotels = _Hotels_;
}));


There are a lot of performance aspects that can be improved in your code. I will cover general suggestions assuming that this code is for Win32 target. I will use minGw compiler with c11 standard.
Compiler Optimizations:
Without optimization code runs about 12.8 seconds on my PC. With -O3 optimization flag it takes about 10.6 seconds (about 17% faster).
Data types and arithmetic operations:
double type and constants with high precision are used in the code. Do you really need this precision? Moreover infinity is used in maxerror variable: double maxerror = 1.0/0.0; Consider to use DBL_MAX instead of inf. If performance is important then general algorythm of data types selection is following:

Can I use integer arithmetics? Prefereably int/uint types with logical/shift operations.
If not, then can I use float?
If not, then chose double or more precise types.
If floating point data types are used then consider NOT using floating point exceptions, NaN, Inf and denormal values. All these things can be very slow.

For example, you extract color components in the following way:
color1[0] = sRGBtolinear((color/65536%256)/255.0);

Here integer division can be replaced by bitwise/shift operations which is much faster. Assembly code will be almost 3 times shorter.
color1[0] = sRGBtolinear(((color >> 16) & 0xff)/255.0);

Inlining:
As it has been already mentioned inline keyword is confusing nowadays. Compilers have attributes or pragmas to always_inline/force_inline or noinline functions, because it is very important in some cases. E.g. if you want to insert assembly code with label in function wich compiler decided to inline. In this case compilation will fail. Only prohibiting inlining can help. In our case functions lineartosRGBOrig and lineartosRGBderivativeOrig can't be inlined because they are recursive. By the way, this recursion is not needed because input to these functions is always positive in current algorithm.
Algorithm changes and code rearrangment:

It is better to move variables declarations from the loop.
Values related to color in function selectnearest can be calculated only once istead of recalculation palettelength times.
RGBtolinear data can be precalculated as a table with 255 elements to significantly improve performance.
initdistance and brightness values are used only in comparison which allows us to remove sqrt operation and some divisions because we don't need exact values. Only relation is important.

Some brief optimizations:
I have made some optimizations that improved performance by 86% to original code compiled with -O3 flag and by 89% to code compiled without optimization. The code is not perfect but it is much faster.
#pragma GCC push_options
#pragma GCC optimize ("O3")

double gRgbToLinearTable[255];

void InitRgbToLinearTable(){
    for (size_t i = 0u; i < 255u; ++i)
    {
        double val = i / 255.0;
        gRgbToLinearTable[i] = (val > 0.0404482362771082 ? pow((val+0.055)/1.055, 2.4) : val/12.92);
    }
}

[[gnu::always_inline]] inline double square(double x) { return x*x; }

[[gnu::always_inline, gnu::flatten]] inline void sRGBtolinear(double* outComponents, uint32_t color){
    outComponents[0] = gRgbToLinearTable[(color >> 16) & 0xff];
    outComponents[1] = gRgbToLinearTable[(color >> 8) & 0xff];
    outComponents[2] = gRgbToLinearTable[color & 0xff];
}

[[gnu::always_inline, gnu::flatten]] inline double lineartosRGB(double input){
    if (input > 0.00313066844250063)
        return (pow(input, 0.4166666666666667)*1.055-0.055);
    else
        return input*12.92;
}

[[gnu::always_inline, gnu::flatten]] inline double lineartosRGBderivative(double input){
    if(std::abs(input) > 0.00313066844250063) return pow(input, -0.5833333333333334)*0.4166666666666667*1.055;
    else return 12.92;
}

size_t selectnearest(const uint32_t* palette, size_t palettelength, uint32_t color)
{
    size_t index = 0;
    double maxerror = DBL_MAX;
    double colors[2][3];
    double initdistance, brightness[2], rgbBrightness[2], brightnessdifference, sRGBbrightnessdifference;
    sRGBtolinear(colors[0], color);
    brightness[0] = (0.212671*colors[0][0])+(0.715160*colors[0][1])+(0.072169*colors[0][2]);
    rgbBrightness[0] = lineartosRGB(brightness[0]);

    for (size_t i = 0; i < palettelength; i++)
    {
        if (palette[i] != color)
        {
            sRGBtolinear(colors[1], palette[i]);

            initdistance = (square(0.212671*(colors[0][0]-colors[1][0]))+square(0.212671*(colors[0][1]-colors[1][1]))+square(0.072169*(colors[0][2]-colors[1][2])));
            brightness[1] = (0.212671*colors[1][0])+(0.715160*colors[1][1])+(0.072169*colors[1][2]);
            rgbBrightness[1] = lineartosRGB(brightness[1]);

            if(brightness[0] != brightness[1])
            {
                brightnessdifference = brightness[1] - brightness[0];
                sRGBbrightnessdifference = rgbBrightness[1] - rgbBrightness[0];
            }
            else
            {
                brightnessdifference = 1.0 ;
                sRGBbrightnessdifference = lineartosRGBderivative(brightness[0]);
            }

            double result = initdistance*(sRGBbrightnessdifference/brightnessdifference);
            if(result < maxerror){
                index = i;
                maxerror = result;
            }
        }
        else
        {
            return i;
        }
    }

    return index;
}

uint32_t* MakeSamplePalette(size_t amountOfColors)
{
    uint32_t* pResult = new uint32_t[amountOfColors];
    for(size_t i = 0; i < amountOfColors; i++)
    {
        pResult[i] = i%6*0x000033 + i/6%6*0x003300 + i/36%6*0x330000;
    }

    return pResult;
}

int main()
{
    const size_t amountofcolors = 216u;
    uint32_t* palette = MakeSamplePalette(amountofcolors);
    volatile uint32_t color;

    InitRgbToLinearTable();
    for(size_t i = 0; i < 65536u; i++){
        color = (static_cast<unsigned int>(rand()) & 0xfff)+(static_cast<unsigned int>((rand()) & 0xfff) << 12);
        color = palette[selectnearest(palette, amountofcolors, color)];
    }

    delete[] palette;
    return color;
}
#pragma GCC pop_options


Fetch an array result set using a mysqli wrapper class

First, you can use mysqli_result::fetch_all in your connectionclass::get_data() instead of manually looping and building the result array.

Second, you can use foreach to easily iterate through results


Guessing a random number between a range of numbers

You can read this to understand scope of variables or method.

In short:

public - Any member of a class declared as public can be accessed outside of the class. So declare public when you want to give client code access to methods/variables of a class.
private - A private method or field is invisible and inaccessible to other classes, and can be used only within the class in which the field or method is declared.
protected - Protected variables and methods allow the class itself to access them, classes inside of the same package to access them, and subclasses of that class to access them.
static - In general when a number of objects created from the same class, they all have their distinct copies of instance variables stored in different location. Sometimes we want to have variables that are common to all objects. To accomplish this use static. Read this.

Think of the main method as a place where you can write code to test your class. No design / logic should be placed in main.

For example:

public class Hilo {
 public Hilo() {}
 //other methods...

public static void main(String[] args) {
 Hilo hilo = new Hilo();
 hilo.getRange();
 hilo.playGame();
 }
}

I would prefer to remove all the static variables used in your class and make those private. The two methods getRange and playGame can be public.


Implementing IDisposable correctly to return TCP connection back to pool

The days of using IDisposable for things like this only came about because of the lack of functional programming concepts in C#. Now that Action and Func<T> exist there's absolutely no reason to use IDisposable for this situation.

A pool of connections/resources can expose a much nicer and simpler interface that removes the need for the using statement altogether and as a result avoids the possibility of the caller "forgetting" to give the resource back to the pool. Just because something implements IDisposable it doesn't mean that the caller will dispose of it properly.

A few points on your implementation:

Your BaseClass is completely unnecessary and can be removed.
The manager class has a poor implementation of what's already in the .NET framework: ConcurrentQueue. It's not only a better option because you don't have to write it, but it's lock-free and much more efficient.
The manager class's lock forces serialised access to one thread at a time, even if there are plenty of resources available. If you have 30 connections, you should let 30 threads access your resource pool at once, not just 1. Use a Sempahore instead.

So with this in mind I'd like to make a couple of suggestions.

Generalise your resource pool. The resource pool shouldn't be coded to a specific type of thing. Anything of any type can be pooled.
Avoid the use of disposable and use higher order functions to wrap up the lifetime of the resource. The consumer can not possible forget to give the resource back to the pool because you're doing it all for them.
Use proper .NET collections to solve the problem, not your own implementation.
Avoid a straight lock which serialises access when you can instead use a semaphore.
Don't push the logic of resource creation into the pool. Pass in a function that can do the creation for you, then you can have something that can create objects of arbitrary complexity.

Here's a quick implementation I've just thrown together (haven't compiled it, it's for reference and for ideas only):

public class Pool<TResource>
{
  private const int PoolWaitTimeoutMs = 1000;

  private readonly BlockingCollection<TResource> _resources;

  public Pool(int size, Func<TResource> producer)
  {
    _resources = new BlockingCollection<TResource>();

    for(var i = 0; i < size; ++i)
    {
      _resources.Add(producer());
    }
  }

  public void Consume(Action<TResource> consumer)
  {
    // This is a helper for when consumers don't produce a result
    Consume(new Func<TResource, object>(res => { consumer(res); return null; }));
  }

  public TResult Consume(Func<TResource, TResult> consumer)
  {

    TResource res;

    try
    {
      // wait for a resource to become available
      if (!_resource.TryTake(out res, PoolWaitTimeoutMs))
      {
        throw new Exception("Unable to acquire resource");
      }

      // invoke the consumer function and return the result
      return consumer(res);
    }
    finally
    {
      // put it back in the queue if we managed to get one
      if(res != null)
      {
        _resources.Add(res);
      }
    }
  }
}

Using the pool them becomes as simple as this:

public class SomePooledResource
{
  public void DoStuff() { ... };
  public List<string> GetStuff() { ... };
  // other stuff
}

// create a pool of 10 resources
var pool = new Pool<SomePooledResource>(10, () => new SomePooledResource);

// use the resource without returning something
pool.Consume(res => res.DoStuff());

// use the resource returning a result
var results1 = pool.Consume(res => res.GetStuff());

// use the resource to do both
var results2 = pool.Consume(res =>
    {
      res.DoStuff();
      return res.GetStuff();
    });


For the part where you first read the file, you could write it like this:
import collections
import re

file = open('bee_movie.txt', 'r')

text = ""
words = collections.Counter()
punctuation = '1234567890!@#$%^&*()_-+=-/*{}[];:\'"\\<>~`|?'
all_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
all_lower = "abcdefghijklmnopqrstuvwxyz"
translation = str.maketrans(all_upper, all_lower, punctuation)

for line in file:
    text += line # concatenating like this is optimized in python 3
    words.update(line.translate(translation).split())

print(sum(words.values()))
print(len(words))
file.close()

For the part where you’re replacing words, it would be faster if you used re.sub. When you use text.replace, it needs to remake the entire script every time it’s used.
Also you should save the text files as .txt files, they don’t need the .py extension.
Btw you can import string and use string.ascii_uppercase, string.ascii_lowercase, and string.punctuation if you don’t want to type out all the characters.


ChangeCalculator for calculating money denominations in change

The main problem with your code is that you've been encoding currency denomination data in C#'s type system: one type for each currency. That somehow led to a complicated interface/generics design, all without providing any real benefits. In fact, this design has several drawbacks:

Each new currency requires additional code (3 extra classes in total).
Apparently the core money-to-coins algorithm needs to be duplicated for each new currency - a proper design should make this reusable across different currencies.
Those generic interfaces aren't very useful: IChangeCalculator<MoneyAmountPLN> is not interchangeable with IChangeCalculator<MoneyAmountEuro>, despite being the 'same' interface.
The IChangeCalculator layer doesn't seem to provide much value: this could easily be done at the call-site.
Wrapping the results in an IMoneyAmount object on which the caller has to call a GetAmounts method seems a little pointless - why not just return those amounts directly?

This can be simplified a lot with a data-driven approach. The core money-to-coins method needs an amount and knowledge about a currency's denominations, and returns a list of coin (or bill) amounts:

public (int amount, decimal denomination)[] SplitIntoDenominations(
    decimal amount,
    decimal[] denominations)

Such a method can easily be reused for different currencies:

var euroDenominations = new decimal[] { 500m, 200m, 100m, ..., 0.05m, 0.02m, 0.01m };
// Denomination arrays can be stored anywhere: in hard-coded arrays,
// in a currency-name/denominations dictionary, or loaded from a file, etc.

var returned = SplitIntoDenominations(amount, euroDenominations);
foreach ((var amount, var denomination) in returned)
    Console.WriteLine($"{amount} coins of €{denomination}.");

You may find it useful to create a CurrencyInfo class that contains a denominations array as well as the name and symbol of the currency, and perhaps additional information, depending on your needs:

var euro = new CurrencyInfo("Euro", "€", new decimal[] { 500m, ..., 0.01m });
var dollar = new CurrencyInfo("Dollar", "$", new decimal[] { 100m, ..., 0.01m });

The same can be done for the return value of this method, if you find an array of named tuples to be insufficient. Again, this depends on your needs, but keep in mind that you only need a single class, regardless of currency.


Binary Search Tree to store objects by object ID

Stop using namespace std;

Having using namespace std;, especially in a header file is considered bad practice. This Stack Overflow post explains the reasoning quite well. In your case it's especially unnecessary since you do not even use something from this namespace in BST.h and only std::string in Packet.h.

Unnecessary includes

Again BST.h. There are a lot of unused includes in there. The only one that might serve a purpose would be Packet.h which could easily be replaced by a forward declaration. Most of the include should go to the corresponding .cpp file.

The BST

I'm not sure about the interface. If your intended usage is to pass packages by reference, it would be desirable to declare BST::insert(Node *&p, Node *newNode) as private, similar to the public and private versions of preorderTraversal. preorderTraversal might also be better called printPreorder or something like this since it only prints the nodes and does not allow to access them.

There is also a small memleak in insert since those Node*s created with Node *newNode = new Node; will never get deleted. valgrind confirms this. As @TobySpeight rightfully pointed out in his comment and detailed in his answer, one can argue if leaking all of the tree's nodes should really be considered as a "small" memleak. A possible solution for this is to use smart pointers from <memory>. There is a good overview in this blog post by Herb Sutter on which type of smart pointer (e.g. std::unique_ptr or std::shared_ptr) as well as the type of parameter passing (by-reference vs. by-value) should be used to express a certain "meaning".


In iOS 4 and later you are encouraged to use animation blocks.

[UIView animateWithDuration: 0.5f
            delay: 0.08f
            options: UIViewAnimationCurveEaseIn
            animations: ^{
                self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            }
            completion: ^(BOOL finished){
               // any code you want to be executed upon animation completion
            }
];

One advantage of using block-based animation is that

  When this code executes, the specified animations are started immediately on another thread so as to avoid blocking the current thread or your application’s main thread.

This means that the rest of your application will not be "locked up" while your animation is executing.


Three functions to select a random character, each of which can be used at most twice

Iterative instead of recursive

Python doesn't really suit itself for recursion

No tail recursion
Generally slower
Limited max depth

Use ALL_CAPS for constant variables

marshels is a constant variable and should be written in ALL CAPS

Thnx @Gareth Rees for clarifying
Functions and variables should be snake_case
@Caridorc is correct in saying that something like isinstance() might work, but without the actual class it is difficult to tell
Think about changing the data type of usedMarshels

list.count(x) is an \$O(n)\$ operation, see time complexity, meaning it will have to loop through the entire list to find how many there are.

Instead you could hold a dictionary of the amount of marshals making it an \$O(1)\$ operation.

Here is some code to give you an idea hopefully,

import random

# Random Marshall class
class Marshel():
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

a = Marshel("First Marshal")
b = Marshel("Second Marshal")

MARSHELS = [a, b]
used_marshals = {a: 2, b: 1}

def get_leader(type_):
    while True:
        # marshal = random.choice((m for m in MARSHELS if isinstance(m, type_)))
        marshal = random.choice(MARSHELS)
        if marshal not in used_marshals or used_marshals[marshal] < 2:
            return marshal

if __name__ == "__main__":
    print(get_leader("Does nothing yet"))
    # Will print "Second Marshal" because that is the only viable option


Trimming unicode whitespace, control characters, and line breaks with regex

So I've toiled away at this for a while and although I am feeling a little out of my depth I'll submit my approach which employs what I do understand about preg_replace and regex.

preg_replace() allows mixed type pattern and replacement parameters, so one call can execute multiple patterns/replacements.
Speeding up regex can be achieved by minimizing capture groups and alternatives (pipes) as well as using character classes and negated characters classes where appropriate.

I've prioritized accuracy and endeavored to provide the most robust patterns considering all possible character sequences that may be submitted from the textarea.  Then I've attempted to write each pattern with greater efficiency (without impacting accuracy).  Finally, I've tried to reduce the overall length and convolution of the regex patterns.

I want to be clear that I don't have any experience with recursive patterns.  I don't know how/when to use them effectively and so none of my patterns employ them.

This is the sample input that I used which has whitespaces, newlines (single and greater than double), and control characters:

$text="\0\n\n\1\n\r\n\13\27a ab\r\n\t\t\r\r\ncà\1êß€\0\0abcbc   d\n\n\t\r\n\5   e\2\n\3\n\4\n";

This input string was designed to be as difficult as possible to best test my method.

$patt_repl=[
    '/^[\s\pC]+|[\s\pC]+$/u'=>'',  // aka mb_trim() -- remove all leading and trailing whitespace and control characters. DO NOT ADD m FLAG TO PATTERN, THAT WILL DAMAGE THE STRING
    '/[\s\pC]*?(\R)[\s\pC]*?(\R)[\s\pC]*/u'=>"\n\n",  // cleans 2 or more new lines (uninterupted by non-white space characters)
    '/(?!\R)[\h\pC]*\R[\h\pC]*(?!\R)/u'=>"\n",    // cleans single new lines
    '/\n+(*SKIP)(*FAIL)|[\h\pC]+/u'=>' '  // convert 1 or more non-newline white-spaces and control characters to single space
];

$text=htmlspecialchars(preg_replace(array_keys($patt_repl),$patt_repl,$text), ENT_HTML5, 'UTF-8');

echo "This is the post-replace/result string dump:\n";
var_dump($text);

Yes, my method uses 4 separate patterns rather than 3 like the OP.  This is for improved accuracy.  I believe the OP's method had some gaps in accuracy, so that is the justification for the additional pattern.

The output from the above method is:

This is the post-replace/result string dump:
string(28) "a ab

cà êß€ abcbc d

e"

...which is what I believe the output should be.

It trims all leading and trailing whitespace and control characters from the input string.
It reduces two or more newline characters (which may have leading, in-between,  trailing whitespace or control characters) to \n\n.
It trims all leading and trailing horizontal whitespace or control characters from all single newline characters.
It converts 1 or more consecutive horizontal whitespace or control characters to  (a single space).  This, during my development, required me to use the (*SKIP)(*FAIL) technique to disqualify newline characters becausse \h wasn't doing what I expected.  I have read on SO and elsewhere that there can be some quirky/untrustworthy behaviors when dealing with \h and \v while processing certain characters on certain systems -- but I do not possess the necessary wisdom to explain this.

For my own confidence, I wanted to have a way to confirm the existence/absense of whitespace and control characters in the string before and after the method.  I found a very helpful function in the top comment at the php manual's ord() page.

Here is a PHP demo that iterates the string and identifies each and every character to prove effectiveness.

Here are a few relevant regex links that I visited during my research:

https://www.regular-expressions.info/unicode.html
https://stackoverflow.com/questions/3230623/filter-all-types-of-whitespace-in-php
https://stackoverflow.com/questions/5471644/what-are-the-whitespaces-matched-by-s-in-php

On the matter of ReDoS and Catastrophic Backtracking, the threat is minimal (if not non-existent) because of my use of character classes and the structure of my alternatives.  In case you haven't already visited it, here is a good page to read if you want to investigate further.

Finally, I humbly ask that if anyone has a string that breaks my method, please provide it to me so that I can update my answer.  And if any of my assertions are incorrect, please correct me.


The unique keys will enforce the requirements you specified, but unless your data entry program either traps error codes returned by MySQL and prompts the user for correction or checks for uniqueness before saving the record, you will probably experience a lot of record rejections where you won't understand why.

I would also use a much larger VARCHAR maximum length for the image_version_e.src column. Remember that VARCHAR columns only require as much storage space as needed for the actual data with trailing spaces stripped (usually). VARCHAR(255) or more is not unreasonable as it will accommodate those really long directory paths or URLs. Your data entry form field for it should be scrollable but much shorter... probably a multiline text field.

See more details in the MySQL documentation of CHAR and VARCHAR.


Bash function that allows running user aliases with sudo on Ubuntu

First of all, you need to quote $@:

command sudo "$@"

If you don't your function will break if the command you pass to sudo contains a space in its path.

Then, this will break if your input is aliased to something which contains a backtick. For example:

$ alias foo='ls `which sudo`'
$ type foo
foo is aliased to `ls `which sudo`'

Now, the output of your sed command is not what you expect:

$ type foo | sed -E 's/^.*`(.*).$/\1/'
$

That will return nothing since the ^.*` means "match the longest possible string from the beginning of the string to a backtick" and, therefore, will match everything except the final '. A better approach would be to use a tool that has non-greedy matching like perl:

$ type foo | perl -pe 's/^.*?\`(.*).$/\1/'
ls `which sudo`

You will also need to eval it in order for it to run correctly:

$ "$(type foo | perl -pe 's/^.*?\`(.*).$/\1/')"
bash: ls `which sudo`: command not found
$ eval $(type foo | perl -pe 's/^.*?\`(.*).$/\1/')
/sbin/sudo

Putting all this together, gives:

sudo() {
    # check if the command passed as argument is an alias
    if alias "$1" &> /dev/null ; then
        # extract the aliased command from the output of 'type'
        # and run it with the remaining arguments
        eval $(type "$1" | perl -pe 's/^.*?\`(.*).$/\1/' "${@:2}")
    else
        # run the original 'sudo' command with all arguments
        command sudo "$@"
    fi
}

I can't guarantee that it will work for all cases though. All things considered, I wouldn't use this approach at all. I would instead use

alias sudo='sudo '

As explained here.


Some notes:

More declarative: x.nil? -> !x
More declarative, idiomatic and compact: is_system == true -> is_system.

A first obvious refactor is DRYing the common conditions using a local variable (a temptative name, you'll know what's more fitting):

unpaid_subscription_suspended = subscription.suspended_at &&
    !suspended_email_1_sent_at && subscription.suspended_at >= Date.today &&
    is_system && !paid_at

if term_type == TERM_MONTH
  unpaid_subscription_suspended && subscription.suspended_at < MONTHLY_WARNING_1.from_now
else
  unpaid_subscription_suspended && subscription.suspended_at < ANNUAL_WARNING_1.from_now
end

A second refactor is to refactor the conditional and move all the expressions to the if/elsif predicates:

case
when !(subscription.suspended_at && !suspended_email_1_sent_at &&
       subscription.suspended_at >= Date.today && is_system && !paid_at)
  false
when term_type == TERM_MONTH && subscription.suspended_at < MONTHLY_WARNING_1.from_now
  true
when term_type == TERM_YEAR && subscription.suspended_at < ANNUAL_WARNING_1.from_now
  true
else
  false
end

As an additional advice, you should group those conditions into methods. For example the first chain of conditions may be abstracted as Subscription#unpaid_subscription_suspended?.


You definitely can make your code cleaner :

Your function main does all the job, that's usually quite bad. You can, at least, separate two aspects : reading the input (and store it in an array) and processing the input. That would be a little bit easier to read
Use comments ! Not even one here, that's pretty bad.
Better use of new lines : you really tend to use way too much of them. Multiple new lines should be used to separate parts of code that do quite different things, but in no case you should use two just after an if
Better variable naming : just one example, but it's because it's very common : i . I really don't like it, because by reading the index, you don't know through what you iterate. The best example for that are matrices, i and j are far less understandable than iRow and iCol
The indentation is also quite bad, especially at the end
You don't free the memory you have allocated.
Have you tried removing your condition on flag in your while ? You set it to false, then there's an if/else, and in both cases, it's set to true again.


I tend to prefer composition over inheritance, but I see why you inherited from List<T>, and I feel like it's okay, but you'll run into some trouble if you decide that some other type of collection would be better suited to your task. I would spend a little time thinking about what you'd need to do in your client code if you changed the implementation. It may be worth implementing IList by delegating to a private instance of List<IVideo>. Then again, it may not be.

XmlSerializer and StreamWriter both implement IDisposable, so it'd be better to put your usages of these into a using block. For example:

public void SaveChanges()
{
    using (var xmlSerializer = new XmlSerializer(Collection.GetType()))
    using (StreamWriter writer = new StreamWriter(RepoPath))
    {
        xmlSerializer.Serialize(writer, Collection);
    }
}


On a simulator with the original code, it takes about 1.52s on my machine.

Since the base image won't get resized (self.size is passed in self.draw(in:)), and its alpha channel is always 1, I could gain at least 200ms by using the following :

self.draw(at: CGPoint.zero, blendMode: .copy, alpha: 1)


Extension method to format properties that are not null and not empty

You're asking for a review of a tiny amount of decent code, so there is not much to say.

return string.Join(" ", parts.Where(s => !String.IsNullOrEmpty(s)));

You're first using string and then String to call a static method. You should be consistent in which one you use.

throw new ArgumentNullException("Address");

If you're using C# 6.0, you could use nameof here:

throw new ArgumentNullException(nameof(Address));

(And Heslacher already mentioned in a comment that it should be address.)

Assert.That(new AddressDto { }.FormatForGui(), Is.EqualTo(""));

I think that Assert.AreEqual() is better, mostly since it's slightly shorter and doesn't use the weird Is pattern:

Assert.AreEqual("", new AddressDto { }.FormatForGui());


Order line reversing (reversing line order)

First I need to mention that I have been learning C coding for some time but would call myself an intermediate beginner at best. So take what I say with the right amount of scepticism.

int MAXSIZE

To define constants like buffer sizes it is better to use const int which make your intention clearer.

Also you should be more consistent with the spaces around your arithmetic operations:

For example, strlen(inputStr) - 1 is clearer than strlen(inputStr)-1.

You should be constant with the way you use functions and how you intend their arguments:

f(arg1, arg2) instead of sometimes f (arg1,arg2) and sometimes f ( arg1, arg2 ).

In addition to these points, which will only improve the readability of your code, I am pretty sure that you could copy directly from input into the array
like this:

/* allocate space in the array for the string and copy it in */
array[i] = malloc((sizeof(char*)) *(strlen(inputStr)) + 1);
strncpy(array[i], inputStr, strlen(inputStr) + 1);

This way you can delete the intermediate step where you save the input into a separate string and allocate (and free!) memory for it.


Store and manage a fixed amount of things generally

Enum names are generally given in the singular form, rather than plural. Hence you may want to call your enum Category.

You should also consider using an EnumMap for your Map implementation:

private final Map<Category, Thing> things = new EnumMap<>(Category.class);

BTW, the return value of Map.put() will be the previously associated value, so you don't need the inner if (things.get (c) != null) { returnThing = things.get(c); } parts of your code (setThing()/removeThing()).

One more observation about your setThing() method: Since you are doing a t.category == c check before the insertion, why not make the method signature just setThing(Thing t)? In that case, the method body simply becomes:

public Thing setThing (Thing t) {
    // t == null check required?
    return things.put(t.category, t);
}

Now, to your question... may I know what's the fixation with exactly four entries in your things object, to the extent of mapping to null values? There is no difference in calling Map.get() for a mapped-to-null key, and an unmapped key: both returns null. The only difference is in Map.containsKey(), but as far as I can tell your class doesn't really expose this to external callers (which I guess is a good design). Is there a more relevant larger context to show how exactly four entries in things are being depended upon?

edit: The code-smell I observe here is that your code is doing/stating the obvious. Consider:

You use null to practically indicate the absence of a mapped Thing.
things is pre-populated with all your enum keys, so things.containsKey(category) will always be true.

In other words, things.containsKey(category) && anotherCondition can be simplified to anotherCondition.

When you are adding or removing mapped Things, you do a null-check to return the previous non-null mapping...
but if the mapping is to null, you return a null anyways.

As mentioned above, the relevant methods in Map already returns the previously associated value or null, so your null checks are pretty much redundant.

Unless your code clearly distinguishes between the absence of a mapping and a null-mapping, which I don't see here, you should simplify your logic to treat both as the same. If you do however, then the difference for Map.containsKey() becomes crucial here, and then all the more should you not have null-mappings...