Class/model hierarchy for a school-management application

You mention that you would rather not create extra models but I would consider creating a model for Teacher, Student and for Parent. It is not really that much more work but will probably keep the separation between the concepts much cleaner in the long run (as per Damien's comments). I personally would also use names like TeacherRole and ParentRole or TeacherFacet.

I would also consider keeping the cardinality as has_one unless you need to deal with the possibility that a user needs more than one teacher profile (possibly because they teach in more than one places) or more than one parent profile (maybe they have multiple children).

You obviously haven't shown your complete data model but it looks wrong that each user is linked to classes through the user_klasses relation but then you query classes using a profile_id field on the Klass. Firstly you probably want to query the profile_id on the UserKlass model (the profile_id on Klass looks like it refer to the teacher's profile) but you should probably put the klasses relation on the Profile model (or whatever you call it).

One other thing I noticed here:

  belongs_to :teacher, class_name: 'Profile', -> { where profile_type: 'teacher' },
                    dependent: :destroy

You probably don't want to remove the teacher record if a class is deleted, they may be teaching other classes after all. However you probably want to delete UserKlass if the Klass (or User for that matter) is deleted. Likewise it would make sense to delete the Profile record when a User is deleted.


Java Generics - Write a generic method to find the maximal element in the range [begin, end] of a list

So, here's the thing, what you have is not a generic method. What you have is a generic class.

Now, it's a clearly defined generic class, but, it is not what the question asked for. (as a generic class it has a number of issues too, but let's get the method/class issue resolved first).

Generic methods

A generic method is just that, a method, except the parameters (or return value) are of a generic type. A generic method always has a <...> structure before the return-type declaration. A normal method is:

public RType methodName(P1Type p1, P2Type p2, ....) {...}

(where RType is the return type, and P1Type is parameter1 type, etc.).

A generic method has the <...> before the return type, and that construct is used somewhere in the method signature... for example:

public <T> RType methodName(T t, SomeType sparm) {....}

The above is a generic method that has the generic type T as a parameter.

Your Class

So, having stated that your solution is a generic class, not a generic method, let's assume the exercise goal was to produce a generic class. What then?

Unless you have exceptional reasons, don't extend ArrayList, "compose" it instead. Have a class that does not extend ArrayList, and have a class field instead, like:

class MaximalElementList<E extends Comparable<E>> {

    List<E> data = ......

Your generics here are OK, no problem with <E extends Comparable<E>>
Your code should use a guard-condition instead of an else... let me explain. Your code has an if/else:

public E getMaxInRange(int begin, int end) {
    E max;
    if (isEmpty())
        throw new IllegalStateException("Can't get a max element from an empty list.");
    else {
        max = this.get(begin);
        for (E elem : this.subList(begin, end)) {
            if (elem.compareTo(max) > 0) {
                max = elem;
            }
        }
    }
    return max;
}

That should instead be:

public E getMaxInRange(int begin, int end) {
    if (isEmpty()) {
        throw new IllegalStateException("Can't get a max element from an empty list.");
    }

    E max;
    max = this.get(begin);
    for (E elem : this.subList(begin, end)) {
        if (elem.compareTo(max) > 0) {
            max = elem;
        }
    }
    return max;
}

Note now, that the max is a messy variable, it can just be:

    E max = this.get(begin);
    for (E elem : this.subList(begin, end)) {
        if (elem.compareTo(max) > 0) {
            max = elem;
        }
    }
    return max;

Your use of a sublist is smart, but I would consider it to be overkill in this case. How about a simpler implementation:

    E max = this.get(begin);
    for (int i = begin + 1; i < end; i++) {
        if (get(i).compareTo(max) > 0) {
            max = get(i);
        }
    }
    return max;

That is now some logic which I think would work well.

Making it a method

Putting that logic in a generic method would "simply" mean:

public <E extends Comparable<E>> E max(List<E> data, int begin, int end) {
    E max = data.get(begin);
    for (int i = begin + 1; i < end; i++) {
        if (data.get(i).compareTo(max) > 0) {
            max = data.get(i);
        }
    }
    return max;

}

With that method, for example, you could do:

List<String> data = Files.readAllLines(Paths.get("some file.txt"));
String maxLine = max(data, 0, 10);


Refusing to use a common template engine

Answer courtesy of JC

In MVC Frameworks, you will often find this question answered a multitude of ways. Here are two principles that I attempt to live by, with regards to this.

Separate business logic from presentation logic. If the function in question takes input from another source, and simply does some formatting on it, then it is similar to the view helpers used in most MVC frameworks, and thus is separated from any business logic that processed the input to the function. However, if the function itself is doing logic based upon its input to determine other things about the data, other then simply how to display it, you wind up with a situation where if you have more then one case down the road, this function will begin to grow substantially, and eventually may become impossible to understand, or inefficient.
Data processed by the system should be usable in many forms. If your data might be needed for other uses, beyond display, then you may later on find yourself having to refactor, or even duplicate the code, when you realize that you need 'Ted Developer' in 'Developer, Ted', 'Ted Developer' and 'Ted' forms, and your function only returns one of the three.


Similar but slightly different JavaScript functions

You can use js' bracket notation for this task

alter = (el, seek, method) -> el.find(seek)[method + "Class"]("active")
#use like this:
alter $("#something"), ".child", "add"

However, your situation doesn't really call for DRYness. Your method names make more sense than alter, or whichever name you may choose.


All the code from len_list1 = [] to a = max(len_list1) can be replaced with:

a = len(max(person_dict.values(), key=len))

max's key parameter is really helpful here. key is called on each element before max checks it. Dictionary's values method is useful here too. If you already have the data in a dictionary, you might as well make use of that fact.

You could also use a generator expression here to have the same effect:

a = max(len(val) for val in person_dict.values())

Or, since we're just mapping using an existing function, map would be clean here as well:

a = max(map(len, person_dict.values()))

The point is, use iteration constructs to avoid needing to repeat the same code over and over again for different objects.


Unused Imports

import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction;

This is never used, so why have it?

Useless Comments

// TODO Auto-generated method stub

Clearly, you've implemented the method.  Remove the TODO comment.

Singletons

Solution s = new Solution();
int x = s.solution(1041);

Solution is a class with no data members, just one function.  There is no reason to make an instance of this class, just make the method static.   Actually, there is no obvious reason to have the Solution class; you can make solution() a static member function in Main.

Pointless Box

Integer maxCountZeroList = 0;

There is no reason to have maxCountZeroList an object.  An int would be sufficient.  Since solutions() returns an int, and ends with return maxCountZeroList;, you are unboxing this integer anyway.

One Pass

You are doing two passes over your data.  The first pass you are counting non-'1' characters, and storing the counts in a List.  The second pass, this time over the list, you are looking for the max() value.

This can be done in one pass.

int countZero = 0;
int maxCountZero = 0;

String nBin = Integer.toBinaryString(N);
for (int i=1;i<nBin.length();i++) {

    if(nBin.charAt(i) == '1')
    {
        if (countZero > maxCountZero)
            maxCountZero = countZero;

        countZero = 0;
    }
    else
    {
        countZero++;
    }

}
return maxCountZero;

Enhanced For Loop

Instead of looping over the indices of nBin, and then calling .charAt() at each index (the only place the index is used), you could instead loop over the characters of the string, eliminating the need for the .charAt() call.

for (char ch : nBin.toCharArray()) {

    if(ch == '1')
    {
        if (countZero > maxCountZero)
            maxCountZero = countZero;

        countZero = 0;
    }
    else
    {
        countZero++;
    }

}

Looking for the wrong thing

This code is not counting "zeros".  It is counting "not ones".  It would be clearer written as:

for (char ch : nBin.toCharArray()) {

    if(ch == '0')
    {
        countZero++;
    }
    else
    {
        if (countZero > maxCountZero)
            maxCountZero = countZero;

        countZero = 0;
    }
}

Efficiency Improvement

@Harshal's improved solution is a bit obfuscated, but it does run in \$O(gap)\$ time.  Here is a less obfuscated implementation which runs in \$O({numGaps})\$ time.

int max_gap = 0;

n >>>= Integer.numberOfTrailingZeros(n);   // Get rid of ending 0's.
n >>>= Integer.numberOfTrailingZeros(~n);  // Get rid of ending 1's.

while (n > 0) {
    int gap = Integer.numberOfTrailingZeros(n);
    if (gap > max_gap)
        max_gap = gap;

    n >>>= gap;
    n >>>= Integer.numberOfTrailingZeros(~n);
}

return max_gap;

Assuming Integer.numberOfTrailingZeros(x) executes in constant time, the above while loop will execute once for each "gap", computing exactly how long each gap is.  With 0x40000001, Harshal's method must loop 31 times, where as this algorithm loops only once.  In contrast, with 0x55555555, this algorithm loops 15 times, finding each gap of one '0', where as Harshal's algorithm loops once; the maximum gap size.

Profiling, and knowledge of the distribution of values, will be important in choosing between the two optimizations.


Bugs

There are several things wrong with this function:

void address(consst uint8_t value)
{
  int counter = 0;
  int newVal = value;
  while(value == 97 && counter < 3)
  {
    counter++;
    newVal = RX.read();
  }
}

You never use the variable newVal, which is a mistake.  Most likely you meant the while loop to read:

while (newVal == 97 && counter < 3)

As it stands, your code will always read 3 extra bytes if the first is 97, even if the second byte is not 97.  You can also get rid of the newVal variable and just use value, if you change the type of value to make it non-const.
const is misspelled.
When you encounter a series of three 97 bytes, you actually read 4 bytes.  The first byte is already read and passed into this function.  The function then reads 3 extra bytes.  This means that the first byte of the "message" will be missing when you call processBytes() later on.
Your message protocol is unclear.  From your code, it appears that the message protocol must be 97 97 97 byte 97 97 97 byte which is extremely wasteful.  If that is not the protocol, there are problems with how you handle the message stream.  For example, the address() function strips all 97s out of the message stream, whether or not they are part of a sequence of three.  Also, if the address() function does not detect a sequence of three 97s, it always discards one byte out of the message stream.  I'd need to see an example of a proper message stream in order to advise on a solution.


Displaying all application errors in a view

While I see no problem design-like or code-like, in the point of view of the user, It can be frustrating.

I guess the method ConfirmEmail is called from a form.

So, imagine how frustrating it is if you fill a form and if there is any error in this form, it redirects you to the Error View ?

Imo, Error display should be handled by Javascript/Html/Css on the same page which thrown the error to avoid losing any data from user's pov. Like, displaying a notification or even an error message below the field.

How you display the error should be specific of the error.


I'm torn between conditionals and abrupt return functions

How about a ternary operator?

var redirect = req.from.redirect
  ? url.parse(req.from.redirect)
  : {
    protocol: 'http',
    hostname: config.domain,
    pathname: 'thanks'
  };

Looks cleaner in my opinion.


wrote a blackjack game in python , would like you get notes on it

Naming things

Try to give proper names to things, such that they follow the usual conventions, are concise, unambiguous and to the point. There are a few things I would change:

Rename cards to deck, to signify that it isn't just a random bunch of cards, but the actual deck you are drawing from.
The function hand() is quite misnamed, it's not about managing just one hand of cards, but rather it implements the whole game. So perhaps play_blackjack() would be better?
The function convert() has a very generic name, that doesn't tell anything about what it is converting from or to. It would be better named convert_card_to_value().

In general, variables describe things, so their names should usually be a noun, whereas functions describe actions, so they should be verbs.

Try to reorganize the code into classes

Classes make it easier to organize your code. I can think of at least three classes that you should make: Card, Deck and Hand.

A Card is quite simple, it just is the color and number of the card, and has a member function to convert it to a value.

A Deck is a collection of cards, with member functions like shuffle(), draw() and so on.

A Hand is also a collection of cards, but has member functions add() and get_value(). The latter is important: you can't just add values of cards together to get the total value of a hand. Think about drawing an ace, 9, king in that order. Your current code converts card values the moment they are drawn, and only checks aces against the total so far. So your method would count this as 11 + 9 + 10 = 30, whereas the correct value is 1 + 9 + 10 = 20.

Avoid infinite recursion

Your code recursively calls itself indefinitely. While this might seem harmless at first, the problem is that you are using more and more stack space, until after enough games played you get a stack overflow. The proper way to deal with this is to structure some parts of your code as loops. For example, you want to have a function to play one game of blackjack, and that function should be called in a loop like so:

def another_game():
     while True:
          answer = input('Would you like to play again?').lower()
          if answer == 'yes':
              return True
          elif answer == 'no':
              return False
          else
              print('Please enter yes or no.')

...

print('Hello!')

while True:
    play_game();
    if not another_game():
        break

print('Goodbye!')
```


This code runs in 2 secs vs the original 24 secs in my box, with no additional memory needed, or 0.5 secs if you don't mind using more than 1 CPU.

Going to explain how it works with an example:

Let say that "n" is 97.
At this point maxSoFar is 9232 (which is the value of cycleLength for 27, 31, 41, ...), which is the maximun value of cycleLength found for all "n" < 97.
97 * 97 is 9409 which is bigger than 9232, which means that if inside the loop of the cycleLength, "j" becomes smaller than 97, then cycleLength will be at most 9232, which is smaller than 9409 so it is not necessary to continue doing any calculations as cycleLenght will be never bigger than n * n.

So with "n" 97, n_square is 9409. We do the first loop, which means that "j" is 292. As "j" > "n", we still have hope that it can become bigger than 9409. Two cycles latter, "j" becomes 73 (292 / 2 / 2). Now we know that 73 is never going to be bigger than 9232, which means that there is no point of searching anymore and we can exit cycleLength.

Note that with this implementation cycleLength for 97 actually return 73 (instead of 9232 of your implementation) but the results are still correct.

The code is basically the same as yours but adding a condition in the cycleLength loop.

public class Main {

private static long maxSoFar = -1;

public static void main(String[] args) {
  long startTime = System.currentTimeMillis();

for (long n = 1; n <= 100000000; n += 2) {
  long value = cycleLength(n);
  if (value > (n * n)) {
    System.out.println(n + " " + value);
    maxSoFar = Math.max(value, maxSoFar);
  }
}

long endTime = System.currentTimeMillis();

System.out.println("Runtime = " + (endTime - startTime) + " milliseconds");
}//main

public static long cycleLength(long j) {
long hi = j;
long original = j;
long n_square = j * j;
while (j > 1) {
  if (j < original && maxSoFar < n_square) {
    return hi;
  }
  if ((j & 1) == 0)  // bitwise AND
  {
    j = j >> 1;  // n even
  } else {
    j = 3 * j + 1; // n odd
    if (hi < j) {
      hi = j;
    }
    j = j >> 1;
  }
}

return hi;
}

}

The multithreaded version creates a bunch of threads each one calculating a different serie of n. So for 2 threads:
Thread 1 will do 1, 5, 9, 13 ...
Thread 2 will do 3, 7, 11, 15 ...

In my box (4 cores) the optimal value for n = 10^8 is 32 threads.

import java.util.concurrent.ConcurrentHashMap;

public class Main implements Runnable {

private long maxSoFar = -1;
private int start;
private int step;
static ConcurrentHashMap results = new ConcurrentHashMap();

public Main(final int start, final int step) {
  this.start = start;
  this.step = step;
}

public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();

Thread[] threads = new Thread[32];

for (int i = 0; i < threads.length; i++) {
  threads[i] = new Thread(new Main((i * 2) + 1, threads.length * 2));
}

for (Thread thread : threads) {
  thread.start();
}

for (Thread thread : threads) {
  thread.join();
}

System.out.println("results = " + results);

long endTime = System.currentTimeMillis();

System.out.println("Runtime = " + (endTime - startTime) + " milliseconds");

}

public void run() {
long startTime = System.currentTimeMillis();

for (long n = start; n <= 100000000; n += step) {
  long value = cycleLength(n);
  if (value > (n * n)) {
    System.out.println(Thread.currentThread().getName() + " " + n + " " + value);
    results.put(n, value);
    maxSoFar = Math.max(value, maxSoFar);
  }
}

long endTime = System.currentTimeMillis();

System.out.println("Runtime = " + Thread.currentThread().getName() + " " + (endTime - startTime) + " milliseconds");
}//main

public long cycleLength(long j) {
long hi = j;
long original = j;
long n_square = j * j;
while (j > 1) {
  if (j < original && maxSoFar < n_square) {
    return hi;
  }
  if ((j & 1) == 0)  // bitwise AND
  {
    j = j >> 1;  // n even
  } else {
    j = 3 * j + 1; // n odd
    if (hi < j) {
      hi = j;
    }
    j = j >> 1;
  }
}

return hi;
}

}


The whole code is overengeneered, very much so in my opinion. The code can be reduced to:

function digitsIncrement(digits) {
    return toDigits(fromDigits(digits) + 1);
}

The two functions mentioned are easy to write, should take 1 to 5 lines each and be immediately understandable.

Remember to convert to a common format, calculate and convert back instead of working in a weird format.


Since you never use r you can shift it down by one and call it _ (the customary unused variable in Python).

def grid_move_v2(rights, ups):
    cur = [1] * (ups + 1)
    for _ in range(rights):
        for u in range(1, ups+1):
            cur[u] = cur[u] + cur[u-1]
    return cur[-1]


Using recursion to count nodes in a binary tree, test equality of linked lists, and find extrema of a linked list

It is better to test for x is None rather than x == None.

Avoid using single-letter variable names — they may make sense to you, but not to anyone else.

I don't see any reason why a node should be automatically not counted if its value is None.  Shouldn't it be up to the predicate to decide whether nodes with None as a value are counted or not?

You can eliminate a case by taking advantage of the fact that int(False) is 0 and int(True) is 1.

def count(tree_node, predicate):
    """Counts the tree_node and its descendants whose value satisfies the predicate."""
    if tree_node is None:
        return 0
    else:
        return int(predicate(tree_node.value)) + \
               count(tree_node.left, predicate) + \
               count(tree_node.right, predicate)

Stylistically, it would be better to consistently use either one long if… elif chain or just ifs with early returns.  I also suggest putting the recursive case at the end of the function.

(ll1 != None and ll2 == None) or (ll2 != None and ll1 == None) can be simplified.

def equal(ll1, ll2):
    """Recursively checks whether two linked lists contain the same values
    in the same order."""
    if ll1 is None and ll2 is None:
        return True
    if ll1 is None or ll2 is None:
        return False
    if ll1.value != ll2.value:
        return False
    return equal(ll1.next, ll2.next)

Assuming that the linked list contains no None data values, the logic can be simplified.

def min_max(ll):
    """Returns a 2-tuple of the minimum and maximum values.
    If ll is empty, returns (None, None)."""
    if ll is None:
        return None, None
    if ll.next is None:
        return ll.value, ll.value
    least, greatest = min_max(ll.next)
    return min(ll.value, least), max(ll.value, greatest)


for what you use config/application.yml instead use config/secrets.yml. It is already implemented in Rails. Than you can fetch your key by:

Rails.application.secrets

even more, add to config/application.rb variable SECRETS = Rails.application.secrets and now you can use it:

SECRETS[:my_secret_key]

read more IN RAILS DOCS


I would begin with the imports.  When importing UIKit you will not need to import Foundation because the contents of UIKit will also include Foundation.

Now to recommend a few things with regards to the Game struct. Now the way the struct is instantiated means that one image is equivalent to a "Game," so you would be able to set the correctWord, and image to constants with let.

Secondly, we can also provide a more descriptive names for the variables to eliminate any confusion later on down the line, like using guessedLetters instead of guessedLetter (plural indicates that this is likely an array), correctAnswer instead of correctWord, and guessedWord instead of formatedWord as these are more clear and descriptive of their purposes.

import UIKit

struct Game
{
    let correctAnswer: String
    let image: UIImage
    var guessedLetters: [Character]
    // création du bon mot par le joueur
    var guessedAnswer: String
    {
        var guessedAnswer = ""
        let answer = correctAnswer.lowercased()

        for letter in answer
        {
            if guessedLetters.contains(letter)
            {
                guessedAnswer += "\(letter)"
            }
            else
            {
                guessedAnswer += "_"
            }
        }

        return guessedAnswer
    }
    // Quand le joueur
    mutating func playerGuessed(_ letter: Character)
    {
        guessedLetters.append(letter)
    }
}

Now with regards to the View Controller. I would begin by dealing with the variables at the top of the controller.  These should either be included in the controller or refactored into their own file. For simplicity sake, I'll just move these to be part of the ViewController.

Next we would want to rename some of the variables to make their purposes more clear.  This will help with understanding of what everything does in a way that is more identifiable than comments. I've opted to use names like imageDictionary and currentGameIndex over imageAndWord and imageFindNumber, for example.

Next, there are a couple values that are unnecessary.  Particularly theKey, theValue, and totalKey. These are not needed because we already have a mutable dictionary that we can perform actions against, so we do not need to create extra versions of these values.  When we are setting the new game parameters, I've updated those references to use the following logic, which will do the same thing without needing additional arrays.

imageDictionary.removeValue(forKey: currentGame.correctAnswer)
let word = imageDictionary.first?.key.lowercased()
let value = imageDictionary.first?.value

I've introduced a guard statement in the newRound method. This statement is useful for when you have a dependency that you need to continue executing.  In this case, you need to have an image available in order to proceed, so the guard case will verify if there is one, and then continue through or terminate early.  This is not necessary, but in cases where there are dependencies that are required, it can be useful and easier to read than nested if statements.

Another change I would recommend is renaming the enableOrNotButton: method. In my example, I've updated it to setButtonStatus enabled: as it helps you understand at a glance what the intent is.  setButtonStatus(enabled:true) shows you that you are intending that the button will be updated to enable = true.

Finally I've removed the redundant comments, as those don't really help much of anything. If the method is named appropriately, as is the case for updateUI(), then you don't really need a comment that says "updateUI() will update the UI".  Comments are more helpful when they explain something that isn't understood.  A good comment should be able to answer a question or provide information that isn't immediately obvious.

import UIKit

class ViewController: UIViewController {

    var imageDictionary = ["Maison": #imageLiteral(resourceName: "image 1"),"Bateau": #imageLiteral(resourceName: "image2") ,"Train": #imageLiteral(resourceName: "image 3"),"Vase": #imageLiteral(resourceName: "image 4")]
    var currentGameIndex = 0
    var currentGame: Game!

    @IBOutlet var letterButtons: [UIButton]!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var wordLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!

    @IBAction func letterButtonsPressed(_ sender: UIButton)
    {
        // Disable the button so the user cannot select the letter again.
        sender.isEnabled = false
        let guessedLetter = sender.title(for: .normal)!
        let lowercasedLetter = Character(guessedLetter.lowercased())
        currentGame.playerGuessed(lowercasedLetter)

        if currentGame.correctAnswer == currentGame.guessedAnswer
        {
            beginNewRound()
        }

        updateUI()
    }

    func updateUI()
    {
        let word = currentGame.guessedAnswer.map{String($0)}
        let spacingWord = word.joined(separator: " ")
        wordLabel.text = spacingWord
        imageView.image = currentGame.image
        scoreLabel.text = "Image: \(currentGameIndex)/\(totalKeys)"

    }

    func beginNewRound()
    {
        guard imageDictionary.isEmpty else {
            setButtonStatus(enabled:false)
            return
        }

        setButtonStatus(enabled:true)
        let word = imageDictionary.first?.key.lowercased()
        let value = imageDictionary.first?.value
        currentGame = Game(correctWord:word, image:value, guessedLetter: [])
        currentGameIndex += 1
        imageDictionary.removeValue(forKey: currentGame.correctAnswer)
        updateUI()
    }

    func setButtonStatus(enabled status: Bool)
    {
            for button in lettersButtons
            {
                button.isEnabled = status
            }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        beginNewRound()
        print(currentGame.correctAnswer)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


Sorting an associative array alphabetically

That snippet of 3 lines you used,
is fine as it is, nothing really wrong with it.
It's proper, efficient, natural, easy to understand.

There is just one thing I'd pick on,
is that the $value variable in the foreach expression is not used.
Another way to achieve the same thing without unused variables is to use & to pass the loop variable by reference:

foreach ($array_name as &$arr) {
    ksort($arr);
}

This has the advantage that the loop index variable $key is now gone too,
we're working with the data that really matters, which is the $arr to sort.


Any tips on how to improve it so I am not repeating code?

There isn't really a lot of repeated code, here. I think you're fine on that front.

Avoid globals

Starting with image1 onward, you have lots of globals. Try to move them into a class, for a few reasons: re-entrance (you could spawn multiple identical windows), general code organization, namespace cleanliness, etc.

Credential management

if ent1.get() == 'admin' and ent2.get() == 'password':

I know that you are

  making a basic program just for a local machine

but this is never a good habit to get into. Hard-coding passwords is not secure, and it isn't much more difficult to do the "right" thing. Import a library to be able to securely handle authentication and encrypted credential storage.


Project Euler # 25 The 1000 digit Fibonacci index

It's possible to calculate the nth Fibonacci number directly thanks to Binet's formula.

Due to floating point errors, the formula doesn't give correct values if n is too large, but it works fine in order to calculate the number of digits.

from math import log10, floor, ceil

def fibonacci_digits(n):
    if n < 2:
        return 1
    ϕ = (1 + 5**0.5) / 2
    return floor(n * log10(ϕ) - log10(5) / 2) + 1

It's possible to calculate the inverse of this function. This way, you can find the first Fibonacci with k digits directly, without any loop:

def euler25(k):
    if k < 2:
        return 1
    ϕ = (1 + 5**0.5) / 2
    return ceil((k + log10(5) / 2 - 1) / log10(ϕ))

It seems to return the correct answer for any k in less than 1 μs :

>>> euler25(1000)
4782
>>> euler25(10_000)
47847
>>> euler25(100_000)
478495
>>> euler25(100_000_000_000_000_000)
478497196678166592

The digits are the same as in:

>>> 1 / log10(ϕ)
4.784971966781666


Handling a WordPress form with multiple checkboxes

You are open to reflected XSS via show_img_url. You should always HTML encode user input when outputting it.
You don't really need to add the class to each cell. Just add it to the table to avoid duplication and increase readability.
Your spacing and indentation is slightly off (the tr elements don't align, and the first td element has too many spaces)


Regularity in the "Rusty Towel of Mutual understanding"

Your randomness for calculating the last postfixes is not regular.... there are very slight deviations

(Note update on the doubling of daggers at the end though... that's not 'slight').

Let's do a couple of things here. Firstly, rename them:

postfixes1 -> concepts:

private static String[] concepts = { "Destruction", "Feminism",
        "Twilight", "Massacre", "Dread", "Terror", "Mutual Understanding",
        "Spite", "Immobility", "Mediocrity", "Anger" };

postfixes2 -> people:

private static String[] people = {"the Occult", "the Captain",
        "the Warrior", "the Hunter", "the Haunted", "the Dead",
        "the Fallen", "the Hitchhiker", "the Wicked King", "the Grue"};

Then, you can make the logic clearer near the end. Your code is (with the renames):

    if (rand.nextInt(concepts.length + people.length) > people.length) {
        if (rand.nextInt(100) < 70) {
            str.append(addons[rand.nextInt(addons.length)]);
            str.append(" ");
        }
        str.append(concepts[rand.nextInt(concepts.length)]);
    } else {
        str.append(people[rand.nextInt(people.length)]);
    }

Now, what's the problem there?

Well, there are 2 ...

people should not have 'the' prepended to all of them. It is repeating yourself. Instead you should have:

str.append("the ").append(people[rand.nextInt(people.length)]);

there is an off-by-one error in if (rand.nextInt(concepts.length + people.length) > people.length) {. This is hard to explain... but....

nextInt(limit) selects a random number up to, but not including the limit.

in this case, the limit is concepts.length + people.length, and, if you put those two arrays together, there are 21 members (11 concepts, 10 people). So, you select a random number up to, but not including 21... then, if it is greater than people.length (10), you choose to add a concept. So, the chances are 10 in 21 that it will be > 10  (values 11, 12, 13, ... 20), and then you chose to do the side that has 11 entries. You are using the proportions of people to decide whether to do a concept.....

Your code should be:

if (rand.nextInt(concepts.length + people.length) >= people.length) {
    // add a concept

or, more logically:

if (rand.nextInt(concepts.length + people.length) < concepts.length) {
    // add a concept

So, you do have an imbalance. You are selecting people about 10% more often than you should....

Update: Jeroen and I were discussing some odd values coming out with dagger, and I hacked out some of your code, and ran it through with this loop:

public static void main(String[] args) {
    RandomNameGenerator rng = new RandomNameGenerator();
    Map<String, AtomicInteger> counts = new TreeMap<>();
    for (int i = 0; i < 100000; i++) {
        String val = rng.getRandomName();
        if (!counts.containsKey(val)) {
            counts.put(val, new AtomicInteger());
        }
        counts.get(val).incrementAndGet();
    }
    counts.forEach((k,v) -> System.out.printf("%6d %s%n", v.get(), k));
}

Note, what I am doing is just counting the occurrences of a String.

I then stripped out some of the 'qualifiers' from your code, and got results like:

   110 Amulet of Anger
   126 Amulet of Destruction
   114 Amulet of Dread
   ......
   127 Chain Mail of Feminism
   125 Chain Mail of Immobility
   118 Chain Mail of Massacre
   134 Chain Mail of Mediocrity
   ......
   140 Crown of the Hitchhiker
   154 Crown of the Hunter
   168 Crown of the Occult
   155 Crown of the Warrior
   141 Crown of the Wicked King
   243 Dagger of Anger
   233 Dagger of Destruction
   271 Dagger of Dread
   245 Dagger of Feminism
   245 Dagger of Immobility
   240 Dagger of Massacre
   254 Dagger of Mediocrity
   ...
   318 Dagger of the Hunter
   299 Dagger of the Occult
   328 Dagger of the Warrior
   295 Dagger of the Wicked King
   131 Fish of Anger
   130 Fish of Destruction
   101 Fish of Dread
   129 Fish of Feminism

Note how Dagger appears about twice as often as other values?

That's because you have "Dagger" in the input data twice:

private static String[] items = { .....,
        "Longsword", "Scissors", "Dagger", "Blade", "Bow", "Axe", "Dagger",
        //
        // Dagger twice          ^^^^^^^^                         ^^^^^^^^
        .....
        "Teapot", "Hood", "Crown", "Cap", "Helmet" };


Generating filters to remove query variables from a URL

Breaking Up Is Hard To Do

My first suggestion would be to break up your one function into many. No need to do all of that in just one function. The best way to do this would be to go about it logically. That is to say, break up your function by their purpose. For instance you could create a get_params() function like the following.

function getParams($queryString) {
    parse_str($queryString, $params);
    return $params;
}

This is a poor example because it doesn't take much from your code, but it does show how your functions should be specialized. Break them up so that they do only one thing and do it well. Even if you don't find yourself reusing that function it will help you in the long run. Don't believe me? Try it and then run your program again. Where is that error coming from now? I am almost positive it will have narrowed the amount of code you need to look at and will probably tell you in which function to look through. Here's a couple more small functions for you. Not to say there aren't more, these are just some maybe not so obvious ones to get you started.

function getOutput($class, $title, $href) {
    return '' . $title . '';
}

function getTermBy($key, $term) {
    return get_term_by('slug', $term, $key);
}

That last function might not be all that great, but if this were a class you could make it so that you'd only have to pass the $term to it, which would be better and cleaner. I tend to tell everyone to ignore OOP until they are ready for it, just as I am telling you. Work on the suggestions in this answer and once this all becomes second nature I think you'd be ready for it. For the time being, just breaking up your code will make it easier to transition into classes should you ever decide to convert this over to one.

What's This Now!

It may be common knowledge what some of these functions do ('get_bloginfo()`), but I haven't a clue. I'm assuming this is wordpress or something. Never got into it myself so I'm not sure. Never the less, you should be commenting your code to let people know what you're doing. You don't have to go into great detail, just enough to say what you expect the outcome to be. I do see that you have some comments, but they seem to be more structural rather than functional.

norunonfunctionsasitishardtoread

Look up, now look down, now back up at me. Sadly these run-on functions are hard to read.

$day_title = ucwords(strftime( '%e de %B ', strtotime( get_query_var('eventDate') )));

But with the power of good code separation your code could look as good as mine!

$eventDate = get_query_var('eventDate');
$eventDateTime = strtotime($eventDate);
$formattedTime = strftime('%e de %B', $eventDateTime);
$day_title = ucwords($formattedTime);
//OR
$day_title = get_query_var('eventDate');
$day_title = strtotime($day_title);
$day_title = strftime('%e de %B', $day_title);
$day_title = ucwords($day_title);

I've always wanted to do that :) Anyways, now that I've had my fun... It won't hurt anything to separate code like this, it will just increase the number of lines in your program. It will still run the same and the slight increase in filesize will be neglible and wont make it run any slower, or if it does, it will be so miniscule as to be unnoticeable.

Consistency

You seem to be struggling with how you want your code to look. This is very common in a new programmer who is still unsure as to what style they want to adopt. You should pick one and stick with it though. Right now you have oneword, camelCase, and under_score variables/functions with no consistency. The only other reason I could think of for code to look like this is if it were all copy-pasted in without fully understanding it, which should never be the case, nor do I think it is. This is not to say you need to pick just one. You can mix and match. Some people use camelcase for variables and underscore for functions, or vice-versa. Its entirely up to you, there is no right or wrong, just preference. But once you pick one you like you should stick with it.

If you ever join a team this will become a big factor, though your preferences will mater little and you'll have to conform your style to the project lead's. They do this for consistency and being consistent with your own code will get you in the hang of this.

Final Thoughts

I've not found your issue, but implementing these suggestions might help you find it. I had a little fun with the answer, so my apologies, but it should still be helpful and understandable.


SQL query to classify and count logged messages

Guessing:

  What do you think is the most CPU intensive part of that query, and
  what are the possible ways to consume less CPU?

We don't have to guess, you test it using SSMS and execution plans.

Capacity:

  The query is very CPU-heavy for the database server (according to the
  stats provided by Azure SQL Server), and eats 15% of the available CPU
  capacity of the server.

15% of 0 is still 0, how many CPUs do you have for this instance, if you only have 1 CPU 15% could be considered significant, however the issue is most likely not this query, it is the ration of CPU you've given it.

Fundamentals:

When you have a table and you are TRYING to use a surrogate key as a primary key, you still have to have a primary key on the object for it to be considered a table. You are currently querying a heap.

Please start by adding a primary key to the table, identity(1,1) is not a primary key, it is a candidate for a primary key, you still have to tell SQL you want it to be the primary key.

Predicate:

How large is this table, it could be the case that you have 4 billion records in the table and you're asking this question with out a filter on date range. Do you intent for this to be a question for all time?  Is there a process that truncates this table, or starts the process over in some fashion?

Indexes:

Indexes, I would create a non cluster index on intent, you could even try a filtered index on the column.

Performance tuning

You will want to compare the execution plans, find the equivalent of dropcleanbuffers and freeproccache for Azure. Subtreecost is what you're looking to improve, time it takes to return is a non-sequitur. You might need to provide table hints to force it to use the indexes to validate if the index is useful or not.

Tempdb:

What does your tempdb look like, I only ask because of the multiple DISTINCT you use in the queries. If there is a lot of data in the table its dumping to tempdb and disk, what does the I/O look like for tempdb, what does the space look like?

Code Changes

I would also consider changing the code @Malachi offers sound suggestion. I would also consider SQL Server Window Functions.


Integrate the product of four infinite series functions

Caveat: I am not a Matlab expert, nor am I competent at an advanced undergraduate level in mathematics.
Efficiency
Removing data structure impedance and redundant or unnecessary calculations is likely to improve the running time of the code under review.

func5 [whatever the func that is] is called twice with exactly the same arguments.

Each time it is wrapped in reshape which adds to the cost.

Indeed func1, func2, and func5 are defined each returning a data structure that requires reshaping. This can be avoided by either working with their data structure directly in the code under review or redefining the functions to return the data structure used by the code.

(n - m + i + k + p)*log(a/sig^2) is calculated twice. Sure in one location it needs to be doubled.

Each time through the inner loop (n - m + i + k + p) increases by one. There's no need to recalculate it in full. It can be passed as a parameter from the enclosing function.

a [defined elsewhere?] is a constant within the code under review. Therefore log(a/sig^2) is also a constant. Yet is being calculated twice in the inner loop.

(log sig) [sig defined elsewhere?] is calculated for each iteration at the each level of the loop. It's a constant.

There are probably other places where redundant computations can be avoided.

Code Clarity
The code is hard to read.
The more that the names of items in the code reflect the way we would label the pieces of the problem domain [mathematics here], the easier it becomes to reason about the way the code implements the problem.
sigma_k better expresses the mathematics than total1. And though I know temp = temp + ... does something, but it's not obvious what. function1_result = start_value + ... is better. partialgamma1_result = start_value + ... is better.
Final thoughts
Giving things meaningful names helps a lot. logsig = log(sig) seems like more work because it is more typing [by 8 more keystrokes]. But it's a false economy because debugging and refactoring code for speed is orders of magnitude more difficult than banging on the keyboard.


Code Review

Prefer int to const inline int. See Previous review.

Prefer to pass by const reference

Prefer to put the & next to the type (not the parameter).
Its part of the type information (note this is the opposite of C).
  static const inline int maxPoints(const std::vector<std::vector<int>> &points)

This is absolutely fine (I have not problems with it).
        int max_points = 0;

But most (I have no real metrics for this, but in my experience) tend to use "CamelCase" rather than "Snake_Case" naming convention.

Prefer to use pre-increment rather than post increment
        for (int index_i = 0; index_i < points.size(); index_i++) {

The reason is that C++ code can simply be changed by changing the type used. Now pre/post fix increment on an integer has exactly the same type. But if we change the type used for the iterator then pre/post increment can be slightly different in cost. The standard implementation of iterators (the most common thing used in loops) will give you a slightly more expensive operation (in theory) than a pre-increment. Thus the standard advice is to always use the pre-increment to make sure you always use the most efficient operation.

Be aware of the new range based operator.
Not sure it totally helps here. But keep in mind the range based operator:
        for (int index_i = 0; index_i < points.size(); index_i++) {
            auto& item = points[index_i];

            // STUFF
        }

        // can be simplified to:
        for (auto& item: points) {

            // STUFF
        }

Your assuming that using namespace std; is somewhere above you.
            map<pair<int, int>, int> points_map;

Don't. Even using using namespace std; is considered bad pactice.

Not very common to see the use of not. It is much more common to use !.
        if (not b) {

        ----

        if (!b) {

For most C developers this will be the normal.


Windows autoclicker with a console interface

Here are some suggestions you can use to improve your code.

Formatting

Insert a space before a { that starts a compound statement and does not go on a separate line; e.g., instead of int main(){, write

int main() {

or

int main()
{

Place a space after a comma and after a control word (while, etc.):         SendInput(1, &input, sizeof(INPUT)) and while (true) {.

Place two spaces around the = operator.

The indentation level of the leftClick function should be reduced to 4 spaces to keep consistent with main.

Naming

In C++, functions are usually named in snake_case instead of camelCase.  This is subjective though.

Standard library usage

Please try to avoid using namespace std; because it is considered bad practice.  The contents of the C++ standard library are put in a special namespace to avoid polluting the global namespace and causing name clashes.  The std namespace is not intended for use with using directives (in general).  using namespace std; forces you to avoid standard names and invalidates the purpose of the std namespace.  See Why is “using namespace std;” considered bad practice?.

std::endl is generally inferior to \n, but it is necessary in this case because of flushing requirements.  Good.

Currently, your code isn't clear in terms of unit of time.  Is the interval intended to be in seconds, milliseconds, or microseconds?  The standard <chrono> library solves this problem.  And instead of Sleep, use std::this_thread::sleep_for from <thread>, which plays well with <chrono>:

using namespace std::chrono_literals;

std::cout << "Place the cursor where you want to click ..." << std::endl;
std::this_thread::sleep_for(7s); // NB: valid syntax!

Indicate your presumed unit of time:

cout << "Set the interval to click (ms): ";

int cinterval {0};
cin >> cinterval;

// ...
std::this_thread::sleep_for(std::chrono::milliseconds{cinterval});


Some points:

public class solution {

Java's conventions say that class names should be PascalCase, not camelCase:

public class Solution {

would be correct.

Another thing is that you print results like:

 | | | | | | |Q|
 |Q| | | | | | |
 | | | |Q| | | |
 | |Q| | | | | |
Q| | | | | | | |
 | | | | | |Q| |
 | | |Q| | | | |
 | | | | |Q| | |

Why not do:

| | | | | | | |Q|
| |Q| | | | | | |
| | | | |Q| | | |
| | |Q| | | | | |
|Q| | | | | | | |
| | | | | | |Q| |
| | | |Q| | | | |
| | | | | |Q| | |

Therefore, printMatrix() will now be:

public static void printMatrix(char[][] board) {
    // 8x8 board
    int n = board.length;
    System.out.println("------------------------------");
    for (int i = 0; i < n; i++) {
        System.out.print("|");
        for (int j = 0; j < n; j++) {
            System.out.print(board[i][j] + "|");
        }
        System.out.println();
    }
    System.out.println("------------------------------");
}

Since this is Java, you might as well have some OOP in your code. It does not look like OOP at all. After some redesigning with OOP, your code will look like this:

public class Solution {

    public static void main(String[] args) {
        List<QueenBoard> solutions = new NQueensProblem(8).getAllSolutions();
        for(QueenBoard board : solutions) {
            System.out.println(board.toString());
        }
    }

}

class NQueensProblem {

    private int size;

    private List<QueenBoard> solutions;

    public NQueensProblem(int size) {
        this.size = size;
        this.solutions = new LinkedList<QueenBoard>();
        solve(size);
    }

    public void solve(int size) {
        QueenBoard board = new QueenBoard(size);
        LogicalBoard logicalBoard = new LogicalBoard(size);
        solve(board, logicalBoard, 0, size);
    }

    public List<QueenBoard> getAllSolutions() {
        return solutions;
    }

    private void solve(QueenBoard board, LogicalBoard logicalBoard,
            int rowNumber, int size) {
        if (rowNumber == size) {
            solutions.add(board);
            return;
        }
        for (int column = 0; column < size; column++) {
            if (logicalBoard.getPossible(rowNumber, column)) {
                QueenBoard newBoard = new QueenBoard(board);
                newBoard.setHasQueen(rowNumber, column, true);
                LogicalBoard newLogicalBoard = new LogicalBoard(logicalBoard);
                newLogicalBoard.setPossible(rowNumber, column, false);
                updateBoard(rowNumber, column, newLogicalBoard, size);
                solve(newBoard, newLogicalBoard, rowNumber + 1, size);
            }
        }
    }

    private void updateBoard(int row, int col, LogicalBoard logicalBoard, int size) {
        // update the row
        for (int j = 0; j < size; j++) {
            logicalBoard.setPossible(row, j, false);
        }
        // update the column
        for (int j = 0; j < size; j++) {
            logicalBoard.setPossible(j, col, false);
        }
        // update the diagonals
        int r = row;
        int c = col;
        while (r >= 0 && c >= 0) {
            logicalBoard.setPossible(r, c, false);
            r--;
            c--;
        }
        r = row;
        c = col;
        while (r < 8 && c < 8) {
            logicalBoard.setPossible(r, c, false);
            r++;
            c++;
        }
        r = row;
        c = col;
        while (r < 8 && c >= 0) {
            logicalBoard.setPossible(r, c, false);
            r++;
            c--;
        }
        r = row;
        c = col;
        while (r >= 0 && c < 8) {
            logicalBoard.setPossible(r, c, false);
            r--;
            c++;
        }
    }

}

class QueenBoard {

    private boolean[][] board;
    int size;

    public QueenBoard(int size) {
        this.size = size;
        this.board = new boolean[size][size];
    }

    public QueenBoard(QueenBoard oldBoard) {
        this.size = oldBoard.size;
        this.board = new boolean[size][size];
        for(int i = 0; i < size; i++) {
            for(int j = 0; j < size; j++) {
                this.board[i][j] = oldBoard.board[i][j];
            }
        }
    }

    public void setHasQueen(int x, int y, boolean value) {
        board[x][y] = value;
    }

    public boolean hasQueen(int x, int y) {
        return board[x][y];
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append("------------------------------\n");
        for (int i = 0; i < size; i++) {
            result.append("|");
            for (int j = 0; j < size; j++) {
                result.append((board[i][j] ? "Q" : " ") + "|");
            }
            result.append("\n");
        }
        result.append("------------------------------");
        return result.toString();
    }

}

class LogicalBoard {

    private boolean[][] board;
    int size;

    public LogicalBoard(int size) {
        this.size = size;
        board = new boolean[size][size];
        for(int i = 0; i < size; i++) {
            for(int j = 0; j < size; j++) {
                this.board[i][j] = true;
            }
        }
    }

    public LogicalBoard(LogicalBoard oldBoard) {
        this.size = oldBoard.size;
        this.board = new boolean[size][size];
        for(int i = 0; i < size; i++) {
            for(int j = 0; j < size; j++) {
                this.board[i][j] = oldBoard.board[i][j];
            }
        }
    }

    public void setPossible(int x, int y, boolean value) {
        board[x][y] = value;
    }

    public boolean getPossible(int x, int y) {
        return board[x][y];
    }

}

Major changes:

The board is now a class
The logical board is now a class
Instead of printing all the solutions while solving, you get all the solutions through getAllSolutions() once it is finished solving the puzzle, and then print them one by one with System.out.println(board.toString())
The solving methods are now non-static

This way, it looks much more Java-like.

Also:

private void updateBoard(int row, int col, LogicalBoard logicalBoard, int size) {
    // update the row
    for (int j = 0; j < size; j++) {
        logicalBoard.setPossible(row, j, false);
    }
    // update the column
    for (int j = 0; j < size; j++) {
        logicalBoard.setPossible(j, col, false);
    }
    // update the diagonals
    int r = row;
    int c = col;
    while (r >= 0 && c >= 0) {
        logicalBoard.setPossible(r, c, false);
        r--;
        c--;
    }
    r = row;
    c = col;
    while (r < 8 && c < 8) {
        logicalBoard.setPossible(r, c, false);
        r++;
        c++;
    }
    r = row;
    c = col;
    while (r < 8 && c >= 0) {
        logicalBoard.setPossible(r, c, false);
        r++;
        c--;
    }
    r = row;
    c = col;
    while (r >= 0 && c < 8) {
        logicalBoard.setPossible(r, c, false);
        r--;
        c++;
    }
}

looks over-repetitive. Try creating multiple methods to handle that:

private void updateBoard(int row, int col, LogicalBoard logicalBoard, int size) {
    updateRow(row, logicalBoard, size);
    updateColumn(col, logicalBoard, size);
    updateDiagonal(row, col, -1, -1, logicalBoard, size);
    updateDiagonal(row, col, 1, 1, logicalBoard, size);
    updateDiagonal(row, col, 1, -1, logicalBoard, size);
    updateDiagonal(row, col, -1, 1, logicalBoard, size);
}

private void updateRow(int row, LogicalBoard logicalBoard, int size) {
    for (int j = 0; j < size; j++) {
        logicalBoard.setPossible(row, j, false);
    }
}

private void updateColumn(int col, LogicalBoard logicalBoard, int size) {
    for (int j = 0; j < size; j++) {
        logicalBoard.setPossible(j, col, false);
    }
}

private void updateDiagonal(int row, int rowIncrement, int col, int colIncrement, LogicalBoard logicalBoard, int size) {
    while (row >= 0 && col < 8) {
        logicalBoard.setPossible(row, col, false);
        row += rowIncrement;
        col += colIncrement;
    }
}

This looks much nicer, and is less repetitive.


Using BeautifulSoup to scrape various tables and combine in a .csv file

Code Style

follow the PEP8 style guide, in particular - fix the imports order, use the lower_case_with_udnerscores variable and function naming style (e.g. scrapeTable and CSVList are violations)

HTML parsing

I think you are over-using the .contents attribute. Consider switching to .get_text()
look into using CSS selectors which is, generally, a more concise way to locate the elements. For example, you can replace table = soup.find('table', {'class': 'tablesorter'}) with table = soup.select_one('table.tablesorter'). Or, you can replace:

links = []
for anchor in soup.findAll('a', href=True):
    if 'imported' in anchor['href']:
        links.append('link' + anchor['href'])

with:

links = ['link' + anchor['href'] for anchor in soup.select("a[href*=imported]")]

where *= means "contains".


Poor performance

For games performance dominates all levels of design but becomes critical as you approach the low level building blocks of the game. Every increase in performance opens up your market, there are far more low end devices than high end with a 20% performance increase doubling the number of devices that can run the game at acceptable levels.

If you are not interested in marketing and its just for fun, then you can solve performance problems with hardware and ignore this answer.

Some points on performance

Avoid getters and setters as they are slower than direct property access.
Avoid array iteration for small arrays. Inline the operations.
Be memory efficient, pre-allocate, reuse rather than deference (delete)
Use small generic objects to cover a wide range of uses, rather than many complex targeted objects

Array.slice and Array.map require allocation and GC overhead.
Array iterators require closure, counters, and logic overheads. For large arrays the overheads become insignificant, but for small arrays 2,3 items long the overhead becomes a significant part of the processing.

One of the biggest overheads of using array iteration is that the coder hides a large number of redundant operations because the iterators obscure the expanded calculations.

Needless CPU wastage

Lets analyze and simplify the function simulatePhysics as it is very inefficient with a lot of repeated calculations, or completely unneeded calculations. Every time it is called it create a lot of garbage for GC to clean up (15 new Array objects)

  simulatePhysics(dt) {
    function taylor(arr) {
      return arr.reduceRight((acc, cur, i) => acc * dt / (i + 1) + cur, 0)
    }

    for (var dim = 0; dim < this.motion[0].length; dim++) {
      for (var deriv = 0; deriv < this.motion.length; deriv++) {
        this.motion[deriv][dim] = taylor(this.motion.slice(deriv).map((cur) => cur[dim]))
      }
    }

    for (var deriv = 0; deriv < this.angMotion.length; deriv++) {
      this.angMotion[deriv] = taylor(this.angMotion.slice(deriv))
    }
  }

This function requires the creation of 15 new arrays, 27 call stack push and pops, 30 temp variable, and 108 math operations.

It can be significantly reduced to no new arrays, no call stack overhead, 6 temp variable, and 19 math operations.

Reducing simulatePhysics

The steps I used to simplify the function and remove unneeded overhead.

1 First to remove all the coding noise we can create some aliases for the names.

 const m = this.motion;
 const aM = this.angMotion;

2 Inline the 2 loops removing all the iterators slice and map overhead.

 m[0][0] = taylor([m[0][0], m[1][0], m[2][0]])
 m[1][0] = taylor([m[1][0], m[2][0]])
 m[2][0] = taylor([m[2][0]])
 m[0][1] = taylor([m[0][1], m[1][1], m[2][1]])
 m[1][1] = taylor([m[1][1], m[2][1]])
 m[2][1] = taylor([m[2][1]])

 aM[0] = taylor([aM[0], aM[1], aM[2]])
 aM[1] = taylor([aM[1], aM[2]])
 aM[2] = taylor([aM[2]])

3 Replace the taylor function with inlined calculations

  m[0][0] = ((0 * dt / 3 + m[2][0]) * dt / 2 + m[1][0]) * dt / 1 + m[0][0]
  m[1][0] = (0 * dt / 2 + m[2][0]) * dt / 1 + m[1][0]
  m[2][0] = 0 * dt / 1 + m[2][0]
  m[0][1] = ((0 * dt / 3 + m[2][1]) * dt / 2 + m[1][1]) * dt / 1 + m[0][1]
  m[1][1] = (0 * dt / 2 + m[2][1]) * dt / 1 + m[1][1]
  m[2][1] = 0 * dt / 1 + m[2][1]

  aM[0] = ((0 * dt / 3 + aM[2]) * dt / 2 + aM[1]) * dt / 1 + aM[0]
  aM[1] = (0 * dt / 2 + aM[2]) * dt / 1 + aM[1]
  aM[2] = 0 * dt / 1 + aM[2]

4 Remove the multiply by zero and divide by ones

  m[0][0] = (m[2][0] * dt / 2 + m[1][0]) * dt + m[0][0]
  m[1][0] = m[2][0] * dt + m[1][0]
  m[2][0] = m[2][0]
  m[0][1] = (m[2][1] * dt / 2 + m[1][1]) * dt + m[0][1]
  m[1][1] = m[2][1] * dt + m[1][1]
  m[2][1] = m[2][1]

  aM[0] = (aM[2] * dt / 2 + aM[1]) * dt + aM[0]
  aM[1] = aM[2] * dt + aM[1]
  aM[2] = aM[2]

5 Cache and substitute with constants, remove unneeded assignments.

 const dt2 = dt / 2;

 m[0][0] = (m[2][0] * dt2 + m[1][0]) * dt + m[0][0]
 m[1][0] = m[2][0] * dt + m[1][0]
 m[0][1] = (m[2][1] * dt2 + m[1][1]) * dt + m[0][1]
 m[1][1] = m[2][1] * dt + m[1][1]

 aM[0] = (aM[2] * dt2 + aM[1]) * dt + aM[0]
 aM[1] = aM[2] * dt + aM[1]

6 More aliases to reduce indexing overhead and rebuild the function

simulatePhysics(dt) {
    const m = this.motion, m0 = m[0], m1 = m[1], m2 = m[2];
    const aM = this.angMotion;
    const dt2 = dt / 2;

    m0[0] = (m2[0] * dt2 + m1[0]) * dt + m0[0];
    m1[0] =  m2[0] * dt  + m1[0];
    m0[1] = (m2[1] * dt2 + m1[1]) * dt + m0[1];
    m1[1] =  m2[1] * dt  + m1[1];
    aM[0] = (aM[2] * dt2 + aM[1]) * dt + aM[0];
    aM[1] =  aM[2] * dt  + aM[1];

}

Whats the gain

Arguably there is some loss in readability, personally it makes a lot more sense than a collection of arrays iterators and copying. But the gain is (tested on chrome) huge.

// tested on random set of 1000 objects
// µs is 1/1,000,000th second. OPS is operations per second.
// An operation is a single call to the function being tested.
Optimized..: MeanTime 0.175µs OPS 5,710,020 Test Total   322ms 1,836,000 operations
Original...: MeanTime 4.198µs OPS   238,185 Test Total 6,566ms 1,564,000 operations

The optimized version is 25 times faster, able to do 5.7million operations in the same time as the original could do 0.3million

Is readability more important than performance? for games you must seriously consider what you lose via traditional coding styles.


HackerRank Implement Queue using two stacks Solution

Algorithmic complexity for combined operations

Containers are interesting elements in most programming languages: they have an internal state, namely their elements and therefore their size.

This introduces an additional state compared to usual algorithmic asymptotical complexity analysis. For example, a naive implemented std::vector::push_back will yield \$\mathcal O(n^2)\$ complexity if push_back increases the capacity only by one:

// pseudo-code, also very bad performance and no error handling, do not use!
void vector::push_back(T value){
    if(_size == _capacity) {
         // has to move all elements and is therefore O(n)
         reserve(_capacity + 1);
    }
    _data[_size++] = value;
}

While trivial, this code has a severe problem: we have to copy all elements in ever iteration. If we use push_back in a loop, we end up with a quadratic complexity.

The real push_back has therefore some tricks up in its sleeves, as the standard dictates that it will have \$O(1)\$ amortized complexity. More about that later in this review.

However, this small introduction should give you a hint about the central flaw in your current approach.

A hidden quadratic term

  I implemented dequeue() in \$O(1)\$ at the cost of enqueue() in \$O(n)\$

For this task, it's much more important to see the cost on both functions for \$k\$ enqueued elements, not a single one.

So let's envision the queue {1,2,3,4}. How many steps do we need?

to enqueue 1:
  1. put `1`  in `s1`
to enqueue 2:
  1. move `1` from `s1` to `s2`
  2. put `2` in `s1`
  3. move `1` from `s2` to `s1`
- to enqueue 3:
  1. move `1` from `s1` to `s2`
  2. move `2` from `s1` to `s2`
  3. put `3` in `s1`
  4. move `2` from `s2` to `s1`
  5. move `1` from `s2` to `s1`
- to enqueue 4:
  1. move `1` from `s1` to `s2`
  2. move `2` from `s1` to `s2`
  3. move `3` from `s1` to `s2`
  4. put `4` in `s1`
  5. move `3` from `s2` to `s1`
  6. move `2` from `s2` to `s1`
  7. move `1` from `s2` to `s1`

We see that the \$n\$th element will take \$2(n-1)\$ swaps. Therefore, if we insert a total of \$n\$ elements into our queue, we end up with \$\mathcal O(n^2)\$ to complete all enqueues.

We need to do better.

A better queue with two stacks

So let's get back to the drawing board. What do we need?

We need to enqueue
We need to dequeue
We need to peek.

None of those terms indicates that we need to have all data in one stack. So first of all, we need to use better names, because s1 and s2 are pretty bland and non-descriptive:

class Queue{
    stack<int> in;
    stack<int> out;

    void flip();   // < new

public:
    void enqueue(int);
    int  dequeue();
    int  peek();
};

I'll implement the methods outside of the class declaration to keep the code segments short, but you're free to place them inline again. Note that I switched from a struct to a class, because its Queues job to make sure that in and out are handled correct; no one else should be able to change them.

What will we use in and out for? Well, as long as we have elements in out, we will use them for dequeue and peek. And whatever gets enqueued gets pushed right ontop of in, no questions asked.

The critical part is how to get an element from in to out, right? I let you think about that for some paragraphs, but you may also stop here and try it yourself; the declaration above contains a clue.

So, let's have a look at my proposal for the definition of enqueue(), peek and dequeue():

void Queue::enqueue(int value) {
    in.push(value);
}

int Queue::peek() {
    if (out.empty()) {
        flip();
    }
    return out.top();
}

int Queue::dequeue() {
    if (out.empty()) {
        flip();
    }
    int value = out.top();
    out.pop();
    return value;
}

Note that the additional private method flip is yet missing. However, I will state the envisioned complexity:

enqueue is \$\mathcal O(1)\$ (amortized)
dequeue is \$\mathcal O(1)\$ (amortized)
peek is \$\mathcal O(1)\$ (amortized)

Intrigued? Great. So let's check flip:

void Queue::flip() {
    while(not in.empty()) {
        out.push(in.top());
        in.pop();
    }
}

flip takes all elements in in and moves them to out. It thereby changes the order of the elements, so that the top in in will be the last to get moved out of out. Note that we call flip only when out is empty.

Amortized analysis

*"Wait a second! That's \$\mathcal O(n)\$" I hear you say. And that's completely correct. However, how often do we need to call flip? Or, rather more important, how often do elements get moved?

The answer on the latter question is: exactly one time from in to out. At no point will they move back. The number of flip calls is much trickier, though, but it doesn't really matter. At worst, flip may need to flip all elements, for example if we use it as follows:

for(int i = 0; i < 100; ++i) {
    queue.enqueue(i);
}
for(int i = 0; i < 100; ++i) {
    queue.dequeue(); // first dequeue will flip
}

However, only the first dequeue will flip. All others will yield the element immediately. Therefore, if we enqueue \$n\$ elements and then dequeue all of them, we end up with dequeue()'s complexity as:

$$\frac{n\mathcal O(1) + \mathcal O(n)}{n} = \mathcal O(1).$$

We can compare that with your original variant:
$$\frac{n\mathcal O(n)}{n} = \mathcal O(n)$$

This is why your code exceeded the time limit.

Further review on code

There are some other findings that don't need as much detail as the algorithm, but nonetheless can be improved:

there are some unused includes (<vector>)
using namespace std is considered bad practice
the names are misleading or at least not self-descriptive
peek() usually returns a value and does not print
the struct Queue should have been a class Queue due to the assumption that the elements are always in the right order.


Swapping adjacent nodes of a linked list

Consider having swapAdjacent(NULL) return NULL.  Once it does, you can get rid of the whole if (nextNode == NULL) statement, and just unconditionally say temp->next = swapAdjacent(nextNode);.
You might want to use a couple of guard clauses to separate the null checks from the other stuff.  That can make the steps easier to follow.

With those things done:

struct node * swapAdjacent(struct node * list) {
   struct node *temp, *curr, *nextNode;

   if (!list) return NULL;
   if (!list->next) return list;

   temp = list;
   curr = list->next;
   nextNode = curr->next;

   curr->next = temp;
   temp->next = swapAdjacent(nextNode);
   return curr;
}

The meanings of the names curr, temp, and nextNode are a bit foggy.  I'd change the names to something that unambiguously refers to the nodes' positions in the list either before or after the swap.
Frankly, temp and nextNode could probably go away, and the resulting code would be simpler for it.

Watch:

struct node * swapAdjacent(struct node * list) {
   if (!list) return NULL;
   if (!list->next) return list;

   struct node *newHead = list->next;
   list->next = swapAdjacent(newHead->next);
   newHead->next = list;

   return newHead;
}

Note how there's a bit of a rotation of values going on.  It was going on in the original code, too...but it was harder to see with the variables in the way.


You probably forgot to test for this, but there's a bug in your program.

def x_move(i):
    if board[i] == 'X' or board[i] == 'O':
        return print('Already taken!')
    else:
        del board[i]
        board.insert(i,'X')
def o_move(i):
    if board[i] == 'X' or board[i] == 'O':
        return print('Already taken!')
    else:
        del board[i]
        board.insert(i,'O')

For starters, you should move this into a single function which takes the player as argument. This way a single function can be used for both players and this will save you from having to fix the bug twice. Code duplication is bad.

An obvious, not necessarily pretty, solution:

def any_move(i, player_character):
    if not isinstance(board[i], int):
        return print('Already taken!')
    else:
        del board[i]
        board.insert(i, player_character)

This checks whether the value picked on the board is an integer. If it's not, it has already been taken by either X, O or whatever player characters you're using at that moment.

But the real problem is this will skip a turn on invalid input. If I pick 4 with X in one turn and pick the same tile with O a turn later, O will be missing out a turn. I imagine there should be a loop in there checking whether valid input has been inserted yet. If not, stay in the loop. If valid input is inserted, make the actual move.

I'm talking about valid input here, not just whether the input is 0 - 8. Your program will crash if I enter something invalid, like b or 11. The first is not an integer and the second is out of range. It crashes on no input (just hit enter) as well. You should at least capture those exceptions.


In def addColumn you can extract bytes and then add them to put:
val bytes = value match {
  case v: String => Bytes.toBytes(v)
  case v: Long => Bytes.toBytes(v)
  case v: Boolean => Bytes.toBytes(v)
  case v: Array[String] => Bytes.toBytes(v.mkString(","))
}
put.addColumn(columnFamily, col, bytes)

I'm not sure that Scala can check generic types in pattern matching, so Array[String] may be checked only for class Array. If it is than the compiler will warn you.
2nd, if you don't use result, you can use foreach instead of map.
3rd value.mkString(",") is String so value type is also String, not Array[String]. Of course you can simple declare def addColumn(columnName: String, value: Any), or first create sealed trait ColumnValue and use def addColumn(columnName: String, value: ColumnValue).
According to 3rd, you can use:
List("f1" -> row.field1, ..., "f4" -> row.field4).foreach {
  // you can use only 2nd case if you handle `Array` in `def addColumn`
  case (columnName, field: Array[_]) => addColumn(columnName, field.mkString(","))
  case (columnName, field) => addColumn(columnName, field)
}


Mostly this looks good, but I’ll make a few suggestions:

Boolean arguments in your function signature

These control whether certain strings/mappings are lowercased first. I think this behaviour should be removed from keymap_replace(). It's scope creep: it’s gone from being string replacements to more complicated string manipulations. I’d leave that sort of manipulation to the caller.

(And you could continue to add options like this: what about uppercasing the string, or reversing it, or another pattern. Rather than muddling up your function with this, I’d just take it out.)

That makes the arguments simpler, and simplifies the function definition as well.

But if you really want those parameters in there, then I’d suggest making them keyword-only. In Python 3, you can insert an asterisk as so:

def keymap_replace(
    string: str,
    mappings: dict,
    *,
    lower_keys=False,
    lower_values=False,
    lower_string=False,
) -> str:

and when the function is called, those boolean arguments have to be as keyword arguments, not positional. There can never be ambiguity in how the function is being used.

Dictionaries are unordered

There’s a possibility for ambiguity, or for substitutions to be chained. For example:

keymap_replace('Hello world', {
    'J': 'K',
    'H': 'J'
})

Should this call return "Jello world" or "Kello world"?

I think the first is more natural – I don’t expect substitutions to be chained – but when I tried the function, I got the latter. You should try to make this less confusing.

One possibility that springs to mind:

replaced_string = ''.join(mappings.get(char, char) for char in string)

Each character in the original string is subject to at most one substitution.


Array that defines product information and generates the html for the product

Well, if this is the real code and not a sample (like, data you're getting in $products is not fetched from the database), then there isn't much use of hard-coding a PHP array just to immediately use it to display HTML paragraphs - why not just write everything as HTML?

Other than that, you're implicitly creating an array (there's no $products = array() first). It's not an error, but it can be a little confusing. My immediate reaction was "where is $product coming from?". Also, you don't need to declare each element separately, you can do everything "at once" like this:

$products = array(
  array(
    'name' => 'Sneakers',
    'price' => 24.99,
    'category' => 'Shoes',
    'description' => 'Black sneakers. Good for walking or athletic activity'
  ),
  array(
    'name' => 'Armani Red Silk Shirt',
    'price' => 379.99,
    'category' => 'Shirts',
    'description' => 'Fancy Italian red silk shirt. Very spiffy, sure to attract the ladies'
  )
);

Also, mixing PHP and HTML in single file isn't good practice, except when you're just echo-ing data in a "view". Other than that, logic should be separated.


Determine a list contains two elements with a given sum

As 200_success mentions, your solution is \$O(n^2)\$, due to the double for loop.

You actually have an error in your inner loop.  You start the inner loop with for (int k = i; ..., but it should be for (int k = i + 1; ....  This means you could return true for an even expected sum when half of that value appears once in the list.

If you correct the above error, the test for list.size() < 2 is unnecessary.  The outer loop will run at most once (size=1) and the inner loop will not run at all, therefore the return false; at the end of the function will be executed.

An \$O(n)\$ solution is:

start with an empty set
for each value x in the list:

if set contains expectedSum - x, return true
add x to the set.

returnfalse

It is important to check for containment before adding the value, or ({1,2,3,4}, 8) would return true, despite not containing a pair of 4’s.

Set<Long> set = new HashSet<>(list.size()*2);
for(long x: list) {
    if (set.contains(expectedSum - x)) {
        return true;
    }
    set.add(x);
}
return false;

The list does not need to be sorted.

The capacity of the HashSet is initialized to double the size of the list, to avoid re-sizings, which would slow the algorithm down.

From the comments: "Why double?" The default load factor for a HashSet is 0.75. If the number of elements in the set exceeds load_factor * capacity, the capacity is increased and the contents rehashed for the new size. If the capacity was set to the size of the list, it would still end up expanding the capacity and rehashing after adding the first 75% of the entries in the list. You need an initial capacity at least 33% larger than the final size to avoid the expansion: list.size()*4/3 + 1 might be sufficient, but is perhaps cutting things a little too fine.  Double seemed a reasonable amount.


I would suggest that you instantiate your Command object and inject into CommandCollection via your addCommand() method.

$command = new Command('add-site', 'path/script_one.sh', $data);
$command->forVersion([4, 5]);
$commandCollection->addCommand($command);

This gives you clear separation of logic such that your collection no longer needs to understand how to instantiate the Command object.  It also removes the obfuscated logic of calling forVersion() on a Command object returned from addCommand().  Why would addCommand() be expected to return a Command object instead of simply adding a Command object to the collection?

Passing the Command dependency like this would also allow you to type hint that a valid Command object is passed. Right now, you are doing absolutely nothing to validate that that the parameters being passed to this method (or really all other public methods across these two classes) contain good values to work with.

Should data passed to forVersion() be information that is actually passed to the Command constructor, as opposed to being passed in a separate method?  Does the version data really need to be mutable on the object such that there should be a setter method like this? Are you allowing your Command objects to be instantiated into a bad or incomplete state?

Should you really be using Laravel Collection object as the basis for your collection class?  In other words, do you really want to you an array for your data structure here?  Note how in your methods you will have to repeatedly iterate over the collection/array to determine if certain entries are present, or to get their values.  Your addCommand() method performs an \$O(n^2)\$ search against your underlying Collection just to be able to add an entry.  Your viewCommand() requires an \$O(n)\$ iteration over the collection in order to return a Command file rendering.

This might not be a problem if you are only ever expecting to be working with a handful of entries in the collection, but will become a problem if you expect your collection to grow to significant sizes (even 100 entries would cause 10,000 individual iterations on the collection to be performed to add a new command, 1000 entries would require 1,000,000 iterations!).

If this concerns you, you might consider a key-value lookup scheme to allow for quick \$O(1)\$ lookup of results.

For example a structure like the following would enable fast lookup against the collection.

[
    '{filename}' => [
        {version} => {Command Object},
        {anotherversion} => {Command Object},
        ...
    ],
    '{anotherFilename}' => [ ... ],
    ...
]

With a viewCommand() method like:

public function viewCommand($name, $version)
{
    if(isset($commandFiles[$name][$version])) {
        return $commandFiles[$name][$version]->render();
    }
    return false;
}

Why should the collection hold a method for rendering the command? You already have the render() command living properly on the object, so isn't this basically a find() method?

For example:

$command = $collection->find($name, $version);
$command->render();

The collection should just be a collection. With methods only for managing/accessing the collection not for calling methods on the objects contained in the collection.

Note that generalizing to just a find() method would also allow you to call this method in the addCommand() method to see if command already exists.

Note that if you decided you still want to stick with Laravel Collection as your base data structure, then you might also get to the realization that your collection class really adds little value above and beyond what the Laravel class adds.  So why not:

$collection = collect([]);
$collection->push(new Command(...));

//  and to render
$command = $collection->where('name', $name);
$command->render();

Otherwise you might find yourself eventually adding filter, sort, etc. methods to your class because you have hidden away the underlying Collection capabilities.

Is it conceivable that a command in the collection could be replaced with a new Command object?  If so, then you should not be throwing exception in this case.  I would not think a collection would necessarily need to hold the logic as to whether an item in the collection could be replaced or not, as a caller could easily check for existence of an item in the collection and make decision to overwrite or not.

public function __get($property)
{
    if (property_exists($this, $property)) {
        return $this->$property;
    }
}

What if property does not exist? Should you throw exception? This condition would likely mean caller is accessing this class in unexpected fashion and should probably fail loudly.

$commandFile->name == $name

Consider using exact comparisons as default behavior, only using loose comparisons where there truly is a use case for it.


Method Of Retrieving Random Value Depending on Type

1) I don't think you need to define an enum since you can use Boolean.class, Integer.class, etc.

2)

public static <T> T getRandom(Class<T> classs) {
  if (classs.equals(Boolean.class)) {
      return (T) randomBool();
  } else if (classs.equals(Integer.class) {
      return (T) randomInt();
  // etc.
  } else
      // Edit: original "else" was: "return null;" changed to:
      throw new IllegalStateException("Cannot generate a random " + classs.toString());
}

EDIT
There is also the solution below, but that would still require casting:

   public enum Type {
    INTEGER {
        @Override public Integer getRandom() {
            return new randomInt();
        }
    }; // BOOLEAN, etc.

    public abstract Object getRandom();
}

That is basically the same as the original OP code, but where the random method call is within the enum instead of being in a separate method with a switch-statement.


Find out the number under 1 million which produces the largest Collatz Sequence

I changed your main function a little bit to LargestCollatz which runs a bit faster on my machine. I'm not sure but I think the biggest improvement is in comparing two integers (c < i) instead of the len function (i > len(list)). Futhermore I used the impopular break statement and used // (which might be faster) instead of / so i could eliminate an int function.

def LargestCollatz(n):

    # Collatz lengths, first entries are 'hand calculated'
    cl = [0, 1, 2]

    for i in range(3, n):
        c = i
        length = 0
        while True:
            if c % 2 == 0:
                c = c//2
            else:
                c = 3*c+1
            length += 1

            if c < i:
                cl.append(length + cl[c])
                break

    return cl.index(max(cl))


Python program to translate sentences from "bird language"

Considering that you have four concrete test cases, it would be a good idea to put them in a docstring as doctests.

Your iteration is awkward.  First of all, you never use i, so there is no need to call enumerate().  A better way to conditionally skip ahead is to call next() on an iterator over the phrase.

def translate(phrase):
    """
    Translate the phrase from bird language.

    >>> translate('hieeelalaooo')
    'hello'
    >>> translate('hoooowe yyyooouuu duoooiiine')
    'how you doin'
    >>> translate('aaa bo cy da eee fe')
    'a b c d e f'
    >>> translate('sooooso aaaaaaaaa')
    'sos aaa'
    """
    phrase = iter(phrase)
    result = ""
    for letter in phrase:
        result += letter
        if letter in VOWELS:   # Vowel. Skip the next two characters.
            next(phrase)
            next(phrase)
        elif letter.isalpha(): # Consonant. Skip the next character.
            next(phrase)
    return result

A much more compact solution, though, would be to perform a regular expression substitution.

import re

def translate(phrase):
    return re.sub(r'([aeiouy])\1\1|([a-z])[aeiouy]', r'\1\2', phrase, flags=re.I)


Program that finds prime numbers in a specific range

I combine here all the above and look up tables.

Use the threshold of sqrt(test_prime) to shrink the range to be tested, as said by @Gaurav.
Increase the prime number to be tested by 2, as said by @1201ProgramAlarm.
Use a look up tables to check only with the prime numbers we have detected until that moment (we remove a lot of unnecessary checks).
Load/Save the look up table for future executions.
Use SIMD instrinsics (not implemented in this solution), so that you can check 4 primes into the look up table at the same time.

My tests took about 4 minutes without pre-calculated lookup table, and about 30 seconds using pre-calculated lookup table.

The code here

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define START 190000000
#define END 200000000

int is_prime(long test, long n_primes, long* list_primes) {
    long max = sqrt(test);
    long index = 1;
    long prime = list_primes[index];
    while (prime <= max) {
        if (test % prime == 0)
            return 0;
        if (++index >= n_primes)
           break;
        prime = list_primes[index];
    }
    return 1;
}

void append_prime(long prime, long* size, long* n_primes, long** list_primes) {
    if (*n_primes == *size) {
        *list_primes = (long*)realloc(*list_primes, (*size + 4096)*sizeof(long));
        *size += 1024;
    }
    (*list_primes)[*n_primes] = prime;
    *n_primes += 1;
}

int load_from_disk(long* size, long* n_primes, long** list_primes) {
    FILE* f = fopen("primes.dat", "rb");
    if (f == NULL)
        return 0;
    fread(size, sizeof(long), 1, f);
    fread(n_primes, sizeof(long), 1, f);
    *list_primes = (long*)malloc( ( (*n_primes + 4095) / 4096 ) * 4096 * sizeof(long) );
    fread(*list_primes, sizeof(long), *n_primes, f);
    fclose(f);
    f = NULL;
    return 1;
}

int save_to_disk(long* size, long* n_primes, long** list_primes) {
    FILE* f = fopen("primes.dat", "w");
    if (f == NULL)
        return 0;
    fwrite(size, sizeof(long), 1, f);
    fwrite(n_primes, sizeof(long), 1, f);
    fwrite(*list_primes, sizeof(long), *n_primes, f);
    fclose(f);
    f = NULL;
    return 1;
}

long find_primes_until(long threshold, long* size, long* n_primes, long** list_primes) {
    if (!load_from_disk(size, n_primes, list_primes)) {
        *size = 4096;
        *n_primes = 0;
        *list_primes = (long*)malloc((*size) * sizeof(long));
        memset(*list_primes, 0, (*size) * sizeof(long));

        if (threshold > 2) {
            (*list_primes)[(*n_primes)++] = 2;
        } else {
            return *n_primes;
        }

        if (threshold > 3) {
            (*list_primes)[(*n_primes)++] = 3;
        } else {
            return *n_primes;
        }

        if (threshold > 5) {
            (*list_primes)[(*n_primes)++] = 5;
        } else {
            return *n_primes;
        }

        if (threshold > 7) {
            (*list_primes)[(*n_primes)++] = 7;
        } else {
            return *n_primes;
        }
    }

    long prime = (*list_primes)[(*n_primes)-1] + 2;
    while (prime < threshold) {
        //printf("Examining number: %ld / %ld      \r", prime, threshold);
        if (is_prime(prime, *n_primes, *list_primes)) {
            //printf("\nPrime number found: %ld\n", prime);
            append_prime(prime, size, n_primes, list_primes);
        }
        prime += 2;
    }
    save_to_disk(size, n_primes, list_primes);

    return *n_primes;
}

void find_primes_interval(long start, long end)
{
    long* list_primes = NULL;
    long  size = 0;
    long  n_primes = 0;

    find_primes_until(start, &size, &n_primes, &list_primes);

    if ((start & 0x01) == 0)
        start++;
    while (start < end) {
        printf("Examining number: %ld       \r", start);
        if (is_prime(start, n_primes, list_primes)) {
            printf("\nPrime number found: %ld\n", start);
            append_prime(start, &size, &n_primes, &list_primes);
        }
        start += 2;
    }
}

int main()
{
    find_primes_interval(START, END);
    return 0;
}


You should think more about how you arrange and style your code. Additionally, you should be aware of DRY methodology and keep from repeating code wherever possible.

I made a couple of modifications to your code. Primarily, I cleaned up the arrangement and styling. After that, I added an Ohm class - which places all of your Ohm related functions as methods (again for code cleanliness):

"""
This class contains functions which perform Ohm's law and power
law calculations based on variables from user input
"""
class Ohm():
    @staticmethod
    def voltage(i, r): return i * r

    @staticmethod
    def current(r, v): return r / v

    @staticmethod
    def resistance(i, v): return i / v

    @staticmethod
    def power(v, i): return v * i

    @staticmethod
    def pvolt(w, i): return w / i

    @staticmethod
    def pcurrent(w, v): return w / v

After that, I changed how you output the block of text from a bunch of print statements, to 1 multiline print statement:

# First user interface menu. let's user choose between ohm's law and power law calculations.
print """Ohm's Law Calculations:
    1. Voltage
    2. Current
    3. Resistance

Power Law Calculations:
    4. Wattage
    5. Voltage
    6. Current
"""

After that, I added a call to int() on the choice = raw_input(...) call so that all input is shunted to an integer. After that, we initialize our Ohm class to an Ohm variable. Then, instead of having multiple definitions for i, r, v,  and w - we ask if the choice is in a list, define i/r/v/w. This lessens the amount of duplicated code:

### Since we're asking for the current in multiple locations, simplify it
if choice in [1, 3, 4, 5]:
    i = float(raw_input("Enter current:"))

### Again, since we're asking for voltage in multiple locations, simplify it
if choice in [2, 3, 4, 6]:
    v = float(raw_input("Enter voltage:"))

### Simplifying input for resistance
if choice in [1, 2]:
    r = float(raw_input("Enter resistance:"))

## And lastly, simplifying for wattage
if choice in [5, 6]:
    w = float(raw_input("Enter wattage:"))

After that, we continue with an if/else block which calls the function according to the user input. Our i/v/r/w should already be defined in the block above. One major change here is that we are no longer printing directly from here. Rather we are setting the output in an output variable, which we later use to print.

output = None
if choice == 1:
    output = "{0} volts".format(Ohm.voltage(i, r))
elif choice == 2:
    output = "{0} amps".format(Ohm.current(r, v))
elif choice == 3:
    output = "{0} ohms".format(Ohm.resistance(i, v))
elif choice == 4:
    output = "{0} watts".format(Ohm.power(i, v))
elif choice == 5:
    output = "{0} volts".format(Ohm.pvolt(w, i))
elif choice == 6:
    output = "{0} amps".format(Ohm.pcurrent(w, v))

Finally, we check if output variable is None. If it is not None, then we print it, otherwise we print an error. As for your 'funny' error, remember that error messages should be informative (ie, should tell the end user where the error occurred and/or why it occurred):

if output is not None:
    print output
else:
    print "Invalid input values, please try again"

Lastly, here is all of the code put together (and a REPL):

"""
Ohm's law calculator
"""

"""
This class contains functions which perform Ohm's law and power
law calculations based on variables from user input
"""
class Ohm():
    @staticmethod
    def voltage(i, r): return i * r

    @staticmethod
    def current(r, v): return r / v

    @staticmethod
    def resistance(i, v): return i / v

    @staticmethod
    def power(v, i): return v * i

    @staticmethod
    def pvolt(w, i): return w / i

    @staticmethod
    def pcurrent(w, v): return w / v

# First user interface menu. let's user choose between ohm's law and power law calculations.
print """Ohm's Law Calculations:
    1. Voltage
    2. Current
    3. Resistance

Power Law Calculations:
    4. Wattage
    5. Voltage
    6. Current
"""

# Grab the user input
choice = int(raw_input(">>> "))

# Initialize our Ohm class
Ohm = Ohm()

### Since we're asking for the current in multiple locations, simplify it
if choice in [1, 3, 4, 5]:
    i = float(raw_input("Enter current:"))

### Again, since we're asking for voltage in multiple locations, simplify it
if choice in [2, 3, 4, 6]:
    v = float(raw_input("Enter voltage:"))

### Simplifying input for resistance
if choice in [1, 2]:
    r = float(raw_input("Enter resistance:"))

## And lastly, simplifying for wattage
if choice in [5, 6]:
    w = float(raw_input("Enter wattage:"))

output = None
if choice == 1:
    output = "{0} volts".format(Ohm.voltage(i, r))
elif choice == 2:
    output = "{0} amps".format(Ohm.current(r, v))
elif choice == 3:
    output = "{0} ohms".format(Ohm.resistance(i, v))
elif choice == 4:
    output = "{0} watts".format(Ohm.power(i, v))
elif choice == 5:
    output = "{0} volts".format(Ohm.pvolt(w, i))
elif choice == 6:
    output = "{0} amps".format(Ohm.pcurrent(w, v))

if output is not None:
    print output
else:
    print "Invalid input values, please try again"


You should reconsider the responsibilities of class UserServiceProvider, too many responsibilities may lead to a lot of dependencies in many cases.
It is quite possible that this class is doing a lot of work that it should not, for example populating User object with sales reports, earnings reports, or activating user, checking activation status etc.

It is not clear in your question but looking at the names of dependencies it looks like it does a lot of checking and population, you should consider moving respective codes to respective repositories and also refactor the service object into separate classes. This will create a spreaded hierarchy like this:

                           DashboardController
                           /                \
            UserProfileService              UserService
                /        \                    /         \
UserProfileRepository  OtherRepository  UserRepository   SomeOtherDependency

Now, instead of injecting UserProfileRepository, OtherRepository, UserRepository, SomeOtherDependency into UserService and then injecting UserService into controller you can inject UserProfileService and UserService into controller with all of their respective dependencies.

A couple of them looks like they can be defined as a relation. You can, for example, define UserProfile as a relation on User which in a typical case should be a one-to-one relationship. This should sort out the dependencies quite a bit.

Main point to take home is that you should re-evaluate the responsibilities of classes and determine which object should be responsible for what action. as a basic rule of thumb, all data fetching and storing should be a responsibility of repository and all data manipulation and logical decisions should be a responsibility of a service object. If a service object requires more than one repository as a dependency then step back and check if the manipulation of data from second repo should really be a responsibility of service object ?


Using a decorator to apply an inherited method to all child objects of the inherited type

Another way to do this would be to use __getattr__().

class Wraps(object):
  def __init__(self, *args):
    self.things = args
  def __getattr__(self, item):
    def each(*args, **kwargs):
      for thing in self.things:
        getattr(thing, item)(*args, **kwargs)
    return each
  def some_real_wraps_method(self):
    print "real method"

class Thing(object):
  def __init__(self, name):
    self.name = name
  def a(self):
    print self.name, "a"
  def b(self, *args, **kwargs):
    print self.name, "b", args, kwargs

w = Wraps(Thing("1"), Thing("2"))
w.a()
w.b()
w.b("arg1", "arg2", named=True)
w.some_real_wraps_method()

Running this will output:

1 a
2 a
1 b () {}
2 b () {}
1 b ('arg1', 'arg2') {'named': True}
2 b ('arg1', 'arg2') {'named': True}
real method

The upside is that you don't have to define an methods in order for them to be proxied. The downside is that it will try to proxy any attribute not defined by Wraps (this can be counteracted with a white list).


Python is 'batteries included', this means offloading code to the core library is a good thing, and often possible. In this case, if you're running Python 3.4+ you could make use of pathlib. All you need is to know the pathlib.PurePath constructor and PurePath.parts.

And so you can change your code to:

import pathlib

def cut_path(path):
    parts = list(pathlib.PurePath(path).parts)
    if len(parts) >= 4:
        parts [2:-1] = ['...']
    return pathlib.PurePath(*parts)

However, as you're doing it on how long the path is, you could dynamically build the new path. And so could use something like:

def cut_path(path, max_size=5):
    if not path:
        return path

    parts = list(pathlib.PurePath(path).parts)

    path = pathlib.PurePath(parts[0])
    for part in parts[1:-1]:
        path /= part
        if len(str(path)) >= max_size:
            path /= '...'
            break
    if len(parts) > 1:
        path /= parts[-1]
    return path

If however you're using Python 2 or Python <3.4 then you can't use the nice new interface, and would have to use the old interface, os.path. Which doesn't support splitting and joining the paths very well. First you may want to use os.path.normcase to normalize the path. Which may destroy the path if you have a Posix path on Windows. After this you'd want to take the drive with os.path.splitdrive, and then split the rest of the parts using os.sep. Then you want to do the same as above, and replace the middle section of the path, and finally os.path.join them all together.

Which could leave you with something like:

def cut_path(path):
    path = os.path.normcase(path)
    drive, path = os.path.splitdrive(path)
    parts = path.split(os.sep)
    parts[0] = drive + parts[0]
    # Join plays funny, so you have to add a separator in these cases.
    if parts[0][-1] == ':':
        parts[0] += os.sep
    if len(parts) >= 4:
        parts [2:-1] = ['...']
    return os.path.join(*parts)