Binary string to integer and integer to binary string

It makes sense for the two functions to be symmetrical - ie that you can call
them in turn to swap between integer and string representations.  So I would
make binstr2int produce an unsigned long of full range returned through a
parameter and have the function return the status (0/-1):

int binstr2int(const char *s, unsigned long &num);

Note that s can be const.

In int2binstr I think the characters should be moved to the beginning of the
string - this is what all other C string functions do (or at least I'm
ignorant of any that do not).  Also, your code is a bit awkward in
that it treats 0 separately from all other numbers.  This is a case where a
do {...} while loop makes sense as it can handle the zero case as any other
number and test for zero once it has done it:

char* int2binstr(unsigned long num, char *s, size_t size)
{
    long len = (long) size - 1;
    do {
        if (len <= 0) {
            errno = ERANGE;
            return NULL;
        }
        s[--len] = (num & 1) ? '1' : '0';
    } while ((num >>= 1) != 0);

    long n = (long) size - len - 1;
    memmove(s, s + len, n);
    s[n] = '\0';
    return s;
}

Here you can see that the tests for a short input string and for
num == 0 are handled naturally.  Also I moved the string into place after
creating it.


hGetContents gets all remaining input, using lazy IO.  The second call to hGetContents throws an error because the first call has already claimed the data, in a sense.

What I would do is have a separate thread tunnel data from the handle to standard output, and have the main thread tunnel data from standard input to the handle:

_ <- forkIO $ hGetContents h >>= putStr
getContents >>= hPutStr h

I would also use LineBuffering rather than NoBuffering, so it doesn't have to transmit a TCP packet for every character (*).

Thus, we have:

import Control.Concurrent
import Network
import System.Environment
import System.IO

main :: IO ()
main = do
    [host, port] <- getArgs
    h <- connectTo host $ PortNumber $ toEnum $ read port
    hSetBuffering stdout LineBuffering
    hSetBuffering h      LineBuffering
    _ <- forkIO $ hGetContents h >>= putStr
    getContents >>= hPutStr h

A couple notes:

I was able to avoid the type signature by using toEnum rather than fromIntegral.
_ <- forkIO $ ... suppresses a warning when the program is compiled with -Wall.

We can do better, though.  Currently, if the server disconnects, the user does not see that the server disconnected until hitting enter a couple times, which produces an ugly error message:

tcp-client: <socket: 3>: commitBuffer: resource vanished (Broken pipe)

Let's see if we can get the program to terminate when either the server or the client closes the connection.  Bear in mind that:

getContents and hGetContents terminate the list when EOF is reached.  Thus:

hGetContents h >>= putStr terminates when the server closes the connection
getContents >>= hPutStr h terminates when the user presses Ctrl+D

The program terminates when the main thread terminates, regardless if child threads still have work to do.

A good way to do this, I think, is to perform the receiving and sending in two separate threads, and have the main thread wait on an MVar:

done <- newEmptyMVar

_ <- forkIO $ (hGetContents h >>= putStr)
              `finally` tryPutMVar done ()

_ <- forkIO $ (getContents >>= hPutStr h)
              `finally` tryPutMVar done ()

-- Wait for at least one of the above threads to complete
takeMVar done

* Actually, sending individual characters at a time will probably trigger Nagle's algorithm.  Still, sending characters one at a time creates a lot of unnecessary CPU overhead.


Find max number of repeating heads and tails

Don't iterate over the indices of a list only to then access the element at that index. Instead iterate directly over the elements of the list! Have a look at Loop Like A Native by Ned Halder.

In the standard library module itertools there is the groupby function, which groups equal elements together. You can use this to make your code easier:

from itertools import groupby

def max_streaks(tosses):
    longest_streaks = {"Heads": 0, "Tails": 0}
    for toss, streak in groupby(tosses):
        longest_streaks[toss] = max(longest_streaks[toss], len(list(streak)))
    return longest_streaks["Heads"], longest_streaks["Tails"]

max_streaks("Heads, Tails, Tails, Tails, Heads, Heads, Tails".split(", "))
# 2, 3

Note that this does not assume anything about tosses, unlike your code. It could be a list or a string, but also something like a generator, which has no len.

You could generalize this function to being able to count the longest streak of any elements by using a collections.defaultdict and returning it:

from collections import defaultdict
from itertools import groupby
from typing import Dict, Iterable, Hashable

def longest_streaks(elements: Iterable[Hashable]) -> Dict[Hashable, int]:
    """Count the length of the longest streak of each distinct element
    present in `elements`.
    All elements need to be hashable.
    """
    longest_streak = defaultdict(int)
    for element, streak in groupby(elements):
        longest_streak[element] = max(longest_streak[element], len(list(streak)))
    return dict(longest_streak)

if __name__ == "__main__":
    longest_streaks([1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 3])
    # {1: 3, 2: 2, 3: 3}

Note that I followed Python's official style-guide, PEP8, by using lower_case for variables and functions and wrapped the calling code in a if __name__ == "__main__": guard to allow importing from this script without running the example. I also added some type hints and a docstring, which makes it easier to figure out what a function does, both for anybody else reading your code and for yourself in two months.


Outputting a user's name, day of birth, and test scores in a bar chart

Judging by your code, you're a beginner in JS (blame it on document.write :P). Anyways, here's some tips to save you early on your JS journey.

MONTHS = 'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'; //months

Declare variables with a var. That's the proper practice, and when you start using functions, you don't accidentally declare globals. In addition, MONTHS is a set of month abbreviations. You probably want to use an array. Lastly, we still retain the convention of constants as call capital letters, so credits to that.

var MONTHS = ['JAN','FEB','MAR', ... ];

document.write ('
Introduce Yourself

');

There are limited reasons to use document.write. The problem with it is that once the page is fully loaded, doing it will discard the entire page and the browser will write the content from a fresh blank page. This means its not suitable for after-page-creation operations.

Suggesting you look into DOM manipulation functions like document.createElement() and document.appendChild as well as document.querySelectorAll. This is as close to a library-like functionality as you get without ever using one.

userName = prompt('Enter your First Name','Alex'); //prompt user for name

While there's nothing against prompts, I suggest you explore more on forms and input elements. They are HTML elements that allow you to input data and have JS retrieve them.

var dateString = prompt('Enter your birth date in the form dd mmm yyyy','26 APR    1988'); //get users date of birth
var substrings = dateString.split(' ');
var day = substrings[0];
var month = substrings[1];
var year = substrings[2];

This will probably break if you don't check for the values. Have some form of validation to check if the values are valid.

var poem = ["Sunday's child is fair and wise", "Monday's child is fair of face",        "Tuesday's child is full of grace", "Wednesday's child is full of woe", "Thursday's child has far to go", "Friday's child is loving and giving", "Saturday's child works hard for a living"];
var daysArray = new Array ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',    'Friday', 'Saturday');

You just declared poem using the literal notation, but not daysArray? Tsk3. Best practice is use literals whenever possible. Saves you keystrokes and looks less Java-ish.


Counting pending bookings using a subselect

Yes, there is a way to eliminate the repeated function call, but as to whether or not it would improve performance you need to benchmark it. This method writes the resulting data into a temporary table, which means it will call the function only once when populating it, but in turn will mean that it will have to write the table to tempdb for that session. Here is how it could be written that way:
if object_id('tempdb..#SpecialBookings') is not null
    drop table tempdb..#SpecialBookings;

select *
into #SpecialBookings
from SPECIAL_GROUP as grp
    cross apply f_BookingsForSpecialGroup(grp.SPECIAL_GROUP_ID) as bookings
where (bookings.IS_BAD = 0 or bookings.IS_PAID = 1);

select (grpCounted.NON_BAD_BOOKINGS - grpCounted.PAID_BOOKINGS) as PENDING_BOOKINGS, *
from
(
    select
        (select count(*) from #SpecialBookings where IS_BAD=0) as NON_BAD_BOOKINGS,
        (select count(*) from #SpecialBookings where IS_PAID=1) as PAID_BOOKINGS,
        *
    from #SpecialBookings
) as grpCounted;

if object_id('tempdb..#SpecialBookings') is not null
    drop table tempdb..#SpecialBookings;

select *
Do you really need all the fields from both the SPECIAL_GROUP table and the f_BookingsForSpecialGroup? If you do really need them, then fair enough, but otherwise, you should not use select *.

Aliases
As you can see I renamed your table aliases a bit to make your code easier to read. Whenever possible, avoid single-letter or otherwise meaningless aliases as they make the code less clear.


In Qt, there is a concept of parents and a hierarchy.

In essence, it means that when a qobject owns another qobject (the other qobject's parent is the first) then the parent will take care of cleaning its children.

There are 2 ways an object becomes a child of another: when it is set in the constructor or when reparented. The qwidget family automatically reparents widgets which you add to it

Common use for the main function is to allocate the root statically and all the rest dynamically as child of the root:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w ();
    w.setWindowTitle("Music Player");
    QIcon * mainwind_icon = new QIcon("MusicPlayer.png");
    w.setWindowIcon(*mainwind_icon);

    QPushButton * enter_button = new QPushButton();
    QTextEdit  * textbox = new QTextEdit();

    QHBoxLayout * vlayout = new QHBoxLayout;
    vlayout->addWidget(textbox);
    vlayout->addWidget(enter_button);

    w.setLayout(vlayout);

    w.show();
    return a.exec();
}

The setlayout takes ownership of the vlayout and its children so the destructor of w will delete those as well

When you are inside an event loop then you can delete a qobject by calling deleteLater on it which will schedule the object (and its children) for deletion. You can also connect a signal to it if needed.


Storing transactions with amounts and payment types

When you use the same base query with different WHERE-conditons you can usually rewrite it using Conditional Aggregation with CASE (aka pivoting):

select -- you can easily add a GROUP BY column here
   sum(cast(case when upper(o.PaymentType) = 'FOOD CARD'
            then o.FinancialContribution end else 0 as decimal(18,4))) as FoodCardContributions
  ,sum(cast(case when upper(o.PaymentType) = 'FUEL CARD'
            then o.FinancialContribution end else 0 as decimal(18,4))) as FuelCardContributions
  ,sum(cast(case when upper(o.PaymentType) in ('GO CARD' , 'GOCARD')
            then o.FinancialContribution end else 0 as decimal(18,4))) as GoCardContributions
  ,sum(cast(case when upper(o.PaymentType) = 'INVOICE PAYMENT'
            then o.FinancialContribution end else 0 as decimal(18,4))) as InvoicePaymentContributions
from dbo.CriticalAssistanceInternalOutcomes as o
where
   upper(o.paymentType)
     in ('GO CARD', 'GOCARD', 'FOOD CARD', 'FUEL CARD', 'INVOICE PAYMENT')

I changed the deprecated MONEY to a better DECIMAL.

Btw, who created that table? Storing numeric values in a VarChar column is very bad practice...


Using a cronjob on node for storing a json file, parsing it and update a database

OK, thank you James!

I was able to get rid of require-reload using request, and use the compression with adm-zip on the fly:

var CronJob = require('cron').CronJob;
var request = require('request');
var AdmZip = require('adm-zip');

var ais_url_france = 'http://data.aishub.net/ws.php?username=XXX&format=1&output=json&compress=1&latmin=40&latmax=52&lonmin=-5&lonmax=10';
new CronJob('* * * * *', function () {
     request({url: ais_url_france, encoding: null}, function (error, response, data) {
            if (!error && response.statusCode === 200) {
                var zip = new AdmZip(data);
                var zipEntries = zip.getEntries();
                if (zipEntries && zipEntries.length) {
                    var file = JSON.parse(zip.readAsText(zipEntries[0]));
                    if (file[0].ERROR === false) {
                        var boats = file[1];
                        if (boats.length > 0) {
                            Boat.destroyAll(function (err, info) {
                                for (var i = 0; i < boats.length; i++) {
                                    Boat.create({
                                        name: boats[i].NAME,
                                        latlng: {
                                            lat: boats[i].LATITUDE,
                                            lng: boats[i].LONGITUDE
                                        }
                                    });
                                }
                            });
                        }
                    }
                }
            }
        });
    }, null, true, null);


create generic method for two different anonymous types

If you want to have only one method  you need to do the following:

Create an interface for properties that are common for both models like:

public interface IValidationQuality
{
    int partition_id { get; }
    int claim_id { get; }
    int claim_validation_test_id { get; }
}

(those are just few of them, you need to find the others)

Add this interface to both models:

public class VW_Validation_Quantity : IValidationQuality { }
public class VW_Validation_340B : IValidationQuality { }

finally you make a few small adjustments to one of the methods:

public HttpResponseMessage GetValidations(ICollection<IValidationQuality> items)
{
    int partitionId = GetPartitionId();
    List < IValidationQuality > = items.Where(x => x.partition_id == partitionId).ToList();
    var duplicateClaims = result.GroupBy(a => a.claim_id).Where(g => g.Count() > 1).Select(y => new { claimID = y.Key, records = y.ToList() });

    var newResult = result.GroupBy(a => a.claim_id).Select(g => g.First()).ToList();

    foreach (var claim in duplicateClaims)
    {
        List<byte?> testIds = new List<byte?>();
        List<string> testNames = new List<string>();
        List<string> resultValues = new List<string>();
        foreach (var record in claim.records)
        {
            testIds.Add(record.claim_validation_test_id[0]);
            testNames.Add(record.Test[0]);
            resultValues.Add(record.Result[0]);
        }

        newResult.Where(x => x.claim_id == claim.claimID).ToList().ForEach(y => { y.claim_validation_test_id = testIds; y.Test = testNames; y.Result = resultValues; });
    }
}

Which means that you pass each collection to this method and becasue both models share the same interface it can work with both of them.

Then you can call it like this:

var result1 = GetValidations(this.db.VW_Validation_Quantity);
var result2 = GetValidations(this.db.VW_Validation_340B);


Pausing script while waiting for Docker container and printing updates

If you don't mind using Bash,
then it will be more elegant to replace the while loop with a counting for loop:

for ((i = 0; ; i++)); do
    # ...
done

I'm guessing that you're using Bash anyway from the let "i++" syntax,
which will not work with simpler shells like Dash.

Note that the various flags of echo are not portable.
For a more portable solution, replace it with printf.

Lastly, the indentation is inconsistent: some blocks are indented with 4 spaces, others with 2. It would be better to indent consistently (I like 4 spaces).


You point it, this program copies and traverse the lists too many times. You should think to reduce the size of the list at each prime iteration, you can initialize the first list without all the multiples of 2,3,5 (it is quite easy), you should pass length(L) as a parameter (it needs to traverse the list at each iteration).

Since the sieve algorithm is based on the modification of a set of data, the list is not the best data structure to work with. I think you should have much better result with ets.

[edit] I have tested your version on my laptop using timer:tc/3 and found 24s (your measure is 19.5s, not 52s). a version using ets and the different optimizations I suggest takes 1.2s for the same job.

With 10000000 the times are 252s and 7s, which suggests that with your algorithm the execution time is increasing more than with ets (ration 10 and 6 for a data set 5 time bigger).

Last point, you are returning 1 as a prime which is not correct.


Through clever usage of destructuring and using objects to store possible events, you can do this.
function focus(key){
  const {activeElement:{[key]: elementSibling} = {}} = document;
  if(elementSibling){
    elementSibling.focus();
  }
}

const ACTIONS = {
  ArrowDown: () => focus('nextElementSibling'),
  ArrowUp: () => focus('previousElementSibling'),
  Enter: (e) => myCustomEvent(e)
}

function handleKeyDown (e) {
  const handler = ACTIONS[e.key];
  if(handler) {
    e.preventDefault();
    handler(e);
  }
}

Here is a working example:

function focus(key){
  const {activeElement:{[key]: elementSibling} = {}} = document;
  if(elementSibling){
    elementSibling.focus();
  }
}

const ACTIONS = {
  ArrowDown: () => focus('nextElementSibling'),
  ArrowUp: () => focus('previousElementSibling'),
  Enter: (e) => myCustomEvent(e)
}

function handleKeyDown (e) {
  console.log(e.key, e.target);
  const handler = ACTIONS[e.key];
  if(handler) {
    e.preventDefault();
    handler(e);
  }
}

// simulating an event
window.addEventListener('keyup', handleKeyDown);

Click on an element then press ArrowUp or ArrowDown

<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>


First of all, your function name sounds weird. The name of the function should brefly describe what it does, so, a name like convertEol would be more appropriate.

Second, I see much redundancy on your code, like this part:

if ($hread === FALSE)   e("Bad file in file_eol(): $file");
if (!is_resource($hread) || get_resource_type($hread) !== 'stream') e("Bad hread in file_eol(): $hread");

As you can see on the PHP manual of fopen function, it will return false if it is not able to open de file, otherwhise, it will ALWAYS return a resource, no matter what (except that you are doing something really crazy, like opening more files than a process is allowed to do).

So, your second verification is redundant.

Also, returning booleans in functions that do not check for some condition it too old-fashioned, too 80's. The same way, triggering uncatchable errors is almost a crime.

You should really learn how to work with Exceptions.

Here is what I would do, not necessarily the only one correct implementation:

function convertEol($fileName, $eolChar) {
    /* For windows, unix and mac.
     * IMPORTANT: for this implementation, \r\n MUST be the first element on the array
     */
    static $replaceableChars = array("\r\n", "\n", "\r");

    $originalFile, $tmpFile;

    try {
        $originalFile = new SplFileObject($fileName, 'r'); // open a file for reading
    } catch (RuntimeException $e) {
        throw new Exception("Unable to open file {$fileName} for reading", null, $e);
    }

    try {
        $tmpFile = new SplFileObject(uniqid() . '.tmp', 'w+'); // open or create a file for writing
    } catch (RuntimeException $e) {
        throw new Exception("Unable to create temp file", null, $e);
    }

    // iterates over the original file, line by line
    foreach ($originalFile as $line) {
        // writes the replaced string
        $tmpFile->fwrite(str_replace($replaceableChars, $eol, $line));
    }

    $tmpFile->fflush(); // makes sure file was written

    rename($tmpFile->getPathname(), $originalFile->getPathname());
}

Usage:

// Normal
convertEol('path/to/file', "\n");

// Unexistent file
convertEol('path/to/unexistent/file', "\n"); // will throw an exception

// Catching error
try {
    convertEol('path/to/unexistent/file', "\n");
} catch (Exception $e) {
    echo 'Oops, something went wrong:' . $e->getTraceAsString();
}
// ...


Cancelling A Task Without Cancellation Token

Starting with the first function, I would make a few changes:

Task.IsCompleted covers all completion states already (https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.iscompleted?view=netframework-4.8)
Tasks are all about not blocking the current thread. Never use Thread.Sleep and always use Task.Delay.
Cancellation can be more succinctly handled with Task.ThrowIfCancellationRequested

public static async Task<T> SynchronizeWithCancellationToken<T>(this Task<T> task, int delayMilliseconds = 10, CancellationToken cancellationToken = default)
{
    if (task == null)
        throw new ArgumentNullException(nameof(task));

    while (!task.IsCompleted)
    {
        await Task.Delay(delayMilliseconds);
        cancellationToken.ThrowIfCancellationRequested();
    }

    return await task;
}

This is about as good as it gets to "add cancellation" to a Task that doesn't do cancellation. The key to understanding Task cancellation in .NET is that it is cooperative. This means that simply passing a cancellation token around doesn't do anything on its own; instead the Task implementation itself has to handle cancellation. This makes a lot of sense since only the Task implementation itself knows when best to allow cancellation without causing invalid state or corruption.

I would definitely recommend taking the time to do a read-through of the MSDN article on this: https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation?view=netframework-4.8

Your second function attempts to use the Task.Run overload that takes a CancellationToken in order to cancel the operation. However, Task.Run only uses the token to avoid starting the Task (if it's already cancelled when it goes to run it), and it's left to the user to use the token inside the implementation passed to Task.Run to handle further cancellation. See here: https://stackoverflow.com/questions/22637642/using-cancellationtoken-for-timeout-in-task-run-does-not-work

The first method is definitely the one you want to use. Just remember that it isn't true cancellation which would require you to modify the implementation of the API function and add the cooperative cancellation bits. When you add cancellation like this, without the implementation bits, you're only cancelling the wait for the Task to finish, not the Task itself. If the Task has further operations to carry out, they will still be carried out. This can often times be a deal breaker with some APIs, and you might be forced to find an alternative implementation that handles cancellation, or even implement your own.

Edit:

It also slipped my mind that you can use CancellationToken.Register to asynchronously wait and get rid of the polling...

    public static async Task ToTask(this CancellationToken token)
    {
        var source = new TaskCompletionSource<object>();
        using (token.Register(() => source.SetResult(null)))
            await source.Task;
    }

    public static async Task<T> SynchronizeWithCancellationToken<T>(this Task<T> task,
        CancellationToken cancellationToken = default, string message = default)
    {
        if (task == null)
            throw new ArgumentNullException(nameof(task));

        if (await Task.WhenAny(task, cancellationToken.ToTask()) == task)
            return await task;
        else
            throw new OperationCanceledException(message ?? "The operation was canceled.");
    }


Bash script to manage multiple Java Development Kits installations

Let's see:

There's no need to use return in the last statement of a function. By default, the return code of the last command is returned anyway.
Using backticks for evaluation is deprecated - you should use $(command args) instead. It is also more readable.
Use More Quotes™. The current script does not handle even whitespace in file names, much less newlines or - at the beginning.
Indent consistently, otherwise it's difficult to follow the code.
Are you sure you need to initialize the symlink?
Don't parse ls output.


Function to represent an integer in a base

n_to_digit doesn't really need to be a template, since its argument n can only ever be in the range 0 to 35. I'd just make it

char n_to_digit(int n) {
    static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
    return digits[n];
}

Notice also the replacement of *digits with digits[]; the optimizer will likely generate the same code either way, but without the optimizer's help, making digits the name of the array itself instead of the name of a pointer to the array will remove one level of pointer dereferencing.

YMMV, but I would find

std::array<char, (sizeof(Integral) << 3)> str;

easier to read if it were just

char str[sizeof(Integral) * 8];

Of course then you'd have to use std::begin(str) instead of str.begin(). But you could make up for it by using it - str instead of std::distance(str.begin(), it).

Actually, hang on —

while (it != str.begin()) {
    *dst_it++ = *(--it);
}

return std::distance(str.begin(), it);

The loop never exits unless it == str.begin(), which means std::distance(str.begin(), it) == 0 by definition! This is certainly a bug.

Since you're trying to make this fully generic: note that *dst_it++ is going to be inefficient for a lot of iterator types. If you were writing this for a popular library, you'd write

*dst_it = '-';
++dst_it;

If you consistently avoid postfix operators, your users might even thank you, because your code will work even with their incompletely belled-and-whistled iterator types.

In the signed version, your use of std::abs(n) is a red flag. abs is never appropriate in generic code. For one thing, if Integral n is some clever fixed-point type, std::abs(n) won't compile; what you meant is more like

using std::abs;
... abs(n) ...

to pick up the correct abs through ADL. (But this opens the whole customization-point can of worms, which is still a mess even in C++17.)

No, the real reason abs is a red flag is because std::abs(-1 - 2147483647) invokes undefined behavior (source). You should never call abs on untrusted input.

The usual hack in this domain is to say

if (n < 0) {
    *dst_it = '-'; ++dst_it;
} else {
    n = -n;
}

and then print the negative of n.

std::integral_constant<bool, std::is_unsigned<Integral>::value>()

could conceivably be written

typename std::is_unsigned<Integral>::type{}

but honestly, only the most evil and sadistic library implementation in the universe would make is_unsigned not derived from boolean_constant already. So you can just write

std::is_unsigned<Integral>{}

and be assured that your tag-dispatch code will work at least as well as your neighbor's. :)


The type of the resultSet reference could be simply Map<...>:

private final Map<HSQuery, List<ChannelBuffer>> resultSet

Reference: Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces
Instead of the Map<HSQuery, List<ChannelBuffer>> I'd use Guava's Multimap. It was
designed for this case.
Constructors and methods should validate their input parameters.

public HSResult(Charset charset) {
    this.charset = charset;
}

Does it make sense to have a charset with null? If not, check it and throw an NullPointerException. (Effective Java, Second Edition, Item 38: Check parameters for validity)


My first recommendation is to use std::ops. Try writing implementations of ops::Add for addition,  ops::Mul<Vec3<T>> for cross product, and ops::Mul<T> for scaler-vector multiplication. Not only does implementing these standard traits make your code more interoperable with other Rust code, but it also gives you operator overloading, so you can use + and * on your vectors.

Second, I would question the user of the trait Vector3<f32>. Why do you need a trait? I would just put your operations in the implementation of Vec3<T> itself

impl <T> Vec3<T> {

// ... methods ...

}

Looking forward to seeing your completed code. This will even more interesting once you get generics working.


Client/Server, Asynchronous ping-pong exchange

As far as I know, it seems to be only a "warning". Async/Await are supposed to be used as a pair in most cases. Let's have a simple example based on your code :

 HostAsync();

Here you have written a basic method call, and the method is :

private async Task HostAsync()

So the warning appears because compiler is expecting something like :

await ...

inside the HostAsync method.

By not putting the await keyword inside this async method, we get basically a synchronous call, a standard method. Not a big issue in most cases but have a look at :

private async Task SendMessages(IEnumerable<TcpClient> clients, string message)

This one has no await too.

Hope this helps !


First of all I don't know why are you trying to reinvent the wheel? Java has a strong and beautiful API with many methods and there is also a method for sorting an custom array. Which is more faster than quicksort. However I think this is for your own practice.

Your convertA method is not good, cause you are passing the reference as argument as well. So either make the method static or use the existing method toArray().
You are converting a student list to an Node array, why? change Node array to Student array. So this

arr[i].getStudent().getAge()

will change to

arr[i].getAge()

there is a possible bug you are calculating (left + right) / 2 which may cause an overflow, though Java int range is very big you will face the overflow very rarely, but if you want to fix this; change to (right - left) / 2 + left.

Check How Other Have Done The Quicksort :

From CodeReview 1

From CodeReview 2

Why you should use the API method?


Repeatedly keep removing 2 smallest elements and add its sum back to the list and return newly inserted elements' total

#include <sstream>

Only include what is necessary.

    for(int i=0 ; i<n ; i++) { ... }

Use range-based for.

    std::cout << ... << std::endl;

Avoid std::endl.

void printArray(std::vector<int> &arr, int n) { ... }
                                       ^^^^^
int main() {
    int n = arr.size();
          ^^^^^^^^^^^^
    printArray(arr,n);
                   ^

You have an implicit conversions from std::vector::size_type to int when you initialize n and pass an int argument to parameter n.

    printArray(arr, n);
    heapSort(arr, n);

std::vector carries its size. You do not have to capture it in a variable and pass it.

    int n = arr.size();
    while (arr.size() > 1) {
        heapSort(arr, n);
        arr.erase(...);
        arr.push_back(...);
    }

With each iteration of the loop, you pop 2 elements and push 1 element reducing the size of arr by 1. n is a local copy of arr.size() and is never updated. This results in out-of-bounds index access in your sort functions after the first iteration of this loop.

As for your issues with excessive calls to heapify(), you are calling heapSort() on every iteration. heapSort() takes a sequence in any order, sorts all of the values into heap order, then sorts all of the values again into sequential sorted order. This is done so you can operate on the two minimum values at the same time. Instead of fully sorting the sequence on every iteration, you can take a partial sort approach. Maintain the sequence in heap order by sifting values around as you mutate the sequence. Finding each minimum values is simply a swap and a sift down. Repairing the heap order on insertion is simply a sift up. Which brings me to know your <algorithm>s. The C++ standard library provides heap operations (is, make, push, pop, sort).

    // Sort into min-heap order
    std::make_heap(arr.begin(), arr.end(), std::greater())

    while (arr.size() > 1) {
        // rotate out the 1st min keeping heap order intact
        std::pop_heap(arr.begin(), arr.end(), std::greater());
        const auto first = arr.back();
        arr.pop_back();

        // rotate out the 2nd min keeping heap order intact
        std::pop_heap(arr.begin(), arr.end(), std::greater());
        const auto second = arr.back();
        arr.pop_back();

        const auto sum = first + second;
        ans += sum;

        // Move the inserted value into its heap order position
        arr.push_back(sum);
        std::push_heap(arr.begin(), arr.end(), std::greater());
    }

std::priority_queue helps clean up some of the duplication.

    std::priority_queue min_heap{std::greater(), std::move(arr)};
    while (min_heap.size() > 1) {
        const auto first = min_heap.top();
        min_heap.pop();
        const auto second = min_heap.top();
        min_heap.pop();

        const auto sum = first + second;
        ans += sum;
        min_heap.push(sum);
    }


From object to array with revert and regroup

I assume that the values are no longer needed in the output array and that you only want to construct the final array that you receive after the call to your array_values function.

// I extend the data with another duplicated value for a better test.
var input = { "Data 1": 0, "Data 2": 1, "Data 3": 3, "Data 4": 0, "Data 5": 3 };

// No change, our output array.
var output = [];

// We will use an additional array to create a mapping between actual values
// and the output array's indices they are stored at.
var mapping = [];

for (var data in input) {
    // Check if the value of this input data is already present in the
    // mapping's array, if it is, append the actual data to the already
    // existing array.
    //
    // NOTE: Using `mapping[input[data]] == undefined` is not a secure method
    // to check if an array index exists, since the value might be undefined
    // and that is not what we want. It is like `isset` and `array_key_exists`
    // in PHP, if you are familiar with that language.
    if (input[data] in mapping) {
        // We access the output array via the mappings array and the original
        // input arrays value and push the data.
        output[mapping[input[data]]].push(data);
        // output[0].push("Data 4");
        // output[2].push("Data 5");
    }
    // No entry exists in the mapping's array.
    else {
        // Push will simply append the data, we also inline the creation of the
        // desired array for additional data for this index.
        output.push([ data ]);
        // output[0] = [ "Data 1" ];
        // output[1] = [ "Data 2" ];
        // output[2] = [ "Data 3" ];

        // Now we need to create the actual mapping in case other data has the
        // same value. We simply create a new index and store the output
        // array's current index there (note the `-1` since `length` starts at
        // one in contrast to the indices which start at zero).
        mapping[input[data]] = output.length - 1;
        // mapping[0] = 0;
        // mapping[1] = 1;
        // mapping[3] = 2;
    }
}

console.dir(output);


C++ implementation of the observer design pattern

Design Review

Ownership

One of the advances of C++ over is C is ownership semantics. We understand who owns an object (and thus who is responsible for destroying the object). We do this by using a set of helper classes that explicitly state ownership or pass by reference to indicate non ownership.

The trouble with pointers is that they have no ownership semantics. You can't tell from their usage who is supposed to own the pointer and thus you can not tell who is responsible for deleting the object. Thus in C++ it is highly discouraged to use RAW pointers in public interfaces (I am not saying are not used, I am saying is that their normally place is deep inside a class so their ownership is very obvious and not normally exposed in public interfaces).

In you interface you never transfer ownership and you have both a register and unregister method on the subject. So that interface can be easily changed to show the ownership is not part of the interface.

template <typename T>
class Subject {
public:
    virtual void registerObserver(Observer<T>& ptr_observer) = 0;
    virtual void unregisterObserver(Observer<T>& ptr_observer) = 0;
    virtual void notifyObservers() = 0;
};

Please note I changed the * to &. This shows you are not passing ownership but you will always pass an observer. The additional upside is that you can no longer pass nullptr as an observer (you forgot to check to see if the pointer was nullptr and thus had a potential for calling a method on a nullptr (not a good idea).

Passing by value:

Here you pass the subjectState by value.

class Observer {
public:
    virtual void update(T subjectState)=0;
};

If T is large or complex then this is probably not a good idea. Pass a reference to the object. If the subject wants a copy they can explicitly make a decision to copy the object when they receive it (they have enough context to make an intelligent choice). So pass by reference instead.

class Observer {
public:
    virtual void update(T const& subjectState)=0;
              //          ^^^^^^  Normally I would pass by const ref.
              //                  But there is a case for passing by ref
              //                  as this allows each subject to mutate the
              //                  state of the object that is detectable
              //                  by other observers.
};

Virtual Destructors

If a class has virtual methods then you should have a virtual destructor.

The compiler will warn you about this if you turn up the warning level.

Override

When you override virtual methods you should add override to the method declaration.

The compiler will warn you about this if you turn up the warning level.

Code Review

Prefer to use the range based for when looping over a container.

        for (std::set<Observer<T>*>::iterator iter = observers.begin(); iter != observers.end(); iter++) {
            (*iter)->update(state);
        }

One thing you should change is the increment. It is slightly more efficient to use prefix increment (though the compiler probably compensates automatically). But it also makes your code look more modern.

        for (std::set<Observer<T>*>::iterator iter = observers.begin(); iter != observers.end(); ++iter) {
            (*iter)->update(state);
        }

This works. But it is a bit verbose.
In C++11 we made this easier with auto which makes the compiler do the work of working out the type.

        for (auto iter = observers.begin(); iter != observers.end(); ++iter) {
            (*iter)->update(state);
        }

In C++14 we added std::begin() and std::end() functions to make the above more generic and work with arrays as well as standard containers.

        for (auto iter = std::begin(observers); iter != std::end(observers); ++iter) {
            (*iter)->update(state);
        }

Also in C++14 we added the range based for:
The below loop is basically syntactic sugar (though it only calls std::end() once in C++17) for the previous loop I wrote.

        for (auto const& item: observers) {
            item->update(state);
        }

Const correctness.

Const correctness is really hard to add in afterwords (believe me). So best to start with your classes with it already in place. So any method that does not mutate the state of the object should be marked const

    void stateChanged() const {  // I added the cost here.
        notifyObservers();
    }

This class should be const and return by reference.

    T const& getState() const { // Notice the 2 `const` on this.
        return state;
    }

Move semantics and efficiency.

Copy semantics are good for simple types. But move semantics allow you a very effecient way of adding an object to another object. So you should learn how to move or construct in place an object.

    // Your version forces two copies.
    // You have a copy when you call setState to put the object
    // into the parameter `state` then you have a second copy
    // when you assign to `this->state`
    void setState(T state) {      // Copy here
        this->state = state;      // Copy here
        stateChanged();
    }

If T was large thats a lot of extra copying.
You should replace this with three methods:

    void setState(T const& newState) {   // Pass by reference avoid copy.
        state = state;
        stateChanged();
    }

    void setState(T&& newState) {        // Pass by RValue-Ref avoid copy.
        state = std::move(newState);     // Then move over current state.
        stateChanged();
    }

    // Advanced technique
    template<typename... A>
    void setState(A&&... args) {             // Pass arguments to construct a T by ref
        state = T(std::forward<A>(args)...); // Build the state in place.
        stateChanged();
    }

Don't use this-> it hides errors.

        this->state = state;

The only reason to use this-> is to distinguish a member that has been shadowed by a local variable (like a parameter). The problem is that it is error prone.

You must always remember to use this-> to use the local member otherwise you will accidentally use the local variable. If you forget there is no compiler warning that will help you.

On the other hand the compiler will warn you when you have shadowed variables. So if you never have a shadowed variable you can never accidentally use the wrong one.

Thus it is discouraged to use this-> as you are just setting yourself up for a hidden error. Rather make the compiler warn you about shadowed variables and use an appropriate name so it does not shadow.

Prefer '\n' over std::endl

    std::cout << "Testing Subject-Observer implementation:" << std::endl;

The difference between the two is a flush of the stream (done by std::endl). Flushing done by the user is one of the main speed slow downs in C++ code over C. The streams will already flush themselves at the optimal time, so a manual flush will usually retard performance.

Prefer to use automatic variables.

    ConcreteSubject<int>* ptr_subject = new ConcreteSubject<int>(42);

This is not Java. You don't need to new objects to create them you can just declare them locally.

    // This creates a local object
    ConcreteSubject<int> ptr_subject(42);

Using pointers like this (RAW pointers) is also discouraged as it very dangerous. If an exception occurs you will leak the pointer. You also have to keep track of the object and remember to call delete on it, which is error prone (as shown by a decades worth of C code). So we usually use wrappers to make sure the delete is called automatically.

    std::unique_ptr<ConcreteSubject<int>> aPointer std::make_unique<ConcreteSubject<int>>(42);

This is a pointer held inside an object wrapper. When it goes out of scope it will automatically be destroyed, this calls the destructor, which calls delete on the contained pointer.

As an example:

    ConcreteObserver<int>* ptr_observer_1 = new ConcreteObserver<int>(ptr_subject);

I see no call to delete for this object. So you just leaked it.


Print a word, one character per line, backwards

Looking at the two implementations side by side, ignoring the goal of the exercise and alternative implementations, I'd say the second example is better:

It uses one fewer variables.
It does a simple index lookup rather than a slice.
The implementation is easier to follow.

For simple problems like this it's often useful to think of the complexity of the solution as the number of "tokens", or distinct language elements, necessary to write it down. For example, print(cont2) is four tokens: print, (, cont2 and ). By a quick read the first example has about twice as many tokens as the second.


result points to the variable being the actual result being returned, but it's actually the current state of processing. Even new_chunks would be a better name.
Some expressions like index + len(chunk.word) or element.index + len(element.text) repeat themselves, and would be better as named variables describing their meaning. This also makes advancing the index inside the for more readable.

index_after_chunk = index + len(chunk.word)
index_after_element = element.index + len(element.text)
Advancing the index: index = index_after_chunk

You should be using Python's chained comparisons for the last if:

if index < index_after_element <= index_after_chunk:

EDIT:

On further examination it seems you're actually checking for intersection of index ranges. Let's say we have this:

from collections import namedtuple
class IndexRange(namedtuple('IndexRange', ['start', 'length'])):
  @property
  def end(self): return self.start + self.length

  # more helper methods here

chunk_range = IndexRange(start=index, length=len(chunk.word))
element_range = IndexRange(start=element.index, length=len(element.text))

You can now cleanly express the logic as (I'm inventing methods here but you get the point):

if chunk_range.disjoint_from(element_range):

first case, ranges are disjoint

elif chunk_range.fully_contains(element_range):

second case, element_range is fully contained in chunk_range

elif chunk_range.contains_point(element_range.end):

third case, element_range starts before chunk_range and ends inside_chunk_range

else:

final case, element_range starts inside chunk_range and ends after chunk_range OR element_range fully contains chunk_range

If I got the cases right, then

You should at least add them as comments explaining what each branch means
Possibly justify the final case in the comment
Possibly reorder the cases to better express your meaning. You don't have to rely on elif, it's not a big deal if you re-test something you've tested before as long as it's readable and encapsulated in a helper method or function.


I have a few suggestions for you:

You should get in the habit on wrapping all code that isn't in a function in a main guard, to ensure that that code only runs if that file is running, and to protect it from import mishaps
Running your code with pylint, a few warnings that popped up were:

Returns: All return statements should return something or none of them should return anything. Since you are returning permutations, the other return's should just return None.
Module Docstring: Your function should contain a docstring describing what the function does, even if it's very obvious. These will help any documentation.
Constant variable names: Since the three variables in the main guard do not change, they should be in all UPPERCASE to make it clear that they are constants.

Refactored code:

def valid_moves(position, target, legal, path, permutations):
    """ Returns unique ways to climb a staircase with passed length `target` """
    if position > target:
        return None
    if position == target:
        permutations.append(path)
        return None
    for move in legal:
        valid_moves(position + move, target, legal, path + [move], permutations)
    return permutations

if __name__ == '__main__':
    START = 0
    STAIRCASE_LENGTH = 3
    LEGAL_MOVES = [1, 2]

    print(*valid_moves(START, STAIRCASE_LENGTH, LEGAL_MOVES, [], []), sep="\n")


Working with resources

In read_and_write_after_tranformation you didn't bother to close any of the image resources:

# Based on a StackOverflow answer.
im = Image.open(infile)
list_of_pixels = list(im.getdata())
im2 = Image.new(im.mode, im.size)
im2.putdata(transformation(list_of_pixels))
im2.save(outfile)

Don't believe everything you read on Stack Overflow =)

You can wrap those in a with ... as. And while at it,
im and im2 are not great names.

with Image.open(infile) as in_img:
    list_of_pixels = list(in_img.getdata())
    with Image.new(in_img.mode, in_img.size) as out_img:
        out_img.putdata(transformation(list_of_pixels))
        out_img.save(outfile)

Usability

This is a nice script.
It would be great to make it more usable,
with command line parameters:

hide sub-command: message to hide, input file, output file
show sub-command: file

You probably already know this, but argparse would be a good tool for this job.


Calculation of the distance to the next space station

Here are a few tips:

Instead of getting each character, creating a new string from it, and then parse the string into a number, just get the character and convert the character code into the number.
Alternatively, parse the whole number once, then get the digits numerically using modulo.
There are only ten digits, so you can easily set up an array of precalculated cube values.
K is a double, but there are no floating point operations here. Use an int, or a long if needed.

Example:

int T = Convert.ToInt32(Console.ReadLine());
int[] cube = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };
for (int k = 0; k < T; k++) {
  string[] split = Console.ReadLine().Split(' ');
  int N = Convert.ToInt32(split[0]);
  int Kst = Convert.ToInt32(split[1]);
  int K = 0;
  for (int i = 0; i < N - 1; i++) {
    K = 0;
    while (Kst > 0) {
      K += cube[Kst % 10];
      Kst /= 10;
    }
    Kst = K;
  }
  Console.WriteLine(K - Convert.ToInt32(split[2]));
}


Incrementing Values inside an if statement

I would say this is quite questionable.
Imagine you never saw this code before, and are trying to understand it, would this make it easier to understand or harder? I say harder.


You don't have to loop throught the collection since you can directly query the database or your object if it is already loaded:

class User extends BaseUser
{
    public function hasRole($checkRole)
    {
        $userWithRole = UserQuery::create()
            ->filterByRole($checkRole)
            ->findOne();

        return !is_null($userWithRole);
    }
}

You can either check that $userWithRole is not null like I did or if it is an instance of User.

If your objects are already hydrated you can avoid the query by querying the Roles collection:

class User extends BaseUser
{
    public function hasRole($checkRole)
    {
        return $this->getRoles()->contains($checkRole);
    }
}


Small things

Your code styling is generally good, but a few possible improvements:

You can add a second generic type parameter to your method to avoid the need to cast to object. i.e. public static List<TIn,TOut> MergeListData<TOut>(List<TIn> collection)
You can probably use a more general collection than List<object> for your input collection. If you use IEnumerable<object> (changing your for for a foreach, which you should probably do anyway), then you can avoid the cast without having to do the previous bullet point, since IEnumarable<T> is covariant
Those exception handlers probably shouldn't be crammed onto a single line. If it were just the catch or the if, it'd be okay, but combining the two seems like too much
_propinfo shouldn't have the underscore, this is usually used for class-level fields.

The general approach

More of an issue is the overall approach of using reflection here. Reflection has three major problems:

It isn't safe. For example, here you could pass a generic type that doesn't have a default constructor and fail on the Activator.CreateInstance. This could be fixed with a generic type constraint, but that limits the useability of the method.
It's hard to read and maintain. The previous bullet point is one potential issue I noticed. Are there others? Who knows, reflective code is really ugly, and verifying all the edge cases by eye is tough!
It's slow. Whether this matters depends on context, but this method is pretty general-purpose, low-level, and operates on collections, which means that decent performance is at least desireable.

So, can we avoid it? Well, when you call the method, you already know what your two types are. Code with that knowledge should also know how convert between the two. So why not delete all that code and just write:

var bs = List1.Select(x => new Name2 { First = x.First, Last = x.Last }).ToList();

What you lose in automagicness you more than make up for in clarity, conciseness, verifiability, and performance. You can of course use a method somewhere instead of a lambda, to avoid spreading the mapping info all over the place.

If you really need this functionality (e.g. because there are lots of types, most of them can map to each other, and you don't feel like writing n^2 mapping methods)... well, that seems like an unusual situation, and I'd start by taking a step back and asking if this indicates a broader architectural problem. But if you've satisfied yourself that it's sensible, then I'd suggest using a library like AutoMapper rather than trying to roll this yourself. That way you don't have to concern yourself with how the magic works, and you get something much more mature and fully-featured (and, probably, performant).


For python 3.0+ (as @Serdalis suggested)

', '.join("{!s}={!r}".format(key,val) for (key,val) in k.items())

Older versions:

', '.join("%s=%r" % (key,val) for (key,val) in k.iteritems())


Some minor nit-picks about your code.

Object.defineProperty(array, method, {
    configurable: false,
    enumerable: false,
    writable: true,
    value: function () {
        // ...

Here, configurable and enumerable default to false anyway. You needn't set them explicitly.

if (noReturnMethods.indexOf(method) > -1) {
    Array.prototype[method].apply(result, arguments);
}

With ES6, you can write the if condition more concisely as noReturnMethods.includes(method).

You could improve readability by storing ['pop','push','reverse','shift','unshift','splice','sort','map','filter'] in a variable. You could probably do

var noReturnMethods = ['push', 'pop', 'reverse', 'shift', 'unshift'];
var returnMethods = ['splice','sort','map','filter'];
var methods = [];
methods = methods.push.apply(noReturnMethods, returnMethods);

... to avoid duplication of the names of methods.

With ES6, you could do methods = [...noReturnMethods, ...returnMethods].

Assuming your environment supports ES6, you should probably make use of arrow functions and the let and const keywords.


The core of your search algorithm is OK except for one thing:

The while(true) loop will run forever, if the searchingFor is not in the array.

In addition you should organize your code properly by separating functionality:  test input/output in one function and the algorithm in another:

void TestBinarySearch()
{
  Console.Write("Enter Array Length: ");
  int length = int.Parse(Console.ReadLine());
  Console.Write("Enter Search Target: ");
  int target = int.Parse(Console.ReadLine());

  Random rand = new Random(5);
  int[] data = Enumerable.Range(0, length).Select(n => rand.Next(length)).OrderBy(d => d).ToArray();
  int foundIndex = BinarySearch(data, target);
  if (foundIndex >= 0)
    Console.WriteLine($"Target found at: {foundIndex}");
  else
    Console.WriteLine("Target not found");
}

int BinarySearch(int[] data, int target)
{
  int min = 0;
  int max = data.Length - 1;
  int mid = (data.Length - 1) / 2;

  while (min != mid && max != mid)
  {
    if (data[mid] == target)
    {
      return mid;
    }

    if (data[mid] < target)
    {
      min = mid;
      mid = (min + max) / 2;
    }
    else if (data[mid] > target)
    {
      max = mid;
      mid = (min + max) / 2;
    }
  }

  return -1;
}


Count the ways to partition an array into two equal sets

Your current approach is going to be very slow because you're slicing the each time and then that is followed by an unnecessary sort calls and ultimately you call set() on both of the lists.

Slicing a list is very slow, because it requires creating an array of new references(pointers) to the items of the original array. To fix that we can use collections.deque here, ie. start with two deques first. First one is going be a deque(say full_deque) of the list passed to the array and second one will be empty(say current_deque). And now during the loop we simply pop the leftmost item from the full_deque and append it to the current_deque, these are O(1) operations for a deque so we will save a lot of time. And then simply call set() on both deques and compare those sets:

from collections import deque

def solve_deque(seq):
    count = 0
    full_deque = deque(seq)
    current_deque = deque()
    for _ in xrange(len(seq)):
        current_deque.append(full_deque.popleft())
        if set(current_deque) == set(full_deque):
            count += 1
    return count

The above operation is around 7 times faster than your version:

>>> A = [random.randint(0, 100) for _ in xrange(1000)]
>>> %timeit solve(A)
10 loops, best of 3: 74.4 ms per loop
>>> %timeit solve_deque(A)
100 loops, best of 3: 11.3 ms per loop

But for bigger list it is still not good enough as the set() calls in each loop are expensive.

>>> A = [random.randint(0, 100) for _ in xrange(10**5)]
>>> %timeit solve_deque(A)
1 loops, best of 3: 1min 26s per loop

To improve this even further we need to approach this differently, and one such approach is to use a Counter. Similar to deque we maintain two Counters here: 1. full_counter: Contains count of the initial list items 2. current_counter: Contains counts of items seen so far. Apart from these we are also going to maintain two sets here: 1. full_keys: Initial unique items from the list 2. current_keys: Unique items seen so far.

Here during the loop we are going to increment the count of current item in current_counter and decrease its count from the full_counter. But we can't compare these counters, so that's where the 2 sets come in. Firstly add current item to the current_keys set and then check if the count of current item is equal to 0 in full_counter and if it is then we can remove this item from the full_keys set and then simply compare these two sets:

from collections import Counter

def solve_counter(seq):
    count = 0
    full_counter = Counter(seq)
    current_counter = Counter()
    full_keys = set(seq)
    current_keys = set()

    for item in seq:
        current_counter[item] += 1
        full_counter[item] -= 1
        current_keys.add(item)
        if full_counter[item] == 0:
            full_keys.remove(item)
        count += full_keys == current_keys
    return count

Timings:

>>> A = [random.randint(0, 100) for _ in xrange(1000)]
>>> %timeit solve_counter(A)
1000 loops, best of 3: 764 µs per loop
>>> A = [random.randint(0, 100) for _ in xrange(10**5)]
>>> %timeit solve_counter(A)
10 loops, best of 3: 109 ms per loop

Few other points:

The recommended way to get both item and the index is to use enumerate() rather than using range() with indexing. Also in Python 2 range() returns a list, so unless you actually need a list always use xrange().
Use upper case variable names(A) only for module level constants, that applies to the function arguments as well, we can use num_list or seq instead of A here.
left[:i].sort() and right[i:].sort() are useless, slice on Python lists returns a new shallow copy. So, here you created two new lists first, sorted them and then threw them away. To sort left and right, simply do left.sort() and rigth.sort().


Showing different forms for user type with Django/Python in views.py

Dicts are good for lookups

When encountering stacked ifs that are all alike, I tend to pickup a dict and try to put it to good use.  One way to structure the variable parts of your routine is with something like:

user_form_types = {
    UserProfile.INSURANCE_BROKER: InsuranceBrokerForm,
    UserProfile.AUTO_DEALERSHIP: AutoDealershipForm,
    UserProfile.MORTGAGE_BROKER: MortgageBrokerForm,
    UserProfile.REALTOR: RealtorForm,
}

This one structure allows the variability in the routine to be described in a manner that makes it easy to read and understand that variability, and easy to use the resulting data.

Using data as code

Since Python makes it easy to reference a class and then instantiate it, the dict can be used, and the routine can be boiled down to simply:

user_form_type = user_form_types.get(profile.affiliate_type)
if not user_form_type:
    form = None
else:
    if postdata:
        form = user_form_type(postdata, instance=profile)
    else:
        form = user_form_type(instance=profile)
return form

Entire Recast Routine

def _get_form(profile, postdata=None):

    user_types = {
        UserProfile.INSURANCE_BROKER: InsuranceBrokerForm,
        UserProfile.AUTO_DEALERSHIP: AutoDealershipForm,
        UserProfile.MORTGAGE_BROKER: MortgageBrokerForm,
        UserProfile.REALTOR: RealtorForm,
    }

    user_form_type = user_types.get(profile.affiliate_type)
    if not user_form_type:
        form = None
    else:
        if postdata:
            form = user_form_type(postdata, instance=profile)
        else:
            form = user_form_type(instance=profile)
    return form


Is this attempt at a merge sort correct?

When a prospective employer asks you a question like this one, they most likely want to see something original.  They want you to show them that you can create code and not just copy and paste bits and pieces of code.

If what you wrote works and runs correctly, then you have accomplished the answer.

Sometimes employers are trying to find out if you know the theory behind a merge sort.  It looks to me like you have done that as well.

The only thing that I can think of that you could do to make your code better is to improve the naming of your variables.

int[] A = {2, 4, 5, 7, 1, 2, 3, 6};
int[] L, R;

L = new int[A.length/2];
R = new int[A.length/2];

Change them to

int[] array = {2, 4, 5, 7, 1, 2, 3, 6};
int[] leftSide;
int[] rightSide;

leftSide = new int[array.length/2];
rightSide = new int[array.length/2];

This would make it much easier to read.


basic structure/design

I would not echo in a class, but throw an exception instead. That way, the calling class can decide how to handle these problems, and your class will thus be more flexible.

Your class also does two things: It changes a password, and it redirects. I would leave the redirection to the calling class as well (but this is probably a matter of taste).

is_empty

The is_empty function doesn't seem to be working correctly.

If only one of the two fields is filled in by the user, Field/s are empty is echoed, but set_values is called anyways.

In this case it doesn't really matter, because it will not do anything. But then your function could be simplified to:

private function is_empty(){
    foreach($_POST as $post_value){
        if(empty($post_value)){
            echo "Field/s are empty";
            break;
        }
    }

    $this->set_values();
}

An alternative way would be to move that check into set_values, where all the other checks also take place:

    if ($this->password_one == "" || $this->password_two == "") {
        $this->show_message("Field/s are empty");
    } else if($this->password_one != $this->password_two){
        $this->show_message("Please make sure the passwords match");
    }else if (strlen($this->password_one) <= 10) {
        $this->show_message("The password you provided is too weak");
    } else {
        $this->password_one = md5($this->password_one);
        $this->change_password_to_new();
    }

Note that I rearranged the if statements for more readability, and used the shoe_message method for all messages, instead of using echo.

Naming

is_posted doesn't seem like an optimal name, although I have problems coming up with a better name.
PHP class names should be in CamelCase

Misc

I would not change a user password. If a user wants their password to be "    <p>  \'  <!-- super good password --> why not let them? In addition to annoying users, this could also lead to real problems, because you have to use those exact filter functions everywhere where the user supplies a password, as otherwise some users will not be able to login.
in set_values, the or (strlen($this->password_two) > 10 check is unnecessary, as password_one and password_two are equal and password_one is already checked.
security: md5 isn't really considered good enough anymore. If possible, you should use bcrypt (password_hash in PHP) or pbkdf2 instead.


I would try to use bulkcopy to load all of the IDs and their CachedText at once into a staging table in Azure, and then do a single update on your document table.

 CREATE TABLE document
(docKey     BIGINT IDENTITY(1, 1) PRIMARY KEY,
 CachedText NVARCHAR(MAX),
 id         INT
);
CREATE TABLE document_stage
(CachedText NVARCHAR(MAX),
 id         INT
);

As you iterate over the files, you create a PSObject with the properties you want in your sql table and add it to an collection. Then after all files are done, or at set batching limits you can use Out-DataTable to convert the collection into a data table, and then let SqlBulkCopy upload to the stage table in one batch, and a single UPDATE will update your primary table.

UPDATE Document
  SET
      CachedText = stg.CachedText
FROM document_stage stg
WHERE document.id = stg.id;

PS script

$files = Get-ChildItem -force -recurse $documentFolder -include *.doc, *.pdf, *.docx

$stagedDataAsArray = @()
foreach ($file in $files) {

    $fileName = $file.name
    $4ID = $fileName.split('-')[1].replace(' ', '').replace(".txt", "")
    $text = Get-Content "$($file.FullName)"
    $text = $text.replace("'", "''")

    $resumeID = $IDCheck | where {$_.OldID -eq $4id} | Select-Object OriginalResumeID
    $resumeID = $resumeID.OriginalResumeID

    <# create the row and add it to our  #>
     $fileInstance = New-Object -TypeName psobject
    $fileInstance | add-member -type NoteProperty -Name cachedText -Value $text
    $fileInstance | add-member -type NoteProperty -Name resumeID -Value $resumeID
    $stagedDataAsArray += $fileInstance
    Remove-Item -Force "$env:TEMP\$fileName"

    }
    $stagedDataAsTable = $stagedDataAsArray | Out-DataTable
    $cn = new-object System.Data.SqlClient.SqlConnection("YOUR AZURE DB CONNECTION STRING");
    $cn.Open()
    $bc = new-object ("System.Data.SqlClient.SqlBulkCopy") $cn
    $bc.DestinationTableName = "dbo.document_stage"
    $bc.WriteToServer($stagedDataAsTable)
    $cn.Close()

    $params = @{
        'Database' = $TRIS5DATABASENAME
        'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName)
        'Username' = $AdminLogin
        'Password' = $InsecurePassword
        'query'    = "UPDATE Document
  SET
      CachedText = stg.CachedText
FROM document_stage stg
WHERE document.id = stg.id;"
    }
    Invoke-Sqlcmd @params -ErrorAction "SilentlyContinue"


Breadth-first tree traversal using STL list

Don't use malloc(). If you do then you will need to track memory that is allocated with new and that allocated with malloc and use the appropriate de-allocation functions. Also using new calls the constructor and makes sure the object is correctly initialized.

#include<malloc.h> //on llvm we don't need this

Don't do this:

using namespace std;

See Why is “using namespace std;” considered bad practice?

In C++ you don't need to typedef structs. struct names are in the same namespace as everything else. Also Add a constructor to make sure things are correctly initialized.

typedef struct Node{
    int val;
    struct Node* left;
    struct Node* right;
}node;

// Prefer
struct Node
{
     int    val;
     Node*  left;
     Node*  right;
     Node(int v):val(v), left(NULL), right(NULL) {}
};

When pushing a value onto a tree or list. Return the new value rather than pass out values.

void push(node** root,int val)

// Your current usage is:
push(&head, 5);

// Easier usage
head = push(head, 5);

Don't use C casts

        node* temp=(node*)malloc(sizeof(node));

If you must cast then use one of the C++ cast's. But any casts are a sign of bad design. Also using new means this is not required.

// Easier implementation of push:
Node* push(Node* current, value)
{
    if (current == NULL)
    {   return new Node(value);
    }

    if (value <= current->value)
        current->left  = push(current->left,  value);
    else
        current->right = push(current->right, value);

    return current;
}

In your breadth first printing of the tree don't treat the head as special. You should just push the head node onto the list. The loop while the list is not empty. Thus you remove the item at the top of the loop not the bottom.

// Code deliberately left out to make you work.

Don't free the nodes as past of the print function. Add a destructor to your node. So that it calls delete on left and right.

~Node()
{    delete left;
     delete right;
}

Then all you need to do is delete the head and all the nodes will be destroyed correctly.

Your design should hide the memory management. You should put the head node inside its own structure. So that it hides all the memory management and you the user of your class does not need to worry about any of that

class Tree
{
    Node*   head;
    Tree(Tree const& copy);
    Tree& operator=(Tree const& rhs);
    public:
        Tree(): head(NULL) {}  // Set up empty tree.
       ~Tree() {delete head;}  // Memory management done.

        void push(int val)
        {
            head = ::push(head, val);
        }
        void printBF()
        {
            ::printout(head);
        }
};

Note the functions you wrote should also made as members of Node.


Return a List based on very similar data

var inputs = new List<MyObject>();
inputs.Add(AssembleMyObject(key, "@BeginTime", MyObjectPropertyConstants.BeginTime()));
inputs.Add(AssembleMyObject(key, "@EndTime", MyObjectPropertyConstants.EndTime()));

return inputs;

You could rewrite this to make it more DRY using LINQ into:

return new Func<Dictionary<string, string>>[]
{
    MyObjectPropertyConstants.BeginTime,
    MyObjectPropertyConstants.EndTime
}.Select(f => AssembleMyObject(key, "@" + f.Name, f()).ToList();

var MyObject

Local variables are usually named in camelCase, e.g. myObject.

public static Dictionary<string, string> BeginTime()

Method should be named using verbs, this looks more like a property. Thought making this into a property would make the above LINQ rewrite more difficult.

new Dictionary<string, string>
{
    {"stuff", "@BeginTime"},
    {"VISIBLE", "TRUE"},
    {"CAPTION", "*beginTime"},
    {"DISPLAYTYPE", "DATEPICKER"},
    {"DATATYPE", "DATE"},
};

Does order matter here? If it does, you shouldn't use Dictionary, since it doesn't guarantee ordering.


Test many sorting algorithms using Python and Nose

You don't need backslashes for line continuation inside any pair of brackets. Remove them. Further, this formatting IMHO is quite strange anyway.

The second problem is that you are both modifying the sorted array and returning it. Note how list.sort modifies but doesn't return and sorted returns but doesn't modify. Considering how slow your sort is, a copy at the start wouldn't hurt.

Your docstring is also all wrong; docstrings should mention user-facing concerns, not implementation detail. A thorough one might say

Sort the input container in place and return it.

This sorts in n² time and is not guaranteed to be stable.
The input must be mutable and its elements must have total order.

Talking about the tests, I'm going to ignore the framework and focus on the meat of the problem. I would try and get automatic test generation down first.

You really want two things. First, for small values do an exhaustive check:

from itertools import product

def test_sort_small(sort):
    for length in range(8):
        for sortable in product(range(4), repeat=length):
            sortable_copy = list(sortable)
            sorted_copy = sort(sortable_copy)

            assert sorted_copy is sortable_copy
            assert sorted_copy == sorted(sortable)

For large values do a random check.

import random

def test_sort_large(sort):
    for log_length in range(4, 12):
        for length in range(2**log_length-4, 2**log_length+5):
            sortable = [random.randint(0, 3) for _ in range(length)]

            sortable_copy = list(sortable)
            sorted_copy = sort(sortable_copy)

            assert sorted_copy is sortable_copy
            assert sorted_copy == sorted(sortable)

Tie those together

def test_sorts(sorts={selection_sort}):
    for sort in sorts:
        test_sort_small(sort)
        test_sort_large(sort)

test_sorts()

Put this logic in whatever framework you want.

Personally I'd also throw in a test with a more compex object, but it shouldn't really matter.

I would definitely try testing with another container, such as a bytearray, if you want to support them.

You could easily get a stable sort, so you might want to add that and add associated tests.


There's one small bug in your code here:

memcpy(foo_addr, shellcode, sizeof(shellcode));

This copies the contents of shellcode, but being a string literal, shellcode includes a null terminator and sizeof(shellcode) is equal to 30, not 29. You should replace this line with:

memcpy(foo_addr, shellcode, sizeof(shellcode) - 1);


While the implementation looks logically correct, some remarks about code style:

package name should include your organization, e.g. com.your.company.users, com.your.company.global
there is no need to prefix arguments with a, you can use the same name as the object fields, since through this, it can be determined which one is referred.

E.g:

public Client(String nick, ...) {
    this.nick = nick;
    // ...
}


A few quick comments:

Read PEP 8, the Python style guide. In particular, Python uses lowercase_with_underscore variable names, and put commas after spaces.
Add some docstrings to your functions, so that it’s clear what purpose they serve in the context of your calculator. This will become useful as you extend the calculator, and you want to change existing function: you may remember what each function is for at the moment, but you may not in six months time.
Add more comments. Tell me why you’re doing certain operations. Anybody can read the code and see what it’s doing, but why is it doing it?

For example: after some inspection, I see that you iterate through prioritizedOperators to apply each operation in order (multiplication and division, then subtraction and addition).
You have no error handling, which means I can enter something silly like 1/0 and get a ZeroDivisionError. You also claim that it only works for positive integers, but the simple examples I tried with negative integers seemed to work as well.

If you only want it to work with positive integers, then you should spit out any input that isn’t positive.
You claim that

  My division rounds up if it isn't an integer

but this doesn’t seem to be true. For example, if I enter 2/3 then I get output 0.
There is no need for getPriorizedOperators to be a function. Just declare the list as a variable in operator.py, then import it in calculator.py. For example:

operator.py:

prioritized_operators =  [
    multiply_operator(),
    divide_operator(),
    plus_operator(),
    minus_operator()
]

calculator.py:

from operator import prioritized_operators

I would rename your _isNumber() function. It only checks if a single character is a numeral, but the name implies I might be able to pass in arbitrary-length strings. Perhaps _is_digit() would be better.

You can tidy up the function logic a little. Rather than calling out to ord(), you can also compare strings directly for the same result. For example:

>>> "0" < "5" < "9"
True
>>> "0" < "x" < "9"
False

Or you could just use the builtin function isdigit(), and do away with your function entirely:

>>> "5".isdigit()
True
>>> "x".isdigit()
False

(Whether you use the latter depends on how much you want to reinvent the wheel.)
Having two functions called calculate() and _calculate() is prone for confusion. Rename one or both of them to have a more specific name.


Yes, It can be better in many ways just replace all your code with this:

The first thing I did is made the code formatting just a bit better.
then I added a title tag a webpage cannot go on without a title
after that I include the meta tags for the UTF-8 encoding and then the viewport meta tag for responsiveness. I also corrected your opening body tag you wrote it as the closing body tag.

Tip: Use vscode as your code editor and add the prettier extension with it to format your code better.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Your Page should have a title</title>

    <form name = "calculator">

        <input type = "text" name = "display" id = "display" disabled>

        <input type = "button" name = "one" value = "1">
        <input type = "button" name = "two" value = "2">
        <input type = "button" name = "three" value = "3">
        <input type = "button" name = "plus" value = "+">

      <input type = "button" name = "four" value = "4">
        <input type = "button" name = "five" value = "5">
        <input type = "button" name = "six" value = "6">
        <input type = "button" name = "minus" value = "-">

        <input type = "button" name = "seven" value = "7">
        <input type = "button" name = "eight" value = "8">
        <input type = "button" name = "nine" value = "9">
        <input type = "button" name = "multiplicatio" value = "*">

        <input type = "button" name = "clear" value = "c">
        <input type = "button" name = "0" value = "0">
        <input type = "button" name = "equal" value = "=">
        <input type = "button" name = "division" value = "/">

    </form>

The Js part

The only thing I did with the Javascript is made the code formatting a lot more readable

window.onload = () => {
  const calculator = document.querySelector('form[name = "calculator"]');
  const btns = document.querySelectorAll(
    `form[name = "calculator"] table tr input[type = "button"]`
  );
  btns.forEach((button) => {
    if (button.value != "c" && button.value != "=") {
      button.addEventListener("click", () => {
        calculator.display.value += button.value;
      });
    } else {
      if (button.value == "c") {
        button.addEventListener("click", () => {
          calculator.display.value = "";
        });
      } else if (button.value == "=") {
        button.addEventListener("click", () => {
          calculator.display.value = eval(calculator.display.value);
        });
      }
    }
  });
};


Make repeating numbers 0 and putting them at the beginning of array

Declaration

  int arr[],n,i,j,nr[]= new int[5];

Consider to declare variables on separate lines. From Code Complete, 2nd Edition, p761:

  Use only one data declaration per line

  [...]

  It’s easier to modify declarations because each declaration is self-contained.

  [...]

  It’s easier to find specific variables because you can scan a single column rather than reading each line. It’s easier to find and fix syntax errors because the line number the compiler gives you has only one declaration >on it.

Unused Variables

  int count =0;

count gets declared and initialized but is never in use.. Unused variables should be removed.

Magic Number

  Your code uses a number that has a certain meaning to it.

One magic number is hidden in the code.

  if(n>25) {

You can create a new constant variable MAX_SIZE

  if(n>MAX_SIZE) {
``

Formatting

  for( i=0; i< arr.length-1;i++)
{ for (j=i+1;j<arr.length;j++)
    {if(arr[i]==arr[j])
       nr[i]=arr[i];
        System.out.println(nr[i]);
    }}

The code has an inconsistent formatting. Some key words are on a new-line and some times on the same line of a {.

Additional the code is format in a more C-like style, which I respect but you should have a look into Oracles Code Conventions for the Java.

Reduce Code Complexity Via Methods

When we consider a Code Smell Metrics and look at the code, we will find at least two points, that apply:

  Methods with more than 20 lines of code
  Methods with nesting more than 2 (?) levels deep
  Any global or static variables

To reduce the complexity we can introduce some new methods. For example

  for(i=0;i<n;i++)
{
    arr[i] = sc.nextInt();
}

can be wrapped into a method storeUserInput.


I also understand that mysql_connect() et. al are deprecated in PHP since 5.5, but I assume better equivalents work the same way.

Sort of. MySQLi can work a lot like the the mysql extension, but personally I prefer PDO. Whereas MySQLi has both an OO and a procedural API, PDO has only an OO one.  PDO can interact with more than just MySQL though.

Due to differences in SQL dialects, it's rare for it to be possible to just change out the driver and have everything work. It is a lot closer to cross compatibility than a specific RDBMS's API.  Also, you can use your knowledge of the PDO API across multiple database systems.  Whether it's MySQL, sqlite, SQL Server, etc, the general API is the same.

Anyway, whether you choose MySQLi or PDO, you should definitely stop using ext/mysql.

As for SQL injection: your code is basically a poster child for it.

$choice = isset($_GET['status']) ? $_GET['status'] : '7';
$result = mysql_query("SELECT id, subject FROM issues WHERE status_id = " . $choice, $conn);

What if I go to page.php?status=0 OR 1=1?  The query becomes:

SELECT id, subject FROM issues WHERE status_id = 0 OR 1=1

This is a fairly benevolent example since all this will do is ignore the status filter. I've seen some very clever exploits though. Given enough time and determination, this small exploit could be ripped open into horrible, horrible things.

The easiest solution to SQL injection is to always stay aware that SQL is a language like any other (well, not on a technical level, but on a superficial level).

In particular, just remember to either escape content if it's being put into the query as a string, or cast it if it's being put in as something else.

For example:

$choice = isset($_GET['status']) ? (int) $_GET['status'] : 7;

$choice is now safe to put into an SQL statement.

This StackOverflow thread gives tons of options for properly handling SQL queries.

if (!$options || !$result || !$chosen_status)
{
    echo("
Error performing query: " . mysql_error() . "
");
    exit();
}

If more than one query fails, this will only output the error for the last one. Additionally, using exit for rendering errors is bad practice. In a file this simple, there's really not much of a better option without going way out of your way. What I tend to do in larger applications though is let uncaught exceptions (in other words, either the ones that I expect to never happen or the ones that are fatal) bubble up to the top at which point the request is transparently piped to an error controller (basically, I've copied the approach of most PHP MVC frameworks). If you wanted to use a similar approach, you could basically wrap exceptions over the MySQL API. That get's ugly fast though.

Oh, also, the mysql_error should be passed through htmlspecialchars.  I'll add more to this note in a minute.

I'm not sure if it's technically valid to close a MySQL connection and then read the result sets.  I suspect that this is not valid, and that if it works, it's just by luck.

Even when not going full-blown MVC, it can be very beneficial to separate logic or manipulation from the view.  In particular, all of the mysql calls in the HTML parts, I would put in the PHP parts.  If your view is only looping over an array, the source of the array can be changed without the view having to know about it.  (Side note: depending on how strictly we're using terminology, the HTML part is probably better not called a view.)

while ($row = mysql_fetch_array($options, MYSQL_ASSOC))

You might as well us mysql_fetch_assoc.

echo('<option value="' . $row['id'] . '">' . $row['name'] . '</option>');

Anything being put into HTML needs to be run through htmlspecialchars. This comes back to being aware of context. It's just the rules of HTML.  Certain things must be escaped in the same way that things in SQL or PHP must be escaped.

(I'm also not a fan of the echo() form of echo, but that's mostly opinion.)

echo '<option value="' . htmlspecialchars($row['id']) . '">' . htmlspecialchars($row['name']) . '</option>';

A lot of people will say that the htmlspecialchars on the id is pointless since it's going to be an int.  While that's true, that's only for now.  With a primary key column it's not likely to happen (in fact it probably shouldn't happen), but I've been in situations before where an int column has been changed to a varchar and we've had problems with the HTML escaping after that. Considering the overhead of htmlspecialchars is tiny, might as well call it on everything being put into HTML.

There's a few more comments and suggestions I have. I was originally going to add them as comments to the code, but I got a bit carried away and decided to rewrite it with PDO.

<?php

$db = new PDO('mysql:host=localhost;dbname=somedatabase', 'username', 'password', array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));

//The error mode being exception means that exceptions will be thrown if a query fails
//(or some other kind of error happens).  This tends to be more convenient since you don't
//have to explicitly check for unexpected errors -- either everything executes fine, or the script
//crashes and burns (which might not be desired behavior in a lot of cases).
//Anyway, there is one little catch.  PDOException instances will sometimes include with them
//the DSN (the 'mysql:host=...' string), the username, and the password. This means that you must be
//very careful about never letting an end user see a PDOException.  In particular, you can either have
//a just-in-case top level try {} catch {} that can catch any unexpected errors, log them, and render
//them in a pretty page (what I like to do in any kind of sizable application), or at the very least,
//you can ensure that display_errors of Off on production servers (which it should be anyway). That way
//the exception will still be logged, but it won't be displayed.

//$options is a bad name. What kind of options?
$issueStatusesStmt = $db->query("SELECT name, id FROM issue_statuses");

//This is done in a weird way, but it has a reason.
//In particular, you can now check if a provided status id exists (isset($issueStatuses[$idToCheck])).
//And, you no longer need your name query since you can pull the name with $issueStatuses[$id]['name'].
$issueStatuses = array();
while ($is = $issueStatusesStmt->fetch(PDO::FETCH_ASSOC)) {
    $issueStatuses[$is['id']] = $is;
}

//This handles the isset check and validates that the provided value is an integer.
//If the value fails the integer check, $statusId will be false.  If no status param is
//provided in the URL, $statusId will be null. There is of course a lot more
//information about this at http://php.net/filter_input
$statusId = filter_input(INPUT_GET, 'status', FILTER_VALIDATE_INT);

 if (!isset($issueStatuses[$statusId]) {
    //This is what's called a magic constant. They tend to lead to problems.
    //In particular, what is this magical status 7? Someone not intimately familiar
    //with your DB data will have no idea.
    $statusId = 7;
}

//This prepares a statement with a placeholder for status_id.
$issuesStmt = $db->prepare("SELECT id, subject FROM issues WHERE status_id = :statusId");
$issuesStmt->execute(array('statusId' => $statusId));
/*
 * You could also do it like:
    $issuesStmt = $db->prepare("SELECT id, subject FROM issues WHERE status_id = ?");
    $issuesStmt->execute(array($statusId));
 * I prefer to stick with named fillers though.  It's significantly less confusing if you have
 * to revisit a complicated query a month later.
*/

//You could make this an associative array like earlier, but really there's no reason to at this point.
$issues = $issuesStmt->fetchAll(PDO::FETCH_ASSOC);

//Note: if $statusId default to 7 and 7 somehow doesn't exist in the database,
//this will issue a notice and $statusName will be null.
$statusName = $issueStatuses[$statusId]['name'];

//PHP will only eat one new line.  The doctype is supposed to be the very top line (unless I've imagined that requirement).
//This means it need to be on the line directly after the closing tag.
?>
<!DOCTYPE html>

        <title>RM Rep</title>

        <form name="status_choice" action="index.php" method="get">
            <select name="status">
                <?php foreach ($issueStatuses as $is) { ?>
                <option value="<?php echo htmlspecialchars($is['id']); ?>"><?php echo htmlspecialchars($is['name']); ?></option>
                <?php } ?>
            </select>
            <input type="submit" value="Submit">
        </form>

<?php echo htmlspecialchars($statusName); ?>

        <?php echo count($issues) . ' results'; ?>

        <?php
        /*
         If no entries are found, you will emit broken HTML in your current code.
         (At least I think an empty table is invalid HTML -- can't remember.)
         (Oh and also, I'm abusing PHP comments right now...)
        */
        ?>

        <?php if (!empty($issues)) { ?>

            <?php foreach ($issues as $issue) { ?>

                <?php echo htmlspecialchars($row['id']); ?>
                <?php echo htmlspecialchars($row['subject']); ?>

            <?php } ?>

        <?php } else { ?>

            No entries matched the given status.

        <?php } ?>


I recommend creating a static class named something like Hash, Crypto or Password depending on your project/context and making these methods public static, instead of making them private methods for the user class.
WARNING!
Unless your password encryption management code is sophisticated enough to manage password scheme versions and handle multi-version-migration complications PasswordHashWorkFactor should not be editable (i.e. by editing the relevant key in the config file). In that case, editing it would cause migration efforts or MORE IMPORTANTLY the attacker with R/W access to the config file can crash the system easily by adding an unnoticeable digit to PasswordHashWorkFactor  (add a 0 to 100000). It would take significant time of the admin/dev to figure out the problem in a sophisticated config file while the users cannot log in. You may have it hardcoded as a const at the static class and change it in every major release at the code level. Again this is a matter of convenience vs security trade-off.
Here is my feedback in more detail as an implementation. You may want to check it out.


Dispatcher for a JSON API without routes

IMHO, all the ini_set doesn't belong here, but in the php.ini, unless you can't edit it for some reasons…

If so, it belong in a bootstrap file, as for the constant definitions and the include

  A bootstrap file usually starts by including those libraries that are necessary for the file itself to function correctly. This involves setting general directory and file paths, loading configuration files, etc.

This bootstrap file can also be very useful for many reasons described on the link i provided like:

  […] set up different application statuses such as Development, Production or Testing […]

An other thing:

IMHO, the test if (!headers_sent()) is pretty useless as is.

As you are returning JSON, you need to send this header('Content-Type: application/json'), so, if you can't for any reason, you should raise an error or an exception, not just doing nothing and echoing your JSON as if nothing happened…


Early-returns
else-after-return is redundant, so your stingy is equivalent to
    if (total_lambs == 1): # from condition 1 at least 1 individual gets paid
        return 1
    if (total_lambs == 2): # from condition 2 and 4 the most each can is 1
        return 2

    ind, total, x0, x1 = 2, 2, 1, 1 # no. individuals, sum of Fib seq, intial Fib nos.
    while (total <= total_lambs):
        x0, x1 = x1, x0 + x1 # advancing the Fib seq
        total = total + x1 # total is the sum of lambs paid
        if (total > total_lambs):
            return ind
        ind = ind + 1

Return parens
You have a mix of this style:
return 1

and this style:
return (stingy(total_lambs) - generous(total_lambs))

the latter not needing outer parens. Probably best to go with the non-parenthetical style. The same is true of
while (total <= total_lambs):

In-place addition
total = total + x1
ind = ind + 1

can be
total += x1
ind += 1


Makefile for C++ OpenGL with GLFW and glad

First of all, good for you for learning how to write a proper makefile.  Few people are any good at it, and it's a really fundamental tool.  Even when nice tools such as CMake are used, it's very useful to understand how to write one from scratch.

With that said, here are some things that may help you improve your makefile:

Prefer Makefile to makefile

The names are equivalent, but since you're using GNU Make, you may as well follow its conventions, and one convention is to name it Makefile instead of makefile.  Either will work, but quoting from the GNU Make man page:

  We recommend 'Makefile' because it appears prominently near the beginning of a directory listing, right near other important files such as 'README'.

Use standard variable names

There are standard names for some of the variables you're using.  For example, use CFLAGS instead of COMPILE_FLAGS and CXXFLAGS which is the same thing, but for invocations of g++ (or more accurately invocations of $(CXX)).  Similarly, use LDFLAGS instead of LINK_FLAGS.

Add INCLUDES to CFLAGS

It's good practice to use variables like INCLUDES to keep things tidy, but it would be better if you added that to CFLAGS:

CFLAGS += $(INCLUDES)

The reason for doing that is in the next point.

Use the implicit rules

GNU Make already has an implicit rule for creating .o files from .c files.  That rule looks like this:

 %.o : %.c
         $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@

The result of this is that if you have defined the flags correctly, you can omit an explicit rule and rely instead on the implicit rule.  In this particular Makefile, it means that you can entirely omit the rule for glad.o.  As long as glad.c is in the current directory, and main.cpp is in the current directory, the built-in rules will understand how to create both glad.o using gcc and main.o using g++.

To expand this a bit, here's what happens when I run make -d to get it to emit more detailed debugging information:

  Considering target file 'main.exe'.
    Considering target file 'main.o'.
     Looking for an implicit rule for 'main.o'.
     Trying pattern rule with stem 'main'.
     Trying implicit prerequisite 'main.c'.
     Trying pattern rule with stem 'main'.
     Trying implicit prerequisite 'main.cc'.
     Trying pattern rule with stem 'main'.
     Trying implicit prerequisite 'main.C'.
     Trying pattern rule with stem 'main'.
     Trying implicit prerequisite 'main.cpp'.
     Found an implicit rule for 'main.o'.
      Considering target file 'main.cpp'.

As you can see, after it has identified a needed target (main.o) it starts looking for implicit rules to create that target.  It finds one eventually because main.cpp exists.  To see the full list in order on your machine, create an empty subdirectory, navigate to it and execute make -d foo.o.  Since foo.o won't exist (it's an empty subdirectory) it will attempt to find an implicit rule that will allow it to create that file and with the -d option, it will tell you all of the things it's trying.  On my machine, that generates 734 lines of output, so there's really quite a number of implicit rules.  There are rules to create object files from C and C++, but also from Fortran, Pascal, Modula, assembly language, and for trying to check out a .o file from various version control systems.

Add LIBRARIES to LDFLAGS

Your main rule (pardon the pun) does this:

$(CXX) $(LIBRARIES) -o main.exe $(objects) glad.o $(LINK_FLAGS)

There are a number of changes I'd make to that line, but one is to consolidate $(LIBRARIES) and $(LINK_FLAGS) into a single variable with a standard name, which is LDFLAGS.

Use predefined variables

Try to avoid repeating hard-coded names in the production rules.  For example, the rule for main.exe could be much simplified to this:

$(CXX) -o $@ $^ $(LDFLAGS)

Add a clean psuedotarget

It's often useful (not least when testing makefiles!) to provide a clean psuedotarget to remove all of the files that were generated, providing a "clean slate" from which to start.  It might be written like this:

.PHONY : clean
clean :
        -rm main.exe $(objects) glad.o

This also makes it less likely that you'll want to have the makefile itself as a dependency, which makes the set of rules cleaner.  This would work even if the first line were omitted, unless there were actually a file named clean.  To tell the makefile that it's not a real file, we use the line .PHONY : clean.

Add glad.o to objects

If you add glad.o to the objects list, you can simplify the rules.

Consider isolating TARGET

For Windows, executables typically end in .exe but not so for most other platforms.  For that reason you could either have a specific variable for the executable extension or keep the target name in a variable:

TARGET = main.exe

Putting it all together

If we take all of these suggestions and apply them, the resulting files looks like this:

CC = gcc
CXX = g++

INCLUDES = -I$(glfw_inc) -I$(glad_inc)
LIBRARIES = -L$(glfw_lib)

glfw = d:/external/glfw-3.1
glfw_inc = $(glfw)/include
glfw_lib = $(glfw)/lib64

glad = d:/external/glad-c
glad_inc = $(glad)/include

CFLAGS = -Wall -ggdb -O3 $(INCLUDES)
CXXFLAGS = -Wall -ggdb -O3 $(INCLUDES)
LDFLAGS = $(LIBRARIES) -lglfw3 -lopengl32 -lglu32 -lgdi32

TARGET = main.exe
cpp_files = main.cpp
objects = $(cpp_files:.cpp=.o) glad.o
headers =

all: $(TARGET)

$(TARGET): $(objects)
        $(CXX) -o $@ $^ $(LDFLAGS)

.PHONY : clean
clean :
        -rm $(TARGET) $(objects)