A temporary directory that exists only during run time of user-specified code

Always set up the trap before trying to create the directory. Otherwise there's a race condition where the script may die after creating the directory but before having a chance to clean it up. And use single quotes for the trap command to make sure the variable is only expanded at exit:

trap 'rm -rf "$tmpdir"' EXIT
tmpdir="$(mktemp -d)"

If the trap ends up being triggered before mktemp the result is simply rm -rf "", which does nothing.

Some other suggestions:

#!/usr/bin/env bash is a more portable shebang.
set -o errexit -o nounset is more readable than set -ue.
BASH_SOURCE is an array, and it's only by accident that $array_name refers to the first element of array_name. directory="$(dirname "${BASH_SOURCE[0]}")" would be more explicit.
if [[ ! "$tmpdir" || ! -d "$tmpdir" ]] is redundant. If mktemp fails the script will stop there, and if it's been removed rm -rf "$tmpdir" is safe, as mentioned.
Don't use ls in scripts!
The temporary directory can't already contain any files. That's part of the contract of mktemp - it will create a new directory if it can, or fail otherwise.


Maybe using jQuery's $.data() to store a bool variable or something like that.

Also you could store a global variable with the active position (e.g. "3" for the 3rd item in the gallery), and then change it, using it along with the :eq() selector.

Either way, I think that the .active class approach is very useful because it gives you the chance to alter the CSS properties for that specific item on your gallery.


Slightly better way:

    candidates.close();                 //I know theres better than this

If improvement is based on this statement, then something like stringstream would be good fit.

Best way:

std::map<std::string, std::size_t> will fit the job nicely. After you've done with it, just iterate through and see if anything has counter equal to 2 or higher, and print those.

Roughly this:

std::map<std::string, std::size_t> appearance_count;
while (std::getline(answers, s))
{
    ++appearance_count[s];
}
while (std::getline(candidates, s))
{
    ++appearance_count[s];
}

for (const auto& reading: appearance_count)
{
    if (reading.second > 1)
    {
        std::cout << reading.first << '\n';
    }
}

Some edge cases:

There might be duplications in the first file, so it will require first adding into std::set, then adding to the map. Second file is unaffected by that, since any string with appearance count larger than 1 is already wanted. Though if the second file contains duplicates as well, you'll need two sets.


The algorithm

Given two string \$S\$ and \$Z\$, \$S\$ is a permutation of \$Z\$ if and only if they have the same multiset of characters. The fastest way of checking this is to sort the characters in each of the two strings which will produce two new strings \$S'\$ and \$Z'\$. Finally, if \$S' = Z'\$, \$S\$ is a permutation of \$Z\$. For example: \$S = \text{stop}\$, \$Z = \text{spot}\$, \$S' = Z' = \text{opst}\$.

You can improve the performance:

Create a HashMap<String, Integer>, call it "map",
For each "word" in the word file, do:
    Sort "word" by characters ("fdsbs" -> "bdfss")
    If "word" is not in "map":
        Put "word" into "map" with value "1"
    Else:
        map.put(word, map.get(word) + 1) # Increment count

In order to process an input word, just sort it by characters and do a simple lookup from map. Summa summarum:

import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;

public class Anagrams {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of test cases: ");
        int testCases = Integer.parseInt(in.nextLine());

        File file = new File("/path/to/words.txt");
        Map<String, Integer> map = readFile(file);

        for (int i = 0; i < testCases; i++) {
            String s = sort(in.nextLine());
            System.out.println(map.getOrDefault(s, 0) - 1);
        }
    }

    private static Map<String, Integer> readFile(File file) {
        Map<String, Integer> map = new HashMap<>();

        try (Scanner fileScanner = new Scanner(file)) {
            while (fileScanner.hasNext()) {
                String word = sort(fileScanner.next());

                if (map.containsKey(word)) {
                    map.put(word, map.get(word) + 1);
                } else {
                    map.put(word, 1);
                }
            }
        } catch (FileNotFoundException ex) {
            return null;
        }

        return map;
    }

    private static String sort(String input) {
        char[] chars = input.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
}


Functional programming approach to repeated function application

In terms of the functional programming paradigm, I would suggest the following for repeated:

def repeated(f, n):
    """Return the function that computes the nth application of f.

    f -- a function that takes one argument
    n -- a positive integer

    >>> repeated(square, 2)(5)
    625
    >>> repeated(cube, 2)(5)
    1953125
    """
    if n == 1:
        return f
    return lambda x: f(repeated(f, n-1)(x))

Note that, per the rule of thumb you have previously discussed, each statement can be replaced with its result and the function still works correctly.

You could also simplify the imports:

from operator import mul, pow

In terms of naming conventions, pylint doesn't like single-character names, so perhaps func and num would be better than f and n/x, but in general you don't have a problem here.

In terms of error handling, you don't currently have any. I don't think that's a problem either, though - the docstrings explain what the inputs are supposed to be, and the user should expect errors/weird behaviour if they supply anything else!


Java application processing GUI input when "Done" is clicked

1 import

I suggest you don't use the wildcard in your import statements, because

it clutters your namespace,
the maintainer of your code does not know what classes exactly you use in your code.

2 Main class

I would rename your class Main to, say, MyFrame, and declare it as a subclass of JFrame.

Summa summarum

All in all, I had this in mind:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class MyFrame extends JFrame {

    private final JPanel panel = new JPanel();
    private final JLabel instructionLabel = new JLabel("What's on your mind?");
    private final JTextArea textArea = new JTextArea(7, 30);
    private final JButton button = new JButton("Done");

    public MyFrame() {
        super("Diary"); // Sets the title to "Diary".
        this.setSize(400, 250);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.panel.setLayout(new BorderLayout(4, 2));
        this.panel.add(instructionLabel, BorderLayout.NORTH);
        this.textArea.setLineWrap(true);
        this.textArea.setWrapStyleWord(true);
        this.panel.add(new JScrollPane(textArea), BorderLayout.CENTER);
        this.button.addActionListener(new MyActionListener());
        this.panel.add(button, BorderLayout.SOUTH);
        this.getContentPane().add(panel);
        centerWindow(this);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> { new MyFrame(); });
    }

    private final class MyActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            try (PrintWriter writer = new PrintWriter("textfile.txt")) {
                writer.println(textArea.getText());
            } catch (final FileNotFoundException ex) {

            }

            MyFrame.this.dispatchEvent(
                    new WindowEvent(MyFrame.this, WindowEvent.WINDOW_CLOSING));
        }
    }

    private static void centerWindow(final Window window) {
        final Dimension dimension = window.getSize();
        final Dimension screen    = Toolkit.getDefaultToolkit().getScreenSize();

        window.setLocation((screen.width - dimension.width) / 2,
                           (screen.height - dimension.height) / 2);
    }
}

Hope that helps.


Why not use a hashmap as the main DS? That way, you optimize for when name and event are defined, and suffer only a constant penalty and degrades to linear for other cases. (In your solution the cost is always linear). (As below)

class Callbacks
  def initialize
    @callbacks = {}
  end

  def add(name, event, &block)
    key = {:name => name, :event => event}
    @callbacks[key] = block if block_given?

shouldn't we throw an exception if block is not given?

  end

  def get(o={})

We can use values_at to extract multiple values from a hash.

    name,event = o.values_at(:name,:event)

We don't need to check if name and event separately because equality checking does it for us.

    return @callbacks[o] if name and event
    @callbacks.each do |k,v|
      return v if k[:name] == name or k[:event] == event
    end
    nil
  end
end

And shouldn't you provide a way to unregister from callback?


Using range minimal query for lowest common ancestor (LCA) -- part 2

advice on ... code style

Including docstrings would be good, e.g. to spell out that RMQ denotes Range Minimal Query.
But as a more pressing matter, your identifiers are much too ambiguous.
The names rmq_index or node_index_map are just not helpful as you never describe an index, and result and raw_array are even worse. At least stick to one or the other, don't use both of them to describe the same thing.
Not once did you refer to the literature (e.g. Schieber and Vishkin), nor comment on an invariant you were maintaining.

It would be helpful to include sample in/out values in the SO posting or, better, in the comments or docstrings. You regrettably ignored the advice to use flake8.

    self.value = value

This appears to be more of a unique id than some continuous value.

    for i,v in enumerate(raw_array):

This may have been clearer as for i, depth_id.

It's not clear how a step is different from a depth.

In ... self.rmq_index[(i+2**(step-1), step-1)][0] < self.rmq_index[(i, step-1)][0]: it would have been helpful to break out depth_left & depth_right and compare them.

These look like they are useful tests:

print rmq.rmq_query(node_index_map[4], node_index_map[5])
print rmq.rmq_query(node_index_map[4], node_index_map[7])

but they would be far more informative in the form of assertEqual statements in a unittest.TestCase.


std::ceil(static_cast<double>(size) / 2 is a very long (and unclear) way to say size - size/2.
No naked loops please. Each loop represents an important algorithm, and deserves a name. For example,

while (array1 != array1end)
    new_array[na_pos++] = *array1++;

wants to be copy(new_array + na_pos, array1, array1_end);, and you may reuse it at least 2 more times (and don't make it void: it has something interesting to return).

Similarly, the merging loop represents a merge algorithm.
The block

if (*array1 < *array2)
    new_array[na_pos++] = *array1++;
else if (*array2 < *array1)
    new_array[na_pos++] = *array2++;
else if (*array1 == *array2) {
    new_array[na_pos++] = *array1++;
    new_array[na_pos++] = *array2++;
}

introduces a subtle problem. Here your algorithm may lose stability. If array1 has two elements comparing equal, say x1,x2, and array2 has an element x3 which also compares equal to them, the final arrangement will be x1, x3, x2, whereas the stable sort should result in x1, x2, x3.

The problem is easy to fix:

if (*array1 <= *array2) {
    new_array[na_pos++] = *array1++;
} else {
    new_array[na_pos++] = *array2++;
}

I strongly recommend to put the loop termination conditions where they belong:

while ((array1 != array1end) && (array2 != array2end))


Converting binary value from BitArray to an int and back in C#

You've made it much more complicated than necessary.

The conversion to a BitArray needlessly copies the values to the bool array bits.  You could instead use that on the conversion back to int.

public static class BinaryConverter
{
    public static BitArray ToBinary(this int numeral)
    {
        return new BitArray(new[] { numeral });
    }

    public static int ToNumeral(this BitArray binary)
    {
        if (binary == null)
            throw new ArgumentNullException("binary");
        if (binary.Length > 32)
            throw new ArgumentException("must be at most 32 bits long");

        var result = new int[1];
        binary.CopyTo(result, 0);
        return result[0];
    }
}


Overriding Backbone.Collection.add to enforce uniqueness on non-id property

I've been looking at this since a while, it seems mostly verbose because you want to handle Backbone collections, and arrays, and single songs..

It seems simpler to normalize in all 3 scenario's items to something that you then process once. I am not 100% this works, but you should get the gist:

//  Don't allow duplicate PlaylistItems, determined by the PlaylistItem's Song's ID.
add: function (items, options) {

   if( !items.length ){
     //Anti duck typing, it's not an array or collection
     items = [items];
   }
   else if ( items instanceof Backbone.Collection ){
     //Provide direct access to the array
     items = items.models;
   }
   _.each(items, function (item) {
       trySetDuplicateSongId.call(this, item);
   }.bind(this));

    return MultiSelectCollection.prototype.add.call(this, items, options);
}

For trySetDuplicateSongId I would extract playlistItemToAdd.get('song').get('id') and cache it into a variable. This should make your search twice as fast. Also I would clean up the whole duplication finding, I find the code a bit verbose. Again, I am making some assumptions here with regards to what you set as defaults, but I would do this:

function trySetDuplicateSongId(playlistItemToAdd) {

    var songId = playlistItemToAdd.get('song').get('id'),
        duplicate = this.find(function (playlistItem) {
            return playlistItem.get('song').get('id') === songId;
        });

    if (duplicate) {
       //  Make their IDs match to prevent adding to the collection.
        if (duplicatePlaylistItem.has('id')) {
            playlistItemToAdd.set('id', duplicatePlaylistItem.get('id'));
        } else {
            playlistItemToAdd.cid = duplicatePlaylistItem.cid;
        }
    }
}

Furthermore, if you have to add lots of songs, then you will run into increasingly bad performance. I would probably have a separate list/object with just the song id's pointing to an object with item id or cid.

Finally, I am curious as to why you would not allow a playlist item to be shared by song lists ;P


Here are a few suggestions:

You should get in the habit of wrapping all code that isn't contained in a function, in a main guard. This will protect the code from being run when the file is imported.
Instead of code like, for example, s = "x" + str(i) + "x", you should use f""in front of your strings so you can directly include variable names into the strings, like so: s = f"x{i}x".
You should include module docstrings for all your functions. This will help any documentation identify what your functions are supposed to do.
Running your code through pylint, here are a few warnings:

Parameters: Having one letter parameters isn't a good practice. Your code lit up when I first pasted it into my editor. Having meaningful names for your parameters also helps remind you what your function is supposed to take in.
Spacing: Any spacing like s=1 or a=b+c should be spread out to s = 1 and a = b + c. This improves the readability of your code greatly.

Below is the refactored code:

def swap(array, index_one, index_two):
    """ Swaps two values in an array, then returns the new array"""
    temp = array[index_one]
    array[index_one] = array[index_two]
    array[index_two] = temp
    return array

def is_same_round(tables, element_one, element_two):
    """
    Returns True if the index of `element_one` is greater than the index
    of `element_two`
    """
    return tables.index(element_one) < tables.index(element_two)

def solve(file):
    """ Solves the file """
    tables = [line.strip('\n') for line in open(file)]
    for i in range(len(tables)):
        tables[i] = int(tables[i][0:len(tables[i]) - 1])
    tables = tables[1:len(tables)]
    roundnumbers = []
    for i in range(len(tables)):
        for j in range(i + 1, len(tables)):
            rounds = 1
            tables = swap(tables, i, j)
            for luku in range(1, len(tables)):
                if not is_same_round(tables, luku, luku + 1):
                    rounds += 1
            roundnumbers.append(rounds)
            tables = swap(tables, i, j)

    result = f"{len(tables)} {min(roundnumbers)} {roundnumbers.count(min(roundnumbers))}"
    print(result)

if __name__ == '__main__':
    for i in range(1, 10):
        file_to_solve = f'junar{i}.in'
        solve(file_to_solve)


Try the DateTime class.  With this you can use relative formats:

new DateTime('second thu of next month');
new DateTime('second thu of jul');

That should make the code a lot easier.


C++ wrapper function for Python's "list.count([character])" method?

When STR is empty, STR.size() returns 0u. As a result, STR.size()-1 becomes maximum value of unsigned size type. i++ < STR.size()-1. This will lead the function to crash.

Also your function will not count CHAR of the first character of STR.

You may want to use standard library.

std::count(begin, end, CHAR)  is just what you are looking for.

for example,

#include <algorithm>
#include <string>

...
char CHAR = 'l';
std::string STR("Hello World!");
ptrdiff_t counter = std::count(STR.begin(), STR.end(), CHAR);
...


Extracting two columns from exported iTunes playlist

Simple mistake

The function main takes a filename as an argument but doesn't use it. Instead, it retrieves it from argv.

Also, filename would be a better name for a filename than file.


To clean up your controller I came up with this:

entire logic is moved to your CarService
method CarModelsToRemoveFromDb is also moved to CarService
CarServicehas two overloads for method Update

Methods for CarService:

private IEnumerable<string> CarModelsToRemoveFromDb (Car car, IEnumerable<string> splitSelectedCars)
{
    var savedCarsInDb = car.CarModels.Select(c=> c.ModelId)
        .ToList();

    return savedCarsInDb.Except(splitSelectedCars, StringComparer.OrdinalIgnoreCase);
}

public void Update(CarModelSelectViewModel model)
{
    var car = GetById(model.carId);
    var splitSelectedCars = model.SelectedCars.Split(',').Select(sValue => sValue.Trim()).ToList();

    if (car.CarModels.Count > 0)
    {
        var carsToRemove = CarModelsToRemoveFromDb(car, splitSelectedCars);

        foreach (var carToRemove in carsToRemove )
        {
            var carIdToDelete = car.RemoveCar(carToRemove);
            Delete(carIdToDelete);
        }
    }

    foreach (var singleSelectedCar in splitSelectedCars)
    {
        var savedCarsInDb = car.CarModels.Select(c=> c.ModelId)
            .ToList();

        if (!savedCarsInDb.Contains(singleSelectedCar))
        {
            riskAppraisal.AddCar(singleSelectedCar);
        }
    }

    Update(car);
}

public void Update(Car car)
{
    //your current logic
}

Controller:

public HttpResponseMessage SaveCarModelSelect(CarModelSelectViewModel model)
{
    _carService.Update(model);
    return Request.CreateResponse(HttpStatusCode.OK);
}

Logic that checks count of Car (car.CarModels.Count > 0) can also be separated out to private method, same for loop foreach (var singleSelectedCar in splitSelectedCars).

I hope it can give you some sense of direction.


Positive, Negative or zero in a 2D array python

You should choose better functions names, function does not give any indication what the purpose of the function is.
In addition, a docstring comment can be used to give a short description.
But actually there is no need for a custom function because numpy.sign already provides the exact functionality:

Returns an element-wise indication of the sign of a number.

Example:
import numpy as np

array = np.random.randint(-10,10, size=(4,4))
print(np.sign(array))

Output:

[[-1  1  1  1]
 [ 1  1  0  0]
 [ 1  1 -1  1]
 [ 1 -1  1 -1]]


Yes, microtime is designed to be used for this. The PHP documentation mentions this use case for microtime().
Consider putting this into a loop and print out the average result: if the measured time is too small, you can't provide a reliable estimation.
Concerning the MySQL request: you should switch to mysqli or PDO.


Function to determine the effect of a lightning bolt on a game character using "abilities"

I have asked that you provide more code, and I hope that you do.

Until then, I suggest you have a look at the Visitor Pattern and its implementation using multiple dispatch.

You have a lightning attack. You are applying certain effects, including some effects that are common to all attacks.

You have not yet reached the point where some defenders will be immune to lightning, or take reduced damage, or immune to stun, but you will.

It makes more sense to Tell, don't Ask in thise situation. You tell the defender that they were attacked by lightning, and let the defender handle things.

The default behavior would be substantially what you have shown. But you could then create a defender subclass that was immune to lightning, or suffered reduced damage, and the logic would be located with that particular defender, which improves your code organization and maintainability.

Beyond that, since your defender seems to be a class already (based on the code you have shown), it should be easy to encode the "standard attack checks" into the base class in a single method. You can then raise an exception or return a sentinel value to indicate that the attack is blocked due to stun or confusion, or just print out the results (not recommended).


Redirect http to https, non-www to www and "/index.php" to "/"

Keep your code consistent. If you are using RewriteRule, use the same capitalisation format in all declarations. Same for setting the flags (R, L, NC etc.); or the variables and so on.

I personally prefer to give an extra newline between any new set of RewriteCond segment, so that I would be able to easily identify groups later on. As well as, adding comments never hurt anybody.

Prefer to handle the requests/paths at as late stage as possible.

Lastly, if you have just one domain name to handle; you can merge the https and naked-domain rules in a single one. The final ruleset would be:

Options +FollowSymlinks

RewriteEngine On

RewriteCond %{HTTPS} off [NC,OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

RewriteCond %{THE_REQUEST} ^.*/index\.php [NC]
RewriteRule ^(.*)index\.php$ https://www.example.com/$1 [R=301,L]


getint that properly handles + or - signs

The method modifies the parameter while it is processing input. It should store the processing result locally and then assign it once it is finished.
It is unclear what the return value of the method means just by reading the code. If it is supposed to indicate success (return is not 0) or failure (return value is 0) then I think you have subtle bug in there in the case when the last character read from input is '\0' - in which case you return 0 even though you potentially have parsed a number. You should simply return 1; to indicate the success case.


Averaging numbers from a file, obeying Single Responsibility Principle

Things you can improve

Variables/Initialization

Floating-point math is challenging in surprising places.  It's easy to write down a reasonable algorithm that introduces 0.01% error on every step, which over 1,000 iteration turns the results into complete slop.  You can easily find volumes filled with advice about how to avoid such surprises.  Much of it is valid today, but much of it is easy to handle quickly:  use double instead of float, and for intermediate values in calculations, it doesn't hurt to use long double.

The problem is how many bits each type uses to store significant digits.  float uses 32 bits, and double uses 64 bits.  64 bits is enough to reliably store 15 significant digit, which is plenty in order to solve all of our floating-point problems for now. All we had to do was throw twice as much space at the problem, and suddenly all sorts of considerations are basically irrelevant.  Even if there is a perceptible speed difference between a program written with all doubles and one written with all floats, it's worth extra microseconds to be able to ignore so many caveats.
Don't use global variables.

int element_counter;
float* all_elements;

The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).

If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.

So instead of using global variables, initialize the variables in main(), and pass them as arguments to functions if necessary.

Standards

strtok is limited to tokenizing only one string (with one set of delimiters) at a time, and it can't be used while threading.  Therefore, strtok is considered deprecated.

Instead, use strtok_r or strtok_s which are threading-friendly versions of strtok.  The POSIX standard provided strtok_r, and the C11 standard provides strtok_s.  The use of either is a little awkward, because the first call is different from the subsequent calls.

The first time you call the function, send in the string to be parsed as the first argument.
On subsequent calls, send in NULL as the first argument.
The last argument is the scratch string.  You don't have to initialize it on first use; on subsequent uses it will hold the string as it is parsed so far.

To demonstrate its use, I've written a simple line counter (of only non-blank lines) using the POSIX standard one.  I'll leave the choice of what version to use and implementation into your program up to you.

#include <string.h> // strtok_r

int countLines(char* instring)
{
    int counter = 0;
    char *scratch, *txt;
    char *delimiter = "\n";
    for (; (txt = strtok_r((!counter ? instring : NULL), delimiter, &scratch)); counter++);
    return counter;
}

If you implement this, you have your question answered.

  Also, in my use of strtok(), what should I be doing with the balance
  of the string after the delimiter? Is that hanging out in memory
  somewhere?

It's not hanging out in memory, it's in the scratch string you provided.
You don't have to return 0 at the end of main(), just like you wouldn't bother putting return; at the end of a void-returning function. The C standard  knows how frequently this is used, and lets you not bother.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.

Syntax/Styling

Put the variable declarations to separate lines.

float sum = 0.0, average;

From Code Complete, 2d Edition, p. 759:

  With statements on their own lines, the code reads from top to bottom,
  instead of top to bottom and left to right. When you’re looking for a
  specific line of code, your eye should be able to follow the left
  margin of the code. It shouldn’t have to dip into each and every line
  just because a single line might contain two statements.

Use strtod() instead of strtof(). (This goes with my point about double vs. float).
Declare your parameters as void if you don't take in any arguments in your methods.

int main(void)

You can simplify your NULL checks.

while(element)  // same as while (element != NULL)

Initialize i inside of your for loops.(C99)

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


concise way to build an object from an array of objects

While it technically still would initialize it as an empty object, one could build derivedData with one call to Array.prototype.reduce(). It is similar to forEach() except that the first argument of the callback function is an accumulator variable, that needs to be returned at the end of the function. See the snippet below for a demonstration.

const data = [
  {"period": "2021-05-01", "quantity": "28"},
  {"period": "2021-06-01", "quantity": "42"},
  {"period": "2021-07-01", "quantity": "66"}
];

const derivedData = data.reduce((accumulator, o) => {
  accumulator[o.period] = o.quantity;
  return accumulator;
}, {});

console.log('derivedData: ', derivedData);

You may find these functional exercises interesting.
Good job using const for variables that don't need to be re-assigned, and using common spacing conventions for modern JavaScript.


Monkey-patching native JavaScript constructors

I don't see any good reason why you're using some of these hacks. It took me a while to understand what you were doing and I was pretty much forced to step through it in debugger. Going to review this line by line and point out simplifications and patterns as I see fit. I'll be batching together all my suggestions into a counter proposal in this jsbin, using the unit tests from your repo.
To start, it seems quite unneccessary and non standard to get the global scope your way (and I'm going to later argue you shouldn't need it)...
var global = new Function("return this;")();

Just do what every other package does and get scope at the start of your wrapper
(function(global) {  })(this); //or use self w/e

I'm not a fan of your fnProps idea. I would prefer you store has = Object.prototype.hasOwnProperty; and filter out items on the Function prototype as follows:
var has = Object.prototype.hasOwnProperty();
/* .... */
//To avoid storing generic function properties (like length) on newRef
Object.getOwnPropertyNames(ref).forEach(function(key) {
    if(!has.call(Function, key)) newRef[key] = ref[key];
});

I'm biased here, but as a past Mootools developer I keep comparing your function with Class.refactor. Personally I would prefer you add a reference to the original function on newRef - maybe as some property _original or let the user handle storing the original. I'm not a fan of adding a global for the original function.
A question, why do you not pass this to your constructors? If you're wrapping some classes this seems like it may make usuage less intuitive.
Update (still at work and can't look into removing the new Function() approach yet but I think I found a great change... You can rewrite the extremely confusing bind.apply(...) like this (unit tests passing):
newRef = Function.apply(null, args);

I'm not a minifier but theres no good reason to do !!this ? x : y
Counter proposal:
I believe you should drop the arity requirement and drop the global - instead inform the user they should cache the original locally. I've rewritten the code with these considerations in mind. Here's a jsbin with these changes (note I haven't removed the global to respect your test cases):
var patch = (function (global) {
    /*jshint evil: true */

    "use strict";
    var has = Object.prototype.hasOwnProperty,
        slice = Array.prototype.slice,
        bind = Function.bind;
    return function (original, patches) {
        var args = [],
            newRef, // This will be the new patched constructor
            i;

        patches.called = patches.called || original; // If we are not patching static calls just pass them through to the original function

        if (patches.constructed) { // This string is evaluated to create the patched constructor body in the case that we are patching newed calls
            newRef = function(/*args*/) {
                return (this && this !== global ? patches.constructed : patches.called).apply(this, arguments);//note called with context
            };
        } else { // This string is evaluated to create the patched constructor body in the case that we are only patching static calls
            newRef = function(/*args*/) {
                return this && this !== global  ? new (bind.apply(original, [].concat({}, slice.call(arguments))))
                                                : patches.called.apply(this, arguments);
            };
        }

        // Create a new function to wrap the patched constructor
        newRef.prototype = original.prototype; // Keep a reference to the original prototype to ensure instances of the patch appear as instances of the original
        newRef.prototype.constructor = newRef; // Ensure the constructor of patched instances is the patched constructor

        Object.getOwnPropertyNames(original).forEach(function (property) { // Add any "static" properties of the original constructor to the patched one
            if (!has.call(Function, property)) { // Don't include static properties of Function since the patched constructor will already have them
                newRef[property] = original[property];
            }
        });

        return newRef; // Return the patched constructor
    };

})(this);

Edit - missed an easy code size optimization:
newRef = function(/*args*/) {
    if(this && this !== global) {
        return patches.constructed ? patches.constructed.apply(this, arguments)
                                   : new (bind.apply(original, [].concat({}, slice.call(arguments))))// create the patched constructor body in the case that we are only patching static calls;
    } else {
        return patches.called.apply(this, arguments);
    }
};


Aggregating search results from multiple databases, in smaller work units

You could split up your code further by separating out the lines where you actually get the cases to yield. It's only a few lines that need just a couple parameters to run and can return a simple variable, making them a prime candidate for refactoring into a function:

def performGenerator(self):
    #Go through each year and each DB in that year
    for year, yearInfo in data["preprocessDBInfo"].items():
        for dbName, dbInfo in yearInfo["dbs"].items():
            #Relevant to search?
            relevantTerms = self.search.ofDB(dbName)
            if len(relevantTerms) == 0:
                continue #Not a relevant database

            yield get_cases(relevantTerms, dbInfo["filePath"])

def get_cases(relevantTerms, filepath)
    fp = os.path.join(prefs["rootPath"], filepath)
    caseDB = caseDB(fp)
    return caseDB.getCases(stubs=True, search=relevantTerms)

This line is confusing me:

caseDB = caseDB(fp)

This isn't intended to modify caseDB, is it? As far as I can tell, it would modify it by replacing the name in your first case, but not the second since you're only modifying it inside the local scope each time the generator is called. It is a very bad idea to match names like this, because it makes it unclear whether or not they're supposed to be the same thing, or caseDB is an instance of a caseDB object. If this reuse of the name is necessary, it's a very confusing pattern that ought to be explicitly explained rather than just used without comment.

You shouldn't test for an empty collection using len(var) == 0. You're wasting time calculating the full length of something just to check if it's zero. Instead, use Python's truthiness. Any variable can be evaluated as a boolean in Python. For collections, this means that it's False if the collection is empty, and True otherwise. This means your test could be:

relevantTerms = self.search.ofDB(dbName)
if not relevantTerms:
    continue  # Not a relevant database

You don't actually use year, so you should throw it away. It's Pythonic to use an underscore for the name of a throwaway value, like this:

for _, yearInfo in data["preprocessDBInfo"].items():

This signals clearer that the value isn't used, which makes your code clearer to read.


For the part you do not like, you can set a before_filter in ApplicationController. Therefore a redirect will not be necessary. Selection form can resubmit to the current page with "view_type" parameter.

#application_controller.rb
before_filter :check_view_type, :only => [:index]

def check_view_type
   session[:view_type] = params[:view_type] if params[:view_type].present?
end

For this specific example I would prefer layout and partial views. It is well described in Rails guides.

#x/index.html.erb
render :partial => 'item', :layout => current_layout, :collection => @items

#application_controller.rb
helper_method :current_layout

def supported_layouts
    [nil]
end

def current_layout
 supported_layouts.include? session[:view_type] ? session[:view_type] : supported_layouts.first
end

#x_controller.rb
def supported_layouts
    %w[box list]
end

def index
  # only index logic
end


Let's look at a simpler problem first: counting the length of a list. Here's the recursive way to do it:

(define (length lst)
  (if (null? lst)
      0
      (+ 1 (length (cdr lst)))))

Okay, so, what would it look like if instead of recursing, we kept a running count of the length instead?

(define (length lst)
  (length-aux lst 0))

(define (length-aux lst count)
  (if (null? lst)
      count
      (length-aux (cdr lst) (+ 1 count))))

Here, length-aux tail-recurses into itself over and over with a new running count until we hit the end of the list, at which point we return the count.

This idiom is common enough that Scheme has a concept called named let, which you can use like this:

(define (length lst)
  (let loop ((lst lst)
             (count 0))
    (if (null? lst)
        count
        (loop (cdr lst) (+ 1 count)))))

You can use a similar approach for solving your problem iteratively:

(define (mX n m)
  (let loop ((m m)
             (product 0))
    (if (zero? m)
        product
        (loop (- m 1) (+ product n)))))

Notice that we are not setting variables here. We are doing a tail recursion into loop, which is passed the new m and product values as arguments.


Follow Java naming conventions.  Your package name should be all
lowercase - 'testspace'. 'reverselist' should be 'reverseList'.
Don't use fully qualified 'java.lang.Math', just 'Math'. You don't need to import classes from the java.lang package.
Indent your comments to match the code.
Use descriptive variable names, e.g. 'v' could be 'exponent' or
'power'.  Why use 'i' and then describe it as 'x' in the comment? Should 'reverselist' be 'reverseArray'?

In general your algorithms are reasonable.


Explanation:

If you're going to take the source of an image and set it to another image, why even bother having those images as HTML? It would be much simpler to simply store the image urls in an array like so:

const imageUrls = [
  "https://i.ytimg.com/vi/E6CYI3Xb1tQ/maxresdefault.jpg",
  "https://upload.wikimedia.org/wikipedia/commons/9/9b/Dragon_Ball_Z_Logo.png",
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDWVk-v3DR5j0pHabogu6i3n1KLhqJWNd-Z54qevISiCoHKF88",
  "https://media.comicbook.com/2017/02/vegeta-dragon-ball-z-235088-1280x0.png"
];

Secondly, you're using a counter variable and an imageSelected variable... but their end goal is the same thing. Stick with the counter.

You're spending a lot of time writing conditions, why not use % (modulo) to determine which is the next image.

When the right button is clicked simply do:

counter = (counter + 1) % imageUrls.length

This way, once you get to the last image (counter = 3) and wish to go to the next one, then (counter + 1) = (3+1) = (4). So the new position is 4 however the imageUrl length is 4.. and 4 % 4 = 0. So, it's an easy solution to reset the counter to 0 when it gets to the end of the image url list.

However, this doesn't work when you wish to go left. Because module doesn't work on negative numbers. To solve this do the following.

counter = (counter + -1 + imageUrls.length) % imageUrls.length

Now, to figure out if it's 1 or -1 and to avoid setting a condition for it, we're going to store those values in the data attributes in the left and right HTML elements like so:

&#10096;
&#10097;

Then simply to access them in the event callback:

Number(this.dataset.direction) //returns a string so reason why use Number to convert it.

Now, all there is left to do is to complete the formula.

counter = (counter + Number(this.dataset.direction) + imageUrls.length) % imageUrls.length;

Avoid setting the onclick function to a container and actually set it to the elements that need to be clicked.

imgDisplay.querySelectorAll("#left, #right").forEach(element=>{
  //first time this is called element = left
  //second time this is called element = second
  //for each element add an event listener.
});

Solution:

const imageUrls = [
  "https://i.ytimg.com/vi/E6CYI3Xb1tQ/maxresdefault.jpg",
  "https://upload.wikimedia.org/wikipedia/commons/9/9b/Dragon_Ball_Z_Logo.png",
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDWVk-v3DR5j0pHabogu6i3n1KLhqJWNd-Z54qevISiCoHKF88",
  "https://media.comicbook.com/2017/02/vegeta-dragon-ball-z-235088-1280x0.png"
];

const imgDisplay = document.getElementById('image-display');

let counter = 0;
const img = new Image();
img.src = imageUrls[counter];
imgDisplay.appendChild(img);

imgDisplay.querySelectorAll("#left, #right").forEach(element=>{
  element.addEventListener('click', function(e){
      counter = (counter + Number(this.dataset.direction) + imageUrls.length) % imageUrls.length;
      img.src = imageUrls[counter];
  });
});

Working Example:

const imageUrls = [
  "https://i.ytimg.com/vi/E6CYI3Xb1tQ/maxresdefault.jpg",
  "https://upload.wikimedia.org/wikipedia/commons/9/9b/Dragon_Ball_Z_Logo.png",
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDWVk-v3DR5j0pHabogu6i3n1KLhqJWNd-Z54qevISiCoHKF88",
  "https://media.comicbook.com/2017/02/vegeta-dragon-ball-z-235088-1280x0.png"
];

const imgDisplay = document.getElementById('image-display');

let counter = 0;
const img = new Image();
img.src = imageUrls[counter];
imgDisplay.appendChild(img);

imgDisplay.querySelectorAll("#left, #right").forEach(element=>{
  element.addEventListener('click', function(e){
      counter = (counter + Number(this.dataset.direction) + imageUrls.length) % imageUrls.length;
      img.src = imageUrls[counter];
  });
});
#image-display {
  width: 500px;
  height: 100%;
  border: 3px solid orange;
  z-index: -1;
  padding: 3;
  margin: 0;
}

#img-size {
  height: 100%;
  width: 100%;
  z-index: -1;
  margin: 0;
  position: relative;
}

/* left arrow */

#left {
  z-index: 0;
  position: fixed;
  left: 21.5%;
  top: 10%;
  cursor: pointer;
  color: #ffffff;
  padding: 0;
}

/* right arrow */

#right {
  z-index: 0;
  position: fixed;
  right: 53.5%;
  top: 10%;
  cursor: pointer;
  color: #ffffff;
  padding: 0;
}

/*Desktop Media Queries*/

@media(min-width: 1573px) {
  #right {
    right: 35%;
    top: 12%;
  }
  #left {
    left: 35.5%;
    top: 12%;
  }
}

@media(min-width: 1613px) {
  #right {
    right: 35.5%;
    top: 11%;
  }
  #left {
    left: 35.5%;
    top: 11%;
  }
}

@media(min-width: 1140px) {
  #right {
    right: 37.5%;
    top: 11%;
  }
  #left {
    left: 37.5%;
    top: 11%;
  }
}

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      &#10096;
      &#10097;


“Space and Time Efficient” way of finding all anagram groups

calcProduct

You don't need the L on these lines:

long res = 1L;
return -1L;

Instead of explaining what 65 is in a comment:

    if (c < 65) { // ASCII A = 65

You can use 'A' directly. And checking c < 'A' is not enough. You should also check c > 'Z'.

The method rewritten:

private static long calcProduct(char[] letters) {
    long res = 1;
    for (char c : letters) {
        if (c < 'A' || c > 'Z') {
            return -1;
        }
        int index = c - 'A';
        res = res * PRIMES[index];
    }
    return res;
}

findAllAnagrams

Instead of StringBuffer, it's recommended to use StringBuilder.

Instead of new HashMap<Long, StringBuffer>() you can use the diamond operator <> to simplify.

The anagrams map is written to but never read. You can remove it.

file is a poor name for an array of words. (words would be better)

The concatenation in sb.append("" + word) is pointless, as sb.append(word) has the same effect.

In general, instead of concatenation inside sb.append(...), it's recommended to chain .append(...).append(...) calls.

Instead of creating a new StringBuffer in every iteration of the loop, you could just create when it's actually needed: when putting the first word in the map.

Finally, it's recommended to always use braces on single-statement if-else conditions.

The method rewritten:

public static Map<Long, StringBuilder> findAllAnagrams(String[] words) {
    Map<Long, StringBuilder> result = new HashMap<>();

    for (String word : words) {
        long product = calcProduct(word.toUpperCase().toCharArray());

        StringBuilder sb = result.get(product);
        if (sb == null) {
            result.put(product, new StringBuilder(word));
        } else {
            sb.append(",").append(word);
        }
    }
    return result;
}

But, this is not nearly good enough. It would be better to use a List<String> as the values:

public static Map<Long, List<String>> findAllAnagrams(String[] words) {
    Map<Long, List<String>> result = new HashMap<>();

    for (String word : words) {
        long product = calcProduct(word.toUpperCase().toCharArray());

        List<String> anagrams = result.get(product);
        if (anagrams == null) {
            anagrams = new ArrayList<>();
            result.put(product, anagrams);
        }
        anagrams.add(word);
    }
    return result;
}

main

You should not suppress the raw types warning but fix it. The loop could have been written like this:

for (Map.Entry<Long, StringBuilder> entry : result.entrySet()) {

And since you don't need the keys in the loop body, it's better to iterate over the values:

    for (List<String> anagrams : findAllAnagrams(file).values()) {
        if (anagrams.size() > 1) {
            for (String word : anagrams) {
                System.out.print(word + " ");
            }
            System.out.println();
        }
    }


My solution relies on the CSS rule which says, "hide all list items that come after the one with the active class."

li.active ~ li {
  display: none;
}

The JavaScript deals with getting the index of the list item containing the active class and re-assigning the active class to the next list item (if there is one).

window.addEventListener("load", init);

var btn, list_length, ul;

function init() {
  ul = document.getElementsByTagName("ul")[0];
  btn = document.getElementsByTagName("button")[0];
  list_length = ul.children.length;

  btn.addEventListener("click", function() {
    if (getItemIndex(getActiveItem()) < (list_length -1)) {
      showNextItem();
    }
  });
}

function getActiveItem() {
  return document.getElementsByClassName("active")[0];
}

function getItemIndex(active_item) {
  var nodeList = Array.prototype.slice.call(ul.children);

  return nodeList.indexOf(active_item);
}

function getListItem(index) {
  return document.getElementsByTagName("li")[index];
}

function showNextItem() {
  var active_item = getActiveItem(),
      next_index  = getItemIndex(active_item) + 1,
      next_item   = getListItem(next_index);

  active_item.classList.remove("active");
  next_item.classList.add("active");

  if ((next_index + 1) < list_length) {
    btn.getElementsByTagName("span")[0].innerHTML = getListItem(next_index + 1).innerHTML;
  } else {
    btn.classList.add("hide");
  }
}
h1 {
  font-size: 1.2em;
}

button {
  font-size: 1em;
}

button.hide {
  display: none;
}

ul {
  margin: 0 0 1em;
  padding: 0;
  border-bottom: 1px solid gray;
  width: 40em;
}

li {
  list-style: none;
  padding: 0.8em 0;
  border-top: 1px solid gray;
}

li.active ~ li {
  display: none;
}

Expanding List

part one

part two

part three

part four

<button>Show part two
</button>


While quickly running over your code, my eyes stopped on your function KeepDividingWhileInt.

It seemed over-complicated.

Let's write what it does:

Creates isDivisible
Sets isDivisible to true
Loops while isDividible is true:

If numToDivide Mod divisor is 0

Divides numToDivide by divisor

Else

Sets isDivisible to false

Returns numToDivide

Well, there is a subtle bug on step 2: You assume that the number is divisible by divisor, which may not be true (e.g.: KeepDividingWhileInt(3,2)).

Also, the whole code could be extremely simplified, by moving the condition inside that if into the while.

Also, you could try to use While ... Wend instead of Do While ... Loop, as suggested by @Mat's Mug. This point actually applies everywhere on your code.

The final result:

Public Function KeepDividingWhileInt(ByVal numToDivide As Long, ByVal divisor As Long) As Long

    While numToDivide Mod divisor = 0
        numToDivide = numToDivide / divisor
    Wend

    KeepDividingWhileInt = numToDivide

End Function

Oh my! The function is so simple that you can read it in a single sentence:

  Divide numToDivide by divisor while the reminder is 0, returning the final result.

So simple, right?


Code broken

Your code doesn't work for several reasons:

You are not passing a function to pthread_create():

err = pthread_create(&(tid[i]), NULL, readFromFile(i), NULL);

Here you are calling the function readFromFile() instead of passing a function pointer to pthread_create().  So you aren't using a thread at all.  Worse than that, when readFromFile() returns, a random value will be passed to pthread_create() because readFromFile() doesn't actually return any particular value.  This will cause the newly created thread to crash.
Even had you done that part correctly, your readFromFile() function doesn't do what you wanted.  It looks like you wanted each thread to read one character and then let another thread read the next character.  But what your function actually does is read the whole file instead of one character.
You are calling strcat() with a character as the second argument instead of a string.  This will cause a crash if the program ever reaches that line.

Pay attention to warnings

If you had built with full warnings, you would have been alerted to mistakes #1 and #3 I listed above.

Implementing a mutex?

The title of the question is misleading.  You aren't implementing a mutex.  You are trying to use one.


Producer-Consumer using low level synchronization

Miscellaneous Remarks

Your elems variable is just list.size(), so why not just use list.size() everywhere and eliminate elems?
Your other size is a constant, and should be called SIZE by convention.
Instead of spreading out int ran = 0; ran = r.nextInt(10);, and if (ran == 7) { ... } over three lines, you should just do if (r.nextInt(10) == 7) { ... }.  Putting it all on one line takes less mental effort to follow the code.

Threading

Both the producer and consumer threads are infinite loops. Neither thread will end normally, and therefore trying to .join() them is superfluous.
Rather than ensuring that the producer runs first, you should just design the consumer to correctly handle the case when there are no more values to consume.  As @DanielR pointed out, when list.size() is zero, r.nextInt(list.size()) throws an IllegalArgumentException.
Your use of lock.notify() right now is superfluous, as there is no corresponding lock.wait() that expects a notification.  A good place to insert a lock.wait() would be where you suspected.  (Without the lock.wait(), the consumer would keep trying frantically to fetch a value, which could work, but is inefficient.  Inserting lock.wait() makes the consumer yield the processor to the producer until the producer notifies the consumer that the values have been replenished.)

public void consumer() throws InterruptedException {
    synchronized (lock) {
        while (list.isEmpty()) {
            // Nothing to consume for now; wait for more.
            lock.wait();
        }
        ...
    }
}

I think that the vocabulary is slightly off.  To me, a "producer" and a "consumer" are both threads.  I would say,

Thread producer = new Thread(new Runnable() {
    @Override
    public void run() {
        low.produce();
    }
});

Therefore, I would rename your methods as verbs produce() and consume().
In Java, every Object can act as a lock.  There is no need to make a separate lock object; you could just synchronize on list or this instead.  (It doesn't matter which object you choose as the lock, as long as the producer and consumer both agree on which object it is.)  As a special case,

public void method() {
    synchronized (this) {
        ...
    }
}

can be written as

public synchronized void method() {
    ...
}

which is slightly more readable and also compiles to slightly tighter bytecode.
I would take move the while-loops from produce() and consume() into the run() method.  That would have the triple benefit of

keeping produce() and consume() simpler
making it more obvious that each Runnable is an infinite loop
moving the synchronized keyword into the method signatures, making it easier to see that produce() and consume() run mutually exclusively, and generating slightly tighter bytecode.

Proposed Solution

import java.util.ArrayList;
import java.util.Random;

public class LowLevelProducerConsumer {
    ArrayList<Integer> list = new ArrayList<Integer>();
    private final int SIZE = 10;
    Random r = new Random(System.currentTimeMillis());

    public synchronized void produce() {
        try {
            while (list.size() != SIZE) {
                list.add(r.nextInt(100));
            }
        } finally {
            // Notifies consumer that entries have been generated
            this.notify();
        }
    }

    public synchronized void consume() throws InterruptedException {
        while (list.isEmpty()) {
            // Nothing to consume for now; wait for more.
            // System.err.println("Consumer waiting...");
            this.wait();
        }

        if (r.nextInt(10) == 7) { // just an arbitrary condition
            int loc = r.nextInt(list.size());
            int data = list.remove(loc);
            System.out.format(
                    "%d removed from index %d , size : %d\n",
                    data, loc, list.size());
            Thread.sleep(300);
        }
    }

    public static void main(String[] args) {
        final LowLevelProducerConsumer low = new LowLevelProducerConsumer();
        Thread producer = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    low.produce();
                }
            }
        });
        Thread consumer = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        low.consume();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        producer.start();
        consumer.start();
    }
}


Print out N by N Spiral Matrix in javascript

This code is well written;

Comments

You have no comments whatsoever, fortunately the code reads well

JSHint.com

Your code passes all checks, well done


I'd say the code is not bad, just a few style issues and a couple of practical things.

You don't need two lines to lowercase the input string, you can do directly
inp = input('Input the text you want to code:\n').lower()

You're not checking user input, if the second input is not an integer, int() will generate a ValueError. You should put a try/catch around that.

Your input implies that numbers lower than 1 and higher than 25 are not acceptable, while actually you're accepting them and doing something different than what you told the user. Either you generate an error and refuse the input, or you say that the input will be modified accordingly. Either way the user should know what's going on.

You have quite a few hard-coded values, consider using constants .

The comment # If the final number is greater than 122.. is useless, the code is clear at that point.

The comment # Function to code a text with caeser chyper. should actually be a docstring . You should also specify what you expect as input and what kind of output you return.

I would rename the variable input to input_string , just so it's not the same name of the input() function.

elif((num + key <= 122)): is actually just else:

You're printing inside of the function. I'd return the value and let the caller decide what to do with it.

You may want to consider putting if __name__ == "__main__": in your code and call your function from there.

This is a simple function, so no need to dig too deep but if you want, you may have a look here about string concatenation .


Spawning two threads and if any of the threads returns true, let the main thread ignore the other and move on

Bug
I'd post this as a comment and a close vote, but you already have two answers.
Your program does not actually fulfill the problem statement.  If one thread quickly returns false and the other has not finished yet (but will return true eventually), your program halts and prints nothing.  But instead, it should wait for the second thread to finish.
Testing
You could have found this yourself with a more robust testing framework.  You should test all of the following situations:

Both return true.  Task 1 returns first.
Both return true.  Task 2 returns first.
Task 1 returns true first and later task 2 would return false.
Task 1 returns true but task 2 returns false later.
Task 2 returns true first and later task 1 would return false.
Task 2 returns true but task 1 returns false later.
Both return false.  Task 1 returns first.
Both return false.  Task 2 returns first.

You might also want to check what happens when a task never returns.  There may be other edge cases as well.
Numbered variables
Variables named 1 and 2 are a potential code smell.  In general when you have this, you should consider if you could actually either name the variables better or switch to a collection (e.g. an array or something that implements the Collection interface).
A side benefit of switching to a collection is that it frees you up in case the requirements change from two to another number.
This is not to say that there are no circumstances under which numbered variables are OK.  Only that when you consider using them, you should consider if they really make sense.
Modularization
To make testing easier, I would move the main code outside of the main method.  So instead of editing the main method for each test, your tests would create the appropriate tasks and pass them to the task runner.  The task runner could then enshrine the logic of

Create threads.
Launch them.
Check if they are finished.
If one is finished, check if its task returned true and produce the correct output.
If both returned false, return.

Note that this will be easier to test if the task runner method returns a string rather than printing output.  You can leave the printing logic in your main method.
Test frameworks
Even better than putting your tests in your main method, put them into some kind of test framework.  E.g. JUnit.  With a testing framework, it is easy to run every test every time.


First of all, I don't see any "unnecessary" calls here. Do you need to insert all these lines into the database? Then all there calls are necessary.
However, you can greatly optimize the process, thanks to
Two cornerstone rules for running multiple DML queries

prepare once execute multiple will gain you like 2-5% speed

(however, in order to get that small speed improvement from prepared statements, you have to disable the emulation mode. But in this case you'll be unable to reuse the placeholder name in the same query. Luckily, there is a values() keyword to the rescue)

wrapping all DML queries in a transaction can boost the speed up to 70 times (though depends on the software settings and hardware configuration) and is overall a sensible move. You either want all rows to be inserted or none.

Error reporting
Another issue to address is error reporting which is completely flawed and far from being any helpful in the real life (I have to admit, it's hard to master this skill as your code most of time works as intended) but, unlike what most people think, it's really simple to make it right.
The first thing you have to realize is that there are two kinds of errors that require absolutely different treatment:

userland errors are specific to the application logic and must be conveyed to the user
PHP errors are system errors and a user has no business with them. At the same time, They are vital for the programmer and must be preserved for the future inspection. Luckily, due to their nature, system errors essentially require the uniform treatment which means you can write the handling code once, store it elsewhere, and completely remove any system error handling from your code.

In order to separate these two kinds of errors, validate your data prior the data manipulation. First check if you have all the required data and only then run your inserts. This way you will be able to separate the user interaction errors from the system errors. Be aware that die() is considered a bad practice. It's better to collect all errors into a variable that have to be conveyed to the user in a more convenient fashion.
Regarding the system errors, just like it was said above, write a dedicated error handler once, that would log the error for the programmer and tell the user that something went wrong. I've got a complete working error handler example in my article dedicated to PHP error reporting, you can simply take this file and include it in your script.
Reduce the nesting level
As you may noticed, your code is hard to read because it is constantly shifting to the right side. Hence it's a good idea to remove unneceessary nesting, as most of time it's a sign of the problem code. For example, it makes sense to check outside variables with isset() but internal variables? It's always a good idea to be positively sure whether some variable exists or not. Hence always have your variables initialized before use. Have $array2 initialized at some point and you can drop that outermost condition. Other levels can be removed as well, such as unnecessary try-catch.
Things that indeed could be considered blunders from your beginners days that look rather amusing:

that $valuearray
the way empty() is used. In fact, to get 1 or 0 from a boolean value you can simply cast it as int

So what could we have after all these improvements?
First of all, separate the data validation from the query execution.
Validate all the data first,
$errors = [];
// perform all other validations
foreach($array2 as $value) {
    if ((isset($value['coord']) || isset($value['bookedbefore'])) && isset($value['bookedslot'])) {
        $errors[] = "Error: you ticked checkbox(es) on the booking selection setting without choosing a corresponding slot";
        break;
    }
}

and after that check for errors and if everything is OK then insert all your data, or show the form back to the user with values filled in and errors displayed
if (!$errors) {
    $sql = "INSERT INTO bookedslot(FK_UserID, FK_SlotCode, booked_before, coordinator_approv)
            VALUES (:UserID, :slotcode, :bookedbefore, :coord )
            ON DUPLICATE KEY UPDATE
                FK_UserID = values(FK_UserID),
                FK_SlotCode = values(FK_SlotCode),
                booked_before = values(booked_before),
                coordinator_approv = values(coordinator_approv)";
    $sth = $dbh->prepare($sql);

    $dbh->beginTransaction();
    foreach($array2 as $value) {
        $slotcode = $value['bookedslot'];
        $bookedbefore = (int)!empty($value['bookedbefore']); // not required
        $coord = (int)!empty($value['coord']); // not required

        $sth->bindValue(':UserID', $UserID);
        $sth->bindValue(':slotcode', $slotcode);
        $sth->bindValue(':bookedbefore', $bookedbefore);
        $sth->bindValue(':coord', $coord);
        $sth->execute();
    }
    $dbh->commit();
} else {
    // inform the user
}

What's going on here?
We are implementing all the things mentioned above. Just note that if your application is intended to die in case of a system error, there is no need to wrap your transaction in a try-catch block: it will be rolled back automatically by mysql as soon as the connection will be closed, and PHP always closes all its connections before die.
Just don't forget to configure PDO to throw exception and to disable the emulation mode. Here I've got an example PDO connection code that does all the necessary stuff.


An array function that returns an array containing all elements appearing a certain number of times

I guess you could use Array.forEach() to do the counting and laterArray.filter() to get the elements with the desired number of occurences.

It reduces the bookkeeping to the minimum of counts, goodbye alreadyPushed. It also reduces the boilerplateness a little, by giving you local variables implicitely:

You have this[i] everywhere, which can look a little cryptic. You could store it in a local var element = this[i]; which could be considered more readable.
in my suggested code, you get those local variables as a result of using functions that receive the value as a parameter which you can of course name however you want.

I think it depends on how much you are used to seeing certain patterns show up in code. After doing it for a while, you know that

var i = this.length;
while(i--){ //...}

will iterate over all the elements. Array.forEach() calls it by its name, which can improve readability.

I had my first ever go at the built in scripting thingy here on stackexchange, take a look and try the code:

Array.prototype.itemsWithQuantity = function(n) {
  var counts = {};

  // count
  this.forEach(function(element) {
    counts[element] = counts[element] == undefined ? 1 : counts[element] + 1
  });

  // return those elements (which are the keys(=property names) of the object) occuring n times
  return Object.keys(counts).filter(function(element) {
    return counts[element] == n;
  });
};

var input = [1, 2, 3, 3, 4, 1, 2, 5];
var output = input.itemsWithQuantity(2);

document.getElementById("output").innerHTML = output.toString();


Why don't you use the setFullYear() method?

eighteenYearsAgo = eighteenYearsAgo.setFullYear(eighteenYearsAgo.getFullYear()-18);

Instead of using the yyymmdd() function, you can also use the Date.toISOString() method. This will also show the time... but you can get rid of it in several ways (split on "T" or use a regular expression).


I don't have word_meaning, is that another dependency ?

Since you are already using the random module, you can simply select a random element from a list with random.choice like this:

rand_word = random.choice(word_dict)

instead of:

rand_word = word_dict[random.randint(0, len(word_dict)-1)]

Here you are picking only one element at a time, but if you wanted to select several unique elements (no repeating items) then you would use random.sample.

Your list of words is a constant, make it so:

word_dict = (
'attach', 'compete', 'day', 'frail', 'grubby', 'gusty', 'interfere', 'lumpy', 'memory',
'necessary', 'neck', 'park', 'picayune', 'sophisticated', 'spiky', 'whistle'
)

(did a simple search & replace in Notepad++). NB: I have sorted it too.

The way you are splitting the string is awkward and the comma delimiter is superfluous. This design choice forces you to waste one line per word and makes the code longer for no benefit.

Note that I made it a tuple (non mutable) instead of a list, hence the parentheses.

You could also load the list from a text file, if you want flexibility and separate data from code.

It is not safe to rely on \n as a line break delimiter because it is platform-specific. On Windows/Mac it is different although Python should still interpret it the same. But you never know. Think about portability issues.

Relying on global variables is probably not so Pythonic. You could pass chances as a parameter to your functions. And if you make changes to that value, then return the value in your functions.

Using a global variable could make debugging harder because the variable can be altered in so many places. If you refactor your functions at some point the variable could even be out of sync.

I would aim for minimal variable scope. If hidden_word_1 (not a great name) is only used in user_guess then it need no be defined as a global variable.

I cannot run your code right now but I am not convinced you need a recursive function. You simply need a while loop eg while chances > 0: and decrement the counter after each wrong response.


struct has public inheritance

By default, struct has public inheritance. Therefore, you don't need to manually specify it every time. You can write shorter (and so more readable) code:

template <>
struct template_all<>
  : std::true_type {};

template <typename ... Types>
struct template_all<std::false_type, Types...>
  : std::false_type {};

template <typename ... Types>
struct template_all<std::true_type, Types...>
  : template_all<Types...>::type {};

Since type traits generally use many templates, you don't want to add even more extra keywords all over the place.

Use alias templates

If you have acces to a compiler that supports some C++14 features, you will probably want to use the alias templates for transformation traits to get rid of many typename and ::type. Unfortunately, the alias templates for the query traits (is_*) have not been accepted, so you have to use std::is_same.

template <typename ... Args>
auto link_complete(Args&& ... args) ->
  std::enable_if_t<
    template_all<
      typename std::is_same<
        std::remove_reference_t<Args>,
        Node
      >...
    >::value,
    void
  >
{
    Node::link_complete( { &args... } );
}

static_assert is great

Instead of using SFINAE for link_complete, you should use static_assert since your function does not have any overload. It will allow you to give a meaningful error message instead of a somewhat obscure SFINAE error message:

template <typename ... Args>
void link_complete(Args&& ... args)
{

    static_assert(
        template_all<
            typename std::is_same<
                std::remove_reference_t<Args>,
                Node
            >::type...
        >::value,
        "link_complete arguments must be of the type Node"
    );

    Node::link_complete( { &args... } );
}

You may want to use std::decay

std::decay calls std::remove_reference and std::remove_cv internally. If needed, it also calls std::remove_extent if T is an array type and calls std::add_pointer if T is a function type. In short:

  This is the type conversion applied to all function arguments when passed by value.

That allows you to check for what we generally think of as "same types":

template <typename ... Args>
void link_complete(Args&& ... args)
{

    static_assert(
        template_all<
            typename std::is_same<
                std::decay_t<Args>,
                Node
            >::type...
        >::value,
        "link_complete arguments must be of the type Node"
    );

    Node::link_complete( { &args... } );
}

Rethink template_all

All in all, your goal is to test boolean conditions on types. Since the query traits have a static constexpr bool value member, you may want to create a template_all that checks for true and false (like std::enable_if or std::conditional) instead of checking for std::true_type and std::false_type. That would make your intent clearer, but it would be more like a all_true template.

template <bool...>
struct all_true; // UNDEFINED

template <>
struct all_true<>
  : std::true_type {};

template <bool... Conds>
struct all_true<false, Conds...>
  : std::false_type {};

template <bool... Conds>
struct all_true<true, Conds...>
  : all_true<Conds...> {};

template <typename ... Args>
void link_complete(Args&& ...)
{
    static_assert(
        all_true<
            std::is_same<
                std::decay_t<Args>,
                Node
            >::value...
        >::value,
        "must have Node types"
    );

    Node::link_complete( { &args... } );
}


The core of your question is whether or not you should use setters ($tpl->setSomeParam()) or a simple array to bind template parameters. While using an array my not seem very OO, it's actually a pretty effective way of decoupling your data from your templates. As you've discovered, having to add a new setter to your layout manager every time you add a new parameter to one of your templates means the layout manager is tightly coupled to all of your templates – not good.

This is pretty common practice these days. Twig, Underscore.js, and many others do the same thing.


Showing that an integer function's value and the EOF value are not the same

The original code from this question improperly assumes that c still has the numeric value of a character, saying "This is the value of getchar()".  This is not actually true based upon that code.  The value being printed out in the last line is not the value of getchar() but the value of the comparison of getchar against != EOF.

To clarify things, I wrote the below code, with comments.

#include <stdio.h>

int main( void )
{
  /* result variables, with initial value for cleanliness */
  int getchar_result = 0;
  int compare_result = 0;

  /* print out the value of EOF as an integer */
  printf( "%d \t This is the value of EOF \n", EOF );

  /* obtaining the result of getchar */
  getchar_result = getchar();

  /* obtaining the result of comparison */
  compare_result = EOF != getchar_result;

  /* print out the actual value of the getchar_result, which may or may not be EOF */
  printf( "%d \t This is the value of getchar()\n", getchar_result );

  /* print out the value of the comparison result against EOF */
  printf( "%d \t This Is the result of (getchar()!=EOF)\n", compare_result);
}

This produced the results, when ctrl+D was entered during the execution the first round, and 1 was entered during the second.  Notice that the comparison value is zero (not true) in the first, and 1 (true) in the second.

UbuntuPrompt>./a.out
-1       This is the value of EOF
-1       This is the value of getchar()
0        This Is the result of (getchar()!=EOF)
UbuntuPrompt>./a.out
-1       This is the value of EOF
1
49       This is the value of getchar()
1        This Is the result of (getchar()!=EOF)

Hope this helps.


View programming pattern in C++ without raw pointers

The intentions are clearly expressed, the code is clean and easily understood. As far as I can see there is no obvious problems.
clang-600.0.57 failed to compile the example:

./view.h:15:9: error: unknown type name 'Data'
  const Data& data_;
        ^
./view.h:16:14: error: unknown type name 'Data'
  View(const Data& data) : data_(data) {}
             ^

I don't know what Standard mandates here. Fix is simple: add a forward declaration class Data; to view.h.
In general I am not sure that this is a right approach. Data must be aware of View anyway (for example, to add another View you need to modify Data). So implementing views as member functions seems more direct.


I don't use numpy, and I'm getting errors when trying to use it on 3.9, but it seems unnecessary here. If you want to pretty-print a grid, that can be done succinctly using join:
def format_grid(grid):
    return "\n".join(" ".join(row) for row in grid)

Which, when you replace all uses of asarray, gives output like:
X _ _
_ _ _
_ _ O

I wouldn't import numpy just to help format. That's a heavy dependency for little gain.

These lines:
grid = [["_", "_", "_"], ["_", "_", "_"], ["_", "_", "_"]]
row_os = ["O", "O", "O"]
row_xs = ["X", "X", "X"]

Can make use of "sequence multiplication" to reduce the duplication:
SIDE_LENGTH = 3

grid = [["_"] * SIDE_LENGTH for _ in range(SIDE_LENGTH)]
row_os = ["O"] * SIDE_LENGTH
row_xs = ["X"] * SIDE_LENGTH

I'd change all_coords, coords_picked, and remaining_coords to be sets from the start. It isn't efficient to create them as lists, then convert them to sets whenever you want to use them. This unfortunately requires that remaining_coords be converted to a list before being given to random.choice, but that's still less conversions being done overall.
You could probably just get rid of remaining_coords too and just use:
comp_coords = random.choice(list(all_coords - coords_picked))

You have it as a global variable, even though you're recalculating it each time anyways. It would be even more efficient though to not recalculate it each time, and instead make a copy of all_coords at the start, then del elements from the set as they're picked. That's probably an unnecessary level of optimization for here though.

You can clean up the winning checks by making use of any and comprehensions. First, change column_1, column_2, and column_3 to:
columns = [[row[i]
           for row in grid]
           for i in range(SIDE_LENGTH)]

Whenever you're postfixing variable names with numbers, you probably want a list instead.
Next, the conditions themselves:
if any((any(row == row_os for row in grid),
        any(col == row_os for col in columns),
        any(diag == row_os for diag in [main_diag, counter_diag]))):
    print("The computer has won!")
    sys.exit()
elif any((any(row == row_xs for row in grid),
          any(col == row_xs for col in columns),
          any(diag == row_xs for diag in [main_diag, counter_diag]))):
    print("Well done, you have won!")
    sys.exit()

There's probably a better way of writing this still, but I haven't had my coffee yet. Basically, I'm again using a comprehensions (or rather, generator expressions) to reduce duplication. If you're writing grid[0], grid[1], grid[2] manually, you likely want to iterate over grid instead.
You could also wrap that condition up in a function, then use the function in both places since each condition is basically the same.
The inner anys could also be replaced with unpacking to make use of the outer any:
if any((*(row == row_os for row in grid),
        *(col == row_os for col in columns),
        *(diag == row_os for diag in [main_diag, counter_diag]))):

But I'm not sure that that's much better.

You should add in error handling. When testing this, I got multiple errors. I accidentally entered 3 in, and got an IndexError, and accidentally pressed enter without entering a number and got a ValueError. Really, the user entering bad input should be expected and handled.

At the end, I have:
import random
import sys

SIDE_LENGTH = 3

def format_grid(grid):
    return "\n".join(" ".join(row) for row in grid)

grid = [["_"] * SIDE_LENGTH for _ in range(SIDE_LENGTH)]
row_os = ["O"] * SIDE_LENGTH
row_xs = ["X"] * SIDE_LENGTH
coords_picked = set()

print(format_grid(grid))  # To make the output represent a grid instead of a list of lists.

# Create a loop to find all co-ordinates in our grid
all_coords = set()
for x in range(SIDE_LENGTH):
    for y in range(SIDE_LENGTH):
        all_coords.add((x, y))

turn = 0
remaining_coords = set()

while turn < 10:
    # Find status of each column
    columns = [[row[i]
               for row in grid]
               for i in range(SIDE_LENGTH)]

    # Find status of 2 diagonals
    main_diag = [row[i] for i, row in enumerate(grid)]
    counter_diag = [row[-i - 1] for i, row in enumerate(grid)]

    # Winning conditions for each player
    if any((any(row == row_os for row in grid),
            any(col == row_os for col in columns),
            any(diag == row_os for diag in [main_diag, counter_diag]))):
        print("The computer has won!")
        sys.exit()
    elif any((any(row == row_xs for row in grid),
            any(col == row_xs for col in columns),
            any(diag == row_xs for diag in [main_diag, counter_diag]))):
        print("Well done, you have won!")
        sys.exit()
    else:
        # If nobody has won yet, take another turn
        if turn % 2 == 0:
            x_coord = input()
            y_coord = input()
            coords_picked.add((int(x_coord), int(y_coord)))
            grid[int(x_coord)][int(y_coord)] = "X"
            print(format_grid(grid))
            turn += 1
        else:
            # Computer randomly picks a co-ordinate in the grid that has not been picked yet
            remaining_coords = all_coords - coords_picked
            comp_coords = random.choice(list(remaining_coords))
            grid[comp_coords[0]][comp_coords[1]] = "O"
            coords_picked.add((comp_coords[0], comp_coords[1]))
            print(comp_coords)
            print(format_grid(grid))
            turn += 1

print("A draw?! We must play again!")


Your lazy method is not thread safe. If two threads check for the key at the same time they will both find it absent and both create a new object.

Wrapping your EnumMap in a ConcurrentMap will get around this.

private ConcurrentMap<Field, Optional> lazyThreadSafeAttributes = new ConcurrentHashMap(lazyAttributes);

private <T> Optional<T> lazyThreadSafeLookup(Field field, Supplier<Optional<T>> answer) {
    return lazyThreadSafeAttributes.computeIfAbsent(field, k -> answer.get());
}


Find a specific file, or find all executable files within the system path

I could have just used the function which(), offered by shutil. Documented here.

Example:

>>> from shutil import which
>>> which('python')
'C:\Python35\python.exe'


Implementing an encryption standard over message text

Functions are your friend. The remove repeated code and improve readability. I have absolutely no idea what the block of text does inside the "".join(XXXX) calls. There is too much going on there that I'm not going to take the time to see what it does or if it can be done better.

However, it does appear that you can replace that mess with something like this:

def doA():
  pass
def doB():
  pass
def makeJoinArgument(value, which_step,step1, step2):
  return step1() if (which_step) else step2() for x in value
def encode(value):
  return "".join("abc", True, doA, doB)
def decode(value):
  return "".join("abc", True, doB, doA)

This obviously doesn't run (and not exactly what you have), but it is much more manageable than what you have now.

Another note (from PEP 8: Style Guide)

  Always use a def statement instead of an assignment statement that
  binds a lambda expression directly to a name.

  Yes:

  def f(x): return 2*x

  No:

  f = lambda x: 2*x

  The first form means that the name of the resulting function object is
  specifically 'f' instead of the generic ''. This is more
  useful for tracebacks and string representations in general. The use
  of the assignment statement eliminates the sole benefit a lambda
  expression can offer over an explicit def statement (i.e. that it can
  be embedded inside a larger expression)


Naming

Class names in general should be singular - Group, Dot.

If you have a constructor which sets coordinates x and y, call the parameters it gets x and y, not a and b... Also, I would refrain from single letter names, although, in this case, x and y seem ok, since they represent coordinates.

Scoping

You declared members, and implemented getters to them which is fine (although you used the wrong idiom for C#), but you failed to declare the members as private. This means that these members are internal, and can be accessed outside the class:

  Depending on the context in which a member declaration occurs, only
  certain declared accessibilities are permitted. If no access modifier
  is specified in a member declaration, a default accessibility is used.
  Top-level types, which are not nested in other types, can only have
  internal or public accessibility. The default accessibility for these
  types is internal.

Edit - this is, of course, wrong (thanks @Matthew) - I got confused with java), the default access modifier for members in C# is private. I still stand by my recommendation to be explicit with private, to be more readable, and compliant with coding conventions.

Object Oriented

For some reason Dot has a property called Group which is... an int?? What did you intend this property to do? If you want it to hold a Group, its type should be Group:

private Group group;

public Group getGroup() {
    return group;
}

public void setGroup(Group group) {
    this.group = group;
}

I also guess the brush is also an instance of a class (and not an int), and should be declared as such:

private Brush brush;

// exercise for the OP...

Also, what is the role of x and y for Group? I should have guessed that Group will hold some Dots instead...

private List<Dot> dots = new List<Dot>();

public Enumerable<Dot> getDots() {
    return dots;
}

public void addDot(Dot dot) {
    dots.Add(dot);
}

What are nested classes? What are subclasses?

You ask whether you should use subclasses of nested classes, but your example shows neither.

A subclass is a class which inherits from another class, and then looks and behaves just like it, plus some other functionality, which makes it a special case of its parent:

public class ChangeRequest : WorkItem {
    // ....
}

In OO design this is expressed as an is a relationship - "ChangeRequest is a WorkItem"

A nested class is a class which is declared inside another class, it does not inherit anything from it, though it might have special permissions to access its enclosing class:

class Container
{
 public class Nested
    {
        Nested() { }
    }
}

Container.Nested nest = new Container.Nested();

As you can see, the relation between Group and Dot doesn't seem to fall under any of these categories, and they should be written as separate classes, each having a property pointing to the other ('Dot has a Group' and 'Group has Dots').


Design pattern review: freeze/thaw (aka, "reversible builder" pattern)

Pattern pros and cons :

Pros :

easy to use
readable (provided you are familiar with the pattern)

Cons :

forces a cyclic dependency between builder and the class being built (we're probably not crossing package boundaries, though)
moves part of the responsibility of the builder to the class being built, in addition to the responsibility that class already had (violating the SRP)

General remarks :

I see no potential clients for the interfaces, i.e. they are little more than marker interfaces.

Conclusion :

In my opinion the pattern adds too little value for what it trades off.


Here is the code refined using these features:

rst.Filter
rst.Update
Scripting.Dictionary
Range("A1").CopyFromRecordset rst

Sub ThisBeTheShitMane()
    Const DBPath = "C:\Users\dzcoats\Documents\Microsoft.accdb"
    Const DebugMode As Boolean = False

    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    Dim key As String
    Dim vAr
    Dim d As Object: Set d = CreateObject("Scripting.Dictionary")

    Set db = DBEngine.OpenDatabase(DBPath)
    Set rst = db.OpenRecordSet("SELECT [VDefects].Defect, [VDefects].Status FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;")

    'Combined List
    With Worksheets(1)
        For Each vAr In .Range("B2", .Range("B" & .Rows.Count).End(xlUp)).Value
            key = vAr
            d(key) = "Completed"
        Next
    End With

    'Open List
    With Worksheets(1)
        For Each vAr In .Range("A2", .Range("A" & .Rows.Count).End(xlUp)).Value
            key = vAr
            If d.Exists(key) Then
                d(key) = "OPEN"
            Else
                If DebugMode Then Debug.Print "vAr: "; vAr, "ID is in the Open List but is missing from the Combined List "
            End If
        Next
    End With

    With rst
        .MoveFirst
        Do Until .EOF
            key = ![Defect]
            .Edit
            ![Status] = IIf(d.Exists(key), d(key), "Bad Defect Number")
            .Update
            .MoveNext
        Loop
        .MoveFirst
    End With

    Worksheets("Sheet2").Range("A1").CopyFromRecordset rst

    rst.Close
    Set rst = Nothing
    db.Close
    Set db = Nothing

End Sub

But we could just let the database do the work for us by converting the Open and Combined list into a comma separated values list and using IN() to check the values.  If [Defect] is a text field you will has to wrap the values in quotes.

Sample Query:

UPDATE VDefects SET VDefects.Status = IIf([VDefects]![Defect] NOT IN (1,2,3,4,5,6) And [VDefects]![Defect] NOT IN (4,5,6,7,8,9),'Bad Defect Number',IIf([VDefects]![Defect] NOT IN (1,2,3,4,5,6),'Completed','OPEN'));

Sub JustDoIt()
    Const DBPath = "C:\Users\best buy\Desktop\Microsoft.accdb"
    Dim db As DAO.Database: Set db = DBEngine.OpenDatabase(DBPath, , True)
    Dim rst As DAO.Recordset
    Dim sSQL As String, t1 As String, t2 As String
    Dim arr1 As Variant, arr2 As Variant

    With Sheet1
        t1 = getValueList(.Range("A2", .Range("A" & rows.Count).End(xlUp)), False)
        t2 = getValueList(.Range("B2", .Range("B" & rows.Count).End(xlUp)), False)
    End With

    sSQL = "UPDATE VDefects SET VDefects.Status = IIf([VDefects]![Defect] NOT IN (" & t1 & ") And [VDefects]![Defect] NOT IN (" & t2 & "),'Bad Defect Number',IIf([VDefects]![Defect] NOT IN (" & t1 & "),'Completed','OPEN'));"

    db.Execute sSQL

    Set rst = db.OpenRecordSet("SELECT [VDefects].Defect, [VDefects].Status FROM [VDefects] WHERE [VDefects].Defect IS NOT NULL;")
    Worksheets("Sheet2").Range("A1").CopyFromRecordset rst

    rst.Close
    Set rst = Nothing
    db.Close
    Set db = Nothing
End Sub

Function getValueList(Target As Range, WrapInQuotes) As String
    Dim arr As Variant
    arr = Application.TRanspose(Target.Value)

    If WrapInQuotes Then
        getValueList = Join(arr, """,""") & """"
    Else
        getValueList = Join(arr, ",")
    End If
End Function


Java String Reverse Algorithm which is the most effcient approch?

Solution 2 is (probably, that depends on many factors) the more efficient one, as its (slightly more complex) loop body is executed only length/2 times, and it doesn't create two character arrays from the input string.

But besides answering your question, I'd like to comment on your coding style - we're on codereview, anyway.

First, I'd always separate input/output and computation, so you can re-use the computation as a "library function" with different input/output or as part of a bigger computation.

Then, you often declare a variable before you want to use it (and even assign an unnecessary initial value to it). It's accepted style to declare a variable exactly when you need it first, and assign it the value you want.

You "adjusted" the length value by -1 because you need that value for the endIndex. That's misleading, as now you have a variable named length, but it doesn't contain the length value. This adjustment should be done in the endIndex variable, not the length.

It's good that you are using Javadoc comments. But you should document pieces of code from an "outside" view: what the method does, not how it's doing its job. See my re-worded javadoc for the main() method.

As a matter of personal style, I'd replace your while loop with a for loop that uses two variables: in every iteration, it increases indexStart and decreases indexEnd.

See my modified version of your solution 2:

package test;

import java.util.Scanner;

public class ReverseString {

    /**
     * This method will read a String from standard input
     * and print the character-reversed string to standard output.
     * @param args
     */
    public static void main(String[] args) {
        //declare variables
        Scanner input = new Scanner(System.in);
        // Don't introduce variables before you need them
        // String inputString = "";
        // int length = 0, indexStart = 0, indexEnd = 0;

        //get input string
        System.out.print("Enter the string you want to reverse: ");
        String inputString = input.nextLine();

        String newString = reverseString(inputString);

        //output result
        System.out.println(newString);

        //close resources
        input.close();
    }

    /**
     * Returns the character-reversed String of the inputString
     * @param inputString the input String
     * @return the input string in reversed order of the characters
     */
    public static String reverseString(String inputString) {
        //find length of string, it needs to be reduced by one to prevent an error
        //as index start at 0.
        // NO! It's not the length that's wrong, it's the indexEnd
        int length = inputString.length();
        //set 'indexOfReferenceArray' equal to string.length-1 for use later in loop
        // int indexEnd = length;

        //convert to arrays
        char[] array = inputString.toCharArray();

        //loop through and reverse order until two vars meet in middle of array
        // while (indexStart<=(length/2)) {
        // I replaced that with a for loop using two variables
        for (int indexStart=0, indexEnd=length-1; indexStart<indexEnd; indexStart++,indexEnd--) {
            //swap array elements
            char temp = array[indexStart];
            array[indexStart] = array[indexEnd];
            array[indexEnd] = temp;
            //increment/decrement to move through arrays
            // That's done by the for loop, now.
            // indexStart++;
            // indexEnd--;
        }

        //convert back to string
        String newString = new String(array);
        return newString;
    }

}

But I'd write still another version of the program:

package test;

import java.util.Scanner;

public class ReverseString2 {

    /**
     * This method will read a String from standard input
     * and print the character-reversed string to standard output.
     * @param args
     */
    public static void main(String[] args) {
        //declare variables
        Scanner input = new Scanner(System.in);
        // Don't introduce variables before you need them
        // String inputString = "";
        // int length = 0, indexStart = 0, indexEnd = 0;

        //get input string
        System.out.print("Enter the string you want to reverse: ");
        String inputString = input.nextLine();

        String newString = reverseString(inputString);

        //output result
        System.out.println(newString);

        //close resources
        input.close();
    }

    /**
     * Returns the character-reversed String of the inputString
     * @param inputString the input String
     * @return the input string in reversed order of the characters
     */
    public static String reverseString(String inputString) {
        int length = inputString.length();
        char[] array = new char[length];

        for (int iSource=0,iTarget=length-1; iTarget>=0; iSource++,iTarget--) {
            array[iTarget] = inputString.charAt(iSource);
        }

        String newString = new String(array);
        return newString;
    }

}


int t = a + b;
a = a > b ?  t - a : a;
b = t - a;
// a is the small one

Or

small = a;
large = b;
if (a>b) {
  small = b;
  large = a;
}

But I think it will be shorter in Python:

if a > b:
   a, b = b, a


I see some things that might help:

index(_:, offsetBy:) is O(n) where n is the amount you're offsetting, so you can squeeze a bit out of calculating the endIndex as an offset from the startIndex especially if you're getting substrings from near the end of the string:

let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(startIndex, offsetBy: end-start)

The other option could be to use the UTF16 view of the string instead of the character view.

The UTF16Index has an option to create directly from an Int (rather than) offsetting an index which will be faster (I assume O(1) but I can't find a reference).

let start16 = String.UTF16Index(start)
let end16   = String.UTF16Index(end)
return String(utf16[start16..<end16])!

The consideration around the UTF16 approach depends if you're going to be using text that has multi-width characters and how you're getting the actual start and end values to make the substring. Here's a post that I found useful getting my head around these options: https://oleb.net/blog/2016/08/swift-3-strings/

So it looks like there is an opportunity for a little bit of a performance increase there!

When you check to see if the string is empty you're checking if the character count is zero. self.characters.count == 0 is O(n) where n is the number of characters, you can get some performance increase here by using self.isEmpty which is O(1).

edit: added 4th option that returns String?

Finally, with the UTF16 option there's the need to cast to a String and force unwrap if you want to return the type String. An alternative could be to return nil instead as your early exit:

I ran a quick profile in Xcode comparing those four options:

1. Baseline approach (in question)
2. Alternative (use isEmpty and calculate endIndex from startIndex)
3. UTF16 (use isEmpty and create UTF16 index directly from Int)
4. UTF16 nil (use isEmpty, create UTF16 index from Int and return String?)

Benchmark substring using "hello tests".substring(1,10)

1. Baseline    -> 1.151s  (2% STDEV)
2. Alternative -> 0.633s  (1% STDEV)
3. UTF16       -> 0.408s  (2% STDEV)
4. UTF16 nil   -> 0.404s  (1% STDEV)

Benchmark early exit using "".substring(1,10)

1. Baseline    -> 0.074s  (4% STDEV)
2. Alternative -> 0.024s (12% STDEV)
3. UTF16       -> 0.024s (11% STDEV)
4. UTF16 nil   -> 0.019s (12% STDEV)

Here's a gist of the test I used for full transparency: https://gist.github.com/mathewsanders/c4c43915c5e1c13e8fe3b912bf4c27d1

So absolutely use isIndex instead of counting characters, and maybe consider using the UTF16 view if it's appropriate for the text you'll be making substrings from.

It also looks like returning nil instead of an empty string gives a bit of a boost, but you might loose that small advantage elsewhere in your code depending on how you handle the nil` return.