Your first comment is misleading (it's the itertools module not the permutations module) and useless anyway. Remove it.

There's absolutely no reason to rename permutations to prm. Don't do it.

num_of_cases would be better called num_cases, simply because it's more conventional.

Your take input comment is misplaced. It should be at the place it refers to.

counter is too vague: what are you counting? I would call it num_matched_anagrams.

You don't need to convert scrambled_word to a list. permutations accepts any iterable. You don't need to call str on the output of raw_input; it already returns a string.

The prior improvements make the comment take input really obvious, so you can remove that.

The later comments are often misaligned. Have them in line with the text.

prm_list can be generated with just list(permutations(scrambled_word)). This removes two comments.

prm_list should just be called word_orders or similar; don't bother naming things by their type.

check is badly named; it should be called something like find_anagrams.

check should not use file, which is deprecated, but open. It should also use with to handle the file.

check should save the dictionary between runs. In fact, this shouldn't really be check's job at all.

The words should have their newlines trimmed, not the other way around.

check should only return anagrams, not deal with appending.

check should have sensibly named parameters.

check should just call permutations itself.

You do

possible_words = list(set(possible_words))

but why bother having possible_words as a list at all?

Instead of if len(possible_words) == 0, do if not possible_words. I would also switch the if around.

num_matched_anagrams+=1 should have spaces: num_matched_anagrams += 1. The comment is obvious, so remove it.

Now to deal with speed.

words should be a set (since it's a set of words) and you loop over the permutations first. This allows a check of:

def find_anagrams(scrambled_word, words):
    for word_order in permutations(scrambled_word):
        potential_word = ''.join(word_order)

        if potential_word in words:
            yield potential_word

which is much faster.

We can improve this further by doing all the work upfront by making a cannonical, sorted version. This generates a mapping:

sorted word → [list of words that sort to this word]

This can be generated like so:

from collections import defaultdict

word_anagrams = defaultdict(set)

with open('dictionary.txt') as dictionary:
   for word in dictionary:
      word = word.rstrip()

      word_anagrams[sorted(word)].add(word)

This then makes find_anagrams just word_anagrams[sorted(scrambled_word)]. This has high initial overhead (0.5 seconds for me with 170k words) but makes subsequent lookups insanely fast.

This gives the code:

from collections import defaultdict

word_anagrams = defaultdict(set)

with open('dictionary.txt') as dictionary:
   for word in dictionary:
      word = word.rstrip()

      word_anagrams[''.join(sorted(word))].add(word)

num_cases = int(raw_input("Input number of words needed to be unscrambled: "))

num_matched_anagrams = 1
while num_matched_anagrams <= num_cases:
   scrambled_word = raw_input("Input scrambled word: ")
   sorted_word = ''.join(sorted(scrambled_word))

   if word_anagrams[sorted_word]:
      for word in word_anagrams[sorted_word]:
         print "Possible Word for Scrambled Word #" + str(num_matched_anagrams) + ": " + word

   else:
      print "No matches found"

   num_matched_anagrams += 1

The loop can be replaced with for num_matched_anagrams in range(1, num_cases+1).

The whole thing should be put into a main function.

The dictionary parsing could be extracted to another function.

The print should use formatting and I'd add brackets for Python 3 compatibility:

print("Possible Word for Scrambled Word #{}: {}".format(num_matched_anagrams, word))

To complete Python 3 compatibility, add this to the top:

try:
   input = raw_input
except NameError:
   pass

This gives:

from collections import defaultdict

try:
   input = raw_input
except NameError:
   pass

def parse_dictionary(filename):
   word_anagrams = defaultdict(set)

   with open(filename) as dictionary:
      for word in dictionary:
         word = word.rstrip()

         word_anagrams[''.join(sorted(word))].add(word)

   return word_anagrams

def main():
   word_anagrams = parse_dictionary("dictionary.txt")

   num_cases = int(input("Input number of words needed to be unscrambled: "))

   for num_matched_anagrams in range(1, num_cases+1):
      scrambled_word = input("Input scrambled word: ")
      sorted_word = ''.join(sorted(scrambled_word))

      if word_anagrams[sorted_word]:
         for word in word_anagrams[sorted_word]:
            print("Possible Word for Scrambled Word #{}: {}".format(num_matched_anagrams, word))

      else:
         print("No matches found")

if __name__ == "__main__":
   main()

Note that this is the same technique as Prashant gave.


What you are approximating is
$$ \pi =\sum_{m=1}^{\infty}\frac{(-1)^{s(m)}}{m},$$
where \$s(m)\$ counts the number of appearances of primes of the form \$4k+1\$ in the prime decomposition of \$m\$, compare

How can we prove \$\pi =1+\frac{1}{2}+\frac{1}{3}+\frac{1}{4}-\frac{1}{5}+\frac{1}{6}+\frac{1}{7}+\cdots\,\$?

on Mathematics Stack Exchange.

The computation of the factor \$ (-1)^{s(m)} \$ can be done more efficiently: Instead of creating a list of all prime factors of \$m \$, then filtering the list for prime factors of the form \$4k+1\$, and finally counting the filtered list, you can compute the sign while factoring the number:

def sign_for_pi_series(n):
    """ Returns sign for 1/n in the pi series.

    The sign is -1 if n has an odd number of prime factors of the form 4k+1,
    and +1 otherwise.
    """
    s = 1
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            if i % 4 == 1:
                s = -s
    if n > 1 and n % 4 == 1:
        s = -s
    return s

The summation then simplifies to

sum_pi = sum(D(sign_for_pi_series(x))/D(x) for x in range(1, iters + 1))
print(sum_pi)


All the parts are here, but your model is taking on too much work. First, let's tackle one of the three hardest things in computer programming: Naming things.

Naming Classes in an MVC Application

You have three classes, called aptly Controller, View and Model. I know you are trying to learn the MVC pattern, but an important aspect or learning this pattern is that names should make sense beyond telling you which layer in MVC they go. A convention for naming things is a must.

The "Rails" way of naming things all starts with the "model". In your case, your Model class contains data about a "quiz", so Quiz is a perfect name for that class. The controller that handles user interaction for Quiz objects should be called QuizesController -- note that "Quiz" is pluralized, because the controller object handles all quizes, not just one.

After that, a QuizView seems like a good name for the view object.

Really if you think about it, a "quiz" is composed of two other things: quiz questions and quiz answers. We need to properly model a "quiz" before anything else. The Model layer in MVC is the foundation -- the bedrock of your application.

Know Your "Domain:" Properly Modeling Your Quiz

We actually have a need for 3 model classes:

Quiz
QuizQuestion
QuizAnswer

A quiz has one or more questions. An answer requires a question. We need to model this in Ruby.

class Quiz
  attr_reader :questions

  def initialize(questions)
    @questions = questions
    @grade = 0
  end

  def answer_question(question, answer_text)
    question = questions[question_number - 1]
    question.answer answer_text
  end

  def grade
    return @grade if @grade > 0

    number_correct = 0

    questions.each do |question|
      number_correct += 1 if question.answered_correctly?
    end

    @grade = calculate_grade number_correct
  end

  def retake
    @grade = 0

    questions.each do |question|
      question.remove_answer
    end
  end

  def quesion_count
    questions.count
  end

private

  def calculate_grade(number_correct)
    number_correct / questions.count
  end

end

A Quiz is a tad more complex, but it just needs a list of QuizQuestions in its constructor. All other operations on the quiz are public methods, some of which are delegated to the QuizQuestion class.

class QuizQuestion
  attr_reader :text, :answer, :expected_answer

  def initialize(text, expected_answer)
    @text = text
    @expected_answer = expected_answer
  end

  def answer(answer_text)
    @answer = QuizAnswer.new self, answer_text
  end

  def answered_correctly?
    return @answer.nil? ? false : @answer.correct?
  end

  def remove_answer
    @answer = nil
  end
end

The QuizQuestion class glues the quiz together with the answer, which we will see in a moment. Again, the constructor doesn't do much, except take in the data it needs in order to exist: The question text and the expected answer. The answer method creates the QuizAnswer object and returns it. The logic of "retaking" a quiz is also delegated to the remove_answer method.

class QuizAnswer
  attr_reader :question, :text

  def initialize(question, text)
    @question = question
    @text = text
  end

  def correct?
    return question.expected_answer == text
  end

  def question_text
    question.text
  end
end

Lastly the QuizAnswer class glues together the quiz question and the user's answer, along with the logic for testing the answer.

Now that we've properly modeled our "domain", the Quiz, QuizQuestion and QuizAnswer classes become our Domain Models combining data with business logic (taking a quiz). Next, we will take a step up from the "foundation" of our application to explore the data access layer, or "Repository".

The Data Access Layer (Repository)

The Repository Pattern decouples the data access from your model and controller. What your controller needs is a QuizRepository object that does all the data access.

Since you are going with flat file storage, we want to extract this behavior into its own layer.

class QuizRepository
  def initialize(filename)
    @filename = filename
  end

  def all
    return @quizes unless @quizes.nil?
    load
    @quizes
  end

  def find(index)
    return nil if index < 0 || index > all.count

    return all[index]
  end

  def reload
    @quizes = nil
  end

private
  def filename
    @filename
  end

  def load
    questions = []
    index = 0
    question_text = ""
    expected_answer = ""
    file = File.open filename

    file.each_line do |line|
      if index % 2 == 0
        question_text = line
      else
        expected_answer = line
        questions << QuizQuestion.new question_text, expected_answer
      end

      index += 1
    end

    @quizes << Quiz.new questions
  end

end

The QuizRepository class needs a filename, and it lazy loads the quiz objects only when you need to get them.

Notice that there is no console interaction. This should be encapsulated by the "Controller".

Handling User Interaction and Displaying Information

Knowledge of the console, and what to display is the realm of the controller and views.

class QuizesController
  def initialize(quiz_repository)
    @quiz_repository = quiz_repository
  end

  def run
    counter = 1
    quiz = @quiz_repository.all.first

    puts "Welcome to the Quiz!"
    puts "--------------------"

    quiz.questions.each do |question|
      puts QuizQuestionView.new question, counter
      answer_text = gets.chomp
      answer = quiz.answer_question question, answer_text
      puts QuizAnswerView.new quiz, answer
      counter += 1
    end
  end
end

The main loop is inside the controller, since the controller in MVC responds to user input. The controller needs a "quiz repository" which is the only argument in its constructor. You'll also notice there are 2 views: QuizQuestionView and QuizAnswerView.

class QuizQuestionView
  def initialize(question, question_number)
    @question = question
    @question_number = question_number
  end

  def to_s
    "Question \##{@question_number}: #{@question.text}"
  end
end

class QuizAnswerView
  def initialize(quiz, answer)
    @quiz = quiz
    @answer = answer
  end

  def to_s
    text = if answer.correct?
             "well done"
           else
             "the correct answer is #{answer.question_text}"
           end

    text + "\nYour score is now #{@quiz.grade}"
         + "\n--------------------------------------------------------------------------"
  end
end

Also notice that there are no calls to gets or puts in the "view" classes. These classes are responsible for output only. The fact that you are outputting to a console is the responsibility of the Controller, since the Controller knows you are interacting with the user via the console. The to_s method is defined, which returns a string that the Controller then prints to the standard output of the console.

Putting All The Layers Together

Now we actually need to run the program:

#!/bin/env ruby

quiz_repository = QuizRepository.new "/data/quiz.txt"
controller = QuizController.new quiz_repository
controller.run

The whole application is started, run and exits in three lines of code.


An installer for shell scripts, written in pure sh

I see a number of things that may help you improve this program.  I don't have a Windows machine handy, so these will all be Linux-based observations.

For local installation, don't use sudo

Right now, when the program is created for a local user, the use of sudo to copy it means it ends up owned by root.  That means that although it's in the local user's bin, they can't run it.  For local installation, sudo shouldn't be needed at all and would be a lot safer.

Don't duplicate entries in .profile

Right now, each invocation of your program will cause an additional possibly duplicate line to be added to .profile.  Better would be to only add a line if it doesn't yet exist there.

Use only POSIX features

Right now the code includes this line:

SCRIPT=$(< /dev/stdin) # read from standard input

However, that's not necessarily portable.  Instead, use cat as in:

SCRIPT=$(cat /dev/stdin) # read portably from standard input


Naming Conventions
Variables in java should be camelCase, meaning they should start with a small letter.

Meaningful names
Someone reading your code doesn't stand a chance in hell to understand what you are trying to do without actually running this code in his head...
Your class is called Main, your only method is main... at least try to tell your reader some story on what you are trying to do, especially when you post it for review!
Variable names like n, m, num, and sum add nothing to explain your code. Names like s and S are even worse.

Efficiency
It is very hard to give efficiency advice, if I can't say what exactly you are trying to achieve, but some obvious observations:

int S[] = new int[100000];

This doesn't look very efficient - you allocate all this memory up front, and I couldn't really see where you are using it...

Your is also not very defensive - you don't close your stream in case of an exception (you should use try(PrintWriter out = new PrintWriter(System.out)) block to make sure of that), and you never validate that num[r - 1] is valid, so there is a decent chance that your code will not run as expected.

Idioms
You should use the idioms relevant for the language you use, for example - sum1 += diff; instead of sum1 = sum1 + diff;
Another example - don't wrap System.out with PrintWriter simply use System.out.println(sum2 - sum1)


Whitelist input data for a lookup by name

Don't ever make assumptions of what to allow or disallow based on what you have seen in your experience.  Always consult the specification, which is, in this case, RFC 4515 Sec 3.  The spec will tell you which characters require escaping, and what the escaping mechanism is.


Singly Linked List Implementation in ES6

TL;DR

Style could better adhere to established standards.
insertAt has bugs to resolve.
This class is missing basic add/remove functions which prevent it from being useful.
Writing a linked list class in JS only makes sense from an educational standpoint; primitive arrays are efficient, universal and offer more functionality with less code.

Style

Spacing

Use a space between )s, {s and keywords, e.g.

if(this.head === null){

is cleaner as

if (this.head === null) {

Add vertical spacing between lines to group logical code blocks together and separate loop, conditional and function logic from declarations. For example,

let curr = this.head;
while(curr !== null){

is easier to read as

let curr = this.head;

while (curr !== null) {

this.size ++ is clearer as this.size++.
Be consistent--sometimes you use }else{, and sometimes you use

}
else{

Your whitespace fixes can be done by putting the code into SE's Code Snippet and pressing "Tidy", then adding blank lines around blocks by hand. Generally, I don't see reason to deviate from this prescribed style.

Variable and function naming

Function names switch between snake_case and camelCase. All JS naming should be camelCase, except class names, which are UpperCamelCase (as you use).
Avoid single-letter variable names like p unless the meaning is obvious. In this case, something like newNode might be clearer.

Functionality

Errors

throw "Wrong index"; is an unclear error message. What exactly is wrong with the index? Consider throw "Index out of list bounds"; which more accurately describes the problem.
You may wish to reconsider using errors at all. I find throwing errors in JS generally less appropriate than return values because the calling code can stick to normal conditionals to handle control flow.

Also, not throwing errors is in keeping with JS's builtin library functions, which generally don't complain about invalid or missing input. For insertAt, for example, you could return true if the insertion was successful and false otherwise. If the user provides something silly as an index that causes a crash, they'll get an appropriate stack trace that likely explains the problem better than a hand-written error string.

If you do wish to stick with error throwing, ensure it is comprehensive. For example, if (index > this.size) doesn't handle the case when index < 0 which could result in difficult-to-track-down bugs for the client who has to make design assumptions based on your throw.

Then, once you've covered that scenario, it begs the question whether you should now validate that the provided input is an integer number and throw an error message for that as well.

The point is, adding errors gives the client the illusion of a comprehensive and robust set of argument and function state restrictions, which is problematic if they aren't actually robust. Throwing no errors, assuming the client is behaving, and reporting true/false as to whether some function failed or not seems preferential.

Variable keywords

Use const when appropriate in place of let. This should apply to almost everything except for loop counters, accumulator variables and runner nodes. For example, let out = []; should be const out = [];. Even if the risk of bugs caused by accidental reassignment is low, this has semantic benefits.

Misleading function names

printList() is a misleading name; it stringifies the list rather than printing. I recommend overriding toString() here.
insert() usually refers to insertion at some specific element, which is the behavior your insertAt() function offers. With insert(), It's not obvious where the insertion is happening; one of addFront, unshift or push seem clearer, depending on which end of your list you decide the front to be.

Internal logic

insertAt is not working correctly, placing items incorrectly, not at all, and neglecting to increment the size.
Consider adjusting your insertAt code to avoid using returns and curr.next.next, which is difficult to reason about and causing bugs.
In printList, pains are taken to conditionally add the -> arrow only for non-last elements when you can simply walk the list and use out.join("->").
Since your internal code relies only on Node objects, you can make your code cleaner by testing while (curr) instead of while (curr === null). This is debatable, because it restricts your internal logic from distinguishing between null and undefined or other falsey values, but if you trust yourself to be consistent about it, I prefer the cleaner look.

Interface

As written, I find your provided function interface insufficient for typical linked list needs. It's not obvious what functionality this class offers over, say, a primitive array.

Consider remove(item). This sort of function that takes an element and searches the structure for it is best used for hashes with random access. The whole point of linked lists is to offer fast insertion and removal of front and back elements, regardless of what those elements might be. Anything in the middle is of no concern, and libraries that offer access to these elements, such as Java's LinkedList collection are generally considered to be flawed because clients may make false assumptions about the time complexity of provided operations.

Without constant time front and back adds, removals and peeks, I can't foresee a reason to use this class instead of a primitive array. insert is the only useful linked list function your interface offers (disregarding isEmpty, printList, etc as useful but trivial).

Rewrites

Revision #1 (same functionality)

class LinkedList {
  constructor() {
    this.head;
    this.size = 0;
  }

  addFront(value) {
    const newNode = new Node(value);

    if (this.head) {
      newNode.next = this.head;
    }

    this.head = newNode;
    this.size++;
  }

  insertAt(value, idx) {
    let curr = this.head;
    let prev;

    while (curr && idx > 0) {
      prev = curr;
      curr = curr.next;
      idx--;
    }

    if (prev) {
      prev.next = new Node(value);
      prev.next.next = curr;
      this.size++;
    }
    else {
      this.addFront(value);
    }
  }

  remove(value) {
    let curr = this.head;
    let prev;

    while (curr) {
      if (curr.val === value) {
        if (prev) {
          prev.next = curr.next;
        }
        else {
          this.head = undefined;
        }

        this.size--;
        return true;
      }

      prev = curr;
      curr = curr.next;
    }

    return false;
  }

  length() {
    return this.size;
  }

  empty() {
    return !this.size;
  }

  toString() {
    const result = [];
    let curr = this.head;

    while (curr) {
      result.push(curr.val);
      curr = curr.next;
    }

    return result.join("->");
  }
}

class Node {
  constructor(val, nextNode=null) {
    this.val = val;
    this.next = nextNode;
  }
}

const list = new LinkedList();
list.remove(1123);
list.insertAt(21, 33);
list.remove(21);
list.addFront(12);
list.addFront(9);
list.addFront(13);
list.addFront(17);
list.remove(1123);
console.log(list.toString());
list.remove(12);
console.log(list.toString());
console.log(list.length(), list.empty());
list.insertAt(21, 2);
console.log(list.toString(), list.length());
list.insertAt(11, 0);
console.log(list.toString(), list.length());

Revision #2 (added front/back operations)

class LinkedList {
  constructor() {
    this.head;
    this.tail;
  }

  addFront(value) {
    const newHead = new Node(value);

    if (this.head) {
      newHead.next = this.head;
    }
    else {
      this.tail = newHead;
    }

    this.head = newHead;
  }

  addBack(value) {
    if (this.tail) {
      this.tail.next = new Node(value);
      this.tail = this.tail.next;
    }
    else {
      this.head = this.tail = new Node(value);
    }
  }

  peekFront() {
    return this.head ? this.head.val : null;
  }

  peekBack() {
    return this.tail ? this.tail.val : null;
  }

  popFront() {
    if (this.head) {
      const value = this.head.val;
      this.head = this.head.next;

      if (!this.head) {
        this.tail = null;
      }

      return value;
    }
  }

  empty() {
    return !this.head;
  }

  toString() {
    const result = [];
    let curr = this.head;

    while (curr) {
      result.push(curr.val);
      curr = curr.next;
    }

    return result.join("->");
  }
}

class Node {
  constructor(val, nextNode=null) {
    this.val = val;
    this.next = nextNode;
  }
}

const list = new LinkedList();
list.popFront();
console.log(list.toString(), list.empty());
list.addBack(1);
console.log(list.toString(), list.empty());
list.popFront();
console.log(list.toString(), list.empty());
list.addFront(2);
console.log(list.toString());
list.addBack(3);
console.log(list.toString());
list.popFront();
console.log(list.toString());
list.addFront(4);
list.addBack(5);
console.log(list.toString());

Note that there is no popBack() because this operation would be linear without doubly linked nodes. However, the class is sufficient to support both stacks and queues with all operations in constant time. Without the tail pointer, only a stack could be supported. Adding popBack() and double links would give you a deque class.

Revision #3 (supported a queue)

class Queue {
  constructor() {
    this.list = new LinkedList();
  }

  offer(value) {
    this.list.addBack(value);
  }

  poll() {
    return this.list.popFront();
  }

  peek() {
    return this.list.peekFront();
  }

  empty() {
    return this.list.empty();
  }

  toString() {
    return this.list.toString();
  }
}

class LinkedList {
  constructor() {
    this.head;
    this.tail;
  }

  addFront(value) {
    const newHead = new Node(value);

    if (this.head) {
      newHead.next = this.head;
    }
    else {
      this.tail = newHead;
    }

    this.head = newHead;
  }

  addBack(value) {
    if (this.tail) {
      this.tail.next = new Node(value);
      this.tail = this.tail.next;
    }
    else {
      this.head = this.tail = new Node(value);
    }
  }

  peekFront() {
    return this.head ? this.head.val : null;
  }

  peekBack() {
    return this.tail ? this.tail.val : null;
  }

  popFront() {
    if (this.head) {
      const value = this.head.val;
      this.head = this.head.next;

      if (!this.head) {
        this.tail = null;
      }

      return value;
    }
  }

  empty() {
    return !this.head;
  }

  toString() {
    const result = [];
    let curr = this.head;

    while (curr) {
      result.push(curr.val);
      curr = curr.next;
    }

    return result.join("->");
  }
}

class Node {
  constructor(val, nextNode=null) {
    this.val = val;
    this.next = nextNode;
  }
}

const q = new Queue();
q.offer(1);
console.log(q.poll());
console.log(q.poll());

for (let i = 0; i < 5; i++) {
  q.offer(i);
}

while (!q.empty()) {
  console.log(q.poll());
}

After all that work, a benchmark shows that it's no faster than a primitive array. This is likely due to overhead from object creation, function calls and garbage collection, which counteracts the shifting necessary on the primitive array.


Unit testing static method that imports environment file

If you really want to unit test that logic, you should fake its data. In order to do that, you need a way to inject that dependency instead of getting it straight from it.

You have 3 options:

Installing a framework to mock the import (as detailed in https://medium.com/@emandm/import-mocking-with-typescript-3224804bb614)
Have a constructor that is autocalled for its usage statically.
Similar to number 2: have a method with environment as parameter (so you can test it), and the current one calls the new one with the imported environment as parameter.


Using  instead of other tag types (, , etc)

The div element, short for division, is a block element mostly used to group larger chunks of HTML, to create CSS-styled layouts.

On the other hand, the span element is an inline element, mostly used to group and stylize text/images. It makes it easy to apply custom styles without changing the general layout.

Also, a div element takes all available width while the span only takes as much width as necessary.

It is certainly not illegal (since HTML5) what you're doing, but to follow semantics I'd use span for what you are trying to achieve.


DeepPtr: a deep-copying unique_ptr wrapper in C++

You already accepted Loki's answer (and he made good points) but there is one comment I wanted to add regarding this:

  •Any other pitfalls that could be caused by this class.

Your class has no information on the concrete type held within, causing slicing in the presence of derived classes;

Consider this scenario:

class Base { ... }; // not abstract (can be instantiated)
class Derived: public Base { ... };

auto ptr1 = DeepPtr<Base>(new Derived{});
auto ptr2 = ptr1;

The last line will populate ptr2 with a Base instance that has all the sliced values from ptr2's Derived instance (because ptr2's constructorr calls new T, which resolves to new Base - not new Derived).

You have two possible solutions for this:

intrusive cloning (your class hierarchy rooted in Base needs to implement a virtual Base* clone() = 0 where each specialization of Base returns it's own instance); this cloning implementation would be then used for deep copy;
transparent cloning, based on template specialization of a factory function, by the derived type. I needed to implement something similar for the same reason (deep copy of polymorphic pointers). You can see here my implementation.

See the use of to_polymorphic functions in my question, and how they instantiate the correct cloning function, transparently.


I would consider your first question as offtopic. So I will only answer the second question.

For each call to maxHeight you make a lot of recursive calls. Consider what happens if n is large. Say n=100, then can you tell me how many times you call maxHeight? I can't work it out other than "lots". Also consider that you will be calling maxHeight with the same arguments very often, calculating the same results over and over.

Lets look at an example recursive function that bears some resemblance to your code:

int f(int n)
{
    if (n == 0)
        return 1;

    int sum = 0;
    while(n--){ // In your code: while((left - right) > k)
        sum += f(n);
    }
}

While this looks innocent, even for small n you will iterate a really long time. For f(1) you will need one call to f(0). For f(2) you will need one call to f(1) (which calls f(0)) and one to f(0) which totals 3 calls. For f(3) you will need one call to f(2) (which then does 3 more calls), f(1) (which does 1 extra call for you) and f(0) i.e. (3+1) + (1+1) + 1 = 7. Continuing on f(4) will need (7 + 1) + (3 + 1) + (1+1) + 1 = 15. I think you can see where this is heading. For f(n) you will need 2^n-1 calls. So for n=300 you have 2^300 ~= 10^100 calls to  f(0). To put that into perspective considering that it's been estimated that there are about 10^80 atoms in the observable universe. I wouldn't want to stick around and wait until that completes. Not even if every atom in the observable universe was a 1 THz computer working optimally in parallel to calculate this.

Your code exhibits the same type of pattern, you make many recursive calls per call to maxHeight so you are probably even worse off.

Comparing to:

int fewest_node(int k,int h)
{
    if(h <= 0)
        return 0;
    return 1+fewest_node(k,h-1)+fewest_node(k,h-1-k);
}

int maxHeight2(int k, int n)
{
    for(int h = 1;;h++)
        if(fewest_node(k,h) > n)
            return h - 1;
}

Calling fewest_node(int j, int h) will result in at most 2^h recursive calls, which is still a lot, but less than your code. But here is the catch, fewest_node() is very simple in structure and the compiler can expand the function in a way similar to loop-unrolling which removes a lot of iteration and overhead. This is a case of K.I.S.Silly.

One way that both of the solutions can be speed up dramatically is by using Dynamic Programming, like this:

#define MAX_N 1000 // Adjust to taste
#define MAX_K 100

int dp_table[MAX_N *MAX_K]={0}; // Not sure if this is legal, otherwise use memset

int fewest_node(int k,int h)
{
    int index = k*MAX_N+h;
    if(!dp_table[index]){
        if(h <= 0)
            return 0;
        dp_table[index] = 1+fewest_node(k,h-1)+fewest_node(k,h-1-k);
    }
    return dp_table[index];
}

int maxHeight2(int k, int n)
{
    for(int h = 1;;h++)
        if(fewest_node(k,h) > n)
            return h - 1;
}

Simply store each calculated result for fewest_node and start from the bottom up with small h. You can also dynamically allocated a table of the required size when you have received your n and k for the problem. This will drop the worst case time from 2^n to n*k which is eons faster. You can do the same for your code. Just introduce a table of cached results.


Not sure that a class definition makes a lot of sense here since you don’t really have any real behavior being defined in this class.
Destructuring can also help you populate variables from the input array directly.
camelCase is generally preferred in JS vs. snake_case.

For example you might simplify to something like this:

const conversionFn = ( [ channelId, payload, sequence ] ) => {
  return { channelId, payload, sequence };
};


Simplifying the notation

        File[] listOfFiles = root.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
            String iName = listOfFiles[i].getName();
            if (listOfFiles[i].isFile() && iName.endsWith(".tif")) {

Consider

        for (File source : root.listFiles()) {
            if (source.isFile() && source.getName().endsWith(".tif")) {

This way we don't create an index variable that we don't need.  Instead, we iterate over the list directly.  This saves dereferencing.

I also got rid of the iName variable.  This is more of a judgment call, but it was only used once.  I find that unnecessary.

I prefer the name source, as it is clearer about the purpose of the file.

Direct answers

                RenderedImage renderedImage[], page;
                File tiffFile = new File(listOfFiles[i].getAbsolutePath());

                SeekableStream seekableStream = new FileSeekableStream(tiffFile);
                ImageDecoder imageDecoder = ImageCodec.createImageDecoder("tiff",seekableStream, null);
                renderedImage = new RenderedImage[imageDecoder.getNumPages()];

                int tifPageCount = 0;
                for (int k = 0; k < imageDecoder.getNumPages(); k++) {
                    renderedImage[k] = imageDecoder.decodeAsRenderedImage(k);
                    tifPageCount++;
                }

Consider

                File tiffFile = new File(source.getAbsolutePath());
                SeekableStream seekableStream = new FileSeekableStream(tiffFile);
                ImageDecoder imageDecoder = ImageCodec.createImageDecoder("tiff", seekableStream, null);

                int tifPageCount = imageDecoder.getNumPages();

This saves declaring the never used page.

It saves declaring and populating renderedImage when you only want to generate a count.

Separation of concerns

The real problem here is that the method does a bunch of different things.  It takes a directory and traverses it.  At each file, it checks if the file matches a characteristic.  If the file matches, it takes an action.  It produces output as it goes.  Consider

public class FileFinder {

    private List<File> files = new ArrayList<>();
    private final FileMatcher matcher;
    private final File root;

    public FileFinder(FileMatcher matcher, File root) {
        this.matcher = matcher;
        this.root = root;
    }

    public List<File> findMatchingFiles() throws IOException {
        files = new ArrayList<>();
        findMatchingFiles(root);
        return files;
    }

    private void findMatchingFiles(File root) throws IOException {
        if (root.isFile()) {
            if (matcher.matches(root)) {
                files.add(root);
            }

            return;
        }

        if (!root.isDirectory()) {
            return;
        }

        for (File file : root.listFiles()) {
            findMatchingFiles(file);
        }
    }

}

This class and method has a single purpose, to traverse a file system from a particular root and find all the matching files.  Rather than processing them in place, it returns the files to be processed by the caller.  It doesn't even know how the files match, only that they do.

It's not clear to me that this needs the throws IOException.  I didn't try it, as I didn't want to set up a test environment.  If needed, this is how to do it.  If not, you can just remove them.

public interface FileMatcher {

    boolean matches(File file);

}

Not much to the interface.

public class SuffixMatcher implements FileMatcher {

    private final String suffix;

    public SuffixMatcher(String suffix) {
        this.suffix = suffix;
    }

    public boolean matches(File file) {
        return file.getName().endsWith(suffix);
    }

}

Not much to the implementation either.  The important part is that this abstracts the matching from the traversal.  We could reuse this code for not just different suffixes but entirely different criteria.

public class TiffCopier {

    public static final int MAXIMUM_COUNT = 15;
    public final int FILE_SIZE;
    public final int MAXIMUM_SIZE;
    public final File FOLDER;
    public final String TARGET_PATH;

    public TiffCopier(int fileSize, String targetPath) throws IOException {
        FILE_SIZE = fileSize;
        MAXIMUM_SIZE = fileSize * 1000;
        TARGET_PATH = targetPath;

        FOLDER = new File(targetPath + "Files by Size\\Files of size " + fileSize + " KB");
    }

    public static int countPages(File source) throws IOException {
        File tiffFile = new File(source.getAbsolutePath());
        SeekableStream seekableStream = new FileSeekableStream(tiffFile);
        ImageDecoder imageDecoder = ImageCodec.createImageDecoder("tiff", seekableStream, null);

        return imageDecoder.getNumPages();
    }

    public void copy(File source) throws IOException, SameFilesException {
        long fileSize = source.length();
        if (fileSize > MAXIMUM_SIZE || countPages(source) > MAXIMUM_COUNT) {
            return;
        }

        File file = new File(TARGET_PATH + source.getName());
        if (file.exists()) {
            System.out.println(file.getName() + " already exists");
            return;
        }

        if (!FOLDER.exists()) {
            if (FOLDER.mkdir()) {
                System.out.println("Folder : " + FOLDER.getAbsolutePath());
            }
        }

        try {
            String sizeDisplay = FileUtils.byteCountToDisplaySize(fileSize);
            System.out.println(source.getName() + " | " + sizeDisplay);
            FileUtils.copyFileToDirectory(source, FOLDER);
        } catch(IOException e) {
            System.out.println("Same files");
            throw new SameFilesException();
        }
    }

    public void copyAll(File root) throws IOException {
        FileMatcher matcher = new SuffixMatcher(".tif");
        FileFinder finder = new FileFinder(matcher, root);

        for (File source : finder.findMatchingFiles()) {
            try {
                copy(source);
            } catch (SameFilesException e) {
                return;
            }
        }
    }

}

This breaks your single long method into smaller pieces.

There are still some separation of concerns issues.  This still has output scattered throughout the execution of the program.  I did localize it to just one of the smaller methods.  But that method still does more things than it should.  I'm not entirely sure of the point of the output, so I didn't try to overengineer a more elegant solution.

This program still halts execution on most IOException occurrences.  It might be better to handle these and continue.

I still include throws IOException in places that may not need it.  I would encourage you to remove the extras.

I did break out several utilities.  For example, the countPages is now its own method.  I left it here, although it could be moved into its own class.  Suffix matching and file system traversal get their own reusable classes.

I did not implement SameFilesException.  Its implementation should be relatively trivial, as it basically just rebrands an IOException occurring at a particular point.

I declared several constants, including two that are just operations performed repeatedly on the same datum.  I find it easier to follow this more abstracted version.

I standardized on putting control statements between ending and beginning braces when that fit.  E.g. } else { on the same line.  You sometimes did that and sometimes put the control statement on a new line after a closing brace.  The normal Java standard is all on the same line, but the most important thing is consistency.  Please pick one style and stick to it throughout each program.

As I said, I didn't try to compile this much less test it.  Beware of silly errors introduced in editing.


How easy is it to crack this encryption algorithm?

Your encryption scheme basically takes a string and does a one-to-one mapping of characters to 63 numbers (0 to 62).  Ignoring this straightforward mapping of characters, your scheme basically is the i-th character of the ciphertext (1-indexed) is c[i] = (p[i] + H**i) % N, where N is the size of the alphabet (63), p[i] is i-th character of the plaintext, and H is the hash calculated from the password.

Decryption should be straightforward as p[i] = (c[i] - H**i) % N.

But the code doesn't work -- decryption is impossible

First, the code is seriously flawed as perl handles integer overflow by switching to floating point numbers rather than moving to a big integer library.

For example, for pw="abc" the hash is 8486571168 (as seen by inserting a print statement).  Note for say the second character in the array you calculate 8486571168**2 in perl is 7.20218901895289e+19 -- an double precision floating point number.  Note adding any number 0 to 63 to 7.20218901895289e+19 leaves the value unchanged in a double -- hence your code doesn't work -- it loses the original value of the plaintext due to rounding errors from using floating point math.

You can easily demonstrate this by using the same password (abc) to encrypt say "hBROKEN1234" or "hNOTWORKING" (or anything else starting with an h of this length).  Regardless of the plaintext, the generated "ciphertext" will always be "9bkpXY1H0oR".  You could fix this by using modular exponentiation library or a big-integer math library, or switching to a language like python that has big integer math built-in.  Note, it suffices to show that an encryption method is broken if the same key encrypts two different plaintexts to the exact same ciphertext.  If that happens clearly there is no decryption function, as the decryption function takes the key and the ciphertext and needs to recover the original plaintext.

Furthermore the algorithm is trivially attackable

Second, this scheme if fixed would be trivial to attack.  You merely have to try to decrypt with all N (length of your alphabet) different values of the hash (modulo the alphabet size) and at least one of them should work.

If you understand modular arithmetic (if not see below) you will see your encryption method for each character c[i] = (p[i] + H**i) % N is exactly equivalent to c[i] = p[i] + (H % N)**i) % N.  This is bad as there are only N possible values of H % N (and in our case N=63), so its trivial to try decrypting with H=0 to H=62 until you find something that is meaningful data.

Background on modular arithmetic

To see this note we are doing modular arithmetic.  In modular arithmetic, there's the concept of congruent numbers; e.g., on a clock face (modulo 12) there's no difference between 3 o'clock or 15 o'clock, or 51 o'clock (48+3), so we say \$3 \equiv 15 \equiv 51 \;(\bmod 12)\$ -- the notation is to only write \$(\bmod N)\$ in parenthesis at the end, even though it applies to the whole equation (all sides).

When you do modular arithmetic for the most part, it doesn't matter if you take the modulus step early.  This is easy to see for addition.  if you add 7 hours to 3 o'clock, you get 10.  Similarly if you add 31 hours (\$31 = 7 \bmod 12\$) to 15 o'clock, you again get 10 on the clock face.  To formalize this notation, let's define two pairs of congruent numbers modulo N, specifically \$a \equiv A\;(\bmod N)\$ which means \$A = a + m N\$ for some integer \$m\$ (\$m\$ could be positive, negative or zero), and similarly let \$b \equiv B \;(\bmod N)\$ and \$B = b + n N\$ for some integer \$n\$.  Doing the addition we get \$A + B = a + b + (m + n) N\$, and since \$m + n\$ is also an integer we just showed the \$A + B \equiv a + b\; (\bmod N)\$.  You can do similar proofs for subtraction, multiplication, and exponentiation.
works.  The proof for multiplication: $$\begin{eqnarray}
A B &=& (a + m N)(b + n N)\\
&=& a b + m b N + n a N + m n N N \\
&=& a b + (m b + n a + m n N) N \\
\therefore A B &\equiv& a b\; (\bmod N)
\end{eqnarray}$$

Similarly for the base in exponentiation, we can show we can take the modulus (of the base) can be done early as

$$\begin{eqnarray}
A^k &=& (a + m N)^k\\
&=&  \sum_{i=0}^k {k \choose i}a^{k-i} (m N)^i \\
&=& a^k + \sum_{i=1}^k {k \choose i}a^{k-i} m^i N^i \\
&=& a^k + N \left(\sum_{i=1}^k {k \choose i}a^{k-i} m^i N^{i-1} \right) \\
\therefore A^k &\equiv& a^k\; (\bmod N)
\end{eqnarray}$$

where the binomial theorem was used.  Thus we are allowed to take an expression like (a + b**x) % N and change it to (a + (b % N)**x) % N and it won't change the result and thus only need to try all the values of (h % N) when brute-force decrypting.


Program that moves characters in n steps to the next character in alphabet based on ASCII code

You should try to state your problem more clearly: "the program that moves the character to the next character" seem to assume we know some other program you're referring to. If I understand what you're trying to do, this is the problem:

"Given a String, replace each alphabetical character with the character STEP positions after in the alphabet, wrapping around if needed."

If this is the problem you're trying to solve, here is how I would do it:

public static char nextCharacterInAlphabet(char character , int step) {
  boolean isLower = Character.isLowerCase(character);
  char c = Character.toLowerCase(character);
  if (c < 'a' || c > 'z')
    return character;
  char nextC = (char)((c - 'a' + step) % 26 + 'a');
  return isLower ? nextC : Character.toUpperCase(nextC);
}


According to the Style Guide for Python Code, function and variable names
should be “lowercase, with words separated by underscores as necessary to improve readability.” In your case I'd suggest

def median_of_sorted_arrays(a, b):

Your code determines the median correctly. However, it modifies the
passed arguments, which might be unexpected to the caller:

a = [-5, 3, 6, 12, 15]
b = [-12, -10, -6, -3, 4, 10]

print(findMedianSortedArrays(a, b))   # prints 3
print(findMedianSortedArrays(a, b))   # prints 13.5

This could be fixed by accessing the lists via subscripting:

i = 0
j = 0
while i < len(a) and j < len(b):
    if (a[i] < b[j]):
        combined.append(a[i])
        i += 1
    else:
        combined.append(b[j])
        j += 1
combined.extend(a[i:])
combined.extend(b[j:])

The next possible improvement is to get rid of the additional storage:
Instead of storing elements from a or b into the combined list
you could just count how many elements have been merged so far,
until the median element is found.

A more efficient algorithm is described in

Median of two sorted arrays with different sizes in O(log(min(n, m)))

The basic idea is to partition both a and b into

a[:i] + a[i:]
b[:j] + b[j:]

such that the following conditions are satisfied:

i + j = (len(a) + len(b) + 1) // 2
a[i-1] <= b[j]
b[j-1] <= a[i]

and this can be done efficiently with a binary search. Then the “union”
of the first (resp. second) halves is the first (resp. second) half of the combined array, so that the median is

max(a[i - 1], b[j - 1])   # if the total length is odd
(max(a[i - 1], b[j - 1]) + min(a[i], b[j])) / 2 # if the total length is even


I assume that Hours is a custom class of yours.

If you are asking if there is an existing Java class that will automagically calculate the "difference" between two instances of your custom class, the the answer is "No".
If you are asking (more generally) what is the best class for handling temporal quantities so that you can compare them, calculate differences and so on, then the answer is to look at the JodaTime libraries.

I also note that you are STILL using "Business" as a package name.  You should stop it before The Protectors of Java Purity find a way to hack your PC and fill the disc drive with zeros!!!

Seriously, it is bad practice.  Don't do it.  Follow the standard Java naming conventions, like professional developers do.


Binning and calculating a huge range of data

You call con.commit() unnecessarily — there is no change to be committed.  You defined all_rows, but never use it.  But those are just minor inefficiencies.

The point of using a database is that you can ask it to tell you interesting things about your data.  If you are just going to dump out the entire contents of a table for analysis, you might as well use a CSV file.

A query like this would be ideal:

SELECT FLOOR(latitude) AS latitude
     , COUNT(userid) AS message_count
     , COUNT(DISTINCT userid) AS distinct_count
    FROM message
    GROUP BY 1
    ORDER BY 1;

Unfortunately, SQLite lacks a FLOOR() function, so a circumlocution is necessary:

SELECT CASE WHEN latitude = CAST(latitude AS INTEGER) OR latitude >= 0 THEN CAST(latitude AS INTEGER)
            ELSE CAST(latitude - 1 AS INTEGER)
       END AS latitude
     , COUNT(userid) AS message_count
     , COUNT(DISTINCT userid) AS distinct_count
    FROM message
    GROUP BY 1
    ORDER BY 1;

Note that a simple CAST (latitude AS INTEGER) would be inappropriate for histogram binning, as casting truncates towards zero, such that -0.99 < latitude < +0.99 would all map to 0.

It should be trivial to read the results from that query into bin_count_all and bin_count_unique.

Note that to make that query run efficiently, it would be wise to

CREATE INDEX message_latitude_userid ON message (latitude, userid);


If that really is all you need to calculate, then it's not too bad.

However, I suspect that you have other date calculations happening in your application.  In that case, why not take advantage of Ruby's Date class?  The >> operator adds months.

require 'date'
next_period = (Date.today >> tax_period_months).month


I think there are two major issues you should address right in the beginning when you start with PHP.

Separation of Layout and Logic

This means in general that you shouldn't mix HTML and PHP code. Later this will lead you to the MVC-Pattern.

index.php

<?php
// connect to database
include("inc/dbconnect.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    //...
}

$result = mysqli_query($database,"SELECT * FROM contacts");

$records=array();
while($row = mysqli_fetch_array($result)) {
    $record[]=$row;
}

mysqli_close($database);

include 'template.php';

template.php

<!DOCTYPE html>

...

        <?php foreach ($records as $record):?>

             <?= $record['firstName']?> <?= $record['lastName']?>
             <a href="mailto:<?= $record['email']?>"><?= $record['email']?>
             <?= $record['phone']?>
             <?= $record['email']?>

        <?php endforeach;?>

...

Prevent SQL Injection

You are passing user input directly to the query you send to the database. Wikipedia will elaborate some examples in detail and shows how queries can be manipulated.

The easies way for you to prevent this, is using PHP Data Objects and Prepared Statements. I think there is no need for going in detail here if you don't have a specific question, there are many good tutorials out there. The important part is, that the user is no longer able to change the query you send to the database.

Minor issues

If you only have one database connection PHP will use this connection automatically with the mysqli_ methods so you don't have to pass the $database around.
It is best practice to leave away the final '?>' in plain php files. This will prevent that you send any whitespace after ?> to the browser accidentally. (Important if you change the header later.)
echo "Everything blew up!" . mysqli_error($database); . May you should use die.


Do % p early.

Since the test case is huge, I expect intermediate values you compute to be huge as well. Multiplication of large numbers is a very expensive operation. Try to keep your results in a native range. Consider e.g.

def modulo_factorial(n, mod):
    result = 1
    for i in range(1, n + 1):
        result = (result * i) % mod
    return result

Ditto for pow.
Do not recompute factorials from scratch. Instead of

for i in divide:
    temp = factorial(i)
    temp = pow(temp, p - 2, p)
    total = total * temp

sort divide first. Then computation of each factorial can be started where the previous one ended.

Also notice that since total is greater than any element of divide, you should compute factorial(total) after the this loop, using the same technique.

And don't forget to % p early.
Most of your imports are never used.


Working with Mobile Device Orientation Detection

First, the code above can be simplified a lot, at least for the purposes of this "review," and rewritten as:

var currentWidth = document.body.clientWidth,
    newOrientation = window.orientation || (currentWidth > 400);

Second, I'd probably be really sure I'm getting a good width value by doing something like this:

var currentWidth = window.innerWidth || document.body.offsetWidth || document.documentElement.offsetWidth,
    newOrientation = window.orientation || (currentWidth > 400);

Next, none of these devices are perfectly square, right, so instead of checking against a constant, why not check if it's wider than it is tall?

var currentWidth = window.innerWidth || document.body.offsetWidth || document.documentElement.offsetWidth,
    currentHeight = window.innerHeight || document.body.offsetHeight || document.documentElement.offsetHeight,
    newOrientation = window.orientation || (currentWidth > currentHeight);

If I understand your question correctly, this should fix the problem with the larger screens.

Also note that this approach will only work reliably if the viewport is the same size as the physical screen. As you probably know, this can be accomplished with the viewport meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

If you're not setting a viewport, you'll get weird behavior. For example, some mobile browsers seem to keep the viewport settings from the last loaded site when a site with no viewport meta tag loads.


Analyzing a web access log to obtaining totals for requests

If you don't need fields other than size, and have no use for lines with no size, a simpler regex like \s(\d+)$ is going to be appreciably faster.  You could even go with \s(\d{4,})$ and skip the >= 1000 test.

If you do keep the full regex, I'd simplify the date portion because date formats are notoriously unpredictable.  \[[^]]+\] does the job more robustly.

(\S+)? is better written as (\S*).

filename_regex is better named  like log_entry_regex, since that's what it matches.

Overwriting the string line with an array of captures is ugly.  And re.findall is not the best choice, because the regex should never match more than once per line (and your code ignores subsequent matches anyway).  Try something like:

matched = re.search(log_entry_regex, line)
if (matched)
    yield matched.groups()

This eliminates the array-of-arrays in the result and ensures results are always a set of matches.  if line and int(line[0][8]) >= 1000 becomes just if int(line[8]) >= 1000.

The global variables are better placed inside the functions where they're used.  save_to_file would need to take arguments then, but it's three lines and could just be inline in the main function.

When you have an array with many values, where each value means something different, a useful pattern is to create "fake enums" with constant field identifiers.  It makes your uses of that array easier to write and easier to read.  It doesn't make much difference here, where the code is short and only one element is actually used; however it becomes invaluable as line count and complexity increase.  Python doesn't have constants, variables will work too:

HOST = 0
…
SIZE = 8
…
if int( line[SIZE] ) >= 1000:


Invert bits of binary representation of number

int n = 0; This initialization is not used.  It could simply be int n;, or could be int n = !(num & 1); inside the loop, to restrict the scope of n.

This loop:

int k = 0;
while (num) {
    ...
    k++;
}

could be written as:

for(int k = 0; num; k++) {
    ...
}

Since you are doing bit manipulation, instead of using addition, you should probably use a “binary or” operation to merge the bit into your accumulator:

    b = b | (n << k);

or simply:

    b |= n << k;

Bug

You are not inverting the most significant zero bits.  Assuming an 8-bit word size, the binary compliment of 9 (0b00001001) should be 0b11110110, not 0b00000110.   And the compliment of that should return to the original number (0b00001001), but instead yields 0b00000001.

And, as mentioned by @Martin R, you could simply return ~num;


Your code is near perfection, if you want to "get OCD" about it you can skip all the empty lines, comments on self-explanatory methods and fields and open code blocks on the same line, for example:

 public Room_Dimension(double length, double width)
{
    super();
    this.length = length;
    this.width = width;
}

and all the rest, could be written as:

 public Room_Dimension(double length, double width){
    super();
    this.length = length;
    this.width = width;
}

to save space, so that the class is visible within the screen with no need of scrolling. Additionally, search for program layout and class interface best practices, to get insight on the subject.


I think what you need is a suffix tree: http://en.wikipedia.org/wiki/Suffix_tree. I don't really remember much about it, except that it exists and seems relevant to the problem at hand.

Style wise, I recommend spaces around operators like < and << and +=


I propose the following refactoring based on:

use of arrays to range and viceversa

though tempered by the fact that you have to deal with possible non contiguous columns range
use of fully qualified range references

to both avoid Select/Activate stuff and have full control of which range/worksheet/workbook you're dealing with
use of Option Explicit statement

to force explicit declaration of type for ALL variables used in the code

this extra work earns you back with a lot more control of what you're actually doing and saves you a lot of time in both code debugging and maintenance
robust function to return a "valid" workbook

see GetWorkBook() function

`

Option Explicit

Sub Import_NAVRec()
    Dim tempbook As Workbook
    Dim LR As Long, LC As Long, c As Long, nCols As Long
    Dim aNavRec() As Variant                            'declare NAV Rec array. it'll be an array of arrays
    Dim headers As String                               'declare the variable where you'll put headers of interest

    Set tempbook = GetWorkBook(ActiveSheet.Range("b2")) 'try setting a workbook whose path is in cell "B2" of ActiveSheet

    If tempbook Is Nothing Then Exit Sub                'exit sub if no valid workbook is returned

    headers = "|Accounting Basis|Accounting Date|Asset Currency|"   ' set your headers delimited by a "|"
    ReDim aNavRec(1 To UBound(Split(headers, "|")) - 1)             ' dim aNavRec to number of headers you want to grab columns of
    With tempbook.ActiveSheet
        LR = .Cells(.Rows.Count, "A").End(xlUp).Row                 'find last row in sourcefile column A
        LC = .Cells(1, .Columns.Count).End(xlToLeft).Column         'find last column in sourcefile headers

        For c = 1 To LC 'loop through every column
            If InStr(headers, "|" & .Cells(1, c) & "|") <> 0 Then   'if current column header is bewteen the wanted ones
                nCols = nCols + 1                                   'update the number of found columns
                aNavRec(nCols) = Application.Transpose(.Range(.Cells(1, c), .Cells(LR, c))) 'store the found column in the variant element in the current index (nCols) of the array. you have to transpose a "column" range to fit into a "horizontal" variant array
            End If
        Next c
        ReDim Preserve aNavRec(1 To nCols)              ' redim aNavRec to actual number of headers found nt to grab columns of
    End With
    tempbook.Close (False)

    Print_output Worksheets("Output").Range("a2"), aNavRec 'after closing 'tempbook' the active workbook (and worksheet) is the one we started with

End Sub

Sub Print_output(iniRng As Range, arrays() As Variant)
    Dim i As Long
    With iniRng
        For i = 1 To UBound(arrays)
            iniRng.Offset(, i - 1).Resize(UBound(arrays) + 1).Value = Application.Transpose(arrays(i)) ' you have to transpose back the array to fit it into a "column" range
        Next i
        .CurrentRegion.EntireColumn.AutoFit
    End With
End Sub

Function GetWorkBook(path As String) As Workbook
    ' returns the workbook corresponding to path
    ' checks whether a workbook with the given name and path is already open
    ' if an already open workbook has the same name but different path:
    ' -  if it is NOT the active one -> it'llbe closed and the requested one will be opened
    ' -  if it IS the active one -> no action will be taken
    '
    ' requires reference to "Microsoft Scripting RuntTime" library

    Dim fso As New FileSystemObject
    Dim f As File
    Dim fName As String

    If Not fso.GetExtensionName(path) Like "xls*" Then Exit Function 'exit if it's not a valid excel file

    If Not fso.FileExists(path) Then Exit Function 'exit if there's no such file

    Set f = fso.GetFile(path) 'get the file corresponding to the now validated path

    fName = fso.GetFileName(path)

    Set GetWorkBook = TrySetWorkbook(fName) 'check whether that workbook is already open
    If GetWorkBook Is Nothing Then 'if no...
        Set GetWorkBook = Workbooks.Open(path) '... open it!
    Else 'if yes...
        If GetWorkBook.FullName <> f.path Then '... and it has a different path from the requested workbook one ...
            ' ... then you should close the already open workbook with the same of the requested one before opening this latter
            If ActiveSheet.Parent.name = fName Then 'if the workbook to close is the active one (!)...
                MsgBox "workbook:" & vbCrLf & vbCrLf & "'" & ActiveSheet.Parent.FullName & "'" _
                       & vbCrLf & vbCrLf & "should be closed to open woorkbook:" & vbCrLf & vbCrLf & "'" & f.path _
                       & vbCrLf & vbCrLf & vbCrLf & "but the former is the active workbook, so no action will be taken", vbInformation
                Set GetWorkBook = Nothing ' set the return workbook to Nothing so as to have calling sub skip the passed path
            Else 'otherwise...
                Workbooks(fName).Close True '... close (saving changes) the already open one...
                Set GetWorkBook = Workbooks.Open(path) '<~~ ... and finally open the requested one
            End If
        End If
    End If

End Function

Function TrySetWorkbook(path As String) As Workbook
    On Error Resume Next
    Set TrySetWorkbook = Workbooks(path)
End Function


Converting partial XML (Node List) to a String

Reading the documentation for
Transformer,
where it says:

  A Transformer may be used multiple times. Parameters and output
  properties are preserved across transformations.

, I'd say that not only can the Transformer object be reused across
multiple nodes, but you should also be able to use a single
StringWriter instead of recreating it for every node; same goes for
the DOMSource actually:

private static String nodeListToString(NodeList nodes) throws TransformerException {
    DOMSource source = new DOMSource();
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    for (int i = 0; i < nodes.getLength(); ++i) {
        source.setNode(nodes.item(i));
        transformer.transform(source, result);
    }

    return writer.toString();
}

That said, I'm only guessing that this should work.

Also, the len variable is probably going to be inlined automatically
anyway, though you could check that with a disassembler just to be sure
(it wouldn't make that much of a difference I suspect).

Otherwise looks good to me; if you've tested it with all kinds of node types and the output looks good, then I'd say that should work IMHO.


BOOL values

Your outer case statements convert a value to itself. SUM(CASE WHEN type IN (1,2) THEN 1 ELSE 0 END) > 0 is TRUE or FALSE, which are equivalent to 1 and 0.

WHERE vs HAVING

WHERE will filter rows from the input, which means that you can't use an aggregate. HAVING filters after the aggregation, which means you can drop the outer query.

Unnecessary JOIN

You are only using the employee_id from employee, which is present in employee_peripheral

Resulting query

SELECT employee_id,
SUM(CASE WHEN type IN (1,2) THEN 1 ELSE 0 END) > 0 AS has_screen,
SUM(CASE WHEN type > 2 THEN 1 ELSE 0 END) > 0 AS has_keyboard
FROM employee_peripheral
GROUP BY employee_id
HAVING (SUM(CASE WHEN type IN (1,2) THEN 1 ELSE 0 END) > 0) <> (SUM(CASE WHEN type > 2 THEN 1 ELSE 0 END) > 0)


Efficient numpy cosine distance calculation

Your code does not run: there are missing import statements:

import numpy as np
import scipy.spatial.distance

Your algorithms compute different results, so some of them must be wrong!

>>> vector = np.array([1, 2, 3, 4, 5])
>>> matrix = np.array([[7, 5, 8, 1, 9], [6, 6, 4, 0, 8]])
>>> cos_matrix_multiplication(matrix, vector)
array([ 0.81818182,  0.76558762])
>>> cos_loop(matrix, vector)
[0.81818181818181823, 0.76558761870466252]
>>> cos_loop_spatial(matrix, vector)
[0.18181818181818177, 0.23441238129533748]

In cos_matrix_multiplication and cos_loop, you've forgotten to subtract the distance from 1. In what follows I have fixed these bugs.
Your graph. (i) It has a very poor "data-ink ratio": just three data points! (ii) We can't actually read off the data points in any case, only estimate them based on the length of the bars; (iii) The labels are hard to read because they are written vertically; (iv) I can't copy and paste the labels, let alone the data. A better way to present this kind of information is in a table, like the one I give below.
You hint in the text that your real problem is to do with finding nearest neighbours. It's always best to ask about your real problem rather than some proxy for it. We might be able to suggest a solution that involves a different approach. (For example, if you were using Euclidean distance rather than cosine distance, it might make sense to use scipy.spatial.KDTree. But we can't help you unless you tell us what you're really trying to do.)
Scipy includes a function scipy.spatial.distance.cdist specifically for computing pairwise distances. In your case you could call it like this:

def cos_cdist(matrix, vector):
    """
    Compute the cosine distances between each row of matrix and vector.
    """
    v = vector.reshape(1, -1)
    return scipy.spatial.distance.cdist(matrix, v, 'cosine').reshape(-1)

You don't give us your test case, so I can't confirm your findings or compare them against my own implementation. For example, how many dimensions do your points typically have? I used the following test case:

import timeit

def test():
    algorithms = (cos_loop_spatial, cos_loop, cos_matrix_multiplication,
                  cos_cdist)
    vector = np.random.rand(10)
    matrix = np.random.rand(100000, 10)
    for algorithm in algorithms:
        t = timeit.timeit(lambda:algorithm(matrix, vector), number=1)
        print("{:30s} {:f}".format(algorithm.__name__, t))

Which produces the following results:

cos_loop_spatial               8.231966
cos_loop                       7.212096
cos_matrix_multiplication      0.106005
cos_cdist                      0.019018

So scipy.spatial.distance.cdist is about five times as fast (on this test case) as cos_matrix_multiplication.


Words Counter using the revealing module pattern

function bindEvents() {
  $textArea.on('keyup', updateWordsCount);
}

// $textArea keyup callback function
function updateWordsCount() {
  var text =  $textArea.val();
  var numOfChars = text.length;
  var numOfWords = countWords(text);
  $chars.html(numOfChars);
  $words.html(numOfWords);
}

The handler is unnecessarily split from the code that binds it. It's not often you see an event handler split off from it's binding. In most cases, the handler code is very specific to the binding, it cannot be reused and therefore makes no sense splitting off. Inline the handler instead.

var $textArea = $('#textArea');
var $words = $('#words'); //a span
var $chars = $('#chars'); //a span

I would discourage the use of $ indicating that a variable is a jQuery instance. Whether it's a jQuery instance, or some other constructors instance, a variable is a variable regardless of what it's bound to.

Another problem is that this piece of code isn't reusable. The selector uses an ID. IDs are supposed to be unique. That means this code can only bind to 3 unique elements, and no more. If you want to make this word counter reusable, use a class.

var flag = true;

flag is a poorly named variable. It's not telling me what it's supposed to be, what it is for, and why it is there.

// counts words for a given string
function countWords(str){
  var cnt = 0;
  var flag = true;
  for(var i = 0; i < str.length; i++){
    if(str[i] !== " " && flag){
      flag = false;
      cnt++;
    }else if(str[i] === " "){
      flag = true;
    }
  }
  return cnt;
};

I think this is overcomplicated. A simple word count can be done by exploding the string into array by spaces, and getting the length of the resulting array. return str.split(' ').length what you are looking for.

For this simple task, a jQuery "plugin" would do. I would expect the plugin to accept an element containing your input and output elements, and a set of options asking for which elements are the input and output inside that group.

jQuery.fn.wordCounter = function(options){

  // For each found group
  return this.each(function(){

    // Look for the input and output under that group
    var input = $(options.input, this);
    var output = $(options.output, this);

    // Counter event and handler
    input.on('keyup', function(){
      output.text(input.val().split(' ').filter(text => text !== '').length);
    });

  });
};

$('.input-group').wordCounter({
  input: '.input-group__input',
  output: '.input-group__count',
});

  <input class="input-group__input">

In larger scale projects, consider using a small framework. vue.js, Ractive.js and riot.js are good candidates for quick-and-easy UI-related operations.


I believe that in addition to the stated Java -> Scala OO question, that you may also be wondering about a good way to "organize" Models/DAOs/Controllers in Play 2. So I will incorporate that in my answer.

I would have asked in a comment, but I don't seem to have the rep yet...

A few notes before we get into an answer:

fedesilvia is correct, that case classes can extend traits and/or classes.
Model classes generally should be case classes. They're a nice, easy-to-use construct that provides your "equals" method, "toString" method, and "hashcode" method. Also, many libraries have provided great mechanisms for working with case classes for a variety of purposes. Not to mention matching, immutable by default, etc...

Let's take a look at how to organize this from top to bottom.

Controllers

As you know, Play's Router sends requests in from the HTTP client to your Controller. It is my opinion that the Controllers then have 3 core responsibilities:

Deserialize the request.
Serialize the response.
Handle any errors appropriately.

Missing between responsibilities 1 and 2, is the actual "handling" of the request. For a CRUD app, this could be where your DAOs come in.

DAOs

In my application, DAOs are Objects that extend a MongoDAO trait. The trait "knows" how to interact the the database drivers (get a connection), and supplies basic utilities. For instance:

/** Basic DAO Behavior for MongoDB documents. */
trait MongoDao {
  /** Name of the MongoDB Collection. */
  protected def colName: String

  /** Returns the default database. */
  protected def db = ReactiveMongoPlugin.db

  /** The actual collection used by the DAO. */
  protected def col: JSONCollection =
    db.collection[JSONCollection](colName)

  /** Returns the first result, if any, for the given query. */
  def findOne[DOC](q: JsObject)(implicit reads: Reads[DOC]) =
    col.find(q).cursor[DOC].headOption

  ...

I also have an abstract class that extends MongoDAO called, "AssetDAO". AssetDao provides 90% to 100% of the DAO implementation for 13 of the Models in my App. Here is it's type:

/** Common DAO behavior for all Assets. */
abstract class AssetDao[A <: AssetModel]
  (override val colName: String)(implicit format: Format[A])
extends MongoDao with ModulePermissions {

The DAO implementations can look like this:

object ArchetypeDao extends AssetDao[Archetype]("archetypes")

But most of them also have a couple methods that are all their own. Usually when I need to make use of Model specific properties in a query.

Model Companion Objects

Given the libraries that I'm using (notably play.api.lib.json), I find it best to put (de-)serialization code in the Companion Objects. For instance:

object Archetype {
  /** Converts Archetype to/from its MongoDB representation */
  implicit val fmt = Json.format[Archetype]

  /** Reads that are used for both Create and Update. */
  val coreReads = (
    (__ \ "name"   ).json.pickBranch(smlReqStr) and
    (__ \ "summary").json.pickBranch(medReqStr) and

    ((__ \ "description").json.pickBranch(fullText) or emptyObj)
  ) reduce
}

As you can see, the Companion Object contains all of the information it needs to (de-)serialize the case class to/from its MongoDB representation; and to/from its "client" representation. So the DAO ends up using the Json.format and the Controller uses the JSON Transformers.

Models

In this setup, all Models are simple case classes that represent persisted data. For instance:

case class Archetype (
  _id:         BSONObjectID,
  module_id:   BSONObjectID,
  doc_meta:    DocMeta,
  name:        String,
  summary:     String,
  description: Option[String]
) extends AssetModel

And here is the AssetModel trait that Archetype implements:

/** Describes some common behavior of asset types */
trait AssetModel {
  def _id:       BSONObjectID
  def module_id: BSONObjectID
  def doc_meta:  DocMeta
}

You may have noticed earlier that Archetype.coreReads doesn't reference all the fields the model has. That's because the "AssetControllers" are taking care of the rest of the fields for every AssetModel. Implementing AssetModel here is what makes that work.

To do it again, I might have the AssetModel Companion Objects extend a trait that provides the common field (de)serialization.

Conclusion

Hopefully, this answer has provided you with:

A better understanding of using OO in Scala.
Some ideas for organizing your Play App to write DRY code.


Yes, you should prepare the statement or at least SQL escape the value of $_GET['fromUrl']. It's good practice to be paranoid about any input potentially provided by the user as it will be wrong at some point.

The wpdb-reference says:

  Briefly, though, all data in SQL queries must be SQL-escaped
  before the SQL query is executed to prevent against SQL injection
  attacks.

The prepared query would look something like this

$wpdb->get_row(
       $wpdb->prepare("SELECT * FROM `my_table` WHERE column = %s",
                      $_GET['fromUrl']),
       ARRAY_A);

which in my opinion is more readable, particularly the SQL query is easier to follow.

Furthermore, inspecting the user input may allow you provide the user better experience by creating meaningful notifications describing what has happened and how the user can cope with the inconvinience.


First of all, I will assume there is something like template <typename T> somewhere in your code. Otherwise, I doubt it would compile.

There is something you could do to improve your program: use emplace_back instead of push_back with an object construction. That way, objects will be created right in the collection (list, vector, etc...). By the way, I'll also assume that markers is a standard collection.

auto callback_factory =
    [&] (IPMarkerType start, IPMarkerType stop) -> std::function<void(IPNode<T>&)>
{
    return [&,start,stop](IPNode<T> & node){
        markers.emplace_back(node.ip, start);
        markers.emplace_back(node.ip.network_ones(node.prefix), stop);
    };
};

And, yeah, something still smells: I really wonder how and/or where you declared markers. If it's a global variable, then I think the template parameter may cause some problems.


How to increase efficiency of recursion algorithm?

Variable names. Name your variables after what they do, no exceptions.

As a sidenote, note that that you're relying on how integer division works in Java.

Having said that, you can improve the code by being explicit.
// As I've said, always name your variables and functions after
// what they are doing. Don't be afraid to use longer names,
// longer names which tell you what the class does are a good
// thing, even if they sound "funny".
public int countEights(int value) {
    // Early exit conditions are a good thing.
    if(value == 0) {
        return 0;
    }

    // We could also skip the declaration and instead return
    // the right count together with the function call. From
    // the viewpoint of the JVM it doesn't make a difference,
    // but here in the code it means that we have the logic
    // for stripping the last digit only once.
    int countedEights = 0;

    // We are testing explicitly for the mentioned "double eights",
    // this has the upside that the intent is clearly visible
    // when reading the code.
    if ((value % 100) == 88) {
        countedEights = 2;
    } else if ((value % 10) == 8) {
        countedEights = 1;
    }

    // And finally we call the function again in the return
    // statement, as it is easier to follow the recursion when
    // it is being called at the end of the function.
    return countedEights + countEights(value / 10);
}

As you can see, we can completely get rid of the nested if by being explicit about our intent.


public override bool CanExecute(object parameter) => parameter is T ? CanExecute((T)parameter) : false;

Beware of a lesser known gotcha. This may not work as expected for parameter that's not "really" a T (it's not in Ts inheritance tree), only has an explicit cast operator defined allowing it to be casted to T.

In that case while (T) parameter would return a T instance,  CanExecute won't even be called because your is check would prevent this from happening.

Other than that, I'd have some remarks related to naming and code style (rather subjective, so treat them as suggestions or food for thought more than claims your code is incorrect)

public interface IGenericCommand<T> : ICommand

There's no use in putting "generic" in the name. Any C# programmer knows that <T> indicates generics by itself. Case in point: in .NET we've got IEnumerable and IEnumerable<T> - not IGenericEnumerable<T>. (So "drop the the" ;) )

/// <typeparam name="T"></typeparam>

/// <param name="parameter"></param>
/// <returns></returns>

In my opinion such empty tags are of no use, all they do is clutter the codebase.

private readonly Func<T, bool> _canExecuteMethod;
private readonly Action<T> _executeMethod;

It's a matter of taste, but here I would ditch the "Method" suffix, as these aren't necessarily "methods". Note that you didn't name the class MethodCommand. Why not just _canExecute and _onExecute?

public bool CanExecute(T parameter) => _canExecuteMethod == null || _canExecuteMethod.Invoke(parameter);

Since you're using the null safety operator already, this could be simplified to _canExecuteMethod?.Invoke(parameter) ?? true.


Structuring code to do URL routing for Node.js

Are you intending to reuse the route, handleAuth, and handleRequestData functions? They could be "private" to the Client constructor function:

function Client(req, res) {
    function route() {
        //...
    }

    function handleAuth() {
        //...
    }

    function handleRequestData() {
        //...
    }

    route();
    handleRoute();
    handleRequestData();
}

See that I didn't set req and res as this members. I don't know if this is mandatory in your case. Also, this is just the beginning of what could be done; as stated in the comments to this answer, every time a new Client is created, new instances of the private functions are created as well, wasting resources.

A more sophisticated approach could define Client using a self-invoking function expression:

var Client = (function() {
    function route(req, res) {
        //...
    }

    function handleAuth(req, res) {
        //...
    }

    function handleRequestData(req, res) {
        //...
    }

    // This is the constructor function:
    return function(req, res) {
        route(req, res);
        handleRoute(req, res);
        handleRequestData(req, res);
    }
})();

Here, Client is defined as the product of the function expression enclosed in the outermost parenthesis. The function expression returns the constructor function, which has access to the closure functions route, handleRoute, and handleRequestData. Note that each of these functions is defined with req and res parameters. This way, they behave like static private functions, and you can code and use them regardless of what's referenced by this.

About self = this: it's known that JavaScript may be very confusing about the this keyword. Some information here. So, sometimes it's convenient to assign this to a closure variable named like self or me. It should not be done blindly though... as anything after all.


Building object from unusually custom object

notificationSettingsCustomPair.stream()
                    .anyMatch(cp-> cp.getKey().equals(something)) ?
                    (Boolean) notificationSettingsCustomPair.stream().filter(cp  -> cp.getKey().equals(something)).collect(toList()).get(0).getValue() : null

can be replaced by

notificationSettingsCustomPair.stream().filter(cp  -> cp.getKey().equals(something)).findFirst().map(v -> v.getValue()).orElse(null)

It's now only streamed once.

Please note that you use your list like a Set which I find strange, you should consider looking at Set specificities.


It appears that you're using the same expressions for the GroupCode and GroupDescription columns in the GROUP BY clause.  That's asking for trouble later on if someone needs to modify either expression, especially given their size.  Instead, use a subquery:

SELECT
    GroupCode,
    GroupDescription,
    -- etc
FROM
    (
        SELECT
            CASE /* etc */ END AS GroupCode,
            CASE /* etc */ END AS GroupDescription,
            -- etc
        FROM
            -- etc
        WHERE
            -- etc
    ) AS dummy
GROUP BY
    GroupCode,
    GroupDescription
ORDER BY
    GroupCode,
    GroupDescription

EDIT:

There may be some other opportunities to use subqueries to reduce duplication of expressions.  For example, the expression for the column AmountX is also used in the Margin calculation.


Am I risking a deadlock in this manner of re-queueing up events?

Why are you requeueing the instance instead of completing the operation...... ? Just asking...

If you really have to reque the instance, and if there is no other locking happening around the code you have shown, then there should be no problems with deadlocks.

Once you have taken the instance from the queue, your lock on the queue is relinqished. There is nothing you can do at this point to deadlock against anything else.

When you requeue the task, it is not going to deadlock either because it is not currently locking the queue.

So, you are fine.... technically.

Your code is a little awkard though. Why do you have part of your logic outside the try/catch? It would be neater if you put it inside the try/catch.

Also, your handling of InterruptedException is not great..... The InterruptedException is a real PITA, but you have to just deal with it. The minimum you can/should do is:

Thread.currentThread().interrupt();


Given a room number, find the floor on which the room lies

When presented with problems that require and input value set, and an output value set, it's always best to express the problem as a function. In your case, the problem is: "Given an input room number, what floor is it on?"

This type of question can then be expressed as a single function:

public static int whichFloor(int room) {
    ....
}

That function is the result of a process called "function extraction", taking a piece of logic, and extracting just that piece in to its own function.

This makes the code logic more visible, and it also helps you to organize your thoughts. It also makes some logic expression more simple (early return values).

So, taking your code in to a function, you get:

System.out.println(whichFloor(37));

And, now we implement whichFloor as:

public static int whichFloor(int queryRoom) {
    int totalFloor = 6;

    int currentRm = 0;
    int floorInQuestion = 1; // staring floor

    while (floorInQuestion != totalFloor) {
        if (floorInQuestion % 2 != 0) {
            currentRm = currentRm + 5;
        } else {
            currentRm = currentRm + 10;
        }
        if (queryRoom <= currentRm) {
            return floorInQuestion;
        }
        floorInQuestion++;
    }
    return -1;
}

There are some changes in that logic. Specifically, I have:

Added {...} braces on the last condition...
... which is now a return statement, and not a break
returns -1 if there's no matching floor.

Now, that while-statement should be a for loop:

public static int whichFloor(int queryRoom) {
    int totalFloor = 6;
    int currentRm = 0;

    for (int floorInQuestion = 1; floorInQuestion != totalFloor, floorInQuestion++) {
        if (floorInQuestion % 2 != 0) {
            currentRm = currentRm + 5;
        } else {
            currentRm = currentRm + 10;
        }
        if (queryRoom <= currentRm) {
            return floorInQuestion;
        }
    }
    return -1;
}

Now, as a looping system, that's how you should have presented your solution.

Note that your logic is clear enough, your variables are well named, and the logic looks sound enough. On the whole, your answer is good, and just needed some tweaks.

... but... is there a better solution that does not use looping?

Consider the pattern in the rooms/floors...

Odd floors have 5 rooms, even floors have 10 rooms. Can we exploit this better? Well, yes, we can treat the floors in pairs and have 15 rooms per pair... and then figure out whether it's in the first of the pair, or the second. Note that using division and remainder operations works best as a 0-based system, not a 1-based system like the input values are in, so we "map" each room to be 1 less, and each floor too, so we treat room 1 as if it was room 0, and floor 1 as if it was floor 0, and then shift the results back afterwards too. I have named zero-based variables with the prefix zero...

public static int whichFloor(int queryRoom) {
    int zeroRoom = queryRoom - 1;    // convert to zero-based room
    int zeroPair = zeroRoom / 15;    // get which 15-room floor-pair the room is in
    int zeroOffset = zeroRoom % 15;  // get which room in the pair
    int zeroFloor = zeroPair * 2;    // convert the pairs back to floors.
    if (zeroOffset >= 5) {
        // the room in the pair is in the upper floor of the pair.
        zeroFloor += 1;
    }

    int resultFloor = zeroFloor + 1; // convert back to one-based system.
    return resultFloor;
}


Avoid using namespace std.

Keep your lines shorter.  Having to constantly scroll back and forth to read lines is unpleasant.  Most of your comments should be on one (or more) lines right before the statement being commented on.  Also, avoid obvious things in comments (like "resets i to use in the next loop.").

Declare variables as close as possible to their first use.

Since isogram_check is a bool, you can test it with !isogram_check instead of isogram_check == false.

With a slight change in algorithm (searching characters before the ith one), your two while loops can be combined into one. Although there are other ways to do this that could be better (for some definition of "better"), your implementation is a quick first pass that works well for short strings (but less well as the strings get longer).


Policy Naming and Behaviour
Your SingleSuccessPolicy name is not a good one. What you actually have here is a MaximumFailuresPolicy.
To effectively create a "real" SingleSuccessPolicy, you'd need to evaluate the final result of your foreach loop. But that is simply impossible in the catch-block.
The problem I see with your code is, that your SingleSuccessPolicy is required to be correctly initialized with new SingleSuccessPolicy(compData.size()-1);. As soon as a differnt SingleSuccessPolicy is passed in, the behaviour is no more the desired one.
You might consider creating the policy inside the GroupComponent constructor. Then you can make sure that the MaximumFailuresPolicy will always behave as a SingleSuccessPolicy, but that would change a whole lot of your structure.
This assumes your compData are immutable after construction, which in turn would IMO warrant a factory / builder pattern instead of what you have here.
What you want to do is yours to decide, but the current way is IMO too unreliable, especially when the ExceptionPolicy depends on what data you are handling. That is not the point of an ExceptionPolicy.
Nitpicks:
Your indentation is not conform to java-standards. Oracle consistently uses an indentation of 4 spaces (or one tab) for blocks.
From method to for-loop, you have 3 spaces, from for-loop to try-catch the same, and from try-catch to statements, you have 2 spaces.
All three alternatives violate conventions, but above all, you're inconsistent!
Additionally I suggest you mark your arguments as final, whereever possible.


Is there an easier way to use Rx's GroupBy operator?

You could use also use a counter provider per grouping observable, in the form of zipping a large stream of integers, like so:

static void Main(string[] args)
{
    var input = GetConsoleLines().ToObservable().TakeWhile(line => !string.IsNullOrEmpty(line));
    input.GroupBy(word => word)
         .SelectMany(grouping => grouping.Zip(Observable.Range(1, int.MaxValue), (s, i) => new Tuple<string, int>(s, i)))
         .Subscribe(r => Console.WriteLine($"you typed {r.Item1} {r.Item2} times"));
}

public static IEnumerable<string> GetConsoleLines()
{
    while(true)
        yield return Console.ReadLine();
}


The better alternative is the second alternative, because the first alternative may only write the data to disk when the Garbage Collector clears up the stream. The file will remain open for all that time too, leading to long holds on file handles in the OS.

i.e. the first one may produce unexpected results.

The second alternative is an improvement, but you should consider using a "try with resources" block, which has been around for the past 6 years in Java 7 and 8... The try-with-resources is a far more elegant way to approach this problem, and it makes the exception handling "trivial"...

public static void storePreferences() {
    File prefs = new File(new File(ReleaseInfo.getAppFolder()), SETTINGSFILENAME);
    try (OutputStream fos = new FileOutputStream(prefs)) {
        Preferences.userRoot().exportSubtree(fos);
    } catch (IOException | BackingStoreException e) {
        e.printStackTrace();
    }
}

Note that I used the more convenient 2-argument File constructor instead of the constant File.separator

Further, I would suggest getting a better-performing new NIO2 functions, and wrap the resulting OutputStream with a buffer:

public static void storePreferences() {
    Path prefs = Paths.get(ReleaseInfo.getAppFolder(), SETTINGSFILENAME);
    try (OutputStream fos = new BufferedOutputStream(Files.newOutputStream(prefs))) {
        Preferences.userRoot().exportSubtree(fos);
    } catch (IOException | BackingStoreException e) {
        e.printStackTrace();
    }
}


are these functions in bad practice?

I would say not, as long as the original functions they are wrapping have the same function signature to allow their replacement.

  is there anything particularly wrong with the code I have written?

Allocating 0 bytes may return NULL, which does not indicate Out-of-memory.
Same for calloc(), realloc().

void* memory = malloc(size);
// if(memory == NULL){
if(memory == NULL && size > 0){

No point in calling free(memory) after if(memory == NULL)

if(memory == NULL){
  //  free(memory);

With eprintf(...), consider passing __FUNC__, __LINE__ of the error source to aid in debugging.  Or at least create unique error messages.

void* safe_malloc(size_t size){
   runtime_error("failed to malloc memory.");

void* safe_calloc(size_t num, size_t size){
    runtime_error("failed to calloc memory.");

In a couple places, use const to allow wider application of the functions that are not changing the referenced data.

// void make_error(char* type, char* message){
void make_error(const char* type, const char* message){

I am not a fan of your name-space choices for error.h which includes eprintf,
 STATUS_OKAY, STATUS_GENERIC_ERROR, make_error, ...  If I say these used in other ..c files how would I be guided back to error.h/error.c as their origin?  Although a bit verbose, I prefer error_printf, ERROR_STATUS_GENERIC,...

Minor: #include <stdio.h> need not be in safe_mem.h nor #include <stdlib.h> in error.h.  error.c should have #include <stdlib.h> as it calls exit().  error.c should not rely on error.h including that.  Similar issues for safe_mem.c

From a design standpoint, I would also include void safe_free(void *) as the functionality of these safe functions may expand and require that even if it present does nothing.  It makes safe_...() symmetric.


Displaying items of a list in a text window

Make only one textWindow.append() operation and consider using StringBuilder, to construct string to append.

public void listOpen() {
    ArrayList<String> open = main.getOpenable();
    StringBuilder appendBuilder = new StringBuilder();
    for(int i = 0; i < open.size(); i++) {
        String value = open.get(i);
        appendBuilder.append(value).append("\n");
        error.setScroll();
    }
    textWindow.append(appendBuilder.toString());
}


You should avoid the natural tendency in Scala to make everything a one-liner.  It hinders the readability and maintainability of the code.  I don't think it's much of a problem in the first two, but the third and fourth solutions seem a bit cryptic.  In most cases the compiler will collapse your more verbose collection of defs down to the same result as your one-liner, but the multiple defs are easier to grok for humans.

I can simplify Problem4 with filter and flatten to reduce the lists without resorting to use of '0' as a placeholder for "not to be considered".

println( (100 to 999).map(x=>(x to 999).map(_*x).filter(isPalindrome)).flatten.max)

But it still reads better to me if not so composed.

For example:

  def products = (100 to 999).map(x=>(x to 999).map(_*x)).flatten
  def palProducts = products.filter(isPalindrome)
  println( palProducts.max )

Even that combines too much in products, I think.  For-comprehension can make it more readable even without separate defs:

  def palProducts =
    for { a <- (100 to 999)
          b <- (  a to 999)
          c = a*b
          if (isPalindrome(c)) } yield c

  println( palProducts.max )

Also, you should add @tailrec annotations to code which is reliant on being tail-recursive, only to prevent them becoming non-tailrec through some accidental change in the future.  This is a minor quibble in these small examples, but it will become more important in larger projects.


Performing a procedure for each form edit

It looks to me that you could use a method that returns the appropriate string.  Something like the following, which follows the pattern in your code:

static string GetEdit(string txt)
{
    string rgxExpr = @"(\w+)\s([\w\s]*)"; // Pega primeiro nome
    string rgxExpr2 = @"\b(\w{1})"; // Abreviação
    Match match1 = Regex.Match(txt, rgxExpr);
    Match match2 = Regex.Match(match1.Groups[1].ToString(), rgxExpr2);
    return match1.Groups[2].ToString().ToUpper() + ", " + match2.Groups[1].ToString().ToUpper();
}

You could do something similar with the other duplicated code by using a list of strings that correspond to a list of textboxes. allowing you to add or delete as needed.


Your code looks good and will work well. I have made some minor improvements to improve readability and reduce redundancy.
export async function retry(fn, retries, delayMs, onFailedAttempt) {
  let attempt = 0;

  while (true) {
    try {
      return await fn();
    } catch (error) {
      if (onFailedAttempt) {
        onFailedAttempt(error, attempt, retries, delayMs);
      }

      if (window.verbose) {
        console.debug(`Trial ${attempt + 1}/${retries} failed. Retrying in ${delayMs}ms...`);
      }

      if (attempt++ < retries) {
        await delay(delayMs);
      } else {
        throw error;
      }
    }
  }
}

Improvements:

onFailedAttempt = null in the function signature is redundant. If onFailedAttempt is not passed as an argument, its value will be undefined. Which will work equally well in your case when checking its value.

Moving await delay(delayMS) in catch block to keep related code together. As we only delay when an error occurs and if this was not the last attempt.

const res = await fn(), res is not needed here. You can simply do return await fn().

We could use the do...while here, but we'll have to check the attempt < retries condition two times in that situation. By using while (true), we only have to check it once.

We can also remove the lastError variable. If we get an error and this was the last attempt, we simply throw error.