I am not sure why you do not just use numpys ndarray and instead have invented your own version.
I would however suggest you make it derive from numpys ndarray, which will save you a lot of work, and it allow you to do all kinds of nice things with it. I would also use __setitem__ instead of replace, so you can use the grid[x,y] = value, notation.
There are some problems with the padding of the start data. First off it has side effects (your input is actually changed), and secondly it will only work with actual lists, other numpy arrays and Grids will fail. I recommend generating the grid first, and then slicing in the data when the input does not fit perfectly. Consider whether it would make sense to move setting the grid to have a certain value based on some data (possibly different types) to some other method.


Your code is disappointing.... as C++. Really, it is a C program written in C++. There's no classes, objects, instances, etc. In part, this is one of the reasons your code is slow.

A natural consequence of the way you compute your answers is that you have to re-build the entire stream 1, 3, and 9 sequences each time the code encounters a new test. If you had a "stream" class for each of the three base classes, and you "remembered" the stream, and made it searchable, then you would have a way to look up whether a test stream value joins. Using an iterator would make sense for the process too.

Iterate the stream, find if there is an intersection, move on.

your code is actually far worse than I realized when it comes to calculating the base 1,3, and 9 streams.... it rebuilds each stream each time you test a new value, for each new value in each test case... thus, for example, you could be computing millions, and millions of values unnecessarily.

You need to "remember" and "index" the base streams, and you'll fare much better.

Also, use the language to your advantage: classes, iterators, vectors, etc.


Recursive trim() function to handle arrays and objects

Avoid if-else nesting to keep things flat. Return inside the first if is enough to do so.

I added is_iterable() so this function can handle more types than just array

/**
 * trim_r
 *
 * Recursively trim an array's or object's string values
 * Preserves all non-string values
 *
 * @access  public
 * @param   mixed
 * @param   mixed
 * @return  mixed
 */
function &trim_r( &$o, $character_mask = null )
{

    // Only apply trim() to strings
    if( is_string( $o ) )
    {
        // Respect the $character_mask; cannot pass null as 2nd parameter for some HHVM versions
        $o = trim( $o, $character_mask ?? " \t\n\r\0\x0B" );
        return $o;
    }

    if( is_iterable($o) || is_object( $o ) )
    {
        // Loop this array/object and apply trim_r() to its members
        foreach( $o as &$v )
        {
            trim_r( $v );
        }

    }

    // Supply this just in case the invoker wishes to receive result as a reference
    return $o;
}


Sure, your method is better. It's a pretty straightforward example of some fundamental programming and design concepts:

You spotted repetition. The same information is being stated multiple times. In this case, the information is how to perform a particular operation for formatting a string. Generally, you should not repeat yourself.
This clued you in to an abstraction: the implementation of this formatting operation can be abstracted out behind a meaningful name
With this knowledge you abstracted out the operation by applying an extract method refactoring.
As a result, you now have code which is:

More readable, since the methods are simpler, and the name of the formatting method explains exactly what its purpose is.
More maintainable, since now any change to this formatting operation just has one place to occur, rather than having to be made in all the places that it's repeated


Reload polyline midpoints into parallel tables

I don't have any experience with arcpy, so possibly some of this may be invalid.
Mostly the code is very good: It's concise; it's clear enough what it does without lot's of documentation, and it has the documentation it needs.
Exactly what makes code "good" depends on how it's going to be used. This looks like a standalone utility you use at your work, so keeing it brief and easy to maintain is probably worth more that thoroughly documenting everything and enforcing type constraints. Not everything below will be applicable to you.
Context:

Use python 3.x if at all possible.
It's good that you've already put most of your code inside a function; now consider using the main method pattern.
The comment about truncating the table is good. You could move it to a confirmation prompt that would be shown to the user at runtime.

Style:

If you have parens of any kind (({[), you don't need to use \ to break your lines.
Your variable names could be more descriptive.
Use snake-case: this_is_a_variable
Be more aggressive about breaking your lines. A reader should rarely, if ever, need to scroll sideways.
Use parens for print statements. print("message") This is required in python 3.
Consider using "string".format() instead of string concatenation. (It make more of a difference in more complicated situations.)
You could save yourself a level of indentation by doing both your DB connections in a single with statement. (but see below)
The warning about truncating the table could be moved to a docstring.
The standard indentation scheme  is 4 spaces per level of indentation, and brackets & parens close on the same level of indentation as the line they were opened on:

lstFC = [
    ["<OWNER>.<SIDEWALK>", "<OWNER>.S_SIDEWLK_MIDPOINT", "SDW_ID"   ],
    ["<OWNER>.<SEWER>"   , "<OWNER>.S_SEWER_MIDPOINT"  , "SEWER_ID" ],
    ["<OWNER>.<ROAD>"    , "<OWNER>.S_ROAD_MIDPOINT"   , "ROAD_ID"  ],
]

Architecture:

It looks like you could make the string literals in lstFC less verbose, by pulling out the common patterns. But that might not be a good idea if those patterns are likely to fail in the future.
Instead of assigning inputFC, targetFC, and idField in three steps, use unpacking to do them all at once.
Alternately, you could save yourself the comment about what's in lstFC by having a class that exposes those as instance properties.
I think it would look better, and be more flexable, to move the for fc in lstFC: loop outside def ReloadMidpoints():, so you'll be calling the function inside the loop.
There's probably a way to do i_rows.insertRows(rows). That way you could first load all the data, then do all the transformations, then write all the data. You'd be making a single large request against the DB, which would likely be faster, and you'd have already succeeded or failed at all of the processing before you ever touched the database. You can even avoid having two connections going on at once.
Speaking of DB safety, consider using a transaction? I don't know how that's done in arcpy.
A lot of database systems support a command called REPLACE, which is like INSERT except it will delete conflicting data before inserting the new rows. If that's an option it might be better than the truncate and rebuild pattern you're using.

To summarize a lot of what I've written:
#!/usr/bin/env python3

import arcpy

DESCRIPTION = """
Transcribe the midpoints of source feature classes
to their respective target feature classes.
This script only works for polyline feature classes (not polygons or points).
CAUTION! The target FCs will get truncated!
         All records in the target FCs will be deleted.
"""

default_connection = "Database Connections\\<YOUR CONNECTION.sde>\\"

default_feature_classes = [
    ("<OWNER>.<SIDEWALK>", "<OWNER>.S_SIDEWLK_MIDPOINT", "SDW_ID"),
    ("<OWNER>.<SEWER>", "<OWNER>.S_SEWER_MIDPOINT", "SEWER_ID"),
    ("<OWNER>.<ROAD>", "<OWNER>.S_ROAD_MIDPOINT", "ROAD_ID"),
]

def main():
    if(_confirm()):
        for (input_FC, target_FC, id_field) in default_feature_classes:
            reload_midpoints(
                default_connection + input_FC,
                default_connection + target_FC,
                id_field
            )
        print(_main_success_message)

def _confirm():
    print(DESCRIPTION)
    input(_confirmation_prompt)
    return True

def midpoint(row):
    return row[0].positionAlongLine(0.50,True).firstPoint

def reload_midpoints(input_connection, target_connection, id_field):
    """Caution!
    The target FCs will get truncated! All records in the target FCs will be deleted."""

    new_rows = []
    with arcpy.da.SearchCursor(input_connection, ['SHAPE@', id_field]) as s_rows:
        new_rows = [
            [(m.X, m.Y), s_rows[1], m.X, m.Y]
            for m in map(midpoint, s_rows)
        ]

    if(new_rows):
        arcpy.TruncateTable_management(target_connection)
        print(_truncation_success_message.format(target_connection))
        with arcpy.da.InsertCursor(
            target_connection,
            ['SHAPE@', id_field, "MIDPOINT_X","MIDPOINT_Y"]
        ) as i_rows:
            i_rows.insertRows(new_rows)
        print(_midpoints_reloaded_message.format(target_connection, input_connection))
    else:
        print(_no_rows_message)

    print("")

_truncation_success_message = "<{0}> has been truncated."
_midpoints_reloaded_message = "<{0}> has been reloaded with midpoints that were generated from <{1}>."
_no_rows_message = "There are no new rows; doing nothing."
_confirmation_prompt = "Press Enter to continue..."
_main_success_message = "Complete."

if __name__ == "__main__":
    main()
```


Optimized solution for a rolling dice code puzzle

Based on your use of in_array(), you don't appear to be concerned with the order of the elements. In that case, you can simply sort the arrays and compare them directly.

function compare($array1, $array2)
{
    sort($array1);
    sort($array2);

    return ($array1 == $array2) ? "Lucky" : "Unlucky";
}


For the starter, you can create small function which will get input since your code requires too much user input.

Just making that one function will reduce repetitive code of raw_input() and printing it's msg.

Also, your code will be more readable.

Code:

def get_input(msg):
    print msg
    val = int(raw_input())
    return val

number = get_input("Please put the amount of BPs: ")

solution = (number * 660)
Avo = (6.022 * (10 ** 23))
Grams_Avo = ( solution / Avo)

conc = float(get_input("Put in Concentration (ng/ul): "))

multiple = (10 ** -9)
amount = (conc * multiple)
total = float(amount / Grams_Avo)
print "Amount of molecules:  %s" % total

plasmid = float(get_input("Amount of ul used by the plasmid: "))
particles = float(plasmid * total)

ratio = get_input("What ratio amount will you use?: ")

molecules_needed = float(particles * ratio)
print molecules_needed

oligo = float(get_input("Conc. of your oligo?: "))
oligo_num = float(oligo * multiple) # amount

G = get_input("Enter number of G in Oligo: ")

A = get_input("Enter number of A in Oligo: ")

T = get_input("Enter number of T in Oligo: ")

C = get_input("Enter number of C in Oligo: ")

sumG = (G * 329)
sumA = (A * 313)
sumT = (T * 304)
sumC = (C * 289)
daoligo = (sumG + sumA + sumT + sumC) # g/mol

print "Total amount of your insert %s" % daoligo

oligototal = float(oligo_num / (daoligo/Avo)) # molecules for insert
complete = float(molecules_needed/oligototal) #amount of insert needed from stock ul

m = """
    What dilution will you use?
    1. Stock
    2. 1:10
    3. 1:20
    4. 1:30
    5. 1:50
    """

code = float(raw_input())
code =  get_input(m)

if code == 1:
    print complete #stock
elif code == 2:
    code2 = (oligototal/10)
    complete1 = float(molecules_needed/code2)
    print complete1 #1:10
elif code == 3:
    code3 = (oligototal/20)
    complete2 = float(molecules_needed/code3)
    print complete2 #1:20
elif code == 4:
    code4 = (oligototal/30)
    complete3 = float(molecules_needed/code4)
    print complete3 #1:30
elif code == 5:
    code_5 = (oligototal/50)
    complete4 = float(molecules_needed/code_5)
    print complete4

Output

Please put the amount of BPs:
12
Put in Concentration (ng/ul):
1
Amount of molecules:  76035353535.4
Amount of ul used by the plasmid:
2
What ratio amount will you use?:
3
4.56212121212e+11
Conc. of your oligo?:
4
Enter number of G in Oligo:
4
Enter number of A in Oligo:
6
Enter number of T in Oligo:
7
Enter number of C in Oligo:
8
Total amount of your insert 7634
9

    What dilution will you use?
    1. Stock
    2. 1:10
    3. 1:20
    4. 1:30
    5. 1:50

1
1.44583333333


Write to a new, modified Excel file from an original one

To make it faster you could move this

(cols for cols in range(self.sheet.ncols) if cols not in self.col_indexes_to_delete)

out of the loop, and use enumerate instead of explicitly incrementing variables.

Revised code:

def write_workbook_to_file(self, dstfilename):
    self.populaterownumstodelete()
    rows = [row for row in xrange(self.sheet.nrows) if row not in self.row_nums_to_delete]
    cols = [col for col in xrange(self.sheet.ncols) if col not in self.col_indexes_to_delete]
    for row_write, row in enumerate(rows):
        for col_write, col in enumerate(cols):
            self.wb_sheet.write(row_write, col_write, self.parseandgetcellvalue(row, col))

In fact you could even move enumerate out of the loop, but I like how the code looks quite clean now.


Dijkstra's and Prim's algorithms: correctness/efficiency

I'll address some minor things (unrelated to efficiency, at least):

The comments describing the algorithm could be at the very top so that the code in between isn't missed.  Any comments describing the functions or the typedefs can stay above them.
These structs are in global scope, so they should be contained by something (such as a function) to put them into local scope, preventing unknown modifications.

For instance, DijkstraResult could probably be defined in the calling code, which I assume is main() (not shown here).  Wherever the result of dijkstra() is received, that struct should be contained there.  This will also help with keeping code lower in scope, which eases maintenance and prevents bugs associated with this.
If you still want a typedef for the std::pair, at least consider a less-obvious (and possibly more accurate) name.  The name DistAndIndex can still be read from the std::pair, so it doesn't help much.  It also doesn't save very many keystrokes, if that's even a concern.
The name infinity doesn't make sense here as you're not assigning it to anything considered infinite (it's also not a number, but a concept).  It is assigned to a max value, which is finite, also according to the documentation.

Bearing that in mind, a more appropriate name may be something like maxDistance.
Curly braces should be used here:

for (Index v = 0; v < num_vertices; ++v)
    if (v != start_vertex)
        unvisited_queue.insert(unvisited_queue.end(),
        std::make_pair(infinity, v));

From a readability standpoint, it's not entirely clear what is contained in what.  It can also hurt maintainability as adding or removing code from here can break something.

Regarding the code within the if block, the second line should be indented so that it is not read as a separate statement.

for (Index v = 0; v < num_vertices; ++v)
{
    if (v != start_vertex)
    {
        unvisited_queue.insert(unvisited_queue.end(),
            std::make_pair(infinity, v));
    }
}

uint8_t should be std::uint8_t in C++.


Big switch statement for sorting a table

As a quick improvement you should move the line ViewBag.sortableBy... out of your case statement and only set it in the default.

Secondly, I'm noticing there seem to be two different kinds of logic going on here: whether somebody's a user or a manager, etc. or whether the order is ascending or descending. It may be a lot easier to do something like this:

    Func<IQueryable<DeviceUsage>, IOrderedQueryable<DeviceUsage>> orderBy;
    IOrderedEnumerable<DeviceUsage> info;
    ViewBag.sortableBy = ascending? sortField : sortField + "desc";

    switch (sortField)
    {
        case "user":

            var deviceUsage = unitOfWork.deviceUsageRepository.Get(where, null, null, d => d.DeviceInstance, d => d.Storage, d => d.User);
            var orderFunction = s => s.User.FullName;
            ViewBag.Desc = true;
            info = ascending? deviceUsage.OrderBy(orderFunction); : deviceUsage.OrderByDescending(orderFunction);
            return PartialView(info.ToPagedList(pageNumber, 15));
        case "manufacturer":
            var orderFunction = o => o.DeviceInstance.Device.Manufacturer1.Name;
            orderBy = ascending? q => q.OrderBy(orderFunction) : q => q.OrderByDescending(orderFunction)
            break;
        .
        .
        .
        default:
            ViewBag.sortableBy="";
            orderBy=q => q.OrderBy(o => o.DeviceInstance.Device.CatalogNo);
            break;
    }

This code obviously requires you to split out whether an order is ascending or not beforehand. This can be done with string manipulation if necessary, but there is probably an easier way using code you haven't shown us.


Inserting two rows that are almost identical to each other

You should create a Stored Procedure that does this with a parameter called @firstname

it would come out way cleaner.

here is what the create would look like, I added in the @InvoiceDate parameters as well thinking that it was also something that was not static in the insert statement.

CREATE PROCEDURE Sproc_Name
    @FirstName nvarchar(50)
    ,@InvoiceDate DateTime
AS
INSERT INTO [dbo].[InvoiceItem] (invoice_item_name, amount, invoice_id) VALUES
('TUITION',
    (SELECT tuition_amount FROM [dbo].[Grade] WHERE grade_id =
    (SELECT grade_id FROM [dbo].[Student] WHERE first_name = @FirstName)),
    (SELECT invoice_id FROM [dbo].[Invoice] WHERE student_id =
    (SELECT student_id FROM [dbo].[Student] WHERE first_name = @FirstName AND invoice_date = @InvoiceDate))),
('TUITION_SERVICE_FEE',
    (SELECT tuition_amount FROM [dbo].[Grade] WHERE grade_id =
    (SELECT grade_id FROM [dbo].[Student] WHERE first_name = @FirstName)) * 0.03,
    (SELECT invoice_id FROM [dbo].[Invoice] WHERE student_id =
    (SELECT student_id FROM [dbo].[Student] WHERE first_name = @FirstName AND invoice_date = @InvoiceDate)))
GO

and then you would call it like this

EXECUTE Sproc_Name @FirstName = "Murdoch", @InvoiceDate = CONVERT(date, GETDATE())
-- CONVERT(date, GETDATE()) gives you 2018-04-05

I just used GetDate() for illustrative purposes, you can put in a string like "2018-04-05" and it should work as well.


Using semicolons is OK. The IO is imperative and side-effectfull by default, so there is nothing to do here. By saying Lwt_unix.listen sock max_pending_request you're just setting a property inside the kernel. It is not blocking, so there is no need to create a thread here.

However, you should never use ignore function, to cast away the Lwt.t type. This is an error. The returned value is a thread, and the effect of connection will not happen, until the thread is determined. So, when you call sock_recv on the sock it might fail with ENOTCONN error. In case, when you really don't need the result of the computation, from a thread, and you don't need to sync with it, you can use Lwt.ignore_result or Lwt.async function, to create a background thread, that will be handled by the system. Note, however, that any exception thrown from the ignored computation will terminate the program, that basically means, that the the computation should never throw exceptions.

And few stylistic notes:

Your indentation is incorrect. Use ocp-indent for indentation, it handles monadic operands (that shouldn't be nested).
You can deconstruct values basically in any context, where you can bind, e.g.,

let accept_connection conn =
  let fd, _ = conn in

can be written as

let accept_connection (fd,_) =

Instead of using expr >>= return value pattern, you can use the map operator >|=. For example, the following

  Lwt_unix.recv sock str 0 maxlen [] >>= fun recvlen ->
  return (String.sub str 0 recvlen)

Can be rewritten as,

  Lwt_unix.recv sock str 0 maxlen [] >|= String.sub str 0


Coding on Point interfaces/superclasses instead of implementations

Inheritance is not to be taken lightly. Have you considered composition instead?

The MedianPoint class seems to represent a point that happens to be median in some collection of points. But this depends on the context. There is nothing in this class that could prevent creating points that are not in fact at the median. You can certainly call the constructor or a factory method with parameters that don't correspond to a median point. As such, it would make more sense to use regular point objects, and distinguish them from non-median points by naming.

The methods in this class can be static methods in a PointUtils good old fashioned utility class.

The same goes for Point2DAdvanced as well. So the answer to all your questions: use Point2D.Double everywhere. The custom point classes don't really add value, and do nothing to help reducing complexity.


Recursive CTEs in SQL Server execute involving a temp table. This is probably why this tiny amount of work even takes a measurable amount of time. This should take <= 1ms.

Use a numbers table. Or, use one of the many tricks to materialize a sequence of numbers without table access such as:

SELECT Num
FROM (VALUES (1), (2), ...) x(Num)

Using Number % 15 = 0 instead of Number % 3 = 0 AND Number % 5 = 0 is less clear. It requires mathematical insight to convince anyone that this is even correct. Code should be obviously correct.

The default length of varchar is unclear. (Can you tell from memory?!) Better use nvarchar(400). By default, use Unicode characters in order to just never have certain bugs and problems.

These issues aside this query is simple. Anyone can very quickly understand it and conclude that it is correct. That's good code.


Just a small point, but in general, its best not to create anonymous functions.
So for example:

$(function(){
    // Create array to store values
    var vimeoArray = [];
    var videoContainer = $('.video-container');

    // etc...

... should be contained inside a named function, and then called.
See Beware anonymous functions.


HashMap Implementation (dictionary) in Python

Your implementation of get is wrong. The code is:

def get(self, key):
        address = self._hash(key)
        bucket = self.data[address]
        if bucket:
            while bucket[2] != None or key != bucket[0]:
                bucket = bucket[2]
            if bucket:
                return bucket[1]
        raise KeyError

The line while bucket[2] != None or key != bucket[0] says "keep traversing the link list as long as it's possible to do so, and if it's impossible, try to do it anyway if the key is wrong". Because of the boolean or, the condition bucket[2] != None means the loop will always step forward in the linked list if it's possible to do so - even if the current key is correct. On top of that, once the loop gets to the last element, if the key at that position does not match the given key, the loop will attempt to iterate once more, giving us:

TypeError                                 Traceback (most recent call last)
<ipython-input-7-a5939dc0e83e> in <module>()
----> 1 h.get("apple")

<ipython-input-1-4777e6d3506b> in get(self, key)
     31         bucket = self.data[address]
     32         if bucket:
---> 33             while bucket[2] != None or key != bucket[0]:
     34                 bucket = bucket[2]
     35             if bucket:

TypeError: 'NoneType' object is not subscriptable

The result is get fails with this error in every case except when the requested key is the last one in its slot.

The correct condition is of course while bucket[2] != None and key != bucket[0]. We then need to check afterwards that we got out of the loop because we found the right key, not because we ran out of buckets, giving us the implementation:

def get(self, key):
        address = self._hash(key)
        bucket = self.data[address]
        if bucket:
            while bucket[2] != None and key != bucket[0]:
                bucket = bucket[2]
            if bucket[0] == key:
                return bucket[1]
        raise KeyError


Your code is somewhat simplistic in that all it is doing is ensuring that the same id values appear in each document. XML is a lot more complicated than that, though, and you may have problems when:

you have multiple entries with the same id
you have entries without an id
the content in entries with the same ID in different documents is wildly different.

In terms of the algorithm, the code is clear, and so on. The string_hasher logic concerns me a bit simply because I am not that familiar with C++ (I am more familiar with XML)..... but, I have the following concerns there:

Why return int for the hash? It is specified to return size_t.
why have the struct at all?

If you convert the const char* ID to be a std::string then you can just make it a map of std::string and use the default values for the hashing and equalities in the template.

Funally, as a small optimization, you can probably save half your memory if you us a 'subtraction' type algorithm for comparing the document structures. Consider )note, I always use braces for code blocks, even if they have just one line):

for (auto& node: doca.child("site_entries").children("entry")) {
    mapa[node.child_value("id")] = node;
}

Then, in the next loop, do the following instead:

for (auto& node: docb.child("site_entries").children("entry")) {
    const char* nid = node.child_value("id");
    if (!mapa.erase(nid)) {
        mapb[nid] = node;
    }
}

Now, at this point, there is no need to perform an intersection on the maps... the values in mapa we know ae not in mapb, and visa versa. You can just print the contents of the two maps without any further processing...

Putting all these suggestions together, your code would look something like:

int main() {
    pugi::xml_document doca, docb;
    std::map<string, pugi::xml_node> mapa, mapb;

    if (!doca.load_file("a.xml") || !docb.load_file("b.xml"))
        return 1;

    for (auto& node: doca.child("site_entries").children("entry")) {
        const char* id = node.child_value("id");
        mapa[new std::string(id, strlen(id))] = node;
    }

    for (auto& node: docb.child("site_entries").children("entry"))
        const char* idcs = node.child_value("id");
        std::string id = new std::string(idcs, strlen(idcs));
        if (!mapa.erase(id)) {
            mapb[id] = node;
        }
    }

    for (auto& ea: mapa) {
        std::cout << "Removed:" << std::endl;
        ea.second.print(std::cout);
    }

    for (auto& eb: mapb) {
        std::cout << "Added:" << std::endl;
        eb.second.print(std::cout);
    }

}


JavaScript

You don't have to list down all characters. All printable characters in the ASCII range are found in 33-126. What you could do is generate a random number within this range, and convert them into characters using String.fromCharCode().

Also, it's always a good practice to separate business logic from view logic. You will want to be able to generate random passwords regardless of what your UI implementation is. In this case, I recommend putting your logic into its own function, and have the event handler call it.

Store elements you get from document.getElementById() and similar APIs to a variable, and use that variable to operate on the element. DOM operations are slow, and you will want to reduce it if possible. This example is small, and the impact is negligible, but it's a good thing to keep in mind.

CSS

For your CSS, I discourage the use of element selectors, unless you're writing a globally applied style. The same goes for the * selector. The problem with using these selectors is that they apply styles globally and will affect not just your code, but code from other developers in your team.

Elements have default styles provided by the browser, and some developers expect this when styling their CSS. If I build a perfectly fine component, but your styles globally turn the font-size to 10px, that's not a nice developer experience.

Use classes instead to target specific elements. I recommend you learn the BEM naming scheme. This allows you to namespace your CSS so that it's contained only to the component/widget you're working on. In this case, your password generator.

Never do outline: none;. This is bad for accessibility and keyboard navigation. Also, do not remove visual cues for interactive elements as this makes your app look non-responsive. For example, the native styling of a button will make it look pressed when you click. If you replace the border color, you lose this. So you should provide an :active styling and style it to give feedback to the user that a press did happen.

Also not a fan of font: large as this may be different on different browsers. Use a fixed value using the rem unit. rems are based on the font-size of the  element. By default,  is 16px which means 16px * 1rem = 16px. 1.5rem is 16px * 1.5rem = 24px, and so on. The neat thing about rem is if the user has a bumped up or bumped down font-size, the your font scales with it as well.

const getRandomCharCode = (start, end) =>
  Math.floor(start + (Math.random() * ((end + 1) - start)))

// Generate an array that's length long, and fill it with random characters
// from 33 to 126 of the ascii range.
const generatePassword = length =>
  Array(length).fill()
  .map(_ => String.fromCharCode(getRandomCharCode(33, 126)))
  .join('')

const generatorButton = document.getElementById("generator")
const generatorTextField = document.getElementById("textField")

generatorButton.addEventListener("click", () => {
  generatorTextField.value = generatePassword(16)
})
:root {
  --gray: #CBC4C4;
  --blue: #029DF1;
  --blue: #029DF1;
  --dark-blue: #007DD1;
  --white: #FFF;
}

body {
  background: var(--blue);
  font-family: sans-serif;
}

.generator {
  width: 300px;
  margin: 0 auto;
  padding: 15px;
  background: var(--gray);
  border-radius: 30px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.generator__button {
  background: var(--blue);
  color: var(--white);
  padding: 15px;
  margin: 0 0 15px;
  font-size: 1.25rem;
  cursor: pointer;
  border: 2px solid var(--blue);
}

.generator__button:active {
  background: var(--dark-blue);
}

.generator__field {
  margin: 0 0 15px;
  font-size: 1.25rem;
  border: 3px solid var(--blue);
}

.generator__field::placeholder {
  opacity: 0.6;
}

Password Generator

  <button class="generator__button" id="generator">Generate!</button>
  <input class="generator__field" id="textField" type="text" placeholder="Your password goes here...">


Finding the similarity between the two movies using Pearson correlation coefficient

So many problems!

All the outputs of mapper1 have the same key, so the first mapping step is wasted.
reducer1 generates all pairs of records, but most of these pairs will be worthless because they have different users and so will be discarded by mapper2
The similarity between movie A and movie B can end up being computed twice on half the data.

These problems are really easy to see if you work through a simple example by hand to see what your code will do.

For example, suppose the data is:

Haruko|Koyaanisqatsi|8
Natsuko|Powaqqatsi|9
Haruko|Powaqqatsi|7
Natsuko|Koyaanisqatsi|10
Natsuko|Naqoyqatsi|8
Haruko|Naqoyqatsi|6

Then mapper1 generates the following key–value pairs:

Key   Value
----  --------------------------------
None  ['Haruko', 'Koyaanisqatsi', 8]
None  ['Natsuko', 'Powaqqatsi', 9]
None  ['Haruko', 'Powaqqatsi', 7]
None  ['Natsuko', 'Koyaanisqatsi', 10]
None  ['Natsuko', 'Naqoyqatsi', 8]
None  ['Haruko', 'Naqoyqatsi', 6]

Since these all have the same key (None) all the values get collected into a single list and passed to one instance of reducer1. So the mapping step was wasted — there's no parallelism here.

Next, reducer1 generates the following key–value pairs:

Key                                Value
--------------------------------   --------------------------------
['Haruko', 'Koyaanisqatsi', 8]     ['Natsuko', 'Powaqqatsi', 9]
['Haruko', 'Koyaanisqatsi', 8]     ['Haruko', 'Powaqqatsi', 7]
['Haruko', 'Koyaanisqatsi', 8]     ['Natsuko', 'Koyaanisqatsi', 10]
['Haruko', 'Koyaanisqatsi', 8]     ['Natsuko', 'Naqoyqatsi', 8]
['Haruko', 'Koyaanisqatsi', 8]     ['Haruko', 'Naqoyqatsi', 6]
['Natsuko', 'Powaqqatsi', 9]       ['Haruko', 'Powaqqatsi', 7]
['Natsuko', 'Powaqqatsi', 9]       ['Natsuko', 'Koyaanisqatsi', 10]
['Natsuko', 'Powaqqatsi', 9]       ['Natsuko', 'Naqoyqatsi', 8]
['Natsuko', 'Powaqqatsi', 9]       ['Haruko', 'Naqoyqatsi', 6]
['Haruko', 'Powaqqatsi', 7]        ['Natsuko', 'Koyaanisqatsi', 10]
['Haruko', 'Powaqqatsi', 7]        ['Natsuko', 'Naqoyqatsi', 8]
['Haruko', 'Powaqqatsi', 7]        ['Haruko', 'Naqoyqatsi', 6]
['Natsuko', 'Koyaanisqatsi', 10]   ['Natsuko', 'Naqoyqatsi', 8]
['Natsuko', 'Koyaanisqatsi', 10]   ['Haruko', 'Naqoyqatsi', 6]
['Natsuko', 'Naqoyqatsi', 8]       ['Haruko', 'Naqoyqatsi', 6]

You can see that most of the output of this step is useless because it consists of records for different users.

Then the mapper2 step filters key–value pairs that have the same user, getting:

Key                               Value
-------------------------------   --------
['Koyaanisqatsi', 'Powaqqatsi']   [8, 7]
['Koyaanisqatsi', 'Naqoyqatsi']   [8, 6]
['Powaqqatsi', 'Koyaanisqatsi']   [9, 10]
['Powaqqatsi', 'Naqoyqatsi']      [9, 8]
['Powaqqatsi', 'Naqoyqatsi']      [7, 6]
['Koyaanisqatsi', 'Naqoyqatsi']   [10, 8]

The values are collected under the different keys and passed to four instances of reducer2:

Key                               Values
-------------------------------   -----------------
['Koyaanisqatsi', 'Powaqqatsi']   [[8, 7]]
['Koyaanisqatsi', 'Naqoyqatsi']   [[8, 6], [10, 8]]
['Powaqqatsi', 'Koyaanisqatsi']   [[9, 10]]
['Powaqqatsi', 'Naqoyqatsi']      [[9, 8], [7, 6]]

Notice that there should be only three pairs of movies, but one of the pairs appears twice.

So, how should you go about fixing the code? Your best bet, I think, is to leave the code alone for the moment, and to work out (on paper, or in a text editor) exactly what the data needs to look like after each step, using a small example (like I did above). When you're happy with the design of each step, then it should be trivial to program it.

I recommend giving the mappers and reducers names that describe what they do. This will make the code easier to understand. See the examples in the MRJob documentation which have names like mapper_get_words and reducer_count_words.


I think your code works. Another approach would be trying to connect to the database using the MongoDB Go Driver.

import (
"context"
"log"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref")

func GetClient() *mongo.Client {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.NewClient(clientOptions)
    if err != nil {
        log.Fatal(err)
    }
    err = client.Connect(context.Background())
    if err != nil {
        log.Fatal(err)
    }
    return client
}

If you can't connect (assuming you passing the right information), it means that the database is not running.

But like I said, it's just another approach.


Nested If, working like an excel SUMIF for two unequal lists summing the distance if GPS timestamp meets criteria

For me, the problem starts with the nested loops showing no specification of what is to be achieved, not even a suggested abstraction (being the body of a function given a name).

Observations:

the output does seem to depend on the order of elements of lista
(even beyond its order: lista[3][i-1])
• hope lista[2][i] >= listc[1][j] is never True for i 0
 (unless you want lista[3][-1] accessed)
the output does not seem to depend on the order of elements of listc
both lista and listc are not changed
→ the "range conditions" won't change unless at least one index changes
all of "the increments" share the condition lista[0][i] == listc[0][j]
the conditions between lista[6/7][i] and listc[1][j] are not complementary for including equality in both cases

implying red/green possibly getting incremented twice in a single iteration (not using else)

idea:

document, in the code, what is to be achieved
Python supports this with docstrings
use telling names
have a tool help you sticking to The Python Style Guide
order listc
for each i, iterate only that part of the ordered listc where lista[0][i] == listc[0][j]
ignore if lista and listc are not "rectangular":

food for thought: untested result of refactoring (get tool support for such, too)
(here extracting local variables, mostly)

list_c = sorted(listc)
for i in range(len(lista[1])):
    red = green = black = 0
    a0i = lista[0][i]
    first = bisect_left(list_c[1], a0i)
    beyond = bisect_right(list_c[1], a0i, first)
    if first < beyond:
        a2i = lista[2][i]
        a3i = lista[3][i]
        c2i = list_c[2][i]
        a8i_intended = lista[8][i] == 'intended value'
        for j in range(first, beyond):
            c1j = list_c[1][j]
            if (c1j <= a3i or c1j >= a2i):
                if lista[7][i] >= c1j and lista[6][i] <= c1j and a8i_intended:
                    red += c2i
                if a3i >= c1j and lista[7][i] <= c1j and not a8i_intended:
                    red += c2i
                if lista[6][i] >= c1j and a2i <= c1j and a8i_intended:
                    green += c2i
                if lista[7][i] >= c1j and a2i <= c1j and not a8i_intended:
                    green += c2i
                if a2i >= c1j and lista[3][i - 1] <= c1j:
                    black += c2i
    toc = timeit.default_timer()
    if i % 100 == 0:
        print('processing algorithm: {}'.format(toc - tic))
        print('we are at row {}'.format(i))
    output[0].append(lista[1][i])
    output[1].append(red)
    output[2].append(green)
    output[3].append(black)

afterthought:  it may be better to handle listc[1][j] <= lista[3][i] and lista[2][i] <= listc[1][j] separately


Create numerical-key array from existing string-key array, with a given string-key as first item

PHP has a function built in for this: array_values()

<?php

$allLanguages = [
    'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
    'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
    'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];

var_dump(array_values($allLanguages));

Outputs:

array(3) {
  [0]=>
  array(3) {
    ["locale"]=>
    string(5) "en_US"
    ["code"]=>
    string(2) "en"
    ["displayName"]=>
    string(7) "English"
  }
  [1]=>
  array(3) {
    ["locale"]=>
    string(5) "sv_SE"
    ["code"]=>
    string(2) "sv"
    ["displayName"]=>
    string(7) "Swedish"
  }
  [2]=>
  array(3) {
    ["locale"]=>
    string(5) "de_DE"
    ["code"]=>
    string(2) "de"
    ["displayName"]=>
    string(6) "German"
  }
}

Live Example

If you combine that function with this answer, you can move the desired array element to the top of the array before removing the keys:

<?php

$allLanguages = [
    'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
    'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
    'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];

$currentLanguage = 'sv';

// Move the desired language to the front of the array
$allLanguages = [$currentLanguage => $allLanguages[$currentLanguage]] + $allLanguages;

// Get a new array with just the values
$allLanguages = array_values($allLanguages);

var_dump($allLanguages);

Live Example

As a one liner:

<?php

$allLanguages = array_values([$currentLanguage => $allLanguages[$currentLanguage]] + $allLanguages);

Live Example

As a helper function:

<?php

function processLanguages($current, $languages) {
    return array_values([$current => $languages[$current]] + $languages);
}

$allLanguages = [
    'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
    'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
    'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];

var_dump(processLanguages('sv', $allLanguages));

Live Example


Minimum number of coins - (dynamic programming solution - topdown approach)

main

    if (value <= 0) {
        std::cout << value << '\n';

This seems to be an error condition.  You might consider using std::cerr instead:

        std::cerr << "Value must be positive.  You provided:  " << value << '\n';
        return EXIT_FAILURE;

This also adds an error message so that we don't have to read the code to try to figure out why it is printing a value to the screen.

The explicit return allows us to return something different for the error condition than for a successful run.  Once we have it, we can get rid of the else clause and just proceed with the rest of the block.

        if (result == 0) {

I'd tend to make this <= 0 instead.  Only positive values are correct.  In fact, I might switch the logic around the other way:

    if ( 0 < result ) {
        std::cout << "The minimum number of coins that sum to " << value << " is " << result << ".\n";
    } else {
        std::cout << "It's not possible to select coins in such a way that they sum up to " << value << ".\n";
    }

I find it easier to follow to make the failure case the else (except for an early return as used prior).  I also added more of a message in the case of success.

Naming

int coins_td(std::vector<int>& v, int n, std::set<int>& s);

The input is described as a desired sum, S, and a list of coin values, V1..VN.  So I would expect a vector named v to refer to that input value.  However, in this case, v holds an intermediate result and s holds the coin values.  The desired value is in n.  It would be reasonable to use the same names as in the problem statement.  Normally if you change them, you'd change them to be more descriptive, e.g. desired_sum and coin_values.

What is a coins_td?  I've been looking at this problem for some time now, and I still have no idea.  It's possible that I'm just being slow, but this suggests to me that it is a non-descriptive name.  Writing it out rather than abbreviating might help.

    static const int coin = 1;

While it's good that you're trying to avoid magic numbers in your code, this is a bit confusing.  What is coin and why does it equal 1?  I actually think that using the value 1 is more obvious about what is happening in this case.

Correctness

for (auto i = s.rbegin(); i != s.rend(); ++i) {
    if (n >= *i) {
        tcoins = std::min(tcoins, coin+coins_td(v, n-*i, s));
        break;
    }
}

This is not correct because it stops at the first one rather than the smallest one.  Consider a desired value of 7 with coin values of 1, 3, 4, and 5.  This code would return an answer of 3 (for 1+1+5), but the correct answer is 2 (4+3).  You should remove the break statement.

    int tcoins = coin+coins_td(v, n-*s.begin(), s);

This is incorrect because it is possible that there may be no way to reach the value n-*s.begin() in which case it will return -1, which will be smaller than any of the correct values.  Instead, set it to a number larger than the maximum possible value:

int tcoins = n + 1;

That will make the loop logic work consistently.

    if (n < 0) {
        return -2;
    }

Same thing here.  You should return a large number, not a small one.  That will also fix the problem of this being a magic number based on the fact that 1 + -2 = -1 where -1 is your magic value for an unset entry in v.

    if (n < 0) {
        return std::numeric_limits<int>::max();
    }

More info on std::numeric_limits.  Or leave this off entirely, as in the current code, this should never happen.  It only happens in the original code because of initializing tcoins without checking that its possible.

std::vector<int> coins(n+1, -1);

And again here.

    if (n == 0) {
        return 0;
    }
    if (v[n] != -1) {
        return v[n];
    }

These are redundant.  Since v[0] = 0, the second if will have the same effect as the first when n == 0.

    if ( v[n] <= n ) {
        return v[n];
    }

Or

    if ( v[n] < std::numeric_limits<int>::max() ) {
        return v[n];
    }

Either should work fine.  Note that a valid v[n] can't be greater than n because the coin values are positive integers (or at least I think that they should be).


Implementation of concurrent blocking queue for producer-consumer

Basic comments:
No point in functions that do nothing.
Also avoid void as definition for empty parameter list.
~condition_variable(void) {}

Why put a member that has no default constructor in the initializer list ( I can go either way)
concurrent_blocking_queue(size_t capacity)
    : m_capacity(capacity), m_critical_section()

But you should be consistent and thus if you do it for one then you should do it for all members.
Design:
When you call full() and empty() from within other members you already have a lock. Yet you are calling a function that will add another level of locking. And locking is usually relatively expensive.
    m_queue_full.wait(lock, [&]{ return !full(); });

    m_queue_empty.wait(lock, [&]{ return !empty(); });

Thus I would change the above to call a private version of these function that do not use locks.
    // OLD STUFF
    m_queue_full.wait(lock, [&]{ return !test_full(); });

    // OLD STUFF
    m_queue_empty.wait(lock, [&]{ return !test_empty(); });

    bool full() const
    {
      framework::scoped_lock lock(m_critical_section);
      return test_full();
    }
    bool empty() const
    {
      framework::scoped_lock lock(m_critical_section);
      return test_empty();
    }

    private:
    bool test_full()  const {STUFF}
    bool test_empty() const {STUFF}


Python has an official style-guide, PEP8. It recommends using lower_case for variables, functions and methods.
I would encourage you to use requests.get instead of urllib.request. It can take care of urlencoding the parameters for you.
You can make pull_from_arxiv a generator to save a few lines.
BeautifulSoup can be sped up using the lxml parser.
on_get can be simplified a bit using a list comprehension.
Not sure if your cleanText is really needed. Anyways, I would use str.replace instead of str.split and str.join.

import requests
from bs4 import BeautifulSoup

class ArXivPully:
    def pull_from_arxiv(self, search_query, num_results=10):
        url = "https://export.arxiv.org/api/query"
        params = {"search_query": f"all:{search_query}",
                  "start": 0,
                  "max_results": num_results}
        data = requests.get(url, params=params).text
        soup = BeautifulSoup(data, 'lxml')
        # ArXiv populates the first title value as the search query
        titles = soup.find_all('title')[1:]
        bodies = soup.find_all('summary')
        links = soup.find_all('link', title='pdf')

        for title, body, link in zip(titles, bodies, links):
            yield (link['href'],
                   title.text.strip().replace("\n", " "),
                   body.text.strip().replace("\n", " "))

    def on_get(self, req, resp):
        """Handles GET requests"""
        resp.media = [list(self.pull_from_arxiv(*item))
                      for item in req.params.items()]

Side note: Using this returns completely different results compared to entering the search string on the arxiv website search field. Not sure why. Same is true for your queries, though (the only difference is that  gets encoded as + and : as %3a by requests.get).


Matasano Cryptopals Challenge 1: convert hex to base64

Base 16 -> Base 2 -> Base 64: Cut out the middleman
You are currently converting each hex digit to 4 binary digits, then converting 6 binary digits into one Base64 digit.  Instead of doing two conversions, how about if you took each three hex digits (= 12 binary digits) and converted that into two Base64 digits?  You can do this up until the end of your hex string, where you might have 1 or 2 leftover hex digits.  You can handle those leftover digits by padding with extra zero bits and outputting extra Base64 digits, including the special '=' digit.
Bug
Your code doesn't convert zeros correctly.  The problem is here:

if (index_b64 == 0)
  buf[0] = '=';
else
  buf[0] = dec_2_base64[index_b64];

As you can see, you output '=' for each Base64 zero digit.  However, the correct digit to output is 'A'.  The special '=' digit is only used to indicate zero bits for padding.  Therefore, if I try to convert the hex string "0000", your program returns "====" when the correct answer is "AAA=".


Word ladder solution in Java using matrix

package arrays;

Wrong, unless it's your name and you've registered the top-level domain arrays. Seriously, use a personal package prefix, even for toy code.

import java.util.Hashtable;

Hashtable still exists? :D Forget it, and use HashMap (it's about the same, but not synchronized and much more in use).

Hashtable<Integer, String> dict = new Hashtable<Integer, String>();
dict.put(1, source);
dict.put(2, "hot");

That's what arrays are good for, you need no map here.

java.util.Arrays.fill(row, 99999);

Feel free to import it. Is 99999 enough? Sure, but the classical choice is Integer.MAX_VALUE. But this may lead to overflow, so sticking with a smaller constant is fine. Just declare the constant as

private final int VERY_FAR = 99999;

so that your code is not filled with essentially random numbers.

for (int i = 0; i < keySet.size() - 1; i++) {
    String mainString = dict.get(i + 1);
        for (int j = i + 2; j <= dict.size(); j++) {

You shouldn't have started the numbering with 1. Now there's i, i+1, i+2, pretty confusing. Actually, you shouldn't numbered the words at all, simply

List<String> dict = Arrays.asList(
    new String[]{"hot","dot","dog","lot","log"});

would do. Actually, you could stick with an array like

String[] dict = {"hot","dot","dog","lot","log"};

but lists are nearly always preferred.

You're computing the hamming distance of all word pairs. Google says

  The number of words in the English language is: 1,025,109.8.

which means some 1e12 pairs. You'd need a pretty smart algorithm to avoid this pairing, so let's forget it for now.

However, the problem is that you compute all the distances, while

you don't really need them
they don't really help

You don't need the distance, all you need is to know if two words are neighbors (i.e., a boolean instead of an int). But actually, the question is not "given two words, determine their distance", but "starting with dog, where can I go?". So what you need is something like

Map<String, Set<String>> neighbors;

and then a path-finding algorithm (which actually could make use of knowing the distance, but that's a different story).

if(mainString.length()!=str.length()) throw new Exception();

That's too brutal. Mathematically, returning infinity would be perfect. Returning some big number would be fine. Throwing an IllegalArgumentException or some exception of your would be fine, too.

However, it's good that you think about it. Doing nothing would be too bad (distance("hot", "hotdog") would be zero).


Check if two strings are one 'edit' apart using Python

All three cases are the same: you iterate over both string until there is a difference, you skip that difference and you check that the remaining of the strings are the same.

The only difference being how you skip the difference: you can store that in a dictionnary to also help short circuit in cases the length difference is 2 or more:

def is_one_away(first: str, other: str) -> bool:
    """Given two strings, check if they are one edit away. An edit can be any one of the following.
    1) Inserting a character
    2) Removing a character
    3) Replacing a character"""

    skip_difference = {
        -1: lambda i: (i, i+1),  # Delete
        1: lambda i: (i+1, i),  # Add
        0: lambda i: (i+1, i+1),  # Modify
    }
    try:
        skip = skip_difference[len(first) - len(other)]
    except KeyError:
        return False  # More than 2 letters of difference

    for i, (l1, l2) in enumerate(zip(first, other)):
        if l1 != l2:
            i -= 1  # Go back to the previous couple of identical letters
            break

    # At this point, either there was no differences and we exhausted one word
    # and `i` indicates the last common letter or we found a difference and
    # got back to the last common letter. Skip that common letter and handle
    # the difference properly.
    remain_first, remain_other = skip(i + 1)
    return first[remain_first:] == other[remain_other:]


C# 5 Async Await .Task.Factory.StartNew cancellation

It's better to use CancellationTokenSource(TimeSpan) constructor to set the cancellation after 5 seconds.

Also, Task.Run method is a recommended way to run compute-bound tasks (see remark here).

Other issues worth noting:

by conventions asynchronous methods should have a suffix Async
using keyword is a recommended way to correctly dispose IDisposable objects
if a task to be cancelled cannot return correct results (according to business requirements) it's recommended to throw OperationCanceledException by calling token.ThrowIfCancellationRequested() method.

private async void SaveDataAsync()
{
    if (GetActiveServiceRequest() == null)
        return;

    var cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token;
    this.ShowWizardPleaseWait("Saving data...");

    var someTask = Task.Run<bool>(() =>
    {
        // Set sleep of 7 seconds to test the 5 seconds timeout.
        System.Threading.Thread.Sleep(7000);

        cancellationToken.ThrowIfCancellationRequested();

        // if not cancelled then save data
        using (App.Data.EmployeeWCF ws = new App.Data.EmployeeWCF())
        {
            return ws.UpdateData(_employee.Data);
        }
    }, cancellationToken);

    try
    {
        this.DialogResult = await someTask
            ? DialogResult.OK
            : DialogResult.Abort;

        btnOK.Enabled = true;
        this.Close();
    }
    catch(OperationCanceledException)
    {
        MessageBox.Show("Timeout. Please try again.")
    }
    finally
    {
        this.HideWizardPleaseWait();
    }
}


The solution was to refactor the function that splits the directories and counts:

ALTER FUNCTION [dbo].[Split]
(
    @RowData nvarchar(max),
    @SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
    Id int identity(1,1),
    Data nvarchar(max)
)
AS
BEGIN
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END

This new version is a ton more efficient and returns data in about 18 seconds vs. 30+ minutes.


Your code looks good, but in my opinion AsyncTasks are good for single operations - it's not pleasant to make AsyncTask reusable. In my projects I use Ion to download some JSON data from API. This (and similar) library is prepared for making API calls, so it's easier and more ellegant to use for network requests.


About your locking strategy to create the singleton, I would use a double check to avoid too much locking:

if(x)
{
    lock(Locker)
        if(x) //again once we got the lock
            DoStuff();
}
else
{
    FooBar();
}

Like this, you will hopefully use the lock only once when you first call the instance.


First of all "bashscript" is a very poor name:

It doesn't tell what the script does. "prepare-articles-for-review.sh" would be better. Or just "prepare-articles.sh"
It is customer to use .sh extension for Bash scripts

If your typical use case is this:

for f in *.pdf; do ./bashscript.sh $f; done 2> /dev/null

Then it would be better to make the script handle multiple file parameters.

  exit $E_BADARGS

I'm not familiar with such variable. I don't think it's a standard, and it's not mentioned in my man bash. If the variable is undefined (and I think it is), then this will have the same effect as exit, which is equivalent to exit $?, where $? is the exit code of the last statement, in this case the echo on the previous line, which is most probably 0. I think you intended to exit with failure, with non-zero exit code.

  NUM=$(pdftk $1 dump_data | grep 'NumberOfPages' | awk '{split($0,a,": "); print a[2]}')

Many problems here:

You should double-quote "$1", to protect from spaces in the filename
The quoting in grep 'NumberOfPages' is redundant
Are you sure there won't be more than one lines matching "NumberOfPages"? Just to be safe, I would add exit in the Awk command
The Awk command can be written simpler as awk -v FS=": " '{print $2}'

  COMMSTR=''

You can simplify to:

  COMMSTR=

  for i in $(seq 1 $NUM);

seq is not recommended because it's not portable. You can achieve the same using native Bash functionality:

for ((i=1; i<=$NUM; i++));

  $(echo "" | ps2pdf -sPAPERSIZE=a4 - pageblanche.pdf)

The $(...) wrapping is really pointless, and awful.
No need for echo "", simply echo is exactly the same.

  $(pdftk A=$1 B=pageblanche.pdf cat $COMMSTR output 'mod_'$1)

Does this work at all? Unfortunately I don't have pdftk so cannot try.
Maybe it's fine, but it looks suspicious.

Btw, you don't need the quotes in 'mod_'$1.
And again, the $(...) wrapping is pointless.

  (pdfnup 'mod_'$1 --nup 2x1 --landscape --outfile 'print_'$1)

As earlier, you don't need those quotes,
and the (...) wrapping is pointless.

The same goes for the rest of the code.

Suggested implementation

I cannot fully test this because I don't have pdftk, but it should work:

#!/bin/bash

if [ $# = 0 ]
then
  echo "Usage: $0 file1.pdf file2.pdf ..."
  exit 1
fi

for file; do
    NUM=$(pdftk "$file" dump_data | awk -v FS=": " '/NumberOfPages/ { print $2; exit }')
    COMMSTR=

    for ((i=1; i<=$NUM; i++)); do COMMSTR="$COMMSTR A$i B1 "; done

    blank=blank.pdf
    ps2pdf -sPAPERSIZE=a4 - $blank < /dev/null
    pdftk A="$file" B=$blank cat $COMMSTR output mod_"$file"
    pdfnup mod_"$file" --nup 2x1 --landscape --outfile print_"$file"
    rm $blank && rm mod_"$file"
done


Lazy properties for the angle and length of a line segment

You can create a custom decorator to cache the values, with the help of this decorator we can also remove the unnecessary repetitive if-else or try-except checks present in each of the properties. Hence, the methods will only contain the required code.

The trick here is to use each method's name and store an additional attribute on the instance itself with _ prefixed to it. So, when we look for a value we are first going to check if it is present on that instance, if yes then return the value otherwise call the function and store the value on the instance and return it.

def cached_property(func):
    attr = '_' + func.__name__

    class Descriptor(object):
        def __get__(self, ins, type):
            if hasattr(ins, attr):
                return getattr(ins, attr)
            else:
                value = func(ins)
                setattr(ins, attr, value)
                return value
    return Descriptor()

class Test(object):

    def __init__(self, name):
        self.name = name

    @cached_property
    def find_max(self):
        print ('property max of {!s} accessed'.format(self))
        lst = range(10**5)
        return max(lst)

    @cached_property
    def find_min(self):
        print ('property min of {!s} accessed'.format(self))
        lst = range(10**5, -1, -1)
        return min(lst)

    def __str__(self):
        return self.name

if __name__ == '__main__':
    t1 = Test('t1')
    t2 = Test('t2')
    print(t1.find_max)
    print(t1.find_min)
    print(t2.find_max)
    print(t2.find_min)
    print(t1.find_max,
    t1.find_min,
    t2.find_max,
    t2.find_min)

    t1.remove_value('_find_max')
    t2.remove_value('_find_min')

    print(t1.find_max)
    print(t1.find_min)
    print(t2.find_max)
    print(t2.find_min)

Output:

property max of t1 accessed
99999
property min of t1 accessed
0
property max of t2 accessed
99999
property min of t2 accessed
0
99999 0 99999 0
property max of t1 accessed
99999
0
99999
property min of t2 accessed
0

For removing a single value I would recommend defining __delete__ method on the descriptor itself:

def cached_property(func):
    attr = '_' + func.__name__

    class Descriptor(object):
        def __get__(self, ins, type):
            if hasattr(ins, attr):
                return getattr(ins, attr)
            else:
                value = func(ins)
                setattr(ins, attr, value)
                return value

        def __delete__(self, ins):
            try:
                delattr(ins, attr)
            except AttributeError:
                pass

    return Descriptor()

Now these two calls:

t1.remove_value('_find_max')
t2.remove_value('_find_min')

Can be replaced with:

del t1.find_max
del t2.find_min


BUG: q_init() doesn't return a value.  Your compiler should have caught this; perhaps you're running without enough diagnostics turned on?  (I think this requires a diagnostic, so perhaps you need a better compiler).

BUG:  We forgot to copy the terminating null character!

for (int i = 0; i < numtest; i++) {
    q_push(nameq, test[i], strlen(test[i]));
}

That should be strlen(test[i])+1.  This was quickly revealed by Valgrind.

Although you don't ever expect malloc() to fail, I think it's better to be in the habit of coding defensively.  "Memory available" might be fragmented, and not available in big enough chunks, for instance.  It's not hard to add the necessary tests, and it makes your code more re-usable, saving you much time in the longer term.
queue_t *q_init(void)
{
    queue_t *q = malloc(sizeof *q);
    if (q) {
        q->size = 0;
        q->head = q->tail = NULL;
    }
    return q;
}

bzero() isn't standard (i.e. portable) C.  Use memset() instead.  Actually, just remove that call entirely, as it's immediately followed by a memcpy() that completely overwrites it, making the bzero() a dead store.

We don't need to cast here:

    printf("[%d] %s\n", i++, (char*)h->data);

char *hname = (char*)(q_peek(nameq)->data);

data is a pointer to void, which can be assigned to any pointer type in C:
    printf("[%d] %s\n", i++, h->data);

const char *hname = q_peek(nameq)->data;

We've included <stdint.h> but then seemingly ignored it.  I would normally use size_t for the queue length and element sizes.  I certainly wouldn't use a signed type such as int.

Naming: why freeq() and not q_free() to match the other functions?

When pushing a value, we allocate twice, but q_pop() and freeq() don't release the value storage, only the queue node.  So we have a memory leak:
==4943==
==4943== 21 bytes in 3 blocks are definitely lost in loss record 1 of 1
==4943==    at 0x480B77F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==4943==    by 0x10922B: q_push (254594.c:40)
==4943==    by 0x10942E: main (254594.c:100)

We can fix this by adding another free() before the one that releases the node object.  But a more elegant fix is to allocate just once, for the node and stored value together:
node_t *new = malloc(sizeof *new + bsize);
if (!new) {
    return ENOMEM;
}
new->next = NULL;
new->data = (char*)(new + 1);
memcpy(new->data, pdata, bsize);

We don't really need the data member any more - the value is always at the same offset from the node pointer.

The interface can be improved - users shouldn't need to know about node_t.  Instead, just return pointer to the data member.

Modified code
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

#define MAX_QSIZE   100
#define MAX_DATSIZE 128

typedef struct node {
    struct node *next;
    char data[];               /* flexible array member */
} node_t;

typedef struct queue_t {
    node_t *head;
    node_t *tail;
    size_t size;                /* element count */
} queue_t;

queue_t *q_init(void)
{
    queue_t *q = malloc(sizeof *q);
    if (q) {
        q->size = 0;
        q->head = q->tail = NULL;
    }
    return q;
}

void *q_push(queue_t *q, const void *pdata, size_t bsize)
{
    if (!q || q->size == MAX_QSIZE || bsize > MAX_DATSIZE) {
        return NULL;
    }

    node_t *new = malloc(sizeof *new + bsize);
    if (!new) {
        return NULL;
    }
    new->next = NULL;
    memcpy(&new->data, pdata, bsize);

    if (q->head) {
        q->tail->next = new;
    } else {
        q->head = new;
    }
    q->tail = new;
    q->size++;

    return &new->data;
}

const void *q_peek(queue_t *q)
{
    if (!q || !q->head) { return NULL; }
    return &q->head->data;
}

void q_pop(queue_t *q)
{
    if (!q || !q->size) { return; }
    node_t *this = q->head;
    q->head = this->next;
    free(this);
    if (!--q->size) {
        q->tail = NULL;
    }
}

void q_free(queue_t *q)
{
    if (!q) { return; }
    node_t *h = q->head;
    while (h) {
        node_t *t = h;
        h = t->next;
        free(t);
    }
    free(q);
}

static void printq(queue_t *q)
{
    int i = 0;
    for (const node_t *h = q->head;  h;  h = h->next) {
        printf("[%d] %s\n", i++, &h->data[0]);
    }
}

int main(void)
{
    const char *test[] =
    {
        "January",
        "February",
        "Random"
    };
    int numtest = sizeof test / sizeof test[0];
    queue_t *nameq = q_init();
    if (!nameq) {
        fprintf(stderr, "Failed to create queue\n");
        return EXIT_FAILURE;
    }
    for (int i = 0;  i < numtest;  i++) {
        if (!q_push(nameq, test[i], strlen(test[i]) + 1)) {
            fprintf(stderr, "Failed to create element %i\n", i);
            return EXIT_FAILURE;
        }
    }
    printq(nameq);

    q_pop(nameq);
    printq(nameq);

    const char *hname = q_peek(nameq);
    printf("head name = %s\n", hname);

    q_free(nameq);
}

This version has no errors when compiled by gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds  -Wstrict-prototypes    -Wconversion, and no issues reported by Valgrind.


Getting paginated data from ajax call and putting the data on the page

When you have an if/else statement inside an else statement and that is the only thing inside that statement, you should make the else statement into and else if instead.  So you would change this:

     if (value.image[0]) {
       image = value.image[0].name;
     } else {
       if (value.profile.gender == 'male') {
         image = 'maleDefault.png';
       } else {
         image = 'femaleDefault.jpg';
       }
     }

to this

if (value.image[0]) {
   image = value.image[0].name;
} else if (value.profile.gender == 'male') {
     image = 'maleDefault.png';
} else {
     image = 'femaleDefault.jpg';
}

All that this does is remove a level of indentation to make the code easier to read.


I would remove Pub.swap and copy its code where you need it.

That's because function calls are expensive, so better avoid calling a function at each iteration if possible.

And try to cache the expressions in loop's condition. For example,

var lengthMinusIndexOuter = length - index_outer;
for (index_inner = 0; index_inner < lengthMinusIndexOuter; index_inner++) {

instead of

for (index_inner = 0; index_inner < length - index_outer; index_inner++)


Count occurrences of a given number in a list

There are a decent number of reservations I take with this code.    Most IDEs would pick this up, but there are some nuances which you may not have fully grasped.

First, your import of java.util.Collections is superfluous and isn't used anywhere.

Next, your bound on List<Number> seems a bit...overly generic.  Since these lists support Number, they could support BigDecimal and BigInteger, or more conventionally, Float and Double - which poses problems later on.

There's no reason to declare this:

Arrays.asList(new List[]{list1, list2});

Arrays.asList takes a variadic argument, so you can simply list the arguments after it without the need for an explicit array.

Arrays.asList(list1, list2);

You should look to do this for your other lists as well.

The biggest issue as far as a broken implementation that I can see is this:

if (number == num)

This is wrong for a few reasons:

You're using == on objects.
The objects you're performing this == on are not guaranteed to unbox.
Strict equivalence in the face of floating-point values is not entirely guaranteed.

If you wanted to fix this, you'd want to fix the bound on what your method accepts to incorporate Comparable...

private static <T extends Number & Comparable<T>> void findCountOfNumber(final List<List<T>> lists, final T num)

...and simply compare the values together.

for (T number : list) {
    if (number.compareTo(num) == 0) {
        count++;
    }
}

You'll also need to ensure that the types you use for your array and the types that you use for num are homogeneous, since it really wouldn't make sense to try to find a floating-point value in a list of integers.  This is easily accomplished with the new type bounds by simply changing your lists to List<Integer>.

Lastly, let's talk about the output.  This is incredibly cryptic:

List have-1
List have-5

What you're saying is, the first list has one occurrence of the number 6, and the second list has five occurrences of the number 6.  But, what you're searching for and which list you're talking about aren't clear.

You should look to express that concisely.  Perhaps instead of using an enhanced-for you should look to use a conventional for, which states clearly what list has what occurrences of what number.


It looks good. Here are a few things you can add to it or change:

You don't have to define true/false yourself. It's unfortunate that bool is not a built-in type in C, but the Standard C Library at least provides an #include file that gives  you those definitions in a portable way. So you can #include <stdbool.h> and it will define the type bool and true/false constants.
You can combine the structure declaration + typedef into the same declaration:

typedef struct stk
{
    char content[MAXSTACKLENGTH];
    int top;
} stack;

Most C programs you'll find use this more compact notation of typedef struct.
You can simplify statements like this and others:

int isEmpty(stack *s)
{
    if (size(s) <= -1)
    {
        return true;
    }
    else if (size(s) > -1)
    {
        return false;
    }
}

By simply returning the condition:

int isEmpty(stack *s)
{
    return size(s) <= -1;
}

The result of a comparison is always a boolean, so it can be returned directly if the function also returns true/false. This is another pattern that you will see used a lot. It makes code more concise.
Comparing against true/false in a conditional is not very usual:

if (isFull(s) == true)

You gave good descriptive names to your functions, so you can just test them like this:

if (isFull(s)) { ...

And to test if not full, the more usual way is to apply the ! (logical not) operator:

if (!isFull(s)) { ... // Reads "if not isFull"

size() currently return -1 for an empty stack. That's unusual. It doesn't make sense for a size to be negative. I'd expect an empty stack to have size 0. You should change that.
I suggest having a init_stack() function that sets the expected initial invariants when a new stack is declared. Better than having to remember to manually set top to -1, for example.
Since you already have a custom pause() function, you don't have to use system("pause"). The latter is non-portable and not recommended for use in real-life programs due to security risk it might incur. Best if you avoid it.
A minor nitpick, you're mixing different styles of curly brace positioning. Some are on the same line as the parent conditional, some are on their own line. This creates a break in your style, which is a little annoying. It would be nice if you kept them consistent, independent of which style you decide for.


Describing algorithms to implement higher level operations in terms of the lower level operations

Your code solves the problem in a desired way, it is concise which is good.
Some comments
Your design limits the shifting to k > len(D) - 1, if it is your intention, then it is perfect otherwise this could be solved by doing
def shift_left(D, k):
    k = k % len(D) #the modulus makes k to be in the positive integer domain
    if (k < 1):
        return
    x = D.delete_first()
    D.insert_last(x)
    #it could be done with a for and saves recursively comparing k each time
    shift_left(D, k-1)

An alternative
def shift_left(D, k):
    k = k % len(D)
    if (k < 1):
        return
    #avoids recursion, which saves recursive calls and passing parameters
    #(could be done using a while)
    for i in range(0,k)
        x = D.delete_first()
        D.insert_last(x)


Find the Nth number divisible by only 2,3,5, or 7

No, not \$O(n)\$. Not even close. I'll get back to this later though. First, the code:

It's a little difficult to tell what your loop logic is. curr is getting incremented each time, but i isn't... whereas typically we'd use i as a loop index. I'd propose using i as the loop index, and then keeping a humble number count named count (or num_humbles or something):

count = 0
dp = {}
for i in itertools.count(start=1):
    if ishumble(i, dp):
        dp[i] = True
        count += 1
        if count == n:
            return i
    else:
        dp[i] = False

You are also correct in this comment:

  #i don't believe this ever get's called

That'll happen in the case where x is divisible by one of our primes, but we somehow haven't seen x/p yet. But we are iterating in order, so you're guaranteed that y in dp for all y<x. So you can simplify that block to:

if x % i == 0:
    return dp[x/i]

Though if you reread that statement again, you'll see that there's no need for dp to be a dictionary. You can just make it a list.

Split things up

Rather than having one function that does both generate the humble numbers and return the nth one, you can split them up. Have one function that generates the humble numbers:

def humble_numbers():
    dp = {}
    for i in itertools.count(start=1):
        if ishumble(i, dp):
            dp[i] = True
            yield i
        else:
            dp[i] = False

And another function that returns the nth one. Actually, that part is a snap using the nth recipe:

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

So the solution becomes:

def humbleNumber(n):
    return nth(humble_numbers(), n)

Note that now that we separated out the original idea into "generate the numbers" and "get the nth one" as separate, we can just play around with the generating functions.

Runtime

Your algorithm is deceptively easy to analyse. For each number we check, we do at most 4 modulo operations, at most 1 dictionary lookup, and 1 dictionary insertion. That's all reasonable and obviously super cheap. But, are we doing one cheap operation per \$n\$? NO, we're not, but it's easy to fall into that trap. Because we're not iterating up to \$n\$... we're iterating up to the \$n\$th humble number. Thus, the runtime is really \$O(H(n))\$.

And humble numbers get really sparse. Here's an unnecessarily prettified table for what the growth rate looks like:

+---------+---------------------------------------+
|       N |                                  H(N) |
+---------+---------------------------------------+
|      10 |                                    12 |
|     100 |                                   480 |
|    1000 |                                387072 |
|   10000 |                           63248102400 |
|  100000 |                 123098144531250000000 |
| 1000000 | 4157518627998641643389868083057746290 |
+---------+---------------------------------------+

Your runtime complexity grows commensurately with the second column. According to Wikipedia, that means your algorithm is something on the order of \$O(e^{\sqrt[4]{n}})\$?

A better approach

Rather than checking every individual number (which leads to terrible runtime complexity), we can build numbers up from the bottom. The numbers we want are basically \$2^a3^b5^c7^d\$, for all \$a,b,c,d\$. Of course, that's difficult to iterate over (how do you know which one to do next?). But a different way of writing that is each humble number is either 2x, 3x, 5x, or 7x some previous humble number. And that's easy to iterate over:

def humble_numbers2():
    primes = (2,3,5,7)
    result = [1]
    yield 1

    def make_multiple(_p):
        return (_p * result[i] for i in itertools.count())

    iters = map(make_multiple, primes)
    merged = heapq.merge(*iters)
    for k,_ in itertools.groupby(merged):
        result.append(k)
        yield k

The key is heapq.merge, which joins sorted iterables (which we know ours are). Basically we're on the fly creating the lists: 2*humble numbers, 3*humble numbers, 5*humble numbers, and 7*humble numbers - which are all humble numbers - and then using itertools.groupby to drop the duplicates (because, e.g., 14 is both 2x the 7th humble number and 7x the 2nd humble number)

This approach is \$O(n)\$. We are only performing constant operations to determine the next humble number. Which, when in doubt, we can always very by timing how long it takes to find the Nth humble number 10 times (after making the modifications I proposed to your solution):

+------+----------------+-----------------+
|  N   | humble_numbers | humble_numbers2 |
+------+----------------+-----------------+
| 100  |         0.003s |          0.002s |
| 1000 |         2.890s |          0.028s |
| 2000 |        53.332s |          0.059s |
| 3000 |       384.589s |          0.091s |
| 4000 |      1730.465s |          0.123s | #ok, I only ran this one once
+------+----------------+-----------------+


You're reimplementing std::forward_list, so a good place to start would be the API documentation for forward_list. That'll show you a lot of deficiencies in your current approach:

Naming. For example, getSize() should be size(), so that you can write generic algorithms that work with your class in addition to std::list, std::vector, etc (all of which have a size() method).
Encapsulation. You provide a public member function getHead() that returns a raw pointer to an internal node. What do you expect the user to be able to do with a node<T>*?
Composability. Your remove member function causes an exit(-1) on failure. It would be much much better to have remove throw an exception, and then allow the caller to catch and handle the exception — possibly with an exit, but possibly in some other way.
Support common C++ idioms. Your list class doesn't provide begin() and end(), so it's not iterable; e.g. I can't say for (auto&& element : myList) { std::cout << element; }. If you provide iteration, then I can write this loop, so I won't need your printList member function anymore.

Finally, one more naming nit: As a member function, printList could just be named print. myList.print() is slightly better (shorter and less repetitive) than myList.printList(). And again it enables generic programming:

// You could overload this printTwice function for each container type:

void printTwice(const List& l)
{
    l.printList();
    l.printList();
}

void printTwice(const Vector& l)
{
    l.printVector();
    l.printVector();
}

// ^ But yuck. Prefer genericity:

template<class Container>
void printTwice(const Container& c)
{
    c.print();
    c.print();
}

// ^ In fact, prefer to use non-member functions for anything that
// doesn't require special access to the innards of the class:

template<class Container>
void printTwice(const Container& c)
{
    print(c);
    print(c);
}

// ^ In fact, prefer to spell the verb "print" in the standard way[*]:

template<class Container>
void printTwice(const Container& c)
{
    std::cout << c << std::endl;
    std::cout << c << std::endl;
}

[* – unless you're really concerned about efficiency, in which case you should probably stay away from iostreams; but at that point you're not doing generic programming anymore anyway]


Maximum Subarray Problem - Recursive O(n log n) algorithm

Your program fails when all of the members of an array are negative, it simply returns 0 instead of the maximum negative number.

Recursion here is slowing you down.  Using Kadane's algorithm, we can make the time complexity linear, or O(n) .

#include<stdio.h>

#define max(a, b) (((a) > (b)) ? (a) : (b))

int maxSubArraySum(int array[], int size)
{
    int maxSoFar = array[0];
    int currentMax = array[0];

    for (int i = 1; i < size; i++)
    {
        currentMax = max(array[i], currentMax + array[i]);
        maxSoFar = max(maxSoFar, currentMax);
    }
    return maxSoFar;
}

int main()
{
    int array[] =  {-2, -3, 4, -1, -2, 1, 5, -3};
    int len = sizeof(array) / sizeof(array[0]);
    int maxSum = maxSubArraySum(array, len);
    printf("Maximum contiguous sum is %d\n", maxSum);
    return 0;
}


Mastermind game - Evaluating the guess in Ruby

There are definitely some inefficiencies in your code, but it's a good start. The first thing I'd say is that there is no reason for you to create variables black and white in calculate_feedback. All they hold is the names of the colors and it's no more efficient. The issue is that you seemed to have started to code this before fully thinking of the implementation.

From a basic perspective, here are the rules:

Guesser has 12 guesses
Each guess gets compared to the correct code
If the guess is the correct color in the correct position a black peg comes up in that spot, otherwise a white peg comes up (at most once per color).

So, let's break this down into an algorithm.

Create secret code and create counter for user's guesses
Get user's guess
Compare user's guess to secret code.
Go back to step 2 until the user either guessed the code correctly or has hit 12 guesses.

The biggest part of the algorithm to focus on is part 3, which is comparing the user's guess to the secret code. Luckily, because you're using Ruby, you have some great resources for this. Let's break this step down into two parts.

First: Find out how many black pegs should be there. This can be done with one line in ruby.

black = code.zip(guess).count{|i| i.inject(:eql?)}

This might look a bit confusing but what it does is it takes the secret code (represented by the array code and zips it into an array with guess. So for the above example code.zip(guess) would give us [["Red", "Blue"], ["Blue", "Green"], ["Green", "Red"], ["Red", "Red"]]. Then count{|i| i.inject(:eql?)} means count all of the arrays within the array where the elements are equal. This is only true for ["Red", "Red"] and so it gives us a count of 1 which is the number of black pegs to be returned. Now, we have to talk about the white pegs. Because there can be at most 1 per color guessed, we should consider eliminating duplicates in the array of the user's guess. Thus, we can do this

white = guess.uniq.count{|i| code.include?(i)}

So great, with only two lines we have the number of white and black pegs we need for each turn. Now let's put this all together into a concise program.

def provide_feedback(code, guess)
  black = code.zip(guess).count{|i| i.inject(:eql?)}
  white = guess.uniq.count{|i| code.include?(i)}
  result = Array.new(4, '')
  black.times { result.unshift('black').pop }
  white.times { result.unshift('white').pop }
  result
end

Of course, this is still a bit more verbose than I'd prefer. Why not tighten it up a bit more by removing the black and white variables all together.

def provide_feedback(code, guess)
  result = Array.new(4, '')
  code.zip(guess).each{|i| result.unshift('black').pop if i.inject(:eql?)}
  guess.uniq.each{|i| result.unshift('white').pop if code.include?(i) && result[-1] == ''}
  result
end

That's the most concise and Ruby way I could think of.


Suggestions for improving error handling

You could combine the try-catch blocks:

int response = -1;  //some error code
var logging = false;
try
{
    //some code to prepare the operation - may cause exceptions
    response = DoOperation();
    //some code to clean after the operation - may cause exceptions

    logging = true;
    if (response > 0) //non-error code
        //log event in database
    else
        //log event error in database
}
catch
{
    if(logging)
    //logging error handling
    else
    //error handling
}

Even better, if you know the logging could throw a particular type of exception that the other operations will not, then catch just that exception and handle it as a logging exception, and let all others trickle down to a general catch:

int response = -1;  //some error code

try
{
    //some code to prepare the operation - may cause exceptions
    response = DoOperation();
    //some code to clean after the operation - may cause exceptions

    if (response > 0) //non-error code
        //log event in database
    else
        //log event error in database
}
catch(LoggingSpecificException)
{
    //logging error handling
}
catch
{
    //error handling
}

As far as the general strategy, it doesn't look too bad. Getting a "return status code" from a method is more than a little outdated (try-throw-catch was designed to replace this style of method return), but there's a lot of "legacy code" out there, and some built-in methods still return values that indicate failure. The return value of DoOperation(), if any, should be its conceptual "product"; data produced by DoOperation as the result of a computation. If DoOperation, conceptually, doesn't make any such calculation, it would be better conceptually (and thus from an understandability standpoint) to return void and instead throw exceptions on errors. However, you'd have to throw and catch multiple types of exceptions, or keep track of multiple states instead of just "logging".

Also, I don't know if you simply omitted it for the operation, but I would think that knowledge of exactly what went wrong might be good to know, and so any general catch should be catch(Exception ex) or similar to allow use of exception data when handling the error.


Hide content unless an array contains at least one non-empty string

As @tokland pointed out, your current code has one too many loops really.

As for checking if all the strings are empty, you have some options.

1) The any? method accepts a block, so you can test if any of the elements in an array match a certain condition. In your case, you could do

@hints.any? { |string| string.present? }

since present? checks if a string is non-empty. But you can also shorten that to just

@hints.any?(&:present)

With that you could do something like

<% if @hints.any?(&:present) %>

Please observe the following hints:

    <% @hints.each do |hint| %>
        <% unless hint.empty? %>

<%= hint %>

        <% end %>
    <% end %>

<% end %>

2) Alternatively, and I'd say nicer, you can filter the array beforehand, to simply not include blank strings using select or, conversely, reject.

@hints = some_hints.reject(&:blank?)   # reject blank strings
# or...
@hints = some_hints.select(&:present?) # keep non-blank strings

This should happen in the controller when you first set @ hints (or even earlier - don't know where the hints come from, but there's little need to keep empty strings around if you don't have to, so either strip them out early, or just avoid adding them to begin with).

With a "clean" @hints array you can do this:

<% unless @hints.empty? %>

Please observe the following hints:

    <% @hints.each do |hint| %>

<%= hint %>

    <% end %>

<% end %>


Setting unique code to model before creating (ruby/rails)

It's the same in Ruby as in other languages where you want a loop to always run at least once: Move the condition to the end.

begin
  code = ...
end until(Table.find_by(code: code).nil?)

Ruby's syntax is a little odd ("end until"), but it's the same as a do { ... } while() in C-like languages.

However, the overall system you're using is really strange. If all you want is a unique number for the new table, just use id. That's what it's for. It's set automatically at the database layer, so there'll be no collisions.

If you just want 4 random digits, don't make a random float (which may not have enough digits, e.g. 0.0), convert it to a string and pull out a section. Just call rand(1000..9999).to_s. Or rand(10_000).to_s.rjust(4, '0') to get a number padded with leading zeros if necessary.

However, anything you do in the application layer is vulnerable to race conditions! Between the time you check if a code already exists in the database, and the time you save your record, that code may have been added, giving you duplicates. E.g. 2 threads both check for the code 1234 at the same time, and both see that it's not in the database, so both then save records with that same code. Oops.

The proper way to avoid such things is to add a uniqueness constraint in the database itself, and rescue the resulting RecordNotUnique error that'll get raised.

Here's an article discussing other ways to generate unique tokens, and a follow-up on how to handle collisions.

However: just use id. Or find a gem that generates unique tokens for you.


"Rock, Paper, Scissors" game - follow-up

Firstly, this is some nice clean code. Well done.

The changes I'd make:

win_msg and lose_msg can instead be global constant strings.
You should pick a preferred string delimiter and stick to using just that one. I prefer '.
I would make a function clear_console as the code is rather strange. And will ease use if you need it again.
game_outcome can be simplified by using a dictionary to store what beats what.

This also means you can expand to RPSLS with ease.
show_results can be changed to use a dictionary too.
update_scores can be changed in one of two ways:

Add a dictionary that converts from outcome to the index.
Change scores to a dictionary.

And so you can get the following code:

import os
from random import choice

MESSAGES = {
    'Win': '{player} beats {computer}. You won!',
    'Lose': '{computer} beats {player}. You lost!',
    'Draw': 'Draw. Nobody wins or losses.'
}

BEATS = {
    'Rock': 'Scissors',
    'Paper': 'Rock',
    'Scissors': 'Paper'
}

def player_choice():
    while True:
        print('Rock, paper or scissors?')
        choice = input('>').capitalize()
        if choice in ('Rock', 'Paper', 'Scissors'):
            return choice

def play_again():
    while True:
        print('\nDo you want to play again?')
        print('(Y)es')
        print('(N)o')
        ans = input('> ').lower()
        if ans == 'y':
            return True
        elif ans == 'n':
            return False

def computer_choice():
    return choice(('Rock', 'Paper', 'Scissors'))

def clear_console():
    os.system('cls' if os.name == 'nt' else 'clear')

def game_outcome(player, computer):
    if player == computer:
        return 'Draw'

    if BEATS[player] == computer:
        return 'Win'
    else:
        return 'Lose'

def rock_paper_scissors(scores):
    clear_console()
    print(f'Wins: {scores["Win"]}\nLosses: {scores["Lose"]}\nDraws: {scores["Draw"]}')
    player = player_choice()
    computer = computer_choice()
    outcome = game_outcome(player, computer)
    print(MESSAGES[outcome].format(player=player, computer=computer))
    scores[outcome] += 1
    return new_scores

def main():
    scores = {
        'Win': 0,
        'Lose': 0,
        'Draw': 0
    }
    still_playing = True
    while still_playing:
        scores = rock_paper_scissors(scores)
        still_playing = play_again()

if __name__ == '__main__':
    main()

From here you can look into using enum to remove the strings from your code. This is good because it's easy to make a typo in a string, say I use 'rock' rather than 'Rock'. It also means that if you do make a typo then you'll be able to see where it was made when you reach that code. However with a string it'll move the error to a later part of the code and make debugging horrible.

Here is an example of how you can use them:

from enum import Enum

class Score(Enum):
    WIN = 'Win'
    LOSE = 'Lose'
    DRAW = 'Draw'

MESSAGES = {
    Score.WIN: '{player} beats {computer}. You won!',
    Score.LOSE: '{computer} beats {player}. You lost!',
    Score.DRAW: 'Draw. Nobody wins or losses.'
}