Print out a table that displays how far a cannon can shoot an object at incremental speeds and angles

Welcome to Code Review! You did a good job so far, but I have some style and logic suggestions for you.

Let's talk about the Catapult class first. In its current form is a good container but it has two flaws. First, you declare the constructor to accept int parameters but are storing them in double variables. Either it should be all int or should be all double, but I am assuming for the rest of this answer that you want double. The second flaw is that you calculate the distance in a separate function and not the constructor. This concept of a cached value is not the flaw, but the way you are using it, is. The only reason you would want to calculate that distance in a different location than in the constructor of Catapult is if it was a very expensive operation that might not need to be called. For this simple example, make the function private and call it in the constructor as follows:

private double angle;
private double speed;
private double distance;

// The second parameter is named "speed" to be consistent with the rest of the
// code. Its better to write a comment or documentation stating that "angle"
// is in degrees and "speed" is in miles per hour.
public Catapult(double angle, double speed) {
    this.angle = angle;
    this.speed = speed;
    this.distance = this.calculateDistance();
}

...

private double calculateDistance() {
    return speed * speed * Math.sin(2 * Math.toRadians(angle)) / 9.8;
}

public double getDistance() {
    return this.distance;
}

Also, rename the other getters to getAngle and getSpeed accordingly.

(Edit: perhaps getLaunchAngle can stay, but getMilesPerHour is not a good function name.)

Next let's talk about CatapultTester. You should move the constants that are defined at the top of main into the class definition itself. I suggest making a constructor for a CatapultTester that takes in those arguments. This way, you have the ability to make several unique CatapultTester objects. If, for example, you want the user of your library to test the Catapult in a custom way, they can build their own CatapultTester objects. Provide that ability to the user:

public class CatapultTester {
    // make sure these are reasonable defaults
    private double startAngle     = 25;
    private double startSpeed     = 20;
    private double angleInterval  =  5;
    private double speedInterval  =  5;
    private double numAngles      =  6;
    private double numSpeeds      =  7;

    public CatapultTester() {}
    public CatapultTester(double startAngle,    double startSpeed,
                          double angleInterval, double speedInterval,
                          double numAngles,     double numSpeeds)
    {
        ...  // implement custom constructor here
    }

    public void printTest() {
        ...  // put your test program here instead
    }

    ...  // add more functionality in the future?
}

The point of doing this is that you're putting all the details of the object in the class itself instead of the main program. The main function would end up looking something like this:

public static void main(String[] args) {
    new CatapultTester().printTest();
}

This clearly conveys the meaning behind your main function, without the specifics that don't need to be known by the user. Now, if you want to expand main in any way, you have a more powerful API to work with.

Now to your actual test function. There are several instances of duplicated code, note the three for loops that run over the same range. What you should do instead is just loop over the range you need and do all the computation in one step. This would also remove the need for an array for the Catapult objects.

The last for loop is enough:

System.out.println("       |                    Projectile Distance (ft.)                    ");
System.out.println("*************************************************************************");
System.out.println("  MPH  |  25 Deg     30 Deg     35 Deg     40 Deg     45 Deg     50 Deg  ");
System.out.println("*************************************************************************");

for (int speed = 0; speed < this.numSpeeds; ++speed) {
    StringBuilder output = new StringBuilder();  // StringBuilder is fast!
    for (int angle = 0; angle < this.numAngles; ++angle) {

        // build one catapult at a time and calculate all necessary values in one go
        Catapult cat = new Catapult(
            angle * this.angleInterval + this.startAngle,
            speed * this.speedInterval + this.startSpeed
        );

        // prints only once at the beginning of the angle loop
        if (angle == 0) {
            output.append(String.format("  %-8.0f", cat.getSpeed()));
        }

        output.append(String.format("%-10.2f ", cat.getDistance()));
    }

    System.out.println(output.toString());
}

System.out.println("*************************************************************************");

You will have to import java.util.StringBuilder for this functionality. This drastically reduces the number of computations and repetitions in your code. Its important to keep in mind the acronym DRY (Don't Repeat Yourself) and if you see something that happens over and over again, see if you can write it once but get the same computations out of it. It will speed up your code and make it more readable. I hope you found these suggestions helpful. Good job and good luck!


One of the simplest and easiest ways to evaluate math expressions is to use the Compute method of the DataTable class:

DataTable dt = new DataTable();
int answer = (int)dt.Compute("2+(4*3)*4", "");

answer is 50.

One caveat you'll have to trap exceptions to catch invalid expressions.


Using regexp (replace) isn't the best solution. I think you should use only substring:

System.out.println(test.substring(0, test.lastIndexOf(":")))


There's no reason to use brute force like that.  I couldn't even get the program to complete without crashing.

To find the count, just take the cube root of n, and round down.  Then, it's a simple matter to construct the list you need.

n = 9238899039
count = int(n ** (1.0/3))
store = range(1, count + 1)


SQL GROUPING SETS in Python using Pandas

About this part:

def grouper(df,grpby=None,aggfunc=None):
    uniqcols = (i for i in grpby if len(df[i].unique()) == 1)
    pwrset = (i for i in powerset(grpby))
    s = set()
    for uniqcol in uniqcols:
        for i in pwrset:
            if uniqcol in i:
                s.add(i) # add a level of aggregation only when non-redundant

The two optional arguments are in fact required by the function.
The convention is that i is a loop variable of type int.
Bug: pwrset is a generator expression. As such it can only be iterated through once, just like the iterator returned from powerset(grpby). Using square brackets [] instead of () would turn it into a list comprehension and fix the bug.
Changing the other generator expression into a list comprehension would allow you to swap the order of the nested for loops. This would be more natural since the nested loop is filtering pwrset, and more efficient because you could break out of the inner loop after first s.add(i). Then s does not even need to be a set (because the rest of the code merely iterates over s). If you make uniqcols a set instead, the inner loop could be avoided altogether.

Revised code:

def grouper(df, grpby, aggfunc):
    uniqcols = set(col for col in grpby if len(df[col].unique()) == 1)
    s = [cols for cols in powerset(grpby) if not uniqcols.isdisjoint(cols)]


Calculating parking fees, given start and end timestamps

The main issue I see with the code is the repetitive if/elses at the bottom. Repetitive code is annoying to write, takes some time to read, and is often a bit more likely to have bugs than DRY code. To identify the parking fee, I'd make an array of ranges and their associated fees, then find the appropriate range:
const getCost = (totalHoursParked) => {
  const costs = [
    // [Maximum number of hours, Associated cost]
    [1/3, 2],
    [2/3, 4],
    [1, 6],
    [2, 7],
    [3, 9],
    [4, 11],
    [8, 13],
    [24, 15],
  ];
  if (totalHoursParked > 24) {
    const days = Math.ceil(totalHoursParked / 24);
    return 16 + 9 * (days - 1);
  }
  const found = costs.find(([maxHours]) => totalHoursParked <= maxHours);
  return found[1];
};

Just calculate the hours stayed, then invoke the function above.
Other suggestions regarding your current code:
Always use const when you can - only use let when you must warn readers of the code that you may be reassigning the variable in the future.
Avoid var - If you're going to write in modern ES6+ syntax, great - in which case, better to avoid var, which has problems such as an unintuitive function scope and automatically assigning to a property of the global object when on the top level.
Prefer [] over new Array() -  it's shorter to write and easier to read, and using the constructor may tempt you to pass it a number, which will result in a sparse array (sparse arrays can have some very strange behaviors; better to avoid them entirely).
Prefer strict equality - better to avoid == and !=, since they have confusing coercion rules a reader of the code should not have to have memorized in order to be confident of the logic the code is implementing.
add24HR is weird While you can loop one-by-one over the hours and increment when encountering every 24th, it'd be much easier to just divide the number of hours by 24 and take the .ceil or .floor of it as needed.
Use meaningful, precise variable names that clearly indicate what the variable contains. Would someone just glancing at the script know what park means, or the difference between totalTime and totalPark, without looking at where those are defined? Probably not - better to call them something like parkDate, returnDate, totalMSParked, totalHoursParked. The penaltyFee = 9 doesn't make a whole lot of sense either except after one reads the description of the problem and some of the code. parkingFees is a function, so it should probably have a verb in its name, like calculateParkingFees.
Only use string interpolation when you need to interpolate For example, this:
return `Your parking fee is only £${4}.`

may as well be
return `Your parking fee is only £4.`

Semicolons Some of your lines have semicolons, but a lot of lines are missing semicolons too. Best to be stylistically consistent - either use semicolons or don't. Unless you're an expert, I'd highly recommend using semicolons, else you will probably occasionally run into the pitfalls of automatic semicolon insertion.
In all, I don't think there's much need in the code for anything other than a small wrapper around the getCost function:

const calculateParkingFees = (parkDateStr, returnDateStr) => {
  const parkDate = new Date(parkDateStr);
  const returnDate = new Date(returnDateStr);
  const totalMSParked = returnDate - parkDate;
  const totalHoursParked = totalMSParked / (1000 * 3600);
  return `Your parking fee is £${getCost(totalHoursParked)}.`;
}

const getCost = (totalHoursParked) => {
  const costs = [
    // [Maximum number of hours, Associated cost]
    [1/3, 2],
    [2/3, 4],
    [1, 6],
    [2, 7],
    [3, 9],
    [4, 11],
    [8, 13],
    [24, 15],
  ];
  if (totalHoursParked > 24) {
    const days = Math.ceil(totalHoursParked / 24);
    return 16 + 9 * (days - 1);
  }
  const found = costs.find(([maxHours]) => totalHoursParked <= maxHours);
  return found[1];
};

console.log(calculateParkingFees("5/12/2020 18:30", "5/18/2020 18:30")); // 6 days
console.log(calculateParkingFees("5/12/2020 18:30", "5/12/2020 19:45")); // bit more than an hour
console.log(calculateParkingFees("5/12/2020 18:30", "5/12/2020 19:00")); // 30 minutes


Counting occurrences of substring in string

Your current implementation could be more efficient.  Copying the passed in string and chopping it up is probably pretty expensive (I'm not a master of .NET internals though).

val.Count()

Why not val.Length?  Count() is very inefficient compared to Length.

copy = copy.Remove(indexOfVal, val.Count());

We don't need to remove part of the string, just search again starting at indexOfVal + val.Length.

Here is an example using an overload of String.IndexOf:

public static int Occurences(this string str, string val)
{
    int occurrences = 0;
    int startingIndex = 0;

    while ((startingIndex = str.IndexOf(val, startingIndex)) >= 0)
    {
        ++occurrences;
        ++startingIndex;
    }

    return occurrences;
}

This implementation will count overlapping occurrences (so "bbb".Occurences("bb") will return 2.

If you don't want to count overlapping occurences, you can replace ++startingIndex; with:

startingIndex += val.Length

On why an exception isn't thrown in the case of "foo".Occurrences("o"), from MSDN:

  If startIndex equals the length of the string instance, the method returns -1.


typeof activeEvents === 'object' && activeEvents !== null can be true for both Array and Object :

const array = [];
const obj = {};

console.log(typeof array === 'object' && array !== null)
console.log(typeof obj === 'object' && obj !== null)

you can use Array.isArray

const activeEvents = [{
  id: '1',
  title: 'event 1'
}, {
  id: '2',
  title: 'event 2'
}]

function App() {
  return (

 List

      { Array.isArray(activeEvents) &&
        activeEvents.map(event => (

 { event.title }

        ))
      }

  );
}

ReactDOM.render( <
  App / > ,
  document.getElementById('root')
);


Yes that's it, that is decoupled.

However, the benefits of this are not visible in your example because the look of SQL and IDBInteraface are the same.

It would become obvious if your example was of that kind:

interface IDBInterface
{
    void Update(string sqlQuery);
    void Insert(string sqlQuery);
    void Select(string sqlQuery);
}

class SQL:IDBInterface
{
    public void Update(string sqlQuery){/*implementation*/};
    public void Insert(string sqlQuery){/*implementation*/};
    public void Select(string sqlQuery){/*implementation*/};

    public void connect(){/*implementation*/};
    public void disconnect(){/*implementation*/};
    public void optimize(){/*implementation*/};;
    public void backup(){/*implementation*/};;
}

In such cases, when using the IDBInterface, you would not even mind about all the administrative work to be done ( connect, disconnect, optimize, backup).


Caesar Cipher [The Odin Project-Javascript Exercise]

Welcome to Code Review, some considerations that can help you to simplify your code:

you have an alphabet of 26 letters, so if the shifting operation is
limited to a 26 characters range you can use the mod operation %26
to determine the final position.
you can have a shift negative operation num (ex. -5), for a 26
set of elements shift this is equal to a positive shift of  Math.abs(26 - Math.abs(num)) , so for 5 the positive shift is 21.

So if you have a c character and you want to obtain the ascii code of the corresponding shifted char of num positions you can obtain it in the following way:

const start = c === c.toLowerCase() ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0);
const diff = c.charCodeAt(0) - start;
const sh = num >= 0 ? diff + num : diff + Math.abs(26 - Math.abs(num));
const code = sh % 26 + start;

The first line returns the ascii code of 'a' or 'A' depending if the char c is lowercase or uppercase called start, the second gives you the difference between c and start, the last two lines calculate the code of the shifted corresponding character.

After your function can be rewritten in the following way:

'use strict';

function caesar(str, num) {
    const arr = [];
    const re = /[a-zA-Z]/;
    for (const c of str) {
        if (re.test(c)) {
            const start = c === c.toLowerCase() ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0);
            const diff = c.charCodeAt(0) - start;
            const sh = num >= 0 ? diff + num : diff + Math.abs(26 - Math.abs(num));
            const code = sh % 26 + start;
            arr.push(String.fromCharCode(code));
        } else {
            arr.push(c);
        }
    }

    return arr.join('');
}

I set arr and regex as const and instead of iterate over string using the index, I preferred the for ... of construct.

Note: I'm a javascript beginner too, so every suggestion to improve my code as for the original question is highly appreciated.


If you don't want create a full-blown xml serializer (I wouldn't if it was a simple as that) all you can do is to just tide this up. This is, add a helper variable for dataItems and create a helper extension for finding elements based on the Name attribute. Then you can remove all the other intermediate viariables and directly assign the values to the properties because this is pretty short right now.

public static string ValueWhereName(this IEnumerable<XElement> sournce, string name)
{
    return sournce.SingleOrDefault(i => i.Attribute("name").Value.Equals(name))?.Value;
}

and use it like this:

var query =
    from item in dataRows
    let dataItems = item.Elements("DataItem")
    select new
    {
        Symbol = dataItems.ValueWhereName("SYMBOL"),
        CompName = dataItems.ValueWhereName("NAME"),
        Cusip = dataItems.ValueWhereName("CUSIP"),
        Sedol = dataItems.ValueWhereName("SEDOL")
    };

If you had a dedicated class for the result you could make it even more robust by using nameof(YourClass.Symbol). But then the properties would have to have the same names as the attributes or you would need to decorate them with your own attributes and use some reflection... You would also need to modify the Equals(name, StringComparison.OrdinalIgnoreCase) call to ignore-case sind the properties obviously wouldn't match the xml attributes casewise.

Another option could be the package Json.NET as it's also able to parse xml but I'm not sure how it could handle the attributes.


size_with_biggest_unit should be streamlined. Move the unit names into a list:

unit_names = [ "", "KB", "MB", "TB" ]

and iterate downwards:

    for exponent in range (4, -1, -1):
        if size > 1024 ** exponent:
            unit_name = unit_names[exponent]
            return str(round(size / 1024 ** exponent)) + unit_name
    raise ImpossibleError

Same (almost same) applies to size_in_bytes.

Hardcoding \ as a path delimiter seriously impairs the portability. Prefer os.path.sep.
Instead of returning a list, consider turning it into an iterator.
Re Unused variable 'subfolders', a pythonic way to tell that the variable is truly unused is to call it _. I don't know if

for folder_name, _, filenames in os.walk(root_folder):

would pacify PyLint, but it would definitely make reviewer happier.


Decoupled chain of responsibility in Python

This looks unfinished to me and far from ready for review.

The docstring for the class Processable doesn't describe the class. What kind of thing is an instance of Processable?
The class Processable is misleadingly named — its instances are things that can process not things that can be processed so a name like Processor would be better.
The execute method has no docstring. What does it do?
The purpose of the execute method is surely to process a request, but in that case shouldn't it take the request as a parameter?
Why does the execute method return a string? This seems to be an unnecessary limitation: a processing chain might need to return a more complex object.
In the chain of responsibility pattern, a processor's default behaviour is to forward the request to the next processor in the chain. But this seems to be omitted from the implementation here. Where is the next processor stored? How is the request forwarded?
It is not clear what happens if none of the processors in the chain want to handle a request.
staticmethod is nearly always an anti-pattern in Python. In some languages (like Java) all functions have to belong to a class. But in Python you can just write a function, and there is no need to make a class whose only job is to act as a container for some functions.
There are no docstrings for process_directly and process_subclass. What do these functions do?
process_directly is coupled tightly to settings.CHAIN_PROCESSORS. It would be better for this to be a parameter, in case the application needs to construct its processor chain in some other way.
process_directly constructs a Processable instance and calls its execute method. But doesn't there need to be a request somewhere?
process_directly throws away the Processable instance after it is finished. This means that if you call it again it has to go through the construction logic again, which is a waste of time, and it makes it hard to implement stateful processors (because the objects don't survive from one execution to the next).
process_directly calls print on the result. It seems unlikely that this is what real processor chains will want to do with the result.
If the test issubclass(cls, Processable) fails, nothing happens. This means that typos and other mistakes in the setting will be silently ignored. It would be better to raise an exception.
I don't understand the purpose of process_subclass.
There's duplicated code (for loading a class from a module) between process_directly and process_subclass.


Python Decorator - inspecting function argument values

I'm not a fan of this design. @TheBlackCat is right. Don't do this.

If you are to do this, rethink your design. A more sensible one might look like

import functools
from contextlib import suppress

def try_except_response(func):
    @functools.wraps(func)
    def wrapper(*args, fail_silently, **kwargs):
        if fail_silently:
            with suppress(Exception):
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)

    return wrapper

The key principle here is KISS.

Note that I'm suppressing Exception, not BaseException, since catching SystemExit and KeyboardInterrupt is almost always a bad idea.

If you want to make fail_silently a default argument, just use another wrapper:

def default_fail_silently(default):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, fail_silently=default, **kwargs):
            return func(*args, fail_silently=fail_silently, **kwargs)
        return wrapper
    return decorator

Then you can do

@default_fail_silently(False)
@try_except_response
def test(a, b, c=1)
    return int(a) + c

This does mean there's more boilerplate, since it exists for each piece of functionality you add, but the logic itself is an order of magnitude simpler.


Performance

The non-Async methods are much faster in case of ReadLine/Write. If you need to run the code in background, use await Task.Run(/* put the whole code here */);

Encoding

You can use the static property Encoding.Unicode. (It is the same as creating a UnicodeEncoding instance without constructor arguments)
Add the Encoding to the stream reader: new StreamReader(fileInfo.Open(FileMode.Open, FileAccess.Read), Encoding.Unicode). Otherwise, if the input file is not unicode encoded, the output becomes a bunch of trash.


PDO sign up function inserting data into multiple tables

If the second or later query fails you'll have inconsistent data in your database. Consider using atomic transactions.
$query_2, $query_3 are bad names. You could pick something more descriptive, like $usersInsert, $freelancersInsert etc.

$query  = $this->db->prepare("INSERT INTO " . DB_NAME . ".users
    (firstname, lastname, email, email_code, password, time_joined, location, portfolio, bio, ip)
    VALUES
    (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$query->bindValue(1, $firstname);
$query->bindValue(2, $lastname);
...

I'd use named binds here. As far as I see they works with INSERT statements too.

$query  = $this->db->prepare("INSERT INTO " . DB_NAME . ".users
    (firstname, lastname, email, email_code, password, time_joined, location, portfolio, bio, ip)
    VALUES
    (:firstname, :lastname, ...)
");

$query->bindValue(":firstname", $firstname);
$query->bindValue(":lastname", $lastname);
...

It would be less error-prone (harder to mix parameters up) and would be easier to read/follow.
Consider Hayley Watson's comment on the die manual page:

  It is poor design to rely on die() for error handling in a web site because it results in an ugly experience for site users: a broken page and - if they're lucky - an error message that is no help to them at all. As far as they are concerned, when the page breaks, the whole site might as well be broken.

  If you ever want the public to use your site, always design it to handle errors in a way that will allow them to continue using it if possible. If it's not possible and the site really is broken, make sure that you find out so that you can fix it. die() by itself won't do either.

Furthermore, at least log the error to a log file, otherwise you might be never know if your future users can't even register.

if($userType == 'designer') {
    $query_5 = $this->db->prepare("INSERT INTO " . DB_NAME . ".designer_titles (job_title_id, job_title) VALUE (?,?)");

    $query_5->bindValue(1, $last_user_id);
    $query_5->bindValue(2, $jobtitle);

    $query_5->execute();

} else if ($userType == 'developer') {
    $query_5 = $this->db->prepare("INSERT INTO " . DB_NAME . ".developer_titles (job_title_id, job_title) VALUE (?,?)");

    $query_5->bindValue(1, $last_user_id);
    $query_5->bindValue(2, $jobtitle);

    $query_5->execute();
}

Both cases are almost the same. You could create a function for that with a $tableName parameter to remove the duplication.

It can be a sign that you could have another database structure with only one table instead of two:

TABLE titles:
    - role (possible values: developer, designer)
    - job_title_id
    - job_title

if($userType == 'designer') {
    ...
} else if ($userType == 'developer') {
    ...
}

You could be more defensive here, if $userType contains something else (not designer nor developer) and if it's should be considered as a programming (or input validation) error sing it somehow. I'd throw an exception and log it in a catch block. (The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas: Dead Programs Tell No Lies.)
You could save a few indentation level with guard clauses which would be readable. You wouldn't have to read through the whole function to figure out what happens when $rows > 0 is false:

$rows = $query->rowCount();

if($rows > 0){
    return;
}
$last_user_id =  $this->db->lastInsertId('user_id');
...

It might be more unambiguous using return false instead of implicit return here.
The comment doesn't say too much, the code is already obvious here:

$password   = $bcrypt->genHash($password);// generating a hash using the $bcrypt object

I'd remove it. (Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)
A lot of parameters is a code smell:  Long Parameter List. Their type are the same, it's easy to mix them up. Consider using a parameter object instead which would contain named fields.

public function registerFreelancer($firstname, $lastname, $email, $password, $location, $portfolio, $jobtitle, $priceperhour, $experience, $bio, $userType){

See: Martin Fowler's Refactoring: Improving the Design of Existing Code book, Chapter 3. Bad Smells in Code, Long Parameter List
I've found this kind of formatting is rather hard to maintain:

$time       = time();
$ip         = $_SERVER['REMOTE_ADDR'];
$email_code = sha1($email + microtime());
$password   = $bcrypt->genHash($password);// generating a hash using the $bcrypt object

If you have a new variable with a longer name you have to modify seven other lines too to keep it nice. It also looks badly on revison control diffs and could cause unnecessary merge conflicts.

From Code Complete, 2nd Edition by Steve McConnell, p758:

  Do not align right sides of assignment statements

  [...]

  With the benefit of 10 years’ hindsight, I have found that,
  while this indentation style might look attractive, it becomes
  a headache to maintain the alignment of the equals signs as variable
  names change and code is run through tools that substitute tabs
  for spaces and spaces for tabs. It is also hard to maintain as
  lines are moved among different parts of the program that have
  different levels of indentation.


Cancelling ongoing http requests when next one is started - web app search feature

You can rewritte this piece of code:

.catch(error => {
    if (
    cts !== 'undefined' &&
    cts.token !== 'undefined' &&
    cts.token.reason !== 'undefined' &&
    cts.token.reason.message === 'next request started'
    ) {
    } else {
    throw error;
    }
}

To:

.catch(error => {
    if (
        typeof cts === 'undefined' ||
        typeof cts.token === 'undefined' ||
        typeof cts.token.reason === 'undefined' ||
        cts.token.reason.message !== 'next request started'
    ) {
        throw error;
    }
}

And you can go further into the simplification using this trick.


Check if an entity exists in a Azure Table Storage

If I remember correctly, accessing a row by PartitionKey and RowKey is built to be the fastest operation you can do on an Azure Table Storage. The performance drawback of using a DynamicTableEntity probably isn't worth it unless the returned entity is really big.

I feel like you should stick to the Retrieve, but there's no better way to be sure than to profile both your solutions for performance to see which is better with your data.

Because there's nothing else to say about your code, from what I know, you have the 2 existing solutions in your hand. Figure the best one now :)


Criticism on x86_64 nasm assembly strToInt and printInt implementation

Warming up
A good thing that I see missing from your program is writing comments about the function numbers and more.
mov rdi, 0    ; STDIN
mov rax, 0    ; SYS_READ
syscall
...
mov rdi, 1    ; STDOUT
mov rax, 1    ; SYS_WRITE
syscall

mov rdi, 0    ; OK
mov rax, 60   ; SYS_EXIT
syscall

Here's an improvement that you can make:

section .data
endl db 10, 0
endlLength equ $ - endl

The output to STDOUT is length driven. It's not useful to zero terminated this newline. All you could get is that ASCII character 0 gets displayed needlessly.
There are some errors in your code

mov rax, 60
mov rbx, 0
syscall

The first argument must go in RDI. You wrote RBX. Habit from 32-bit ?

_convertStringLoop:
  xor rdx, rdx      ;clear rdx
  mul rbx           ;multiply rax by 10
  mov dl, [rcx]     ;get 1 byte from rcx address
  sub dl, '0'       ;seb by '0' to get actual value
  add rax, rdx      ;add it to rax

You have misplaced that xor rdx, rdx instruction. The mul rbx instruction that follows will modify RDX as part of its operation. If the input that you get from the user at the keyboard is really big, then RDX can become non-zero! But wait! You need RDX to be zero so the addition can work correctly...
This will work fine zero-extending DL into EDX into RDX:
_convertStringLoop:
   mul   rbx              ; multiply rax by 10
   movzx edx, byte [rcx]  ; Get 1 byte from RCX address and put in RDX
   sub   dl, '0'          ; seb by '0' to get actual value
   add   rax, rdx         ; add it to rax

and this will work too and allows to not use RBX at all (saves many instructions):
_convertStringLoop:
   imul  rax, 10          ; multiply rax by 10
   movzx edx, byte [rcx]  ; Get 1 byte from RCX address and put in RDX
   sub   dl, '0'          ; seb by '0' to get actual value
   add   rax, rdx         ; add it to rax

;print negetive sign
mov [rsi + 1], byte '-'
mov rax, 1
mov rdi, 1
inc rsi
mov rdx, 1
syscall
dec rsi

This code overwrites the value of RBX that you're trying to preserve on the stack!
You need to offset by a negative number or else decrement RSI beforehand:
; print negative sign
dec  rsi
mov  byte [rsi], '-'
mov  rdx, 1
mov  rdi, 1   ; STDOUT
mov  rax, 1   ; SYS_WRITE
syscall
inc  rsi

Some better ways of doing things

cqo
cmp rdx, -1         ;check to see if negetive
jne _divisionLoop   ;if not negetive jump

You can test if RAX contains a negative number simply by testing the register with itself and then inspecting the sign flag:
test rax, rax
jns  _divisionLoop   ; RAX is positive

cmp byte[rcx], '-'   ;if not negetive jump
jne _exitStrToInt
not rax              ;1's complement (make negetive)
inc rax              ;2's complement (make negetive)

The instruction set offers you the NEG instruction to negate a number:
cmp  byte [rcx], '-'   ; If not negative jump
jne  _exitStrToInt
neg  rax

cmp rax, 0
jnz _divisionLoop ;jump if the division did not result in a zero

To find out if a register is 0, you can test it with itself and inspect the zero flag. This shaves off a byte and generally produces faster code:
test  rax, rax
jnz   _divisionLoop


Language choice
A lot of your commentary on this code revolves around whether bash is a good choice for this project.  I would say, yes, it is a good choice.  You have shell commands, and you want to make a bit of a wrapper around them.  That's a perfect use case for shell, even with so many more recent choices available.
A related concern that you raised is

I am a Python developer and I fear I may have written a Python-script in Bash.

Yeah, maybe, a bit.  But that's life in coding.  Everything you do is going to be influenced by previous languages you've been exposed to.  Most shell programs don't involve arrays, but there's nothing wrong with you taking advantage of unpopular features.  I will talk about making this like native shell in the review below.
Code review

Your use of indentation and quoting is excellent.
Nice variables names.  Yay for copying the command line arguments into named variables.
Your style guide seems like a reasonable choice although I just skimmed it.  I've liked Google's style guide and shellcheck.  Shellcheck is a linter so it could be used in your CI pipeline.
I like that you exit after some commands that could fail.  It would be nice from the calling perspective if you used distinct exit codes.  It would also be a good idea to check that rm, mkdir and cp succeeded.
Did you try it without evaling the command?  I didn't try it, but I'm guessing you can skip the eval.
So, back to the arrays being unusual in a shell script... The shell will split a string into arguments if they are separated by spaces.  You could make languages be a long space-delimited string and not worry about turning it into an array.  The for loop would become for lang in $languages; do and the shell would give you one at a time.  It also works your way and it should be decipherable to folks who aren't used to arrays in the shell, so I wouldn't worry about it.
The if at the top would usually be expressed like if [[ "$*" < 3 ]].  Your way is fine.  The (( )) tells the shell to "do math in here" and that works here, but you might want to do string comparisons or check file existence.  Then you'll need the [[ ]].


This is procedural code trying to pretend that it is OO.  Just stick a namespace around it and write it like the procedural code that it is:

framework/verv.php

namespace verv;

function setLang() { /* Implementation */ }
function dbConnect() { /* Implementation */ }

function main()
{
    setLang();
    dbConnect();
    // etc
}

Usage

verv\main();

Advantages

No more static and self littering the code.
No loss in usual OO benefits like data hiding and encapsulation, while reducing keystrokes required for implementation.


Beside the obvious fact that you're reinventing the wheel as this functionality is already present in php, here are some comments to your code:

Strange to use strpos() – If you want to reinvent the wheel, then I wouldn't use strpos() at all.
Doesn't restart checks – As commented upon by mdfst13, cases like ababc vs abc fails, as you don't restart the test if the first candidate fails.
Too long substrings gives index errors – Testing with octopus vs pussy results in index errors on the source string.
$a and $b are not really good names – They don't convey anything regarding their intended purpose, as $source and $substr would do.*
No comments – It always nice to have a little comments to indicate what you are trying to achieve in a code block.

So an even more basic version which implements these comments could look like:

function isSubStr($source, $substr) {
  $len_src = strlen($source);
  $len_sub = strlen($substr);
  $max_start_pos = $len_src - $len_sub;

  // If longer, there isn't room for it
  if ($max_start_pos < 0) {
    return false;
  }

  // Find start position for substring
  $pos = 0;
  while ($pos <= $max_start_pos) {

    // Check if we have a valid start position
    if ($source[$pos] == $substr[0]) {

       // Assume it is a good candidate, and verify this
       $foundCandidate = true;

      // Check for equality between source and substring,
      // and verify length of both strings
      for ($subIdx = 0, $orgIdx = $pos;
           $orgIdx < $len_src && $subIdx < $len_sub;
           $orgIdx++, $subIdx++) {

        if ($source[$orgIdx] != $substr[$subIdx]) {
          $foundCandidate = false;
          break;
        }
      }

      // If we exited previous loop due to exhausting the substring,
      // and not have a falsified candidate we have a match
      if ($foundCandidate && $len_sub == $subIdx) {
            return true;
      }
    }

    $pos++;
  }

  // Passed max start position without finding start of substr
  if ($pos > $max_start_pos) {
    return false;
  }
}

This code passes for all of the following cases:

public function testExamples() {
      $this->assertEquals(isSubStr('cat', 'at'), true);
      $this->assertEquals(isSubStr('cat', 'fluffy'), false);
      $this->assertEquals(isSubStr('cheeze', 'ee'), true);
      $this->assertEquals(isSubStr('snow', 'o'), true);
      $this->assertEquals(isSubStr('octopus', 'top'), true);
      $this->assertEquals(isSubStr('octopus', 'zzz'), false);
      $this->assertEquals(isSubStr('octopus', 'pussy'), false);
      $this->assertEquals(isSubStr('octopus', 'tops'), false);
      $this->assertEquals(isSubStr('ababc', 'abc'), true);
      $this->assertEquals(isSubStr('abc', 'abc'), true);
}


str_replace vs array_map & trim on URL segments

Which version to use

I wouldn't care about the timing difference. There may be situations where it matters, but in almost all cases, both variants will be so fast that the difference becomes irrelevant (we are talking about a fraction of a millisecond here) and other factors should decide which version you use.

In this case, those other factors might be readability and reusability/adaptability. I think the second version is more readable, but as you said, the first version can be easily adapted.

So if you predict that you need to perform additional changes to the segments, go with the first approach, otherwise with the second.

Differences

Please note that the versions are not the same (the first one only trims slashes, while the second one removes them all). For your use-case, this doesn't matter.

But as this code will probably be wrapped in a function which may then be reused in different contexts (you could eg pass the slash as argument, and then use the function to trim whitespace from arrays (for the first version), or you could use it to remove an unwanted character from the segments (for the second version)), it still matters.


If you’re using HTML5 <nav> element, it’s not necessary to apply a role of ‘navigation’ – certain HTML elements inherently pass their relevant roles to the accessibility API. If you were wrapping the navigation menu in a <div>, for example, then you’d need to apply a role of ‘navigation’.

Role="menubar" has been correctly applied to the <ul> element, as has role="menuitem" to the <a> tags.

I would suggest applying a role="none" to each <li> element; otherwise this could confuse some users of assistive technologies since listitems and menuitems would be interspersed with each other.

Might be an idea to provide an aria-label to the <ul> with role="menubar"; used to help people understand the menu purpose and uniquely identify it from other menubars on the page.

Can also apply a tabindex="0" to first and last <a> elements – gives keyboard focus to link and makes a part of the tab order of the page. Alternatively, give a tabindex="-1" to make <a>s focusable but not part of the tab order of the page.


Converting time in number of minutes past midnight to HH:MM format

Following @Martin R's comment, I'll make my comment above a solution:

printf already supports what you're trying to achieve with your if-then-else jungle:

#include <stdio.h>

int main()
{
    int T;
    scanf("%d", &T);

    for (int i = 1; i <= T; i++) {

        int N;
        scanf("%d", &N);

        int hours = N / 60;
        int minutes = N % 60;

        printf("Case #%d: %02d:%02d\n", i, hours, minutes);
    }
}

You're also missing to check the return value of scanf. It is used to report errors in the input. What is the purpose of the first scanf?

Edit

From @chux's comment: you should validate the constraints of N after the input.

Edit

Note: additional variables should indeed have no influence on performance and are a good way to document meaning of your code, so please ignore my initial statement about "saving variables".

Old version was:

  Also, I'd change the variable naming. Use minutes instead of N to
  communicate clearly what you're handling in the variable. You can then
  write the computation directly in the parameter list of printf, saving
  you two additional variables.


Simple parsing for string formatting (version 2)

I think CS subjects like automata are too much for this problem, thats more something you have to deal with when implementing a regular expressions engine. Here is some code in C# that I've written to replace tags in a string, its absolutely not optimal because the state is checked every iteration and each character is copied individually, but you'll get the my idea.

private string ReplaceTags(string text, Dictionary<string, string> tags)
{
    StringBuilder result = new StringBuilder();
    StringBuilder tag = new StringBuilder();

    int mode = 0;

    int len = text.Length - 1;

    for (int i = 0; i <= len; i++)
    {
        char c = text[i];

        if (mode == 0)
        {
            if (text[i] == '\\')
            {
                i++;

                if (i <= len)
                {
                    result.Append(text[i]);
                }
            }
            else if (text[i] == '[')
            {
                mode = 1;
            }
            else
            {
                result.Append(text[i]);
            }
        }
        else
        {
            if (text[i] == ']')
            {
                string _tag = tag.ToString().ToLowerInvariant();

                if (tags.ContainsKey(_tag))
                {
                    result.Append(tags[_tag]);
                }

                tag.Length = 0;
                mode = 0;
            }
            else
            {
                tag.Append(text[i]);
            }
        }
    }

    return result.ToString();
}


Shots from the hip, three decades since I seriously programmed shell notwithstanding:

document your code - in the code.
The comments presented are a good start - in the middle, irritatingly.
What is the whole script useful for, how shall it be used?
You can even have executable comments:
if called incorrectly or with -h, --help (or even -?), print a
Usage: to "standard error output"/file descriptor 2
Then there are things left open:
Why tee to es_passes.txt instead of redirect, have sed print the pattern space?  (I read Spanish_passes at first - the reason why in the following comment es may be as appropriate as elastic needed horizontal scrolling)
with security related artefacts, assess security implications
choose the right tool
this does not just depend on task at hand and tools available, but on "craftsperson", too
(Here, I might have chosen perl in the 90ies and Python in the current millenium century)
the options and commands to sed speak of GNU sed
• mention such in your question
• consider using --posix
don't use cat | command where command allows specifying input file(s)
prefer using awks patterns over separate filtering (e.g.,grep)
(unless input is massive):
awk '/PASSWORD kibana|elastic/{print $4}' es_passes.txt …
(not convinced piping to xargs -I is the way to proceed.)
the conventional "unix" way to eliminate duplicate lines is uniq, preceded with a sort where global uniqueness is necessary and altering line sequence admissible.


“Offset position on scroll” JavaScript snippet

Basic simplifications

It's good to extract duplicated expressions to a local variable:

scrollPercent = (s / (d - c) * 18);
scrollPercent02 = (s / (d - c) * 14);
scrollPercent03 = (s / (d - c) * 30);
scrollPercent04 = (s / (d - c) * 4);

This is equivalent but shorter and safer:

var coef = s / (d - c);
scrollPercent01 = coef * 18;
scrollPercent02 = coef * 14;
scrollPercent03 = coef * 30;
scrollPercent04 = coef * 4;

Similarly:

var position01 = -(scrollPercent * ($(document).width() - $stripe01.width()));
var position02 = -(scrollPercent02 * ($(document).width() - $stripe01.width()));
var position03 = -(scrollPercent03 * -($(document).width() - $stripe03.width()));
var position04 = (scrollPercent04 * -($(document).width() - $stripe04.width()));

Extract the common $(document).width():

var width = $(document).width();
var position01 = -(scrollPercent * (width - $stripe01.width()));
var position02 = -(scrollPercent02 * (width - $stripe01.width()));
var position03 = -(scrollPercent03 * -(width - $stripe03.width()));
var position04 = (scrollPercent04 * -(width - $stripe04.width()));

Btw, the above statements look a bit confusing with the oddly placed negative signs. If I rearrange them, this should be equivalent:

var position01 = -(scrollPercent01 * (width - $stripe01.width()));
var position02 = -(scrollPercent02 * (width - $stripe01.width()));
var position03 =  (scrollPercent03 * (width - $stripe03.width()));
var position04 = -(scrollPercent04 * (width - $stripe04.width()));

Using arrays

To convert to using arrays to be able to process with a loop,
you would need to create parallel arrays,
each with the same number of elements.
In this case 6, because that's the most diverse case you need to support.
Something like this, but I'm not sure it's really any better or more readable than the original:

var $stripes = [
    $('.stripe-01'),
    $('.stripe-02'),
    $('.stripe-03'),
    $('.stripe-04'),
    $('.stripe-05'),
    $('.stripe-06')
];

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    var coef = s / (d - c);
    var scrollPercents = [
        coef * 18,
        coef * 14,
        coef * 30,
        coef * 4
    ];
    var positions = [
        - (scrollPercents[0] * (width - $stripes[0].width())),
        - (scrollPercents[1] * (width - $stripes[0].width())),
          (scrollPercents[2] * (width - $stripes[2].width())),
          (scrollPercents[2] * (width - $stripes[2].width())),
          (scrollPercents[2] * (width - $stripes[2].width())),
        - (scrollPercents[3] * (width - $stripes[3].width()))
    ];
    var layout_param = [
        'left',
        'left',
        'right',
        'right',
        'right',
        'left'
    ];

    for (var i = 0; i < $stripes.length; ++i) {
        $stripes[i].css({
            layout_param[i]: positions[i]
        });
    }
});


Since the Roman numerals are fixed and known in advance, it would be more efficient to write:

translateRomanDigit :: Char -> Int
translateRomanDigit 'I' = 1
translateRomanDigit 'V' = 5
...

translateFromRoman = map translateRomanDigit

The compiler can implement translateRomanDigit as a jump table or as a binary search. Using lookup will always perform a linear search.

As for >>> vs . - there should be no difference except that >>> requires you to import Control.Arrow whereas . is provided for in the Prelude.


Python strings have a translate method that applies a substitution cipher. There is also a function str.maketrans (string.maketrans in Python 2) that helps with building the translation table:

>>> from string import ascii_lowercase as alphabet
>>> shift = 13
>>> cipher = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])
>>> print("caeser salad is tasty".translate(cipher))
pnrfre fnynq vf gnfgl

of coarse in python2(with a shift of 13) one can simply do "My Message".encode("rot13")


Dynamic loading of Javascript dependency graph

I have JavaScript module for loading dynamically script files by dependency graph:

But... why? There are libraries out there that already do this. Take for instance, RequireJS. Most libraries out there ship as UMD modules (defined as CommonJS, AMD, and global), you can easily drop them into RequireJS-like or Browserify-like workflows.

Also, if you already know the order at which the modules come in (because of your deps graph), why not take a step further and just use ES modules together with a bundler like Rollup? Together with Uglify, you can strip away unnecessary bloat. Aside from the tooling, ES modules explicitly define their dependencies. You don't need an external deps map.

Async loading of modules all at once only prevent render-blocking and make your site look fast. It does not speed up loading of the site. What makes sites faster is smaller or lesser dependencies, or async loading plus loading only what's needed at the moment.

Consider using the tools existing in the ecosystem instead of building your own.


JavaScript function that reuses a modal for adding, deleting, and viewing an item

Avoid inline handlers - they have way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with addEventListener instead.
While you could iterate over all buttons and add a listener to each, consider using event delegation instead: add a single click listener to the table, and on click, if the click was on a button, examine the button's attributes or index to see which one was clicked, and examine the data-id attribute to get the ID.
Something along the lines of:

    <button data-mode="view" class="btn btn-sm btn-default" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>
    &nbsp;
    <button data-mode="update" class="btn btn-sm btn-info" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>
    &nbsp;
    <button data-mode="delete" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>

$(table).on('click', 'button', function() {
  const { id, mode } = this.dataset;
  // ...
});

Always use const when you can - see https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6. let permits reassignment, which makes the code's intent harder to understand at a glance - whenever a developer sees a let, they may well think "This was declared with let, not const, so I need to be on the lookout for where this will get reassigned."
Give functions names with verbs - the loadingOverlay function might be more readable if it was named something like showLoadingOverlay or loadOverlay or something of the sort. (not sure what it does)
Accidental use of the comma operator - rowObjects['license', id] is equivalent to rowObjects[id]. Did you mean rowObjects['license' + id]? Consider using a linter to warn you about these sorts of potential mistakes automatically.
Array keys should be numeric only - if your keys are going to contain non-numeric strings like license, or if you aren't going to have all elements of an array filled, use an object instead:
const rowObjects = {};

Assigning titles concisely can be done by making an object indexed by mode string. When you need to figure out the title to set, just look up the property on the object: see below.
Abstract separate functionality into functions - see this anecdote. While you don't have to go that far, if you have a non-trivial block of code that does something somewhat separate from the rest of the code in a section, consider putting it into a function instead. I'd put the population of the $form into a function - see below.
Button toggling Instead of needsButton and inputsDisabled, consider hiding both buttons by default, then showing one or the other depending on whether delete, or something other than view was pressed:
const titlesByMode = {
    add: 'Add new license',
    update: 'Updating license',
    view: 'Viewing license',
    delete: 'Delete this license?',
};
$(table).on('click', 'button', function() {
    showLoadingOverlay(false, modal);
    const { id, mode } = this.dataset;
    modalMode = mode;
    if (mode === 'add') {
        $form.find('input').val('');
    } else {
        populateForm(id);
    }
    $form.find(':input').prop('disabled', mode === 'view' || mode === 'delete');

    $('h4#modal-title', modal).text(titlesByMode[mode]);
    // Hide both buttons by default:
    $('#submitButton', modal).hide();
    $('#deleteButton', modal).hide();
    if (mode === 'delete') {
        $('#deleteButton', modal).show();
    } else if (mode !== 'view') {
        $('#submitButton', modal).show();
    }
});

const populateForm = (id) => {
    const data = rowObjects['license' + id];

    $form.find('input#email').val(data.email);
    $form.find('input#key').val(data.activation_key);
    $form.find('input#expiration').val(moment(data.expiration).format('MM/DD/YYYY'));
    $form.find('select#type-select').val(data.type);
    $form.find('input#hidden-id').val(data.id);
};
```


Implementing equals(), hashCode(), toString() in the hierarchy like the Optional from Guava

Some remarks:

Why does getException() return a Throwable instead of an Exception? Or even better, a RuntimeException? More generally, what is the purpose of this method? If I were you I'd "drop" it and make .get() throw the wanted exception instead. Since the exception would be a RuntimeException, there would be no need to declare it.
Is it on purpose that PresentResult and AbsentResult are not final? What do you expect further subclasses to extend if anything?
Is it legal to initialize a PresentResult with a null value, an AbsentResult with a null exception?


Split big file into separate files depending on column's distinct values

It would be more efficient to open each file only once,
instead of reopening every time you need it.
Two obvious approaches come to mind:

Accumulate all the lines you want to write to files into a dictionary of lists, and then write to the files one by one. Given that your content is very large, this alternative may consume too much memory and therefore not suitable for your case.
Keep a dictionary of open file handles to write to.
If the lines are ordered in such a way that the lines that should go to the same file are grouped together, then you don't even need a dictionary, you could just keep track of the previous filename, so that if the filename is the same then append to the currently open file, otherwise close the current file and open a new one.

And most certainly you don't want to open input_path_file1 twice to read the first line and then again to process the rest of the file.
Opening it once would suffice, and instead of next(file) to skip the first line,
you could store it with first_line = next(file).

The variable rows is not used, so it could be removed.

The variable unique_values is a dictionary of counts,
but the counts are not used for anything.
So this could have been a set instead of a dict.


Print a double as a decimal with a specified precision

Well, there's the obvious stuff, like whitespace and declaring variables at their first point of use. For example:

static void     print_decimal(double decimal, int precision)
{
    size_t  integer;

    while (precision--)
    {
        decimal *= 100.;
        integer = (int)decimal;

could usefully be rewritten as

static void print_decimal(double decimal, int precision)
{
    while (precision--) {
        decimal *= 100.;
        size_t integer = (int)decimal;

This spots a bug: you fail to handle negative inputs. If you want integer to hold a signed int, you should define it as int (not size_t); and vice versa, if you want it to hold an unsigned size_t, you should be casting (size_t)decimal (not (int)decimal).

    if (!precision  && (integer % 10) >= 5 && decimal != (double)integer)
        integer += 10;

This line could use some comments. I imagine it has something to do with rounding?

    printf("%i", integer);

It's more idiomatic to use printf("%d", integer) to print a decimal integer in C (and C++). True, %i exists, but it's deservedly obscure.

(Also, because of the above bug where you made integer a size_t, down here you should be using %zu to print it. But once you make it an int, you can go back to using %d.)

Every compiler will warn you about the format-string mismatch between %i and size_t. Are you compiling with -Wall? (No.) Why not? (There's no reason not to.) So, start compiling with -Wall today! It'll find your bugs so that you don't have to.

Performance-wise... I conclude from context that you expect this line to only ever print one digit, is that right? That is, your code could benefit from some "design by contract":

    assert(0 <= integer && integer <= 9);
    printf("%i", integer);

If the assertion is correct, then we can speed up the code by writing simply

    assert(0 <= integer && integer <= 9);
    putchar('0' + integer);

However, by adding the assertion, we have made the code a little bit testable. We can write some simple tests — just loop over all the floating-point numbers in the world and see if any of them fail the assertion — and indeed it doesn't take long to find one that fails.

print_decimal(0.097, 2);

This prints

010

when it should actually have printed

10

according to my understanding of your intent.

Which reminds me: print_decimal is a weird name for this function, since it literally does not have the ability to print a decimal point! Even your example print_decimal(65.226, 4) actually prints 652260, not 65.2260. This seems problematic for your prospective users.

So in conclusion:

Make your code testable.
Test your code.
Compile your code with -Wall.


Show/hide text field depending on select option

You can use Conditional (ternary) Operator.

Syntax :

condition ? expr1 : expr2

Reformated code :

function showHide(){
    var selectedValue =document.getElementById("choice_criteria_id").value;
    document.getElementById("id_src_addr").style.display = (selectedValue == "source_ip") ? "inline" : "none";
    document.getElementById("id_dst_addr").style.display = (selectedValue == "dest_ip") ? "inline" : "none";
    document.getElementById("id_port").style.display = (selectedValue == "port") ? "inline" : "none";
    document.getElementById("id_port_range").style.display = (selectedValue == "port_range") ? "inline" : "none";
}

Example in CodePen


This is doomed to failure:

struct StringArg
{
    int length;
    char* data;
    StringArg(const char* inData)
    {
        length = strlen(inData);
        data = new char[length+1];
        strcpy(data, inData);
    }
};

This can only lead to disaster. It is unlikely it is more efficient than std::string and is much more likely to lead to memory leaks.

Use std::string it will work is correct and has been optimized very heavily you can not beat it using your own hand written one. This is a premature optimization.

Same Again:

struct StringReturn
{
    int size;
    char* data;
    StringReturn(int inSize)
    {
        size = inSize;
        data = new char[size+1];
    }
};

Don't pass pointers around:

StringArg* stringArg(char* line)
{
    return new StringArg(line);
}

Use std::unique_ptr to encapsulate the pointer object so that it does correct memory management. If you are doing things correctly the resulting code optimizes to a no-op and if you don't do things correctly it saves your ass. In fact I would just throw away your string classes and use std::string. The copy construction from a return is nearly always elided by NRVO and thus is much more efficient than you seem to think.

Same Again

StringReturn* stringReturnInfo(int size)
{
    return new StringReturn(size);
}

Manually copying a C-string is very painful. Use std::string

    int lengths = str->length;
    char* urlData = new char[lengths+1];
    char* fmt = new char[4];
    memcpy(urlData, str->data, str->length);
    urlData[lengths] = 0;

    // Or you can do:

    std::string urlData = line;

Also your code is not exception safe.
Please use RIAA to make sure that there are no leaks (or use std::string that does this already).

The definition of a URL can be found here: http://tools.ietf.org/html/rfc3986
Pretending the '+' is a space is only valid in the path section of a URI and not valid in the query or fragment parts of the URI thus scanning the whole string for '+' is not correct.

  I also need to completely decode the string. I am aware of double encoded attacks

The specification does not allow for double (or nested) encoding. If it decodes to another '%' then that is the value. You don't try and re-interpret that value.


x86 assembly function that determines whether an array is continuous

My thoughts, in no particular order:

I'm ok with the comments.  Some things seem obvious to me, but I'd rather have an unneeded obvious comment than have something that ISN'T obvious (to me) lacking a comment.
The label names seem fine.
You might want to include the C prototype as a comment in the asm code.  If someone wants to use this code, being able to copy/paste this into their C code might be valuable.
You might want to special case handling the first array entry.  Not much point in comparing the value you just read with the memory location you just read it from.  Maybe inc edx right before continuity_loop and move the inc ecx to right after?
How about changing the return codes so that -1 indicates success, 0 indicates bad length, and >0 indicates the mismatched index?  This lets you return more useful information than just 'failed'.  Also, it helps with how often you have to set eax (hint: move the xor eax, eax up after the push; then eax already contains the 'right' return value in 2/3 cases).
Spacing problem on inc     ecx?

Note I haven't tried the things I'm suggesting.  Sometimes things look good in abstract, but don't work out as neatly when you actually try to write them.

There might be some way to tighten up continuity_loop, but (other than moving the inc ecx) I'm not seeing it right now.  If you end up making the other changes, I can give it a second look.


This isn't that much of a mess at all. Let's clean it up, then get a little fancy.

Right off the bat it seems a little funky to have a None Gender, as it appears you're not actually trying to account for agender individuals but instead providing for the failure to produce a Gender for a particular Client. Operations that might fail in Haskell usually signal so by returning a Maybe value, so let's drop None from the definition and see what needs changing.

data Gender = Male | Female | Unknown
              deriving (Show, Eq)

genderCount and cGender depend on None, let's start with the latter. c doesn't mean much as a prefix to me, so I'm going to call this function clientGender, but that's a stylistic preference. Changing this function to use Maybe is straightforward.

clientGender :: Client -> Maybe Gender
clientGender GovOrg {}       = Nothing
clientGender Individual {..} = Just (gender person)
clientGender Company {..}    = Just (gender contact)

Now let's turn to genderCount. The first thing to notice is that the function is a tiny wrapped up case statement. This is usually a code smell to me that hints at a missed opportunity to break functions into smaller, more independent pieces. In this case genderCount has nothing to do with Clients, so let's rip that part out!

genderCount :: Gender -> (Int, Int, Int) -- Counting Genders, not Clients!
genderCount Male    = (1, 0, 0)
genderCount Female  = (0, 1, 0)
genderCount Unknown = (0, 0, 1)

This is still unsatisfactory, right? There's that convention-typed tuple, and we've got a perfectly good GenderCount datatype lying around, so let's use it.

genderCount :: Gender -> GenderCount
genderCount Male    = GenderCount 1 0 0
genderCount Female  = GenderCount 0 1 0
genderCount Unknown = GenderCount 0 0 1

It's a small change, but users of GenderCount can rely on the field names rather than a tuple ordering.

And now countGenders, the piece that glues it all together. Our type is still correct, which is awesome! No changes there. The implementation though is doing a few different things we'll need to adjust. In an informational sense it's determining the genders of all of the clients, then accumulating a count of each Gender. What it looks like though is some weird tuple math to produce a GenderCount value from nowhere! We can rewrite it given our new implementations to be a little prettier, but first we're going to need a way to add two GenderCounts together.

addGenderCounts :: GenderCount -> GenderCount -> GenderCount
addGenderCounts (GenderCount m f u) (GenderCount n g v) = GenderCount (m + n) (f + g) (u + v)

A lot of repeated instances of GenderCount in there, but that's not so bad given we can use this as a combinator. Now we can put our countGenders function together.

countGenders :: [Client] -> GenderCount
countGenders = foldr (addGenderCounts . genderCount) (GenderCount 0 0 0) . mapMaybe clientGender

This works! I've imported mapMaybe from Data.Maybe here to account for our clientGender function sometimes returning Nothing (mapMaybe drops all the Nothings and returns a list of the Just values). We use a right fold to accumulate our GenderCount values, and a starting value of GenderCount 0 0 0 for our accumulator.

There are a few ways to go from here to clean things up further. You could get rid of the GenderCount 0 0 0 value by using foldr1, at the cost of adding another composition with map into the mix. If you have sharp eyes and a working knowledge of the Typeclassopedia you'll note a striking similarity between the way we use GenderCount with a right fold, and a Monoid. If you don't have a working knowledge of the Typeclassopedia, our motivation is that Monoids allow us to specify an identity element and an associative reduction operation, revealing some higher level abstractions (and functions) we can use to wire our code together. Let's make a Monoid.

instance Monoid GenderCount where
    mempty = GenderCount 0 0 0
    mappend = addGenderCounts

-- Laws:
-- mempty <> x = x
-- x <> mempty = x
-- x <> (y <> z) = (x <> y) <> z

I won't prove the Monoid laws, but you should be able to see that they are trivial given the properties of addition and our definition of GenderCount.

Let's try one more pass at countGenders now.

countGenders :: [Client] -> GenderCount
countGenders = foldMap genderCount . mapMaybe clientGender

Nice!


One thing I noticed.  You're modifying the loop counter inside the loop to run another loop.  This is one way in a large project to create unseen bugs. By keeping track of the previous character it is fairly easy to code this with only one loop.

Your trapping strings that have other characters besides letters, but you're neglecting empty strings and null.

Here's one way the revised code can look:

static string Encode(string input)
{
    if (input == null || input.Length == 0)
    {
        ArgErrHandler("String must have at least one letter.");
    }
    if (input.Any(x => !char.IsLetter(x)))
    {
        ArgErrHandler("String must have only letters.");
    }
    if (input.Length == 2 || input.Length == 1)
    {
        return (input.Length == 1 || input[0] != input[1]) ? input : $"{input[0]}{2}";
    }
    int limit = input.Length - 1;
    int counter = 1;
    StringBuilder sb = new StringBuilder();
    int i = 1;
    char prev = '\0';
    do
    {

        prev = input[i - 1];
        if (input[i] == prev)
        {
            ++counter;
        }
        else
        {
            if (counter > 1)
            {
                sb.Append($"{prev}{counter}");
            }
            else
            {
                sb.Append(prev);
            }
            prev = input[i];
            counter = 1;
        }
    } while (++i < limit);
    if (input[i] == prev)
    {
        ++counter;
        sb.Append($"{prev}{counter}");
    }
    else
    {
        if (counter > 1)
        {
            sb.Append($"{prev}{counter}{input[i]}");
        }
        else
        {
            sb.Append($"{prev}{input[i]}");
        }
    }
    return $"{sb}";
}
private static void ArgErrHandler(string message)
{
    throw new ArgumentException(message);
}


Function to test whether the source and destination squares represent a valid knight move

It looks like there may be an issue in range-checking.

You don't check for the rows and columns to be non-negative.
( < 0 ) The types aren't marked as unsigned, so they might be negative.
If board is zero-based, and it seems to be, checking against numXYZ should include the boundary.
( >= board.numXYZ() )

The range check becomes:

if ( r1 < 0 || r1 >= board.numRows() ||
     r2 < 0 || r2 >= board.numRows() ||
     c1 < 0 || c1 >= board.numCols() ||
     c2 < 0 || c2 >= board.numCols() ) {
  return false;
}

The jump check can be simplified. The absolute distance in one dimension must be one, and in the other must be two.

unsigned int rowdiff = abs(r1 - r2);
unsigned int coldiff = abs(c1 - c2);
if ( rowdiff == 1 && coldiff == 2 || rowdiff == 2 && coldiff == 1 )

Alternatively, we can note that the product of the distances must be ±2, leading to a more concise check, but that may obscure the underlying objective:

if ( abs((r1 - r2) * (c1 - c2)) != 2 ) return false;

At which point the final check is:

return board[r1][c1] == "knight" && board[r2][c2] == "";


Remove row when everything in the row is same

The proper way to do this is use the Range.RemoveDuplicates method.

Here is the refactored macro created by clicking the Remove Duplicates button on the Data tab of the Ribbon.  Array(1, 2, 3, 4, 5, 6) contains all the column numbers that need matching data for a row to be deleted.

Application.ScreenUpdating = False
Range("A1").CurrentRegion.RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6), Header:=xlYes


Instead of rewriting the code you can just trigger the change event after you bind it which will cause it to sync on page load

$('select').change(function() {
  var optionText = $(this).find('option:selected').text();
  $(this).prev().text(optionText);
}).trigger('change'); // <-- trigger change


Assigning values to a particular table column

One big problem is that your code is not complete so I have to guess. In the future please post complete working code.

There are some obvious inefficiencies in your code, though I'm not sure if the compiler will fix them for you or not, but it's still good programming practice to:

What's the point of the second numberOfFilledRows(); ?
You have the same code repeated three times, with the only difference being the two strings, one used as the index to dataRow[] and the other being put in the string concatenation. In cases like this you should factor out the common code to a separate function.
You repeatedly call rowIndex.ToString(). The compiler may be smart enough to put this in a temporary variable, but this is a clue that you're doing something the wrong way. You don't say what type worksheet is, but isn't there a method that takes two ints for the row and column numbers?
your numberOfFilledRows() is reinventing the wheel. Excel already has functions to find the end of a range (probably much faster too).

EDIT Also, the fastest way to check if a string is empty is to compare the .Length member to 0. See http://www.dotnetperls.com/empty-string

You may also want to look into StyleCop and/or FXCop.


Functions to hide and reclaim first visible publication on a page using Selenium

As the code is similar, they can be merged together.

I'll suggest you to break down the functions into smaller reusable chunks which will follow the Single Responsibility Principle (SRP). These functions will be testable and reusable.

Both functions are

Adding a delay of 500 milliseconds
Selecting elements from provided page
Clicking the first element from the collection
Finding an element from its ancestor and returning the innerText of it.

As these are the steps, we can similarly divide those functions into smaller functions each doing the task of one step above.

For first step (to add delay) I've not created a new function as I guess that is already created in utils module.

The first function (Step #2) will select the elements from the page using the provided xpath and return the first of them.

function getFirstVisiblePublication(page, xpath) {
    aqUtils.Delay(500);

    var elements = page.EvaluateXpath(xpath);
    return elements[0];
}

The second function combines Steps #3 & #4; as #3 only requires to click the element I haven't created new function.

The below function will accept the page in which the target element is to be searched and xpath of the element. This will call the above function to get the first element and click it.

This function will return the text/label of the anchor element which is obtained by using the first element's ancestors.

function getFirstVisiblePublicationAnchorLabel(page, xpath) {
    // Get first element
    var firstElement = getFirstVisiblePublication(page, xpath);
    firstElement.Click();

    return firstElement.parent.parent.FindChildByXPath('//a').textContent;
}

Usage:

Function can be called as follows:

var hideButtonXpath = "//img[@title='To hide this item in your profile, mark it as invisible']";
var publicationTitle = getFirstVisiblePublicationAnchorLabel(PageObj, hideButtonXpath);


VBA- Retrieving data from an access database by referencing a column in excel

I would suggest that instead of building such a large WHERE clause dynamically, and running into the 64K character limitation of a query's text, that you create a table and insert into it the data from Excel. Your SQL then becomes:

SELECT Sheet2.Material, Sheet2.MPN
FROM Sheet2
INNER JOIN TempSelection
  ON Sheet2.Material = TempSelection.Material

which will work with large amount of selection.

To achieve this, you should create the table TempSelection in Access - it only needs one column, Material of the same data type as the Sheet2 table (is that a linked table to Excel or an actual Access table that was imported from Excel? If imported, good; otherwise, I encourage you to import data instead).

Then your For...Next loop would now look similar to this...

db.Execute "DELETE FROM TempSelection;", dbFailOnError
Set rsTemp = db.OpenRecordset("TempSelection", dbOpenDynaset)
For Each r In Range("A2:A6768")
  rsTemp.AddNew
  rsTemp.Fields("Material").Value = r.Value2 'Or, r.Value if needed
  rsTemp.Update
Next r


Saving the values of all variabled declared in a block

Since this will be used at toplevel anyway, I would just wrap all the parameters in a module.

macro param_save(file, blk)
    modname = gensym()
    Expr(:toplevel,
        Expr(:using, :JLD),
        Expr(:module, false, modname, esc(blk)),
        quote
            JLD.save($file, Dict(
                string(n) => eval($modname, n)
                for n in names($modname, true)
                if n ≠ $(Meta.quot(modname))))
        end)
end


Shortest and most efficient way for an endless image/content rotation in Vanilla JS and jQuery

Eliminating functional differences between Vanilla JS and jQuery versions

Your vanilla script and your jQuery script are not functionally equivalent. Your vanilla is selecting the container by its ID, while the jQuery is selecting the container by its class and then selecting the images. Your vanilla script would more closely resemble the jQuery by using document.querySelector() and/or document.querySelectorAll().

e.g.: var images = document.querySelectorAll('.container > img');

Making it work for multiple containers

Your code will function strangely if more than one image rotator container is on the page: the jQuery will grab image elements from all the containers and only set one to active at a time, while the vanilla javascript will only change elements in the first container it grabs.

(EDIT: As you noted in the comments, you can work around this by selecting the different containers by ID before passing them to your function, but that approach requires manually specifying IDs both in the HTML and in the JavaScript. Ideally, you'd be able to just add more elements with the appropriate classes in the HTML to take advantage of the existing image rotator  functionality.)

With a little tweaking, you can ensure your code processes each container separately (allowing each container to have its own active image).

var containers = document.querySelectorAll('.container');
for (var i = 0; i < containers.length; i++) {
  beginRotation(containers[i]);
}
function beginRotation(container){
    setInterval(function() {
        var current = container.querySelector('.active');
        current.classList.remove('active');
        var next = current.nextElementSibling || container.firstElementChild;
        next.classList.add('active');
    }, 2000);
}

The above code first grabs all the elements with the container class, then sets the interval to run on each of them.

Minor nitpick(s)

You don't need that semicolon at the end of your if(e){ ... } statement in your vanilla js example.

Supporting older browsers (if you have to)

IE9 and below do not support classList, so if you want to support them you'll have to use the className property.

To remove a class, something like this would work:

current.className = current.className.replace("active", "").trim();

and its complement to add a class:

next.className = (next.className + " active").trim();

Note that this only really works because we know what to expect in the class names. This would break, for example, if you had an element with a class my-active-class because it would replace the substring active. A better (but more tedious) approach would be to split className into an array (using element.className.split(" ")) and check each array element for the desired class.

You'd also want to be aware that although IE9 supports CSS opacity, it doesn't support CSS transitions. The end result is that the images will transition promptly instead of fading in and out for IE9 users.

Working Example

var containers = document.querySelectorAll('.container');
for (var i = 0; i < containers.length; i++) {
  beginRotation(containers[i]);
}

function beginRotation(container) {
  setInterval(function() {
    var current = container.querySelector('.active');
    current.className = current.className.replace("active", "").trim();
    var next = current.nextElementSibling || container.firstElementChild;
    next.className = (next.className + " active").trim();
  }, 2000);
}
.container > img {
  opacity: 0;
  position: absolute;
  -webkit-transition: all 1s linear;
  transition: all 1.5s linear;
}
.container > img.active {
  opacity: 1;
}

&nbsp;

EDIT: Efficiency Suggestion(s)

Caching DOM Queries

You can make the code in setInterval more efficient by getting all the necessary DOM operations out of the way beforehand.

If you want to reduce the number of DOM queries (which are typically expensive operations) you can cache an array of references to all the relevant  elements and then reference that array in the setInterval function.

I know you're hoping for the "shortest and most efficient way", but this would be for efficiency at the expense of brevity, since you'd need to set up an extra variable to track the index of the active image. Using this index would save your code from having to read the current classLists of the images, requery the container element to get the active image, and traverse the DOM for the next sibling or first child.

var containers = document.querySelectorAll('.container');
for (var i = 0; i < containers.length; i++) {
    beginRotation(containers[i], containers[i].querySelectorAll('img'));
}
function beginRotation(container, imgs) {
    var i = getIndexOf(container.querySelector('.active'), imgs);
    setInterval(function () {
        imgs[i++].classList.remove('active');
        imgs[(i == imgs.length ? i = 0 : i)].classList.add('active');
    }, 2000);
}
function getIndexOf(target, arr) {
    var len = arr.length;
    while (len--) {
        if (target == arr[len]) {
            return len;
        }
    }
}


This is ok since it's valid CSS anyways. However...

The problem with both approaches (.btn-accordion.is-active and .accordion-menu .is-active) is that they're least 0020 in specificity. Should you ever want to override, the override must at least have a specificity of 0020.

.btn-accordion {
  color: red;
}
.btn-accordion.is-active {
  color: blue;
}

/* overriding selector needs to be at least the same specificity */
.btn-accordion.is-active {
  color: green;
}

In the case where you can't control order of the styles, you can raise the specificity. However, this would equate to longer selectors and/or harder-to-override selectors.

.btn-accordion {
  color: red;
}

/* An override appearing earlier in the styles */
/* Specificity: 0021 */
li.btn-accordion.is-active {
  color: blue;
}

/* Specificity: 0020 */
.btn-accordion.is-active {
  color: green;
}

CSS tightly coupled to the HTML structure are fragile. Accidentally removing/renaming the class name, the selector becomes useless. If the HTML structure changes, the selectors also become useless.

Long chains of selectors are also hard to maintain. You do not know how deep a selector is relative to its parent/descendant selector. It's also hard to figure out if a combination of selectors is even used on the page, leading to excess fat on the CSS.

One way to avoid specificity climb is to use BEM naming scheme. This allows you to write selectors with just one class while being able to specify the containing block, block contents and modifiers.

With the following code, it allows me to know the accordion-menu__button belongs to accordion-menu set of elements and that it has a accordion-menu__button--is-active state. Since the selectors are just 1 class name, modifier selectors can predictably be placed after the selectors they modify. It also allows me to easily deduce that a style is applied since it doesn't depend on the HTML nesting structure.

/* Default state of the button */
.accordion-menu__button{
  color: red;
}

/* Override the color when the button is active */
.accordion-menu__button--is-active{
  color: green;
}

However, this would mean that every target element will have a class. But in most cases, especially in large apps, you will have templating mechanisms that will do all this repetitiveness for you and the tradeoff of writing this way vs manageability of the code is justifiable.


Object with highest count in a Groovy list

You could obviously try parcels.max{it.count}.

max and other useful operations on Groovy Collections are explained in the following article:
https://groovy.codeplex.com/wikipage?title=Collections


I write to the file in the test method so I can see where/how it failed.

Don't do that. This:

using (var file = new System.IO.StreamWriter(@"C:\Users\Hosch250\Documents\Visual Studio 2013\Projects\ConsoleApplication14\ConsoleApplication14\TestFile.cs", true))
{
    file.WriteLine("Expected Count: " + expectedTitles.Count);
    file.WriteLine("Actual Count: " + titles.Count);
}

Has just become a possible reason for your test to fail that has nothing to do with your test. For example, if this was part of a test suite in a repo on GitHub, I couldn't run this test successfully. It's important that tests be portable and deal only with the code under test.

If you really want to know exactly which item caused your test to fail, use the overload that takes a message string.


public function validBraces($braces) {

I'd call this isValidBraces instead to show that it returns a Boolean value.  This also makes it read a little better in normal usage.

if ($braces === "") {

The difference between "" and '' is that the double quoted string allows variable interpolation.  Since you are not using variable interpolation, consider

if ( '' === $braces ) {

The single quoted string will also be slightly quicker to interpret, although I don't know that the difference would matter in this case.

I also changed the order.  It's not uncommon to see the constant on the left in C-based languages.  This is because '' = $braces would give a compiler error while $braces = '' will happily evaluate as false and continue.

Incidentally, you don't need this statement, as the later for loop and count check will handle this case for you.  There's an argument that the code is a little cleaner without this check.  It certainly would be a little shorter.

$balance = array();

I might call this $open_braces.  It doesn't balance anything.  It's a stack of all the currently open braces, so call it that.

for ($i = 0; $i < strlen($braces); $i++) {

As a general rule, you want to avoid calling a function on every loop iteration which always returns the same value.

for ($i = 0, $n = strlen($braces); $i < $n; $i++) {

That way you only do the strlen call once at the initialization of the loop.  Each iteration can do the simpler check instead.

  if (!($braces[$i] === "(" || $braces[$i] === ")"
       || $braces[$i] === "{" || $braces[$i] === "}"
       || $braces[$i] === "[" || $braces[$i] === "]")) {

It's possible to write the if more simply by first defining a constant:

private $closing_match_of = array( '(' => ')', '{' => '}', '[' => ']' );

Then set a variable in the function before the loop starts:

$opening_match_of = array_flip($this->closing_match_of);

The array_flip will reverse the arrows from the way that they are in CLOSING_MATCH_OF.  So where you had '{' => '}', you will now have '}' => '{'.  Using the array_flip ensures that you will have parallel matches in both.  You could declare a second constant, but then that would be fragile in the face of changes.  This way you can make changes in a single place.

Then replace the if as follows:

  if ( isset($this->closing_match_of[$braces[$i]]) ) {
    $open_braces[] = $braces[$i];
  } elseif ( isset($opening_match_of[$braces[$i]]) ) {
    if ( array_pop($open_braces) !== $opening_match_of[$braces[$i]] ) {
      return false;
    }
  } else {
    throw new InvalidArgumentException('Invalid string');
  }

This checks if the character at position $i in the $braces string has a closing match (i.e. is a key in the $this->closing_match_of array).  If so, then you know that it is an opening brace and add it to the list of things that you need to match.  If not, it checks if $braces[$i] has an opening match (i.e. if it is a key in the $opening_match_of array).  If so, then it checks to see if it matches the most recent unmatched open brace.  If not, then it returns false to indicate that the string does not consist of matching braces.

The final case is if the character has no closing match nor opening match defined in the arrays.  In that case, it's not a brace.  Since the string is supposed to consist entirely of braces, it throws the exception.  We don't have to check anything in this case because we already did the checks earlier in the if and elseif clauses.

If you are only adding one element to the end of an array, the []= operator is more efficient than an array_push.

I changed the order of the checks to avoid repeating them.  The other way you did two or three checks on a valid case and two on an invalid case.  This way, you do one or two on a valid case and two on an invalid case.  Hopefully the valid cases are more common.

Note that I haven't tried to run or test this code.


First: welcome to CodeReview! I hope that you get good feedback.

About your code. Your usage of Python is not terrible; most of your problems are conceptual, about the decisions you've made about your class. Looking at the method signatures from the outside, one would guess that addRate() can be called multiple times per single Bank instance, and that convert would then allow for any currency to be converted. That isn't the case; instead, your "Bank" class is actually closer to an "ExchangeRate" class.

There are two ways to go, here. Either make your class an ExchangeRate, in which case

you need to rename the class
convert, rather than accepting the name of a currency, should perhaps accept a forward boolean. Or, if you want to keep passing the name of a currency, it's important to make the argument name more clear, i.e. dest_currency.
Rename your addCommission to setCommission. "add" implies having more than one.
Rename your addRate to setRate. "add" implies having more than one.

Or, keep a "Bank" class, in which case:

you need to change the way that you store your exchange rates, probably to a dictionary-based system instead of a single float member
convert would accept both a source and destination currency
addRate's signature would stay the same, but its contents would change to use your dict.


Implementing my own shared-ownership double-indirecting smart-pointer

I wouldn't call it SharedPtr because the contrast to a std::shared_ptr is too big, and the name too similar.
Maybe DoublePtr or alike to emphasize the double-indirection which is the crucial feature...
I would make Manager a private non-template member of your class, because it's an implementation-detail. Also, I would make it a dumb struct and put the useful function it contains (disown) into the private part of DoublePtr.
While having a default-ctor without allocation might be enough of a boon to allow a resourceless state (it probably is), there's no reason to disallow creating a pointer-group which starts as nullptr.
Thus I would remove the check in the ctor.
op= is wrong, try self-assignment. It should be disown after own.
op=(&&) would be better as a simple swap.
op(bool) is wrong: Use get() != nullptr.
reset and reset_all could easily be upgraded from basic to strong exception-safety (commit-or-rollback), just create a new DoublePtr and swap.
Many of your functions can and should be marked noexcept.
Also, pure observing methods should be marked const.


Handle static objects using custom adapter

I see no problem in such wrappers except they are kinda cumbersome to write. They provide a good way to decouple your code not only from static objects, but from the all the objects you cannot mock too (for example, sealed classes from 3rd party libraries). I use that kind of adapters myself and have little problem with them. It is important to have these classes as simple as possible (so that you don't need to test them) and only expose properties and methods you realy need.

Update: ctrucza suggests using a service locator in his answer. While it's a good solution when your class has many dependencies which leads to many constructor parameters, it makes unit-testing your class a little harder.

If you add some new dependency into your class and resolve it with some generic service locator's method then your code (including unit tests and production code) will compile just fine. You only realize that something is wrong when your working unit-tests will suddenly fail with null reference exception, or some other resolution exception your service locator provides. The constructor injection, on the other hand, gives you a clear knowledge of what dependencies a class using and if you miss some constructor parameter in your tests, the compiler will tell you.

One more thing. If you have a dozen dependencies in your class, may be the design of the class is wrong and refactoring is needed. I think that's really good indicator, which will be hidden if you are using a service locator pattern.


My 2 cents:

Code looks really good overall
In prependOverride, the naming is unfortunate

The parameter isLTR is really what you request, not what it is
The var direction really is a boolean, not the direction of the element
If you are going to /** type **/ variables, you might as well go Spartan and use e instead of element

prependOverride has 4 magical constants
isLTR should cache the regex, not rebuild it in every call

for prependOverride the following might be cleaner:

function prependOverride(/*HTML Element*/ e, /*Boolean*/ requiresLTR) {
    var hasLTR = getDirection(e) === "ltr";
    if (hasLTR !== requiresLTR) {
        e.innerHTML = (requiresLTR? "&#8237;" : "&#8238;") + e.innerHTML + "&#8236;";
    }
}

or, even you could pass the direction you require

function prependOverride(/*HTML Element*/ e, /*String*/ requiredLTR) {
    var actualLTR = getDirection(e);
    if (actualLTR !== requiredLTR) {
        e.innerHTML = (requiredLTR=="ltr"? "&#8237;" : "&#8238;") + e.innerHTML + "&#8236;";
    }
}

I will leave the naming of the magical constants to you.


Is this `img` creator decently secure from XSS?

The part of your code shown here does not look like it's vulnerable to XSS, but it could be cleaner. You seem to be doing 3 separate things:

Ensuring that a URI looks like a path to an image.
Ensuring that a URI doesn't contain certain characters like quotes and angle brackets.
Trimming whitespace from the ends of a URI.

Doing those things in discreet steps would be cleaner. If you trim the string first, you won't need to look at the match results, only check whether there was a match. That means you can avoid the poor style used in the construct if (m=foo) without having to rewrite that part, and you can eliminate redundancy.

You could use encodeURI instead of throwing out URIs with certain characters; this way the user doesn't have to encode those characters before passing you the string.

s = s.trim();
if (s.match(/^https?:\/\/.*?\.(bmp|png|webp|gif|jpg|jpeg|svg)(\?.*)?$/)) {
    // looks like a path to an image
    return '<img src="' + encodeURI(s) + '">';
}

If you are doing this on the client, consider creating an image element and returning that instead of returning a string.

s = s.trim();
if (s.match(/^https?:\/\/.*?\.(bmp|png|webp|gif|jpg|jpeg|svg)(\?.*)?$/)) {
    var img = new Image();
    img.src = encodeURI(s);
    return img;
}

Also, the regular expressions you are using and the one in this example will match things like http://lol.jpg; you may want to consider making it more strict.


The biggest thing here is that you should make the ShaderParam class itself generic, not just its SetValue method.  This will get rid of your type check and double cast (any time you have a type check or a double cast, chances are you're using the type system incorrectly).  It will also get rid of the ShaderParamFloat class completely.

For example:

public class ShaderParam<T>
{
    private T value;

    ... (other code here)

    public void SetValue(T value)
    {
        this.value = value;
        ...
    }
}

You can now use this for floats by instantiating a ShaderParam<float>, plus it works just as well for other types.

Some other comments:

Don't write comments that just duplicate the code.  A variable named valueChanged doesn't need a comment saying "If the value has changed" - that much is obvious from the name.  More importantly in this code, the method named EnsureSet() should have a comment explaining its purpose and why it should be called, not just a comment that expands the name into a longer sentence.  I'm not an OpenGL user so I don't know what GL.Uniform1() does, but that code is surprising to me and a comment to explain why it's written that way would be useful.
I take it you have good reasons for making some things public and others internal.  To me, those choices seem pretty arbitrary.  If it works in your situation, consider making the class itself internal and all members public.
I don't personally like making fields public/internal, though given that they are readonly, I could live with it.  I might personally still change this to use properties and a readonly backing field.  That gives you the added benefit of being able to set breakpoints later if you ever need to debug.
Not relevant if you make the first change above, but why is ShaderParamFloat still abstract?
The private fields in ShaderParamFloat should be explicitly marked private.
There is no need to initialize value to 0 or valueChanged to false.  Those are their default values.
I would personally call the class ShaderParameter instead of ShaderParam.  Your abbreviation is pretty obvious in this case, but I tend to stay away from all but the most commonly used abbreviations.  In particular, if using the abbreviation improves the readability of the code, then it makes sense.  I don't think that applies here.

EDIT:

Based on your updated question, I would still recommend a solution like I mentioned above, where the base ShaderParameter is a generic class.  However, it does make sense for you to derive classes from that with different implementations of EnsureSet.  For example:

public abstract class ShaderParameter<T>
{
    private T value;

    public abstract void EnsureSet();

    public void SetValue(T value)
    {
        this.value = value;
    }
}

public class FloatShaderParameter : ShaderParameter<float>
{
    public override void EnsureSet()
    {
        ...
    }
}

And you can then derive similar classes for the other types of parameters.  Note that you only need a single implementation of SetValue in the base, and it works for all derived classes.