Assigning defaults for Smarty using object-oriented style

Well, there's a few things wrong here, but let's go over it together and I'll try to steer you in the right direction. Let's start with globals. Globals are extremely bad and should be avoided at all costs. If you have a variable that needs to be available in multiple parts of your script, then you should pass that variable as a parameter to whichever function needs it, and return the modified version if applicable. Why? Well globals are an old feature that have been proven to be full of all kinds of security issues. Not to mention they are just plain impossible to track. Sure, I know where $Smarty came from because I saw you define it in your constructor, but lets say I'm pages into your code and see that for the first time. How am I to know where this came from? Hopefully PHP will deprecate this soon, but until then, just take my word, and that of the entire community's, and don't use globals.

Lets take a look at your constructor. First you should know that the access parameter (public, private, or protected) should be used on every function, more accurately known as a method. This includes the constructor. By default it uses the public status, but I've heard rumors of this getting deprecated soon and it is better to go ahead and assume the default won't always be there for you. Besides, its always a good idea to explicitly define what you expect a method or property's access type to be. Second, the proper way to make a constructor is no longer to create a method with the same name as the class. This used to be the case in PHP 4 I think, but it is now deprecated. It still exists for backwards compatibility, but there's no saying how long that will last. Use the magic method __construct() instead. Magic meaning reserved.

So, let's review. Globals are bad, constructors are built with __construct(). How then do we create a class where we have a "global" variable created in the class contructor? Well like this:

private $smarty;

public function __construct() {
    $this->smarty = new Smarty();
}

You'll notice there's a couple of new things going on here. Hopefully you'll also notice how much cleaner this is. So, what's private $smarty? Its pretty much the same as global $smarty, except the variable isn't available globally, only within the class scope ($this->smarty). If we set the access parameter to public, it would be a little more like a global in that we could access it outside of the class, but in order to do so we would have to use an instance of the class like so: $template->smarty. That's because the variable, or, more accurately property, is associated with that class. The reason we are using a private access type her is because $smarty defines an interior "property" that should only be accessed from within the scope of the class. Sorry I can't explain that any better. Look at it like this. If I created a user class, I wouldn't want the password database to be "public" and available outside of the class. It is sort of the same here, except without sensitive data in the mix.

Let's continue. Next is a static display() method. Static methods exist for no other purpose than to defy OOP. Some might argue that I'm wrong here, but let's break down that acronym. Object Oriented Programming. About the only thing static still has in common with OOP is that it is vaguely related to an object. The inner principles of OOP (encapsulation, inheritance, and polymorphism) are simply ignored by static methods. In a lot of cases you'd be better off with just a normal helper function. Assume you won't ever need static methods for the time being. It is an advanced feature of classes and isn't likely to be necessary until you have a better grasp on the whole concept. Instead, what you should do is drop the static keyword and use the class property like it was meant to be.

public function display( $filename ) {
    $this->smarty->display( $filename );
}

Now, you may have started noticing a pattern here. Each of these new methods I have showed you are simply wrappers for the Smarty class. And that is because you are not doing anything yet that requires "extending" the Smarty class. From what I can see, you would be better of just using the smarty class directly and dropping classes altogether. But hopefully the above helped explain some of the basic concepts for you so that when you do decide to start using OOP, you have a better grasp of it.

EDIT

Oh, and about your problem. The above should help you with the structure, but until you start getting into the more advanced stuff (frameworks and autoloading), this is the best solution. At least as far as I know. The only improvement I would make is to use an absolute path name instead of relative, and you can do that using the magic constant __FILE__.


Counting penalties for each player by joining tables, where some of the data is null

You should stay away from pre-ANSI92 join syntax, as it is more error-prone and more difficult to read. It's better to use explicit join syntax in all cases.

This join:

from players, penalties
where players.playerno = penalties.playerno

Should be written as:

from players
join penalties
  on players.playerno = penalties.playerno

The primary reasons for this are:

Avoid accidental cross/Cartesian joins if you forgot a WHERE clause.
Easier to read, since your join conditions are isolated in the ON clause instead of being mixed in with your filtering criteria in the WHERE clause.

Use meaningful table aliases to shorten column references. For instance, players AS ply and penalties AS pen would make for good aliases. Do avoid using single-letter aliases like p though, for readability.

select ply.playerno, ply.name, count(pen.playerno)
from players AS ply
left join penalties AS pen
...

Use vertical white space (i.e. new lines) to make statements, in particular SELECT clauses, easier to read:

select
    ply.playerno,
    ply.name,
    count(pen.playerno) as `Penalty count`
from ...

MySQL uses all lowercase for all table, columns, etc. identifiers, so using UPPER CASE for keywords makes it easier to tell SQL keywords from identifiers. Also, name is a reserved SQL keyword, so when you have a column called name (or any other SQL keyword) it should be quoted with back-ticks like:

SELECT ply.playerno, ply.`name` FROM players AS ply

There is a much simpler way to aggregate this than how you have done it, with no need for a nested sub-query with an additional join. COUNT(), like other SQL aggregate functions, will take care of handling potentially NULL aggregates to zero, as long as they are included in the query (in this case by using LEFT JOIN instead of INNER JOIN), so we can get the same result much more simply like this:

SELECT
    ply.playerno,
    ply.`name`,
    COUNT(pen.playerno) AS `Penalty count`
FROM players AS ply
LEFT JOIN penalties AS pen
    ON ply.playerno = pen.playerno
GROUP BY
    ply.playerno,
    ply.`name`
ORDER BY
    ply.playerno;


Regarding the primary question, your code is very close to being a well-defined function. Simply wrap the entire code in a function, making filename the right argument, fpath the left argument, and allUsed the result like so (with a couple of unreference lines omitted):

 GetAllUsed←{
         filename←⍵
         fpath←⍺
         getxml←{⎕XML⊃⎕NGET ⍵}
         doc←getxml filename
         attrib←↑doc[;4]
         col←{attrib[;(attrib[1;;1]⍳⊂⍵);2]}
         oot←((⍴fpath)↑¨col'fname')∊⊂fpath
         cn←oot/(col'callee_name')
         mn←oot/(col'method_name')
         ∪(⍉↑(cn mn))[⍋cn;]
     }

I cannot envision a scenario where one might not want it as a dyadic function, or where one would want to introduce a global variable of any sort. I prefer the file name as the right argument, leaving the opportunity to make the left argument optional (possibly having it default to the first few path segments of the right arg?)

Regarding the actual code, the biggest issue is that it relies on the set of attributes for each MemberCall element being exactly the same. An additional or missing attribute will cause the code to fail, with an index error most likely, or produce a bad result.

If it is indeed the case that the attribute sets are identical, then a much simpler approach can be taken by restructuring the attributes for all elements into a single matrix of name/value pairs. There is no need to construct a rank-3 array as is done currently.

If this is not the case, then one approach is to define a little getter function that picks out a given attribute for each element. This function can handle the issue of missing or extra attributes, attributes in any order, etc.


Adding elements to a hash from an output

You don't have to write code for testing of key existence because autovivification will do the work for you. So your cycle can be written as simple:

foreach my $line (@data) {
    my ($mac, $ip, $if) = (split /\s+/, $line)[0,1,5];
    push @{$data_str{$if}}, {$ip => $mac};
}

It is good practice to name your data instead of pollute indexes all over your code. It is much better if they are all in one place. Alternative way is:

my ($mac, $ip, undef, undef, undef, $if) = split /\s+/, $line;

which shows line structure visually.

Another thing is your data structure. Why it has hash value which is array of hashes with IP as one key and mac address. This structure is not good to work with. If I would have to find which MAC belong to given IP I would have to write something like

sub get_mac {
    my ($hash, $if, $ip) = @_;
    for my $x (@{$hash->{$if}}) {
       return $x->{$ip} if exists $x->{$ip};
    }
    return ();
}

which is slow and tedious. Much better is construct two level hash:

foreach my $line (@data) {
    my ($mac, $ip, $if) = (split /\s+/, $line)[0,1,5];
    $data_str{$if}{$ip} = $mac;
}

Now if I would like to know MAC of given IP

my $mac = $data_str{$if}{$ip};

Easy and efficient. I still can get all IPs and MACs

my @ips = keys %{$data_str{$if}};
my @macs = values %{$data_str{$if}};

I can also make original pairs out of this structure

my @pairs = map {+{$_ => $data_str{$if}{$_}}} keys %{$data_str{$if}};


mid = (endIndex + startIndex) / 2; may overflow. A canonical idiom is

    mid = startIndex + (endIndex - startIndex)/2;

Allocating (and deallocating) a new temp array in each invocation is a waste of time. Allocate the entire temp once, and pass it down, using same indices as for the actual array. Notice that it also allows to not copying data back from temp to array, which is another waste of time. Instead, ping-pong the arrays' roles.

Of course, it doesn't affect the asymptotic, but should speed it up twofold.
The algorithm looks much more natural with semi-open ranges (that is, end is one after the last element. This will avoid +1 and -1 index corrections, and use < instead of <= to compare indices.


I'd recommend a few things:

PEP8
List comprehensions
str.format
with
Slices

But I'll show how they can make your code nicer.

Using str.format you can easily create name.
Alternately, if you don't want to use str.join:

name = '{} {}'.format(first_name, last_name)
name = ' '.join([first_name, last_name])

Using a list comprehension you can reduce the amount of code to create the rows_data.

rows_data = [row for row in csv.reader(scan)]

Using with you can remove the file.close calls.
This can lead to a very small amount of code to read the rows_data.

with open(class_file_names[int(math_class) - 1], 'r+') as scan:
    rows_data = [row for row in csv.reader(scan)]

I'll touch on PEP8, class_file_names should be all caps, so CLASS_FILE_NAMES as it's a constant.
You should also have a space either side of most operators, the largest exception are commas.

Finally slices makes your x code much easier to read.
To get the first three items in a list you can use list[:3] where for two you can use list[:2].
combining these together you can overwrite your existing scores with ease:

x[:3] = [str(score)] + x[:2]

Also your max code may be wrong as it may use the max from the string representation,
not from what the numbers mean.
And on the second test, you will average as if there has been three tests, where there has been two.

In all I'd use:

CLASS_FILE_NAMES = ['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
FIELDNAMES = ['Student Name', 'Oldest Score', 'Older Score',
              'Latest Score', 'Average', 'Highest']

file_name = CLASS_FILE_NAMES[int(math_class) - 1]
name = '{} {}'.format(first_name, last_name)
with open(file_name, 'r+') as scan:
    rows_data = [row for row in csv.reader(scan)]

with open(file_name, 'w', newline="") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=FIELDNAMES)
    writer.writeheader()
    name_found = False
    for x in rows_data[1:]:
        if x[0] == name:
            x[:3] = [str(score)] + x[:2]
            nums = [int(x) for x in x[:3]]
            x[4] = sum(nums) / 3
            x[5] = max(nums)
            nameFound = True
        writer.writerow({
            'Student Name': x[0],
            'Latest Score': x[1],
            'Older Score': x[2],
            'Oldest Score': x[3],
            'Average': x[4],
            'Highest': x[5]})

    if not name_found:
        writer.writerow({
            'Student Name': name,
            'Latest Score': score,
            'Older Score': '0',
            'Oldest Score': '0',
            'Average': score,
            'Highest': score})

input("Test complete! Press anything to close.")


PHP - using static variables to store "client" for later use

Before going through advises just wanted to remind you can alternatively use Aws\Sdk class as a client factory.
Sample usage:

// The same options that can be provided to a specific client constructor can also be supplied to the Aws\Sdk class.
// Use the us-west-2 region and latest version of each client.
$sharedConfig = [
    'region' => 'us-west-2',
    'version' => 'latest'
];

// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk($sharedConfig);

// Create an Amazon S3 client using the shared configuration data.
$client = $sdk->createS3();

Observe AWS SDK for PHP guide, just in case you hadn't yet.They give a notation there:

  Note

  We highly recommended that you use the Sdk class to create clients if
  you're using multiple client instances in your application. The Sdk
  class automatically uses the same HTTP client for each SDK client,
  allowing SDK clients for different services to perform nonblocking
  HTTP requests. If the SDK clients don't use the same HTTP client, then
  HTTP requests sent by the SDK client might block promise orchestration
  between services.

But, proceeding with your approach, you have a variation of Singleton pattern (restricts the instantiation of a class to a single object, which can be useful when only one object is required across the system).In your case S3Helper acting as a factory producing/returning the same S3Client instance.

To prevent instantiation/cloning of S3Helper from the outer code you can close __construct, __clone (and even __wakeup) methods:

class S3Helper {
    ...
    private function __construct() { }
    private function __clone() { }

To eliminate multiple return statements in your static getClient() method use the following condition (set client if it's not set yet):

private static function getClient() {
    if (self::$client === null) {   # use strict comparison here
        $auth = self::getAuth();
        self::$client = new S3Client([
            'region' => 'eu-west-2',
            'version' => '2006-03-01',
            'endpoint' => $auth['endpoint'],
            'credentials' => [
                'key' => $auth['key'],
                'secret' => $auth['secret']
            ],
            'use_path_style_endpoint' => true
        ]);
    }
    return self::$client;
}


Sum of all possible concatenations of array values

I'm always leery of the claim that problems require brute force algorithms. There is, for example, a formula for directly calculating the Nth Fibonacci number.

In the case of this problem, there is a much simpler way to perform the calculation that does not require O(n^2) time. Each element of the array pairs with every other element exactly twice - once as the most significant part, and once as the least significant part. These two parts can be calculated separately in one pass.

The low part is the sum of the elements times the number of elements.

The high part is the sum of (the "offset" for each element times the sum of the elements). The offset is the digit base raised to the number of digits (expressed generally, but this problem always uses base 10). So for a two digit number (11 or 22) the offset is 100.

function concatenationsSum2(a) {
    var lowSum = 0;
    for (var i = 0; i < a.length; i++)
        lowSum += a[i];

    var sum = lowSum * a.length;

    for (var i = 0; i < a.length; i++) {
        var size = a[i].toString().length;
        var offset = iPower(10, size);
        sum = sum + lowSum * offset;
    }

    return sum;
}

function iPower(base, power) {
    var result = 1;
    for (var i = 1; i <= power; i++)
        result *= base;

    return result;
}

And from there, we can simplify even further by combining the two parts.

function concatenationsSum3(a) {
    var lowSum = 0;
    var offsetSum = 0;
    for (var i = 0; i < a.length; i++) {
        lowSum += a[i];

        var size = a[i].toString().length;
        var offset = iPower(10, size);
        offsetSum += offset;
    }

    return lowSum * a.length + lowSum * offsetSum;
}


You have a few flags (removed, responded) which are almost equivalent and possibly useless. removeListener() won't cause any error if listener has been already removed then removed is unnecessary. After you called removeListener() your callback won't be called then also responded (which BTW is a misleading name) is unnecessary. Also, setTimeout() won't call its callback twice then again responded isn't necessary.

Use const instead of let whenever possible and declare your variables (usually one per line) when you initialize them. In (untested) code:

if (!socket) {
    reject("Socket supplied is not valid.");
    return;
}

if (socket.disconnected) {
    reject("Socket is disconnected");
    return;
}

const timeout = setTimeout(() => {
   socket.removeListener(wait_key, callback);

   if (error_on_timeout) {
       reject("Socket timeout");
   } else {
       resolve(null);
   }
}, max_wait)

const callback = (data) => {
    clearTimeout(timeout);
    socket.removeListener(wait_key, callback);
    resolve(data);
};

socket.on(wait_key, callback);
socket.emit(emit, data)

Few more notes: resolve() and reject() won't stop execution then you need to add the proper return. Use semicolon consistently: someone prefers to avoid semicolon as much as possible, pick a style and use it consistently.


Generic java configuration class with type safety

Generics can only go so far to help you, and, this is one of those times where it just does not help all that much.

In essence, you have the following:

a configuration system where you can get values based on names (a Map).
when you set a value it is for a given type (which is either specified when you set the value, or it is not, in which case it is inferred).
when you get a value, it is matched against the type the getter expects, and, if it matches, it is returned.

Since the getter/setter is the only place where you actually know the type of the value, there is actually zero benefit for your entire Setting subclass... it is redundant. You can get the same behaviour with:

private final Map<String, Object> options;

public DefaultConfiguration() {
    this.options = new HashMap<String, Object>();
}

@Override
public <T> T get(String option, Class<T> type) {
    Object value = options.get(option);
    if (value != null) {
        return type.cast(value);
    }
    return null;
}

@Override
public <T> void set(String option, T setting, Class<T> type) {
    // no point in even checking the type, the generic method will enforce that.
    // this method is essentially redundant, and could be
    //   public void set(String option, Object value);
    options.put(option, setting);
}

@Override
public void set(String option, Object setting) {
    // this essentially a duplicate option.
    options.put(option, setting);
}

here you have the exact same functionality as you did before.... if the user wants to, they can compile-time type-check their values when they set them (by ensusuring the Class<T> parameter matches the T setting value

When they retrieve the value, they can cast the result to the specified type, or return null if it is not castable.

The functionality in MyConfiguration is unchanged, but, I recommend you use constants for the keys:

private static final String SETTINGA = "settingA";
....

Finally, you may want to consider your DefaultConfiguration extending something like HashMap directly.... like:

public class DefaultConfiguration
          extends HashMap<String,Object>
          implements Configuration {

then, remove the options Map variable, and simply have methods like (note the direct get(option) instead of options.get(option):

@Override
public <T> T get(String option, Class<T> type) {
    Setting setting = get(option);
    if (setting != null) {
        return type.cast(setting.getSetting(type));
    }
    return null;
}

Now, when people use your class, they have access directly to the configuration too (with, and without your 'helper' methods).

The bottom line though, is that your implementation does not enforce type-safety between the set and the get. The only thing it does is return null instead of throwing a ClassCastException when people use your code wrong.


Useless code

Currently, your code has some useless parts to it:

You have a set, but you never add anything to it.  When you reach the end of the string, you check your set for it containing something, but it never does.  You can just remove that whole set and do count++ when you reach the end of the string.  The way you are parsing the input, there is no way you can ever reach the same output string more than once.
Your solve() function always returns 0.  And nobody even checks the return value.  So you should make your solve() function return void.

Incorrect answer

Currently, your program will return an incorrect answer if count ever increases past \$2^{31}\$.  The question warned about this, so you should make count be long instead.

Too slow

The problem with your program is that you are just computing the answer in the brute force way, by generating every possible output.  This problem requires a dynamic programming technique to solve faster.  In simple terms, you are solving the same subproblem repeatedly.  If you just remembered the answer for each subproblem you already solved, then things would run much faster.

Here is an example of how I would fix your program to run faster:

import java.util.Scanner;

public class AlphaCode {
    static int n;
    static long [] solved;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            String s = sc.nextLine();
            if (s.equals("0")) {
                break;
            }
            n = s.length();
            solved = new long[n];
            for (int i=0; i<n; i++) {
                solved[i] = -1;
            }
            long ret = solve(s, 0);
            System.out.println(ret);
        }
    }

    private static long solve(String s, int i)
    {
        long count = 0;

        if (i >= n) {
            return 1;
        }

        if (solved[i] != -1) {
            return solved[i];
        }

        for (int j = 0; j < 2 && i + j < n; ++j) {
            int x = Integer.parseInt(s.substring(i, i + j + 1));
            if (x <= 26) {
                count += solve(s, i + j + 1);
            }
        }
        solved[i] = count;
        return count;
    }

}


Adding two numbers as strings from a textfile

Some basic C++ advice:

Don't use using namespace std;. It leads to namespace pollution: it you use another library, you may import names in the global namespace that may clash with those in the std namespace. Anyway, adding std:: in front of the standard library components does not hinder readability.
return 0; at the end of main is useless. If the program reaches the end of main without having encountered any return statement, it will automagically return 0.
You compare signed and unsigned integer values in this line:

for (int i=0; i<line.length(); i++)

That means that you didn't turn on the right compiler flags (-Wall, -pedantic and -Wextra flags that you should almost always use) or that you ignored the warnings. Try never to ignore warnings, they help to write good code. To fix this warning, simply turn int i=0 into std::size_t i=0. Ideally, you should even write typename std::string::size_type i=0 but people generally agree that it is too long, and the main standard library implementations use std::size_t anyway for the length of a string.

The rationale for this warning is that in some cases, the comparison will happen, but small negative integers may be compared to big unsigned integers. On theo ther hand, if you compare unsigned integers with different sizes, you will never have such a problem.
It's really no more than a tidbit, but post-incrementation (++i) may be faster than pre-incrementation (i++). We all know that premature optimization is the root of all evils, but this one is simple enough to write as you go. In other words, you should remember this useful guideline:

  Use ++i if you don't have a specific reason to use i++.

The variable count is never used, you can remove it. You compiler should have told you that it was unused.
Try to organize your headers in alphabetical order:

#include<fstream>
#include<iotream>
#include<string>
#include<vector>

It will help you when you want to check whether a header is already included or not.
If you want to check whether an ifstream was successfully openen, don't use is_open, use operator!:

ifstream myfile("bignum.txt"); //this opens the file bignum.txt
if (not myfile)
{
    // An error occured
    // handle the error
}
// else use myfile

Also, this it not the idiomatic way to read a file line by line:

while (!myfile.eof())
{
    getline(myfile,line);
    // ...
}

Here is how you should do it, std::getline has been designed to be used in such a loop:

while (getline(myfile, line))
{
    // ...
}

Actually, using eof can read past end of file which makes it unsafe to read a file line by line until the end of the file is reached.


overloaded const and non-const class methods returning references in C++

const-version of the method get() returns a copy

Why is this a good thing?

  the non-const method get() is const only by contract, (not checked by compiler)
      harder to get a const-reference, though not impossible

What?

  the const-ness of the const method get() is checked by compiler
      copy of the returned object is controlled by the user

What does it matter if it is const if you have to go to the effort of making a copy.

  requires two const_casts which is hard to read

Really!

PS. getters and setters are an anti pattern (unless you are a container).
Exposing the internal implementation like this tightly couples your class to any code that uses it. This makes modifying your code in the future much harder. It is best to make your methods do the work rather than expose the members and do the work outside the class.

class X
{
     Y   value;

     public:
         // Why over complicate things.
         // This has the same functionality.
         Y&       get()       {return value;}
         Y const& get() const {return value;}
 };

OK so you want the code to get the value in one location:

class Z
{
     Y   value;

     public:
         Y&       get()       {return value;}

         // Only really need one cast.
         // We know that get() is not modifying the object.
         // If it was you can't share functions anyway.
         // Thus it is safe to cast away const-ness before calling get.
         // Because you are returning a const& from this function it is
         // fine and you don't need to add const-ness back anyway.
         Y const& get() const {return const_cast<Z&>(*this).get();}
 };


Long story short: read the style guide.

Imports should be in alphabetical order;
Function names should be lowercase_with_underscores, not mixedCase;
Functions should start with """docstrings""", not # comments; and
Indents should be four spaces, not two.

time.strftime(...) always returns a string (that's what it's for!) so wrapping it in a str call is redundant.

There should be much less code at the top level of your script - move it into an entry point function (e.g. call it main) then guard its call:

if __name__ == '__main__':
    main()

This makes it easier to import the functionality elsewhere later.

if not ''.join(row).strip():
    pass
else:
    rows.append(row)

could be simplified to:

if ''.join(row):
    rows.append(row)

csv.reader already strips newlines, and there's no point including the pass block.

You can (and should!) use os.path.join instead of e.g. script_path + "\\" + csv_file.


Rendering partials dynamically in Rails 3

You can override ActiveModel#to_partial_path if you want - same as how you might override to_param. See the documentation (and be sure to check the source too - they're doing some caching that's elided in the docs, but might be worth looking in to).

Anyway, in your case, you could likely just redefine the method on the User model like so:

# in app/models/user.rb
class User < ActiveRecord::Base
  # ...
  def to_partial_path
    collection = ActiveSupport::Inflector.tableize(self)
    "#{collection}/#{self.role}"
  end
end

This way, you can use render as you would normally. You'll only be doing what Rails is already doing - just a little differently.


Selection and Insertion sorts from scratch in Java

Please try to follow the code formatting conventions of the language that you're using. This makes your code much more readable for other programmers.
If you use a Java IDE like Eclipse, NetBeans or IntelliJ it can format the code for you. In Eclipse this is triggered by pressing Ctrl+Shift+F.

Your use of CamelCase for identifiers is correct but only methods should start with lower case, class names start with a capital letter.

Don't abbreviate english words unnecessarily. Writing insrt instead of insert gains you nothing and makes the code harder to read.

You're defining classes that have the same behavior, so it would be good to define a common interface so you can use them interchangeable.

interface Sort {
    void sort(int[] a);
}

class InsertionSort implements Sort {
    // ...
}

class SelectionSort implements Sort {
    // ...
}

For your print statement you can use StringJoiner. It's specially built for your use case and allows you to specify a delimiter, prefix and suffix.

public static void main(String[] args) {
    Sort ss = new SelectionSort();
    Sort is = new InsertionSort();
    int[] arr = { 2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345 };
    is.sort(arr);
    StringJoiner sj = new StringJoiner(",", "{", "}");
    for (int el : arr) {
        sj.add(String.valueOf(el));
    }
    System.out.println(sj);
}

Since you sort the array in-place (you don't create a new array during sort) for both algorithms you don't have to return the array. The reference that you hold on it outside is enough.

Your Insertion Sort can be simplified by getting rid of the keepGoing boolean.
You move the conditional from the if statement into the head of the while loop.
You want the while loop to continue while a[j] > insrt, no need for an extra variable. Then you move the actual insertion out of the else clause and put it after the while loop.
Your're going to be at the right insertion spot once the while loop has finished.

class InsertionSort implements Sort {

    public void sort(int[] a) {
        int insert, j;
        for (int i = 1; i < a.length; i++) {
            insert = a[i];
            j = i - 1;
            while ((j >= 0) && a[j] > insert) {
                a[j + 1] = a[j];
                j--;
            }
            a[j + 1] = insert;
        }
    }
}

You SelectionSort looks fine to me.


I'll go through your program from top to bottom, mentioning some details.

static void Main(string[] args)
{
    ShowOutput();
    string user_input = UserInput();
    int result = PerformCalculation(InputToList(user_input));
    Console.WriteLine($"{user_input}={result}");
    Console.Read();
}

Starting with the Main method is good practice. The reader gets an overview about what the whole program is supposed to do.

Starting the program with ShowOutput() is confusing. The usual sequence of events is: Input — Processing — Output. By showing the output first, you are reversing this usual sequence of events.

static void ShowOutput()
{
    Console.WriteLine("Enter numbers followed by operation eg. 1+2-4");
}

Instead of ShowOutput this method should better be named ShowPrompt. This is more specific, and prompting the user clearly belongs to the input phase.

static string UserInput()
{
    string User_input = Console.ReadLine();
    return User_input;
}

Typically method names start with a verb, like in ShowOutput above. The method UserInput should rather be called ReadLine since that is exactly what happens here.

static string[] InputToList(string input)
{
    string number1 = "";
    string number2 = "";
    string Oprt = ""; //Mathematical operator
    string[] Arithmetic = new string[3];

Now it is getting more complicated, and inconsistencies appear. Some of your variables start with a lowercase letter, some with an uppercase letter. They should all start with a lowercase letter. That's by convention.

The usual abbreviation for operator is op. The letters prt remind me of the PrtScr key on the keyboard, which means Print Screen.

From reading the code until here, I have no idea what the variable Arithmetic might be. Granted, it's not easy to find a name for it. It could be something like "calculation atoms", "calculation parts", "words", "things", "tokens". When continuing to read the program, a better name might become apparent. This variable should then be renamed.

    int n = 0;
    foreach (char charecter in input)
    {
        int num;
        bool isNumerical = int.TryParse(charecter.ToString(), out num);
        n += 1;
        if (isNumerical)
        {
            number1 += num;
        }
        else
        {
            Oprt = charecter.ToString();
            Arithmetic[0] = number1;
            Arithmetic[1] = Oprt;
            for(int i = n; i <= input.Length - 1; i++)
            {
                number2 += input[i];
            }
            Arithmetic[2] = number2;
        }
    }

This code is long and tricky and fragile. In the upper part you parse number1 until you find a character (not charecter) that is not numeric. In that moment you save the current number1 into the result array. You can be lucky that you do this in exactly this moment, because later the variable number1 will be overwritten again, as soon as the number2 is parsed.

    return Arithmetic;
}

There must be some simpler way of expressing this idea. Imagine you explain this to a human friend. You would hopefully not choose to explain the code above, but some simpler code. To parse an expression that consists of numbers and operators:

parse a number
parse an operator
parse a number
continue with step 2

This is a high-level view on the whole topic of parsing an expression. That's how your code should look. The method should be called TryParseExpr. The current name InputToList is too unspecific.

static int PerformCalculation(string[] Input)

As Zoran already mentioned in his answer, performing a calculation on strings is inefficient and sounds strange. Calculations should be performed on numbers.

Converting the string parts into numbers and operators should be done by the TryParseExpr method I suggested above.

{
    int result = 0;
    switch (Input[1])
    {
        case "+":
            result = Int32.Parse(Input[0]) + Int32.Parse(Input[2]);
            break;
        case "-":
            result = Int32.Parse(Input[0]) - Int32.Parse(Input[2]);
            break;
        case "*":
            result = Int32.Parse(Input[0]) * Int32.Parse(Input[2]);
            break;
        case "/":
            result = Int32.Parse(Input[0]) / Int32.Parse(Input[2]);
            break;
    }
    return result;
}

This style of int result = 0; ...; result = the actual result; ...; return result; leads to long code. In most cases the code becomes easier to understand when the result is not saved in a variable but returned directly. Such as in:

static int Calculate(int left, char op, int right)
{
    switch (op)
    {
        case '+':
            return left + right;
        case '-':
            return left - right;
        case '*':
            return left * right;
        case '/':
            return left / right;
        default:
            throw new ArgumentException($"unknown operator {op}");
    }
}

This is as simple as it gets. There are no unnecessary arrays, and each parameter has the correct data type.

In your original code you suggest to the user that they may enter 1+2-4, but this is something your current code cannot handle. Given the above Calculate method, it's not too difficult to extend the calculation to an arbitrary amount of numbers and operators:

static int Calculate(IReadOnlyList<int> nums, IReadOnlyList<char> ops)
{
    int res = nums[0];
    for (int i = 0; i < ops.Count; i++)
        res = Calculate(res, ops[i], nums[i + 1]);

    return res;
}

In this method the calculation is performed strictly from left to right. The usual operator precedence (* before +) is ignored. That's only for simplicity. It could be added later.

This extended Calculate method can be used like this:

// 1 + 2 - 4
Console.WriteLine(Calculate(new List<int> {1, 2, 4}, new List<char> {'+', '-'}));

Now the remaining task is to let the user enter a line and convert this line into these two lists of numbers and operators. This is the job of a lexer. A lexer takes a string (or another input source) and repeatedly looks at the beginning to split off a small piece of data, such as a number or an operator.

The general idea I outlined above in the 4 steps can be written in C# like this:

public bool TryParseExpr(out List<int> nums, out List<char> ops)
{
    nums = new List<int>();
    ops = new List<char>();

    if (!TryParseInt(out int firstNum))
        return false;
    nums.Add(firstNum);

    while (TryParseOp(out char op))
    {
        ops.Add(op);

        if (!TryParseInt(out int num))
            return false;
        nums.Add(num);
    }

    return true;
}

Each of the paragraphs in this method corresponds roughly to one of the steps from above. Here they are again, for comparison:

parse a number
parse an operator
parse a number
continue with step 2

Now the only missing part are the basic building blocks, TryParseInt and TryParseOp. These I present together with the whole program that I built from your code:

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests
{
    [TestClass]
    public class Program
    {
        [TestMethod]
        public void Test()
        {
            TestOk("1", 1);
            TestOk("12345", 12345);
            TestOk("12345+11111", 23456);
            TestOk("2147483647", int.MaxValue);
            TestOk("1+2+3+4+5+6", 21);
            TestOk("1+2-3+4-5+6*5", 25);

            TestError("2147483648", "2147483648");
            TestError("a", "a");
            TestError("1+2+3+4+5+a", "a");
        }

        static void TestOk(string input, int expected)
        {
            Lexer lexer = new Lexer(input);
            Assert.AreEqual(true, lexer.TryParseExpr(out List<int> nums, out List<char> ops));
            int result = Calculate(nums, ops);
            Assert.AreEqual(expected, result);
        }

        static void TestError(string input, string expectedRest)
        {
            Lexer lexer = new Lexer(input);
            Assert.AreEqual(false, lexer.TryParseExpr(out List<int> nums, out List<char> ops));
            Assert.AreEqual(expectedRest, lexer.Rest);
        }

        static int Calculate(IReadOnlyList<int> nums, IReadOnlyList<char> ops)
        {
            int res = nums[0];
            for (int i = 0; i < ops.Count; i++)
                res = Calculate(res, ops[i], nums[i + 1]);

            return res;
        }

        static int Calculate(int left, char op, int right)
        {
            switch (op)
            {
                case '+':
                    return left + right;
                case '-':
                    return left - right;
                case '*':
                    return left * right;
                case '/':
                    return left / right;
                default:
                    throw new ArgumentException($"unknown operator {op}");
            }
        }
    }

    // The lexer takes a string and repeatedly converts the text at the
    // current position into a useful piece of data, like a number or an
    // operator.
    //
    // To do this, it remembers the whole text and the current position
    // of the next character to read. It also remembers the length of the
    // text, but this is only for performance reasons, to avoid asking for
    // text.Length again and again.
    class Lexer
    {
        private readonly string text;
        private int pos;
        private readonly int end;

        public Lexer(string text)
        {
            this.text = text;
            end = text.Length;
        }

        public string Rest => text.Substring(pos);

        public void SkipSpace()
        {
            while (pos < end && char.IsWhiteSpace(text[pos]))
                pos++;
        }

        public bool TryParseInt(out int num)
        {
            int i = pos;

            // The number may have a single sign.
            if (i < end && (text[i] == '-' || text[i] == '+'))
                i++;

            // After that, an arbitrary number of digits.
            while (i < end && char.IsDigit(text[i]))
                i++;

            // The TryParse handles the case of too many digits (overflow).
            bool ok = int.TryParse(text.Substring(pos, i - pos), out num);
            if (ok)
                pos = i;

            return ok;
        }

        public bool TryParseOp(out char op)
        {
            if (pos < end)
            {
                switch (text[pos])
                {
                    case '+':
                    case '-':
                    case '*':
                    case '/':
                        op = text[pos];
                        pos++;
                        return true;
                }
            }

            op = '\0';
            return false;
        }

        public bool TryParseExpr(out List<int> nums, out List<char> ops)
        {
            nums = new List<int>();
            ops = new List<char>();

            if (!TryParseInt(out int firstNum))
                return false;
            nums.Add(firstNum);

            while (TryParseOp(out char op))
            {
                ops.Add(op);

                if (!TryParseInt(out int num))
                    return false;
                nums.Add(num);
            }

            return true;
        }
    }
}

You can play around with this code by adding more and more test cases. There's also a method called SkipSpace that is currently unused. To allow the user to enter 1 + 2 - 4 as well, your parsing code should skip the space before and after each number or operator.


Using Data.Array to solve Sierpinski in Haskell

// is best called with one bulk list because each call incurs one O(n) array copy.

Folds over iterates when you need an index and know its range, it's like for vs. while.

drawCanvas :: Canvas -> IO ()
drawCanvas = putStrLn . unlines . map (map snd)
  . DL.groupBy ((==) `DF.on` fst . fst) . DA.assocs

mkSierpinski :: Int -> Int -> Canvas
mkSierpinski maxLevel sierLevel = emptyCanvas maxLevel DA.//
  [ ((r+h, j), '1')
  | maxLevel >= sierLevel
  , (r, c) <- DF.foldrM split (0, 0) [maxLevel-sierLevel+1..maxLevel]
  , h <- [0..2^(maxLevel-sierLevel)-1]
  , j <- [c-h..c+h]
  ]


I added some comments to your code. I haven't tested anything, but that's the first things I would do to optimize your code. Under Linux, if you compile with g, you can use perf top to see live where your code takes time.
Good luck!

Module smearingmodule
IMPLICIT NONE
contains
subroutine smearing(i, nMCd, nPeriodT, nPeriods, DF, theta, wm) bind(C, name="smearing_")
    use, intrinsic                         :: iso_c_binding, only : c_double, c_int
    integer(c_int), intent(in)                                 :: i, nMCd, nPeriods
    integer(c_int), intent(in), dimension(nPeriods)            :: nPeriodT
    real(c_double), intent(in), dimension(i,5)        :: DF
    real(c_double), intent(in), dimension(i,nMCd)     :: theta
    real(c_double), dimension(nMCd, nPeriods), intent(out)  :: wm
    integer                                             :: d

!   To use more efficiently vectorization in the subsmearing sburoutine,
!   DF(:,4), theta(:,d) and DF(:,1) need to be 256-bit aligned.
!   This can be done by :
!   1) Setting the size of the 1st dimension of DF and theta to a multiple of 4
!      double-precision elements (padding at the end of each column)
!   2) Forcing the arrays to start at the proper alignment. With the
!      ifort compiler, this can be done after the allocation using
!      !DIR$ ATTRIBUTES ALIGN : 32 :: DF, theta
!
    do d=1,nMCd
    ! * Now you have to pass the physical sizes of the arrays DF and
    !   theta because they don''t correspond to the logical size
    !   because of the padding
    ! * If you can, use wf dimensioned as (nPeriods,nMCd) to avoid
    !   the implicit matrix transposition in (d,:)
        CALL subsmearing(d, i, nMCd, nPeriodT, nPeriods, DF, theta, wm(d,:))
    end do

end subroutine smearing

subroutine subsmearing(d, i, nMCd, nPeriodT, nPeriods, DF, theta, wm)
    integer, intent(in)                                 :: d, i, nMCd, nPeriods
    integer, intent(in), dimension(nPeriods)            :: nPeriodT
    double precision, intent(in), dimension(i,5)        :: DF
    double precision, intent(in), dimension(i,nMCd)     :: theta
    double precision, dimension(nPeriods), intent(out)  :: wm
    double precision, allocatable, dimension(:,:)       :: out
    double precision, dimension(i,8)                    :: bigDF
    double precision, dimension(i)                      :: epredC, epredT, diff, A1, A2
    double precision, dimension(i,i)                    :: B1, B2
    integer                                             :: j, Period, jj
    double precision                                    :: sumWeights

!   In general, put explicitly the boundaries in your array syntax. This
!   makes the code more explicit and in case the physical dimensions
!   don''t correspond to the logical dimensions (because of padding for
!   instance), your code will be more robust.

    diff = 0.0d0
    wm = 0.0d0

!   1) Use 1.d0 insetad of 1 to avoid conversion
!   2) Remove array syntax here so that DF streams only once through the CPU
!     epredC = 0.d0
!     epredT = 0.d0
!     do k=1, i ! and not size(DF,1) because of padding
!      epredC = epredC + exp(DF(k,4) + (theta(k,d) * DF(k,1)))
!      epredT = epredT + exp(DF(k,4) - (theta(k,d) * (1.d0-DF(k,1))))
!     end do
    epredC = exp(DF(:,4) + (theta(:,d) * DF(:,1)))
    epredT = exp(DF(:,4) - (theta(:,d) * (1-DF(:,1))))

    do j=1,i
        B1(:,j)=epredT(j)
        B2(:,j)=epredC(j)
    end do

    ! Here, replace matmul by Lapack matrix multiply (dgemm).
    ! Matmul is good only for small matrices.
    ! Otherwise, put the boundaries of DF as DF(1:i,5)
    call dgemm('N','N',
    A1 = matmul(DF(:,5), B1)
    A2 = matmul(DF(:,5), B2)

    diff = (A1-A2)/DBLE(i)

    ! It would be better to dimension bigDF as (8,i) here for
    ! the subsetPeriod subroutine
    ! In that case, you would need:
    ! do k=1,i
    !   bigDF(1:5,k) = DF(k)
    !   bigDF(  6,k) = epredC
    !   bigDF(  7,k) = epredT
    !   bigDF(  8,k) = diff
    ! end do
    ! If bigDF is properly aligned, you will have a very efficient store
    ! here

    bigDF(:,1:5) = DF
    bigDF(:,6) = epredC
    bigDF(:,7) = epredT
    bigDF(:,8) = diff

    ! 1) Put the allocate and deallocate statements outside of the
    !     loop.
    ! 2) Dimension the array as ( 8, maxval(nPeriodT) ). 8 is better
    !    than 7 for vectorization, and the transposed version is
    !    preferable for the called loop
    ! 3) Compute sumWeights_inv = 1.d0/sumWeights outside of the loop
    !    and multiply by sumWeights_inv in the loop : a division is a
    !    evry expensive operation
    ! 4) sumWeights could be computed on the fly for free in
    !    subsetPeriod. You would need to pass it as an argument
    do jj =1, nPeriods
        ALLOCATE(out(nPeriodT(jj),7))
        CALL subsetPeriod(bigDF, i, 8, nPeriodT(jj), jj, out) !Filters data
        sumWeights = sum(out(:,2))
        do j=1, nPeriodT(jj)
            ! Multiply by inverse
            wm(jj) = wm(jj) + (out(j,7)*out(j,2)/sumWeights)
        end do
        DEALLOCATE(out)
    end do

end subroutine subsmearing

subroutine subsetPeriod(A, rowA, colA, rowB, Period, B)
    integer, intent(in)                                    :: rowA, colA, rowB, Period
    double precision, dimension(rowA, colA), intent(in)    :: A
    double precision, dimension(rowB,colA-1), intent(out)  :: B
    integer                                                :: i, pos

    pos = 1
    do i = 1, size(A,1)
        if(A(i,2)==Period)then
            B(pos,1) = A(i,1)
    ! Transposing bigDF and out is important for better
    ! data access in this line
            B(pos,2:) = A(i,3:)
            pos = pos+1
        end if
    end do
end subroutine subsetPeriod

end module smearingmodule


You do not have to check len(sys.argv) yourself. A properly constructed ArgumentParser will sort that out by itself.
Likewise, you do not need to pass sys.argv[1:] to parse_args(), argparse will figure it out.
default=None and required=False are default values for an optional argument (those starting with '-'), you do not need to supply them.
You do not need to use a lambda to specify the function to call, just pass in the name of the function: it will simplify handling this parameters.
You can add do_work as a default value for '-a': no more TypeError as the content of parsed_args.cmd will alway be a callable.
There is no need in using a mutually exclusive group if you only ever put one option in it: remove it.
You should use if __name__ == '__main__': and put your top-level code under it.
In do_*work you should test database using is None or is not None.

def do_work(database=None):
    if database is not None:
        print 'Doing work for {0}'.format(database)
    else:
        print 'Doing work all database'

def do_other_work(database=None):
    if database is not None:
        print 'Doing other work for {0}'.format(database)
    else:
        print 'Doing other work all database'

def create_parser():
    parser = ArgumentParser(description='Parser')
    parser.add_argument('--db', '-d', dest='database', help='Database name')
    parser.add_argument('-a', dest='cmd', action='store_const',
                        const=do_other_work, default=do_work)
    return parser

if __name__ == '__main__':
    parsed_args = create_parser().parse_args()
    parserd_args.cmd(parsed_args.database)


Support entitlement date check for customer assets

First thing would be to scan your code with Sonar. This will hit all the formatting complaints, magic numbers, etc.. Likewise, set up your IDE to auto format on save action to save lots of time fixing those Sonar findings.

The next thing to simplify would be to use Calendar instead of Date.


If all you do in your lock is global_counter++ you may as well make it a c++11 atomic, and just write local_counter = global_counter++.

Or, using what you've used so far, local_counter = __sync_fetch_and_add(&global_counter,1)

You may drop the wraparound check. You can increment once per nanosecond and it'd flip in a few hundred years.

After all that's been said in the comments I'm pretty much convinced there are no simple (read: 3 lines of code) solutions given 4g threads will get created and we have only 32 bit atomics.

There are 3 valid solutions:

Stay with the mutex. I guess if you're spending the time to create a thread, it's not the end of the world to lock a mutex once per the thread's lifetime.
Reuse those threads so you never get to 4g. Maybe you can not coz your client's app created them?
Reuse the nonce ranges. Having so many threads means most of them exit way before they consume the 64bit range per 32bit snapshot.
Now, you can have a destructor on the TLS entry of the snapshot. Lookup pthread_key_create.
You can use this destructor to push the current snapshot and counter into a lock free stack and pop them out in get_new_snapshot.
You can init that array/stack with 1000 nonce ranges (999,0), (998,0),... (0,0)
The first thread would pop (0,0). When it exits it'd push back whatever it got to. Say (0,122283).
If a thread ever consumes it's 64bit range of nonces (if your app runs for a millennia) it can pop another range.
You can pre-allocate a stack large enough for as many concurrent threads as you like. If it's ever consumed default to dynamically allocating more ranges. But this would would probably never get executed.

I can give more detail about a pre-allocated lock free stack, if you like.


Allowing users to view and manage articles

Try to envision how you would want your code to look, then build from there.

For example, I would like for the articles in the sidebar to just be there, so I pretend I have a function I can call that just fixes this for me.

res.render('article', { articles, article, title: article.name })
vs
render('article', {article, title: article.name })

Where does this new render function come from? I don't care, just take it as a dependency.

The same thing could be said about the cache and the article lookup. Just pretend it is there already.

Other than that, you could:

Refactor to async/await
Handle errors using a wrapper around your controller functions instead of .catch(err)
Remove a few redundant comments
Use a class with dependencies injected

I ended up with the following after a quick refactor:

class ArticleController{
    constructor(articleRepo){
        this._articleRepo = articleRepo
    }

    async retrieve(req, res, render){
        const article = await this._getArticleOrFail(req.params.publicId)
        return render('article', {article, title: article.name})
    }

    async settings(req, res, render){
        const article = await this._getArticleOrFail(req.params.publicId)

        const {page} = req.params
        const pageTitle = this._getSettingsPageTitle(page)
        const pageTemplate = `settings-${page}`

        return render(pageTemplate, {article, title: `${article.name}: ${pageTitle}`})
    }

    async _getArticleOrFail(id){
        const article = await this._articleRepo.getArticleById(id)

        if(!article){
            const error = new Error('Article not found')
            error.status = 404
            throw error
        }

        return article
    }

    _getSettingsPageTitle(page){
        return {
            edit: 'Edit name, URL',
            response: 'Edit email response',
            notifications: 'Configure notifications'
        }[page]
    }
}

module.exports = ArticleController

To get this working you need a couple of higher-order functions around your controller functions. One to create the render function that automatically adds articles, and one that handles errors and passes them into next(). Lastly, you need to create an ArticleRepo that you can pass as a dependency.

Some ideas:

class SidebarLayout{
    constructor(articleRepo){
        this._articleRepo = articleRepo
    }
    withSidebarData(controllerFunction){
        return async (req, res) => {
            const articles = await this._articleRepo.getUserArticles(req.user.id)
            const render = (template, data) => res.render(template, {...data, articles})

            return controllerFunction(req, res, render)
        }
    }
}

const createRoute = routeFunction => (req, res, next) => routeFunction(req, res, next).catch(next)

const articleRoute = createRoute(
    sidebarLayout.withSidebarData(articleController.retrieve.bind(articleController))
)

app.get('article', articleRoute)

There are multiple other ways to do it as well. You could have a more general templating class to inject alongside articlerepo instead of the middleware solution, or you could even decide on the actual template to use outside of the controller and simply pass in a template. But the point is to offload the necessary bits of logic outside of the controller.


There is a common pattern followed in all the if-else blocks in the given code. This can be moved to a function or a loop.

Here the pseudo code does this using a loop. As the condition in each successive block is cumulative, it is tracked as a separate variable modified by each successive iteration.

arr = {"I", "V", "X", "L", "C", "D", "M"}; // Store these in an array
for (c = 0; c < 15; c++) {
    findRomans = romans.get(c);
    condition = false;
    for(index = 0; index < size(arr); index++) {
        condition = condition || romans.get(c + 1).equals(arr[index]);
        if (findRomans.equals(arr[index])) {
            int multiplier = condition ? 1 : -1;
            arabic += multiplier * defaultArabics.get(index);
        }
    }
}
return arabic;

This code is just more concise than the original one. There is no efficiency gained here.


Reusable function for a validation process

The basic idea that I suggest is to decompose every bit of logic into small reusable functions. In my answer, I will touch only on validation logic because that part of your code has the most code duplication.
The following code is how I would like to see validation:
$('#addSubmit').on('click', function (e) {
    e.preventDefault();

    const validator = getValidator([
        [$('#addcity'), [
            combine(empty, emptyError),
            combine(notCapitalized, notCapitalizedError)]
        ],
        [$('#addregion'), [
            combine(emptyOrNull, emptyError)]
        ],
    ]);

    if (validator.hasErrors()) {
        const { element, error } = validator.getFirstError();
        $('.message').text(error.message);
        $('#errorModal').modal('show').on('hidden.bs.modal', element.focus.bind(element));
    } else {
        // Post request...
    }
});

Here we use the validator object to check if there are any errors and to get the first occurred error to display its message on the modal dialog. For the getValidator function we need to provide an element that we want to validate and a list of functions that find errors. Since functions that check for errors and actual errors are independent we need the ability to combine them. For example, the line combine(empty, emptyError) means that we want to check if a value is empty and return emptyError if so.
Also, I've made additional validation for the city field (see notCapitalizedError) to show how easy is to add new validation logic. To not hardcode error messages I've added data-name="" attributes to all inputs:
<input type="text" id="addcity" data-name="City" placeholder="City">
<input type="text" id="addregion" data-name="Region" placeholder="Region">

The implementation code is a bit hard to read and the following:
const empty = (str) => (str === "");
const emptyError = ($el) => ({ name: "empty", message: `You must enter a ${$el.data('name')}.` });
const notCapitalized = (str) => (!empty(str) && str[0] === str[0].toLowerCase());
const notCapitalizedError = ($el) => ({ name: "not-capitalized", message: `${$el.data('name')} should be capitalized.` });
const emptyOrNull = (val) => (empty(val) || val == null);

const combine = (hasError, createErr) => function($el) {
    return (hasError($el.val()) ? createErr($el) : null);
}

const getErrors = ($element, fns) => fns.map((fn) => fn($element)).filter(res => res !== null);
const getValidator = (data) => {
    const map = new Map();
    data.forEach(([$el, functions]) => {
        map.set($el, functions);
    })

    const elements = Array.from(map.keys());
    const getFunctions = ($el) => map.get($el) || [];
    const elErrors = ($el) => getErrors($el, getFunctions($el));
    const elHasErrors = ($el) => (elErrors($el).length > 0);
    const hasErrors = () => elements.some(elHasErrors);

    return {
        hasErrors,
        getFirstError: () => {
            if (hasErrors()) {
                const $element = elements.find(elHasErrors);
                return { element: $element, error: elErrors($element)[0]};
            }

            return null;
        }
    }
}


Capitalize string except for conjunction words

I think that you should be using ArrayLists for those conditional statements.

specifically you should store your conjunction words in an ArrayList something like this

Dim conjunctions
Set conjunctions = CreateObject("System.Collections.Arraylist")

conjunctions.Add("a")
conjunctions.Add("an")
conjunctions.Add("and")
conjunctions.Add("as")
conjunctions.Add("at")
conjunctions.Add("by")
' Etc ......

for each item in xTextSplit
    xWord = item
    if conjunctions.contains(lcase(item))
        xWord = lcase(item)
    elseif suffixes.contains(lcase(item))
          xWord = ucase(item)
    end if
    xCompleteWord = xCompleteWord & " " & xWord
next

suffixes would be another ArrayList.  this could be used with the method that Vogel612 suggests.

creating an ArrayList is a better way to perform this task because now you can add more words to the conjunction ArrayList and not have to worry if you found all the instances of it in the code.  It is more Maintainable.

NOTE: I haven't tested this code

 I think that you should be using Dictionary's for those conditional statements.

specifically you should store your conjunction words in a dictionary something like this

Dim conjunctions   ' Create a variable.
Set conjunctions = CreateObject("Scripting.Dictionary")

conjunctions.Add(1,"a")
conjunctions.Add(2,"an")
conjunctions.Add(3,"and")
conjunctions.Add(4, "as")
conjunctions.Add(5, "at")
conjunctions.Add(6, "by")
' Etc ......

for each item in xTextSplit
    xWord = item
    if conjunctions.Exist(lcase(item))
        xWord = lcase(item)
    elseif suffixes.Exist(lcase(item))
          xWord = ucase(item)
    end if
    xCompleteWord = xCompleteWord & " " & xWord
next

suffixes would be another dictionary.  this could be used with the method that Vogel612 suggests.


Code to implement the Jaro similarity for fuzzy matching strings

Style

PEP8 advocates two blank lines before function definition at top-level code. You should also try to reduce line length such as your long return in jaro_similarity, taking advantage of implicit line continuation and splitting before operators you could rewrite it as:

def jaro_similarity(s1, s2):
    matches = len(technical_match(s1, s2))
    if matches == 0:
        return 0
    else:
        return (
                matches / len(s1)
                + matches / len(s2)
                + (matches + transpositions(s1, s2)) / matches
        ) / 3

You should also avoid leaving code at top-level and, instead, put it in a main function. Also, get yourself familiar with the if __name__ == '__main__': guard:

def main(filename='foobar.txt', pattern='hat', constant=.5):
    match_text = open(filename).read().splitlines()
    results = []
    for i in match_text:
        if jaro_similarity(i, pattern) > constant:
            results.append(i)
    return results

if __name__ == '__main__':
    print(main())

Code

you open a file but never close it, prefer using a with statement when working with file;
your match function should be more understandable if shortened to return set(s1) & set(s2) which uses the mathematical notation for set intersection; in fact, since it is only used once, it would be even clearer if the function was not defined at all;
technical_match can be simplified a lot using either a list-comprehension or the filter builtin;
instead of re-computing the matched letters in transpositions, you could pass them as parameter; besides, using a set instead of a list let you perform containing checks in \$\mathcal{O}(1)\$ time vs \$\mathcal{O}(n)\$ for  lists; and again, filter is your friend;
you don't need math.floor as you can perform integral division using the // operator.

Proposed rewrite:

def technical_match(s1, s2):
    max_distance = max(len(s1), len(s2)//2) - 1

    def is_close(letter):
        return abs(s1.index(letter) - s2.index(letter)) <= max_distance

    return filter(is_close, set(s1) & set(s2))

def transpositions(s1, s2, matches):
    s1 = ''.join(filter(matches.__contains__, s1))
    s2 = ''.join(filter(matches.__contains__, s2))
    return sum(a != b for a, b in zip(s1, s2))

def jaro_similarity(s1, s2):
    matches = set(technical_match(s1, s2))
    if not matches:
        return 0
    else:
        match_count = len(matches)
        return (
                match_count / len(s1)
                + match_count / len(s2)
                + (match_count + transpositions(s1, s2, matches)) / matches
        ) / 3

def main(filename='foobar.txt', pattern='hat', threshold=.5):
    with open(filename) as f:
        for line in f:
            line = line.strip()
            if jaro_similarity(line, pattern) > threshold:
                yield line

if __name__ == '__main__':
    print(list(main()))

Algorithm

Your code don't implement Jaro similarity it may give close results but it is not the right algorithm. For starter, you don't substract half the transpositions in the third term of the sum, instead you add them fully; you also failed to correctly compute the maximum allowed distance which is \$\frac{\max(\text{len(s1)},\text{len(s2)})}{2}\$ instead of \$\max(\text{len(s1)},\frac{\text{len(s2)}}{2})\$. Second, using sets in technical_match (well, match actually) lead you to completely ignore repeated letters: think things like matlab vs mathematica where the second a in both words is a match. (Your version return 3 matches, the algorithm consider there are 4 of them.)

The french version of the wikipedia page gives useful examples of application showing that the algorithm instead uses a sliding window to check for matches. I wondered how duplicate letters should be handled (think of goose vs hot, is there 1 or 2 matches?) until I found a C# implementation on SO: a letter that already matched should not match again (this is the first check in the first for loop).

Converting the code to Python is almost straightforward:

import itertools

def jaro_similarity(string1, string2):
    if not string1:
        return float(not string2)

    window_size = max(len(string1), len(string2)) // 2 - 1
    matched1 = [False] * len(string1)
    matched2 = [False] * len(string2)

    matches = 0
    for i, char in enumerate(string1):
        start = max(0, i - window_size)
        end = i + window_size + 1
        for j, c in enumerate(string2[start:end], start):
            if matched2[j]:
                # Account for repeated characters matching a single one
                # in the other string. Like `goose` vs `hot`, only a
                # single `o` of `goose` should match the only `o` in `hot`
                continue
            if c == char:
                matched1[i] = True
                matched2[j] = True
                matches += 1
                break

    if not matches:
        return 0.0

    matches1 = itertools.compress(string1, matched1)
    matches2 = itertools.compress(string2, matched2)
    transpositions = sum(a != b for a, b in zip(matches1, matches2))

    return (
            matches / len(string1)
            + matches / len(string2)
            + (matches - transpositions/2) / matches
    ) / 3

def main(filename='foobar.txt', pattern='hat'):
    print('Comparing to pattern:', pattern)
    with open(filename) as match_text:
        for line in match_text:
            line = line.strip()
            print(line, jaro_similarity(pattern, line))

if __name__ == '__main__':
    main(pattern='hat')
    main(pattern='goose')


Directory listing, sorting and filtering in F#

I am not sure if I can summarize the changes I made better, but I made several refactorings and better error handling (when inputing a string, for example, your program crashed.) I also chose to make it zero-indexed, rather than 1-indexed, mostly to simplify the code.

open System
open System.IO

let getLatestSubDir = Seq.maxBy Directory.GetCreationTime // Refactored
let sortedSubDirs = Directory.GetDirectories >> Seq.sort // Refactored
let printDirMenu =
    sortedSubDirs >> Seq.iteri (fun idx path -> printfn "%d %s" idx path)
let openDir (dir : string) = System.Diagnostics.Process.Start(dir) |> ignore

[<EntryPoint>]
let main argv =
    let path = argv |> Seq.head
    printDirMenu path
    let input = System.Console.ReadLine()
    match Int32.TryParse(input) with
    | true, n ->
        let dir =
            path
            |> sortedSubDirs
            |> Seq.tryItem n
        match dir with
        | Some d ->
            Directory.GetDirectories(d)
            |> getLatestSubDir
            |> openDir
        | None -> printfn "Invalid input"
    | _ -> printfn "Invalid input"
    Console.ReadKey() |> ignore
    0

It is definitely possible to factor the sorting so it is only done once, rather than twice in my code.

The code also crashes when the chosen folder doesn't have any sub folders.


Your solution does not honor multibyte characters, i.e. it will probably break for non-English languages.

Instead you could utilize PCRE (regular expressions) and Unicode character grounps:

$foundLetter = preg_match('(\pL)u', $password);
$foundNumber = preg_match('(\pN)u', $password);
$foundSymbol = preg_match('(???)u', $password);

Not sure what you define as a symbol, [\pP\p{Xps}] (Punctuation + Whitespace) would reflect your current version (I think). Maybe a better alternative would be [^\pL\pN] though, which just ensures one non alphanumeric letter.

In theory you could change your script into a one liner now:

return strlen($password) >= 8 && (
    preg_match('(\pL)u', $password)
  + preg_match('(\pN)u', $password)
  + preg_match('([^\pL\pN])u', $password)
) >= 2;


Why do you need the function? To measure the distance (in miles) between two points? Then you want to select all points of a certain type and order them by distance from a given origin.

With a CTE (common table expression)  you can simplify things a lot too.

But, the real issue, is that you should use the functions already available in the geography datatype: STDistance. This STDistance function returns the 'LineString' distance, which is 0.25% accurate to the geodesic distance. Additionally, this is better than the 0.5% accuracy of the Haversine distance.

So, by the sounds of it, you have horribly overcomplicated this process. Consider this (SQLFiddle example here too):

Select s.FEATURE_NAME as SName,
       s.GeoLocation.Lat as SLat,
       s.GeoLocation.Long as SLong,
       t.FEATURE_NAME as TName,
       t.GeoLocation.Lat as TLat,
       t.GeoLocation.Long as TLong,
       s.GeoLocation.STDistance(t.GeoLocation) * 0.00062137 as Distance
from Features s,
     Features t
where s.FEATURE_NAME = 'Seattle'
  and s.FEATURE_CLASS = 'Populated Place'
  and t.FEATURE_CLASS = 'Lake'
order by Distance desc


Determining the similarity between two documents

For flexibility, your cosineSimilarity() method should taken in List<Integer> arguments, instead of ArrayList<Integer> arguments.  This method doesn't care how the list is stored, only that it is a list which implements .size() and .get(i) methods.

For efficiency you should used double variables, not Double objects in the method:

public static double cosineSimilarity(List<Integer> vectorOne,
                                      List<Integer> vectorTwo)
    double dotProduct = 0.0;
    double normVecA = 0.0;
    double normVecB = 0.0;

When you open a Scanner, you should .close() it, to prevent resource leaks.  The "try-with-resources" construct will automatically close resources that it opens.  So instead of:

Scanner textFile = new Scanner(new File("Enter textfile  here"));

use

try(Scanner textFile = new Scanner(new File("Enter textfile  here")) {
    // use textFile inside this block.
}
// textFile is automatically closed when the block is exited.

Ditto with FileWriter.  Use "try-with-resources" to automatically close the writer.

try(FileWriter fw = new FileWriter(fileName, true)) {
    fw.write( ... );
}
// fw has been automatically closed at this point.

If you are using .nextInt(), you should loop on .hasNextInt(), not .hasNext().

while(textFile.hasNextInt()) {
     arsenal.add(textFile.nextInt());
}

It sounds like you want a Map<String,List<Integer>> to store an ArrayList for each team.

List<String> team_names = List.of("Arsenal", "Chelsea", "Liverpool",
        "ManchesterCity", "ManchesterUnited", "Tottenham");

Map<String,List<Integer>> stats = new HashMap<>();

// Read in all team stats from (for example) "<TeamName>_stats.txt" files

for(String team_name : team_names) {
   List<Integer> team_stats = new ArrayList<>();
   try (Scanner textFile = new Scanner(new File(team+"_stats.txt"))) {
      while(textFile.hasNextInt()) {
          team_stats.add(textFile.nextInt());
      }
   }
   stats.put(team_name, team_stats);
}

Then you can use stats.get(team_name) to get each team's stats for comparison / analysis

for(String team1_name : team_names) {
   List<Integer> team1_stats = stats.get(team1_name);

   for(String team2_name: team_names) {
      // Skip comparing a team against itself
      if (team1_name.equals(team2_name))
          continue;

      List<Integer> team2_stats = stats.get(team2_name);

      double output = cosineSimilarity(team1_stats, team2_stats);

      // ... display "output", or write to file, or ...
   }
}

Depending on how you want your output written (one file for all comparisons, or one file per team for a comparison with all other teams, you'll want to open the FileWriter before the outer loop, or before the inner loop.


Welcome to the Code Review Community.
General Observations
The use of small functions is very good and makes the code more readable, but overall the readability can be improved.
The code does seem to follow the concept of the single responsibility principle.
I'm going to address the code in 2 phases, one is dealing with improving the use of C programming and the second is coding style in general.
The use of structures to represent the queues and the stacks might have decreased the complexity of the code.
For the future it might be good if you provided an example input and expected output.
C Programming Improvements
Check for Warnings
When you initially compile with C use the -Wall compiler flag to list any warnings as well as any errors. In many cases the warnings can indicate possible bugs in the code.
While this code compiles it does have the following warnings using the -Wall flag:
gcc -Wall dfsbfs.c
dfsbfs.c:133:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
  133 | void main(){
      |      ^~~~
dfsbfs.c: In function ‘main’:
dfsbfs.c:138:14: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[10]’ [-Wformat=]
  138 |      scanf("%s",&v);
      |             ~^  ~~
      |              |  |
      |              |  char (*)[10]
      |              char *
dfsbfs.c: In function ‘dequeue’:
dfsbfs.c:22:1: warning: control reaches end of non-void function [-Wreturn-type]
   22 | }
      | ^
dfsbfs.c: In function ‘POP’:
dfsbfs.c:87:1: warning: control reaches end of non-void function [-Wreturn-type]
   87 | }
      | ^

The warning about control reaches end of non-void function indicates that the code is missing a return statement if F == -1 in the function dequeue().
The warning about main () indicates that this program is not following the C programming standards about the main() function which should always return an integer value indicating the success or failure of the program to the operating system.
Avoid Global Variables
It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation.
Magic Numbers
There are many Magic Numbers in the global declarations (-1, 10, 100 and 9), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
Readability and Coding Style
Code Consistency
The indentation of the code is inconsistent. This makes the code much harder to read and maintain. For instance it would be better if the function dequeue() looked something like this:
int dequeue(){
  if (F == -1)
  {
    printf("underflow\n");
  }
  else{
    vertex = q[F];
    printf("%c", vertex);
    F++;
    if (F < 10)
    {
      return pos[F];
    }
    else
    {
      return -1;
    }
  }
}

Some other inconsistencies are that variables are both upper and lower case characters and in most cases are single characters while in some other cases meaningful names. In the C programming language some common practices are that variable and function names are all lower case, and that variable and functions names with multiple words are snake_case. Symbolic constants, which are not used in this program are all upper case.
Horizontal and Vertical Spacing
In most programming languages it is common to improve readability by using horizontal spacing between operators and operands as shown above in the if statements and the printf statements.
The code might be slightly more readable of the open braces { lined up with the closing braces '}', however, this would be determined by local coding standards.


You can use array_merge to reduce the array from 2-dim to 1-dim, then implode the array.

$this->view->error_message =
    implode(array_reduce($form->getMessages(),
                         "array_merge",
                         array()),
            "<br/>");

http://php.net/manual/en/function.array-merge.php

http://www.php.net/manual/en/function.array-reduce.php


Type to represent multiple possible values

How about this?

Use constructor(private _options: any[]) instead of field declaration and assignment.
As a defensive programming measure use = [] to initialize the array with an empty value in null/undefined was padded in.
Instead of numerous searches through chosenIndices (via indexOf) use a simple .map(...) function instead.

export class SelectableModifier {

  constructor(private _numSelectionsNeeded: number, private _options: any[] = [], private _selectionTime: string) { }

  get numSelectionsNeeded(): number {
    return this._numSelectionsNeeded;
  }

  get options(): any[] {
    return this._options;
  }

  get selectionTime(): string {
    return this._selectionTime;
  }

  public makeSelection(chosenIndices: number[]): any[] {
    if (chosenIndices.length != this.numSelectionsNeeded) {
      throw new Error("The selection requires that " + this._numSelectionsNeeded + " selections be made but " + chosenIndices.length + " were instead.");
    }

    return chosenIndices.map(indexOfChosen => this.options[indexOfChosen]);
  }
}

UPD1

If null/undefined choices should be treated as errors, you can check for their presence and throw.

public makeSelection(chosenIndices: number[]): any[] {
    if (chosenIndices.length != this.numSelectionsNeeded) {
        throw new Error(`The selection requires that ${this._numSelectionsNeeded} selections be made but ${chosenIndices.length} were instead.`);
    }

    const result = chosenIndices.map(indexOfChosen => this.options[indexOfChosen]);
    if (result.some(item => item == null))
        throw new Error('Selection can not be null/undefined.');
    return result;
}


Your code looks good, and very clean. Best practices are usually subjective; there's no absolute best way to clone and insert an element. That being said, I would make two suggestions:
1. Be consistent with your HTML
Your conditions div doesn't have quotes around its ID, whereas your template div does. I'd recommend always surrounding IDs in quotes as a standard practice.
2. Swap the .show() and .appendTo() order
This suggestion is purely subjective, but semantically, I think it makes more sense to add the cloned element to the DOM first, then change its display property, rather than change its display property first (which won't have any affect yet anyway) and then add it to the DOM. Again, that's just my opinion.
Other notes
If you're interested in adding autofocus to your input elements (so that as a new element is added, it automatically gets focus) you could do that fairly easily by inserting this line just before you close your function:
[0].childNodes[3].focus();

Also, if you ever modify your code to where you need to access the cloned elements by ID, keep in mind that your cloned elements will start with condition2.  You're using the length to generate the number, so when you add the first element the length will be 2.


Function caller (to multiple receivers) interface

If I understand correctly,
the purpose of Caller seems to be to call a function on multiple objects.
It works like this:

Construct a Caller x by passing 1 or more objects in the constructor
Call any method m on x, and it will be dispatched to method m of all objects

Right? The docstring doesn't explain this very well.
CallDispatcher might be a better name.

My impression is that you're discovering powerful features of Python,
and you're trying to use them because you can,
not because you have a concrete purpose.
Sort of like an exercise, not for real-life use.

It seems to me that __getattr__ is seriously abused.
I don't have experience overriding this method,
but I would guess it's designed to implement getters dynamically.
First of all,
adding getters dynamically seems like a hack that should be used with extreme care,
including a good justification that it's the best option.
Secondly,
instead of behaving as a getter,
this implementation mutates the object and returns self.
I see you did that to make chaining and currying possible,
it's interesting, but it seems a misuse of the language.

Another thing I don't like about the approach is the heavy dependence on duck typing.
The objects that can be used with Caller don't have to follow a well-defined interface,
they can be anything.
The user just has to make sure that when they call a .hello function on a Caller object,
all the objects inside have a .hello function defined.
It's great that Python let's us do this kind of thing,
but it doesn't mean that we should.
I prefer to have well-defined and well-documented interfaces,
with a list of legitimate methods that I'm allowed to call.

Python conventions

Instead of:

class Caller():

The class should be declared as:

class Caller:

Instead of:

    if len(self._names) == 0:

The Pythonic way:

    if not self._names:

Instead of:

        print ("Receiver3 - b", arg)

There should be no space before the opening paren:

        print("Receiver3 - b", arg)


First of all, yes, CortexM0 lacks any way to do 32x32=64 multiplication in hardware. CortexM3 and CortexM4 have the umull instruction, which lets you do 32x32=64 really easily.

And yes, since you're writing in C, one possible implementation would be

uint64_t mul32x32(uint32_t r0, uint32_t r1) { return r0*(uint64_t)r1; }

but I assume you've already tried that (with -O3 and whatever other optimization and inlining options you can turn up) and discovered that your compiler doesn't inline the multiplication, but leaves it as a call to some internal libc function.

A quick Google search turned up this previous StackOverflow question on exactly the same topic, where someone in the comments linked to GCC's implementation of 64x64=64 multiplication for CortexM0 (here), with the suggestion that you could constant-propagate "upper bits are known to be zero" through the whole thing by hand and that would give you something decent. I don't know if that's true.

Have you also benchmarked the "naive" approach of

uint64_t mul32x32(uint32_t r0, uint32_t r1)
{
    uint16_t r0h = r0 >> 16, r0l = r0 & 0xFFFF;
    uint16_t r1h = r1 >> 16, r1l = r1 & 0xFFFF;
    uint64_t result = (r0h * r1h);
    result <<= 16;
    result += r0h*r1l;
    result += r0l*r1h;
    result <<= 16;
    result += r0l*r1l;
    return result;
}

or equivalently

uint64_t mul32x32(uint32_t r0, uint32_t r1)
{
    uint16_t r0h = r0 >> 16, r0l = r0 & 0xFFFF;
    uint16_t r1h = r1 >> 16, r1l = r1 & 0xFFFF;
    return ((uint64_t)(r0h * r1h) << 32)
         + ((uint64_t)(r0h * r1l) << 16)
         + ((uint64_t)(r0l * r1h) << 16)
         + ((uint64_t)(r0l * r1l) << 0);
}

? As long as none of the arithmetic operations get turned into library function calls, this has the benefit of being portable ANSI C and being susceptible to inlining by the compiler. If you care about speed, susceptibility-to-inlining should be your #1 concern.

Since you have access to your compiler and we don't (I'm guessing Green Hills, from the __asm{ } syntax for inline assembly blocks?), you might get better answers if you posted the assembly that results from the above three C implementations.

Finally, note that CortexM0's MULS instruction takes either 1 cycle or 32 cycles, depending on the processor. If you're on one of those 32-cycle processors, doing four MULS instructions in a row is probably one of the worst things you can do. If MULS only takes 1 cycle, then you're probably okay; I don't think there's any need to space out those MULS instructions the way one might on a machine where they took multiple cycles (software pipelining).


Use better variable names

Right now, I have no idea what you mean by wq. Also, buf could be spelled out as buffer without loosing anything.

Also, PEP8 recommends snake_case for variables and two blank lines between function definitions.

Better comparisons

You should use the fact that isLeft is already a boolean and use if isLeft: instead of if isLeft == True:

Also, you could use that the empty list evaluates as False and save one call to len:

if len(wq) == 0:
    return

if not wq:
    return

Iterate over object, not its indices

Instead of doing:

for i in range(len(wq)):
    buf.append(wq[i].value)
for i in range(len(wq)-1, -1, -1):
    buf.append(wq[i].value)

do:

for node in wq:
    buf.append(node.value)
for node in wq[::-1]:
    buf.append(node.value)

But what you really want is probably:

buf  = [x.value for x in wq]
# or
buf = [x.value for x in wq[::-1]]
buf = [x.value for x in reversed(wq)]

where the latter is necessary, because deque does not support the slice notation.

This already saves a lot of append calls and merges them into one assignment. But since these two things are very similar (only the direction changes), we can also write;

buffer = iter(wq) if is_left else reversed(wq)
print [node.value for node in buffer]

Use collections.deque

Since you are always popping left, you could use collections.deque, where this operation is faster than for a simple list.

from collections import deque
...
wq = deque([root])
wq_temp = deque([])

Miscellaneous

For this I think it is better to return as early as possible. Also, use tuple assignment:

# inner while
wq = wqTemp
wqTemp = []
if len(wq) == 0:
    return

# inner while
if not wqTemp:
    return
wq, wqTemp = wqTemp, []

Even better, you can move the check for the empty list to the condition of the while loop, because initially wq is either empty (then the while loop does nothing) or has root in it so is not empty.

This

wq = []
wqtemp = []
wq.append(root)

can be written as:

wq, wqtemp = [root], []

Final result

Wrapping everything together:

from collections import deque

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def zigzag_print(wq, is_left):
    if not wq:
        return
    buffer = iter(wq) if is_left else reversed(wq)
    print [node.value for node in buffer]

def zigzag(root):
    wq, wq_temp = deque([root]), deque([])
    is_left = True
    while wq:
        zigzag_print(wq, is_left)
        is_left = not is_left
        while wq:
            node = wq.popleft()
            if node.left:
                wq_temp.append(node.left)
            if node.right:
                wq_temp.append(node.right)
        wq, wq_temp = wq_temp, deque([])


Inserting into a binary search tree in C

There is a third option:

Node *add_internal(Node *root, int value) {
    if(root == NULL) {
        return create_node(value);
    }

    // Decide whether to insert left or right
    if (root->value >= value) {
        root->left = add_internal(root->left, value);
    } else {
        root->right = add_internal(root->right, value);
    }
    return root;
}

Basically moves the null test into the recursive call.

However this version requires it to be called as root = add_internal(root, value);. But it has the advantage that it can deal with a null root in a transparent way.


You've four for-loops that are doing the same with different input. Make a function for this logic and call it with the different arrays.

I don't know how typescript handles it and how often you call this function, but it could be better to define your characters outside of this because generating them every time you call this function is not necessary.

Besides, you don't need to define your alphabet twice. You can use toUpperCase/toLowerCase.

And last: From an outsiders perspective, I have no idea what this code is for:

 return 0.5 - Math.random()

You should make a function for it or at the very least, write a comment for it.


You are mixing a repository with a classifier. The classifier is not doing anything except separating out keys from non-keys. The repository doesn't do anything with what it holds. You convert strings to a particular type and then store them back as strings, without gaining any real value along the way.

DDType doesn't seem to do anything except act as a classifier. And it doesn't even do that, as it only translates the string values "text", "numeric", etc, into predicates which are then discarded at the end of the classification.

Without seeing the use case, I can only presume that add(dd) is called from time to time and the sets are updated, either into keys or into inserts.

keys and inserts can be variables that hold immutable Sets. That will improve thread safety a smidgen.
Remove the redundant classifer:

def add(dd:DomainDictionary, value:String) = {
  dd.domainDictionaryType match {
    case "numeric" => keys = keys + (dd, value.toInt)
    case _ => inserts = inserts + (dd, value)
  }
}

For full thread safety, use a Repository Pattern, or use Actors.


Query: user can see all posts by him and his friends

It looks like you are performing the same query against the Friends table twice.  If you need that query, I would split it off and run that query first, passing the result to your main query as a parameter.  But as you'll see at the end, I don't think that is necessary.

Also, you are using surrogate keys (yay!).  When you say "natural join" I think you are joining on userid AND visible (because they have common names between the two tables).  This is a waste, and also an error if you want posts that are visible and invisible.  Be specific about your join:

 from posts P join users U on P.userid = U.userid

Why do you have a status column in Friends table and what is the difference between status and visible?  Couldn't you just delete the Friend record if a user no longer wants that friend?  The reason I'm asking is that you could limit the size of this table and at the same time add a unique constraint on (userid, friendid) so that you test for uniqueness on insert and don't have to in the query.  Ensuring uniqueness takes time.  If you aren't already getting unique results, then your first choice should be to restructure your table and your query so that you do.

UNIQUE KEY `friendship_unique` (`userid`,`friend`),

You may have to use InnoDB instead of MyISAM in order for that to work.  MyISAM will accept it and silently ignore it because MyISAM does not support foreign keys or most constraints.  For this reason, InnoDB may be faster for joins.  With big tables I think it is.  The one down side of using InnoDB vs. MyISAM is that the minimum time for inserting into an InnoDB table is about 5ms where MyISAM inserts are less than 1ms.  In practice, this is only an issue if you are storing log files or session information in the database that needs to be updated with every request.  You can always turn a single table from InnoDB to MyISAM later if you need the insert speed more than you need query speed, but that should be the exception rather than the rule.

You are making a lot of non-standard type choices for your column definitions.  Why are you using int instead of bigint for your ID column?  Why are you using int instead of bit for your boolean columns?  Why aren't you using UTF-8?  Why no keys?  Are you using MyISAM tables because you don't want to pay to distribute this database, or is it just on a web server where it's free to use InnoDB?  I think something like the following would be much more standard:

CREATE TABLE IF NOT EXISTS `user` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT
  `fname` VARCHAR(45) NOT NULL ,
  `lname` VARCHAR(45) NOT NULL ,
  `usernick` VARCHAR(45) NOT NULL ,
  `useremail` VARCHAR(45) NOT NULL ,
  `is_deleted` bit(1) NOT NULL DEFAULT b'0' COMMENT 'True if record is logically deleted.',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE IF NOT EXISTS `friend` (
  `id` bigint(20) unsigned NOT NULL
  `friend_id` bigint(20) unsigned NOT NULL
  `date` TIMESTAMP NOT NULL DEFAULT now() , //
  `is_deleted` bit(1) NOT NULL DEFAULT b'0' COMMENT 'True if record is logically deleted.',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
  UNIQUE KEY `user_friend_unique` (`id`,`friend_id`),
  KEY `friend_fk_user` (`id`),
  KEY `friend_fk_friend` (`friend_id`),
  CONSTRAINT `friend_fk_user` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE CASCADE,
  CONSTRAINT `friend_fk_friend` FOREIGN KEY (`friend_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

OK, now you have clearly told MySQL to use InnoDB, to make your surrogate key unique, index on it, use it as a foreign key, and to delete records from the friend table when either of the corresponding user records are deleted.  This ensures a much cleaner database - fewer records means faster queries.

Hmm... I also think you can restructure your query.  Here are your friends posts:

select F.fname, F.lname, P.postid, P.status, P.date, U.usernick, P.is_deleted
  from friend F join post P on p.user_id = F.id
  where F.id = '{$_SESSION['user_id']}'

Here are your posts:

select U.fname, U.lname, P.postid, P.status, P.date, U.usernick, P.is_deleted
  from post P join user U on P.user_id = U.id
  where P.user_id = '{$_SESSION['user_id']}'

You should be able to do something like that without making any of the other changes I suggested.


Project Euler Problem 9: Special Pythagorean triplet

You may immediately

    return a * b * c;

as soon as the values are found.
The loop

    for (int cValue= 1; cValue<=value/2; cValue++)

is superfluous: you already have a and b, and you know that \$a+b+c\$ must be equal to value, so

    cValue = value - aValue - bValue;

suffices.
Thou shalt not brute force.

Recall that the Pythagorean triple \$a, b, c: a^2 + b^2 = c^2\$ can be expressed as $$a = k(u^2 - v^2)\\
b = 2kuv\\
c = k(u^2 + v^2)$$
with coprime \$u,v\$. Since they must add up to a particular value \$N\$ (in your case, 1000), conclude that \$2k(u^2 + uv) = N\$, or \$v = \dfrac{N}{2ku} - u\$.

We know that sides must be positive, so we have

\$u > v \rightarrow u > \dfrac{N}{2ku} - u \rightarrow u > \sqrt{\dfrac{N}{4k}}\$, and
\$v > 0 \rightarrow \dfrac{N}{2ku} - u > 0 \rightarrow u < \sqrt{\dfrac{N}{2k}}\$

Now loop over the range [sqrt(125), sqrt(500)] looking or the divisors of 500 (the range is as small as [11 .. 22], and the only divisor is 20). I intentionally will not explain how to recover \$a, b, c\$ once the divisor is found. It is pretty straightforward.