Update Trigger (Comparing Descriptive string), as well as checking for valid updates

It will only work as intended for single-row updates

The fact that you use TOP 1 and SCOPE_IDENTITY() tells me this was designed with one-row updates/inserts in mind. But what happens when you update multiple rows? (In case you don't know, the trigger only fires once for the whole changed set, rather than once for each row. The changed rows are added to the inserted and deleted tables).

To solve this, I'd recommend using a temp table or variable table instead of @CMP, and the output clause instead of @NEWID. For example:

-- Example table with identity
create table Things (KeyId int identity(1, 1), Value varchar(31))`

-- Table to store identity ints which get created
declare @NewIds table (NewKeyId int)

insert into Things (Value)
output inserted.KeyId into @Keys (NewKeyId) -- this line gets the new identities
select 'Value text'
from OtherTable

Now you can access the created IDs using @Keys. Of course you'd want to store the EpisodeId or something in the same table, to relate them.

EDIT: Untested replacement

So I've just roughly written some SQL I think should work instead of everything including and below the SELECT Top 1 statement. The main issue I have with that part of your trigger is that it will only work for one-row updates, and it performs an INSERT then an UPDATE on that inserted data, which can be optimised.

INSERT into EpisodeHistory
SELECT
    EpisodeID = d.EpisodeID,
    eOwner = d.eOwner,
    eDescription = iif(h.HistoryID is null, d.eDescription, ''),
    eDescRef = isnull(h.HistoryID, 0),
    hWhen = getDate(),
from deleted d
    left join (
        select
            HistoryID, EpisodeID, eOwner, eDescription,
            row_number() over (partition by EpisodeID, eOwner, eDescription ORDER BY HistoryID) as RowNumber
        from EpisodeHistory
        where eDescription <> ''
    ) h
    on d.EpisodeID = h.EpisodeID
        and d.eOwner = h.eOwner
        and d.eDescription = h.eDescription
        and h.RowNumber = 1

Rather than inserting the EpisodeHistory, then checking and updating based on the data we've just inserted, this code just does the operation all in one.

First I'll explain the left join. The point of the join is to find the HistoryID of the earliest matching EpisodeHistory row (since we want to put it in eDescRef, right?). So we do a normal select of the EpisodeHistory table, except we also add a column for row_number(), which, when combined with the fact that we've put RowNumber = 1 in the join condition, will means it will only join to the first HistoryID that matches. This makes sure that if there are two rows with the same EpisodeID, eOwner and eDescription, it will only join to the one with the lowest HistoryID.

Now the actual columns that are inserted are fairly simple. If the left join fails (if no rows in EpisodeHistory match), selecting h.HistoryID will return NULL. Therefore, eDescription = iif(h.HistoryID is null, d.eDescription, '') means that if a HistoryID was not found in the join, it will just do a normal insert of eDescription. If one was found, it will blank that field. The next line is fairly simple in that it inserts HistoryID if the join happened, otherwise it puts in 0.

Since the entire operation can be done in one statement like above, so you can ignore that bit I said above about temporary tables and an output clause.

This code above also has the added bonus of working for multiple-row updates.

It's a trigger...

You may already know, but the SQL Server community is fairly divided when it comes to whether triggers should be avoided or not. They can be easy to forget, hard to debug, and can hinder performance as they become part of the write operation.

Since you mention performance I'll elaborate on that aspect, and I'll make some assumptions I hope you can forgive. I'm going to assume there's an application that sits in front of this database, and the application prompts the insert/update. Say the user is on a form and makes changes to an episode, and submits the change. Usually the application will wait for confirmation of the update/insert operation before proceeding (before loading the next page, for instance). With the trigger, the application now has to wait for the initial insert/update, as well as the trigger to complete its operation too.

Therefore, if you haven't already, consider the possibility of separating out this process. In this example I gave above, you could have it so that the application still waits for the initial insert/update operations, loading the next page normally, but then in the background (asynchronously) it tells the database to perform audit operations. Boom, you've reduced page load time, better UX. This also has the benefit of you not having to worry so much about performance tuning the auditing operation.

Checksum?

I'm going to assume since performance is an issue that you've considered indexes, and have an index set up to optimise this Episode and EpisodeHistory comparison. Have you considered the use of CHECKSUM()? I don't have any experience with it myself, however I'd imagine you could use it in combination with persistent computed columns to improve the load when write and maybe reading to the indexes.

In this instance you'd have an extra column on both tables called something like eDescriptionChecksum, which would be a checksum of eDescription, and you'd put that column in the index instead of eDescription. Then when you perform the comparison to see if they're the same, you'd be comparing the relatively small and light int checksum column instead of the potentially-huge (n)varchar column.

Minor issue

I see when you set the @CMP, you select from multiple tables. It's recommended to use joins instead – use of multiple tables in the from clause is being depreciated by all DBMSs.

If anything's unclear, let me know. Hope you found this helpful.


Write a procedure stream-limit that finds

Looks fine to me.  I would only suggest changing (> tol diff) to (< diff tol) because it reads more like the problem specification and is easier to understand.


You have quite a lot of duplication in your code - everything is written out twice, once for each player. This means that you have to change everything in two places if you want to alter the logic, and that adding more players is a huge pain.

Instead, I would suggest the use of lists to hold multiple items, allowing you to have an arbitrary number of players (you start this with the playernames and dicelist, then seem to give up!)

You should also factor out the "magic numbers" like the number of players, number of faces on the die and the starting score. For example:

import random

# Configuration
PLAYERS = 2  # could be another input at the start
FACES = 10
START_SCORE = 20  # or 50?

# Initialisation
names = [input("\nWhat is player {}'s name?".format(x+1))
         for x in range(PLAYERS)]
scores = [START_SCORE for _ in range(PLAYERS)]

# Main game loop
while all(score > 0 for score in scores):
    print()

    # Calculate rolls
    rolls = [random.randint(1, FACES) for _ in range(PLAYERS)]
    for name, roll in zip(names, rolls):
        print("{} rolled {}".format(name, roll))

    # Determine winning roll
    winning_roll = max(rolls)
    diffs = [winning_roll - roll for roll in rolls]

    # Update scores
    for index, name in enumerate(names):
        scores[index] += diffs[index]
        if diffs[index] == 0:
            print("{} won!".format(name))
            scores[index] -= sum(diffs)

    # Report progress
    for name, score in zip(names, scores):
        print("{} now has {} points".format(name, score))

# Who won?
print()
winning_score = min(scores)
for name, score in zip(names, scores):
    if score == winning_score:
        print("{} is the winner!".format(name))

Note the use of zip, enumerate and list comprehensions to deal effectively with the various lists.

The rules have been adapted slightly to accommodate multiple players - those with the highest score get the sum of all differences subtracted from their score, whereas the others get only their difference added. This is the same for two players, but you could tweak this logic according to how the game should work.

One significant improvement over the current structure would be to implement as a set of short, self-contained functions rather than one long script.


The best way for inserting multiple objects into array

Looks like you were trying to follow the best practices on not mutating data but this is an overkill:

when processing data locally in a function there's no need to clone the intermediate data
no need to clone the array in return, it's already a temporary cloned array
reduce is the wrong choice here - at least if you keep its needless duplication of the resultant array in each step - the task is a simple transformation of each element so map() seems a better choice + an additional splice on the special key
insertedData is always an empty array so no need for [...result, ...insertedData]
for consistency, if you use splice and concat then go all the way and use concat instead of array spread as well or switch to array spread instead of concat.

Simplified code using map():

function foo() {

  const commonData = Object.entries(settings).map(([key, value]) => ({
    key: transformToUpperCase(key),
    value,
  }));

  if (Object.hasOwnProperty.call(settings, SETTINGS_FIELDS.EXAMPLE1)) {
    commonData.splice(2, 0, {
      key: myKey,
      value: myValue,
    }, {
      key: myKey,
      value: myValue,
    });
  }

  return commonData;
}

If you don't override prototype of settings or objects in general the key check can be simplified further: if (SETTINGS_FIELDS.EXAMPLE1 in settings)


This works, but is essentially O(N**2); you can make it O(N) fairly easily by turning your whitelist/blacklist into dicts:

def __init__(self, users_filepath, whitelist_filepath, blacklist_filepath):
    """
    Get filepaths and load the following files: users file , whitelist file and blacklist file

    users_filepath: Path to a text file which contains the raw output of the 'rcon users' in the in-game console.
    whitelist_filepath: Path to a csv file which contains Steam IDs and player-names of the white-listed players.
    blacklist_filepath: Path to a csv file which contains Steam IDs, player-names and alert-message for the black-listed players.
    """
    with open(users_filepath) as f:
        self.users_rawcontents = f.read()
    raw_whitelist = list(csv.DictReader(open(whitelist_filepath)))
    raw_blacklist = list(csv.DictReader(open(blacklist_filepath)))
    self.whitelist = { p['Steam_ID']: p for p in raw_whitelist }
    self.blacklist = { p['Steam_ID']: p for p in raw_blacklist }

def get_playername(self, steamid, player_records):
    """
    Function to return name of a person if steamid exits in given records
    and return 'Unknown' otherwise.
    """
    return player_records.get(steamid, 'Unknown')

So instead of iterating over the entire list of player_records every time you look someone up, it iterates over your whitelist and blacklist each once at startup-time, making them thereafter be O(1) to search by steamid (which is the only kind of search you ever do).


should the model method be identify! or is identify proper?

You should only end the method name with a bang (!) if the method modifies the object it is called on.  Furthermore, only if there is also another method of the same name without the bang which does not modify the object.  So no, you should not use a bang in your method name.

  return nil vs throw exception

I would take a cue from either ActiveRecord#find or #find_by_*.  The first will throw an exception when given an ID that doesn't exist.  The later will return nil.  Think of it as entering a URL in your browser as opposed to doing a Google search.  With the first, it's expected that you know the exact URL, with the later, it's not and you should get some sort of result or lack of result.  According to what you say, you should be going with throwing exceptions.

However, I would rethink how you're doing things.  I would do this with initialize instead of having to explicitly call populate_data.


Detecting connected acyclic through Tarjan strongly connected components variant

I don't think graph algorithms work well with functional programming: you have to track which nodes were already visited and that pretty much requires global mutable state. You can simulate mutable state in a purely functional way by adding a parameter and a return value to the graph-walking function, but that quickly becomes tedious.

Because of that, I think that using imperative F#, or maybe even better, C# is a good choice here.

Your code does not tell you whether the graph is weakly connected, it tells you whether all nodes are reachable from the first node. (I'm assuming you're not interested in strongly connected graphs, because that implies cycles.) For example, given:

let aLine = function
| 0 -> [1]
| 1 -> [2]
| 2 -> [3]
| 3 -> []

Then (kindOfGraph aLine 0 4).connected returns true, while (kindOfGraph aLine 1 4).connected returns false. I don't know whether this is a bug in the code or whether you're misusing the word "connected" to mean something different, I could imagine both being the case.

I don't like that you're representing the graph as a function (plus the first node and size). I think that graph should be a self contained data structure, maybe something like Map<int, int list>.

I don't understand why are you using Tarjan's algorithm here.

To find out whether a graph contains cycles, DFS is enough.

To find whether all nodes are reachable from a specific node, simplified DFS (that doesn't try other starting nodes) will work.

To find whether a graph is weakly connected is more complicated. I think the simplest way would be to convert it to an undirected graph (by adding the reverse of each edge) and then performing DFS on that.

Since you're not actually interested in the connected and acyclic properties separately and since you're aware that your code is not always accurate when it comes to being acyclic, I would return only a single boolean value, not a record with misleading field names.


I don't know sqat about coldfusion, but it seems you could eliminate some duplication:

<cfsavecontent variable="mytest">
    [
    <cfoutput query="getimeline">
    {"title":"#name_time#","date":"#dateformat(date_time,"mmmm d, yyyy")#"}<cfif (getimeline.CurrentRow NEQ getimeline.RecordCount)>,</cfif>
    </cfoutput>
    ]
</cfsavecontent>

<cffile action="write" file="C:test.txt"  output="#mytest#">

If you don't mind that the comma will get placed on the next line,
then you can use this more readable writing style:

<cfsavecontent variable="mytest">
    [
    <cfoutput query="getimeline">
    {"title":"#name_time#","date":"#dateformat(date_time,"mmmm d, yyyy")#"}
    <cfif (getimeline.CurrentRow NEQ getimeline.RecordCount)>,</cfif>
    </cfoutput>
    ]
</cfsavecontent>

<cffile action="write" file="C:test.txt"  output="#mytest#">


The parents method will traverse the DOM all the way up the chain. Rather use the closest method, which will stop at the first match:

$('.add').on('click', function(e) {
    e.preventDefault();

    var number = $(this).closest('.tab_content').attr('id').split('_')[1];

    alert(number);
});


Dividing a ThreadPool class into component classes to reduce/isolate complexity

There are way too many member variables:

unsigned int numberOfThreads;
std::vector<std::thread> workers;
unsigned int availableThreads;

Can you not find the number of threads with workers.size(). What's the difference between number of Threads and Available Threads and more importantly why do you need to know!

You have three mutex's and two condition variables! Why? Also why are you putting the unique_lock as a member of the class! That would make them hard to use in a shared context.

Normally I would expect to see:

//In class:
    std::mutex               lock;
    std::condition_variable  sync;

//Adding Stuff Function:
    std::lock_guard   guard(lock);
    queue.push(item);
    sync.notify();

//Taking stuff from Queue
    std::lock_guard   guard(lock);
    sync.wait(guard, [queue](){!queue.empty();});
    if (!queue.empty()) {
        result = queue.pop();
    }

The only method that should be public on that class is adding a new job. All other methods are private members.

This is what mine would look like this:

class WorkQueue
{
    private:
        std::vector<std::thread>            threads;
        std::deque<std::function<void()>>   queue;
        std::mutex                          lock;
        std::condition_variable             sync;
        bool                                finished;

        std::function<void()> getWork();
        void work();
    public:
        WorkQueue(int threadCount);
        ~WorkQueue();
        template<typename F>
        void addWork(F&& func);
};


AutoDictionary for objects with a key property

The single most surprising thing that jumps at me is that an AutoDictionary doesn't implement IDictionary, and therefore can't be used as such. This is a rather major oversight, enough to be a showstopper in deciding whether or not I would use this data structure or not.

Short of implementing and exposing an Add(object, object) method, this AutoDictionary is simply not a dictionary as far as client code is concerned - it's a [keyed] collection, or an enumerable, but not a dictionary.

I would definitely try to find a way to implement the generic IDictionary<TKey,TValue> interface on top of IDictionary, too.

How? Well you already have a TKey generic type parameter, so a generic dictionary implementation would definitely be easy. The non-generic interface could validate the type of the key parameter (e.g. the first object in the Add(object, object) method) and throw some ArgumentException if the type can't be cast to TKey.

I'd also add a constructor that intakes the IDictionary dependency:

public AutoDictionary(IDictionary<TKey, TItem> source, Func<TItem, TKey> keySelector)
    : this(keySelector)
{
    _items = source;
}

Accepting a generic dictionary constrained with TKey would make the _items assignment compile and guaranteed to work, but would would still need to validate that the existing keys are those returned by the keySelector, and throw an exception otherwise.

Why is the second generic type parameter named TItem, when every IDictionary reference in the framework names it TValue? That's another rather surprising detail.

This is bad:

public void CopyTo(TItem[] array, int arrayIndex) { }

The method should at least throw a NotImplementedException. This no-op member is part of the interface, the contract you've signed when you decided to implement it: IMO leaving it unimplemented breaks the Liskov Substitution Principle, which means your implementation cannot be used in place of any other ICollection implementation. It should populate the array parameter with all values in stored in _items.

The class isn't sealed, which means a new class could be derived from it. Consider implementing the interface members as virtual, so their implementation could be overridden in inherited types - or outright seal the class.


This is perfect use case for group_by, which basically does all the work for you in a single line:

We also get the added benefit of having the user ids as arrays instead of strings.  This makes more sense, and if for some reason you do want to get the string representation back, you can simply call join(' ') on the array of user ids.

Finally, if you add more servers to your cluster, you just need to edit the single line defining the server names at the top of the file, and everything will still work.

users = (1..255) #<= Amount of users
servers = %w(calculon darth invader_zim)
server_capacity = 100

assigned_users = users.group_by.with_index do |u, i|
  all_servers_full = (i >= servers.size * server_capacity)
  all_servers_full ? 'failsafe' : servers[i % servers.size]
end

assigned_users.each do |server, users|
  puts "#{server} server has #{users.size} users"
end


Is this "unsafe" declaration unnecessary?

unsafe is purely a compile-time check. If it were needed the code wouldn’t compile. The runtime errors are caused by something else.

Furthermore, unsafe is needed if and only if you are using unmanaged pointers (e.g. inside a fixed block).


Selecting employees and updating a DataGridView

Naming is important, C# uses Pascal casing for classes and methods, so you should use EmployeeData instead of employeeData, and UpdatePerson instead of updatePerson
Fields live in classes and thus you don't need to give them a class prefix

private string FirstName { get; set; }
private string LastName { get; set; }
private string Age { get; set; }

C# has a type system that you can use instead of declaring everything as a string

private int Age {get;set;}

updatePerson uses the verb update, and methods with verbs usually do/change things with side-effects but your method just converts the object to a string[], and to be honest, I don't see any need for this method.


Categorize & sub categorize from contents of one row and more execute even more queries in results

PDO has some rather handy fetching options.  FETCH_GROUP is good for grouping the first level (product categories), but some extra handling is necessary to group the second level (product name-sizes).  To perform this nested grouping, I'll show the implementation of a temporary variable to track whether or not the current iteration is processing a new group or the same group as the previous iteration.

It is important to point out that you should not be making multiple trips to the database.  Since this script can be sensibly executed with a single trip to the database, it should be.
Prepared statements should be used for stability/security.

 tags must live inside
 tags for proper html markup.

Tested Code:

$products = ['Tshirt', 'Trousers'];
$placeholders = str_repeat('?,', count($products) - 1) . '?';

$stmt = $conn->prepare("
     SELECT SUBSTRING_INDEX(product_type, '-', 1) AS product_group, product_type, text
     FROM sales
     WHERE SUBSTRING_INDEX(product_type, '-', 1) IN ($placeholders)
     ORDER BY product_type
     ");
$stmt->execute($products);
$results = $stmt->fetchAll(PDO::FETCH_GROUP);
foreach ($results as $productGroup => $subarray) {
    echo "
{$productGroup}
";
    $typeGroup = null;
    foreach ($subarray as $row) {
        if ($row['product_type'] != $typeGroup) {
            if ($typeGroup) {
                echo "

";
            }
            echo "

{$row['product_type']}

";
        }
        echo "
{$row['text']}
";
        $typeGroup = $row['product_type'];
    }
    echo "

";
}

Sample data / Rendered output:

...yeah, didn't try very hard on the images.


Combine keycode regex and variable array

There are two items I can see here which concern me. The first is that, if you have already computed the prohibetedKeyPressed, why not make the boolean check fail-fast? In other words, put the !prohibitedKeyPressed before the regex so that you don't have to do the regex when there's a prohibited key?

I would actually take that further, and turn your code in to guard-clauses:

searchBox.keyup(function (e) { // DYNAMIC AUTO SEARCH FUNCTION

        if ([112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123].indexOf(e.which) > -1) {
            return;
        }

        if (!String.fromCharCode(e.which).match(/[^A-Za-z0-9 ]\x08/)) {
            return;
        }

        // code to execute if key is allowed

});

That makes the return criteria clear.

Now, the regex should probably be anchored.... but worse than that, the expression is a double-negative - if not the char is not a letter/digit.... do something. Now that I look more closely, it does not work at all..... it will never match anything. The \x08 needs to be inside the character class.... hmmm... have you tested this? The search will always happen because the single key-press will never be a single-character and a backspace.... so, the ajax call will happen whenever a non function key is pressed.....

I would make the code:

if (String.fromCharCode(e.which).match(/^[A-Za-z0-9 \x08]$/)) {
    // do something with it - call ajax
}

Now, having done that, why do you need the initial not-a-function-key check at all? Can't the whole thing just be a positive test?

searchBox.keyup(function (e) { // DYNAMIC AUTO SEARCH FUNCTION
    if (String.fromCharCode(e.which).match(/^[A-Za-z0-9 \x08]$/)) {
        // do something with it - call ajax
    }
}


Grouping consecutive numbers into ranges in Python 3.2; third version (accepts page numbers as an unsorted set)

def range_find(pageset):

    pagerangelist=[]

    for page in list(pageset):

There is no point in listifying the set just to iterate over it. I think you meant for page in sorted(pageset) to get access to the page in sorted order.

        if page in pageset and page-1 in pageset:pagerangelist[-1].append(page)
        elif page in pageset and not (page-1 in pageset):pagerangelist.append([page])

You still make it hard to read by putting those on the same line.

    pagerangestringlist=[]

If you've got multiple words I suggest under scores. I also suggest dropping types like list/set from your names. I'd call this page_range_strings.

    for pagerange in pagerangelist:

        if len(pagerange)==1:pagerangestringlist.append(str(pagerange[0]))
        else: pagerangestringlist.append(str(pagerange[0])+'-'+str(pagerange[-1]))

I'm going to recommend using string formating. It'll be easier to read then concatenating strings.

    return ','.join(pagerangestringlist)


Fast case-insensitive hash-code for specific codes

There isn't much left to optimize there, just few cycles, but with 40 millions calls the difference might be at least measurable.

When value.length == 3 you perform << 8 twice and csc or JIT compiler have no chance to optimize this, given that length can be only 2 or 3 then you can make it explicit (I think you will also gain in clarity but that's just a point of view):

public static int Encode(this string value)
{
    Debug.Assert(value != null);
    Debug.Assert(value.Length == 2 || value.Length == 3);

    if (value.Length == 2)
    {
        return ((int)value[0] << 8)
            | EncodeLetter(value[1]);
    }
    else
    {
        return ((int)value[0] << 16)
            | ((int)value[1] << 8)
            | EncodeLetter(value[2]);
    }

    int EncodeLetter(char c)
        => c > 'Z' ? (return c - CaseFix) : (c);
}

In this way you should save one shift << (which isn't super-fast in all .NET environments). Also direct access to string items without value.Length - 1 should be slightly faster. Bitwise OR | may be faster than sum + but it depends on an huge amount of details (specific CPU, in primis, and how uop will be fused with surrounding code)...not something we can determine without more details. Here I like it only because of clarity.

It would be nice if we may get the JIT compiler to drop bounds checking here, is unsafe code allowed here?

I added few Debug.Assert(), not a penalty price you want to pay in released code but probably useful when running tests on your own development machine.

About Decode(): "9Z".Encode() might be saved in a static readonly field (in my case it seems it's not optimized away by compiler/JIT).


GroupBy by nodeJS or ES6 of very nested JSON Objects with condition

A few thoughts;

Most would write const flatFeature = []; to initialize an array in javascript, though what you have is certainly correct.
You should strive to de-nest your code.  Having code unnecessarily placed in if or if-else blocks increases the number of paths through your code, making it harder to follow and unit test.  In this case, you could de-nest by changing your first if to something like if (!subscription.plan || !subscription.plan.feature) return; which clearly indicates that there is no work to do in this function unless those conditions are met.
You should strongly consider using an object to map your flatFeature names to the objects encountered with greatest expiration date.  That eliminates the looping find() operation to determine if an existing flatFeature with that name has already been encountered, making this a constant time lookup.  This may not be a big deal if there are 100 subscriptions being iterated, but what if there are 1 million?
Taking above approach of building a name-keyed object gives you flexibility to continue to work against those keyed feature names or you can simply use Object.values(obj) to get the array of feature objects.
Stylistically, your code looks somewhat "dense" and has long horizontal lines (especially your ternary) that make code harder to read and understand at a glance.  Using javascript's destructuring can oftentimes help in keeping your code more terse and thus more easily read.

Putting it together, I might use something like:
const features = allActiveSubscriptions.reduce(
  (obj, sub) => {
    const { plan: { featuresList }, expDate } = sub;

    if (!featuresList) return obj;

    featuresList.forEach( ({ name }) => {
      const existFeat = obj[name];

      if (!existFeat) {
        obj[name] = { name, expDate };
        return;
      }

      if (expDate > existFeat.expDate) {
        existFeat.expDate = expDate;
      }
    });

    return obj;
  },
  {}
);

// if you want an array
const featArray = Object.values(features);

In terms of worst-case operational efficiency, this makes your function perform in O(m x n) as opposed to O(m x n x p) as it is currently (where m is number of subscriptions, n is maximum feature list size, and p number of unique feature names).


Add 1 to a number represented as an array of digits, using recursion

First of all, please be consistent: int[] digits is the norm, but you also wrote String args[] and int [] digits.  Classes are normally named with an initial uppercase (PlusOne).  It is also customary to put a space before and after binary operators and after each comma, as well as after the if keyword.

There isn't any point in instantiating a plusOne object, when all you want is a function.  Therefore, you should have public static int[] plusOne(int[] digits).  The increment function is a helper; it should be private static int[] increment(…).

It's weird that the operation usually operates on the array in place, but sometimes writes "junk" to that array then returns a new one.  Perhaps that is a consequence of the nature of the problem, but it's an issue that should be clearly documented in JavaDoc.

In Java, it is usually preferable to avoid recursion (due to concerns about stack overflow and performance) if the problem can also be easily solved using iteration — as this problem can.  If you do use recursion, though, I recommend structuring the code to make it more obvious that there are two base cases and one recursive case.  The way the index == 0 case sets newDigits[digits.length] = 0 feels weird: it doesn't work locally the way recursion should.  If you're going to make the assumption that it's OK to plop a 0 at the end, you might as well assume that you want a 1 followed by 0s everywhere else, in which case you could just do new int[digits.length + 1].

public class PlusOne {

    private PlusOne() {}  // Suppress the default constructor

    /**
     * Adds one to an integer that is represented as an array of digits
     * (most-significant digit first).
     *
     * @return The returned array may or may not be the same array
     *         as the input.  In either case, the contents of the
     *         input array will be overwritten.
     */
    public static int[] plusOne(int[] digits) {
        return increment(digits, digits.length - 1);
    }

    private static int[] increment(int[] digits, int index) {
        if (digits[index] != 9) {
            digits[index] += 1;
            return digits;
        } else {
            digits[index] = 0;
            if (index > 0) {
                return increment(digits, index - 1);
            } else {
                int[] newDigits = new int[digits.length + 1];
                newDigits[0] = 1;
                return newDigits;
            }
        }
    }
}


Which way should I use while writing this method?

From the way you describe the problem, it is clear that there only needs to be one method. That method is supposed to: "... prompts the customer for the car type. ... Your method will return a valid car type".

What you have presented here, is the guts of some code which prompts the user for a character value, and then another method which converts the char to a String type.

From what I can tell (and filling in some blanks) your code looks functional, but I am not certain it satisfies the requirements (for just one method).

I would start with the 'specification' for the method, and use that as a template for the code. I will make the assumption (as you have) that the method should return the 'full' name of the car type (i.e. return "Economy" instead of 'E').

The good things in your code are the use of the do {...} while(...) block. You have a good loop there, with good conditional exit criteria.

You have not shown us what input is so I will assume it is a Scanner on System.in.

If we wrap the code you have there with a method that makes sense, it would be something like:

public String promptForCarType(Scanner input) {
    .....
    return carType;
}

That would be a method that prompts the user for a car type, and returns the user's selection.

The code inside that is what you have written above. There are a few things you should consider though:

You should probably get the full input from the user (not just the first character), and make sure the user only entered a single character (data validation).
Do you know what a 'switch' statement is? It would be really neat in here (and would remove the need to call the carType(char) method).
When you have java methods that return a value, there is often no need to 'store' the return value to the end of the method... you can just return when you have it....
when dealing with user input, you should try to leave them an 'exit strategy', like "enter Q to quit"
if you do an early-return mechanism, there is no need to do any conditions in the loop, you can just do while (true) {...}

One possible method for you may be something like:

public String promptForCarType(Scanner input) {
    System.out.println("(E) Economy  - 50 TL");
    System.out.println("(M) Midsize  - 70 TL");
    System.out.println("(F) Fullsize - 100 TL");
    // add in a Q option here ....
    // the Scanner may not have input....
    while (true) { // convert to while loop.
        System.out.println("Enter the car type (E/M/F) : ");
        if (!input.hasNext()) {
            throw SomeExceptionToSayTheresNoMoreInput(....);
        }
        String userinput = input.next();
        // check that input is just one character long.....
        char type = userinput.charAt(0);
        type = Character.toUpperCase(type);
        switch (type) {
            case 'E' : return "Economy";
            .....   // other cases
            case 'Q' : throw new UserWantsToQuitException(".....");
            default : // no need for a default, the loop will just go around again
        }
    }
}


Your code defines a function with a clear input and a clear output. Also, you've put the call to it behind the if __name__ == '__main__':. You've taken good habits on this points. Nonetheless, a few things can still be improved.

Python version

If you are learning Python, there is no good reason to start with Python 2 which is reaching its end of life. You should focus on learning Python 3, going to be supported for a while and with various warts corrected (and obviously more features).

In any case, the sets module is not required since Python 2.6 since we have the set builtin.

Style

There is an official standard Python style guide called PEP 8. This is highly recommended reading. It gives guidelines to help writing code that is both readable and consistent. The Python community tries to follow these guidelines, more or less strictly (a key aspect of PEP 8 is that it provides guidelines and not strict rules to follow blindly).

It deals with various aspects of the code style: naming conventions, indentation convention, etc.

You'll find various tools to try to check whether your code is PEP 8 compliant and if is it not, to try and fix this:

pycodestyle package (formerly known as pep8) to check you code
pep8online to check your code with an online tool
autopep8 package to fix your code automatically
Also, this is also checked by various linters: pylint, pyflakes, flake8, etc.

In your case, the major points I would fix are:

indentation should be 4 space
function names should snake_cased
you could try to take into account the advice to use join instead of "CPython's efficient implementation of in-place string concatenation".

Naming

On top of the snake-case point mentioned above, a few things could be improved in the naming. Naming is a difficult part of programming so what I suggest are just personal, far from perfect, suggestions (from a non-native English speaker). In your case, I'd call the function tranform_string so that it conveys the fact that:

it is an action (a noun would correspond to an object/class name)
it applies to string (and not to single character even if the distinction is fuzzy in Python compared to other programming languages)

The name str is a bit of a problem because it hides the str builtin. I do not find any alternative better than str_ which is still pretty poor :-(.

Edit: I don't know why I didn't think about "s" in the first place but after reading it in another answer, it looks like a much better option indeed. I am too lazy to edit my code everywhere.

Finally, i is a good name for an (integer) index. For a single character, c seems easier to understand (char if you feel verbose).

Chained comparison

In Python, you can chain comparison. If your case, you can write:

elif 97 <= ord(cur_char) < 122:

More beautiful character check

From the Zen of Python:

  Beautiful is better than ugly.
  Explicit is better than implicit.
  Simple is better than complex.

In your case, you could avoid the call the ord and get rid of the magic number by writing the simple:

elif 'a' <= cur_char < 'z':

Rewriting the logic

You could have the logic adding a character to new_str in a single place.

    cur_char = c.lower()
    if cur_char == 'z':
        new_char = 'A'
    elif 'a' <= cur_char < 'z':
        new_char = chr(ord(c) + 1)
        if new_char in vowels:
            new_char = new_char.upper()
    else:
        new_char = c
    new_str += new_char

Then, you could try to makes the logic as close as possible to the way it is given in the problem for instance by making "z" a special case only for the operation where you take the following letter.

    low_char = c.lower()
    if 'a' <= low_char <= 'z':
        new_char = 'a' if low_char == 'z' else chr(ord(c) + 1)
        if new_char in vowels:
            new_char = new_char.upper()
    else:
        new_char = c
    new_str += new_char

Shorter way to define vowels

Because strings are iterable and set takes any kind of iterable, you could write:

vowels = set('aeiou')

Better ascii check

You could reuse values from the string module to make your test more beautiful:

   if low_char in string.ascii_lowercase:

Removing string concatenation

As mentionned earlier, it is advised not to use string concatenation and use join instead, when relevant.

At this stage, the code (with added tests) looks like:

import string

def transform_string(s):
    vowels = set('aeiou')
    lst = []
    for c in s:
        if c in string.ascii_letters:
            new_c = 'a' if c.lower() == 'z' else chr(ord(c) + 1)
            if new_c in vowels:
                new_c = new_c.upper()
        else:
            new_c = c
        lst.append(new_c)
    return "".join(lst)

if __name__=='__main__':
    assert transform_string("")            == ""
    assert transform_string("qwertyuiop")  == "rxfsUzvjpq"
    assert transform_string("asdfghjkl")   == "btEghIklm"
    assert transform_string("zxcvbnm")     == "AydwcOn"
    assert transform_string("1234567890")  == "1234567890"
    assert transform_string("QWERTYUIOP")  == "RXFSUZVJPQ"
    assert transform_string("ASDFGHJKL")   == "BTEGHIKLM"
    assert transform_string("ZXCVBNM")     == "AYDWCON"
    assert transform_string("(){}<>+_-=")  == "(){}<>+_-="


Bash Compress Managed Directory Ignoring .git, bower_components, node_modules, etc

I'm just going to poke at some of your unix conventions and validation.

Your general handling looks polished. I like the way that you handle whether this is an interactive terminal, but wonder whether it would simply be better to use the more standard check for $PS1 or the i flag ( reference here ). If you are going to use tty to tell, you should probably rely on the exit status rather than the text message.

The way you find the user directory is great, and is similar to what I normally do too. There are some variations on it, but it is more than good enough.

This next one is the one that concerns me most though:

if [[ -z $1 ]]; then
  echo "Usage: managed_directory_compressor /your-directory/ zip-file-name"
else
  .....

That code has three problems....

your script takes 2 parameters, but you only check for 1.
if the parameter is missing, you still exit with a success exit code (0). You should exit with something else .. (like 1).
there is no need for an else condition. Treat it like a guard-clause...

This is how I would do it (and I would use $# and not $2 because having too many arguments is as bad as not having enough....

if [[ $# -ne 2 ]]; then
  echo "Usage: managed_directory_compressor /your-directory/ zip-file-name"
  exit 1
fi

Then there is no need to indent, or so on, for the remaining code.

The remaining code looks relatively good. There's no error handling on the zip operation though.

One last thing, your first comments are duplicated:

# This script zips a directory, excluding specified files, types and subdirectories.
#  while zipping the directory it excludes hidden directories and certain file types

If you're going to comment things, make them good.


Finding hidden field values in a web page before submitting a login form

Whenever chaining awk together with grep, sed, head, tail or other text processor tools, consider the possibility of doing it all with just awk, as it's very powerful. Reducing the number of processes in the pipeline makes sense, and in some examples can drastically improve performance.

Here's one way to write the two lines of pipelines as a single line (expanded to multiple lines for readability):

awk -F '"' '
    /csrf1/ {csrf1 = $4 "=" $6}
    /csrf2/ {
      csrf2 = $4 "=" $6;
      if (count++ > 0) {
        print csrf1 "&" csrf2;
        exit;
      }
    }' signup.php

That is:

When you see a line matching "csrf1", save it
When you see a line matching "csrf2", save it, and:

If this is the first time, increment the count and do nothing else
If this is the second time, print csrf1 and csrf2 and stop processing

Note that the algorithm overwrites the first csrf1 and csrf2 values that were seen, and print only the second time.

I also used -F '"' instead of -F "\"" because it's easier to both write and read.

And if you want to save the result of this in a variable, then instead of:

CSRF=`awk ...`

Use the modern $(...) syntax:

CSRF=$(awk ...)


To test these things the first thing I usually do is wire in a sameThreadExecutor; if you don't want a dependency you'll have to write your own but it's just an implementation of ExecutorService that calls its callable immediately and returns a completed future.

The aim is to replace the async part of your code with something synchronous. The mocking could be done with Mockito, it's just very unwieldy. You would have to mock the task executor with a doAnswer:

Mockito.when(taskExecutor.call(any())).thenAnswer((invocation) -> ... ugly work goes here ...)

For safety you might want to add timeout parameters to the call() method and handle timeout exceptions (cancel the timed out future).


I'm not an expert on multithreading at all, but I've attempted refactoring your code a bit.
First of all, to code defensively, I suggest adding the readonly modifier to your lock object. It's not required but will prevent accidental assignments:

private static readonly object syncRoot = new object();

I'm against incurring the complexity of an out argument: let's just check if the timer exists. We can stop it and remove it if it does; setting DispatcherTimer.IsEnabled isn't necessary because DispatcherTimer.Stop() sets it to false anyway:

if (timers.ContainsKey(namedInvocation))
{
    timers[namedInvocation].Stop();
    timers.Remove(namedInvocation);
}

We can get rid of the object initializer because DispatcherTimer has the perfect constructor for us anyway; this has the added benefit of inlining the lambda:

var timer = new DispatcherTimer(delay, priority, (s, e) => action(), dispatcher);
timer.Start();
timers.Add(namedInvocation, timer);

Again, remember we don't need to set IsEnabled because DispatcherTimer.Start() sets it to true for us (alternatively, you can leave it in place but remove the call to Start(). But the method call seems more intuitive to me; setting a property doesn't make it obvious that the timer has been started).

You may have noticed I used var wherever it seemed appropriate; it's just as type safe as using the actual type but takes up less space, both on the page in in my brain.

That leaves us with the following end result:

public static class DispatcherExtensions
{
    private static Dictionary<string, DispatcherTimer> timers =
        new Dictionary<string, DispatcherTimer>();
    private static readonly object syncRoot = new object();

    public static void DelayInvoke(this Dispatcher dispatcher, string namedInvocation,
        Action action, TimeSpan delay,
        DispatcherPriority priority = DispatcherPriority.Normal)
    {
        lock (syncRoot)
        {
            if (timers.ContainsKey(namedInvocation))
            {
                timers[namedInvocation].Stop();
                timers.Remove(namedInvocation);
            }
            var timer = new DispatcherTimer(delay, priority, (s,e) => action(), dispatcher);
            timer.Start();
            timers.Add(namedInvocation, timer);
        }
    }
}

In case I introduced a bug or if you have improvements, let me know in the comments.

Edit: supporting cancellation

(@svick's suggestion)

To provide the possibility of cancelling your timers, you would factor out the timer removing logic (I inverted the condition to reduce nesting...) into a new method that is called at the beginning of DelayInvoke.

private static void RemoveTimer(string namedInvocation)
{
    if (!timers.ContainsKey(namedInvocation)) return;
    timers[namedInvocation].Stop();
    timers.Remove(namedInvocation);
}

Then, you'd create another extension method (first parameter is useless, but calling the method via the Dispatcher is consistent and convenient, so I left it there). Something like this:

public static void CancelNamedInvocation(this Dispatcher dispatcher, string namedInvocation)
{
    lock(syncRoot)
    {
        RemoveTimer(namedInvocation);
    }
}


Sort characters in a Python string by frequency

The “set or increment dictionary value” logic

freq = {}
for i in s:
    if i in freq:
        freq[i] +=1
    else:
        freq[i] = 1

can be simplified using a defaultdict:

from collections import defaultdict

# ...

freq = defaultdict(int)
for i in s:
    freq[i] += 1

But instead of creating, updating and sorting your own dictionary you can
use the built-in Counter class:

  A counter tool is provided to support convenient and rapid tallies.

and its most_common() method:

  Return a list of the n most common elements and their counts from the most common to the least.

That simplifies the code to

from collections import Counter

def frequencySort(s):
    """
    :type s: str
    :rtype: str
    """
    counter = Counter(s)
    output = "".join(char * freq for char, freq in counter.most_common())
    return output


I modified the formatting part for better readability and maintainability, at the cost of lower performance:

var columns = new Dictionary<string, Func<Reads, object>>
{
    ["Read Date"] = x => x.CurrentReadDate,
    ["Device"] = x => x.DeviceKey,

    ["Suffix"] = x => x.Suffix,
    ["Read"] = x => x.CurrentReadRawValue,
    // add the rest of headers/property selectors below
};
//var format = "{0},{1} : {2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27}";
var format = "{0}{1} : " + string.Join(",", columns.Select((_, i) => $"{{{i}}}").Skip(2));

var csv = new StringBuilder()
    .AppendFormat(format, columns.Keys.ToArray())
    .AppendLine();
foreach (var read in reads)
{
    var values = columns.Values.Select(selector => selector(read));
    csv
        .AppendFormat(format, values.ToArray())
        .AppendLine();
}

The advantage of this approach is that you can add/move/remove the columns without having to worry about updating the header and the format, and if they are kept in sync or not.

Note:

You can also revert to the constant format if it becomes more complex.
The property selector can be chained if you need special format on individual property, like: x => x.CurrentReadDate.ToString("yyyyMMddThhmm")


Tic Tac Toe getWinner() method logic for a grid of any size nxn

You should declare the variables by using the smallest scope that is needed. By omitting the scope specifier (private,public etc) the variable can be accessed by the classes which are in the same package.

So for your class you should declare them private.

If the name of a method implies something like getN() one expect to get exactly that what is implied by the name. You are returning size which is n * n. You should store the n which is passed inside the constructor and return it in this method.

Storing n will help you a lot more than only for this method. Every time you are using Math.sqrt(size) you could just use n instead.

Using braces {} for single if statement or single line loop statements will make your code less error prone.

You don't use the isValidMove() method. In addition one wouldn't expect for a invalid move that the next player would become "".

You need to implement this method and it should be called first at the move() method and if it returns false you should throw an IllegalArgumentException.

The getCurrentPlayer() method doesn't need a while loop. A simple if statement would be enough.

For the getWinner() method you should consider to store the last player in a variable. In this way you wouldn't need to check for .Equals("X") nor .Equals("O").

If you also store the last move, you don't need the checks for diagonal lines if the last move isn't in the middle or in the corners.

Assuming a 5x5 grid and player X will make his move

X _ _ _ _    _ _ _ _ _    _ _ _ _ _
_ _ _ _ _    _ _ _ _ _    _ _ _ _ _
_ _ _ _ _    _ X _ _ _    _ _ X _ _
_ _ _ _ _    _ _ _ _ _    _ _ _ _ _
_ _ _ _ _    _ _ _ _ _    _ _ _ _ _
    1            2            3

For the first example you need to check horizontal and vertical based on the moves position and the diagonal from the upper left corner to the lower right corner.
For the second example you need to check only horizontal and vertical.
For the third example you need to check horizontal, vertical and both diagonals.

The horizontal check

For the horizontal check we need the current row where the move had been made. This row can be computed by dividing the current move by n. To get the first position of this row we multiply the row by n to get the start position of the checking loop.

int startPosition = (lastMove / n) * n;

You need to keep in your mind that by dividing 2 int you will get an int back.

Let us check this for examples

Example 1:

startPosition = (0 / 5) * 5 == 0

Example 2:

startPosition = (11 / 5) * 5 == 10

Example 3:

startPosition = (12 / 5) * 5 == 10

So now we have a starting position for the horizontal checking loop we can add a method to check the horizontal line. In the loops body we will check if the current position of the board does not equal the last player so we can return early.

Private boolean isHorizontalWin(int lastMove, String lastPlayer) {
    int startPosition = (lastMove / n) * n == 0
    for (int i = startPosition; i < startPosition + n; i++) {
        if (!board[i].equals(lastPlayer)) {
            return false;
        }
    }
    return true;
}

The vertical check

For the vertical check we need the current column. This column we can compute by subtracting n from the current move until the result is < n. Let us add a method for this.

private int getCurrentColumn(int lastMove) {
    while (lastMove >= n) {
        lastMove -= n;
    }
    return lastMove;
}

This is now the starting position for the vertical checking loop. The iterating variable needs to be incremented by n.

But what is the ending condition?

Example 1:

we have a startPosition == 0  and the last check should be performed at board[20]

Example 2:

we have a startPosition == 1  and the last check should be performed at board[21]

Example 3:

we have a startPosition == 2  and the last check should be performed at board[22]

So for all three examples:

for (int i = startPosition; i < size ; i += n) {

}

The diagonal check(s)

Here the starting positions are clear. It is the upper left corner so 0 and the upper right corner so n - 1.

If we loop from the upper left to the lower right, the last position to check is size -1.

If we loop from the upper right to the lower left, the last position to check is size - n.

Let us use new samples for getting the value of which we need to increment the iterating variable.

n == 3

0 1 2
3 4 5
6 7 8

Here if we check upper left to lower right, we need to increment by 4. From upper right to lower left we need to increment by 2.

n == 5

 0  1  2  3  4
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

Here if we check upper left to lower right, we need to increment by 6. From upper right to lower left we need to increment by 4.

Again we see a pattern:

upper left to lower right: n + 1
upper right to lower left: n - 1

You need, for implementing the missing points, to add methods for

checking if the move is a special move, in other words

does the last move needs a winning check for the upper left to lower right diagonal
does the last move needs a winning check for the upper right to lower left diagonal

checking if the current player has

vertically won
left to right diagonal won
right to left diagonal won

This would lead to the refactored getWinner() method which could look like

public String getWinner() {
   if(isHorizontalWin(lastMove, lastPlayer)) {
       return lastPlayer;
   }
   if(isVerticalWin(lastMove, lastPlayer)) {
       return lastPlayer;
   }
   if(isLeftToRightCheckNeeded(lastMove) && isLeftToRightWin(lastPlayer)) {
       return lastPlayer;
   }
   if(isRightToLeftCheckNeeded(lastMove) && isRightToLeftWin(lastPlayer)) {
       return lastPlayer;
   }
   return "";
}


Compare the index of each char in a string in an alphabet array to a range of numbers

There are two alternatives I can recommend, one alternative avoids all the if/else/if cascading, and replaces it with a single 'switch' statement. Switch statements are optimized at compile time so that, effectively, each char/operation takes as long as any other. it makes sense to extract that to a function too.
The second alternative is to trade code space, for memory space.
First though, improving your current solution...
Current version
Your current version has a lot of unnecessary conditions in the cascading if/else system.
If you check for 'low' values first, then you can assume the next value's lower range is already handled. It is easier to explain this by example.... you have:

if (index >= 0 && index <= 2) {
    currentButton = 2;
} else if (index >= 3 && index <= 5) {
    currentButton = 3;
} else if (index >= 6 && index <= 8) {

But this will produce the same results, with half the comparisons:
if (index < 0)
{
    currentButton = 1; //invalid index, char not found?
}
else if (index <= 2)
{
    currentButton = 2;
}
else if (index <= 5)
{
    currentButton = 3;
}
else if (index <= 8)
{

Note how I have also used the conventional C# style there for the braces....
1. Switch:
A switch statement can work on chars:
switch (currentLetter)
{
    case 'a':
    case 'b':
    case 'c':
        return 2;
    case 'd':
    case 'e':
    case 'f':
        return 3;
    .....
    default:
        return 1; // whatever you need for an invalid char
}

The above code (included in a function) will encode each char to a key, and unmapped chars will return 1.
2. In memory lookup
A second common way to do this is to prepopulate an array with the indexes for each char:
int[] keys = new int[]{2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};

Then use that array as a simple lookup:
if (currentChar < 'a' || currentChar > 'z')
{
    return 1;
}
return keys[currentChar - 'a'];

That converts the char to an offset in the keys array. I have taken the liberty of coding this up in Ideone to ensure it works (which it does, except for the handling of space characters)


Hex boardgame with fast random rollouts (OpenAI gym framework)

When reading this function alone, without any surrounding code, I wonder where the initial + 1 for the position comes from. That looks like an off-by-one bug to me. I don't know whether it is indeed a bug, it's just suspicious.
The calls to tuple() look redundant since the current_position already is a tuple. Doesn't your IDE warn about such things?
The word position is a bad name since it is ambiguous. It could either mean an (x, y) tuple or the complete (board, player_to_move) tuple, like in the sentence "in this position, Red should resign". A better name would be last_move or prev_move.
Is there a good reason why you use a tuple at all? Having two variables x and y would make the code pretty clear. These variable names are short enough that you don't need the low_x and related variables anymore.
Do you need the call to tolist() at all?
Instead of generating a 2-dimensional matrix, it could be more efficient if you just took the 6 neighbor regions explicitly and individually. That way you also get rid of the pop(0). I don't know whether that is faster in Python though.


Gradient Boosting Class/Module using sklearn. (My first Python Module)

General: docstrings should explain the parameters.

features = df.drop('days_remaning', axis=1)
output = df['days_remaning']

You really ought to put 'days_remaning' into its own variable, declared either via a constant or read in from a configuration file, so that if the field name in your csv changes, you don't have to make the change in multiple places. Similar feeling for the file paths.

       print(f'Loading Local Model, product: {product}.')

This is not output of the program, but just logging its progress. So you should not be using print() but instead the logging module. That way you can configure where the logging goes (and if it's shown at all).

    if os.path.isfile(self.save_path):
        print(f'Loading Local Model, product: {product}.')
        self.model = joblib.load(self.save_path)
    else:
        print(f'Creating New Model, product: {product}.')
        self.model = self.create_model()

This seems odd to me. If the file already exists you load it, but if it doesn't exist you save it? This is actually a race condition since whoever is running this code doesn't know what behavior will happen, based on whether the file exists or is deleted. However I'm not sure what should be done here instead.

    params = dict(
        learning_rate=0.01,
        loss='ls',
        max_depth=4,
        max_features=0.3,
        min_samples_leaf=9,
        n_estimators=500
    )

The dict initializer syntax is more pythonic, and may save a function call.

    params = {
        learning_rate : 0.01,
        loss : 'ls',
        max_depth : 4,
        max_features : 0.3,
        min_samples_leaf : 9,
        n_estimators : 500
    }

but why are you even creating the params variable at all? Just call the function with named parameters!

def print_model_output(self, data: List[List[int]]) -> None:
    for output in self.use_model(data):
        print('In about {} to {} days you will need to buy new {}.'.format(
            math.floor(output), math.ceil(output), self.product))

This doesn't make sense. self.product won't change through this loop. I suspect there shouldn't be a loop at all, as there's never more than one product / output.

def calculate_error_rates(self) -> Tuple[float]:
    train_error = mean_absolute_error(
        self.y_train, self.model.predict(self.x_train))
    test_error = mean_absolute_error(
        self.y_test, self.model.predict(self.x_test))
    return train_error, test_error

This code strongly suggests that instead of two variables y_whatever and x_whatever you should instead have a 2-element tuple called whatever. Then you could get rid of some of this duplicated code.

    features_labels = np.array(['days_after_restock', 'left_content'])

Why an np.array here? What's wrong with a regular list?


First, your JS and CSS could do some indenting. It's barely readable.

Now, seeing that you use transforms and you use a 2.x.x version of jQuery, I can assume you're targeting a modern browser. Instead of using jQuery's animate, you can use CSS transitions on width instead. Trigger your accordion by adding and removing classes that change the value of width. Aside from lesser JS, CSS animations are mostly hardware accelerated. This, in simple terms, mean smoother animations.

If you have the luxury of a build step, I suggest offloading the task of adding prefixes to your CSS to a task runner. Grunt or Gulp, with Autoprefixer should be able to help you.

Additionally, I would recommend being uniform with CSS colors. If you write hex most of the time, make sure they're all in hex and avoid color names. If you mostly do 6-digit hex, then write in 6-digit hex and avoid the 3 digit ones. If you're worried about file size, let a compressor task like cssmin do it for you.


If you actually need to securely wipe your non-SSD drive consider using
shred, or look at some
of the linked pages too.

Also I don't see much point in the pseudo-random data generation given
that you just want to make the previous content unrecoverable.  If you
a want faster program you could probably use a faster hash too.

For the code I only want to note that write might write less than the
specified number of bytes and that's not immediately an error.


DOM querying is expensive
Search on Google for "js DOM query expensive" and you will likely find many posts from the past 10 years that discuss how in-efficient it is to be querying the DOM each time. Stop Writing Slow Javascript appears to be somewhat recent - see the section Cache DOM Lookups. This answer on SO about various DOM-selector functions will likely be interesting as well.
In the code below, notice that the variables searchBox and ul are declared at the top
var searchBox, ul;

Those variables don't get assigned until the callback for a new event listener for the DOMContentLoaded event is triggered.
document.addEventListener("DOMContentLoaded", function(event) {
    searchBox = getElementById('typeahead');
    searchBox.addEventListener('keyup', typeAhead);

    ul = document.createElement('ul');
    ul.setAttribute('id', 'searchResults')
    appendChild(document.body, ul);
    hideList();
    addEvent(ul);
});

You will also notice that in that event callback, the unordered list (i.e. ul) is added to the document and hidden. That way there is only one list ever added, and because of that, we can hide and show the list instead of removing it. The function removeChild can be replaced with a function hideList that will set the display style (using HTMLElement.style) to none. Additionally, the call to addEvent() was moved into that callback function, so we only add the event listener once. One could also use event delegation and have one click handler for the whole page - it would just handle clicks differently depending on the type of element clicked.
Keep the scopes limited
Another thing that article mentions is limiting the scope as much as possible (see the section Keep your scopes close and your scope even closer). One way to not clutter up the global namespace is to wrap the code with an IIFE:
;(function(window, document, undefined) {
    var data = ['alabama', 'alaska', 'arizona', 'arkansas', 'california', 'colorado', 'connecticut', 'delaware'];
    //...
})(window, document);

See the changes applied below. There are likely other improvements that can be made as well...

'use strict';;
;(function(window, document, undefined) {
  var data = ['alabama', 'alaska', 'arizona', 'arkansas', 'california', 'colorado', 'connecticut', 'delaware'];

  /**
   * variables: searchBox is where you type the city name, ul is the list of suggestions
   */
  var searchBox, ul;

  /**
   * methods
   */
  function getElementById(id) {
    return document.getElementById(id);
  }

  function iterate(arr, callback) {
    for (var i = 0; i < arr.length; i++) {
      callback(arr[i], i);
    }
  }

  var search = function(val) {
    var arr = [];
    iterate(data, function(item, index) {
      if (item.indexOf(val) !== -1) {
        arr.push(item);
      }
    })
    return arr;
  }

  var addEvent = function(elm) {
    elm.addEventListener('click', function(event) {
    console.log('list click - target: ',event.target,' currentTarget: ',event.currentTarget);
      if (event.target !== event.currentTarget) {
        searchBox.value = event.target.textContent;
        hideList();
      }
      event.stopPropagation();
    });
  }

  var appendChild = function(parent, child) {
    parent.appendChild(child);
  }
  var hideList = function() {
    ul.style.display = 'none';
    while (ul.firstChild) {
      ul.removeChild(ul.firstChild);
    }
  }

  var bindData = function(arr) {
    ul.style.display = '';
    iterate(arr, function(item, index) {
      var li = document.createElement('li');
      var a = document.createElement('a');
      a.textContent = item;
      appendChild(li, a)
      appendChild(ul, li);
    });
  }

  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this,
        args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) {
          func.apply(context, args);
        }
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) {
        func.apply(context, args);
      }
    };
  }

  var typeAhead = debounce(function(event) {
    hideList(); //removeChild();
    var value = event.target.value;
    if (value !== '') {
      var arr = search(value);
      bindData(arr);
    }
  }, 400);

  document.addEventListener("DOMContentLoaded", function(event) {
    searchBox = getElementById('typeahead');
    searchBox.addEventListener('keyup', typeAhead);

    ul = document.createElement('ul');
    ul.setAttribute('id', 'searchResults')
    appendChild(document.body, ul);
    hideList();
    addEvent(ul);
  });
})(window, document);
<input type="text" placeholder="type to search" id="typeahead">


FizzBuzz encapsulation In Ruby (identifying and separating concerns)

To this end, any feedback, criticism, or questions are greatly appreciated.

Here are some ideas to improve the code.
Split printing and logic
Might be debatable but from my POV the

The printing of the numbers

and

The logic for determining what should be returned

are not split.
One of the goals of object oriented design is to make the code easier to change. So imagine we want to implement now to print Boom if a number number % 10 == 0. How would we do this? We would need to implement a BoomNumber class and change FizzBuzzer and might even change the main method because fizz_value does not make sense anymore. Not good!
In this example we can just swap out the builder and it would work.
class PrintableNumber
  def initialize(name)
    @name = name
  end

  def to_s
    @name
  end
end

class BoomNumberBuilder
  def initialize(number)
    @number = number
  end

  def build
    PrintableNumber.new(name)
  end

  private

  attr_reader :number

  def name
    if boom?
      "Boom"
    else
      number
    end
  end

  def boom?
    number % 10 == 0
  end
end

class FizzNumberBuilder
  def initialize(number)
    @number = number
  end

  def build
    PrintableNumber.new(name)
  end

  private

  attr_reader :number

  def name
    if fizzbuzz?
      "FizzBuzz"
    elsif fizz?
      "Fizz"
    elsif buzz?
      "Buzz"
    else
      number
    end
  end

  def fizzbuzz?
    fizz? && buzz?
  end

  def fizz?
    number % 3 == 0
  end

  def buzz?
    number % 5 == 0
  end
end

class PrintableNumberCollector
  include Enumerable

  def initialize(collection, builder = FizzNumberBuilder)
    @collection = collection
    @builder = builder
  end

  def each
    collection.each do |item|
      yield builder.new(item).build
    end
  end

  private

  attr_reader :collection, :builder
end

puts "== Fizzer =="
fizzer = PrintableNumberCollector.new((1..10).to_a)
puts fizzer.map(&:to_s).join("\n")

puts "== Boomer =="
boomer = PrintableNumberCollector.new((1..10).to_a, BoomNumberBuilder)
puts boomer.map(&:to_s).join("\n")

 Implement common interface
In your FizzNumber class you implement a fizz_value method which you then use in your main fizzer.map(&:fizz_value).join("\n"). This creates an unnecessary coupling. If you look into the method, you can already see what the method name should be number.to_s
  def fizz_value
    value = FIZZ_MAP.find { |key, value| send(value) }
    value&.first || @number.to_s
  end
end

so a better function name would be
def to_s
  value&.first || @number.to_s
end

private

def value
  FIZZ_MAP.find { |key, value| send(value) }
end

Avoid meta programming
Try to avoid meta programming (send) if not absolutely necessary. It makes the code a lot harder to read. You only have 4 different cases which can easily reflected with an if else.
  def to_s
    if fizzbuzz?
      "FizzBuzz"
    elsif fizz?
      "Fizz"
    elsif buzz?
      "Buzz"
    else
      number
    end
  end

Use getter and setter
Instead of using instance variables @collection you should try to use getter / setter methods. If you need to do e.g. validations or some processing of the variable, you only need to change one place.
class FizzBuzzer
  attr_reader :collection

  def each
    collection.each do |item|
      yield FizzNumber.new(item)
    end
  end
end

Use simple delegator
Instead of implementing the each method you could also use the SimpleDelegator module.
https://ruby-doc.org/stdlib-2.5.1/libdoc/delegate/rdoc/SimpleDelegator.html


Using Stored Procedures in ColdFusion / Lucee

your code could use some formatting so that it can be read without much effort

create schema OrderDetail authorization dbo
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'OrderHeader.[get]') AND type in (N'P', N'PC'))
DROP PROC OrderHeader.[get]
GO
CREATE PROC OrderHeader.[get]
(@UsrID Int
,@OrderHeaderID Int
) AS
SELECT OrderHeaderInfo
FROM OrderHeader
WHERE OrderHeaderID = @OrderHeaderID

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'OrderDetail.WhereOrderHeaderID') AND type in (N'P', N'PC'))
DROP PROC OrderDetail.WhereOrderHeaderID
GO
CREATE PROC OrderDetail.WhereOrderHeaderID
(@UsrID Int
,@OrderHeaderID Int
) AS
SELECT Item,Qty
FROM OrderDetail
WHERE OrderHeaderID = @OrderHeaderID
exec OrderHeader.[get] @UsrID,@OrderHeaderID

you also should be consistent about Capitalization of Keywords in SQL, it will make it easier to see what is going on in your SQL.

CREATE SCHEMA OrderDetail authorization dbo
IF EXISTS (SELECT *
               FROM sys.objects
               WHERE object_id = OBJECT_ID(N'OrderHeader.[get]')
                   AND type IN (N'P', N'PC'))
DROP PROC OrderHeader.[get]
GO

CREATE PROC OrderHeader.[get]
(
    @UsrID INT
    ,@OrderHeaderID INT
) AS
SELECT OrderHeaderInfo
    FROM OrderHeader
    WHERE OrderHeaderID = @OrderHeaderID

IF EXISTS (SELECT *
               FROM sys.objects
               WHERE object_id = OBJECT_ID(N'OrderDetail.WhereOrderHeaderID')
                   AND type IN (N'P', N'PC'))
DROP PROC OrderDetail.WhereOrderHeaderID
GO

CREATE PROC OrderDetail.WhereOrderHeaderID
(
    @UsrID INT
    ,@OrderHeaderID INT
) AS
SELECT Item
    , Qty
    FROM OrderDetail
    WHERE OrderHeaderID = @OrderHeaderID

EXEC OrderHeader.[get] @UsrID,@OrderHeaderID

That is much easier to read, wouldn't you agree?


As Dan Pantry pointed out, === Object and === String do not work; you'll have to compare with a string name of the object:

if(opts.body) {
  constructor = opts.body.constructor;
  if(typeof constructor === "object" || typeof constructor === "string") {
    body = opts.body;
  }
}

Not every browser supports the XMLHttpRequest object. You'll have to do a little checking to get the right object.

The two main objects used are XMLHttpRequest and ActiveXObject("Microsoft.XMLHTTP"). The second one is used by IE.

You can use a simple ternary to see which object to use:

xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));

If you need to copy this into a variable, most people use self, not that.

I don't think you need to check whether to return that.responseXML or that.responseText; I think responseText will contain the response no matter what, so you should just use that.

The complete variable is un-used in the ajaxComplete function; you don't need it.

You should put parenthesis around some places when defining the method variable. It is quite difficult to understand being that there is more than one ternary.

For one-time-use variables like data, don't store them in a variable; just substitue the value of the variable where you are using the variable and destroy the variable.

It's a waste of memory to keep something in memory that you only use once.


Setting alternative records true if its even count else leave last record

In the else clause it might be better to have an if statement with a block of code than a continue statement:

    foreach (var attendance in attendancesPerDay)
    {
        if (attendancesPerDay.IndexOf(attendance) != attendancesPerDay.Count - 1)
        {
            if (counter % 2 == 0)
                attendance.In = true;
            else
                attendance.Out = true;
            counter++;
        }
    }

The logic is basically the same and it is easier to see the scope of the code.

To reduce the repetition of the code there could be a short function that takes 2 parameters, counter and attendance and performs the assignment.

As a personal choice I prefer to specify the real type in a foreach loop because it is self documenting, the user of var hides too much.


PowerShell script to Find and Replace in Word Document, including Header, Footer and TextBoxes within

COM Automation (which is what you are using) is always going to be slow. There's not much you can do about that except to try find new ways to do what you want with as few operations as possible.

An alternative you could investigate is the Open XML SDK. I've never tried it myself, but it is supposed to be a lot faster than COM Automation.

The Open XML SDK is a .NET library, so there should be no problem calling it from PowerShell, but you will have to translate the example code from C# or VB.NET into PowerShell.

Here's an example for Excel which you could adapt. Or maybe you could find an actual Word example. I didn't search very hard.

You should also check out Open-XML-PowerTools. This is a PowerShell wrapper for the Open XML SDK. Maybe it will do what you want already.

Here's a screencast that shows searching and replacing using  Open-XML-PowerTools.


A word of warning: I am very much a C newbie myself, so it may be good to take my advice with a grain of salt.

Formatting

The only good thing I can say about your formatting is that it's consistent. But a 1-space indent really isn't readable. I recommend 4 spaces instead. Please put some whitespace around your operators: a space after every comma, a space on each side of =, -, +, *, …. Don't cram multiple assignments on one line: I find

int i, j, k;

or

int i = 0;
int j = 0;
int k = 0;

acceptable, but not int i=0,j=0,k=0;.

If you are targetting a C89-compatible environment, this is as far as we can go. I recommend you move on (e.g. to C++ or C99), where we can put the declaration of for-loop variables inside the loop itself:

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

… and we also don't have to put all declarations at the top of each scope – just declare your variables at the point of first use.

malloc and error handling

Always check the return value of malloc:

float *temp = (float*) malloc(row * sizeof(float));
if (temp == NULL)
{
    /* return some error code */
}

C isn't object oriented, but whatever

You always bundle the three variables mat, row, col. I suggest you put those into a struct, and pass this single struct around instead:

typedef struct {
    float **mat;
    int rows;
    int cols;
} Matrix;

I would then create a Matrix_new function that creates and populates an instance, e.g.

// this code assumes C99. Ignore my more compact brace style.

/**
 * Allocates a new `Matrix` instance. Returns a pointer to the instance on
 * success, a `NULL` pointer on failure.
 *
 * A Matrix must always be freed via `Matrix_destroy(instance)`!
 */

Matrix*
Matrix_new(int rows, int cols) {

    Matrix* matrix = (Matrix*) malloc(sizeof(Matrix));
    if (matrix == NULL) {
        return NULL;
    }

    float** mat = (float**) malloc(rows * sizeof(float*));
    if (mat == NULL) {
        free(matrix);
        return NULL;
    }

    for (int i = 0; i < rows; i++) {
        float* row = (float*) malloc(cols * sizeof(float));
        if (row == NULL) {
            // if a row allocation fails, we have to `free` the previous rows.
            i--;
            for (; i >= 0; i--) {
                free(mat[i]);
            }
            free(mat);
            free(matrix);
            return NULL;
        }

    }

    matrix->mat  = mat;
    matrix->rows = rows;
    matrix->cols = cols;
    return matrix;
}

and of course, a mirroring Matrix_destroy:

/**
 * Safely frees a Matrix instance.
 */

int
Matrix_destroy(Matrix* matrix) {

    if (matrix == NULL) {
        return 0;
    }

    float** mat = matrix->mat;
    int rows = matrix->rows;

    for (int i = 0; i < rows; i++) {
        free(mat[i]);
    }

    free(mat);
    free(matrix);

    return 1;
}

Then, you can rewrite your other methods to take advantage of this bundling.

Return values

Very often (e.g. in final_result, create_mat, feed_mat), you return a pointer from your function even when that pointer was an argument to that function. It is generally preferable to return an error code, and to return values via pointers/out-arguments.

For example, final_result could be changed to:

/**
 * Calculates the final result.
 *
 * Returns an error code.
 *
 * After successful execution, the `out_result` pointer will point to the
 * result, which is a `float*` of `self->rows` length. The caller owns the
 * result, and is responsible for calling `free(*out_result)`.
 *
 * Example usage:
 *
 *     float *result;
 *     if (! final_result(matrix, &result)) {
 *         // abort with error
 *     }
 *     // do something with `result`:
 *     for (int i = 0; i < matrix->rows; i++) {
 *         printf("%f\n", result[i]);
 *     }
 *     free(result);
 */

int
final_result(Matrix* self, float** out_result) {
    if (self == NULL) {
        return 0;
    }

    float* temp = (float*) malloc(self->rows * sizeof(float));
    if (temp == NULL) {
        return 0;
    }

    float* result = (float*) malloc(self->rows * sizeof(float));
    if (result == NULL) {
        free(temp);
        return 0;
    }

    for (int i = 0; i < self->rows; i++) {
        temp[i]   = 0;
        result[i] = 0;
    }

    printf("Processing result...\n");

    do {
        for (int i = 0; i < self->rows; i++) {
            float T = 0;
            for (int j = 0; j < self->cols - 1; j++) {
                if (i != j) {
                    T += self->mat[i][j] * temp[j];
                }
            }
            result[i] = (self->mat[i][self->cols - 1] - T) / self->mat[i][i];
            temp[i] = result[i];
        }
    } while (condition(result, temp, self->rows) == 0);

    free(temp);
    *out_result = result;
    return 1;
}

Miscellaneous Helper Functions

memset

When zeroing all elements in some data structure, you can often use memset from string.h instead:

temp=(float*)malloc((row)*sizeof(float));//Edit: row-1 changed to row
for(i=0;i<row;i++)
{
 temp[i] = 0;
}

becomes

float* temp = (float*) malloc(row * sizeof(float));
if (temp == NULL) {
    // return error code
}
memset(temp, 0, row * sizeof(float));

fabsf

If you are interested in an absolute value of a float, use the fabsf function from math.h. With it, your condition function simplifies to:

int
condition(float* result, float* temp, int row) {
    int flag = 0;

    for (int i = 0; i < row; i++) {
        if (fabsf(temp[i] - result[i]) < chk_end) {
            flag = 1;
        }
        else {
            flag = 0;
            break;
        }
    }

    return flag;
}


is_palindrome function that ignores whitespace and punctuation

You are unnecessarily importing punctuation
Avoid reassigning module names such as string in your code
A list comprehension would be a simpler way of filtering out the data you don't want

from string import ascii_letters

def is_palindrome(candidate):
    """
    Returns True if candidate is a palindrome, ignoring whitespaces and punctuation.
    """
    stripped = [char.lower() for char in candidate if char in ascii_letters]
    return stripped == stripped[::-1]


Golang function to clean a string of scripts

As per usual, I'd say the best way to reliably get rid of any script tags in an HTML string, is to use a parser. HTML is a bit too complex to consume using your standard string functions and regular expressions. It's a hierarchical language, best processed as such. Thankfully, golang has a package for this, and it's fantastically easy to remove script tags:

import (
    "bytes"
    "fmt"
    "log"
    "string"

    "golang.org/x/net/html" // go get -u golang.org etc...
)

func main() {
    doc, err := html.Parse(strings.NewReader(htmlString))
    if err != nil {
        log.Fatal(err)
    }
    removeScript(doc)
    buf := bytes.NewBuffer([]bytes{})
    if err := html.Render(buf, doc); err != nil {
        log.Fatal(err)
    }
    fmt.Println(buf.String())
}

func removeScript(n *html.Node) {
    // if note is script tag
    if n.Type == html.ElementNode && n.Data == "script" {
        n.Parent.RemoveChild(n)
        return // script tag is gone...
    }
    // traverse DOM
    for c := n.FirstChild; c != nil; c = c.NextSibling {
        removeScript(c)
    }
}

The use of n.Data is not a typo BTW. The field name is a bit unfortunate, but as the doc pages state:

  A Node consists of a NodeType and some Data (tag name for element nodes, content for text)

This code was not tested. It's loosely based on the parse example in the official godoc pages.

Although not relevant in this case, it is worth looking into the tokenizer API, too. It is a lower-level api, that can help you process an HTML stream (eg parsing/validating a large file in a stream). You can use it to check how many script tags there are, for example:

tokenizer := html.NewTokenizer(strings.NewReader(htmlString))
tagCount := 0
for {
    tt := z.Next()
    switch tt {
    case ErrorToken:
        return z.Err()
    //case TextToken: ignore, we don't need it here
    case StartTagToken //, EndTagToken: ignore end-tags to make life easier
        tn, _ := z.TagName()
        if string(tn) == "script"  {
            tagCount++
        }
    }
}

Do with it as you like. Again, in this case, there's no reason why you would use the tokenizer I think, unless you want to manually write all tags that aren't script tags to a separate buffer and process them some more. Just thought it worth mentioning here...


Code that lists and inserts data to database: Make methods more reusable in superclass

The first advise is to not over-architect the classes.

Keep alternatives in mind - JPA for instance eclipseLink. A bit of not reinventing the wheel as the database field has a long history of "clever" code.
This is an O/R mapping translating data base Relations into java Objects and vice versa. For a beginner I would first refrain from such magic, and continue as you did. (Your mapRow.)
The entity classes like Member in general are kept small without logic.
And for every entity class there is a repository class with data access (retrieve and such). They rely on a persistence manager singleton instance that takes care of the connection per transaction session (time doing some task).

A long ID and using generated keys is used often.
For the ID inheritance can be used. Too much inheritance can be painful however.

So keep id in its own base class, and do
public class Member extends IdEntity { ... }

public void insert(Member member) throws SQLException {
    try (Connection connection = dataSource.getConnection()) {
        try (PreparedStatement statement = connection.prepareStatement(
                "INSERT INTO members (member_name, email) values (?, ?)",
                Statement.RETURN_GENERATED_KEYS)) {
            statement.setString(1, member.getName());
            statement.setString(2, member.getEmail());
            statement.executeUpdate();

            SQLUtils.fillGeneratedKeys(member, statement);
        }
    }
}

public abstract class SQLUtils {

    public static void fillGeneratedKeys(IdEntity entity, PreparedStatement statement) throws SQLException {
        try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
            generatedKeys.next();
            entity.setId(generatedKeys.getLong("id"));
        }
    }

3a. Similar is the initialisation of a time stamp field. If you disregard the database server's clock and use java's clock, think of a locale independent time.

Consider a "transaction" level; grouping of data base access.
Several database operations, say some INSERTs and UPDATEs best function under the same connection. Possible as transaction, an error raising a rollback and otherwise the data is committed at the end. This cleans up the repetition of try (Connection ....

In every case consider a connection pool or at least getting the connection by your own utility function.

For query methods do not use null results but Optional or exceptions. It not only prevents NullPointerExceptions, but allows chaining:

Several usage like:
A.retrieve().map(A::getChildren()).map(List::size).orElse(0);

protected Optional<T> retrieve(long id, String sql) throws SQLException {
    try (Connection connection = dataSource.getConnection()) {
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setLong(1, id);
            try (ResultSet rs = statement.executeQuery()) {
                if (rs.next()) {
                    return Optional.of(mapRow(rs)=;
                }
                return Optional.empty();
            }
        }
    }
}

Here Long can be long (It is a long id field too). For retrieve-by-id an exception would probably be better.
Here it could be a painful use of inheritance as the child class provides logic; but it is okay.
protected abstract String retrieveByIdSQL();

public final T retrieveById(long id) throws SQLException {
    String sql = retrieveByIdSQL();
    try (Connection connection = dataSource.getConnection()) {
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setLong(1, id);
            try (ResultSet rs = statement.executeQuery()) {
                if (rs.next()) {
                    return mapRow(rs);
                }
                throw new SQLException(...);
            }
        }
    }

Consider translating an SQLException to your own child of a RuntimeException, by rethrowing catched exceptions. Checked exceptions like SQLException must be catched,
which nowadays with Stream usage can be cumbersome. But you could postpone this for the fare future.


I definitely think sample #1 is more readable. The main reason is the (lack of) ternary operator. Although any programmer should understand it, it increases the amount of code you have to read. With sample #1 you can quickly skip the parts after + in the hours and minutes assignments, whereas with ? : you have to read more carefully.

Also, in sample #2 you basically add handling of a special case without needing it, adding unneeded complexity.

Another bonus in sample #1 is that night is not defined in the middle of the hours/minutes/seconds block, so the code is more logically grouped.

By the way, I think the use of shift should be documented with a comment.


Determine final player in a counting game

General remarks

The computation should be separated from the program output. That increases the clarity of the program, and makes the functions better testable. In your case, func playertold should return the result instead of printing it.

Type annotations are often not needed, e.g.
var currentNumber:Int = 1
var currentPlayer:Int = 1
var reversedOrder:Bool = false

can be simplified to
var currentNumber = 1
var currentPlayer = 1
var reversedOrder = false

The indending and spacing it not consistent: The function body and some blocks are not indented, some empty lines are superfluous.

Simplify the program logic
The while-loop
var currentNumber:Int = 1
while currentNumber != number {
    // ... do something ...
    currentNumber += 1
}

can be simplified to a for-loop over a range:
for currentNumber in 1..<number {
    // ... do something ...
}

Instead of a boolean variable reversedOrder you can use a integer variable direction which holds the values +1 or -1. Advancing to the next player is then done with
currentPlayer += direction
// or:
currentPlayer += 2 * direction

depending on whether the next player is skipped or not. After updating the currentPlayer one can check for wrap-around. That saves a lot of case distinctions.
Instead of the remainder operator % can can use the isMultiple(of:) method which was introduced in Swift 5, which expresses the intent better.
The function would then look like this:
func playertold(number: Int) -> Int {
    var currentPlayer = 1
    var direction = +1

    for currentNumber in 1..<number {
        if currentNumber.isMultiple(of: 9) {
            direction = -direction
        }
        // Advance position:
        if currentNumber.isMultiple(of: 17) {
            currentPlayer += 2 * direction
        } else {
            currentPlayer += direction
        }
        // Check for wrap-around:
        if currentPlayer < 1 {
            currentPlayer += 17
        } else if currentPlayer > 17 {
            currentPlayer -= 17
        }
    }
    return currentPlayer
}

More suggestions
Avoid “magic constants.” In this function that are the numbers 9 and 17, and the latter has two different meanings. What if you want to change the number of players from 17 to 20? In your original code you would have to replace multiple instances of 16 and 17, and in the above version you still have to multiple instances of 17 – but not the 17 in the isMultiple(of: 17) check! That is too error-prone.
One option is to define constants, e.g.
let numPlayers = 17
let reversePosition = 9
let skipPosition = 17

Another – more flexible – option is to make these additional parameters of the function, with default values:
func playertold(number: Int, numPlayers: Int = 17,
                reversePosition: Int = 9, skipPosition: Int = 17) -> Int {
    var currentPlayer = 1
    var direction = +1

    for currentNumber in 1..<number {
        if currentNumber.isMultiple(of: reversePosition) {
            direction = -direction
        }
        // Advance position:
        if currentNumber.isMultiple(of: skipPosition) {
            currentPlayer += 2 * direction
        } else {
            currentPlayer += direction
        }
        // Check for wrap-around:
        if currentPlayer < 1 {
            currentPlayer += numPlayers
        } else if currentPlayer > numPlayers {
            currentPlayer -= numPlayers
        }
    }
    return currentPlayer
}

Now the intent of every constant is clear. The function can still be called with
the standard values
print(playertold(number: 1234))

but also with custom values
print(playertold(number: 1234, numPlayers: 20, reversePosition: 5, skipPosition: 15))


Readability

With your lengthy template statement, I'd put the class statement onto the next line:

template </*...*/>
class map

Naming standards

According to this answer, identifiers in the form _Identifier are reserved:

  7.1.3 Reserved identifiers

  Each header declares or defines all identifiers listed in its
  associated subclause, and optionally declares or defines identifiers
  listed in its associated future library directions subclause and
  identifiers which are always reserved either for any use or for use as
  file scope identifiers.

  All identifiers that begin with an underscore and either an uppercase
  letter or another underscore are always reserved for any use.

  [...]

Const-correctness

You have iterators, but you should also have const iterators:

const_iterator cbegin() const
{
    return &data_[0];
}

const_iterator cend() const
{
    return &data_[size_];
}

empty() should be const:

bool empty() const
{
    return size_ == 0;
}

has_key() should be const and use the aforementioned const iterators:

bool has_key(const key_type &_Key) const
{
    for (const_iterator i = cbegin(); i != cend(); ++i)
    {
        if (i->first == _Key)
        {
            return true;
        }
    }
    return false;
}


Angular 5 Forms - Extending Form Control

Update the signature of the module to include your new properties.
This will let the compiler know about your new properties and will prevent it from throwing errors in the HTML template or in the component.ts file.
declare module '@angular/forms' {
  interface AbstractControl {
    focused: boolean;
  }
}

I added AbstractControl because that is the base class that FormControl is built on and derives its properties from.

Add your new properties by extending the class, passing through (...args) for both the constructor(...args) and super(...args) calls.
export class FormControlCustom extends FormControl {

  public focused: boolean = false;

  constructor(...args) {
    super(...args);
  }

}

Typecast your FormControl. Now all your FormControlCustom elements will have the new properties defined in the class which extends FormControl by default.
sampleForm = new FormGroup({
    property: new FormControlCustom('', Validators.required)
});

I tested this and it is working perfectly in Angular 9.


The very first concern is what if item just happens to be a string starting with [ or {?

How about instead of testing for [ and {, why not try parsing it? And if it fails, just return as is? This way, you don't need half-hearted checks.

export function resolveValues (data) {
  return mapValues(data, item => {
    try{ return JSON.parse(item) }
    catch (e) { return item; };
  })
}


To make it elegant clean code I would:

make proper use of blank lines;
abide by the coding standards defined by PHP-FIG;
use the DOMNodeList object as an array so I can use foreach();
be consistent with either single ' or double quotes ";
use a guard clause.

Refactored code:

$aEls = $doc->getElementsByTagName('a');

foreach ($aEls as $a) {
    $url = parse_url(strtolower($a->getAttribute('href')));

    if ($url['host'] === $localDomain) {
        continue;
    }

    $title = $a->getAttribute('title') . ' [external link to ' . $url['host'] . ']';

    $a->setAttribute('title', $title);
    $a->setAttribute('target', '_blank');
}

(not tested)


Calling API only once on changing segments

The operator you are looking for is distinctUntilChanged(). It skips only equal items followed one by one.

Or distinct() operator which skips the items what has been even once emitted in the sequence. In your case the fetchPurchaseHistory method could be triggered no more than 3 times by this observable with distinct operator