topological sorting to find the pre-requisite for courses

Thank you for sharing your code.

Here are my thought on it:

OOP

Your code is a procedural approach to the problem.

There is nothing wrong with procedural approaches in general, but Java is an object oriented (OO) programming language and if you want to become a good Java programmer then you should start solving problems in an OO way.

If you don't care about OOP you should look for a different programming language that better supports procedural or functional approaches.

Naming

Finding good names is the hardest part in programming, so always take your time to think about the names of your identifiers.

Naming Conventions

Please read (and follow) the
Java Naming Conventions

Your class name violates the Java naming conventions. Maybe you got the name provided by your teacher. Then you have to use it of cause. But keep in mind that you should not use underscores in your own identifier names (except constants).

avoid single character names / abbreviations

Since the number of characters is quite limited in most languages you will soon run out of names. This means that you either have to choose another character which is not so obviously connected to the purpose of the variable. And/or you have to "reuse" variable names in different contexts. Both makes your code hard to read and understand for other persons. (keep in mind that you are  that other person yourself if you look at your code in a few month!) The same is true for (uncommon) abbreviations. You might find them being obvious today, while you're actively dealing with the problem, but You might have to "relearn" them if you worked on something else for a while.

On the other hand in Java the length of identifier names names is virtually unlimited. There is no penalty in any way for long identifier names. So don't be stingy with letters when choosing names.

As usual there are some exceptions for this suggestion.
E.g. the running index of loops is usually held in a single letter named variable like i in

for(int i =0; i<SOME_CONSTANT; i++)

But even there you should use more problem oriented names to support your readers, especially in nested loops like this:

for(int row =0; row<ENTRY_COUNT; row++)
   for(int column =0; column<ENTRY_FIELD_COUNT; column++)

Choose you names from the problem domain, not from the technical solution.

You have variable names like map, k (as for key) and v (as for value). Better names for them might be like

    int course = a[1];
    int prerequest = a[0];
    if (!prerequestsForCourse.containsKey(course)) {
        prerequestsForCourse.put(course, new ArrayList<Integer>());
    }
    prerequestsForCourse.get(course).add(prerequest);

Magic numbers

your code has some magic numbers. This are literal values with a special meaning like here:

int totalCourse = 0;
//...
int k = a[1];
int v = a[0];

You should introduce constants with meaningful names:

int totalCourse = INITIAL_COUNT_IS_ZERO;
//...
int k = a[INDEX_OF_COURSE];
int v = a[INDEX_OF_PREREQUEST];

Know your language / read the API

You are using an legacy pattern to ensure the existence of the  the course in the map to the list of its prerequests. You may have found that or have been told to use it. But you should always look at the API of the class or interface you use if there is a better solution. You would have found this
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-
which would simplify your code to this:

prerequestsForCourse.computeIfAbsent(course,()->new ArrayList()).add(prerequest);

Single Layer Of Abstraction

This principle states that a method (or class) should either do simple/primitive calculations or (exclusive) call other methods (on other objects).

The last line in your method findTotalCourseInOrder() is the call to findOrderInSeries() which let me assume that you already know how to extract a bunch of lines to a separate method. You should do this with the the for loop above too:

private static int[] findTotalCourseInOrder(int totalCourse, int[][] arr) {
    HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
    int[] a1 = new int[totalCourse];
    int var = mapPrerequestsToCourses(arr, map, a1);
    return findOrderInSeries(map, a1, var, totalCourse);
}

private static int mapPrerequestsToCourses(int[][] arr, HashMap<Integer, ArrayList<Integer>> map, int[] a1) {
    int var = 0;

    for (int i = 0; i < arr.length; i++) {
        int[] a = arr[i];
        int k = a[1];
        int v = a[0];
        if (!map.containsKey(k)) {
            map.put(k, new ArrayList<Integer>());
        }
        map.get(k).add(v);
        a1[v]++;
    }
    for (int j = 0; j < a1.length; j++) {
        if (a1[j] == 0) {
            var = j;
            break;
        }
    }
    return var;
}

avoid break

break (as well as continue) are javas substitute for goto. Using them leads to code that is both, hard to read and hard to maintain/refactor.

You should not use break outside of a switch block.

An alternative implementation without the break statement could be based on the previous suggestion. In that modification the value returned is the result of the for loop. So you could simply exchange  break; by return j;

define variables as late as possible

In all you methods you define all variables right at the top of the method.

In Java this is not needed (as it is in C).

The problem with that is that it confuses your IDEs automated refactoring feature.

E.g.:  Your variable var is only used in the last for loop in findTotalCourseInOrder().
If you want to apply the extract method refactoring to this last for loop you get the variable var as a parameter to the new method.

    var = extracted(a1, var);
    return findOrderInSeries(map, a1, var, totalCourse);
}

private static int extracted(int[] a1, int var) {
    for (int j = 0; j < a1.length; j++) {
        if (a1[j] == 0) {
            var = j;
            break;
        }
    }
    return var;
}

If you'd move the declaration of variable var right before the loop you could include this line in the selection and the new method would not have this extra parameter.
Your code:

    int var = 0;
    for (int j = 0; j < a1.length; j++) {
        if (a1[j] == 0) {
            var = j;
            break;
        }
    }
    return findOrderInSeries(map, a1, var, totalCourse);
}

would change to:

    int var = extracted(a1);
    return findOrderInSeries(map, a1, var, totalCourse);
}

private static int extracted(int[] a1) {
    int var = 0;
    for (int j = 0; j < a1.length; j++) {
        if (a1[j] == 0) {
            var = j;
            break;
        }
    }
    return var;
}


This is not C++, yet. Just using std::cout does not C++ make. But do not fret, we'll get there.

Safe interface

Whenever designing an API (or interface), you should strive to make it as safe as possible.

Your interface here is not safe: having two un-linked variables to correctly pass is asking for troubles; it is just too easy to mix the variables up and pass a size that does not correspond to the array to be sorted (or printed).

Obviously, in your toy example it does not show up, however as soon as you manipulate multiple arrays in the same function you'll be very likely to make this mistake. And even with a single array, passing the length before re-allocating (for example) is also likely.

So, you need to aim for an interface that conveys both pieces of information in a single argument. An obvious choice is std::vector, another would be some instance of array_view or a random_access_range but those are not Standard so let's not bother for now.

Thus, the interface becomes:

void insertion_sort(std::vector<int>& array);
void print(std::vector<int> const& array);

Do note the consistency in the naming; both times the argument is named array instead of being once arr and once array. Consistency may be the hobgobelin of little minds, but it does help readers.

Algorithmic

An insertion sort is generally described simply as: read each element in turn, and insert it in the right position among the previous read (and sorted) elements.

The cost of the algorithm is thus:

for each of the N elements
the cost of inserting it in the i-1 (where i is the index of the element being read) first elements

The outer loop we cannot do anything about, but what of the insertion?

In your code, the insertion is done by:

    while (j > 0 && arr[j - 1] > arr[j]) {
        tmp = arr[j];
        arr[j] = arr[j - 1];
        arr[j - 1] = tmp;
        j--;
    }

That is, the value is bubbling up toward the front until it finds its spot.

This is suboptimal in terms of comparisons: the optimal algorithm to find the position to insert is using a binary search rather than a linear search, for O(log N) complexity rather than O(N) one.

In terms of number of moves, well, you may have to move all elements, so it could only be improved by a constant factor anyway.

Standing on the shoulders of giants, we can improve the code by separating the search and the move, and use pre-existing algorithms to do so:

std::upper_bound yields a pointer to the first element in the range that is greater than the value we search with
std::rotate rotates the elements of the range (and middle point) passed to it, such that the range delimited by the last two elements come to precede the range delimited by the first two

We can use them keeping to indices, although it is slightly verbose:

void insertion_sort(std::vector<int>& array) {
    typedef std::vector<int>::iterator It;

    for (size_t i = 1, length = array.size(); i < length; ++i) {
        // 1. Search
        It const end_sorted = array.begin() + i;
        It const insertion_point =
            std::upper_bound(array.begin(), end_sorted, array[i]);

        // 2. Insert
        std::rotate(insertion_point, end_sorted, end_sorted + 1);
    }
}

Thus I advise jumping the gun and just switch to iterators since that it what the interfaces of the algorithms we use consume:

void insertion_sort(std::vector<int>& array) {
    typedef std::vector<int>::iterator It;

    for (It it = array.begin(), end = array.end(); it != end; ++it) {
        // 1. Search
        It const insertion_point =
            std::upper_bound(array.begin(), it, *it);

        // 2. Insert
        std::rotate(insertion_point, it, it + 1);
    }
}

Which in modern C++ would use auto rather than explicitly naming the iterator type:

void insertion_sort(std::vector<int>& array) {
    for (auto it = array.begin(), end = array.end(); it != end; ++it) {
        // 1. Search
        auto const insertion_point =
            std::upper_bound(array.begin(), it, *it);

        // 2. Insert
        std::rotate(insertion_point, it, it + 1);
    }
}

Note that abbreviating further is not a good idea; while one-liners may give the writer a fuzzy warm feeling, they just end up being head scratchers for maintainers:

// Puzzle time!
void insertion_sort(std::vector<int>& array) {
    for (auto it = array.begin(), end = array.end(); it != end; ++it) {
        std::rotate(std::upper_bound(array.begin(), it, *it), it, it + 1);
    }
}

What does endl do?

Finally, a trick question: what do think std::endl is and does?

std::endl is a so called stream manipulator, it is a function whose signature is:

template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os );

So, when used on a stream, it does an operation on said stream and returns it (to allow further chaining).

Specifically, ostream << std::endl is equivalent to:

ostream << '\n';
ostream.flush();

Where flush makes sure that the data is not buffered in the process but fully sent to the Operating System (it does not guarantee that the data is on disk, sent over the network, or anything else).

There is very little reason to call flush in general:

in the absence of guarantee that the data arrived on disk (or wherever), it serves not practical purpose
the buffer was introduced for performance reasons, bypassing it is asking to go slow

So, not only should you generally avoid flush, std::endl is a mouthful. Just write '\n' to get an end-of-line character and be done with it.

Thus, we rewrite print:

void print(std::vector<int> const& array) {
    for (auto it = array.begin(), end = array.end(); it != end; ++i) {
        std::cout << *it << '\n';
    }
}

Or, using the range-for notation of modern C++:

void print(std::vector<int> const& array) {
    for (int e: array) { std::cout << e << '\n'; }
}

Who said C++ could not be nifty?


You should use flat to emit each wordApi and then you will be able to filter your data and apply your function one by one.

Your stream should look like this:

jamSpeakServiceApi.getAllWords()
            .subscribeOn(Schedulers.io())
            .flatMap(wordApis -> Observable.from(wordApis))
            .filter(wordApi -> wordApi.getCountry().toLowerCase().equals("jamaica"))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<WordApi>() {
                @Override
                public void onCompleted() {
                    Log.d("retroffit Completed", "Completed");
                }

                @Override
                public void onError(Throwable e) {
                    Log.d("retroffit error", e.toString());
                }

                @Override
                public void onNext(WordApi wordApi) {
                    Word.saveWordFromApi(wordApi);
                    Log.d(wordApi.getWord(),wordApi.getWord());
                }
            })

I used some lambdas, and I recommend you to use them too. Take a look at the Retrolambda Gradle plugin. It works well with an Android environment.


Could my object use static methods? Anything I need to do to make the code better?

If you wanted to make isAllowdIp static (and there's nothing wrong with that, per se), you -indeed- don't need an instance of your class to call that method. But owing to there being no instance, you won't have access to any non-static properties of your class, either.
To get around that, you'd have to change:

protected $_targetSmsIp = array('89.184.168.65');

To

protected static $_targetSmsIp = array('89.184.168.65');

And change these method, too:

public static function isAllowedIp($ip)
{//don't check empty strings, they're always invalid ips!
    return !!in_array($ip, self::$_targetSmsIp);
}
public static function addAllowedIp($ip)
{//don't allow '' defaults! adding empty strings aren't valid ips
    if (!filter_var($ip, FILTER_VALIDATE_IP))
    {//check what you're adding to the OK-list!
        throw new InvalidArgumentException($ip. ' is not a valid IP');
    }
    self::$_targetSmsIp[] = $ip;
}

This, by itself isn't code that makes my eyes water, but it doesn't exactly sit well with me, either: It's hard to tell what the actual task of your class is: validate IP's/data? Is it the API connection layer?
I gather it's the latter. In which case, I'd define my methods to only accept objects of a given type. This object is where you can filter, check and validate all input... For example, the IpObject:

class IpObject
{
    private $ip = null;
    private static $valideIps = array();
    public function __construct($ip = null)
    {
        if ($ip)
        {
            $this->setIp($ip);
        }
    }
    public function getIp()
    {
        return $this->ip;
    }
    public function setIp($ip)
    {
        if (!filter_var($ip, FILTER_VALIDATE_IP) || !in_array($ip, self::$validIps))
        {
            throw new InvalidArgumentException($ip.' is not valid');
        }
        $this->ip = $ip;
        return $this;
    }
}

The major problem with your creating statics here is that, by changeing the allowed IP's for one instance, you're changing the allowed IP's accross the board: you can't black-list or OK ip's for instances of your object individually, so after a while it'll get quite tricky to work out which IP's are allowed and which aren't.

All in all, an array in this object won't add too much overhead... not that you notice, and it will make life easier when testing/debugging.
Instead of using statics. having an instance at the ready is 99.99% of times the better option.


Validating user credentials and logging into a Symfony site

Note: the suggestion below is founded on a certain vision about readability, that may not be shared by everybody, as illustrated by the totally opposite approach proposed by @Thijs Riezebeek.

A pretty simple, light, and though efficient solution I frequently use in such cases is to merely:

Return the appropriate explainatory message when there is an error.
Do nothing otherwise.

First it makes your function as simple as possible (when successfull you don't even need to return anything).

Then from the app which invokes the function it's easy to use while being readable, assumed you change the function name for something like invalidUser(). So the app can work like this:

if ($errorMessage = invalidUser(...)) {
  // take any appropriate action, using $errorMessage
}
// otherwise merely continue


Pulling financial data via IEX Cloud API

This seems mostly to be an API question?  Assuming all that data for
each of the companies is required and there's no combined API endpoint
that can be fed with, say, 10s or 100s of symbols, this would seem to
be the best way.  If so, there'd still be possible concurrent execution
options to make multiple API requests at the same time and possible get
more throughput with it, though the number of API calls would still be
the same.

The streaming endpoints looking interesting at first, but they don't support the data here; any other endpoints all look like they only accept single symbols.

What you should definitely do is create a (few) function(s) and ideally
get rid of the try blocks.  From a first look I've zero idea where
stuff gets thrown.  But I'm guessing mostly keys not being present.
Preferably this could be handled directly (with default values or
similar features) that do not require lots of exception handling.  Yes,
Python might encourage this, but simply catching ValueError around a
huge block will eventually catch unintended exceptions too.

So at least something like this would be a good start:

def fetch_company_info(ticker):
    company = Stock(ticker, output_format='pandas')

    book_value = 0
    income_ttm = 0

    try:
        # Get income from last 4 quarters, sum it, and store to temp Dataframe
        df_income = company.get_income_statement(period="quarter", last=4)
        df_income['TTM'] = df_income.sum(axis=1)
        income_ttm = int(df_income.loc['netIncome', 'TTM'])

        # Get book value from most recent quarter, and store to temp Dataframe
        df_book = company.get_balance_sheet(period="quarter")
        book_value = int(df_book.loc['shareholderEquity'])

    # Ignore IEX Cloud errors
    except iexfinance.utils.exceptions.IEXQueryError:
        pass

    return income_ttm, book_value

I also shuffled the variables a bit around - with the right order this
could even be type checked ...

In any case, I can't see anything wrong here and I've removed the other
two exceptions as they look more like hiding problems than actual proper
handling of the exact problem that was encountered.  With the example
names I also couldn't trigger them at all.

The main body of the script is now rather small:

# Loop through companies in tickers list
for ticker in tickers:
    # Call IEX Cloud API, and store stats to Dataframe
    output_df.loc[ticker] = fetch_company_info(ticker)

print(output_df)

If there's no need for reusability then that's it, otherwise I'd suggest
a main function and moving all currently global definitions into it,
then have some argument parser or configuration file handling, etc. to
make it a more fully grown solution.

After some discussion in the comments it turns out that splitting the
return values from the assignment can lead to easy mistakes like the
order of the values being wrong.  With that in mind, either the output_df
global should be kept in the function, or (better) be passed in as
a variable instead:

for ticker in tickers:
    fetch_company_info(ticker, output_df)

and

def fetch_company_info(ticker, output_df):
    ...
    output_df[ticker] = [income_ttm, book_value]


Testing database table creation with NUnit

I would do something like this instead -

using(var conn = context.NewConnection()) {
    var table = conn.GetSchema("Tables");
    var tableNames = table.Rows.Cast<DataRow>()
                                            .Select(x => x["TABLE_NAME"].ToString())
                                            .ToArray();
    Assert.That(tableNames.Contains("NewTable"), Is.True);
}

Tests are usually structured in Setup-Act-Assert fashion. A good unit test is one that tests just one condition on an action.

Multiple asserts are practically unavoidable in certain cases, but having logic to decide when Assert should pass or fail isn't a good practice. The code under test should have the logic to branch, the test should only look at expected v/s actual results in a given scenario.

In this case, our setup is - we get the schema from the database, and get the list of column names.

Our logic (Act) is that certain column name must exist. So we write an assertion to ensure that.

In other cases, there is an action and a result, the assertion is on the result. In this case, it is more of testing a state, so there isn't an assertion on the result of an action.


Check if nullable int has value and compare value to another integer

There is really no need to check HasValue in this situation. It is sufficient to compare with highestWeightOfParcel because if collo.WeightGrammes is null the comparison is false for any value of highestWeightOfParcel:

int highestWeightOfParcel  = 0;

if (collo.WeightGrammes > highestWeightOfParcel)
{
    highestWeightOfParcel = collo.WeightGrammes.Value;
}


Pack several file documents into the single archive file in c#

Every file within the ZIP archive has the same path, so it would be awkward when extracting them.  You should either take another parameter enumerating the entry names, or generate them automatically using a counter.

There's a limit to the scalability of this code, since the input and output all have to fit within memory.  That problem can be avoided by accepting Streams instead of byte[]s for the input.  You should also accept a Stream to which the output should be written.  You could still do everything in memory by using MemoryStreams everywhere, but you would also have the flexibility to read from and write to files or the network.


Organizing a Python list of lists as function of number of occurances

Try this code:

def organize_in_decreasing_order(membership_list):
    conlist = np.concatenate(membership_list)
    count = np.bincount(conlist)
    ordered_list = np.argsort(count)[::-1]
    lookup = np.argsort(ordered_list)
    return [[lookup[i] for i in sublist] for sublist in membership_list]

Be aware that the function above returns the organized list, but - in contrast to your implementation - does not change the input argument. You should also be aware that when count has repeated elements, the lists yielded by both implementations may not coincide. The reason for the different behaviour is that ties are dealt with differently.


VBA, Transferring of Data from one File to another

Seems like instead of transferring, Copying the Data and using ThisWorkbook was able to get the job done easily.
Sub Mainsubtwo()

Call Reset
Worksheets("Main Data").Rows("12:" & Rows.Count).ClearContents

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'Open CM file
Set MainDataCM = Workbooks.Open(Sheets("Input").Range("B16") & Sheets("Input").Range("B19"))

With Sheets("Main Data")
lastrow = Sheets("Main Data").Range("A" & .Rows.Count).End(xlUp).Row
Sheets("Main Data").Range("A2:P" & lastrow).Copy
End With
'Paste into this workbook
ThisWorkbook.Sheets("Main Data").Range("A12").PasteSpecial xlPasteValues

'Close CM file
MainDataCM.Close SaveChanges:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True

Worksheets("Input").Activate
Worksheets("Input").Select

MsgBox "Step 1 Completed"

End Sub


How do I structure my entities for easier persistence?

You are not correct in assuming the above... If you want to count the number of rentals for one Movie you can do the following (given you are not removing records from your database):

@NamedQueries{
   @NamedQuery(name="Movie.getRentalCount",
       query="SELECT COUNT FROM Rentals r WHERE r.bookMovieId = :movieId")
}
@Entity
class Movie{

   @Transient
   public static final String getRentalCount = "uniqueQueryNameForMovie";

   // ...
}

This allows you to do the following in your purchase process:

@Inject
EntityManager entityManager;

public Long getRentalCountForMovieId(long movieId){
    TypedQuery<Long> q = entityManager.createNamedQuery(Movie.getRentalCount, Long);
    q.setParameter("movieId", movieId);
    return q.getSingleResult();
}

You'd need to use the wrapper class, as TypedQuery only accepts Objects as type.

Also it should be unneccesary to create Rental instances while changing the contents of your cart. They should only be created when you check the cart out in the end, because before that there is no need for a Rental instance...

If you decided to destroy the instances of Rental on return of the Movie: You should keep a record of older Rentals for historization and usability reasons.


More testing is required:
flux_capacitor("11:59 AM", 62)
 => "12:21 AM"

Definitely test some corner cases.

Updated Thoughts
I think you should completely rethink the way you are handling time.
Use a regex to validate that time is a valid string, then simply use string.split to get each portion of the time: hours, minutes, and AM/PM.
Next you should convert those into a quantity of minutes:
hours += 12 if meridian == 'PM'
total_minutes = hours*60+minutes+mins

Next I would recalculate the time as a 24-hour time (which goes up to 23 hours, 59 minutes):
# this is integer math so the decimal portion will be discarded
# adjusted_minutes may be greater than 23, but adjusted_minutes should always be less than 60
adjusted_hours = (total_minutes / 60)
adjusted_minutes = total_minutes - (60*adjusted_hours)

# modulus 24 converts adjusted_hours into 24-hour time
adjusted_hours = adjusted_hours % 24

Now convert to 12 hour time if necessary and determine if this is AM or PM
# the added mins may have been several days worth, so adjusted_hours might be very large.

if adjusted_hours > 12
    meridian = "PM"
    adjusted_hours -= 12
else
    meridian = "AM"
end

Finally return a string of the new time:
# zero pad the minutes, as this is expected for a time
return "%d:%02d %s" % [adjusted_hours, adjusted_minutes, meridian]

Final Solution
Since a solution that reliably passes all test cases has yet to be put forth...
def flux_capacitor(time, mins)
    #check if time in valid format
    time_match = time.strip.match /^(12|11|10|0?\d):([012345]\d)\s+(AM|PM)/

    #throw error on invalid time
    raise(ArgumentError, "Invalid time: #{time.strip}") if not time_match

    #calculate new time
    strhours, strminutes, meridian = time_match.captures
    hours = (meridian == "AM" ? strhours.to_i : strhours.to_i + 12)
    total_minutes = hours * 60 + strminutes.to_i + mins
    total_minutes = total_minutes % (24*60) # we only want the minutes that fit within a day
    adjusted_hours, adjusted_minutes = total_minutes.divmod(60)
    if adjusted_hours > 12
        adjusted_hours -= 12
        meridian = "PM"
    else
        meridian = "AM"
    end

    "%d:%02d %s" % [adjusted_hours, adjusted_minutes, meridian]
end

Testing:
[ "11:13 PM",
  "13:09 PM", #invalid!
  "1:59 AM",
  "04:49 PM",
  "4:79 PM" #invalid!
].each do |time|
    begin
      puts flux_capacitor(time, 0)
    rescue
      puts $!
    end
end
puts "----------"
puts "#{flux_capacitor("11:13 PM", 10)}, expected: 11:23 PM"
puts "#{flux_capacitor("11:13 PM", 12*60)}, expected 11:13 AM"
puts "#{flux_capacitor("11:13 PM", 24*60)}, expected 11:13 PM"
puts "#{flux_capacitor("11:13 PM", 24*60 + 1)}, expected 11:14 PM"
puts "#{flux_capacitor("11:59 AM", 62)}, expected 1:01 PM"
puts "#{flux_capacitor("11:59 PM", 62)}, expected 1:01 AM"


SQL stored procedure for fruit checks with several joins

There are a couple of things slowing you down.

Two Left Outer Joins and a Full Outer Join.

There may not be much you can do about this unless you can trim down the fields that need to be returned. Start with trying to remove the Full Outer Join. It will have worse performance than the Left Outer Joins.
Scanning an entire field will also be a bit on the slow side, but again, there may be little you can do beyond making sure there are proper indices on the table if this is truly a requirement.

LIKE '%' + @CheckUrlFilter + '%'

It looks very much like this is a requirement.
It's poor practice to select all fields from a table using the table.* notation. Doing this will force the RDBMS to lookup the table's meta data. I've found that it's pretty rare that I'll need every column from a table. It's best to be explicit about what you're selecting, even if you're selecting everything. Any performance improvement from this will be marginal, but it has the benefit of protecting your code from breaking if the underlying table changes.

I don't know enough about the data or requirements to give any real concrete advice, but nixing that Full Outer Join is the best bet for getting a performance boost. Looking at your query carefully, it doesn't seem that you ever select from Fruits so you should be able to replace the Null check on the ID with a Where Exists clause and get rid of the Full Outer Join altogether. Something like...

WHERE EXISTS(
        SELECT FRUITS.ID
        FROM FRUITS
        WHERE Fruits.CategoryID = FruitCategories.ID
)


Dirty Bash hack to run the ssh connections in the Parallel mode

The only part I would change are the chained if statements. Use case:
CurrntTime="some_timestamp"
MachineName="some_host"
for retval in 0 255 2 1 8; do
   echo "Testing exitcode ${retval}"
   case ${retval} in
   0)
        echo  "$CurrntTime $MachineName   : SSH connection is Up";;
   255)
        echo  "$CurrntTime $MachineName   : SSH Authentication Failed";;
   2)
        echo  "$CurrntTime $MachineName   : SSH connection is Down";;
   1)
        echo  "$CurrntTime $MachineName   : SSH Authentication Failed";;
   *)
        echo  "$CurrntTime $MachineName   : SSH connection is Down";;
   esac
done

More optimisation is not needed. The alternative beneath is slightly shorter but makes the code harder to read (more fun, though):
CurrntTime="some_timestamp"
MachineName="some_host"

ssh_err_0="connection is Up"
ssh_err_1="Authentication Failed"
ssh_err_2="connection is Down"
ssh_err_255="Authentication Failed"
ssh_err_other="connection is Down"

for retval in 0 255 2 1 8; do
   echo "Testing exitcode ${retval}"
   printf "%s" "$CurrntTime $MachineName   : SSH "
   case ${retval} in
   0|1|2|255)
      message="ssh_err_${retval}"
      echo "${!message}";;
   *)
      echo "${ssh_err_other}";;
   esac
done

When you use the first case in the total script, and move the SSH_Connection() function to the start of the script, it would be
#!/bin/bash

SSH_Connection () {
    hostTarget=${1}
    sshpass -e ssh -q "${hostTarget}" "true" -o StrictHostKeyChecking=no \
       -o ConnectTimeout=60 2>/dev/null

    case $? in
    0)
       echo  "$CurrntTime $hostTarget: SSH connection is Up";;
    255)
       echo  "$CurrntTime $hostTarget: SSH Authentication Failed";;
    2)
       echo  "$CurrntTime $hostTarget: SSH connection is Down";;
    1)
       echo  "$CurrntTime $hostTarget: SSH Authentication Failed";;
    *)
       echo  "$CurrntTime $hostTarget: SSH connection is Down";;
    esac
}

echo "$(date) Starting the SSH Connection Check...."

read -rsp $'Please Enter password below: ' SSHPASS
export SSHPASS

HostList=$(<~/host2)

CurrntTime=$(date +'%m/%d/%Y %T')

for MachineName in ${HostList}; do
   SSH_Connection "${MachineName}" &
done
# wait for all outstanding background jobs to complete before continuing
wait
# at last clear the exported variable containing the password
unset SSHPASS

I did not move the CurrentTime=$(..) inside the function. When you want to see the date/time after the ssh is finished, then you will need to store the exit code in a variable:
...
sshpass -e ssh ...
retval=$?
CurrentTime=$(date +'%m/%d/%Y %T')
case ${retval} in ...


Indentation
You should use four spaces instead of two.
Spacing
Your class methods should be separated by an empty line, so everything doesn't look so crowded.
Getters
Since all class variables are public (except _var and __var variables), you don't need to define getters to access these properties. Simple do Iterator.name, etc.
Iterator.__str__
You should utilize f"" strings to directly include variables in strings.
def __str__(self):
    return f"{self.name},{self.val}"


To solve the grouping problem, use itertools.groupby.
To read files with comma-separated fields, use the csv module.
In almost all cases, open() should be called using a with block, so that the files will be automatically closed for you, even if an exception occurs within the block:

with open(file_path) as in_f, open(destination, 'w') as out_f:
    data = csv.reader(in_f)
    # code goes here

filePath violates Python's official style guide, which recommends underscores, like your curr_line.


Iterating and fetching values from dictionary

In your code you write

    flag = 1
    if flag == 1:
        break

The if will always be True, so this is just

    flag = 1
    break

You only use flag for another if that also will always be True, so make this

    break
break

Simplifying this to

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []
result1 = ''
result2 = ''
for k,v in c_result1.iteritems():
    for k1,v1 in v.iteritems():
        result1 = k1
        result.append(result1)
        print 'result = ', result1
        break
    break
for k,v in c_result2.iteritems():
    for k1,v1 in v.iteritems():
        result2 = k1
        result.append(result2)
        print 'result = ', result2
        break
    break
print 'REsult is : , ', result

Removing the inner prints gives

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []
for k,v in c_result1.iteritems():
    for k1,v1 in v.iteritems():
        result.append(k1)
        break
    break
for k,v in c_result2.iteritems():
    for k1,v1 in v.iteritems():
        result.append(k1)
        break
    break
print 'REsult is : , ', result

This can be simplified by using itervalues and not calling iteritems on the inner loop:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []
for v in c_result1.itervalues():
    for k in v:
        result.append(k)
        break
    break
for v in c_result2.itervalues():
    for k in v:
        result.append(k)
        break
    break
print 'REsult is : , ', result

This is actually just the same as calling next twice:

help(next)
#>>> Help on built-in function next in module builtins:
#>>>
#>>> next(...)
#>>>     next(iterator[, default])
#>>>
#>>>     Return the next item from the iterator. If default is given and the iterator
#>>>     is exhausted, it is returned instead of raising StopIteration.
#>>>

However this is only simpler if you know it's going to succeed:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []

inner = next(c_result1.itervalues())
result.append(next(iter(inner)))

inner = next(c_result1.itervalues())
result.append(next(iter(inner)))

print 'REsult is : , ', result

Either way, one should make a function or use a loop to avoid repeating oneself:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
result = []

for c_result in (c_result1, c_result2):
    for v in c_result.itervalues():
        for k in v:
            result.append(k)
            break
        break

print 'REsult is : , ', result


Your write function is incorrect:

size_t WriteData( void *ptr, size_t size, size_t nmemb, std::FILE *stream ) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

CURL will abort the transfer if you do not return size*nmemb. So you need to take care to make sure that you actually write all the data provided.

Also this is the action of the default CURLOPT_WRITEFUNCTION so there is no need to write your own version.

You don't check if the File pointer is NULL

    File = std::fopen( Destination, "wb" );

This is a C function (even if you have used it from C++). This means you must check the return value to make sure the faction succeeded.

Don't artifically stop the application. You may forget to remove this and then it will make the program look like it is broken.

std::cin.get( );

If you run from the command line it is not needed. If you are running inside an IDE set up your IDE so that it does not close the output window when the application finishes.

If your program always succeeded. Then I prefer not to return an exit value from main(). The compiler in this one special case will plant a return 0; for you to indicate success. This is a good indication that you have designed your application so that it never fails.

return( EXIT_SUCCESS );

I only return a value if there is a potential for failure and I want to be able to indicate the possible failure states.


A Decorator that turns Function Annotations into Type Checks

This is a very very poor implementation.

Firstly the code has little care for nested datatypes, and makes them a pain to add in a future version.

To add support for this all that needs to be done is change the, per type, control flow to use recursion. The option to use standard loops rather than recursion is available too, however that will likely make the code harder to read.
The code just looks very error prone. Whilst RegEx has it's place in some limited scenarios, this is not then. The following snippet is almost never a good idea.

is_optional: bool = "Optional" in str(annotation)
if is_optional:
    annotation = re.search("Optional\[(.*)\]", str(annotation)).group(1)

This is the kind of nonsense I would expect of a junior that just learnt what RegEx is.
Whilst 'proper' low level typing inspection isn't that readable, mangling it with strings makes the code harder to read for people used to interacting with typing.

Also, when performing low level changes on core Python libraries read the PEPs that accompany them. They're their for a reason. For instance, PEP 484 states how to remove the need for using strings.

  The string literal should contain a valid Python expression (i.e., compile(lit, '', 'eval') should be a valid code object) and it should evaluate without errors once the module has been fully loaded. The local and global namespace in which it is evaluated should be the same namespaces in which default arguments to the same function would be evaluated.

Furthermore, reading the PEP is not required, as the typing documentation shows a function that does this out of the box.

  typing.get_type_hints(obj[, globals[, locals]])
  Return a dictionary containing type hints for a function, method, module or class object.

Whilst I can understand that hacking a solution may be the most fun way to implement something. It's how I learnt the typing library. You should at least read the documentation of the module. Python's documentation is very high-quality, and ignoring it leads to poor code.

Here's a naive implementation:

import typing
import inspect

def is_type(instance, type_info):
    if type_info == typing.Any:
        return True
    if hasattr(type_info, '__origin__'):
        if type_info.__origin__ in {typing.Union, typing.Optional}:
            return any(is_type(instance, arg) for arg in type_info.__args__)
    return isinstance(instance, type_info)

def enforce_types(func):
    types_info = typing.get_type_hints(func)
    signature = inspect.signature(func)

    def inner(*args, **kwargs):
        sig = signature.bind(*args, **kwargs)
        sig.apply_defaults()
        for name, value in sig.arguments.items():
            if not is_type(value, types_info.get(name, typing.Any)):
                raise TypeError(
                    '{name} is not of the correct type'
                    .format(name=name)
                )
        return func(*args, **kwargs)

    return inner


A function that returns all letters in the Alphabet except the ones in a pre-defined list

I suggest you check PEP0008 https://www.python.org/dev/peps/pep-0008/ the official Python style guide and Flake8 http://flake8.pycqa.org/en/latest/ as a tool for style enforcement.

Docstrings: Python documentation strings or docstrings are a way of documenting your classes/function/modules and are usually accessed through help(). You should include docstrings to your functions indicating what they do and what they return.
Type hints: Type Annotations are a new feature added in PEP 484 that allow for adding type hints to variables. They are used to inform someone reading the code what the type of a variable should be. As you're taking a list as input and will return a string, you should have some documentation indicating that. Use type hints.

function should look like:

def get_remaining_letters(letters: list) -> str:
    """Return lowercase alphabetic letters that are not present in letters."""

Blank lines: instead of this # ----------------------------------------------------------- # an empty line is sufficient and note that according to PEP0008 empty lines as well as comments should be used sparingly (when necessary) to separate logical sections as well as explain the not-so-obvious parts of the code.
main guard: use if __name__ == '__main__': guard at the end of the script to allow outside modules to import this module without running it as a whole. You will be calling your functions from there.

if __name__ == '__main__':
    pre_defined_list = ['a', 'b', 'b']
    test = get_remaining_letters(pre_defined_list)
    print(test)

Evaluation to empty list: In Python empty sequences evaluate to False.
instead of if list_of_characters == []: it is written: if not list_of_characters:
Adding to strings: Python strings are immutable which means that each time you're adding to a string like in remaining_letters += char a new string is created and assigned the new value which is inefficient and should be replaced with list comprehension syntax which is shorter and more efficient or Pythonic as you call it.

An improved version of the code:

import string

def get_remaining_letters(letters: list) -> str:
    """Return lowercase alphabetic letters not present in letters."""
    return ''.join(letter for letter in string.ascii_lowercase if letter not in letters)

if __name__ == '__main__':
    chosen = [letter for letter in 'sdfmmmsvvd']
    print(get_remaining_letters(chosen))


By changing the start and end points to start+epsilon/2 and end-epsilon/2, we can simplify the calculation tremendously. This means that the domain is what we want to evaluate the function at, removing the zip and averaging logic, secondly, because we now have heights of the same length as domain, we can just call f(domain), to have it update in place. Finally, we can use np.sum to return the answer. Put together, these changes result in simpler code, and roughly 100x faster (especially for small epsilon)

def integral1(f, left, right, epsilon):
    left += epsilon / 2
    right -= epsilon / 2
    domain = np.linspace(left, right, (right-left) // epsilon)
    return np.sum(f(domain), dtype = np.float128) * epsilon


Simple POST function in ClojureScript and Node.js

Looks great! Some minor suggestions; pull the parsed-url aset into a doto, and that naming the request req isn't very useful. Prefer dash to underscore.

(let [parsed-url (doto (.parse url url_str)
                   (aset "method" "POST"))]
  (doto (.request http parsed-url cb)
    (.write data)
    (.end)))


I would convert your fooColl to this:

IEnumerable<ColumnItsValues> foolCols = listColumns.Join(listValues,
            columns => columns.PropertyID,
            values => values.PropertyID,
            (columns, values) => new ColumnItsValues
                                 {
                                     ColumnName = columns.ColumnName,
                                     ValueOfColumn = values.ValueOfColumn
                                  });

in this way you're using a type you already know (ColumnItsValues), which make it more extendable/testable/readable.
About where == vs equals, I suggest to take a read to this blog post.

Alternatively, if as required by comments, you can change fooCols in this way:

IList<ColumnItsValues> foolCols = listColumns.Join(listValues,
            columns => columns.PropertyID,
            values => values.PropertyID,
            (columns, values) => new ColumnItsValues
                                 {
                                     ColumnName = columns.ColumnName,
                                     ValueOfColumn = values.ValueOfColumn
                                  }).ToList();

or

ColumnItsValues[] foolCols = listColumns.Join(listValues,
            columns => columns.PropertyID,
            values => values.PropertyID,
            (columns, values) => new ColumnItsValues
                                 {
                                     ColumnName = columns.ColumnName,
                                     ValueOfColumn = values.ValueOfColumn
                                  }).ToArray();

Depends on which additional functionalities you need and on your final purpose. My choice usually is try to keep my objects as simple and lightweight as possible. Both the array and the list extends IEnumerable<T>: IList<T> gives the capability to insert/remove at a given index and, since it is an extension of ICollection<T> permits you Add, Clear or check if it Contains an element, on the other hand if you keep using arrays (ColumnValues[]) the lenght would be immutable.


Using vswprintf( ... ) to create wchar_t* with variable argument list

The code you have written is fine, apart from three small issues:

You need to check that format isn't null before calling vswprintf otherwise it crashes.
There seems to be the potential for memory leaking, you are assuming the caller will always release the memory.  It would return a std::wstring instead, no need to new the buffer and it is "automatically" released.
Check the results of vswprintf_s() it will almost never fail, but when it does you'll be trying to track down what went wrong for days. :)

This is my version:
// the caller will free the memory
std::wstring getMessage(const wchar_t* format, ...)
{
    std::wstring output;                                            // function return value.
    if (format != nullptr)
    {
        va_list args;
        va_start(args, format);
        const auto size = vswprintf(nullptr, 0, format, args);      // get the size of the final string
        if (size > 0)                                               // If the above call worked
        {
            const auto buffSize = 1 + size;
            output.reserve(buffSize);                               // create the buffer
            if (vswprintf_s(output.data, buffSize, format, args) < 0)// create the string
            {
                output.clear();                                     // Empty the string if there is a problem
            }
        }
        va_end(args);
    }
    return output;
}


Constructor to transform an Outlook contact into a Dynamics CRM contact

You could create a helper function with a loop:

public string getFirstNonNullOrEmpty(params string[] names) {
    foreach (string name in names) {
        if (String.IsNullOrEmpty(name)) {
            continue;
        }
        return name;
    }
    return @"Naam niet bekend";
}

Usage:

LastName = getFirstNonNullOrEmpty(contactItem.LastName, contactItem.FirstName,
    contactItem.FullName, contactItem.CompanyName, contactItem.Email1Address);

You might also need this because of the else branch:

if (String.IsNullOrEmpty(contactItem.LastName))
    && !String.IsNullOrEmpty(contactItem.FirstName)) {
    FirstName = "";
}

You might want to use IsNullOrWhiteSpace instead of IsNullOrEmpty.

(I'm not too familiar with C# and don't have a C# compiler right now so the syntax might be invalid.)


First thing: congratulations on starting with rspec! Way to go.

My first remark would be to remove your three first contexts (Fields, Associations & Validations).

Why? Because those are not testing any parts of your code - they are testing ActiveModel functionalities. You want to test your code, not your librairies - at least, not without a very good reason to think that there is a problem there. This is time spent to write specs that do not provide any benefits.

On the other side, while your model don't have much logic yet, I like the fact that you tested your scopes - this is your logic, and it should be tested.


You can use an if statement and the conditional operator:

string label;
if (ctrl.IrregularCouponFirst) {
  label = ctrl.IrregularCouponLast ? "label.Both" : "label.First";
} else {
  label = ctrl.IrregularCouponLast ? "label.Last" : "label.None";
}
return LocalString.Evaluate(label);

You can also use only conditional operators. This way of chaining conditional operators checks take a bit of work to grasp the first time, but it's very compact:

return LocalString.Evaluate(
  ctrl.IrregularCouponFirst && ctrl.IrregularCouponLast ? "label.Both" :
  ctrl.IrregularCouponFirst ? "label.First" :
  ctrl.IrregularCouponLast ? "label.Last" :
  "label.None"
);


It's strange that you would call this.componentDidMount. I have not seen this before. Either way, what if you created an indicator in your state that declared what should be shown? For example:

this.state = {
  dataRecent : [],
  dataAlltime : [],
  display: "recent"
}

Then inside of your render function you can choose what gets displayed.

this.state.display === 'recent'
  ? this.state.dataRecent.map...
  : this.state.dataAlltime.map...

I would create two functions that handle getting both sets of data.

getAlltimeData() => {
   fetch(API+"alltime")
    .then(response => response.json())
    .then(data => this.setState({ dataRecent:data }))
}

getRecentData() => {
   fetch(API+"recent")
    .then(response => response.json())
    .then(data => this.setState({ dataRecent:data }))
}

You can then call both of them when the component mounts.

componentDidMount() {
  this.getAlltimeData();
  this.getRecentData();
}

At this point you have the data you need. What you don't have is a click handler to switch between recent and all time.

handleRecentClick() {
  this.setState({ display: 'recent' });
}

handleAlltimeClick() {
  this.setState({ display: 'allTime' });
}

Pass those to the buttons that change state respectively.

 <button onClick={this.handleRecentClick}>All Time Sort</button>
 <button onClick={this.handleAlltimeClick}>Recent Sort</button>

Make sure to bind your functions in the constructor like you did with the others.


Initial impressions:

public Node newNode(T data) shouldn't be on the interface, why would anything outside of the list need to construct one?
print shouldn't be on the interface, I know you say it's for debugging, but a better approach would be to provider an iterator so that something outside the list could iterate the items and print them.
I don't like the fact that Node is visible outside of the list class.  It reveals too much of the underlying functionality.  What happens if I call 'newNode' then pass the contents of it to the delete method?
One of your delete methods takes in a 'delete_at' parameter, then ignores it in certain conditions and deletes the last member of the list instead...

public void delete(ILinkedList.posForOperation delete_at, ILinkedList.Node node) {
        if(node.next == null)
            delete(ILinkedList.posForOperation.END);
        else if(delete_at == ILinkedList.posForOperation.AFTER){

void deleteAtPos(int pos), there's no way for a caller to really know where in the list an item is (unless they count as they insert them?), so what's the purpose of this method?


Can this LINQ lambda expression be written any better?

LINQ isn't as rigid about the order of clauses as SQL is (this applies to both syntaxes). This means that if you switch your Join around, you can put your Where before your Join.
If you have Select right after Join, you can combine the two together.
When the property you're using in an anonymous object creation expression has the same name as the one you're assigning it to, you can omit the name.

This means that your code could be simplified to this:

COURSE_RELATED_VERSIONS
.Where (crv => crv.COURSE_ID == 38890 && crv.COURSE_PARENT_NODE_ID == -1)
.Join (
   COURSE_TREEs,
   crv => crv.COURSE_NODE_ID,
   ct => ct.COURSE_NODE_ID,
   (crv, ct) => new { ct.COURSE_NODE_ID, ct.NODE_TEXT }
)

But in general, if you're doing something more complicated, you need to follow the pattern in your question. Which is exactly why the query syntax exists: it can make complicated queries much simpler.

Also, I would suggest that your tweak your mapping so that the names follow usual .Net naming conventions (e.g. CourseRelatedVersion or CourseNodeId).


On right click draw triangle to the canvas

General problems

It is better to add events via addEventListener rather than in the HTML, this keeps the source code together making it easier to maintain. It also protects your code from 3rd party code overwriting the event handler. If some code later sets window.onload = theirFunction; it overwrites your event that will not get called.
Keep your variables out of the global scope if possible. stage and triangle do not need to be in global scope. triangle is only used in the one function so define it there.
Use const rather than var if you do not intend to modify a variable.
Don't let lines get too long. 80 character is the usual limit. If a line gets longer than that break it into multiple lines.
Right click will bring up the context menu. You can prevent this by listening to the contextmenu event and calling preventDefault on the event object.
Why the defaulting to keyCode? is that even defined for the easelJS event ?
Don't add needless code. You define a variable for evt.nativeEvent, and e.which. These are not really needed.
Use correct names for variables. You use key for which button is pressed, this can be confusing when code gets longer.
You say you want to add a triangle on the right click but the code you had will add a triangle for any button except the left button.
Make your code easier to read by using spaces after commas, between operators, after statements and befor { eg if(bar===poo){foo(a,b+2,c);} is better if (bar === poo) { foo(a, b + 2, c); }

The rewrite

Rewrite of your code using the above.

body{
    margin: 0;
    background-color: #d3d3d3;
    font-family: Sans-Serif;
}

h1{
    font-weight: 100;
    text-align: center;
}

canvas{
    display: block;
    margin: auto;
    background-color: #ffffff;
    border: solid 1px #000000;
}
<!DOCTYPE html>

        <title>Draw Triangle</title>
        <link rel="stylesheet" href="styles.css"/>

Right click to draw a Triangle to the canvas

        <canvas id = "myCanvas" width = "900" height = "700"></canvas>

Additional notes.

I don't know what your intention is but the triangle seems a little odd not being centered on the mouse click. Also I would define the triangle as a abstract path rather than hard coded to the function.

Is there a reason you put the code in the head of the document. You could have placed it at the bottom of the page and avoided having to wait for the page load event.

Also, maybe you are wanting to learn easelJS, but the load time of easelJS is substantial and what you do can just as easily be done using the native 2D API.

I strongly believe that you should have a very good reason to use a 3rd party library, especially when you are learning. You are best spending your time learning the native (and very good and performant) APIs. You may not always be able to use the library, but you will always have access to the native API

Rewrite without easelJS

To match your code I have implemented a very simple stage. Though what you do does not require a stage object and could be a lot simplier.

// Please note this code uses a compact style for single line statements
// There is no ; before the closing } to comply with JSLint rule
// "Semicolan must be followed by newline."

;(() => { // wrapping your code inside a function alows you to keep the global scope clean
          // the ; befor the ( is to prevent code above it without a ; from
          // mistaking the ( as a function call

  const canvas = document.getElementById("myCanvas");
  const ctx = canvas.getContext("2d");

  const shapes = { // you could add more shapes here
    triangle: [ [0, -20], [20, 20], [-20, 20] ], // coordinates of triangle
  };

  addEventListener("load", init); // add the load event listener

  // implement a stage object to hold shapes
  const stage = {
    shapes: [],
    addShape(x, y, color, path) { this.shapes.push({x,  y, color, path }) },
    update() {  // function to redraw all shapes on the stage
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      this.shapes.forEach((shape) => {
        var i;
        ctx.fillStyle = shape.color;
        ctx.beginPath();
        i = 0;
        while (i < shape.path.length) {
          ctx.lineTo(  // sometimes it is best to break up complex lines
              shape.path[i  ][0] + shape.x,
              shape.path[i++][1] + shape.y
          )
        }
        ctx.closePath();  // this is really only needed if you are using stroke
        ctx.fill();
      });
    }
  };

  function init() {
    canvas.addEventListener("mousedown", mouseDown);
    canvas.addEventListener("contextmenu", event => event.preventDefault() );
    function mouseDown(event) {
      const bounds = event.target.getBoundingClientRect();
   const x = event.pageX - bounds.left - scrollX;
   const y = event.pageY - bounds.top  - scrollY;
      if (event.which === 3) {
        stage.addShape(x, y, "black", shapes.triangle);
        stage.update();
      }
    }
  }
})();
body {
  margin: 0;
  background-color: #d3d3d3;
  font-family: Sans-Serif;
}

h1 {
  font-weight: 100;
  text-align: center;
}

canvas {
  display: block;
  margin: auto;
  background-color: #ffffff;
  border: solid 1px #000000;
}
<!DOCTYPE html>

  <title>Draw Triangle</title>

Right click to draw a Triangle to the canvas

  <canvas id="myCanvas" width="900" height="700"></canvas>

The simplest way to achieve the same functionality.

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const triangle = [ [0, -20], [20, 20], [-20, 20] ];
canvas.addEventListener("mousedown", mouseDown);
canvas.addEventListener("contextmenu", e => e.preventDefault() );
function mouseDown(event) {
  const bounds = event.target.getBoundingClientRect();
  const x = event.pageX - bounds.left - scrollX;
  const y = event.pageY - bounds.top  - scrollY;
  if (event.which === 3) { drawShape(x, y, triangle) }
}
function drawShape(x, y, shape) {
  var i = 0;
  ctx.fillStyle = "black";
  ctx.beginPath();
  while (i < shape.length) { ctx.lineTo( shape[i][0] + x, shape[i++][1] + y ) }
  ctx.fill();
}
body {
  margin: 0;
  background-color: #d3d3d3;
  font-family: Sans-Serif;
}

h1 {
  font-weight: 100;
  text-align: center;
}

canvas {
  display: block;
  margin: auto;
  background-color: #fff;
  border: solid 1px #000;
}

Right click to draw a Triangle to the canvas

  <canvas id="myCanvas" width="900" height="700"></canvas>


Formatting XML strings in JavaScript for readability

I've been looking something like this, nice idea. But Your function couldn't parse text nodes. Try insert some text, example:

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body>textNode<soapenv:temp>innerText</soapenv:temp><ns:temp><ns:getCourseResponse xmlns:ns="http://course.ws.blackboard" /></ns:temp></soapenv:Body></soapenv:Envelope>

My proposition for this problem is:

1) change spliting code in this way:

.replace( /(<([a-zA-Z]+\b)[^>]*>)(?!<\/\2>|[\w\s])/g, "$1\n" ) //add \n after tag if not followed by the closing tag of pair or text node
.replace( /(<\/[a-zA-Z]+[^>]*>)/g, "$1\n") //add \n after closing tag
.replace( />\s+(.+?)\s+<(?!\/)/g, ">\n$1\n<") //add \n between sets of angled brackets and text node between them
.replace( />(.+?)<([a-zA-Z])/g, ">\n$1\n<$2") //add \n between angled brackets and text node between them
.replace(/\?></, "?>\n<") //detect a header of XML

2) little modify third statement else if and add one more:

 else if (/<.*>/.test(line)) //if the line starts with an opening tag and does not contain an entire node
 {
  xmlArr[i] = tabs + line;  //add the tabs at the beginning of the line
  tabs += indent;  //and add one indent to the store
 }
 else  //if the line contain a text node
 {
  xmlArr[i] = tabs + line;  // add the tabs at the beginning of the line
 }

So finaly, our function will be:

function formatXML(input,indent)
{
  indent = indent || '\t'; //you can set/define other ident than tabs

  //PART 1: Add \n where necessary
  xmlString = input.replace(/^\s+|\s+$/g, '');  //trim it (just in case) {method trim() not working in IE8}

  xmlString = input
                   .replace( /(<([a-zA-Z]+\b)[^>]*>)(?!<\/\2>|[\w\s])/g, "$1\n" ) //add \n after tag if not followed by the closing tag of pair or text node
                   .replace( /(<\/[a-zA-Z]+[^>]*>)/g, "$1\n") //add \n after closing tag
                   .replace( />\s+(.+?)\s+<(?!\/)/g, ">\n$1\n<") //add \n between sets of angled brackets and text node between them
                   .replace( />(.+?)<([a-zA-Z])/g, ">\n$1\n<$2") //add \n between angled brackets and text node between them
                   .replace(/\?></, "?>\n<") //detect a header of XML

  xmlArr = xmlString.split('\n');  //split it into an array (for analise each line separately)

  //PART 2: indent each line appropriately

  var tabs = '';  //store the current indentation
  var start = 0;  //starting line

  if (/^<[?]xml/.test(xmlArr[0]))  start++;  //if the first line is a header, ignore it

  for (var i = start; i < xmlArr.length; i++) //for each line
  {
    var line = xmlArr[i].replace(/^\s+|\s+$/g, '');  //trim it (just in case)

    if (/^<[/]/.test(line))  //if the line is a closing tag
     {
      tabs = tabs.replace(indent, '');  //remove one indent from the store
      xmlArr[i] = tabs + line;  //add the tabs at the beginning of the line
     }
     else if (/<.*>.*<\/.*>|<.*[^>]\/>/.test(line))  //if the line contains an entire node
     {
      //leave the store as is
      xmlArr[i] = tabs + line; //add the tabs at the beginning of the line
     }
     else if (/<.*>/.test(line)) //if the line starts with an opening tag and does not contain an entire node
     {
      xmlArr[i] = tabs + line;  //add the tabs at the beginning of the line
      tabs += indent;  //and add one indent to the store
     }
     else  //if the line contain a text node
     {
      xmlArr[i] = tabs + line;  // add the tabs at the beginning of the line
     }
  }

  //PART 3: return formatted string (source)
  return  xmlArr.join('\n');  //rejoin the array to a string and return it
}


You have a bug: if dt is a Sunday, then it outputs the date range starting from the previous Sunday.  That is because datetime.isocalendar() represents the day of week as a number from 1 (= Monday) to 7 (= Sunday), but you want to subtract 0 to 6 days.

>>> print week_string(date(2014, 01, 19))
Jan 12 - 18, 2014

My recommendation:

def week_string(dt):
    # Use underscore to indicate disinterest in the year and week
    _, _, weekday = dt.isocalendar()
    week_0 = dt - timedelta(days=weekday % 7)  # Sunday
    week_1 = week_0 + timedelta(days=6)        # Saturday

Then, I would write the following six lines more compactly:

    day_0, month_0, year_0 = week_0.strftime('%e-%b-%Y').lstrip().split('-')
    day_1, month_1, year_1 = week_1.strftime('%e-%b-%Y').lstrip().split('-')

The rest of it seems fine.


For the first problem I suggest you some performance improvements. You can use inclusion-exclusion technique for this problem.

So first improvement

def calculate_the_sum(threshold = 10):
    return(sum(range(3, threshold, 3)) + sum(range(5, threshold, 5)) - sum(range(15, threshold, 15)))

def main():
    threshold = 1000000
    print(' Calculates the sum of all numbers that are multiples of 3 or 5')
    print(' The Sum of numbers below {} is: {}'.format(threshold,calculate_the_sum(threshold)))

if __name__ == "__main__":
    main()

I have tested both solutions in ideone (Python 3) for threshold=1000000. Your solution ~ 0.20s. My ~ 0.05s.

Next – you can use well known formula for the sum of arithmetic progression.


Finding the nearest defibrillator exercise from CodingGames

The main observation I would make is that this code — particularly the for loop — looks very procedural.  To find the minimum of some collection as determined by some metric, use .minBy[B](f: (A) ⇒ B): A.

For readability, avoid interleaving function definitions with the execution flow.  Put all of the definitions first, if possible.

You potentially split each defibrillator input line twice: once to extract the coordinates, then maybe again if you are interested in extracting the name.  I suggest parsing each line once and constructing a case class object from it.

Your sanitizeString function is rather heavy-handed.  To parse French-formatted decimals, use java.text.NumberFormat.

Note that defibrilatorCount is misspelled.

Suggested solution

import math.{cos, sqrt}
import io.StdIn.{readInt, readLine}
import java.text.NumberFormat
import java.util.Locale

object Solution extends App {
  val frenchFmt = NumberFormat.getInstance(Locale.FRANCE)
  def parseDouble(s: String): Double = frenchFmt.parse(s).doubleValue

  case class GeoObject(long: Double, lat: Double, name: String)

  def parseDefibrillator(line: String): GeoObject = {
    val fields = line.split(";")
    GeoObject(parseDouble(fields(4)), parseDouble(fields(5)), fields(1))
  }

  def distanceMetric(a: GeoObject, b: GeoObject): Double = {
    val x = (a.long - b.long) * cos((a.lat + a.lat) / 2)
    val y = a.lat - b.lat
    6371 * sqrt(x * x + y * y)
    // Note: 6371 * sqrt is optional, if just comparing distances
  }

  val player = GeoObject(parseDouble(readLine), parseDouble(readLine), null)
  val count = readInt
  val nearest = (0 until count).map(_ => parseDefibrillator(readLine))
                               .minBy(distanceMetric(player, _))
  println(nearest.name)
}


Having a parent respond to a child's event

It's really hard to judge if exposing selector is the "right" thing to do without reviewing more of your source code.
Also, it depends on your architecture design. If you're using a Model View Controller approach, then yes. Elements associated with the view will be exposed.
Check out some of the examples for Backbone.js.
Here are some other factors that come into play:

Coding standards
size of your source
how strictly you're required to follow Object Oriented Programming, OOP.
who will maintain your code.

The code you provided looks great. As long as you produce consistent readable code that has a good level of data abstraction and works, then you shouldn't worry about the small details.
If you're still concerned about it though then just create an adapter for the .bind().
Old Code:
ordersSearchResult.selector.bind('searchResultLinkClicked', function () {
    ordersEditDisplay.hide();
    ordersSearchDisplay.fadeIn();
});

New Code:
...
OrdersSearchResult.prototype.bind = function(eventName, fn ){
    this.selector.bind( eventName, fn );
};
...
var ordersSearchResult = new OrdersSearchResult();
ordersSearchResult.bind('searchResultLinkClicked', function () {
    ordersEditDisplay.hide();
    ordersSearchDisplay.fadeIn();
});

Here are a few additional tips.
1) Name variables and properties based on their overall purpose and type.

Programmer A: There's a problem with orders in your code.
Programmer B: Which one? Are you talking about the function, jQuery object, element id, or something else?

To avoid this situation, create unique names assuming the language is case insensitive.
Old code:
$(function Orders() {
    "use strict";
    var orders = $('#Orders');
    ...

New code:
$(function OrdersFunc() {
    "use strict";
    var $orders = $('#OrdersTable');
    ...

More info here: "How to name variables"
2) Add the dollar sign as a prefix for jQuery variables.
It would make more sense to rename selector as $el.
3) Try not to create method names that are the same from a different library API.
ordersEditDisplay.hide() sounds like ordersEditDisplay returns a jQuery object, but that isn't the case.
Instead of ordersEditDisplay.hide();, try ordersEditDisplay.hideView();
4) Use the Singleton Pattern or an object literal to create a namespace.
Great examples can be found here
Final Code:
var mySite = {};
mySite.Orders = {};
mySite.Orders.init = function() {
    "use strict";
    var $orders = $('#OrdersTable');

    var ordersSearchResult = new OrdersSearchResult();
    var ordersSearchDisplay = new OrdersSearchDisplay();
    var ordersEditDisplay = new OrdersEditDisplay();

    ordersSearchResult.$el.bind('searchResultLinkClicked', function () {
        ordersEditDisplay.hideView();
        ordersSearchDisplay.fadeInView();
    });
};
$(mySite.Orders.init);


I have a few suggestions for optimizing your code.
Since ES6 came out it is considered best practice to declare variables as const. It is also a good practice to declare your variables at the top of your script.  For example you are selecting the element #ddlApplicationType everytime you loop over your array. That is not necessary. Just select it once at the top of your script and reuse it as often as you want in your code by referencing the variable const selectApplicationType.  If you know that you are going to reassign a variable you can use the let keyword. Like I did in the $.each function. temp gets reassigned everytime the $.each loops over it. I declared it inside this function because it is a temporarly used variable and will never be needed in the global scope.
When using DOM elements you should check if they exist first. For example if you have multiple pages and a DOM element referenced in your code is missing all the following code will break.
In the example below I used string literals. I think it makes the code a bit more readable. I hope I could help you.
const AppType = [
    ['All'],
    ['API'],
    ['AWS'],
    ['Web']
];
const selectApplicationType = $("#ddlApplicationType")

if (selectApplicationType.length > 0) {
    $.each(AppType, (index, AppType) => {
        let temp = `<option value="${AppType}">${AppType}</option>`
        selectApplicationType.append(temp)
    })
} else {
    console.log(`Element #ddlApplicationType is missing`)
}


Yes, there is a more efficient solution that still uses recursion; specifically, using Tail Recursion.

When you return n * factorial(n-1);, the compiler can’t optimize the call away because it still has more work to do when the call to factorial(n-1) returns; it has to do the multiplication, and return the result.

If, instead, you ended the function with return factorial(arguments);, the compiler can optimize away both the call and the return with a jump to the start of the factorial function, with the new arguments.  No additional stack frames are required.  The arguments you need to pass would be the original argument(s) and any “running total”.

int factorial(int n, int product=1) {
    if ( n <= 1 )
        return product;
    return factorial(n-1, n*product);
}

The difference between your implementation and a tail-recursive one can be seen by trying to calculate factorial(1000000000).  Your implementation will require 1 billion stack frames, which should likely crash the program.  A tail-recursive algorithm uses only 1 stack frame, so it will return the (incorrect) answer of zero.

(Why zero?  Assuming 32-bit integer, 34! has 17 even numbers, 8 multiples of 4, 4 multiples of 8, 2 multiples of 16, and a 32, which means the answer is has 17+8+4+2+1=32 powers of 2.  And any number multiplied by 2^32, modulo 32-bits is zero.  Any higher factorial is a multiple of 34!, so will also evaluate as zero.)


This is the way I would approach it. Live demo here: http://jsbin.com/iHEgalU/3/edit
Sure, bad js can slow your site down. Something like this is going to be pretty fast no matter what you do (unless you go out of your way to make it slow), but better is better and I say it's good to write the best, fastest, and most totally rock-sauce code you possibly can. So here goes.

Some people may consider it overkill considering the simplicity of your task, but I prefer writing in a manner that allows me to easily expand my script while keeping everything tidy and following good practices. You can extract the improved logic and use it in whatever style you like. I have commented this quite a bit. Refer to the live demo where there are no comments if you'd rather see it that way.

<input id="text_site_search" type="text" name="text_site_search" value="Site Search">

Avoid inline event functions! Notice that I have removed them from the html and put them in the js where they belong! This is much cleaner! HTML can't "do" things, so it doesn't need to know about click functions.

var myStuff = {
  options: { //these will be defaults, used if a parameter is not passed to init()
    sel: '',
    placeholder: 'My Placeholder'
  },
  init: function(sel, placeholder) { //this will kick everything off, that's all we need to run, you can pass options in like this or by object. I tend to use objects, but no need here.
    if (sel) { this.options.sel = sel }
    if (placeholder) { this.options.placeholder = placeholder }
    //there are several ways you could replace the passed in options...this is just an example that's ok for this case. jQuery has a method called $.extend, for example

    var obj = this; //cache a reference to "this" which currently refers to "myStuff"
    var inputSearch = document.getElementById(sel); //search the dom for the element and cache the reference
    //no need to keep searching the dom for an element. Search once and store the result.

    inputSearch.addEventListener('focus', function() {
      if (this.value === obj.defaultValue) { //"this" refers to the element when inside an event handler
        this.value = '';
      }
    });

    inputSearch.addEventListener('blur', function() {
      if (this.value === "") {
         this.value = obj.defaultValue;
      }
    });
  }
};

myStuff.init('text_site_search', 'Site Search');

The options thing here isn't really all that helpful given the simplicity. If this is all this will ever do, I'd probably just use the parameters directly (just use sel where you need it), but I wanted to demonstrate the concept.

Note: IE8 and lower do not support addEventListener. Look up the conditional that deals with that issue if needed.

The funny thing about this whole script is that it is remarkably similar to html5 placeholders, though older browsers won't support that.

<input type="text" name="text_site_search" placeholder="Site Search">


Conditional functions or multiple similar definitions?

My question is: are there any performance issues with the conditional functions approach?

In a word: no.

The additional performance cost is an extra select statement, whose cost probably depends on the number of switch options in the select.

I say "no" because I expect that the performance cost for a few extra instructions is measured in nanoseconds: and there aren't enough keystrokes per second for that to make a difference. Also the actual work you do (i.e. calling OpenGL functions) is probably/hopefully more significant than the performance of the code required to get there; it's like, "Q: Is calling a subroutine expensive? A: Probably not as expensive as executing/running the subroutine."

The befit of using "function pointers" (or perhaps a different subclass for each screen) is more to do with the code's maintainability and readability: for example, it would let you have different people creating each screen; to be contrasted with having a single KeyInputProcess function, where all handling for every screen is defined in the same function.

Taking the trouble to create an abstract base class for a screen (with concrete subclasses for specific screens, and a virtual KeyInputProcess method) may make more code more maintainable (easier to add new functionality without changing existing functionality, nor requiring previously-simple methods to become too complicated)
On the other hand, for a smaller project with one programmer, defining many abstract and concrete classes might be 'over-engineering' (the Wikipedia article for over-engineering says, "See also: YAGNI"). Beware that if you practice YAGNI then, later when you do need it, you ought to be good at refactoring: i.e. adding structure later to previously less-structured code, where I'd regard "conditional statements within one function" as 'less structured' and "abstract base class with subclasses" as 'more structured'.

  Which approach is better if I want to maximize performance?

Possibly a function pointer: because it's only one or two opcodes to dispatch to the right function, instead of testing several switch statements (assuming that the compiler implements select as "if else if else if else if").

It's also possible that a function pointer isn't as fast: it dispatches to a different location i the code, which may cause slowness due to memory pages and CPU caching; whereas instead a monolithic KeyInputProcess function might have all its code located on the same page of memory.

In either case I doubt whether the performance difference is significant in this case (handling keystrokes).


SQL Query to perform a "reverse exclusion" on a LEFT JOIN with a select from the left side table

You already have the table2_vals you need.
Just cross join them with table1. No need for long nested stuff and group by:
select t1x.Table1_Id,q.Table2_Val
from
    Table1 t1x
    cross join
    (
        SELECT t2.Table2_Val
        FROM Table2 t2
        LEFT JOIN Table1 t1 ON t2.Table2_ID = t1.Table1_ID
        WHERE t1.Table1_ID IS NULL
    )q


Is it really \$O(n\log n)\$?

Inside your main loop, you have this line:

            currPartial.remove(pointMap.get(sortedTimes.get(i)));

which removes a Point object from a linked list.  This takes \$O(n)\$ time, so your whole algorithm takes \$O(n^2)\$ time.

Not only that, but this line which copies the best list so far is also \$O(n)\$ time:

           bestPartial = new LinkedList<Point>(currPartial);

Possible fixes

You could fix the first problem by using a data structure other than a LinkedList.  For example, you could use a HashSet or LinkedHashSet.

You could fix the second problem by not making a copy of the best solution.  Instead, remember the index i of the best solution.  Then when you want to print the best solution, make another pass through the sorted times doing exactly what the first pass did.  This time, however, you stop at the best index and print the contents of currPartial at that index.


The correct place to implode array - MVC and Repositories concept

Logic or data transformation should usually be moved out of the controller.  Your places repository seems like a better choice for the implode.  After all, one of the major purposes of repositories is to decouple data handling and storage as much as possible from other parts of the application, including controller.s


Is there a cleaner/better way to write this Contact Manager in React?

Don't add extra properties to the component for things that belong in state.  Delete this.people because you already have this.state.people.  Move i into state.
Of course if you do that you cannot use mutating operations like ++ and .push() so you need to make a few changes.  When you are setting a state based on a previous state it is a best practice to use an update function to get the current state which ensures that you always have the most recent value.
You can do this:
this.setState({ people: this.state.people.concat(newPerson) });

But it's better to do this:
this.setState(prevState => ({ people: prevState.people.concat(newPerson) }));

The common code convention in JavaScript is to use camelCase for functions and class methods.  So use addPerson, removeElement, etc.
You want to be able to clear the inputs when you add a contact.  In order to do that, your <input> elements need to be controlled components which get their value from state.
Revised Code:
import React, { Component } from "react";

export default function App() {
  return (

React Contact Manager

      <Content />

  );
}

class Content extends Component {
  state = {
    people: [],
    name: "",
    age: "",
    telephone: "",
    searchTerm: "",
    id: 0,
  };

  getName = (e) => {
    this.setState({ name: e.target.value });
  };
  getAge = (e) => {
    this.setState({ age: e.target.value });
  };
  getTelephone = (e) => {
    this.setState({ telephone: e.target.value });
  };
  getSearchTerm = (e) => {
    this.setState({ searchTerm: e.target.value });
  };

  addPerson = () => {
    this.setState(state => ({
      // clear inputs
      name: "",
      age: "",
      telephone: "",
      // increment id
      id: state.id + 1,
      // add person
      people: state.people.concat({
        id: state.id,
        name: state.name,
        age: state.age,
        telephone: state.telephone,
      })
    }));
  };

  removeElement = (id) => {
    this.setState( state => ({
      people: state.people.filter((person) => person.id !== id)
    }));
  };

  clearItems = () => {
    this.setState({ people: [] });
  };

  render() {
    return (

          <input
            type="text"
            placeholder="Name"
            className="fname"
            value={this.state.name}
            onChange={this.getName}
          />
          <input
            type="number"
            placeholder="Age"
            className="age"
            value={this.state.age}
            onChange={this.getAge}
          />
          <input
            type="tel"
            placeholder="Telephone Number"
            className="telephone"
            value={this.state.telephone}
            onChange={this.getTelephone}
          />

          <button className="add" onClick={this.addPerson}>
            Add
          </button>

          {(this.state.people || []).map((person) => (

                {person.name + ", " + person.age}
                {person.telephone}

              <button
                className="delete"
                onClick={() => this.removeElement(person.id)}
              >
                Remove
              </button>

          ))}

        <button className="clear" onClick={this.clearItems}>
          Clear
        </button>

    );
  }
}


Using the same variables for different purposes in the same block of code is confusing to the reader. Split the code in 2-3 functions so that they become local variables.
You use trial division to compute the list of small primes even though you know about sieving. Sieving is faster.
arr.remove(x) in the innermost loop is slow because it scans through the whole list (to find the element to remove, and to move subsequent elements back). Use a set instead, or a list of boolean values similar to arr in the first part of the code.


Disable execution of parts of the code based on user's choice C++

I see two things:

option acquisition (a lot of control flow and ad-hoc checks to detect the user input)
operational program flow (the decisions based on it). Here I'd suggest Null Object pattern

Acquisition

At first, I'd suggest using standard library algorithms and types instead of ad-hoc program flow and casting:

std::vector<std::string> const args(argv+1, argv+argc);

Which you can use much easier, like:

auto find_arg    = [&](auto option) { return std::find(args.begin(), args.end(), option); };

So now you can just locate an argument using find_arg("--port"). And you can build on it:

auto find_arg    = [&](auto option) { return std::find(args.begin(), args.end(), option); };
auto has_flag    = [&](auto option) { return args.end() != find_arg(option); };

Now you can simply do:

bool const socketsActivated = !has_flag("--nosocket");
bool const logActivated     = !has_flag("--nolog");

Note that these are immutable, so program logic is strictly simpler and more verifiable. Getting the port takes a little more effort, but can be supported generically too:

auto get_option  = [&](auto option, auto default_value) -> std::string {
    auto it = find_arg(option);
    if (it != args.end()) {
        it = ++it;
        if (it == args.end()) { // There was no argument
            throw std::runtime_error(std::string(option) + " requires an argument");
        }
        return *it;
    }
    return default_value;
};

So now you can write:

int main(int argc_, char *argv_[])
{
    std::vector<std::string> const args(argv_+1, argv_+argc_);

    auto find_arg    = [&](auto option) { return std::find(args.begin(), args.end(), option); };
    auto has_flag    = [&](auto option) { return args.end() != find_arg(option); };
    auto get_option  = [&](auto option, auto default_value) -> std::string {
        auto it = find_arg(option);
        if (it != args.end()) {
            it = ++it;
            if (it == args.end()) { // There was no argument
                throw std::runtime_error(std::string(option) + " requires an argument");
            }
            return *it;
        }
        return default_value;
    };

    std::string const port      = get_option("--port", "27013");
    bool const socketsActivated = !has_flag("--nosocket");
    bool const logActivated     = !has_flag("--nolog");

It's more legible, less error prone and very extensible.

The extra mile

When you find yourself collecting operations like has_flag, get_option you can move them to a suitable abstraction.

Here's exactly the same data + operations grouped into a CommandLineParser:

struct CommandLineParser {
    CommandLineParser(int argc, char** argv) : _args(argv+1, argv+argc) {}

    auto find_arg  (std::string const& option) const {
        return std::find(_args.begin(), _args.end(), option);
    };
    bool has_flag  (std::string const& option) {
        return _args.end() != find_arg(option);
    };
    std::string get_option(std::string const& option, std::string const& default_value) {
        auto it = find_arg(option);
        if (it != _args.end()) {
            it = ++it;
            if (it == _args.end()) { // There was no port argument
                throw std::runtime_error(option + " requires an argument");
            }
            return *it;
        }
        return default_value;
    };

    std::vector<std::string> const _args;
};

And now main starts like this:

int main(int argc, char *argv[])
{
    CommandLineParser clp(argc, argv);
    std::string const port      = clp.get_option("--port", "27013");
    bool const socketsActivated = !clp.has_flag("--nosocket");
    bool const logActivated     = !clp.has_flag("--nolog");

Clean as a whistle.

Null Object Pattern

Here you prevent having null objects or repeated switches by having different implementations of the same interface. You just instantiate a "do-nothing" implementation if the behaviour is disabled:

/////////////////////////////////////
// abstract interface and null-implementation
struct IServer {
    virtual void update() = 0;
};

struct NullServer : IServer {
    virtual void update() override { }; // do nothing
};

struct CommunicationServer : IServer {
    CommunicationServer(std::string) {}
    virtual void update() override {
        std::clog << "Communication update\n";
    }
};

struct EchoServer : IServer {
  EchoServer(std::string) {}
    virtual void update() override {
        std::clog << "Echo update\n";
    }
};

Now you can simplify the call - site:

int main(int argc, char *argv[])
{
    std::unique_ptr<IServer>          server(new NullServer);
    std::unique_ptr<IServer>          echo(new NullServer);
    std::unique_ptr<IFileOperations>  traceFile(new NullFileOperations);

    // parse user config
    CommandLineParser clp(argc, argv);

    if (!clp.has_flag("--nosocket")){
        server = std::make_unique<CommunicationServer>(clp.get_option("--port", "27013"));
        echo   = std::make_unique<EchoServer>("27014");
    }

    if (!clp.has_flag("--nolog")) {
        traceFile = std::make_unique<FileOperations>();
    }

    while (!_kbhit()) // Till the key was pressed
    {
        Sleep(25); // lower the load on CPU

        server->update();
        echo->update();
    }
}

Full Demo

Live On Coliru

#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <memory>
#include <thread>

// mocks
static void Sleep(int ms) {
    std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}

static bool _kbhit() {
    static int remain = 10;
    return remain-- == 0;
}

/////////////////////////////////////
// abstract interface and null-implementation
struct IServer {
    virtual void update() = 0;
};

struct NullServer : IServer {
    virtual void update() override { }; // do nothing
};

struct CommunicationServer : IServer {
    CommunicationServer(std::string) {}
    virtual void update() override {
        std::clog << "Communication update\n";
    }
};

struct EchoServer : IServer {
  EchoServer(std::string) {}
    virtual void update() override {
        std::clog << "Echo update\n";
    }
};

/////////////////////////////////////
// similar for other interfaces
struct IFileOperations { };
struct NullFileOperations : IFileOperations { };
struct FileOperations : IFileOperations {};

struct CommandLineParser {
    CommandLineParser(int argc, char** argv) : _args(argv+1, argv+argc) {}

    auto find_arg  (std::string const& option) const {
        return std::find(_args.begin(), _args.end(), option);
    };
    bool has_flag  (std::string const& option) {
        return _args.end() != find_arg(option);
    };
    std::string get_option(std::string const& option, std::string const& default_value) {
        auto it = find_arg(option);
        if (it != _args.end()) {
            it = ++it;
            if (it == _args.end()) { // There was no port argument
                throw std::runtime_error(option + " requires an argument");
            }
            return *it;
        }
        return default_value;
    };

    std::vector<std::string> const _args;
};

int main(int argc, char *argv[])
{
    std::unique_ptr<IServer>          server(new NullServer);
    std::unique_ptr<IServer>          echo(new NullServer);
    std::unique_ptr<IFileOperations>  traceFile(new NullFileOperations);

    // parse user config
    CommandLineParser clp(argc, argv);

    if (!clp.has_flag("--nosocket")){
        server = std::make_unique<CommunicationServer>(clp.get_option("--port", "27013"));
        echo   = std::make_unique<EchoServer>("27014");
    }

    if (!clp.has_flag("--nolog")) {
        traceFile = std::make_unique<FileOperations>();
    }

    while (!_kbhit()) // Till the key was pressed
    {
        Sleep(25); // lower the load on CPU

        server->update();
        echo->update();
    }
}

Which, without options, prints e.g.

Communication update
Echo update
Communication update
Echo update
Communication update
Echo update
Communication update
Echo update
Communication update
Echo update
Communication update
Echo update
Communication update
Echo update
Communication update
Echo update
Communication update
Echo update
Communication update
Echo update

But with --nosocket prints nothing, and with missing port prints:

terminate called after throwing an instance of 'std::runtime_error'
  what():  --port requires an argument


Find the smallest divisible number for the given input 'n' such that number is evenly divisible by 1 to n

Your solution to the problem is "check every number to see if it has that property", but that's a lot of numbers. You can do a lot better.

Let me give you a big hint.

Suppose you want find the solution for n == 9. Suppose you had the solution for n == 8 is 840.  Don't worry about how you know that.

Given the fact that 840 is the smallest number that is divisible by 1, 2, 3, 4, 5, 6, 7 and 8, and that 9 is 3 times 3, how do you find a number that is divisible by 1, 2, 3, 4, 5, 6, 7, 8 and 9?  Plainly multiplying 840 by 9 gives a number that is too large, because 9 is already 3 x 3.  We only need to multiply by 3. So the solution for 9 is 2520.

Now suppose we want to find the solution for 10. We already know the solution for 9, and hey, it is already divisible by 10. So we're done.

Now suppose we want to find the solution for 11.  2520 is not divisible by 11, and 11 is prime.  So we have to multiply by 11.

What about 12?  12 is 3 x 4, and we already have a number that is divisible by both 3 and 4, so the solution for 11 is the same as the solution for 12.

And so on.

So is it now clear how to solve this problem efficiently?

UPDATE

Apparently it was not clear.

Think about it this way.

The solution for 2 is 2.
The solution for 3 needs to have a factor of 3, but the solution for 2 has no factor of 3. So the solution for 3 is 2 x 3.
The solution for 4 needs two factors of 2. The solution for 3 has only one factor of 2, so we add an additional factor of two: 2 x 3 x 2.
The solution for 5 needs a factor of 5, but we don't have one in the solution for 4. So 2 x 3 x 2 x 5.
The solution for 6 needs a factor of 2 and a factor of 3. The solution for 5 has a 2 and a 3 already, so 2 x 3 x 2 x 5 works for 6.
The solution for 7 needs a factor of 7, but the solution for 6 doesn't have one.  So 2 x 3 x 2 x 5 x 7.
The solution for 8 needs three factors of 2, but the solution for 7 only has two.  So 2 x 3 x 2 x 5 x 7 x 2.
The solution for 9 needs two factors of 3, but the solution for 8 only has one.  So 2 x 3 x 2 x 5 x 7 x 2 x 3.
The solution for 10 needs a factor of 2 and a factor of 5. The solution for 9 already has those. So 2 x 3 x 2 x 5 x 7 x 2 x 3.
Now do you see the pattern?


There are a few items to make this code better.

Naming. Once is an OK name for the class, but the method name IsDone is a problem. This is an 'atomic' operation that sets values, as well as gets values. A method called something like "Trigger", and changing the class name to a common term like OneShot, will give you the semantics like:

private readonly OneShot terminator = new OneShot();

if (terminator.Trigger())
{
    ... do something if we are the first trigger
}

or, using your semantics, the negated value:

if (!terminator.Trigger()) return;

Your fields should all be private.

private const Int32 JobDone = 11011;
private const Int32 NotDone = 119;

private Int32 _done;

otherwise other code can possibly reset or mess up your trigger.
Why use the bizarre numbers for the constants? What's wrong with 1, and 0. The special numbers make me think there's something especially magical with them.

Apart from that, the Interlocked.CompareExchange is the right tool for the job. It creates an atomic compare-and-set operation that makes it thread safe.


Greedy algorithm in Ruby - any suggestions?

@currency could be renamed @currencies, or perhaps better, @denominations.  Naming an array in the plural leads to easy naming when iterating, e.g.:

@currencies.each do |currency|

instead of:

@currency.each do |x|

The name of method sort_coins doesn't match what it's doing.  Whether or not it's sorting, it's also printing.  A better name might be print_coins.

@quotient might be a better name for @pos.

Most of the variables in sort_coins do not need to be member variables: @pos and @total_coins should lose the @.  And, if you decide to make it an argument to sort_coins (see below), @total as well.

This:

@currency = coins.sort
@currency = @currency.reverse

Could be this:

@currency = coins.sort.reverse

The initialization of @total_coins needs to move from the constructor to sort_coins.  This prevents a bug triggered by calling sort_coins more than once.

Consider passing total to sort_coins rather than to the constructor.  This would allow sort_coins to be called on an instance of Greedy with a different total each time, and no need to create a new instance of Greedy for each.  It would also get the variable's initialization closer to where it is used, making for simpler code.

Consider the constructor argument for the set of coins bing simply coins rather than *coins, because it makes the calling code easier to understand.  E.g.,

Greedy.new('cents', 71, 1, [5, 10, 25, 50]).sort_coins

vs.

Greedy.new('cents', 71, 1, 5, 10, 25, 50).sort_coins

Put a line of white space between methods, and at the top and bottom of the class definition.

If all acted upon, these suggestions yield:

class Greedy

  def initialize(unit, coins)
    @unit = unit
    @demoninations = coins.sort.reverse
    unless @demoninations.include?(1)
      @demoninations.push(1)
    end
  end

  def print_coins(total)
    total_coins = 0
    @demoninations.each do |demonination|
      quotient = (total / demonination).floor
      total_coins += quotient
      total -= demonination * quotient
      puts "#{quotient}: #{demonination} #{@unit}"
    end
    puts "#{total_coins} total coins"
  end

end

Greedy.new('cents', [1, 5, 10, 25, 50]).print_coins(72)
#=> 1: 50 cents
#=> 0: 25 cents
#=> 2: 10 cents
#=> 0: 5 cents
#=> 2: 1 cents
#=> 5 total coins


Object can throw exception on construction, but I don't want it to stop everything

My application does a number of different tasks, and I don't want a broken or missing xml file to interfere with the other tasks the application does.

If you don't need the XML file configuration, why do you have it? How can you continue without it?

How you answer this conceptual question has a lot to do with how you implement the code logic using exceptions.


Send message with SignalR to client(s) from injected (IoC) method

Currently, your setup doesn't allow for any cancellation or error handling. The latter is an implementation detail, so I guess you've handled that in the actual code. I would consider the following:

Return the started task out of Start
Will you ever need to provide a result from the started task? If so, provide an overload for Func<double,T>
Provide cancellation support via a cancellation token (if business logic dictates this is acceptable)
Provide a Stop method that also that can stop the task created by Start