Here are some observations that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Don't use system("cls")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a separate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  For example, if your terminal supports ANSI Escape sequences, you could use this:

void cls()
{
    std::cout << "\x1b[2J";
}

Isolate platform-specific code

In this code, there are several things that are DOS/Windows only including #include <conio.h> and the getch() and kbhit() functions within that, and also system("cls"); that I've already mentioned.  Your code runs successfully on Linux if I supply those missing functions, but it would be nice if there were an #ifdef WINDOWS already in the code so that one could recompile without having to alter the source code.

Eliminate "magic numbers"

There are a few numbers in the code, such as 8 and 14 that have a specific meaning in their particular context.  By using named constants such as BACKSPACE or COLUMN_WIDTH, the program becomes easier to read and maintain.

Don't abuse the ternary operator

The code currently includes this inscrutable bit of code:

key.size() ? key.pop_back(): 0;

This is not valid C++ even if your compiler accepts it.  The problem is that the two options must both evaluate to the same type.  std::string.pop_back() returns void but 0 is an int.  The fix is to simply use an if instead which makes the code both valid and readable C++:

if (key.size()) {
    key.pop_back();
}

Be careful with references

The for loop starts with this:

map<string,int>::iterator &tter = contacts.begin();

That's not right because tter should be an iterator, not a reference to an iterator.  It should instead be written as:

map<string,int>::iterator tter = contacts.begin();

Or even better, you could use the next suggestion if your compiler is compliant.

Use "range-for" to simplify your code

Instead of using an explicit iterator, your for loop could use "range-for":

for (const auto &person : contacts)

Simplify I/O by defining a function

This code outputs each contact when needed but it does so using a relatively long formatting string.  I'd suggest creating a function do that so that that formatting code is isolated to one place.  In particular, I'd create an operator<< function like so:

std::ostream& operator<<(std::ostream &out, const std::pair<const std::string, int> &p) {
    return out
        << std::setw(4) << "Name : " << std::setw(10) << std::left << p.first
        << std::setw(14) << ", Number : " << std::setw(10) << p.second;
}

Note, too, that I've used simply p.first rather than p.first.c_str().

Use an initializer list to initialize static data

Use of an initializer list simplifies construction of data structures:

std::map<std::string,int> contacts{
    {"Pradip",999092456},
    {"Raju",999092457},
    {"Praveed",999092445},
    {"Prasad",999092415},
    {"Asim",999092785},
    {"Massi",999092215}
};

Avoid continue and break

Looping constructs in code are generally considerably easier to read and understand if they do not use continue or break.  In this case, it's very easy to avoid them:

for (const auto &person : contacts) {
    if (string::npos != person.first.find(key)) {
        std::cout << person << std::endl;
    }
}

Think about the user

There is no obvious way to gracefully exit the program.  I'd suggest using a switch to control when the program is done.  Something like this:

bool done=false;
while (!done)
{
    if ( kbhit() ){

        key_code = getch();
        cls();
        switch (key_code) {
            case BACKSPACE:
                if (key.size()) {
                    key.pop_back();
                }
                break;
            case CTRL_C:
                done = true;
                break;
            default:
                key+=key_code;
        }
        std::cout << "Contacts with : " << key << std::endl;
        // etc.

Omit return 0

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.


Is building a test instance from a mix of both mock and real objects OK?

You would be testing the MapMarker more in isolation if you would inject only mocks.

Isolation is important for two things:

stability of test results
more explicit and direct feedback

If a bug would be introduced in the RailsMarker, this test would also fail, causing it to be less stable.
In case of this bug, there would by multiple test failures (also for RailsMarker and possibly other tests that use this class) making it harder to find the bug.

In general I would use mocks for any dependant object that has more logic than just getters and setters. That being said, it looks like the RailsMarker might qualify.


I felt that this code would be good as a jQuery plugin, so I went ahead and altered your code until I was satisfied. I left in some comments that are applicable to your code, but I would encourage someone else (and may do it myself still, I don't know yet) to give an actual review.

(function ($, console) {
    'use strict';

    var defaultOptions = {
        //markup is what will be used to create the font sizer widget; you can do this a million better ways, but I felt this was easy to understand.
        //I'd consider enhancing it to take a jQuery object or a function that returns a string or a jQuery object, but all of that would make this more complex.
        //At the very least, this way makes for progressive enhancement as opposed to breakage when JS is disabled.
        markup: 'Font size: Smaller | Bigger Current Font Size:',
        markupClickFilter: 'a', //if you change the markup of this widget to something where you use elements other than A tags for buttons, you may wish to change this
        affects: null, //required: this is a jQuery object representing the elements that this widget affects
        size: null, //override for initial size of affected elements
        increment: 4
    };
    $.fn.fontSizer = function (options) {
        //initialize / preconditions
        var opts = $.extend({}, defaultOptions, options),
            $currentSize, //$ for element in markup if it exists
            sizeChange = function () {}; //noop to avoid null check when using this, meh...
        if (!opts.affects || !opts.affects.length) {
            //should always UI test in a modern browser that provides console
            console.error('failed to initialize fontSizer: must provide affects property');
            return this; //jQuery plugins are expected to follow this convention
        }

        //widget setup
        this.html(opts.markup); //again, this setup functionality could be done better in many ways
        $currentSize = this.find('[data-id=current_size]'); //for example to not use magic strings like this
        if ($currentSize.length) {
            sizeChange = function () { //this could also be a trigger
                $currentSize.html(opts.affects.css('font-size'));
            };
        }

        //set initial size and update $currentSize
        if (opts.size !== null) {
            opts.affects.css({
                'font-size': opts.size
            });
        }
        sizeChange();

        return this.on('click', opts.markupClickFilter, function (e) {
            var size = parseFloat(opts.affects.css('font-size')), //parseFloat is more correct than parseInt
                make = $(this).data('make'),
                fixed = parseFloat(make); //minor enhancement: allow fixed sizing

            if (make === 'smaller') { //preference: always use ===
                size -= opts.increment; //a new variable was unnecessary, if you feel you must, you should at least declare it at the top of the function
            } else if (make === 'bigger') {
                size += opts.increment;
            } else if (fixed !== 0) {
                size = make; //using make instead of fixed here allows things like make === '1.5em'
            }

            //update size (and set $currentSize)
            opts.affects.css({
                'font-size': size
            });
            sizeChange();

            //this prevents the annoying hashchange and extra history step that isn't doing anything useful
            e.preventDefault();
        });
    };
}(jQuery, console || {error: function () {}}));

Usage:

(function ($) {
    'use strict';
    $(function () {
        $('#sizer').fontSizer({
            affects: $('p.basic')
        });
        $('#sizer2').fontSizer({
            affects: $('p.custom'),
            markup: 'Font size: Small | Large | XL Current Font Size:'
        });
    });
}(jQuery));

Html for usage example:

Enable Javascript for a font resizer

some text

some text

some text

Enable Javascript for a font resizer

some text

some text

some text

JsFiddle


Check style found code duplication in factory

I've just got idea how solution should be implemented. It seems stayed clear for me when question was published (this implementation is not best, but idea is pretty good for me). My abstract factory should be replaced with strategy pattern who returns builder that I need.

public EventDto mapToDto(Event googleEvent, EventDto baseEventDto) {
    return getStrategy(googleEvent.getStatus()).mapToDto(googleEvent, baseEventDto);
}

public EventDto mapToDto(Event googleEvent, String originalCalendarId) {
    return getStrategy(googleEvent.getStatus()).mapToDto(googleEvent, originalCalendarId);
}

public GoogleEventDtoMapperAbstract getMappingStrategy(String status) {
    switch (status) {
        case GoogleEventStatus.CANCELLED:
            return googleEventDtoMapperCanceled;
        case GoogleEventStatus.CONFIRMED:
            // will be implemented by needs
        case GoogleEventStatus.TENTATIVE:
            // will be implemented by needs
        default:
            return googleEventDtoMapperConfirmed;
    }
}


Higher-order Prolog predicates combine/3 and reduce/3

This has gone unanswered for a long time, and even though I haven't done any serious prolog coding, I would like to come with some general remarks which might be useful for you.

Style wise I would add spaces after commas, to increase readability. Other than that it looks clean enough, but some comments on what the different parts does, wouldn't hurt.

But my main point in this review is this: Device code structures after you have a need for it, and don't create structure first and then ask for a need of it.

You've done it the other way around, which is kind of strange, but could be a good learning experience for you. Could it be useful for some cases? Who knows. In general, most likely not, as normally you have the use case first, and then code a solution to it.


Update table with greatest value from itself and another table

I would update with a join to a derived table. This would likely perform better than your subselect as well as be more intuitive to read (in my opinion, at least).

UPDATE a
INNER JOIN (
    SELECT
        id,
        MAX(`date`) AS max_date
    FROM b
    GROUP BY id
) AS max_dates
    ON a.id = max_dates.id
SET a.maximum = GREATEST(a.`date`, max_dates.max_date)


Find the duplicate in a sorted array In less-than O(n)

Don't use (left + right) / 2 in a binary search, as (left + right) is vulnerable to overflow.  Java's binary search implementation had such a bug for some time.

Instead, do

int middle = left + (right - left) / 2;

Alternatively, you could do

int middle = (int)(unchecked((uint)left + (uint)right) >> 1);


Displaying available destinations using Angular.JS

Translations are UI logic, a different representation of the same data. They should stay on the template. On the other hand, country and city logic go in the controller. They should only be aware of the data, but not how it is represented.

The answer to this is to use Angular filters, and a separate service/factory/provider to hold the current language. The controller exposes the data to the UI, but the data is language-neutral.

Given that this is so similar, here's another answer where I explained how to use Angular filters with translations: https://codereview.stackexchange.com/a/116063/11919


Minesweeper, python Tkinter, Checking close by tiles

Okay. Improved my answer. You can call this code as normal with self.__total(x,y). In my own test, it showed the exact same results as your code has.

def __total(self, x, y, count=0, old=False):
    if (not count and old) or not old:
        for x_index in range(-1+x, 2+x):
            for y_index in range(-1+y, 2+y):
                if 0 <= x_index < self.__Size and 0 <= y_index < self.__Size:
                    if old:
                        self.__push(x_index, y_index)
                    else:
                        count += self.__buttons[y_index][x_index].mine

    if old:
        return count
    return self.__total(x,y, count, True)

Another solution would be using Numpy:

import numpy as np

def __total(self, x,y):
    count = np.sum( self.__buttons[ x-1 if x>0 else 0:x+2, y-1 if y>0 else 0:y+2 ] )
    if not count:
        for x_offset in range(-1, 2):
            x_index = x + x_offset
            for y_offset in range(-1, 2):
                y_index = y + y_offset
                if 0 <= x_index < self.__Size and 0 <= y_index < self.__Size:
                    self.__push(x_index, y_index)
    return count

The problem with this code is, that you can't use array class, but would need a Numpy array of all mines in a extra variable. But it would speed up your calculations just because of the nature of Numpy.


Since you have PDO::PARAM_STR everywhere, you can just pass all the parameters to the execute:

$query = $db->getConnection()->prepare("INSERT INTO `users` (first_name, last_name, email, username, password, unique_id, date_joined) VALUES(:fname, :lname, :email, :username, :pass, :uniqueid, :date_joined)");
$query->execute(array(
    ':fname' => $first_name,
    ':lname' => $last_name,
    ':email' => $email,
    ':username' => $username,
    ':pass' => $passHash,
    ':uniqueid' => $emailHash,
    ':date_joined' => $date
));

  What about if one wasn't a string? Would the "best" practice be to follow this and just bindParam as usual on the variable that isn't PDO::PARAM_STR?

You can have a custom version of the execute which could work like this:

myCustomExecute($query, array(
    ':fname' => [$first_name, PDO::PARAM_STR]
    ':lname' => [$last_name, PDO::PARAM_STR],
    ':age' => [$age, PDO::PARAM_INT]
));

Inside the myCustomExecute you just loop over the array and do bindValue for each array item (note, it is better to use bindValue instead of bindParam, see for example, this).

But I feel like you want something bigger than this to avoid writing a boilerplate code. In this case your are looking for an ORM.

The practical solution is to search for existing solution and choose the one you like.

Less practical way would be to write something simple around PDO.

The final syntax would be something like this:

// ActiveRecord pattern
$model = new Person();
$person->first_name = 'John';
$person->age = 22;
$person->save();

// OR, in the case of DataMapper pattern, you have separate
// object for your model and another one which handles
// the database operation
$table = new PersonMapper();
$person = new Person();
$person->first_name = 'John';
$person->age = 22;
$table->save($person);

The record class or mapper class usually have some kind of metadata (you define it manually or they get this metadata directly from the database), so they know the type of each filed, as well as some other limitations (like uniqueness checks). And usually you are able to specify some own validation rules to check before the data is saved to the database.

This removes a lot of the boiler plate, because with plain PDO you have to repeat your fields for times - twice in the SQL (first_name -> :fname) and then twice in the bindValue or execute calls.


MySQL data fetching without page refresh

Personally, I hate having a setInterval in JS code, especially to
 fetch live updates. I hate it even more when it is used for hitting
 the server for a database read/write operation, irrespective the size
 of project.

The code you have is quite good, considering that it was your first time. There are quite a few suggestions though. Read on:

Instead of having 2 separate files to fetch data of attendance = 0 and attendance = 1, use a single file with a parameter passed via a GET or POST request.
Instead of dumping the entire data as HTML, I'd suggest outputting the results as JSON so that it might be of use to other applications, without having to resort to HTML parsers. This helps if you think/plan on providing an API for other users to develop on.
Since the data for room_data gets updated with an underlying python application, you can modify it to write the output to a static JSON file and hit this JSON content instead of executing a MySQL query every second. This will help as the browser will get a 304 response status from the server if the JSON was not updated since last fetch. Caching FTW ^_^
Put the external script/stylesheets in head.
Since all you need for the MySQL to return is concatenated name string, do so in MySQL itself:

SELECT CONCAT(firstname, ' ', lastname) AS 'name'
FROM room_Data
WHERE attendance = :something

Do not use h4 tags for list items.

If you follow (1) above, you won't need the (3). I strongly recommend using (3) though.


EF entity, extended with partial classes for actions

The best aspect of your approach is that you keep the autogenerated class as is, which makes it more readable and clean, and keeps your extra code safe from deletion if you modify the database schema.

You can extend this class with a partial class to add a constructor setting automatic properties like Date to DateTime.UtcNow.

The static classes Do, Get, and Set are not using any of the members of the entity class, so I see no reason of being part of an entity unless you mean to add some Fluent Interface to your code. But this has pros and cons, and these static classes are not the best way to do so. Also, would you do that for all entities in your model? too much repetition, complexity, error prone, and dependency on context.

In Entity Framework, the best practices is to keep the entities unaware of their context or repository for a variety of reasons like single responsibility, and testabilty.

By using EF designer, you automatically generate code like below, which you can modify or extend

public class BloggingContext : ApplicationDbContext
{
    public System.Data.Entity.DbSet<PCServer.Data.Post> Posts { get; set; }
    public System.Data.Entity.DbSet<PCServer.Data.User> Users { get; set; }
    ...
}

You can create multiple context classes, but usually I did not see any benefit of doing so. One context for all your entities is fine.

The context owns the repository here as Posts property here is your repository, no need to create a new one. And DbSet has out-of-the-box all the repository methods you need like Create, Add, Find, and Remove.

Setting entity properties and calling repository methods would then be simple and called directly as you did in the last lines in your question, like below:

BloggingContext context = new BloggingContext();

context.Posts.Add(new Post { Title = "Hi!" });
List<Post> posts = await context.Posts.ToListAsync();

Post post = context.Posts.First(p => p.Id == 100); // or context.Posts.Find(100) if Post.Id is marked as [Key]
post.Title = "Changing title!";

And after all:

await context.SaveChangesAsync();


Always do a clearInterval() before doing a new setInterval() on the same variable. Doesn't matter if it has been cleared or not.

e.g.

clearInterval(revealImage);
revealTimer = setInterval(revealImage,100);

You're code has a bug where the revealTimer is being reset before being cleared.

Why do you need to reset it?

function init() {
    ctx = document.getElementById("canvas").getContext("2d");
    setInterval(switchImage,3000);
    setInterval(revealImage,100);
}

Should work just as well.


A recursive sort and filter for a nested object

If you have control over the format of the object you're filtering and sorting, then you should definitely consider reformatting it into something more palatable.
Using localeCompare() to sort Date objects seems funky. You can do something like this:

return new Date(tempB).getTime() - new Date(tempA).getTime()

If you don't know how deep the object is nested, then recursion is a pretty solid way to go. If you want to try a more hackish solution, you could also use JSON.stringify() and regex to extract the date fields from deeply nested objects (not suggested). Please provide more examples of valid objects to sort though, your code seems like it would break on certain instances.


Yes, this is the way to do error handling in Go. By design, you can't let exceptions propagate to the callers "silently", you have to consider what makes sense at each step. I found that on large-scale projects, it makes it significantly easier to predict and test the error handling behavior of your code. It also forces you to put the error handling first, which (imho) results in more readable, less nested code.
Truly global variables don't exist in Go — if a package foo exports a variable Bar, other packages will have to call foo.Bar to access it. That being said, it pretty much never makes sense to do that. In the example you gave, cmd.go and project.go are in the same package, and all package-level variables are shared, so identifiers conflict. If you want this variable to be shared, it's more readable to put all functions that use it in the same file.
When you want to mock some of your functions, it's the sign that there should probably be an associated interface. You can then "mock" an interface easily, by re-implementing your interface in your tests and making it do whatever you want. I find this more readable and idiomatic than using complex frameworks.

Note on the last question: if your interface has many functions:

type Fooer interface {
    Foo1(string) (string, error)
    Foo2(int) (string, int)
    ...
    // Foo42() []byte
}

and you only want to test Foo1, you can use the following syntax

type fakeFooer struct {
    Fooer
    ret string
}

func (fi fakeFooer) Foo1(_ string) (string, error) {
     return fi.ret, nil
}

and not implement any other functions. fakeFooer{"bar"} will "implement" Fooer, calling Foo1 will do what you expect, and trying to call Foo2 on it will panic (nil pointer dereference).


Speed/optimization

Unfortunately, istream_buf_iterators aren't a particularly fast way to read the entirety of a file into a string. One simple way to improve speed is to use the istream's read instead. To do that, you can replace this:

string inputString{istreambuf_iterator<char>(is), istreambuf_iterator<char>()};

...with something like this:

string inputString;

is.seekg(0, std::ios::end);
size_t length = is.tellg();
inputString.resize(length);
is.seekg(0, std::ios::beg);
is.read(&inputString[0], length);

At least in my testing, this reduces the time from around 800 ms to around 600 ms for a pair of test files I threw together (about 6.5 megabytes, mostly from project Gutenberg, with one chapter of one book edited out of one of the files).

If you're running this under Linux, you'll probably also benefit from adding a line like this toward the beginning of main:

std::ios::sync_with_stdio(false);

On Windows this has essentially no effect, but on Linux it can make quite a bit of difference.

Correctness

Command line arguments

You declare the command line arguments as argc/argv like usual, but attempt to refer to two arguments as arg[1] and arg[2] (should be argv instead of arg).

You should also check that argc > 2 before attempting to use argv[2].

EOF detection

This code:

while (stream) {
    stream >> token;
    result[token] += 1;
}

...is broken. It doesn't detect the end of the file correctly. For accurate EOF detection, consider using something like this instead:

while (stream >> token)
    ++result[token];

Translation

I'm pretty sure you transposed these two strings:

string const g_source      = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890";
string const g_destination = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

I'm pretty sure the intent was the either upper-case or lower-case input would be mapped to lower-case output. As it stands, you seem to be trying to map lower-case input to both lower-case and upper-case output.

Style

Simplicity

Although it probably won't make a huge difference in speed, I'd rather use a simple std::array for the translation table, and just fill in the result character for every possible input:

static const size = std::numeric_limits<unsigned char>::max();

std::array<char, size> translation_table;

for (int i=0; i<size; i++)
   if (std::isalpha(i))
       translation_table[i] = std::tolower(i);
   else if (std::isdigit(i))
       translation_table[i] = i;
   else
       translation_table[i] = ' ';

Then translating a character becomes utterly trivial:

transform(
    rawString.begin(),
    rawString.end(),
    rawString.begin(),
    [](unsigned char c) { return translation_table[c]; });

Also note the change to unsigned char, so if we have an input that's negative when viewed as a char, we don't try to index outside the table.

Encapsulation

Taking the next step from the last point, I'd rather hide the implementation of the translation a bit more by wrapping it up into a class. For example, something like this might be usable:

class formatter {
    class xlat_table {
        static const int table_size = std::numeric_limits<unsigned char>::max();
        std::array<char, table_size> table;
    public:
        xlat_table() {
            for (int i = 0; i < table_size; i++)
                if (std::isalpha(i))
                    table[i] = std::tolower(i);
                else if (std::isdigit(i))
                    table[i] = i;
                else table[i] = ' ';
        }
        char operator[](size_t n) { return table[n]; }
    };

    static xlat_table table;

public:

    void operator()(std::string &rawString) {
        transform(
            rawString.begin(),
            rawString.end(),
            rawString.begin(),
            [this](unsigned char c) { return table[c]; });
    }
};

formatter::xlat_table formatter::table;

This creates the xlat_table as a static member of formatter, so we can create formatter objects freely, without initializing a new translation table every time.

Conclusion

This should improve speed at least a little bit, but this will probably be I/O bound in most cases, so just translating the code to C++ isn't necessarily going to give any huge speed improvement. On the other hand, if you have something that can do really fast I/O (e.g., a reasonably high-end SSD) you might be more likely to see substantial gains.

My final code putting the pieces together looks like this:

#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <unordered_map>
#include <chrono>
#include <array>
#include <cctype>

using namespace std;

bool containsKey(unordered_map<string, int> const &wordMap, string const &key)
{
    return wordMap.find(key) != wordMap.end();
}

class formatter {
    class xlat_table {
        static const int table_size = std::numeric_limits<unsigned char>::max();
        std::array<char, table_size> table;
    public:
        xlat_table() {
            for (int i = 0; i < table_size; i++)
                if (std::isalpha(i))
                    table[i] = std::tolower(i);
                else if (std::isdigit(i))
                    table[i] = i;
                else table[i] = ' ';
        }
        char operator[](size_t n) { return table[n]; }
    };

    static xlat_table table;

public:

    void operator()(std::string &rawString) {
        transform(
            rawString.begin(),
            rawString.end(),
            rawString.begin(),
            [this](unsigned char c) { return table[c]; });
    }
};

formatter::xlat_table formatter::table;

unordered_map<string, int> wordOccurences(istream &is)
{
    unordered_map<string, int> result;

    string inputString;

    is.seekg(0, std::ios::end);
    size_t length = is.tellg();
    inputString.resize(length);
    is.seekg(0, std::ios::beg);
    is.read(&inputString[0], length);

    formatter()(inputString);

    istringstream stream(inputString);
    string token;

    while (stream >> token) {
        ++result[token];
    }

    return result;
}

double documentMagnitude(unordered_map<string, int> const &document)
{
    double magnitude = 0.0;

    for (auto const &word : document) {
        magnitude += double(word.second * word.second);
    }

    return sqrt(magnitude);
}

double cos_dist(std::istream &file1, std::istream &file2) {
    using namespace std::chrono;

    auto begin = high_resolution_clock::now();

    unordered_map<string, int> document1 = wordOccurences(file1);
    unordered_map<string, int> document2 = wordOccurences(file2);

    double magnitude1 = documentMagnitude(document1);
    double magnitude2 = documentMagnitude(document2);

    double innerProduct = 0.0;

    for (auto const &word : document2) {
        if (containsKey(document1, word.first)) {
            innerProduct += double(word.second * document1[word.first]);
        }
    }

    double cosAngle = innerProduct / magnitude1 / magnitude2;

    auto end = high_resolution_clock::now();

    std::cout << "Time: " << duration_cast<milliseconds>(end - begin).count() << " ms\n";

    return cosAngle;
}

int main(int argc, char *argv[])
{
    std::ios::sync_with_stdio(false);

    string filename1 = argv[1];
    string filename2 = argv[2];

    ifstream file1(filename1);
    ifstream file2(filename2);

    double cosAngle = cos_dist(file1, file2);

    cout << "Distance: " << acos(cosAngle) << '\n';
}

With all the pieces put together, this reduces the time (on my test files) from about 800 milliseconds to about 450-475 milliseconds. I haven't done any detailed profiling to find what parts of the code are consuming that time, so there might be some fairly obvious places to get more improvement.


Scraping names and images of products from a webpage

Code Style
There is a number of common PEP8 style guide violations which you may address:

imports to be properly organized
respect blank lines usage: remove the one in the urls list definition, use two newlines between the function definitions, remove extra blank lines at the beginning of the function bodies
inline comments should be 2 spaces from the right, there should be a single space after the # character
usage of spaces around the operators and in expressions and statements

Other Improvements
You can move some of your if checks from Python to CSS selectors. For instance:
[img_link.attrib['src'] for img_link in item.cssselect(".overview a img") if '.jpeg' in img_link.attrib['src']]

could be replaced with:
[img_link.attrib['src'] for img_link in item.cssselect(".overview a img[src$=jpeg]")]

When image_links is truthy, you send it to saving_images() function, which means that image_link is not used and you just wasted time defining it. How about refactoring it to be:
image_links = [img_link.attrib['src'] for img_link in item.cssselect(".overview a img[src$=jpeg]")]
if image_links:
    saving_images(cat, name, image_links)
else:  # single image
    image_link = [img.attrib['src'] for img in item.cssselect(".picture a img")]
    saving_images(cat, name, image_link)


A bunch of random observations

avoid def as a non-top level form e.g. in (def the-guess (atom "")), prefer let bindings
there's no need to use a ref for the connection, as it never changes after creation. Prefer a simple map, which also enables you to use plain destructuring instead of using let to extract its components:

(defn conn-handler [{:keys [in out] :as conn}] ...)
...
conn {:in in :out out}]
(println "Client connected")
(doto (Thread. #(conn-handler conn)) (.start))

instead of using interop to interact with the in/out streams you could use a more idiomatic (binding [*out* out *in* in] (println ...) (read-line))
you loop over the conn, but you always recur over the very same object. You can remove conn from the loop/recur forms
if you follow the binding approach as described above, but within the anonymous function that you use to initialize the thread, you could completely remove the conn name from the whole code:

(defn conn-handler [] (println "...") ...)

(doto (Thread. #(binding [*in* in *out* out] (conn-handler)) (.start))

there's no need to use an atom for the guess, just use plain recursion:

(loop [the-guess ""]
...
  (recur g))

The following code contains the revised conn-handler and -main functions, including all the suggestions above, plus the cosmetic change of using the threading macro -> instead of the doto form, which seems a bit clearer:

(defn conn-handler []
  (println "Welcome to this simple hangman game.")
  (loop [the-guess ""]
    (println (str "Guess the word: " (guess the-guess word)))
    (flush)
    (let [g (str the-guess (readLine))
          res (guess g word)]
      (if (= word res)
        (do
          (println res)
          (println "Correct!")
          (flush))
        (do
          (recur g))))))

(defn -main [& args]
  (println "Server running…")
  (with-open [server (listen 3456)]
    (while true
      (let [client (.accept server)
            in (BufferedReader.(InputStreamReader.(.getInputStream client)))
            out (PrintWriter. (.getOutputStream client))]
        (println "Client connected")
        (-> #(binding [*in*  in
                       *out* out]
               conn-handler)
            (Thread.)
            (.start))))))


Generically Cache Database Lookups By Id

Cache semantic

A cache is something optional. You should be able to disable the cache by always returning "null" in the lookup method without worrying that your algorithm fails. It only should be slower. I don't think your implementation will pass this check. The cache should NOT retreive new data on its own.

Cache scope

A cache has a well defined lookup and object scope. Your implementation has a cached object lookup scope of "method" and a cached object usage scope that is somehow greater. Both should fall into the same scope to satisfy symmetry. Without knowing your UseCase-Layer you most of the time want to have all objects needed available in the UseCase. Refreshing your UseCase will often cause refreshing your cache because you want to process a UseCase on the latest data.

One other thing: Your Child-Objects may not the only Objects that have references on the Parent-Object. Those objects you would have to handle with seperate caches so you cannot take advantage of the already loaded instances. Consider caching on In thhe Business-Layer if you have no Persistence Mapping Tool (JPA). Otherwise you should make use of Entity-Caches.

Lambda expressions

My opinion on lambda expressions is ambivalent. Of course you can have very compact and technically expressive statements. But technically expressive statements may not be semantically expressive. Often they hide bad design. You can compress code that it looks good in one method that would normally be splitted into two methods. But the only reason you may have need for two methods was bad design.

I consider usage of lambda expression rarely: Listener-notifications, mapping JPA objects to Busines-Objects or massive parallel number calculations. I never use lambda expressions to make code "shorter".

Approach

Simplify the data retreiving process:

public class ChildService {

    public List<Child> getChildren() {

        List<Child> result = new ArrayList<>();

        try (ResultSet resultSet = connection.createStatement().executeQuery("")) {

            while (resultSet.next()) {
                result.add(new ChildProxy(resultSet.getLong("parent_id")));
            }

        } catch (SQLException e) {
            ...
        }

        return result;
    }

}

Passing the parent id to the constructor of the Child object and resolving the parent through the DAO:

public class Child {

    protected long parentId;

    public Child(long parentId) {
        this.parentId = parentId;
    }

    public Parent getParent() {
        return new ParentDaoImpl().getById(this.parentId);
    }

}

Derive a Caching enabled ChildProxy from the "Child" and intercept the getParent()-method to check for a cached Parent-Object. If you would have a JPA-Layer you may not need this because OR-Mapper often have their own caching mechanisms that are sufficient for most usecases.

public class ChildProxy extends Child {

    public ChildProxy(long parentId) {
        super(parentId);
    }

    Parent getParent() {

        Parent parent = Cache.lookup(Parent.class, this.parentId);

        if (parent == null) {
            parent = super.getParent();
            Cache.put(this.parentId, parent);
        }

        return parent;
    }

}

Formulating your UseCase:

public class UseCase {

    private final List<Child> children = new ArrayList<>();

    public void init() {
        ...
        this.children.addAll(new ChildService().getChildren());
        ...
    }

    public void reset() {
        Cache.clear();
        this.children.clear();
        init();
    }

    ...

}

Maybe you have to think a little bit more about the caching scope. It's not that easy because most developers tend to simply store expensive objects near their first occurance.

My advice is: NEVER cache at the first place. ALWAYS formulate your statements as they are NOT EXPENSIVE. After that you can go on with an optimization...

... that should be transparent to the existing implementation

... and has a well defined scope to match the use case requirements


Object-oriented Tamagotchi-like program with a GUI

Your code is built by using classes and consequently by creating objects(instances) of those classes. In addition you are also utilizing the concept of inheritance to associate multiple classes to each other.
So yes, your code is OOP.


Compare two map objects and show relative information Java 8

Code review in order of appearance:

public static String getAllExecTimes(MasterVO masterVO, boolean displayAll) {

Static methods should be avoided if you may expect them to contain state, such as hints on how to format the class. Why not create an object that performs the formatting?

Boolean parameters are not a good idea. They are pretty unreadable. But in this case it is worse, as the displayAll doesn't give any hint to a user what actually is displayed. What about an enum, e.g. enum Display {DISPLAY_MAP_C_ONLY, DISPLAY_MAPS_A_B_C;}?

Map<Integer, DurationVo> durationMap = null;
Map<Integer, Integer> orderMap = null;
List<Integer> keys = null;

Never ever instantiate variables before they are needed in Java, and don't use the same variable reference for two different maps (A and C). This makes for very error prone code, especially if you are starting to assign null to the variables, which should almost never be necessary. Create separate methods when code is very similar or when variable names are starting to clash.

Why is there a MasterVO and a DurationVo? It's fine to choose all uppercase or camelcase, but please do so consistently.

durationMap = masterVO.getMapA();
orderMap = masterVO.getOrderMap();

You know, a map is a mapping from a set of keys to values. However, you only have duration and order, and it isn't even clear which one is key and what is the value.

keys = new ArrayList<>(orderMap.keySet());
keys.sort(new CustomComparator());

Now this is just not right. If you put the keys into a TreeSet instead then they will be ordered during insertion. Even better, why not use a TreeMap and sort then when you setup the Map?

if (null != target) {

First of all, you should just write this as if (target != null) {; this is a well known anti-pattern for Java, it's just not needed and it hurts readability. It is item #1: "Yoda Conditions" for the "new jargon" article at coding horror.

The bigger question is why you would allow null values in such a map in the first place. Even without knowing the design, I have the feeling that null values should be avoidable in this case, especially since keys without values are simply skipped in the resulting string.

if (null != masterVO.getMapB()) {

Now whole maps seem to be missing in action. Use Optional<...Map> instead.

private static final class CustomComparator implements Comparator<Integer> {

    public int compare(Integer first, Integer second) {
        return first.compareTo(second);
    }
}

Seriously, how does this custom comparator differ from normal integer ordering? Do you need to specify a specific comparator in that case? And why is it called CustomComperator? That name doesn't explain how it is custom.


Sum-based sliding rate limiting with Redis and Lua

There might be one correctness issue here:

If a customer makes just one purchase all week with the transaction amount exceeding the cap, do you still want to throttle the transaction? Just wanted to bring that up in case you missed this corner case.

Since you talk about performance, you will want to consider which of the two are important to you:

request latency - each request completing within a fixed time
throughput - number of requests served from the cache in a time period.

You can have higher latency, but still maintain a high throughput as long as the transactions are not serialized.

One suggestion I had that might help with both is that you can pull the following:

--[[
Cleaning up old entries up to @minSecond (in our example,
minSecond = Now (Epoch time in secs) - 604800 (nb of secs in a week)):
--]]
redis.call('ZREMRANGEBYSCORE', userKey, '-inf', @minSecond)

outside into a separate call or issue it lazily.

Lazy techniques can be:

GC once every 'N' calls,
run GC as a cron / batch job once a day for all customers
Do GC only if the size of the sorted set is greater than a fixed threshold

This will make individual transactions potentially faster at the expense of a larger memory footprint.

This might have some performance implication, so I would do some benchmarking just for that one call.

If you're okay with being slightly inaccurate about the cap on spending per customer, there are two things you can potentially play with:

Use Exponential Moving Averages. This will allow you to not do a range query on the sorted set, and instead do a constant time query. There's plenty of resources on this topic on the inter-webs.
Use daily aggregates. Whenever you get a query, you will need to look-up exactly 7 key-value pairs. Ofcourse this will not work if you want precision.

Otherwise, your existing approach will get the job done.


Module to support autocomplete for movie tags

.attr('value') is bad. Always. You should use .val() instead.
var i; can go into the callback function instead of whatever scope you are in at the very beginning.


First index of number in the arithmetic progression (which is multiple of prime)

Time elapsed is almost all in overhead
I'm not sure you can do any better than what you've done.  I tested your program and it ran extremely fast.  In fact, I determined that most of the time was probably being spent bringing up the JVM.  I ran your program with varying test inputs (up to 100000 test case input), and also ran your program without computing the result (just reading the input and outputting one number per test case).  The timings showed that most of the time was being spent just bringing up the JVM (or some other Java related overhead):
100000 test case (times are in seconds)
0.14: bringing up the JVM
0.19: parsing the input and generating output
0.12: calculating the answer
0.45: total time

100 test case
0.14: bringing up the JVM
0.02: parsing the input and generating output
0.01: calculating the answer
0.17: total time

So I believe that your actual algorithm runs for about 0.01 seconds out of 0.17 total time.
C program was faster (less overhead?)
I converted your program to C and tested it to see if it would run any faster.  It did run faster, probably because of the lack of overhead:
100000 test case (C program)
0.29: total time

100 test case (C program)
0.01: total time

Here is the C program, just to show you that it is exactly the same as your java program:
#include <stdio.h>

static long long getPowerValue(long long base, long long primeNo);

int main(void)
{
    int noOfTestCaseT = 0;
    long long firstElement, commonDifference, primeNo;

    scanf("%d", &noOfTestCaseT);

    while (noOfTestCaseT != 0){
        noOfTestCaseT--;
        scanf("%lld %lld %lld", &firstElement, &commonDifference, &primeNo);
        firstElement %= primeNo;
        commonDifference %= primeNo;
        if(commonDifference == 0) puts("-1\n");
        else if (firstElement == 0) puts("0\n");
        else {
            long long inverseMod = getPowerValue(commonDifference, primeNo);
            int result = (int) ((inverseMod * (primeNo-firstElement))%primeNo);
            printf("%d\n", result);
        }
    }
    return 0;
}

static long long getPowerValue(long long base, long long primeNo)
{
    long long exp = primeNo -2;
    long long powerResult = 1;
    while (exp > 0){
        if ((exp & 1) == 1) powerResult = (powerResult * base) % primeNo;
        base = (base * base) % primeNo;
        exp = exp >> 1 ;
    }
    return powerResult;
}

A slightly faster inverse mod function
From wikipedia, I copied this algorithm for finding the inverse mod.  Supposedly, it is slightly faster than the algorithm you are using.  Using the 100000 test case input, I found that it was a little bit faster, but not by much (maybe 10% faster).  Here is the function (it replaces your getPowerValue function):
private static long inverse(long a, long n)
{
    long t    = 0;
    long newt = 1;
    long r    = n;
    long newr = a;

    while (newr != 0) {
        long quotient = r / newr;
        long tmp;

        tmp  = newt;
        newt = t - quotient * newt;
        t    = tmp;

        tmp  = newr;
        newr = r - quotient * newr;
        r    = tmp;
    }
    if (t < 0)
        t += n;
    return t;
}


static functions

Both of your getNameNumber and printNumber should be made static, because I doubt that you plan to export them.

Simpler functions

printf("Enter the amount of people: ");

can simply use puts, which doesn't have any formatting code in it. You use puts below, so this would also help with consistency.

Stack allocation

person people[size];

is not available in all versions of C, since size is not a constant. For best portability you'd want to malloc this, or perhaps alloca if you feel strongly that the memory should be in the stack and not on the heap.

const

printNumber's array arguments should be const, since you don't mutate them.

Your questions

  To avoid a very long name that exceeds char's size, I limit it to 255. Is there a better way?

For your use case, not really. A fixed array is the most appropriate. However, your code is vulnerable to overflows. You should be putting a width in your format specifier.

  To avoid buffer, I included a space before % sign and not use getchar(). Is there a better way?

I'm not sure which usage of % you're referring to, but they all look fairly sane, so no; there's not really a better way.


The amount of comments you use is more distracting than helpful. Good comments are those that explain what the overall logic of a block of code is, they don’t explain each line of code. Code is supposed to be self-documenting, that is, the code should explain itself. You accomplish this by using good variable names and good function names, which explain their own meaning.

Also, you need to use the functionality in the standard library. For example, to test whether a character is a normal letter or not, use isalpha rather than the four comparisons you’re using (against 'a', 'z', etc.)


Elegant wp-query markup for repetitive post-type category loops

First off, Wordpress is an awful platform when it comes to separation of business logic from display logic.  If you expect to continue working in it, you can expect to continue to feel the pain that you are feeling.

The thing that concerns me the most about your comments, is that you say you cut/paste this code repeatedly.  That immediately screamw out for putting this code into a widget or function so that it is reusable.  Think if you had a function like:

display_category_list($post_type, $category_name, $show_posts = -1)
{
    // your code
}

This would simplify your main pages to have calls like:

display_category_list('project', 'documentary');
display_category_list('foo', 'bar');

So that could solve the copy/paste problem.

Now let's get into the problem of display templating.  Even working with basic PHP output mechanisms, you can greatly clean up your code, simply by separating out the logic from the HTML in a more reasonable fashion.  You could structure your code like this:

display_category_list($post_type, $category_name, $show_posts = -1)
{
    // Define main section template.
    // You could just as easily include this to keep template
    // in a separate file
    $section_template = <<<'EOT'

{{list}}

EOT;

    // list template, again could be included
    $list_template = <<<'EOT'

{{category_name}}

    {{items}}

EOT;

    // item template
    $item_template = <<<'EOT'

{{title}}

EOT;

    // Actual function logic
    $args = array(
        'post_type' => $post_type,
        'showposts' => $show_posts,
        'category_name' => $category_name,
    );
    $query = new WP_Query($args);

    // put default "no post" content here (this could come from template as well)
    $list_content = '';
    if($query->have_posts()) {
        $list_content = str_replace('{{category_name}}', $category_name, $list_template);
        $items = '';
        while ($project_query->have_posts()) {
            $post->the_post();
            $link = the_permalink();
            $poster = (get_field('project_poster')) ?
                $image['sizes']['medium'] : 'https://placehold.it/1600x900';
            $poster_alt_text = get_the_title();
            $title = the_field('project_title');
            $template_data = array(
                '{{link}}' => $link,
                '{{poster}}' => $poster,
                '{{poster_alt_text}}' => $poster_alt_text,
                '{{title}}' => $title
            );
            $items .= str_replace(
                array_keys($template_data),
                array_values($template_data),
                $item_template
            );
            $items .= PHP_EOL;
        }
        $list_content = str_replace('{{items}}', $items, $list_content);
    }
    echo str_replace('{{list}}', $list_content, $section_template);
    wp_reset_postdata();
}

Note how I have moved the HTML into templates defined within nowdoc blocks.  This approach can allow you to easily pull this content out of the function itself into separate template files that are easier to manage.  For example, the function could be rewritten with template-to-variable assignments like this:

$section_template = include('/path/to/section_template.php');

With the template file looking like:

return <<<'EOT'

{{list}}

EOT;

This means you could even go so far as to pass template file paths into the function on the fly to switch out templates to be used (or you could have some config settings for template paths that the function uses).  This could totally get you out of having any HTML within the function itself.


Google Foobar Level 3 - Lucky Triples (Find the Access Codes)

Optimizing this algorithm

                if(l[i3]%l[i2]==0 && l[i2]%l[i1]==0 && !log.contains(new ArrayList<>(Arrays.asList(l[i1], l[i2], l[i3])))){

I have two problems with this section of code.

First, in l[i2]%l[i1]==0, this will return the same result regardless of the value of i3.  So why is it inside the i3 loop?  It could be before that loop and skip the loop if not true.

Second, you use List.contains with an arbitrarily long list.  The longer the list, the slower that method is.  Consider using a HashSet instead.  Then the speed remains constant relative to the size.

With these two changes:

    public static int answer(int[] l) {
        Set<List<Integer>> log = new HashSet<>();
        for (int i1 = 0; i1 < l.length; i1++) {
            for (int i2 = i1 + 1; i2 < l.length; i2++) {
                if (l[i2] % l[i1] != 0) {
                    continue;
                }

                for (int i3 = i2 + 1; i3 < l.length; i3++) {
                    if ((l[i3] % l[i2] == 0)) {
                        log.add(Arrays.asList(l[i1], l[i2], l[i3]));
                    }
                }
            }
        }

        return log.size();
    }

Now you only check the third element if the first two elements are divisible.

And now, instead of using List.contains, you simply rely on the uniqueness of elements of a Set.

I also switched to use the interfaces as the types for log rather than the implementation.  This allows me to skip the new ArrayList operations altogether.

I'm not crazy about the variable names either, but I didn't try to change them.

Assumptions

Both your original and this variant assume that the list is sorted in ascending order.

Custom datatype

This solution probably takes longer for small result sets, because HashSet is often higher overhead than List.  You may be able to reduce the overhead by declaring your own type and providing an optimized hashCode method for it.  Or the compiler may have already optimized it.  You'll have to benchmark to be sure.


I'm wondering about the value of BDD constructs.

The value / non-value should become more apparent after implementing more and more test cases. Keep going!

  Thoughts? Criticisms?

Be careful with test cases that use things defined outside of them, for example:

def test_PV(self):
    self.assertEqual(pv(self.data1, self.rate1), self.cf1.PV)

Ideally, it's best when a test cases is self-contained,
and includes everything inside about the test,
including the expected value and the input values.
Here, we have to trust that self.data1, self.rate1, self.cf1.PV are all correctly setup to make this work, and that they were not tampered with afterwards.
That's a bit too much trust required.

The test case would be easier to understand and safer from side effects if you included all values needed to validate the calculation:

def test_PV(self):
    data = (-10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    rate = .05
    cf = CashFlow(data, rate)
    self.assertEqual(pv(data, rate), cf.PV)

This looks a lot less magical,
as the connection between data, rate and cf is clearly visible.
Although the definition of pv is still outside,
I could live with that,
because I see the intuition that whatever is pv,
the goal of this test is to verify that CashFlow(data, rate).PV behaves like pv(data, rate).

Note also that in this implementation you can no for a fact that no other test case could mess with data, rate and cf.
You cannot mistakenly add another test case with side effects to break this one.
I know such mistakes seem unlikely to do (why would anyone ever edit cf1?),
but minimizing potential side-effecty things is a good practice in general,
and especially critical in unit tests.

I understand you did this because you anticipate many tests based on this data:

@classmethod
    cls.data1 = [-10,1,2,3,4,5,6,7,8,9,10]
    cls.rate1 = .05
    cls.cf1 = CashFlow(cls.data1, rate=cls.rate1)

However, right now you only have a single test,
which makes this look a bit speculative.
Especially because you named the variables data1, rate1, cf1,
suggesting that there might be soon data2, rate2, and so on.

You might rightfully ask,
should you duplicate the initial data in multiple test cases,
violating the DRY principle?
The DRY principle is less important in unit tests than in implementation.
It's ok to duplicate, but it can become inconvenient if the specification changes later.
But the thing is, if the specification changes that's usually a big problem anyway,
with no good solution.
So yes, it's ok to duplicate the initial data.
If later you realize that a different initial data would be more interesting to test,
don't edit the previous values,
but add new tests with the new initial data.
If the previous values should still pass,
there's no need to remove them, who knows, they might still catch some bugs.

  Is it bad to calculate both sides of the test?

It's not great, but it can be acceptable.
You might want to add some test cases to verify pv itself so you can trust it.

  Should I use assertAlmostEqual() since there could be rounding errors?

When, you experience rounding errors, then you should add.
If you don't have rounding errors in your current test case,
then no need to speculate.
If you do have rounding errors already, then it's not even a choice.


NewSequentialId - pure net core 2.2 implementation of sql server function

You want to reduce both computation time and memory allocation. Memory allocation itself takes time, so that's a good place to start -- try to find all the places where you're allocating memory and see if they can be avoided.

ArrayPool<byte>.Shared.Rent(16); can avoid an allocation, but not always. Can we do better? Turns out we can; we'll see how.

BitConverter.GetBytes(ticksDiff) makes an allocation. ticksDiff is just an integer so it's quite easy to extract its binary representation using binary operators. We'll see how we can use this later on.

But first:

Profiling

Profilers are your friend! You should always start the optimization journey by asking "Where are the bottlenecks?", which you can promptly answer with cold hard data from a profiling tool.

As suspected, dotTrace reports that the ArrayPool<byte>.Shared.Rent/Return and BitConverter.GetBytes(ticksDiff) calls take a significant chunk (~21%) of the total running time. Let's get rid of those.

Guid constructor

You're using the Guid constructor that takes a byte[], which has perpetuated an implementation that necessarily allocates a byte array somewhere. You can get clever with this to allocate on the stack instead of the heap (Span<byte> with stackalloc) or to minimize the number of allocations that actually need to happen (ThreadLocal<byte[]>), but the best solution is to not allocate anything at all. To accomplish this, you can use one of the other Guid constructors that takes its values directly, instead of taking a byte array.

There's a constructor overload that takes an int, two shorts, and eight bytes. You can pack these values directly (see the reference source for endianness on the int and shorts):

int a = ticksDiffBytes[7] | (ticksDiffBytes[6] << 8) | (ticksDiffBytes[5] << 16) | (ticksDiffBytes[4] << 24);
short b = (short)(ticksDiffBytes[3] | (ticksDiffBytes[2] << 8));
short c = (short)(ticksDiffBytes[1] | (ticksDiffBytes[0] << 8));

var guid = new Guid(
    a,
    b,
    c,
    (byte)(sequenceNumber >> 8),
    (byte)(sequenceNumber),
    macBytes[0],
    macBytes[1],
    macBytes[2],
    macBytes[3],
    macBytes[4],
    macBytes[5]);

Binary stuff

You can extract bits directly from ticksDiff to avoid the call to BitConverter.GetBytes:

var ticksDiff = nowTicks - baseDateTicks;

int a = (int)(
    ((ticksDiff >> 56) & 0xFF) |
    ((ticksDiff & 0x00FF000000000000) >> 40) |
    ((ticksDiff & 0x0000FF0000000000) >> 24) |
    ((ticksDiff & 0x000000FF00000000) >> 8));

short b = (short)(
    ((ticksDiff & 0x00000000FF000000) >> 24) |
    ((ticksDiff & 0x0000000000FF0000) >> 8));

short c = (short)(
    ((ticksDiff & 0x000000000000FF00) >> 8) |
    ((ticksDiff & 0x00000000000000FF) << 8));

If you can tolerate a change in endianness, the following is a lot cleaner to read (but provides no measurable change in runtime for me):

var ticksDiff = nowTicks - baseDateTicks;

int a = (int)(ticksDiff);
short b = (short)(ticksDiff >> 32);
short c = (short)(ticksDiff >> 48);

Remainder

You don't need to do a remainder when computing sequenceNumber because we're extracting the remainder bits directly anyhow when we pass (byte)(sequenceNumber >> 8), (byte)(sequenceNumber) to the Guid constructor.

My numbers below make it hard to conclude if this helps at all. This is the kind of thing that might be optimized away by the jitter anyway.

Benchmarks

With these changes, my benchmarks look as follows:

|                                    Method |     Mean |   Error |  StdDev | Ratio |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------------------------------------ |---------:|--------:|--------:|------:|-------:|------:|------:|----------:|
|                          NewGuid_Original | 224.2 ns | 4.37 ns | 4.49 ns |  1.00 | 0.0041 |     - |     - |      20 B |
|                  NewGuid_WithPackedValues | 153.6 ns | 2.51 ns | 2.35 ns |  1.00 | 0.0041 |     - |     - |      20 B |
| NewGuid_WithPackedValuesAndNoBitConverter | 148.6 ns | 2.43 ns | 2.28 ns |  1.00 |      - |     - |     - |         - |
|                NewGuid_WithReorderedBytes | 148.9 ns | 2.92 ns | 3.00 ns |  1.00 |      - |     - |     - |         - |
|  NewGuid_WithReorderedBytesAndNoRemainder | 146.4 ns | 2.11 ns | 1.98 ns |  1.00 |      - |     - |     - |         - |

Final code:

public static Guid NewGuid_WithBinaryOptimizationsAndWithoutRemainder()
{
    var nowTicks = DateTime.UtcNow.Ticks;
    var sequenceNumber = Interlocked.Increment(ref ClockSequenceNumber);

    var ticksDiff = nowTicks - baseDateTicks;

    int a = (int)(ticksDiff);
    short b = (short)(ticksDiff >> 32);
    short c = (short)(ticksDiff >> 48);

    var guid = new Guid(
        a,
        b,
        c,
        (byte)(sequenceNumber >> 8),
        (byte)(sequenceNumber),
        macBytes[0],
        macBytes[1],
        macBytes[2],
        macBytes[3],
        macBytes[4],
        macBytes[5]);

    return guid;
}


Constructor start, destructor end timer in C++

Design:

The problem I have is that you need to modify the thing you want to time (which means changing the timing).

  void functionIWantToTime()
  {
       CSDSTimer time("functionIWantToTime");

       // Stuff that takes time
  }

What would be better is a way to time a function without modifying it.

 CSDSTimer("functionIWantToTime", &functionIWantToTime);

This also allows you to time random set of stuff that is not a function by using a lambda to combine them.

 CSDSTimer("Stuff", [](){
     function1();
     function2();
 )};

Code Review

Pass big parameters by const reference

To avoid copying objects pass by const reference.

CSDSTimer(std::string name, std::string context = "global", std::ostream &stream = std::cout)
                  ^^^^^^ Add const&  ^^^^^

Avoid holding pointers:

std::ostream *_default_str;

You pass by reference. Why not store a reference?

Prefer '\n' over std::endl

The difference is a flush. Flushing is usually sub-optimal; the stream will flush at the optimal time. Manual flushing usually just retards performance.

Timer Accuracy

I did not spot it. But @hoffmale suggested using a more accurate timer. I agree that is probably a good idea (you have nothing to lose with more accuracy).


All your win1, win2 and win3 functions are essentially the same. When you have multiple functions/pieces of code that are nearly identical, look at what parts of them are the same, and what parts are different. Make the identical parts the body of a function, and the differing parts parameters of the function.
In the case of those three functions, they're all the same; except for the bonus factor. Simply make that a parameter:
def win(bonus_factor):
    amount_won = bet * bonus_factor
    # I did different wins, the win1,2,3 function contains them
    print("WIN!WIN!WIN! \n You won " , amount_won, "credits! ")
    a.append(a[-1] + amount_won)
    print("Actual balance : ", a[-1])

Then change the callsite to use the same function:
elif reel_1 + reel_2 + reel_3 == 8:
    win(6)

elif  reel_1 + reel_2 + reel_3 == 7:
    win(4)

elif  reel_1 + reel_2 + reel_3 == 6:
    win(2)

And better yet, the 6, 4 and 2 should be extracted out into constants at the top of the file so they're named and easily modifiable.
That reduced the duplication of those three functions, but there's multiple things that need to be said about a:

It's a terrible name. The name you associate with an object should be descriptive and let readers know its purpose. Which makes more sense to you?:
a.append(a[-1] + (bet * 4))
balance_history.append(balance_history[-1] + (bet * 4))

You'll find that overwhelmingly, the latter will be easier to understand. Not only is a completely non-descript, but it's also so simple that you can't search for usages of it using simple "find" tools, since a is such a common letter.

It's not necessary. If you do a search for usages of a, you'll see that it's only used for two things: a[-1], and a.append. While there's something to be said about anticipating future needs, you're currently accumulating a history of balances that you never use. This not only uses up more memory than is needed, but it also convolutes the logic. If you're maintaining a history, that suggests that the history is used somewhere. It never is though. You could safely change a to balance = 1000, then just do simple math on it directly. That would make a lot of this code cleaner and more sensical.

Speaking of memory usage, you're using recursion for basic looping, which is not a good thing. Your spin function is essentially:
def spin():
    # Logic
    reels(), spin()

Every single time your player takes another turn, spin is allocating another stack frame, and taking up more memory. If your player were to take ~1000 turns, your program would crash due to the stack being exhausted. Change that function to a basic while loop:
def spin():
    global balance
    while True:
        # And this is the main function, the spin
        spin1 = input("Balance : " + str(balance) + " Press enter to spin the wheel ")

        if spin1 == "":
            print("****************************THE WHEEL IS SPINNING**************************** \n")
            balance -= bet
            print("Balance : ", balance)
            reels()
        else:
            print("You can only spin the wheel with enter")

A few changes I made:

I changes balance to be a simple integer and discussed above (notice how much more sense balance -= bet makes).
It's using a while loop. This does not eat up memory as the program is used. Recursion should be reserved for the very specific cases where it's the proper choice, like when iterating a recursive structure. Especially in a language like Python, recursion should be avoided unless you're very familiar with it and know about its strengths/weaknesses.
I rearranged the if branches. You originally had it so if if spin1 == "": was true, all it would do is print; then the actual functionality happened at the bottom of the function. I think it makes much more sense as I have it here; where everything is grouped.
I did a lot of small touchups (more on that below).

You're making heavy use of global variables. This is quite common when starting out, but it's a habit you should work to fix quickly. General rules of thumb to follow unless you have good reason to do otherwise:

All the changing data that a function requires to operate (balance, for example) should be explicitly passed to the function as arguments. This means you can test the function by simply passing it data, and you don't need to alter global state. This isn't a big deal now, but needing to alter mutable globals to test a function will become a disaster once your function is larger.
All data that the function produces should be returned from the function. Again, this means you can test the function all you want without affecting any other code.

As an alternative, you may also find that creating a class to maintain a state is a cleaner choice as well. That's getting a little more advanced though.

I'm going to show the full final code below, but I needed to make many small fixes to make it clean. Please be aware of formatting. Yes, it is very important. You have many places in your code where care was not taken to make it consistent and readable:
elif reel_1 + reel_2 + reel_3 == 8:
    win3()

elif  reel_1 + reel_2 + reel_3 == 7:  # Too many spaces after the elif
    win2()

"Balance : "+ str(a[-1])+ " Press enter to spin the wheel "  # Inconsistent spacing around +

def spin() :  # There shouldn't be a space before the colon

If you're going to write Python, you should spend an afternoon to read over PEP8 at least once. The look of your code reflects strongly on that care that was taken while writing it. You want you code to look sharp, and clean. You may have your own stylistic preferences, but be consistent when applying them, and when in doubt, stick to PEP8.

The final code:
import random

balance = 1000
bet = 20

def win(bonus_factor):
    global balance
    amount_won = bet * bonus_factor
    # I did different wins, the win1,2,3 function contains them
    print("WIN!WIN!WIN! \n You won ", amount_won, "credits! ")
    balance += amount_won
    print("Actual balance : ", balance)

def reels():
    global balance
    # Here is the random number calculation.As you can see, theres a pretty good chance to win so it
    # would not be a good casino game for the house :)
    reel_1 = random.randint(1, 3)
    reel_2 = random.randint(1, 3)
    reel_3 = random.randint(1, 3)

    if reel_1 + reel_2 + reel_3 == 9:
        print("Jackpot!!!!!!!!!!")
        balance += bet * 100
        print("Actual balance : ", balance)

    elif reel_1 + reel_2 + reel_3 == 8:
        win(6)

    elif reel_1 + reel_2 + reel_3 == 7:
        win(4)

    elif reel_1 + reel_2 + reel_3 == 6:
        win(2)
    else:
        print("No win this time")

def spin():
    global balance
    while True:
        # And this is the main function, the spin
        spin1 = input("Balance : " + str(balance) + " Press enter to spin the wheel ")

        if spin1 == "":
            print("****************************THE WHEEL IS SPINNING**************************** \n")
            balance -= bet
            print("Balance : ", balance)
            reels()
        else:
            print("You can only spin the wheel with enter")

spin()


I think your implementation is overall very good, two small comments:

Improving readability for return statement in hasNext to return examples.size() != index;
Making the examples field final: private final List<Vector> examples;

However, if the Vector class here is java.util.Vector you should know that it is considered deprecated in favor of the ArrayList class.

Also, since you create your iterator from a List<Vector> you could get an Iterator<Vector> by calling list.iterator();


There's a bug: you're not checking if the last character is a letter or digit, only that it isn't a hyphen, so this fails to reject "abcdef&". Denis' solution may be less efficient (2 iterations instead of 1), but with at most 16 characters that's not much of a concern, and it's both easier to read and it works correctly.
The first two rules read very nicely. I especially like that the business rules are translated to code almost 1:1, that will make updating easier. However, I do think those extension methods are over-engineered. str.Length < 6 || str.Length > 16 and !char.IsLetter(str.First()) || str.Last() == '-' is already quite readable, and that doesn't require extra code that needs to be understood and maintained.
You can use => syntax for methods with single-expression bodies.


Fizzbuzz in COBOL, Verbose dinosaur style

As I'm sure you are aware, COBOL tends to be written one way at one site, another way at another.

Often things like name prefixes, and paragraph/SECTION prefixes cannot be other than dictated. Same with case of identifiers.

I dislike WSnn- (drives people nuts trying to insert numbers so that new data can be located rationally rather than in the order of arrival in specification) and WS- (similar for the LINKAGE SECTION) but am happy with W-/L-/LS- (or nothing). Absolutely hate single-word identifiers. Even these days with forewarning of what may appear later, it is plain dumb to have them there waiting for some compiler-change to make them invalid.

Also, since COBOL has no concept of "main", it is something to avoid pretending exists.

For paragraphs, or SECTIONS, I go with two numerics. Then with each subsequent level, append an alpha, A, D, G, J, M etc (allowing for insertions), and keep all related paragraphs/SECTIONS together, physically. Your program only has one level, so it doesn't really matter what you do in that one.

Nicely laid-out. I tend to be more extreme, but the effort you've invested impresses the reader (if they are a programmer, rather than a 9-5-er).

Hate the comments.

I'd remove all the redundant code (you don't need an ENVIRONMENT DIVISION, for instance).

Ah, for these last two, they have been generated for you, so I'd suggest copying an existing model program rather than using the OpenCOBOLIDE bolierplate.

I only use VARYING with things that, well, vary. So I'd use TIMES. Describe the situation better. You have to do more typing, but in addition to the better description of the data, your code will be faster than using VARYING.

Forget ideas like using REM. COBOL has done remainders since day one, a considerable time ago, so why (I don't know the answer to this) is there a function for it? In Enterprise COBOL (IBM Mainframe) REM would return a floating-point item, then converted to what you define in your program. Wow, do we need that?

I would work on the data-names a bit, but they are better than VAR1, VAR2 (or WS13-VAR1 and WS34-VAR2).

Here's an example of how I like to format a program:

http://ibmmainframes.com/viewtopic.php?p=278927#278927

And since that is a link, here's the code:

   IDENTIFICATION DIVISION.
   PROGRAM-ID. BBHEXD.
   ENVIRONMENT DIVISION.
   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  W-WHEN-COMPILED                      PIC X(8)BX(8).

   01  W-DISPLAY-HEX-MAX-UIND      USAGE IS INDEX.
   01  W-FIRST-TIME-FLAG                    PIC X VALUE "Y".
       88  W-FIRST-TIME-IN-PROGRAM          VALUE "Y".
       88  W-NOT-FIRST-TIME-FLAG            VALUE "N".

   01  W-WORK-BYTE-FOR-CALC         COMP    PIC S9(4) VALUE ZERO.
   01  FILLER REDEFINES W-WORK-BYTE-FOR-CALC.
       05  FILLER                           PIC X.
       05  W-WORK-BYTE                      PIC X.

   01  W-LEFT-HALF-BYTE-NUM         COMP    PIC S9(4).
   01  W-RIGHT-HALF-BYTE-NUM        COMP    PIC S9(4).
   01  W-BYTES-TO-OUTPUT            COMP    PIC S9(4).
   01  W-BYTES-MOVED                COMP    PIC S9(4).

   01  W-HEX-ALPHA-SUB              COMP    PIC S9(4).
   01  W-HEX-ALPHA-TABLE VALUE "ABCDEF".
       05  FILLER OCCURS 6 TIMES
            INDEXED BY W-HEX-ALPHA-IDX.
           10  W-HEX-ALPHA                  PIC X.

   01  W-DISPLAY-HEX.
       05  W-LEFT-HEX                       PIC X.
       05  W-RIGHT-HEX                      PIC X.

   01  W-HEX-TO-DISPLAY-LEFT-TABLE VALUE SPACE.
       05  FILLER OCCURS 1 TO 132 TIMES
           DEPENDING ON W-BYTES-TO-OUTPUT
           INDEXED BY W-DISPLAY-HEX-LEFT-IND.
           10  W-HEX-TO-DISPLAY-LEFT        PIC X.
               88  W-HEX-TO-DISPLAY-LEFT-IS-EMPTY
                                            VALUE SPACE.
   01  W-HEX-TO-DISPLAY-RIGHT-TABLE VALUE SPACE.
       05  FILLER OCCURS 1 TO 132 TIMES
           DEPENDING ON W-BYTES-TO-OUTPUT
           INDEXED BY W-DISPLAY-HEX-RIGHT-IND.
           10  W-HEX-TO-DISPLAY-RIGHT       PIC X.

   01  W-BYTE-TO-DISPLAY-TABLE VALUE SPACE.
       05  FILLER OCCURS 1 TO 132 TIMES
           DEPENDING ON W-BYTES-TO-OUTPUT
           INDEXED BY W-DISPLAY-BYTE-IND.
           10  W-BYTE-TO-DISPLAY            PIC X.
   01  W-CONVERT-TO-HEX-FROM-DIGIT   COMP   PIC S9(4).

   01  W-CONVERTED-HEX-DIGIT                PIC X.
   01  W-CONVERTED-HEX-DIGIT-NUM
         REDEFINES W-CONVERTED-HEX-DIGIT    PIC 9.

   01  W-CONVERTED-HEX-DIGIT-NUM4           PIC 9(4).
   01  FILLER REDEFINES W-CONVERTED-HEX-DIGIT-NUM4.
       05  FILLER                           PIC XXX.
       05  W-CONVERTED-HEX-DIGIT-NUM4L      PIC 9.

   01  W-COLS-LINE.
       05  FILLER OCCURS 1 TO 132 TIMES
           DEPENDING ON W-BYTES-TO-OUTPUT.
           10  FILLER                       PIC X.

   01  W-COLS-TABLE.
       05  FILLER                           PIC X(10) VALUE
           "----+----1".
       05  FILLER                           PIC X(10) VALUE
           "----+----2".
       05  FILLER                           PIC X(10) VALUE
           "----+----3".
       05  FILLER                           PIC X(10) VALUE
           "----+----4".
       05  FILLER                           PIC X(10) VALUE
           "----+----5".
       05  FILLER                           PIC X(10) VALUE
           "----+----6".
       05  FILLER                           PIC X(10) VALUE
           "----+----7".
       05  FILLER                           PIC X(10) VALUE
           "----+----8".
       05  FILLER                           PIC X(10) VALUE
           "----+----9".
       05  FILLER                           PIC X(10) VALUE
           "----+----0".
       05  FILLER                           PIC X(10) VALUE
           "----+----1".
       05  FILLER                           PIC X(10) VALUE
           "----+----2".
       05  FILLER                           PIC X(10) VALUE
           "----+----3".
       05  FILLER                           PIC X(02) VALUE
           "--".

   LINKAGE SECTION.

   01  L-DATA-LENGTH COMP PIC S9(8).

   01  L-BBHEXD-CONTROL-BLOCK.
       05  L-BBHEXD-CB-MAX-LINE         COMP PIC S9(4) VALUE +80.
           88  L-BBHEXD-CB-MAX-LINE-VALID    VALUE +80 +132.
       05  L-BBHEXD-CB-CHUNK-LENGTH     COMP PIC S9(4) VALUE ZERO.
           88  L-BBHEXD-CB-CHUNK-LENGTH-ZERO VALUE ZERO.
       05  FILLER                            PIC X(96) VALUE SPACE.

   01  L-DATA-PICX1-FOR-USING PIC X.

   01  L-DATA-TO-DISPLAY REDEFINES L-DATA-PICX1-FOR-USING.
       05  FILLER OCCURS 99999999 TIMES
             INDEXED BY L-DTD-BYTE-FOR-C-AND-C-IDX.
           10  L-DTD-BYTE-FOR-CONV-AND-COPY PIC X.

   PROCEDURE DIVISION USING
                                    L-DATA-PICX1-FOR-USING
                                    L-DATA-LENGTH
                                    L-BBHEXD-CONTROL-BLOCK
                                    .
   00-CONTROL SECTION.

       PERFORM                      10-FIRST-TIME
       PERFORM                      30-CNV-LK-DATA-TO-HEX-AND-DISP
       GOBACK
       .
   10-FIRST-TIME SECTION.

       IF W-FIRST-TIME-IN-PROGRAM
           PERFORM                  10A-SAY-WHO-WE-ARE
           SET W-NOT-FIRST-TIME-FLAG
                                    TO TRUE
       END-IF

       PERFORM                      10D-CHECK-OUTPUT-LENGTH
       PERFORM                      10G-SET-OUTPUT-LNGTH-AND-CHUNK
       .
   10A-SAY-WHO-WE-ARE SECTION.

       MOVE WHEN-COMPILED           TO W-WHEN-COMPILED
       DISPLAY "BBHEXD This program compiled on "
                                    W-WHEN-COMPILED
       .
   10D-CHECK-OUTPUT-LENGTH SECTION.

       IF ( NOT L-BBHEXD-CB-MAX-LINE-VALID )
           DISPLAY "BBHEXD maximum line length should be 80 or 132"
           DISPLAY "BBHEXD found>" L-BBHEXD-CB-MAX-LINE "<"
           CALL "FOODUMP"
       END-IF
       .
   10G-SET-OUTPUT-LNGTH-AND-CHUNK SECTION.

       IF L-BBHEXD-CB-CHUNK-LENGTH-ZERO
           MOVE L-BBHEXD-CB-MAX-LINE
                                    TO W-BYTES-TO-OUTPUT
       ELSE
           IF ( L-BBHEXD-CB-CHUNK-LENGTH
               GREATER THAN L-BBHEXD-CB-MAX-LINE )
               DISPLAY "BBHEXD Sorry, chunks ignored, too big"
               DISPLAY "BBHEXD Chunks>" L-BBHEXD-CB-CHUNK-LENGTH "<"
               DISPLAY "BBHEXD Maxlen>" L-BBHEXD-CB-MAX-LINE "<"
               MOVE L-BBHEXD-CB-MAX-LINE
                                    TO W-BYTES-TO-OUTPUT
           ELSE
               MOVE L-BBHEXD-CB-CHUNK-LENGTH
                                    TO W-BYTES-TO-OUTPUT
           END-IF
       END-IF

       SET W-DISPLAY-BYTE-IND       TO W-BYTES-TO-OUTPUT
       SET W-DISPLAY-HEX-MAX-UIND   TO W-DISPLAY-BYTE-IND

       IF L-DATA-LENGTH EQUAL TO ZERO
           DISPLAY "BBHEXD You want to display zero bytes?"
           DISPLAY "BBHEXD Do not expect to see them"
       END-IF
       .
   30-CNV-LK-DATA-TO-HEX-AND-DISP SECTION.

       SET W-DISPLAY-HEX-LEFT-IND
           W-DISPLAY-HEX-RIGHT-IND
           W-DISPLAY-BYTE-IND       TO +1
       MOVE ZERO                    TO W-BYTES-MOVED

       PERFORM                      30A-BYTE-BY-BYTE-CONVERT
         VARYING                    L-DTD-BYTE-FOR-C-AND-C-IDX
         FROM                       1
         BY                         1
         UNTIL                      L-DTD-BYTE-FOR-C-AND-C-IDX
           GREATER THAN             L-DATA-LENGTH

       IF ( W-BYTES-MOVED NOT EQUAL TO ZERO )
           MOVE W-BYTES-MOVED       TO W-BYTES-TO-OUTPUT
           PERFORM                  99A-DISPLAY-PART-OF-OUTPUT
       END-IF

       .
   30A-BYTE-BY-BYTE-CONVERT SECTION.

       MOVE L-DTD-BYTE-FOR-CONV-AND-COPY
             ( L-DTD-BYTE-FOR-C-AND-C-IDX )
                                    TO W-WORK-BYTE

       DIVIDE W-WORK-BYTE-FOR-CALC  BY 16
         GIVING                     W-LEFT-HALF-BYTE-NUM
         REMAINDER                  W-RIGHT-HALF-BYTE-NUM

       MOVE W-LEFT-HALF-BYTE-NUM    TO W-CONVERT-TO-HEX-FROM-DIGIT
       PERFORM                      30AA-CONVERT-HALF-BYTE
       MOVE W-CONVERTED-HEX-DIGIT   TO W-LEFT-HEX
       MOVE W-RIGHT-HALF-BYTE-NUM   TO W-CONVERT-TO-HEX-FROM-DIGIT
       PERFORM                      30AA-CONVERT-HALF-BYTE
       MOVE W-CONVERTED-HEX-DIGIT   TO W-RIGHT-HEX

       IF ( W-DISPLAY-HEX-LEFT-IND
           GREATER THAN W-DISPLAY-HEX-MAX-UIND )
           PERFORM                  99A-DISPLAY-PART-OF-OUTPUT
           SET W-DISPLAY-HEX-LEFT-IND
               W-DISPLAY-HEX-RIGHT-IND
               W-DISPLAY-BYTE-IND
                                    TO +1
       END-IF

       MOVE W-LEFT-HEX              TO W-HEX-TO-DISPLAY-LEFT
                                        ( W-DISPLAY-HEX-LEFT-IND )
       MOVE W-RIGHT-HEX             TO W-HEX-TO-DISPLAY-RIGHT
                                        ( W-DISPLAY-HEX-RIGHT-IND )
       MOVE W-WORK-BYTE             TO W-BYTE-TO-DISPLAY
                                        ( W-DISPLAY-BYTE-IND )
       ADD +1                       TO W-BYTES-MOVED
       SET W-DISPLAY-HEX-LEFT-IND
           W-DISPLAY-HEX-RIGHT-IND
           W-DISPLAY-BYTE-IND       UP BY +1
       .
   30AA-CONVERT-HALF-BYTE SECTION.

       IF ( W-CONVERT-TO-HEX-FROM-DIGIT GREATER THAN 9 )
           SUBTRACT 9               FROM W-CONVERT-TO-HEX-FROM-DIGIT
             GIVING                 W-HEX-ALPHA-SUB
           SET W-HEX-ALPHA-IDX      TO W-HEX-ALPHA-SUB
           MOVE W-HEX-ALPHA ( W-HEX-ALPHA-IDX )
                                    TO W-CONVERTED-HEX-DIGIT
       ELSE
           MOVE W-CONVERT-TO-HEX-FROM-DIGIT
                                    TO W-CONVERTED-HEX-DIGIT-NUM4
           MOVE W-CONVERTED-HEX-DIGIT-NUM4L
                                    TO W-CONVERTED-HEX-DIGIT-NUM
       END-IF

       .
   99A-DISPLAY-PART-OF-OUTPUT SECTION.

       MOVE W-COLS-TABLE            TO W-COLS-LINE
       DISPLAY                      W-COLS-LINE

       DISPLAY                      W-BYTE-TO-DISPLAY-TABLE
       DISPLAY                      W-HEX-TO-DISPLAY-LEFT-TABLE
       DISPLAY                      W-HEX-TO-DISPLAY-RIGHT-TABLE
       MOVE SPACE                   TO W-BYTE-TO-DISPLAY-TABLE
                                       W-HEX-TO-DISPLAY-LEFT-TABLE
                                       W-HEX-TO-DISPLAY-RIGHT-TABLE
       MOVE ZERO                    TO W-BYTES-MOVED

       .

To demonstrate the usefulness of meaningful names, here's a version with the names rubbished:

   IDENTIFICATION DIVISION.
   PROGRAM-ID. UGLY.
   ENVIRONMENT DIVISION.
   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  W-A                      PIC X(8)BX(8).

   01  W-B            USAGE IS INDEX.
   01  W-C          USAGE IS INDEX.

   01  W-D              PIC S9(9).
   01  FILLER REDEFINES W-D.
       05  FILLER                           PIC X(5).
       05  W-E         PIC 9(4).
   01  W-F PIC X VALUE "Y".
       88  W-F-Y VALUE "Y".
       88  W-F-N VALUE "N".

   01  W-G         COMP    PIC S9(4) VALUE ZERO.
   01  FILLER REDEFINES W-G.
       05  FILLER                           PIC X.
       05  W-H                      PIC X.

   01  W-I         COMP    PIC S9(4).
   01  W-J        COMP    PIC S9(4).
   01  W-K            COMP    PIC S9(4).

   01  W-L              COMP    PIC S9(4).
   01  W-M VALUE "ABCDEF".
       05  FILLER OCCURS 6 TIMES
            INDEXED BY I.
           10  W-N                  PIC X.

   01  W-O.
       05  W-P                       PIC X.
       05  W-Q                      PIC X.

   01  W-R.
       05  FILLER OCCURS 1 TO 132 TIMES
           DEPENDING ON W-K
           INDEXED BY J.
           10  W-S        PIC X.
               88  W-S-Y
                                            VALUE SPACE.
   01  W-T.
       05  FILLER OCCURS 1 TO 132 TIMES
           DEPENDING ON W-K
           INDEXED BY K.
           10  W-U       PIC X.

   01  W-V.
       05  FILLER OCCURS 1 TO 132 TIMES
           DEPENDING ON W-K
           INDEXED BY L.
           10  W-W            PIC X.
   01  W-X   COMP   PIC S9(4).

   01  W-Y                PIC X.
   01  W-Z
         REDEFINES W-Y    PIC 9.

   01  W-AA           PIC 9(4).
   01  FILLER REDEFINES W-AA.
       05  FILLER                           PIC XXX.
       05  W-AB      PIC 9.

   01  W-AC.
       05  FILLER OCCURS 1 TO 132 TIMES
           DEPENDING ON W-K.
           10  FILLER                       PIC X.

   01  W-AD.
       05  FILLER                           PIC X(10) VALUE
           "----+----1".
       05  FILLER                           PIC X(10) VALUE
           "----+----2".
       05  FILLER                           PIC X(10) VALUE
           "----+----3".
       05  FILLER                           PIC X(10) VALUE
           "----+----4".
       05  FILLER                           PIC X(10) VALUE
           "----+----5".
       05  FILLER                           PIC X(10) VALUE
           "----+----6".
       05  FILLER                           PIC X(10) VALUE
           "----+----7".
       05  FILLER                           PIC X(10) VALUE
           "----+----8".
       05  FILLER                           PIC X(10) VALUE
           "----+----9".
       05  FILLER                           PIC X(10) VALUE
           "----+----0".
       05  FILLER                           PIC X(10) VALUE
           "----+----1".
       05  FILLER                           PIC X(10) VALUE
           "----+----2".
       05  FILLER                           PIC X(10) VALUE
           "----+----3".
       05  FILLER                           PIC X(02) VALUE
           "--".

   LINKAGE SECTION.

   01  L-A PIC X.

   01  L-B REDEFINES L-A.
       05  FILLER OCCURS 99999999 TIMES
             INDEXED BY M.
           10  L-C PIC X.

   01  L-D COMP PIC S9(8).

   01  L-E.
       05  L-F         COMP PIC S9(4) VALUE +80.
           88  L-F-VALID    VALUE +80 +132.
       05  L-G     COMP PIC S9(4) VALUE ZERO.
           88  L-G-Y VALUE ZERO.
       05  FILLER                            PIC X(96) VALUE SPACE.

   PROCEDURE DIVISION USING         L-A
                                    L-D
                                    L-E
                                    .
   00-A SECTION.
       IF W-F-Y
           MOVE WHEN-COMPILED       TO W-A
           DISPLAY                  "UGLY program compiled on "
                                    W-A
           SET W-F-N                TO TRUE
       END-IF

       IF ( NOT L-F-VALID )
           DISPLAY "UGLY maximum line length should be 80 or 132"
           DISPLAY "UGLY found>" L-F "<"
           CALL "FOODUMP"
       END-IF
       IF L-G-Y
           MOVE L-F                 TO W-K
       ELSE
           IF ( L-G
               GREATER THAN L-F )
               DISPLAY "UGLY Sorry, chunks ignored, too big"
               DISPLAY "UGLY Chunks>" L-G "<"
               DISPLAY "UGLY Maxlen>" L-F "<"
               MOVE L-F             TO W-K
           ELSE
               MOVE L-G             TO W-K
           END-IF
       END-IF
       SET L                        TO W-K
       SET W-B                      TO L
       SET J
           K
           L                       TO ZERO

       PERFORM                      00-B
         VARYING                    M
         FROM                       1
         BY                         1
         UNTIL                      M
           GREATER THAN             L-D

       IF ( NOT W-S-Y )
           SET W-C                  TO J
           MOVE W-C                 TO W-D
           MOVE W-E                 TO W-K
           PERFORM                  00-D
       END-IF

       GOBACK
       .
   00-B SECTION.

       MOVE L-C
             ( M )
                                    TO W-H

       DIVIDE W-G                   BY 16
         GIVING                     W-I
         REMAINDER                  W-J

       MOVE W-I                     TO W-X
       PERFORM                      00-C
       MOVE W-Y                     TO W-P
       MOVE W-J                     TO W-X
       PERFORM                      00-C
       MOVE W-Y                     TO W-Q

       SET J
           K
           L                        UP BY +1

       IF ( J GREATER THAN W-B )
           PERFORM                  00-D
           MOVE SPACE               TO W-R
                                       W-U
           SET J
               K
               L
                                    TO +1
       END-IF

       MOVE W-P                     TO W-S
                                        ( J )
       MOVE W-Q                     TO W-U
                                        ( K )
       MOVE W-H                     TO W-W
                                        ( L )
       .
   00-C SECTION.

       IF ( W-X GREATER THAN 9 )
           SUBTRACT 9               FROM W-X
             GIVING                 W-L
           SET I                    TO W-L
           MOVE W-N ( I )           TO W-Y
       ELSE
           MOVE W-X                 TO W-AA
           MOVE W-AB                TO W-Z
       END-IF

       .
   00-D SECTION.

       MOVE W-AD                    TO W-AC
       DISPLAY                      W-AC

       DISPLAY                      W-V
       DISPLAY                      W-R
       DISPLAY                      W-T
       .

Now, there are a couple of bugs in this version. Enjoy finding them, as you first have to work out, with no aid, what the program does.

Since you have GnuCOBOL, track down the discussion area at SourceForge.Net, the current home of GnuCOBOL.


Generic comparitive array selection sort

When I put this into IntelliJ with my default settings I already get a warning on the Comparable[] data0 declaration.

  Raw use of parameterized class

Changing the array declarations to these:

Integer[] data0 = {2, 8, -39, 904, 8, 0};
Double[] data1 = {1.1, -5.68, 4.39, -0.01, 5.59};

solved both warnings.


How would you refactor this case statement?

I haven't run this code, but maybe something along these lines:

def new_button
  content_tag(:li, class: "has-form") do
    text = "New #{controller_name.singularize.titleize}"
    path = { controller: controller_name, action: "new" }
    link_to(text, path, class: "button")
  end
end

Using content_tag and link_to is arguably cleaner, and they handle escaping automatically.

Letting the router generate the URL for you from a hash is preferable to doing string manipulation.

The text generation is perhaps inelegant, but simple. If you're using I18n elsewhere in this app I'd consider using that:

model_slug = controller_name.singularize
text = t("new_x", x: t("activerecord.models.#{model_slug}"))

But it's overkill if you're not using it for anything else.


Calculating energy from mass and light speed

The implementation looks fine. Only the conventions on capital letters and spacing might be a bit different in the java community.

A class name always starts with a capital letter

public class Methodes

General utility classes are usually called Util but Methodes is fine depending on your own project preference. Especially when you're not native English it might change depending on who you work with, and how well you know the language.

Method names start with a lower case. And the opening { is placed at the same line as the method name

public static double energie(double m, double c) {
    return (double) (m*Math.pow(c, 2));
}

If you really want to place { at the line after the method name that's fine as long as you're consistent. So either do it always, or do it never. (big discussion in general about which is better, the community overal prefers on the same line).

Variables start with a lower case letter and are camel case, constants are written full uppercase and separated with _. Preferably use meaningful names, although m, C and e in this context are already pretty decent.

public class ExampleClass {
    //this is a constant. Since java 7 (?) you can also use _ in numbers to read easier.
    public static final int SPEED_OF_LIGHT = 300_000;

    public static int calculateEnergy(double mass) {
        return (double) (mass*Math.pow(SPEED_OF_LIGHT , 2));
    }

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

        System.out.println("Valeur de la masse en kg : ");
        double mass = sc.nextDouble();

        double energy = calculateEnergy(mass);
        System.out.println("Pour " + mass + " kg donné, l'énergie équivaut à "
                          + energy + " Joules");
    }
}


Remove control and non-ASCII characters from large files

One source of performance degradation is frequent memory allocations.  In your case, the StringBuilder will allocate space for every line in your file, and may allocate additional space (along with a data copy) for longer lines.

You can eliminate all of that by reusing the StringBuilder object.  At the start of BuildClearString, call the clear method on it (sb.Clear(); or sb.Length = 0;).  Follow that up by a capacity check.

if (sb.Capacity < line.Length)
    sb.Capacity = line.Length;

By changing the capacity you ensure that you have a buffer big enough to hold all the characters you will be adding, so you won't incur any memory allocations when processing a line.  By reusing it, you keep the existing allocated memory, thus avoiding any allocations for later lines unless the line is longer than any you've already encountered.  You can also set an initial capacity on the StringBuilder object.


Replacing occurrences in NSString and NSMutableString

In both cases, this is exactly the most efficient way for removing a substring from a string.

In practice, I'm not sure how practical or how frequently you'll truly need to be using the second example, and for most of us, simply doing this:

string1 = [[string1 stringByReplacingOccurrencesOfString:@"aaa" withString:@""] mutableCopy];

is a bit easier to remember.  And you generally want to work with immutable objects whenever you can anyway.  But given the requirements, the method you've used does remove the substring without creating a new object.

One thing that may or may not be of concern is the white space that's left in these strings at the beginning/end.  So you may or may not want to put some effort into trimming the white space.

Also, by replacing @"aaa" with @"", that means you're also effectively replacing @"aaaa" with @"a".  Be sure this is what is intended, otherwise this problem is a bit more complicated.

You can also use regex.  Regex will be slightly less efficient, but can give you some more control over what's being replaced:

NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/\baaa\b/"
                                                                       options:nil
                                                                         error:&error];
NSString *str2 = [regex stringByReplacingMatchesInString:string
                                                 options:nil
                                                   range:NSMakeRange(0, [str length])
                                            withTemplate:@""];
NSLog(@"%@", str2);

I don't know at this moment whether there's anything similar to this available for mutating a NSMutableString object rather than creating a new object.


to avoid DRY i would put this line (i think it is in your code only a sample logic) inside the cell. in this case you have the logic for calculating the remaining time inside the cell and not outside somewhere. and you can use always the same function to update the progress.

cell.timeLeftLabel.text = progress + "hours:minutes:seconds"

should be become

cell.updateProgress()