Dotty 0.19 (Scala 3) features: contextual abstractions

First, a minor thing here:

def (me: Me) send[Receiver, OutMsg] (receiver: Receiver, msg: OutMsg) (given Entity[Receiver, OutMsg], Entity[Me, InMsg]): Unit

The second given parameter is actually redundant - it's literally the same type as  this, and with contextual parameters, there shouldn't be any other instance.

In fact, implementation of send in Person shows that you can have a default impl:

def (me: Me) send[Receiver, OutMsg] (receiver: Receiver, msg: OutMsg) (given Entity[Receiver, OutMsg]): Unit =
  receiver.receive(me, msg)(given this)

Next, something more subtle:

def (me: Me) receive[Sender, ReplyMsg] (sender: Sender, msg: InMsg) (given Entity[Sender, ReplyMsg]): Unit

Whoever is implementing this will have to support any ReplyMsg, and therefore won't be able to create one (without breaking type system by casting or nulls). Try implementing it in a way that sends something back - you won't be able to make a call to send compile with normal code. If it's desirable, you can simplify the signature using existentials:

def (me: Me) receive[Sender] (sender: Sender, msg: InMsg) (given Entity[Sender, ?]): Unit

But I think it's not, as you wanted to reply to things. You'll have to work out a way to make it work - the simplest one being having 3 parameters - Entity[Me, In, Out] and accepting something that has Me[Other, Out, In].


Your major performance issue is almost certainly the way you perform your output. This is a common problem in how online judges evaluate performance.... they assume output time is part of the algorithmic solve-time.
Output
When programs output data to the console it is seldom a performance critical aspect of code. So, why should that code be lightning-fast when the console redraws are slow. In other words, Java's System.out.print* methods are not designed to be as fast as some other languages. Specifically, the print*() methods are synchronized so that only one thread can print at a time. They also incur a fair amount of overhead to own, manage, and release the system resources attached to the console. Each time you call print*(...) you repeat a lot of this work.
The bottom line is that you should call these methods just once.
    StringBuilder sb = new StringBuilder();
    for (m=0; m < size; m++) {
        if(m > 0) {
            sb.append(" ");
        }
        sb.append(list.get(m));
    }
    System.out.println(sb);

Put all the data in to a StringBuilder, and then print it once.
Other things
In addition, you code would benefit from using a number of more convenient mechanisms.... like whitespace and braces.
Your code is suffocating, it has no breathing room. Consider:

    String[] numbers = line5.split(" ");
    for(int z=0;z<N;z++) list.add(Long.parseLong(numbers[z]));
    String line2 = br.readLine();

which should be:
    String[] numbers = line5.split(" ");
    for(int z=0; z < N; z++) {
        list.add(Long.parseLong(numbers[z]));
    }
    String line2 = br.readLine();

Similarly, in other places you have no whitespace or braces on conde blocks or around operators.
Additionally, your variable names are irritating, and inconvenient. You have two variables called "m", both M and m.
Finally, if you put your code in to more methods, it will give the Java compiler a chance to optimize the code when it compiles it. Java's basic using of performance compilation is a "method", since you only have one method, and since it is only called once (the main method), your logic is never compiled and optimized properly.


Pseudo-random number generator & password generator

Welcome to Rust, and welcome to Code Review!
rustfmt & clippy
Always run cargo fmt and cargo clippy first.  cargo fmt
formats your code according to the official Rust Style Guide, and
cargo clippy detects common mistakes and provides feedback on
improving your code (none in this case).
main.rs
The biggest problem with the main function is its structure.
Logically, the job of main is to:

read the length of the password;

read the excluded characters; and

output the generated password.

You spent so much code on the first step that it is hard to recognize
at a glance without being familiar with input loops.  For readability,
it is preferable to extract all of this into a function:
fn input_length() -> usize {
    loop {
        eprintln!("Enter the length of password: ");

        let mut length = String::new();
        io::stdin()
            .read_line(&mut length)
            .expect("cannot read line");

        match length.trim().parse() {
            Ok(length) => return length,
            Err(_) => eprintln!("Error: invalid length\n"),
        }
    }
}

Lengths are usually represented by usize in Rust to avoid type
casts, instead of u32.
It is recommended to define variables as close to their usage as
possible.
Personally, I would change all occurrences of println! to
eprintln! expect the one that actually prints the password, so that
the program can be easily used in an automated script by reading
stdout.
Moving on, we see that there is no need to extract all characters in
exclude, a String, into excluded, a Vec<char> (the naming can
be improved, by the way).  A String encodes the characters in UTF-8,
which is variable-length, so ASCII characters take up only 1 byte
each, whereas a sequence of chars always stores each character as 4
bytes.  Moreover, UTF-8 is specially constructed so that searching
requires only a linear scan and no computation of character
boundaries, so there is no performance gain.
password.rs
It shouldn't be the job of the password module to expose a constant
array containing ASCII characters.  A better name for ASCII may be
ALLOWED_CHARS.
The function rand_pass will often be called with the password::
prefix, so it is not necessary to repeat this information.  I would
name it generate.
Since the function does not consume excluded, take a &[char], or
better, &str parameter.  See Why is it discouraged to accept a
reference to a String (&String), Vec (&Vec), or Box (&Box)
as a function argument?.
The function can be rewritten in a more logically straightforward
manner using iterators:
use std::iter;

pub fn generate(length: usize, excluded: &str) -> String {
    iter::repeat_with(generate_char)
        .filter(|c| !excluded.contains(&c))
        .take(length)
        .collect()
}

where generate_char is a function Fn() -> char that generates an
individual random character in the password, omitted for simplicity.
The intent is now clearer.
xorshift.rs
A better name for the module might be time_rng.
use declarations can be condensed:
use std::time::{SystemTime, UNIX_EPOCH};

A mutable variable is more readable to me here:
let mut x = seed;
x ^= (seed << 13);
x ^= (x >> 17);
x ^= (x << 5);
x % len

It is best to not count on the reader knowing the operator precedence
here.


Advice 1

I would not abuse the user with the question whether he wants to continue; just have a command (say, quit) for quitting the game while still guessing.

Advice 2

randomnumberguessinggame

The Python way is random_number_guessing_game.

Advice 3

You don't have to use parentheses in the branch and loop conditionals.

Summa summarum

I had this in mind:

import random

def main():
    actual_number = random.randrange(0, 1000)
    while True:
        guess = input("Enter your guess: ")

        if guess.strip().lower() == "quit":
            print("Bye!")
            return

        try:
            guess_number = int(guess)
        except ValueError:
            print(guess, "is not an integer!")
            continue

        if guess_number < actual_number:
            print("Your guess is too small.")
        elif guess_number > actual_number:
            print("Your guess is too large.")
        else:
            print(guess_number, "Excellent!")
            return

main()

Hope that helps.


Printing all the permutations of a string in alphabetical order-ver1.1

Nothing I would bother about complaing about in real code review.

But for argument's sake:

Pass by const ref

Rather than passing by value. It usually means that an extra copy will be removed. In this case that's not true but I think its a good habit.

void readInputFile( std::string const& filename )

No need to return 0 from main

If main() can not return anything else. Then I don't bother with a return statement in main (it's special). The compiler adds a return 0 if no return is provided for main.

Personally I use this (that face that I have not added a return) to indicate that the application has no real failure state.


It is not clear (since you don't show the definition of card) however if all you are doing is creating properties for each public property of card then try this:

JObject arrayEntry = JObject.FromObject(card);

You might need a few more lines to add or remove additional properties based on your business rules. But this would cut down on a lot of the clutter.


BestApproximationDiv2 problem in Haskell

Hmmm, not much ideas, only syntax:

showResult :: (Int, Int, Int) -> String
showResult (a, b, x) = concat [show a, "/", show b, " has ", show x, " exact digits"]

preciseDivision :: Int -> Int -> [Int]
preciseDivision a b = let (d,r) = divMod (10*a) b in d : preciseDivision r b

...where toResult ds p b = fmap (\a -> (a, b, 1 + length ds)) $ bestNumerator ds p b


Implementing an open/close function in Prolog

Always try hard to avoid assert/1 and retract/1: Using these predicates makes it impossible to reason about your other predicates in isolation, and therefore make debugging and extending your code much harder.

In this case, there is a clear declarative solution:

Represent the state of all doors as a Prolog term, and thread this state through all predicates that need it. For example, a simple representation could be:

[door_state(door1, open), door_state(door2, closed), door_state(door3, open)]

You can thread such a state through as follows:

state0_action_state(S0, Action, S) :-
    ...

This predicate relates an initital state to the next state, depending on Action. Given the example representation above, an action like close(door1) would result in the next state:

[door_state(door1, closed), door_state(door2, closed), door_state(door3, open)]

Thus, your predicates can all be tested in isolation, and do not depend on any implicit state.


SemaphoreSlim extension method for safely handling cancellation and disposal

Review

Is there a better way to safely manage the cancellation and disposal of SemaphoreSlim instances?

You've made a pattern to safely manage completing / aborting a task that is acquiring or has acquired a lock on a semaphore, not to safely manage the cancellation and disposal of SemaphoreSlim instances.

You should only release the semaphore if you are sure you have acquired a lock. So take await semaphore.WaitAsync(cancellationToken); out the try block (as suggested in the comments).

You should also provide overloads or equivalent checks that return Task<T> and/or accept a CancellationToken as argument for the task.

In your exception handlers you might get false negatives, in that it's possible an OperationCanceledException or ObjectDisposedException was raised while condition cancellationToken.IsCancellationRequested was met, but coming from a different source than the cancellationToken. I don't know whether this is a big issue, since cancellation was requested anyway. But you should definately document in which scenarios exceptions could be propagated to the consumer.

Rather than the catch - if - throw blocks, you could use catch when (condition) blocks. For instance, catch (OperationCanceledException ex) when (cancellationToken == ex.CancellationToken). This is more compact, doesn't require you rethrow yourself and allows you to focus on silently capturing these exceptions on certain conditions. You might want to log something on such errors.

I'm not convinced this extension method should take the semaphore as source object. To me, the semaphore is more of a utility used to execute these tasks. Maybe a static Helper class would have been the better choice.


It is not apparent from the function name convrtisbn10 what the
function does. Does is convert from or to ISBN-10, and from or to what?
And why does a conversion function not return anything?
You are calling getBookInfo(completeISBN) at the end of the function:
Whatever that is, it should not be part of the conversion.

The validity of the input string is not verified. If the input is too
short or too long, the result will be nonsense. If the input contains
non-digits, the function will crash.

A better function definition might be

func convertToISBN13(isbn10: String) -> String?

where the argument name indicates that is is a ISBN-10 and the function
name indicates that it is converted to a ISBN-13. The return value
is an optional, so that we can return nil for invalid input.
(An alternative would be to throw an error for invalid input.)

The type annotation in

var checkSum: Int = 0

is not necessary, also variables should be declared at the narrowest
scope where they are needed.

Setting an initial value for

var completeISBN = ""

hides an error in your program:

if (10 - remander) == 10 {
    checkSum = 0
} else {
    checkSum = 10 - remander
    completeISBN = result + "\(checkSum)"
}

In the first case the checksum is not appended to the ISBN.
The compiler does not notice that because completeISBN has a
defined value.

The string interpolation in

let newISBN = "978" + "\(isbn)"

is not necessary because isbn is already a string:

let newISBN = "978" + isbn

The variables

var oddSum = 0, evenSum = 0

are not needed, all calculations can update  checkSum directly.

It is not necessary to process the characters in reverse order.
Just process them starting with the first one (and use multiplier 3
for odd indices).

As said above,

    let digit = Int(String(s))!

would abort the program execution if s is not a number, this
should be checked.

I would move the calculation of the ISBN-13 checksum to
a separate function, which can then be used independently to
calculate or verify checksums.

Putting all this together, the code could look like this:

func checksumISBN13(isbn13: String) -> Int? {
    var checksum = 0
    for (position, char) in isbn13.characters.enumerated() {
        guard let digit = Int(String(char)) else {
            return nil
        }
        if position % 2 == 0 {
            checksum += digit
        } else {
            checksum += 3 * digit
        }
    }
    let remainder = checksum % 10
    if remainder == 0 {
        return 0
    } else {
        return 10 - remainder
    }
}

func convertToISBN13(isbn10: String) -> String? {

    guard isbn10.characters.count == 10 else {
        return nil
    }
    let isbn13 = "978" + String(isbn10.characters.dropLast())
    guard let checksum = checksumISBN13(isbn13: isbn13) else {
        return nil
    }
    return isbn13 + String(checksum)
}

Finally, note that ISBNs are usually printed in groups with a separator
(e.g. "978-3-86680-192-9"), so another suggestion is to

tolerate (not require) separator characters in the input string, and
create the output string in the grouped format.

A more universal approach would be to define a ISBN type which
can be initialized from both ISBN-10 and ISBN-13 strings (with
or without checksums). Just to give you an idea:

public struct ISBN: CustomStringConvertible {
    private let digits: [Int] // 13 digits

    public init?(isbn13: String) {
        // Verify that `isbn13` has 12 or 13 characters (ignoring separators)
        // Fill `digits`.
        // If 12 digits: append checksum.
        // If 13 digits: verify checksum.
    }

    public init?(isbn10: String) {
        // Verify that `isbn10` has 9 or 10 characters (ignoring separators)
        // Remove last character (checksum) if present.
        self.init(isbn13: "978" + isbn10)
    }

    var description: String {
        // Create and return formatted string description
    }
}


Do not use using namespace std. Read
this
Instead of using "magic numbers" in your program. Use symbolic
constants. CARBON_AMU and HYDROGEN_AMU should be ints.

const int CARBON_AMU= 12;
const int HYDROGEN_AMU = 1;
const double AVOGADRO = 6.02214141070409084099072e23;

Utilize functions in your program, instead of initializing a
variable with an expression:

long formulaWeight(int carbonAtoms, int hydrogenAtoms){
    return((carbonAtoms * CARBON_AMU) + (hydrogenAtoms * HYDROGEN_AMU));
}

double numMolecules(float mass, long formulaWeight)
{
    return((mass / formulaWeight) * AVOGADRO);
}

(e.g. 10.5 2 6): " << flush;

I don't see any advantage in using std::flush. You can remove it.
Fix your indentation. This is much easier to read:

cout << mass << " grams of hydrocarbon\nwith "
     << carbonAtoms << " carbon atom(s) and "
     << hydrogenAtoms << " hydrogen atom(s)\ncontains "
     << molecules << " molecules" << endl;


Getting partition boundaries in sorted integer array using only equalTo operator

In general single letter variables are okay, but here short names like first and last would be more readable.

Also java has a very strong convention of always using braces {}, and an indentation of 4 spaces. (Historically C/C++ had normally 3, and one whished less nesting of code due to the "superior" quality of the new language.)

List as interface is more generic than ArrayList, so do not overspecify, be too restrictive.

Using an exclusive upperbound is often done in computer science, and indeed in the java APIs themselve. Here it would mean having partions [f, l> like [a, b>, [b, c>, [c, d>, [d, e>. So at the end of the range searching loop f = l;.

   public void printPartitionBoundaries(List<Integer> array)
   {
      int f = 0;
      int l = array.size(); // Upperbound exclusive
      while (f < l) {
         int cp = array.get(f);

of (old first) is a leftover.

The loop with done: done could be removed, a while (true) would
work as well. Hence use the first if-condition as while-condition.

Also m was calculated too early.

Also == false and == true should really not be seen.

The nested ifs can be simplified.

Mind that the condition treats two cases of 1 element and 0 elements. Simpler would be while (f < l).

         while ((l-f) > 1)
         {
            int m = (f + l)/2;
            if (!array.get(f).equals(array.get(l))
                   && !array.get(f).equals(array.get(m))) {
               l = m;
            } else {
               f = m;
            }
         }

I wonder about the correctness; somehow one expects f = m + 1; to have a loop variant (l-f) diminishing every step.

The following if-statement on l == array.size() should become:

         System.out.println("Value " + cp + " is till " + (l-1) + " index");

Check, maybe the while-condition should become > 0, and extra step more.

         f = l;
         l =  array.size();
      }
   }

To verify the correctness I leave up to you yourself.

Resulting code:

   public void printPartitionBoundaries(List<Integer> array)
   {
      int f = 0;
      int l = array.size(); // Upperbound exclusive
      while (f < l) { // f != l
         int cp = array.get(f);
         while ((l-f) > 1) // maybe better f != l too
         {
            int m = (f + l)/2;
            if (!array.get(f).equals(array.get(l))
                   && !array.get(f).equals(array.get(m))) {
               l = m;
            } else {
               f = m;
            }
         }
         System.out.println("Value " + cp + " is till " + (l-1) + " index");
         f = l;
         l =  array.size();
      }
   }


Formatting mm:ss to string with Javascript

I made a few changes to the function that I think improve readability.  By using parseInt() on the seconds, I eliminated the need to later set the secNum from 01 to 1.  Since we no longer need to change that, the minStr and secStr can be set with a ternary operator. I also used destructuring to clean up the splitting of the time.

To make it less error prone, you'd also want to make sure to do some sanity checks on the input, as mentioned in the comments.

All told, it ended up looking like this:

// Tests
console.log(formatTime('1:00'))
console.log(formatTime('1:01'))
console.log(formatTime('1:30'))
console.log(formatTime('0:30'))
console.log(formatTime('bad data'))

function formatTime(formattedTime) {
    // Set up minutes and seconds
    const [match, minNum, secNum] = formattedTime.match(/(\d+):(\d+)/) || [];

    // Make sure we're getting the data in correct
    if(!match) return false;

    // Get the correct minutes and seconds strings
    let minStr = (minNum === '1') ? 'minute' : 'minutes'
    let secStr = (parseInt(secNum) === 1) ? 'second' : 'seconds'

    // Return the formatted time
    if (parseInt(minNum) === 0) {
        return `${secNum} ${secStr}`;
    } else if (parseInt(secNum) === 0) {
        return `${minNum} ${minStr}`;
    } else {
        return `${minNum} ${minStr} ${parseInt(secNum)} ${secStr}`;
    }
}

This is making use of some ES6 additions, so if you want good browser support you'll need to make sure to run this through Babel.


GetCommonBaseClass: Readabiliy and Functionality

I think that code A is quite a lot simpler, so it's also more readable. It's quite clear what GetCommonBaseClass(Type a, Type b) is supposed to do and GetCommonBaseClass(params Type[] types) is also quite straightforward.
On the other hand, CommonBaseClass(params Type[] types) in Code B is much more complicated, it's hard to see what's actually going on in all that code.

Also, in code A, GetCommonBaseClass(params Type[] types) could be simplified even more by using something like types.Aggregate(GetCommonBaseClass).

Regarding the edge cases, I think that, null inputs should cause an ArgumentNullException to be thrown. (Or not, if null is really a valid value.) With interfaces, I think the correct behavior depends on your requirements. If you don't know, I think the safest choice is to throw an exception. It's trivial to allow interfaces later on, if that's needed. On the other hand, adding a restriction could cause a issues with older code that uses your method.


Reversing a linked list by iteration and recursion

Code Comments:
curr = malloc(sizeof(Node));

malloc() returns void* thus you need to cast it before assignment.
curr = (Node*) malloc(sizeof(Node));

Most (all I have seen) coding standards mention not to use this:
Node * head, * curr;
head = NULL;

I agree with them as it just makes things hard to read (thus maintain). So one variable per line. And initialize on declaration (where appropriate).
Node  *head = NULL;
Node  *curr;

OK. The next one is arguable (so feel free to use best judgement).
Personally I find that hard to read:
 if (!head->next)

I think it would be easier to read as:
if (head->next == NULL)

But surprisingly I normally I prefer using the ! when the object is a pointer (or bool). I think in this case it is because it is combined with testing a nested member of a structure it just does not look correct (but as I said it is an arguable case).
Edge Case
What happens if the list is empty?
Node * reverse_list(Node * head) {

  if (!head->next) //only one elem
    return head;

You have chosen the wrong edge case.
The one you should be checking is checking for NULL. A list of one node is no different than a list of many. The edge case with pointers is nearly always the NULL case.
Algorithm
Iterative
The code before your while loop looks like the code inside the while loop. This sort of suggests you can replace it with a do-while loop. Thus your iterative code should look more like this:
Node* reverse(Node* list)
{
    if (list == NULL)
    {
        return NULL;
    }

    Node*   last    = NULL;
    do
    {
        Node*   next    = list->next;
        list->next      = last;
        last            = list;
        list            = next;
    }
    while(list != NULL);

    return last;
}

Recursive
Converting a loop into recursion requires an extra function to cope with the extra variable used for last. So the main recursion looks like this (it just calls the actually recursive function setting up the last parameter). You should have this wrapper function to help users of the code from calling the recursive part of the function incorrectly.
Node* r_reverse(Node* list)
{
    return r_reverseItem(NULL, list);
}

Now we can do the recursion. Again the edge case is still NULL.
Node* r_reverseItem(Node* last, Node* list)
{
    if (list == NULL)
    {
        return last;
    }

    Node*   next    = list->next;
    list->next      = last;
    return r_reverseItem(list,next);
}


JavaScript program to find if array is in Arithmetic or Geometric sequence

This is great example to practice identifying the right abstraction.

In testing to see if an array is geometric or arithmetic series, what you are really doing is testing if a particular mathemtical relation holds for each element.  That is, the heart of your program is in these 2 lines:

if(arr[i+1]-arr[i]===arr[i+2]-arr[i+1]){
//...
else if(arr[i+1]/arr[i] ===arr[i+2]/arr[i+1]){

Let's go ahead and extract just these relations into their own functions:

// This tells if an arithmetic relation holds at a particular index of the array
// The function signature here is chosen to work with javascript's every method
// The reason will become clear below.
function isArithmeticAtIndex(elm, i, arr) {
  if (i < 2) return true; // trivially true when it can't be false
  return arr[i] - arr[i-1] === arr[i-1] - arr[i-2];
}

function isGeometricAtIndex(elm, i, arr) {
  if (i < 2) return true;
  if (arr[i-1] == 0 || arr[i-2] == 0) return false; // can't divide by 0
  return arr[i] / arr[i-1] === arr[i-1] / arr[i-2];
}

Now we'll create a generic function that tells us if a particular mathematical relation holds at every elment of an array:

function hasSeriesRelation(arr, relationFn) {
  // geometric and arithmetic series (and most others)
  // don't make sense with less than 3 elements
  if (arr.length < 3) return false;
  return arr.every(relationFn);
}

At this point, we are basically done.  We can use what we've written as follows:

a = [1,2,3,4];
hasSeriesRelation(a, isArithmeticAtIndex);
// => true
a = [1,2,3,5];
hasSeriesRelation(a, isArithmeticAtIndex);
// => false
a = [1,2,4,8];
hasSeriesRelation(a, isGeometricAtIndex);
// => true
a = [1,2,4,9];
hasSeriesRelation(a, isGeometricAtIndex);
// => false

But writing hasSeriesRelation(a, isGeometricAtIndex) is cumbersome, so let's wrap these up in their own functions, and make them array methods:

Array.prototype.isArithmeticSeries = function() { return hasSeriesRelation(this, isArithmeticAtIndex) };
Array.prototype.isGeometricSeries = function() { return hasSeriesRelation(this, isGeometricAtIndex) };

And now we can write things like:

[1,2,4,8].isGeometricSeries();
[1,2,3,4].isArithmeticSeries();

Side Note: Some consider extending Array.prototype bad practice.  I think it can be okay depending on your circumstances.  See this post for more discussion.  In any case, it's only marginally relevant to this discussion, because you can easily rewrite the above to functions with signatures like function isArithmeticSeries(arr)

Finally, note that we have gained the ability to quickly and easily add new types of series.  For example, we might want to identify Fibonacci-like series:

function isFibonacciAtIndex(elm, i, arr) {
  if (i < 2) return true; // trivially true when it can't be false
  return arr[i] === arr[i-1] + arr[i-2];
}

a = [1,1,2,3,5,8];
hasSeriesRelation(a, isFibonacciAtIndex);
// => true


First of all, I'd be hesitant to use as-you-type correction to begin with. It doesn't take much for something like that to be an annoyance rather than a help. It's probably better to validate the input only when it loses focus, or when the form is about to be submitted, and then inform the user somehow.

Point is, it's not hard make your code trip over something. For instance, I just pasted in "2312" and got a GPA with 3 decimal places. I also tried typing in a valid value, and then went back with the arrow keys and removed the first digit with the intention of replacing it - but removing that first digit cleared the entire input. If I just select the first digit, and hit a key, my input gets ignored, valid or not. I can't manually enter a decimal point. The cursor jumps around... and so on.

Unless your system is perfect and takes all possible interactions into account, it'll likely be very annoying and frustrating to use.

Point is, it's a lot easier to validate stuff, once it's all been entered. For instance, this regular expression /^([0-3](\.\d\d?)?|4(.00?)?)$/ will match a valid GPA with 0-2 decimal places.

But don't change the value! You can format it, if it's otherwise valid (like adding ".00" if the user just typed "4"), but leave it at that. Just call attention to the error, optimally with an explanation of why the value is invalid.

In any event, presuming this is being sent to a server, always, always validate it on the server. Never trust the client™

But there's still code to review here, regardless of its use.

Code notes:

Declare your variables with var. Right now, every variable is global! Big no-no.
Don't find and re-find an element with getElementById; find it once, stick it in a variable, and use that instead.
Don't use the old-school .onblur = etc. event handling. Favor addEventListener instead (or use a library to do the event handler registration for maximum compatibility)

More broadly, there's no need to keep declaring a function like function (e) { FormatGPA(this.id); } for each event. Declare that function once, and use it for every event. Or simply don't use an argument for the format function, and let it know what element to find. Or, if you use addEventListener, the element will be available as this in the event handler, i.e.:

var someInput = document.getElementById("some-input");
someInput.addEventListener("click", someHandler, false);

function someHandler() {
  alert(this.value); // `this` refers to the element that triggered the event
}

(using alert just as an example - it's obviously not an ideal way to provide feedback.)

Style notes:

Function names and variables should be lowerCamelCase (unless they are constructors), so: formatGPA. And if you've got an acronym at the start of your name, make it all-lowercase, i.e. gpaElementId.
Don't use HTML comment syntax in your JS code; it doesn't matter, and makes little sense.
Avoid the brace-on-new-line style. JavaScript has automatic semicolon insertion, which (long story short) means that you should stick to a style like

if(condition) {

} else {

}


Globals

Generally speaking it's not a good idea to use globals like this. It harms re-entrance. What if you want to support two stopwatches at once, either in one UI or as a web server? Having globals like this will prevent that.

It also harms testability. It is more difficult to test methods that rely on global state than it is to test methods that are self-contained, having state passed to them either in an object context (self) or as method parameters.

One way to get around this is make a class with attributes number_of_seconds and is_counting (which I find would be more intuitive than stop_counting).

Booleans

This block:

if stopCounting == False:
    numberOfSeconds += 1
    seconds.config(text=str(numberOfSeconds))
    seconds.after(1000, counting)
elif stopCounting == True:
    stopCounting = False
    numberOfSeconds = 0
    seconds.config(text=str(numberOfSeconds))

is more easily expressed as

if stopCounting:
    stopCounting = False
    numberOfSeconds = 0
    seconds.config(text=str(numberOfSeconds))
else:
    numberOfSeconds += 1
    seconds.config(text=str(numberOfSeconds))
    seconds.after(1000, counting)

Variable names

They should be lower_snake_case, i.e. start_button.


Finding the distance between the two closest points in a 2-D plane

Coding style

Your code is difficult to read because it is written very condensed.

There is a well-established coding style for Python, the
PEP8 coding style,
and conformance to that style can be checked online at
PEP8 online.

In your case it reports “missing space around operator” in almost every
code line, also “line too long” and “multiple statements on one line”
violations. As an example,

elif len(points)==3: return min(dist(points[0],points[1]),dist(points[0],points[2]),dist(points[1],points[2]))

is better written as

elif len(points) == 3:
    return min(dist(points[0], points[1]),
               dist(points[0], points[2]),
               dist(points[1], points[2]))

Variable naming

Another aspect which makes the code difficult to understand is the
naming of variables. Here are some examples:

points_y = sorted(points, key= lambda z:z[1])
points.sort(key=lambda g:g[0])

The parameter names z and g seem to be arbitrary. Why are they different
at all if they both refer to a point? Similarly at

yleft = [t for t in points_y if t[0]<=points[ave-1][0]]
yright = [q for q in points_y if q[0]>=points[ave][0]]

Why t and q? I'd suggest point or p in all those places.

def min_dist(points,points_y):

Both parameters contain all points, just sorted differently (by x and y,
respectively). Why the asymmetry in the parameter names? I'd suggest

def min_dist(points_x, points_y):

here, plus a doc comment explaining the meaning of the parameters.

ave = (len(points)+1)//2

makes one think of “average” but is just half of the list length.

Some simplifications

import sys

is not needed. The inner parentheses in

return math.hypot((b[0]-a[0]),(b[1]-a[1]))

are not needed. The elif in

elif len(points)==3:

can be replaced by an if. The slicing in

d1 = min_dist(points[0:ave],yleft)
d2 = min_dist(points[ave:len(points)],yright)

can be simplified to

d1 = min_dist(points[:ave], yleft)
d2 = min_dist(points[ave:], yright)

Validate the input

The program aborts with RecursionError or IndexError if zero or
one point are passed to the function. You should validate the input
and throw an appropriate exception in those cases.

A possible problem

If points[ave-1][0] == points[ave][0] (which means that more than one point
lies on the dividing vertical line) then elements from the point_y
list are assigned to both yleft and yright:

yleft = [t for t in points_y if t[0]<=points[ave-1][0]]
yright = [q for q in points_y if q[0]>=points[ave][0]]

which means that in the recursive calls

d1 = min_dist(points[0:ave],yleft)
d2 = min_dist(points[ave:len(points)],yright)

the second list is not necessarily a rearrangement of the first list anymore.

I haven't found an example where this leads to a wrong result, but it could
be an performance problem because “too large” lists are passed down the
recursion. As an extremal case, if all points have the same x-coordinate
then yleft and yright will always be the complete initial points_y
list.

Performance improvements

points[ave][0]] is accessed multiple times, it might be advantageous to
assign that value to a variable once.

The initial value

d_=2*(10**18)

is a bit arbitrary, but actually not needed: In the following loop we are
only interested in points having a distance less than the previously
computed minimum distance in the left and right half:

d = min(d1, d2)
# ...
for i in range(len(arr_split) - 1):
    for j in range(i+1, min(len(arr_split), i + 7)):
        temp = dist(arr_split[i], arr_split[j])
        if temp < d:
            d = temp
return d

And while it is true that pairs of points having a distance less than d
are at most seven (or six?) indices apart, it seems to be more efficient
to leave the inner loop if the y-coordinates differ by d or more:

for i in range(len(arr_split) - 1):
    for j in range(i + 1, len(arr_split)):
        if arr_split[j][1] - arr_split[i][1] >= d:
            break
        temp = dist(arr_split[i], arr_split[j])
        if temp < d:
            d = temp
return d

Further suggestions

Instead of storing the point coordinates a a tuple you could define a
custom class

class Point:
    __slots__ = ('x', 'y')

    def __init__(self, x, y):
        self.x = x
        self.y = y

so that you can access the x- and y-coordinates of a point with p.x
and p.y instead of subscripting.


How do I optimize the bubble sort in Assembly8086?

On your array that has 5 elements
the 1st iteration of the outerloop (CX=4) has to do 4 compares in the innerloop
the 2nd iteration of the outerloop (CX=3) has to do 3 compares in the innerloop
the 3rd iteration of the outerloop (CX=2) has to do 2 compares in the innerloop
the 4th iteration of the outerloop (CX=1) has to do 1 compare in the innerloop
In your code you have initialized the outerloop counter correctly but you should see that the current value of the outerloop counter can serve as the initial value of the innerloop counter. You don't need to re-compute this!

When it comes to speed, XCHG with a memory operand is bad. Normally we would load 2 successive elements in 2 different registers, compare those, and if necessary write them back switched.
However because your array contains byte-sized elements, you can load 2 elements in 1 word-sized register, compare its low and high byte-sized halves, and if necessary xchg the halves and write the word register back. That's how I did it in below code.

The LOOP instruction has become infamous for being slow these days. You can easily replace it by the pair of instructions dec cx jnz ....

    mov   cx, n
    dec   cx             ; Max number of compares is (n - 1)
outerloop:
    push  cx             ; (1) Preserve outerloop counter CX

    xor   di, di
innerloop:
    mov   ax, array[di]
    cmp   al, ah
    jle   if_end
    xchg  al, ah
    mov   array[di], ax
if_end:
    inc   di
    dec   cx
    jnz   innerloop

    pop   cx             ; (1) Restore outerloop counter CX
    dec   cx
    jnz   outerloop

I also can't comprehend the idea of pushing CX to stack for using nested-for loops. If you would give some suggestion about it I would be very happy.

Pushing the outerloop counter CX is only necessary if the innerloop wants to use and change the CX register for its own purposes. We can easily re-write the above code and use e.g. BX to control the innerloop. Then we don't need to push cx or pop cx.
    mov   cx, n
    dec   cx             ; Max number of compares is (n - 1)
outerloop:

    mov   bx, cx
    xor   di, di
innerloop:
    mov   ax, array[di]
    cmp   al, ah
    jle   if_end
    xchg  al, ah
    mov   array[di], ax
if_end:
    inc   di
    dec   bx
    jnz   innerloop

    dec   cx
    jnz   outerloop

And while we're optimizing this, we can even write the innerloop without using a special loop counter. We can use the index register DI at the same time for indexing the memory and for counting. This method also speeds things up since the combo cmp di, cx jb innerloop can macro-fuse and give us some extra speed.
    mov   cx, n
    dec   cx             ; Max number of compares is (n - 1)
outerloop:

    xor   di, di
innerloop:
    mov   ax, array[di]
    cmp   al, ah
    jle   if_end
    xchg  al, ah
    mov   array[di], ax
if_end:
    inc   di
    cmp   di, cx
    jb    innerloop

    dec   cx
    jnz   outerloop

stacksg     SEGMENT BYTE STACK 'stack'
            DW 12 DUP(?)
stacksg     ENDS

Might I further suggest you set the stack to a more realistic value like 128 words?


This question has a number of misconceptions

You are unlikely to develop a real-time system using .NET because of
unbounded GC times
ConcurrentQueue<T> is better than BlockingCollection<T> not because
it does not use locks. It actually uses more locks, just in a
smarter way.
ConcurrentQueue<T> provides worse API exactly because it is faster.
Most of the missing APIs are missing because there is no way of
implementing them efficiently and in a thread-safe manner

Your code has a number of weaknesses:

I don't see any reasonable use for IsAddingCompleted and friends
I am not sure there are no race conditions. For example, lets assume we have produced == consumed == 0. Thread1 adds an item and is just before incrementing produced. Thread2 calls TryDequeue, since produced==consumed, it goes through and stops right before changing sleeping. Thread1 continues, changes produced to 1, checks if sleeping is 0, which it is and quits without setting the event. Thread2 continues to Wait(). Now we have a task and an eteranlly-waiting client.
There is no way to abort a waiting TryDequeue and finish gracefully


Queue that connects multiple producers and multiple consumers

Since you say that your whole system is based on message passing you should take a serious look at akka.   You get a rock solid message passing system, and you can even spread it on multiple machines in the future.

I have not checked in detail, but you have some very serious concurrency bugs.  For example, add checks if writing is allowed, then writes to the queue.  The problem is that you did not synchronize add, so the check might pass, but before calling the next line, some other thread might bring the count down latch down to zero.  BlockingQueue is thread-safe, but it is far from enough to make your code thread-safe.

I don't like the MessagePipeline api: it is too complex.  I really don't see the advantage of writing or taking "batches" of messages.  If the reader or writers want to process many messages, just let them read or write many messages themselves by processing their many messages in a loop.  The api itself should only read/write one message at a time.  In that case, your whole MessagePipeline is superfluous since a simple BlockingQueue is exactly what you want.  You will also avoid many concurrency bugs.  You would also need to keep the CountDownLatch or something similar to let the consumer know when it's over.


Using RestTemplate with HttpComponentsClientHttpRequestFactory in a multithreaded environment

Will you have many instances of TimeoutThreadExample in your real application? If not, then the restTemplate field will be better non-static, initialized in the constructor:

private final RestTemplate restTemplate;

public TimeoutThreadExample() {
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setReadTimeout(READ_TIME_OUT);
    requestFactory.setConnectTimeout(CONNECTION_TIME_OUT);
    restTemplate = new RestTemplate(requestFactory);
}

On the other hand, if you will have many instances of TimeoutThreadExample, then it will be better to make restTemplate static, and initialize it in a static initializer block instead of using a method:

private static final RestTemplate restTemplate;

static {
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setReadTimeout(READ_TIME_OUT);
    requestFactory.setConnectTimeout(CONNECTION_TIME_OUT);
    restTemplate = new RestTemplate(requestFactory);
}

As for this question:

  // is it ok to create a new instance of HttpComponentsClientHttpRequestFactory everytime?

In both alternatives I offered, the instance is really created only once, so that's ok.

  The way I am creating RestTemplate along with HttpComponentsClientHttpRequestFactory is thread safe and efficient?

Initializing static variables is thread safe. And since you're creating RestTemplate and HttpComponentsClientHttpRequestFactory only once, it's efficient too.


The code converts a pair of numbers to a dictionary key by putting the numbers in a list and then turning the list into a string: str([a, b]). But that's not necessary: you can use the tuple (a, b) as a dictionary key without having to convert it to a string.

(The reason that you can't use a list [a, b] as a dictionary key is that lists can be modified, which invalidates their use as keys. Tuples can't be modified, and so you can use them as keys.)
It would simplify the code if the function routes (i) started by looking up its parameters in the results dictionary to see if it already had an answer; and (ii) always stored its result in the dictionary. If you did both of these, then you could avoid a lot of the cases:

results = {}

def routes(a, b):
    "Number of routes from (a, b) to (0, 0) in a grid."
    if (a, b) in results:
        return results[a, b]
    elif a > b:
        r = routes(b, a)
    elif a == 0:
        r = 1
    else:
        r = routes(a - 1, b) + routes(a, b - 1)
    results[a, b] = r
    return r

This code does two things: it computes the number of routes, and it arranges to cache the results of the computation in a dictionary to avoid having to recompute it. The principle of separation of concerns suggests that we should try to split these two things into different bits of code. That would make them easier to understand, test, and reuse.

In this case, Python already has built-in support for caching the results of a function: see functools.lru_cache. So all you need to implement is the route-counting part of the code, and let lru_cache do the caching:

from functools import lru_cache

@lru_cache(maxsize=None)
def routes(a, b):
    "Number of routes from (a, b) to (0, 0) in a grid."
    if a > b:
        return routes(b, a)
    elif a == 0:
        return 1
    else:
        return routes(a - 1, b) + routes(a, b - 1)


Reasonable ActiveSupport dependency and define_method usage?

1) I believe that depending on popular and stable libraries is not a problem. Though I prefer more opinionated approach: to symbolize_keys!.

2) You define_method looks clear enough, IMHO

3) You may simplify grouped like this:

def grouped_by(key)
  self.values.flat_map { |type| type[key] }.compact!
end


WKS is right, first of all you should split your layout from your logic and your logic from your database query. (see Model-View-Controller-Pattern)

Lets start with your model (Model.php): (actually you could split it in a model for each entity/database table)

<?php
class Model()
{
     public function __construct(PDO $connection)
     {
         $this->connection=connection;
     }

     public function getZones($week)  //find a nicer name
     {
         //... see Peters post for a sample join
         // prepare multi dimensional array as needed in your template
         return $zones;
     }
}

It is in general a bad idea to run SQL queries in a loop, so try to create one join for all your queries.

Now the simple Controller (index.php)

<?php
require 'Model.php';
$connection=new PDO(...);
$model=new Model($connection);
$currentWeek = ...;
$zones= $model->getZones($currentWeek);

include "view.php"

That's it! Nothing fancy. Now the view:

         Zona
         Baptismos Mulheres
         Conf. Mulheres
         Batismos Homems
         Conf. Homems

    <?php foreach($zones as $zone):?>

         <?php echo $zone['name']; ?>

        <?php foreach($zones['areas'] as $area):?>

                 <?php $area['name']; ?> <?php echo $area['companions']; ?>

        <?php endforeach?>
    <?php endforeach?>

Don't use all-capital-letter variable names. And don't use global variables. Both is considered bad practice.


Thanks for sharing your code.
Comments
Your code has (essentially) only one comment.
Comments should explain why the code is like it is. Your (first) comment is a good example.
Naming
Finding good names is the hardest part in programming, so always take your time to think about the names of your identifiers.
Please read (and follow) the Java Naming Conventions. The name of your base class starts with a lower case letter which should be upper case instead.
Avoid Single Character Names and Abbreviations
Since the number of characters is quite limited in most languages you will soon run out of names. This means that you either have to choose another character which is not so obviously connected to the purpose of the variable or you will have to "reuse" variable names for different, possibly unrelated contexts. This makes your code hard to read and understand for other people (keep in mind that you are that other person too, if you look at your code in a few months!) The same is true for abbreviations. You might find them obvious today, while you're actively dealing with the problem, but you might have to "relearn" them if you worked on something else for a while.
On the other hand, Java's identifier names can be virtually unlimited in length. There is no penalty in any way for long identifier names. So don't be stingy with letters when choosing names.
Define Variables as Late as Possible
You define your variables at the beginning of main. But the variable c is used only within the loop. This makes it hard to move the coin drop code to its own method. Your IDE's automated refactoring will introduce both an extra parameter and an unneeded return value. So always declare variables just before their first use unless they are magic numbers.
Magic Numbers
Your code has some magic numbers. They are literal values with a special meaning like here:
while (r != -1)
//...
    if (column == 0 || column == row || row == 0) {
        pasVal = 1;

You should introduce constants with meaningful names:
public static final int LOWEST_INDEX = 0;
public static final int TRIANGLE_START_NUMBER = 1;
public static final int INVALID_INDEX = -1;
// ...

while (r != INDEX)
//...
    if (column == LOWEST_INDEX || column == row || row == LOWEST_INDEX){
        pasVal = TRIANGLE_START_NUMBER;


Efficient implementation of a Dynamic Programming challenge

It looks like the nested loops of your algorithm are using only three rows of the dp matrix:

dp[j]
dp[j-1]
dp[j-2]

You can use this observation to transform your solution from one requiring O(N^2) space to one requiring O(N) space by changing

double **dp = new double*[max];

to

double dp[3][max]; // Now your matrix has a chance of fitting on the stack

and adding %3 to all operations that touch the first index of the dp matrix.

This may or may not eliminate the timeout, but it will make your program better by reducing the amount of resources that it needs to operate.


Trim trailing lines and remove blank lines in C

Well designed code.

  I am a bit suspicious of that realloc idiom for reallocing the buffer if it gets full. Is it right?

I see no errors.

Nit: I'd rather see newsize declared locally.  It is only used there.

// newsize = size + BUFSIZ;
size_t newsize = size + BUFSIZ;

Other

Unneeded code

The initial allocation is not needed.  realloc() in the loop can handle starting from 0

//size = BUFSIZ;
//if (buf == NULL)
//    if ((buf = malloc(size)) == NULL)
//      err(EXIT_FAILURE, "malloc");
size = 0;

Perhaps there is a concern about ...

fwrite(NULL, 1, 0, stdout);

... yet given the spec "If size or nmemb is zero, fwrite returns zero and the state of the stream remains unchanged.", I see no issue.

Either way I'd consider the micro-optimization below, just for the sake of avoiding the fwite() function call as i==0 will be quite common.  (Usually I do not encourage any micro-op - I'll make an exception here)

// fwrite(buf, 1, i, stdout);
if (i > 0) fwrite(buf, 1, i, stdout);

Checking output

Code does not check the return values of fwrite(), putchar(c).  Robust code would and report the problem - even if it is rare.

Missing free()

Free the allocation, else trim() leaks memory.

free(buf);

ferror()

Good that code checks this.

main() always reports success

main() employs the implied return 0;.  Yet failure is possible.

Given code has exitval = EXIT_FAILURE;, I'd expect main() to return exitval; in the end.

Initialize

Rather than declare then assign lines later, consider declare with initialization.

// int status;
// ...
// status = BEG;
int status = BEG;

// size_t size;
// ...
// size = BUFSIZ;
size_t size = BUFSIZ;

Same for i.


This type of practice is common, and works well.

The Java JIT compiler will identify the LOGS_VERBOSE as being a constant, and will know that it is always false, and thus will compile-out the logging entirely.

There is a slight performance hit on any code that has not (yet) been compiled.... but, once the compile has happened, there is no hit at all.

It is relatively common to use a System property to determine whether to log...

public static final boolean LOGS_VERBOSE = Boolean.getBoolean("LOGS_VERBOSE");

This behaves in the exact same way (because JIT happens after the property is set)... but, if you start your program as:

java -DLOGS_VERBOSE=true ......

then suddenly you have the fully-featured logging.

In many cases this sort of checking can improve performance because it can eliminate expensive 'setup' for log messages


Suitable way for Validating JPA Entities in Spring Boot

The approach is ok, although it depends on the context. If the application receives AppUserDto in the controller layer, doing the validation in the service layer might be too late. Moreover, the service layer will be dependent on the DTO.
If AppUserDto is received in the controller layer (e.g. from a REST API) a good approach is validating the request in the controller layer, mapping the DTO to the entity, and passing it down to the service layer:
@RestController
public class UserController {
    //...

    @PutMapping(value = "/user")
    public void updateUser(@RequestBody @Valid AppUserDto appUserDto) {
        AppUser appUser = toEntity(appUserDto);
        appUserService.update(appUser);
    }

    //...
}

After the validation with @Valid, if there are no errors, toEntity will map the DTO to the entity. The mapping can be done manually or using ModelMapper. More info on this approach here.
In general, DTO validation should be done as soon as possible to prevent internal components to work with invalid objects (as mentioned in the article you linked). Additionally, mapping the DTO to the entity keeps the service layer independent of the particular request so that it can be better reused and tested.


I decided I didn't want to use any of them. I decided to make my own.

That's a mistake.

and followed the convention of leading underscore to mean non-published.

A leading underscore followed by an uppercase letter is reserved identifier reserved for the implementation.

Please note that this code is published under the MIT license.

Also note that this code is not published under the creative commons license. See the bottom of the page. Everything published on any stack-exchange site is available under creative commons.
Design
There are a lot of missing features that I would expect in unit test framework.

Ability to run tests in isolation
Ability to run groups of tests.
Ability to set up state for tests
Ability to tear down state and reset the environment.
Some facility for mocking other classes.


Here is my refactoring:

private void movePosition(Plant p) {
    xpos += Integer.signum(p.getXpos() - xpos) * DELTA_X;
    ypos += Integer.signum(p.getYpos() - ypos) * DELTA_Y;

    xpos = Math.floorMod(xpos, MAX_X);
    ypos = Math.floorMod(ypos, MAX_Y);
}

1. Signum

signum implements the sign function, which gives -1, 0 or 1 for negative integers, zero and positive integers respectively. It encodes the original logic in a very short and readable expression.
The sign is multiplied by the appropriate amount of units (constants are not detailed in the code, btw).

I have nothing against decision tables in principle (see rolfl's answer), but I don't think this is necesary here.
In his answer, palacsint cited "Code Complete". I can do that too!

From Code Complete 2nd Edition, Chapter 19: General Control Issues, page 431:

  Use decision tables to replace complicated conditions

  Sometimes you have a complicated test involving several variables. [...]

... and sometimes you don't ;-)

2. Modulus

The wrap-around behaviour of the original code can be achieved with a modulus operation. Note that you cannot just use the % operator in Java because it computes the remainder, which can be negative when your position goes below zero. The floorMod operation actually computes modular arithmetic.

Now, you might think: this is wrong, the original code does not work like this!
Yes, but let me explain:

First, OP's coordinates range from 1 to 720 (both inclusive). I have an issue with this and I deliberately changed the approach here. The reason is that, in the original code, instead of using a coordinate space that have the origin at (0,0), the origin is translated at (1,1).

Most of the time, you end up having to add or substract 1 to you operations. That can eventually lead to off-by-one errors. If coordinates are from 0 to 719, however, the wrap-around logic is simply given by the modulus operation.
"But the original behavior is not like a modulus!", you might say. Why do you say this? because, suppose x is 710, and then I add 30: with modulus, I goes back to 20, whereas using OP's code, I would have 1 because when we are out of bounds, we go back to the minimal (or maximal) position.

To that, I reply that you never are at position 710, but only at 0, 30, 60, ..., 690. At least, this is what I understand from OP's code, where the object seems to move on a grid, and not freely around. I suppose the object is always located initially at a multiple of 30, and then can only move by 30 units.

If I am wrong, then (1) sorry, and (2) yes, the modulus is not exactly the good answer; you might better use the boundPos function from rolfl.


You're using using blocks to dispose your disposables, which is excellent. However these blocks increase the nesting of your code; since there's nothing between using (var oracleConnection = new OracleConnection(ConnectionString)) and using (var oracleCommand = oracleConnection.CreateCommand()) you could drop the curly braces and "stack" them, like this:

    using (var oracleConnection = new OracleConnection(ConnectionString))
    using (var oracleCommand = oracleConnection.CreateCommand())
    {
        ...
    }

Within that scope, you're reassigning variable Id at each row that gets read; ultimately the value of Id will be that of the last row that was read. I doubt this is the intended behavior.

As for the string query, I agree it's "dangerous" - I prefer (by far) to use an object-relational mapper such as Entity Framework (which as @svick has mentioned has an Oracle provider), but never used it for anything other than SQL Server. I believe you could look into NHibernate as well, or shop around - something like ".net ORM for oracle" should find you some interesting links :)


Using inputted data from vector to create two outputs

Although there's room for argument that it might be an abuse, one way you could do the adjacent sums part of this would be to use std::adjacent_difference, but pass it a function that adds instead of subtracts:

std::adjacent_difference(inputs.begin(), inputs.end(),
    std::ostream_iterator<int>(std::cout, "\t"),
    std::plus<int>());

Note, however, that the first result you get from this will be just the first item, not added to anything. Each subsequent value in the result will be the sum of the current and previous items.

You might consider, instead, implementing an adjacent_sum that produces the result you want a little more directly:

template <class InIt, class OutIt>
OutIt adjacent_sum(InIt begin, InIt end, OutIt result) {
     ++begin;
     while (begin != end) {
          *result = *begin + *(begin-1);
          ++result;
          ++begin;
     }
     return result;
}

// ...

adjacent_sum(inputs.begin(), inputs.end(),
    std::ostream_iterator<int>(std::cout, " "));

For the second part, I'd probably use std::transform, supplying forward iterators for the first range, and a reverse iterator for the beginning of the second range:

std::transform(inputs.begin(), inputs.begin()+inputs.size()/2,
    inputs.rbegin(),
    std::ostream_iterator<int>(std::cout, " "),
    std::plus<int>());


Share data between 2 React components using React Hooks

MovieSearchComponent

With the useState the common pattern is to name the state update function matching with the state value, i.e. movieList and setMovieList. This makes it clear what state the function will update.
I had to read and reread your description of addMovie and compare it against the actual implementation. It isn't clear if the function is to add a movie, add an array of movies, or, based on the implementation, replace existing movie array list. The name of the function and the result of the function executing should match. In your description you say addMovie updates the movielist array, so for the sake of code review I'll assume that to mean the third option with state replacement. In this case the callback function can simply be setMovieList. Update the prop name as well.

Code suggestions
import React, { Fragment } from 'react';

...

const MovieSearchComponent = () => {
  const [movieList, setMovieList] = useState<Movie[]>([]);

  return (
    <Fragment>
      <MovieSearch setMovieList={setMovieList} />
      <MovieResultList movieList={movieList}/>
    </Fragment>
  )
};

MovieSearch

Update prop addMovie to setMovieList.
Values like apiKey and baseurl that never change don't need to be in the functional component body and continually redefined. Declare them externally in the file.
It may be better to extract the synthetic event data and allow the event object to be returned to the event pool as quickly as possible. Extract and pass the event's target's value to setMovieSearchResults.
Handle the fetch request's unhappy paths, i.e. a not-successful responses or errors handling successful responses. Checking that the fetch was successful.
You should always standardize and sanitize user input.

Code suggestions
const apikey = 'api_key=***************dad4';
const baseurl = 'https://api.themoviedb.org/3/search/movie?'

const Search = styled.input`
  color: green;
`;

const MovieSearch = ({ setMovieList }) => {
    const searchTMDBapi = e => {
        const { value } = e.target;

        // Simple example: URI encode and lowercase
        // ... there's more you could do
        const query = encodeURI(value.toLowerCase());

        setMovieSearchResults(query);
    }

    const setMovieSearchResults = debounce(query => {
        fetch(baseurl + apikey + '&language=en-US&query=' + query + '&page=1&include_adult=false')
          .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.json();
          })
          .then(data => setMovieList(data.results))
          .catch(console.error);
  }, 500);

  return <Search placeholder="Search" onChange={searchTMDBapi}/>
}

MovieResultList

Pretty simple & clean component. Only suggestion here might be to tighten up variables by using object destructuring.

Code suggestions
const MovieResultList = ({ movieList }) => (

      {movieList.map(({ id, original_title }) =>
{original_title}
)}

);


Solved the problem. Might some cleanup and/or advise

Security

You should use prepared statements for all variable data to protect against SQL injection.

The thing is, Joomla actually doesn't seem to support prepared statements. For me, that would be a reason to think about using a different CMS, but you should at the very least follow their guidelines to prevent SQL injection (checking data type and escaping. which - when done correctly - does offer complete protection against injections).

When echoing data, you should also protect against XSS.

Misc

all your SQL keywords should be uppercase (eg and -> AND) to increase readability.
your table and column names are too long, which makes the queries hard to read. For example, to you really need customsforall or virtuemart in them?
you get a new DBO for each query, this doesn't seem necessary.
you should be able to use JOIN to reduce the amount of queries you have.


Tiny function to write array or string to a file for testing with MVC, Ajax, etc

Mixing fwrite and file_put_contents usage is a little strange, as they are functions which overlap in functionality. file_put_contents in fact is just a wrapper to call fopen, fwrite and fclose - expanding that call to it's component parts would therefore make what the code is doing more obviously repetitive.

So, the first goal I would suggest is to avoid repeatedly opening the file to append text to it; the goal of the function is simply to append bytes to a file - so make the function do that, in one write call. An example of what I mean is:

function write_to_file($message)
{
    $header = "\nMessage:\t ";

    if (is_array($message)) {
        $header = "\nMessage is array.\n";
        $message = print_r($message, true);
    }

    file_put_contents(
        '/path/to/logs/a_log_file.php',
        $header . $message,
        FILE_APPEND | LOCK_EX
    );
}


From Q to compiler in less than 30 seconds

I have a couple of suggestions which are not specifically about the code, but rather about the user experience.

The first thing I did was copy-paste the script to a file, make it executable and tried to run it.

$ chmod +x fetchQ.py
$ ./fetchQ.py 124307 autoproject
./fetchQ.py: line 5: $' Code Review question fetcher.  Given the number of the question, uses\nthe StackExchange API version 2.2 to fetch the markdown of the question and\nwrite it to a local file with the name given as the second argument. ': command not found
... etc ...

As you understand, I just assumed the script had a shebang line and instead of using python, Bash tried to interpret the script itself. I think other users might have the same expectations and that you should therefore begin your script with the line #!/usr/bin/env python.

Now, you might have noticed, I accidentally left out the .md extension for the file name. Because the primary use-case for this program is to set up a file for AutoProject, which requires files to have that extension, I think it should automatically be added if no other extension is provided.

Finally, the other argument to the program is the question id. Instead of making users extract the id themselves from the url, I think the user should have the option to pass the full link directly because just pressing CtrlL; CtrlC is easier than by hand selecting the id portion.


How's this looking as an OOP language overall?

Ruby is actually multi-paradigm.
It allows you to use OO, and it gives you the option not to.
For example you didn't use any objects,
so you didn't actually employ OOP.

For improvements:

Your {lang}_translate code is very repetitive,
you can change it to a class to reduce repetitiveness.
You load the YAML file on each word translated (or incorrectly inputted),
and so you should load it once.
You have to add multiple things when you add a new language.

Both the index and language in the case.
Both the index and language in the puts
The language file in the new {lang}_translate function.

You can remove this all if you use a list and a class.

First, to remove the first two points,
I would make a class that lazily loads the translations.
And implements the translation.
Also I personally think your case statement in {lang}_translate is better as if elsif else.
exit seems like a bad design here,
if you were to want to allow the user to change language by entering 'q',
you will have to remove the exit.

class Translate
    def initialize(file_name)
        @file_name = file_name
    end

    def set_translation
        @translations = YAML.load_file @file_name
    end

    def translate
        puts "Enter word or phrase to be translated to English, press 'Q' to quit:"
        input = gets.chomp
        if (@translations || set_translation)[input]?
            puts "The translation from Spanish to English is: #{@translations[input]}"
        elsif input =~ /q/i
            return
        else
            puts "Invalid word or phrase redirecting..."
            translate
        end
    end
end

spanish = Translate.new('spanish.yaml')
spanish.translate

This can then be expanded easily to allow any language,
by just passing a different file path.

As for welcome,
I would recommend using an Array so you have control over the order.
And so you can specify languages by only name and file.

languages = [
    ["Spanish", Translate.new('spanish.yaml')],
    ["Russian", Translate.new('russian.yaml')],
    ["Arabic", Translate.new('arabic.yaml')]
]

Being able to use this in the output is a simple each_with_index.

For the program to automatically call translate
you need to get the index of the language in the languages Array.
Where you get the index either via a regex or .index.
Finally you then check if it's valid input, and output correctly.

def welcome
    languages = [
        ["Spanish", Translate.new('spanish.yaml')],
        ["Russian", Translate.new('russian.yaml')],
        ["Arabic", Translate.new('arabic.yaml')]
    ]

    puts "Welcome to the Translation Center! Please enter the language you would like to translate to English or you can choose from the list below:"
    languages.each_with_index { |item, index| puts String(index + 1) + '. ' + item[0] }
    language = gets.chomp!.downcase

    index = if /^\d+$/.match(language) then
        Integer(language) - 1
    else
        languages.index { |x| x[0].downcase == language }
    end

    if index.nil? or (language = languages[index][1]).nil?
        puts "Language is not yet supported within Translation Center."
    else
        language.translate
    end
end

Finally, I think that you should allow users to input more than one word or phrase at a time. This would be adding a simple infinite loop to Translate.translate, and changing it to not be recursive.


Detecting Windows Phone and Tablet clients

I guess something like :

return DeviceDetectionCls.isWindows8Phone(userAgent) || DeviceDetectionCls.isWindows8Tablet(userAgent);

would do the trick.


You should first ask yourself, why do you write a method to check if a file is in use.

You can't use this method to avoid exceptions, because although your method returns False just a microsecond later the file could be opened exclusivly by another program. You still would need to do any file operation inside a Try..Catch block. So the best way would be to do just that.

Looking at your code, I would suggest to use a guard condition to save one level of indentation like so

If Not IO.File.Exists(path) Then
    Return False
End If
Try....

Using File.OpenWrite(string) would be enough because the only difference to Open(FileMode, FileAccess, FileShare) would be the FileMode value having FileMode.OpenOrCreate and the FileAccess value having FileAccess.Write

If you want to go the way you have posted as answer you could omit the FileAccess.ReadWrite and FileShare.None enumeration because the Open(FileMode) method just calls the overloaded Open(FileMode, FileAccess, FileShare) method with the same values as your call.

What I like about your code is that you apply the .NET Naming GuideLine and your using of the Using to make sure that the stream is closed properly.

What I dislike is that you don't check wether path is null. Proper method parameter validation for public methods should always be done.


This is very much C-style code: the only thing that qualifies it as C++ is the fact that you use new and delete[] rather than malloc() and free().

I don't see why RECORD_TIME should be a constant. I would expect it to be a constructor parameter. Or, use std::vector to store the samples, and you won't even have to worry about the array capacity, or even new and delete[].

The recorder class should be responsible for initializing sample_counter to zero, which you never did in your recorder_init(). In addition, I would expect there to be a method for appending a sample, and that method would automatically increment sample_counter. Again, though, if you used a std::vector, you wouldn't need such a complication, since the vector's size would serve that purpose.


Threading structure
I rather dislike the overall structure of the code. Rather than having two threads contending over a single location where the current estimate of \$\pi\$ is stored, I'd rather have the calculator thread compute successive approximations, and write them to a queue. The display thread would then wait on value to show up in the queue, display it, and repeat. The locking and such should be in the queue itself.
You've also created not just one, but two secondary threads. There's no real point in this. You started with the process' primary thread, then all it does is create two other threads, then wait for them to finish. It might as well do something useful, and only create one other thread.
Formula
It seems to me that if you're going to try to make it faster, you could at least do a minor improvement to the formula. One that's quite a bit faster, and still utterly trivial (in fact, arguably simpler than the plain Leibniz formula) is:
\$ {\pi \over 4} = {\sum_{n=0}^{\infty} {2 \over (4n+1)(4n+3)}}\$
Summation
This does have one interesting twist: if you just use a naive summation over this formula, you'll find that it "gets stuck"--with a typical double, no matter how many iterations you do, it will only ever get about 8 digits correct.
The problem is that you have a number of relatively large magnitude, and you're trying to add numbers of relatively small magnitude to it. Each of them individually is too small to affect the larger number, so it remains constant.
In this case, there's a pretty simple cure: start from the smallest numbers, and work your way toward larger numbers. That way, the sum you have and the amount you're adding to it each time have closer to the same magnitude, so more terms continue to improve the overall result.
For this particular program, that has a bit of a problem though: since we're trying to display the approximation as it gets better over time, we want approximations that actually do get better over time--and if we start from the smallest, and sum toward the largest, our approximation is truly terrible for almost the entire time, then at the very end, the last few iterations suddenly make it a lot better in a hurry.
As a compromise, we can take a middle ground: work from beginning to end, but work in "chunks" of (say) 10'000'000 terms, so we have an overall estimate, and we have a temporary sum of only the most recent terms. At the beginning of each iteration of the inner loop, we start over from a value of 0.0, so we don't have a drastically larger term dominating when we do the addition. Then when we've added those terms together, we add the result to the overall estimate.
This also works nicely with updating the display--each time we add an intermediate value to our overall estimate, we can send the result out to be displayed.
Portability
I've left out the asynchronous keyboard reading, so the code can be portable. I'd rather use an even better formula than just let one that converges extremely slowly run for weeks on end (and then add non-portable code to let them quit more easily when they get bored).
Code
So, doing things this way, we could end up with code on this general order:
#include <iostream>
#include <iomanip>
#include <deque>
#include <mutex>
#include <thread>
#include <condition_variable>

namespace concurrent {
    template<class T>
    class queue {
        std::deque<T> storage;
        std::mutex m;
        std::condition_variable cv;
    public:
        void push(T const &t) {
            std::unique_lock<std::mutex> L(m);
            storage.push_back(t);
            cv.notify_one();
        }

        // This is not exception safe--if copying T may throw,
        // this can/will lose data.
        T pop() {
            std::unique_lock<std::mutex> L(m);
            cv.wait(L, [&] { return !storage.empty(); });
            auto t = storage.front();
            storage.pop_front();
            return t;
        }
    };
}

int main() {
    concurrent::queue<double> values;

    auto t = std::thread([&] {
        double pi4 = 0.0;
        for (double n = 0.0; n < 8'000'000'000.0; n += 10'000'000) {
            double temp = 0.0;
            for (double i = 0; i < 10'000'000; i++)
                temp += 2.0 / ((4.0 * (n + i) + 1.0) * (4.0 * (n + i) + 3.0));
            pi4 += temp;
            values.push(4.0 * pi4);
        }
        values.push(-1.0);
    });

    double pi;
    while ((pi=values.pop())> 0.0)
        std::cout << "\r" << std::setw(11) << std::setprecision(11) << std::fixed << pi;
    t.join();
}

On my machine, this calculates Pi to 10 places in about 45 seconds. Unless your computer is quite old/slow (like mine is) it'll probably run faster than that for you.
On the other hand, for watching the value converge, this does have kind of the opposite problem: it finds around six or seven digits nearly instantly, then grinds for a long time to a few more. Visually, some might find the Leibniz formula more appealing for the fact that it goes first above, then below, then back above, below again, and so on as it approaches the true value of Pi (though that's more apparent if you draw a graph rather than just printing out the values).


Handling newly devices added to or removed from a list

Detecting changes

What you need is an ObservableCollection:

  Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.

Your code is very short so there is not much to comment on but there is one more thing that you can improve.

dfuDevices.Except(Devices).AsParallel().ForAll(device => {
    if (device.GetType() == typeof(DFUDeviceModel)) {
        OnDfuDeviceDetected(device);
    }
});

You can simplify this by using the OfType<T>() extension that

  Filters the elements of an IEnumerable based on a specified type.

dfuDevices
    .Except(Devices)
    .OfType<DFUDeviceModel>()
    .AsParallel()
    .ForAll(OnDfuDeviceDetected);


Script to remove .vb files from a directory

You could combine expression vs. command mode in PowerShell, process only files (!$_.PSIsContainer) and use regex instead of ChangeExtension:

gci -include *.vb -Recurse |
    ? { (!$_.PSIsContainer) -and (Test-Path ($_.FullName -replace "\.vb$", ".cs") } |
    % { rm $_ -force }


It's hard to beat the performance of standard Excel WorksheetFunctions.
This will find the matches.

  Range("M4:M6525").Formula = "=IF(ISNA(MATCH(J4,$K$4:$K$6525,0)),"""",INDEX($K$4:$K$6525,MATCH(J4,$K$4:$K$6525,0), 1))"

Then if you want to remove the formulae use this

  Range("M4:M6525").Value =Range("M4:M6525").Value


Generally, it is a good idea to separate your view logic from your business logic, e.g your data access.

The code you've presented is procedural, and whilst there's nothing wrong with that at this stage, it could become unsustainable in terms of future maintainability.

One thing that I am conscious about, is that you are directly plugging variables into your SQL query that you are constructing: there is a risk of SQL injection. I would suggest that you wrap your variables with sqlite_escape_string before placing them into your query. I note that you might want to look into PDO for database portability and a 'better' layer between your application and the database.

You seem to be be using strpost to ascertain whether a manufacturer was 'All'. I would suggest doing the following:

$whereSubClause = array();

/* Firstly identify if we have 'All' as the manufacture -
 * if we do, we don't need to add constraints to the query.
 */
if ( 'All' != $manufacturer ){

  $mfg = sqlite_escape_string($manufacturer);
  $whereSubclause[] = "`Manufacturer` = {$mfg}";

}

if ( 'Any' != $model ){

    $model = sqlite_escape_string($model);
    $whereSubclause[] = "`Model` = {$model}";

}

if ( 'Any' != $forsale ){

    $forSale = sqlite_escape_string($forsale);
    $whereSubclause[] = "`ForSale` = {$forSale}";

}

// We can now safely construct the SQL --
// I haven't provided the method for this, but you'd end up with:

$query = "SELECT * FROM `vehicles` WHERE (`Manufacturer` = 'AMG') AND (`Manufacturer` = 'AMG') AND (`ForSale` = '1')"

I would then personally output the data into an array, which can then be passed to a view. Using a foreach loop, I would construct the rows in the table.


1: You can replace:

$sSrc = (substr($sSrc,-1)=='/' ? substr($sSrc,0,-1) : $sSrc);
$sDst = (substr($sDst,-1)=='/' ? substr($sDst,0,-1) : $sDst);

with:

$sSrc = rtrim($sSrc,'/');
$sDst = rtrim($sDst,'/');

2: I would prefer the use of more normal variable names. There's no reason to use $blnKeepPerm if you can be clearer $copyPerms.

3: There is some repetition in your code.

4: The use of $blnRetval leads you to execute stuff after a failure.

In all there's really nothing wrong with this function, but it could be written more clearly. I'll give it a try:

function copyDir($sourceDir,$destDir,$copyPerms = FALSE)
{
  // cleanup
  $sourceDir = rtrim($sourceDir,'/');
  $destDir   = rtrim($destDir,'/');
  // protect
  if (!is_dir($sourceDir)) return FALSE;
  // check destination dir
  if (!is_dir($destDir))
  {
    // create directory
    $permissions = $copyPerms ? fileperms($sourceDir) : 0777-umask();
    if (!@mkdir($destDir,$permissions,TRUE)) return FALSE;
  }
  // copy files and directories recursievely
  foreach (scandir($sourceDir) as $fileName)
  {
    // do not copy current or parent directory
    if (!in_array($fileName,array('.','..')))
    {
      $sourcePath = "$sourceDir/$fileName";
      $destPath   = "$destDir/$fileName";
      // is it a file?
      if (!is_dir($sourcePath))
      {
        // oopy file
        if (!@copy($sourcePath,$destPath)) return FALSE;
        if ($copyPerms) && !@chmod($destPath,fileperms($sourcePath))) return FALSE;
      }
      // copy directory, here we recurse
      elseif (!copyDir($sourcePath,$destPath,$copyPerms)) return FALSE;
    }
  }
  return TRUE; // success!
}

I kept your code virtually intact. However, you can find other solutions online:

https://stackoverflow.com/questions/5707806/recursive-copy-of-directory

https://stackoverflow.com/questions/2050859/copy-entire-contents-of-a-directory-to-another-using-php

and many more.


Rather than swapping out the entire JFrame for another on the button click, you should simply be updating the contents.  This is all very overwrought.  I think all you really need is a panel with a button and a label.  Click the button, and display the results in the label.
Related to the above, rather than overriding paint, you should be using a layout and adding subcomponents.

To get you started:

public class DicePanel extends JPanel {
  private final Dice dice;

  private JButton rollButton;
  private JLabel displayLabel;

  public DicePanel(Dice dice) {
    this.dice = dice;

    rollButton = new JButton("Roll");
    displayLabel = new JLabel();

    rollButton.addActionListener(e ->
      displayLabel.setText("You rolled a: " + dice.roll())
    );
    // or if you're not using Java 8, you can do the more verbose thing.

    // not specifying a layout defaults to a flow layout.  Set a layout via:
    // setLayout(new BorderLayout()); // or whatever
    add(rollButton);
    add(displayLabel);
  }
}

Your program should just create a Dice, create a DicePanel with that, and stick it in a JFrame and show it.  Then play around with layouts to get something you like.


One issue I always come across when implementing this myself is that keys can contain .. But your code simply concatenates nested keys together, your flattener function will not correctly represent the object it just flattened. You'll have to find a way to tell a valid . from a . that was part of the key.

While Object.keys() is a really handy function to get the object keys, you're effectively creating an array with it. Same goes for forEach's callback, you're creating the callback function. For larger objects, you easily generate lots of objects this way. This can cause the GC to kick in more frequently, causing things like jerky scrolling, UI freezing, animation hitching. I recommend using plain for-in loops once you start seeing these issues.

Also, your code overcomplicated itself. At every node, your function is generating a flat object, and its return is merged to the parent node's flat object. Theoretically, this is how things are done in a "functional" manner - create, never mutate. But this becomes very impractical, you're building throw-away objects. What you could do is create just one object. Then as you traverse through the tree, just append to it. To the outside world, the function is still pure even if its implementation isn't.

For instance, your code could have been as simple as this (ignoring the . in key issue):

const dict = {
    "Key1" : "1",
    "Key2" : {
        "a" : "2",
        "b" : "3",
        "c" : {
            "d" : "3",
            "e" : "1"
        }
    }
}

const flatten = (source, parentPath = '', target = {}) => {

  for(const key in source){
    // Construct the necessary pieces of metadata
    const value = source[key]
    const path = parentPath ? `${parentPath}.${key}` : key

    // Either append or dive another level
    if (typeof value === 'object'){
      flatten(value, path, target)
    } else {
      target[path] = source[key]
    }
  }

  return target
}

// To the outside world, you pass in dict, and you get a new object.
// No side effects happen, we're all good.
console.log(flatten(dict))


Style

Use CamelCase only. last_status -> lastStatus, site_json -> siteJSON, etc.
Even in constants. UP -> Up or StatusUp, etc.
Imports are usually split into groups by source, so separate memcache from stdlib with a newline.
Stuttering. E.g. configuration := Configuration{} could be c := Configuration{}.
People would search for main() in main.go. So I would rename monitor.go to main.go.

Code

file, _ := os.Open(path)

I see you skip error handling in some places. I'm not sure whether this is just a brief version for this site, or an actual code, but this is a very bad practice.

v.last_status == 2

if (err == nil) && (resp.StatusCode == 200) {

Avoid magic numbers. Use Up/StatusUp and http.StatusOK respectively.

for i := 0; i < len(sites); i++ {

I'd use range. In Go 1.4 it'll be legal to write for range sites as well.

site := sites[res.url]
if site.last_status != res.status {
    sites[res.url].last_status = res.status
}

You index the map twice and make an unnecessary comparison. Wouldn't sites[res.url] = res.status do?

Architecture

If you can change the output JSON format, I'd suggest saving the status code returned by http.Get rather than a simple bool. That will give you more info on why the site is down (4XX and 5XX error) or that the site have moved (3XX).

  I have attempted to do this concurrently using go routines but I'm concerned about my synchronization step.

Your synchronisation seems mostly fine to me. (Don't forget to test with -race though). An alternative would be to use sync.WaitGroup and a map with a sync.Mutex.


Print a random anagram of a given string

When building a string you should build a list, and then use ''.join(). This is as strings are immutable, and so generating newWord takes \$O(n^2)\$ time.
You are mannually poping pos from value. If you change value to a list, you can just use list.pop.
You should import random at the top of your code. Never in a function.
Common Python style is to use snake_case for variables.
Common Python style is to use _ as a throw away variable.
You can use random.randrange, rather than randint
It's best if you return rather than print your anagram.

And so you could use:

def anagram(value):
    new_word = []
    value = list(value)
    for _ in range(len(value)):
        pos = random.randrange(len(value))
        new_word.append(value.pop(pos))
    return ''.join(new_word)

This however runs in \$O(n^2)\$ time. If you use a Fisher–Yates shuffle, you can do this in \$O(n)\$ time.

def anagram(value):
    value = list(value)
    for i in range(len(value)):
        pos = random.randrange(i, len(value))
        value[i], value[pos] = value[pos], value[i]
    return ''.join(value)

You can also use random.shuffle, which likely also uses the above algorithm. However you won't have to maintain it. Allowing:

def anagram(value):
    value = list(value)
    random.shuffle(value)
    return ''.join(value)


Even though your prime number generator is not the bottleneck, you should not do this:

for (int i = 2; i <= Math.Sqrt(max); i++)
                     ^^^^^^^^^

Do not calculate the same square root in every loop iteration. Sqrt is an expensive enough operation that you don't want to call unnecessarily. Calculate it only once, store that in a variable and use that in the loop.

I couldn't completely analyze your algorithm, but I ran through the first few steps with the debugger. It looks like you're doing a lot of unnecessary work.
For each prime, you start by looking for a sum of length 1, then length 2, then 3, etc. Even if you have already found a sum of length 100, you always start at 0 again. I'm guessing that's where your bottleneck is.
You want to find the longest anyway, so why not start at the maximum length and shorten it as you go? You can stop as soon as you find one. (there are a lot more possible sums of length 2 than of length 500)

My algorithm works like this:
We have a sum of primes: p(1), p(2), p(3), ... p(n-1), p(n)
See if this sum is a prime also (by doing a binary search on the prime numbers)
If it's not, check the next sum of the same length by substracting p(1) and adding p(n+1). Keep doing this until we find a prime or until the sum becomes greater than 1000000.
Then, shorten the length by 1 by subtracting the last prime, so we get the sum p(1),p(2),p(3)...p(n-1) and check each sum of this length, etc.
(This code is a few years old and might still be a little sloppy)

public int Solve050() {
    const int Limit = 1000000;
    int[] primes = WhateverPrimeGenerator.PrimesUpTo(Limit).ToArray();
    int sum = 0, length = 0;
    //Find the maximum possible length by adding up primes, while sum < Limit
    while (sum < Limit) {
        int newSum = sum + primes[length];
        if (newSum >= Limit) break;
        sum = newSum;
        length++;
    }

    int answer = 0;
    for (; length > 1; length--) {
        answer = FindPrime(primes, Limit, sum, length - 1);
        if (answer > 0) break;
        sum -= primes[length - 1];
    }
    return answer;
}

 //Tries to find a prime of sum-length defined by lastIndex
private static int FindPrime(int[] primes, int maxSum, int sum, int lastIndex)
{
    int result = 0;
    int index = lastIndex + 1;
    for (int firstIndex = 0; lastIndex < primes.Length && sum <= maxSum; firstIndex++, lastIndex++) {
        index = Array.BinarySearch(primes, index, primes.Length - index, sum);
        if (index > 0) result = primes[index]; //Prime found
        if (index < 0) index = ~index;
        sum = sum - primes[firstIndex] + primes[lastIndex + 1];
    }
    return result;
}


This is not a real answer, but it is too long to be a comment.

I would be very lazy, in this case, and define the language at a global level. You could even make it a constant, because it probably won't change during the running of the script. If you want to keep language setters and getters in every object then I would indeed use a parent class for that.

I also wonder if you reconnect to the database for every query? That's very inefficient. I hope you reuse the connection. Also, even though the variables are not under user control, I would, as a habit, use parameter binding in queries, for security reasons. Better use it too often than too little.

Also try to use sensible names for your variable and field names. The use of 'current' in some, and not in others, seems weird. Remember, they are always 'current' when used. Names have to make sense. Just remove the word 'current' everywhere and it's fixed.


Adding groups to ListView depending on the data in a list

It's possible with the help of LINQ to reduce your code to this (assuming, of course, the version of .NET you're using will allow it):

private void FeedDataToPane(IEnumerable<Assignment> assignmentList)
{
    MonitorPane.BeginUpdate();
    MonitorPane.Groups.Clear();
    MonitorPane.SmallImageList = imageList;

    assignmentList
        .GroupBy(assignment => assignment.Time, CreateListViewGroup)
        .ToList();

    MonitorPane.EndUpdate();
}

private static ListViewGroup CreateListViewGroup(TimeSpan time, IEnumerable<Assignment> assignments)
{
    var group = new ListViewGroup(time.ToString());
    MonitorPane.Groups.Add(group);

    foreach (var assignment in assignments)
    {
        var item = new ListViewItem(assignment.Type, assignment.ImageIndex, group);
        item.SubItems.Add(assignment.Description);
        MonitorPane.Items.Add(item);
    }

    return group;
}


A simple each loop could make your code smaller, something like:

var elems = [
  $('#slides'),
  $('#rev_slider_2_1'),
  $('#clients')
];

$.each(elems, function (index, $elem) {
  var previous = index > 0 : elems[index-1].id : null;
  var next = index < elems.length-1 ? elems[index+1].id : null;
  $elem.on('mousewheel', function(event) {
    event.preventDefault();
    if (event.originalEvent.wheelDelta >= 0 && previous) {
        //console.log('Scroll up');
        goTo(previous);
    } else if (next) {
        //console.log('Scroll down');
        goTo(next);
    }
  });
});


Don't repeat element IDs. What you want is a data-* attribute, e.g. data-property. Or you could use class names, since those can repeat and you'll want to style things anyway. Of course, you could also build your elements as needed.
Use CSS classes properly. If you've set the containing DIV's class, you just need to write your CSS to automatically style its descendants properly, instead of setting a class like redtext. While you're at it, don't use an element name in your class names. If you want target a specific tag a selector like div.green is what you need, in which case the class name would just be green. However, green is problematic too; you're not saying it should be green, you're saying that that index/stock is up or rising. So name your classes that; i.e. name them something semantically appropriate.
It'd be simpler to first collect all the symbol names, and then query Yahoo once for all of them, instead of firing off queries one at a time.
Use $.getJSON's ability to accept a data object, rather than manually creating a query string

For instance, you could use this HTML (repeat as needed, unless you want to simply build it in JS):

  S&amp;P 500

and this CSS:

.symbol { /* basic styling */ }

.symbol.up { /* styling for a symbol that's "up" */ }
.symbol.up .change { /* styling for the change span */ }

.symbol.down { /* styling for a symbol that's "down" */ }
.symbol.down .change { /* styling for the change span */ }

As for the JavaScript

var elements, symbols, query;

// get the elements
elements = $(".symbol");

// get the symbols and join them to a comma-separated string
symbols = elements.map(function () {
    var symbol = $(this).data("symbol")
    return "'"+symbol+"'";
}).toArray().join(",");

// get the quotes
$.getJSON("http://query.yahooapis.com/v1/public/yql", {
    format: "json",
    diagnostics: "true",
    env: "http://datatables.org/alltables.env",
    q: "select * from yahoo.finance.quotes where symbol in (" + symbols + ")"
}, function (data, xhr, status) {
    // TODO: sanity checking of the data
    data.query.results.quote.forEach(function (quote) {
        var element = elements.filter("[data-symbol='"+quote.Symbol+"']:first");
        if(/^\+/.test(quote.PercentChange)) {
            element.addClass("up");
        } else {
            element.addClass("down");
        }
        element.children("[data-property]").each(function () {
            var child = $(this),
                prop = child.data("property");
            child.text(quote[prop]);
        });
    });
});

Here's a jsfiddle

Of course, a much simpler approach would to be build elements as needed. Keep the CSS but remove all the HTML (except the indices div, just so we have a place to put stuff) in favor of letting your JS do the work of setting it all up.

var symbols = ['^GSPC', '^NDX', 'GLD', 'SLV', '^N225', '^FTSE'],
    properties = [
        { classname: 'name', property: 'Name' },
        { classname: 'result', property: 'LastTradePriceOnly' },
        { classname: 'change', property: 'Change' }
    ];

function buildElement(quote) {
    var container = $("

").addClass("symbol");
    properties.forEach(function (prop) {
        var child = $("").addClass(prop.classname);
        child.text(quote[prop.property]);
        container.append(child);
    });
    if(/^\+/.test(quote.PercentChange)) {
        container.addClass("up");
    } else {
        container.addClass("down");
    }
    return container;
}

$.getJSON("http://query.yahooapis.com/v1/public/yql", {
    format: "json",
    diagnostics: "true",
    env: "http://datatables.org/alltables.env",
    q: "select * from yahoo.finance.quotes where symbol in ('" + symbols.join("','") + "')"
}, function (data, xhr, status) {
    // do some sanity checking of the data here
    var elements = data.query.results.quote.map(buildElement);
    $("#indices").append(elements);
});

Here's a jsfiddle of that.


Parens

When you call a function you do not need to place the argument in parens:

Instead of:  readNumerals(line)
       Use:  readNumerals line

Error Handling

In Haskell we use types like Either or Maybe to indicate errors. Instead of:

let nums = readNumerals(line)
if errorNum `elem` mums
  then ...some error...
  else ...

You should define readNumerals to have this type:

readNumerals :: String -> Maybe [Numeral]

and write:

case readNumerals line of
  Nothing -> ... some error ...
  Just ns -> ... parse was valid, numerals are in `ns` ...

data Numeral

The data structure Numeral has many fields which are redundant. For instance, if n is a Numeral and numeralValue n is 1, then it will always be the case that numeralSymbol n will be I and subRules n will be ['V','X']. So there's no point storing these in the record - you can just implement these as functions:

subRules :: Numeral -> [Char]
subRules n = case numeralValue n of
                1  -> ['V','X']
                5  -> []
                10 -> ['L', 'C']
                ...

This allows you to eliminate the subRules field from the record.

Make Numeral an ADT

In fact, Numeral doesn't even need any fields. Here's a simpler way to implement Numeral:

data Numeral = I | V | X | L | C deriving (Show, Eq)

numeralValue :: Numeral -> Int
numeralValue I = 1
numeralValue V = 5
...

subRule :: Numeral -> [Numeral]
subRule I = [V, X]
subRule V = []
...

The nice thing is that the code for getValue doesn't change at all. The function subRuler does change a little (and also becomes simpler):

subRuler :: [Numeral] -> [Numeral] -> Bool
subRuler [] _ = False
subRuler _ [] = False
subRules as bs = (head bs) `elem` as

Avoid using head

head is a partial function - i.e. it could throw an error. Here's how to write subRuler without using head:

subRules [] _ = False
subRuler _ [] = False
subRuler as (b:_) = b `elem` as

We've replaced head with pattern matching, and it does the same thing. tail is also a partial function which you should replace with pattern matching.