XOR linked list implementation - Follow Up

Don't use a different name for a struct and its typedef
Why is struct StNode typedef'ed to StHexNode? What does the Hex mean here, I don't see anything hexadecimal or hexagonal in the rest of the code? You can use exactly the same name for a struct as for its typedef, so I would just use that:
typedef struct StNode StNode;

You can also combine the typedef with the struct definition:
typedef struct StNode {
    ...
} StNode;

Use typedefs consistently
I see you use StHexNode in some places, and struct StNode in others. Be consistent and only use the typedef'ed variant.
Avoid repeating type names if possible
In this line:
StHexNode *newNode = malloc(sizeof(struct StNode));

Besides the inconstent use of the typedef, you repeat the type twice. That makes this error prone (if you make a mistake on the right side it will compile without errors but it will probably be wrong), and if you ever have to change the type of the variable newNode, you would have to do it in at least two places. It is better to avoid repeating the type name, but instead repeat the variable name:
StNode *newNode = malloc(sizeof(*newNode));

Prefer using compound assignment operators to avoid repetition
Use compound assignment operators if possible to save some typing, and also avoiding possible mistakes. For example, instead of:
lastNode->both = (uintptr_t)newNode ^ lastNode->both;

Prefer:
lastNode->both ^= (uintptr_t)newNode;

Simplifying get()
You can simplify the function get() somewhat. In particular, when looping over the elements of a list, try to start at index 0, and avoid making the start and end special cases. You can do this here like so:
StNode *get(StNode *headNode, unsigned int index)
{
    StNode *currNode = headNode;
    uintptr_t prev = 0;

    for (int i = 0; i < index; i++)
    {
        uintptr_t next = currNode->both ^ prev;
        prev = (uintptr_t)currNode;
        currNode = (StNode *)(next);
    }

    return currNode;
}

Note that you could even avoid the declaration of currNode if you change the name of headNode to currNode, but I would personally keep it as it is above, as it makes the role of the parameter and the local variable more clear.
Simplifying free_list()
The same goes for free_list(): you should not need to make a list of one element a special case. Also, why is free_list() calculating the number of elements of a list that will have been deleted by the time it returns?
void free_list(StNode *headNode)
{
    StNode *currNode = headNode;
    uintptr_t prev = 0;

    while (currNode)
    {
        uintptr_t next = currNode->both ^ prev;
        prev = (uintptr_t)currNode;
        free(currNode);
        currNode = (StNode *)(next);
    }
}

Use a unique and consistent naming scheme
If you want to use your XOR linked list in a real program, consider that names like StNode and get() are very generic and will likely conflict with other parts of a larger project. Maybe you need a binary tree implementation as well for example, and how are you going to name its function to retrieve an element at a given index? To solve this issue in C, come up with a unique prefix that you can use for all the struct and function names. For example, prefix everything with xllist_:
typedef struct xllist_node {
    ...
} xllist_node;

xllist_node *xllist_add(xllist_node *lastNode, int value);
xllist_node *xllist_get(xllist_node *headNode, usigned int index);
void xllist_free(xllist_node *headNode);

Of course you can argue about what the prefix should be exactly. I find something like xor_linked_list or XorLinkedList a bit too verbose, so xllist is a compromise: it still has list clearly in the name, and if you don't know what xl is you can look it up, and once you have seen what it means it is easy to remember that xl stands for XOR linked I hope.
Create a struct representing the whole list
You have a struct for a node, but not one for the whole list. That means the caller of your functions has to manually allocate the first list element, and it needs to keep track of both the head and tail node. It is much better if you create a struct representing the list:
typedef struct xllist {
    xllist_node *head;
    xllist_node *tail;
} xllist;

And then pass a pointer to this struct to functions like xllist_get(), xllist_add() and xllist_free(), like so:
xllist_node *xllist_add(xllist *list, int value) {
    xllist_node *newNode = malloc(sizeof(*newNode));
    newNode->both = (uintptr_t)xllist->tail;
    newNode->value = value;

    if (xllist->tail) {
        // Append it to the existing tail node
        xllist->tail->both ^= (uintptr_t)newNode;
        xllist->tail = newNode;
    } else {
        // The list was empty
        xllist->head = newNode;
        xllist->tail = newNode;
    }

    return newNode;
}

And you use it like so in main():
xllist myList = {NULL, NULL}; // declare an empty list

for (int i = 100; i < 200; i++)
{
    xllist_add(&myList, i);
}


VBA Excel function to interpolate precipitation data

Naming

Your variable's names are pretty generic. Tell me what they are - use the name to give information - the characters are free.

The same goes for the function name - IDWW. I'm not sure what it should be doing.

I imagine you'd be good with names like

firstValue, secondValue, thirdValue, firstDistance, secondDistance, thirdDistance

I don't know what those are because they aren't given a Type. Your function also doesn't have a return Type. That means you're taking in 6 variants and returning a variant. That has impact.

Variant

When you don't define or type your variable, VBA will declare it as a Variant, which are objects:

  Performance. A variable you declare with the Object type is flexible
  enough to contain a reference to any object. However, when you invoke
  a method or property on such a variable, you always incur late binding
  (at run time). To force early binding (at compile time) and better
  performance, declare the variable with a specific class name, or cast
  it to the specific data type.

Total you are working with 12 Variants and a return Variant.

You also have 6 variables made of 1 letter and 1 number. The code is already pretty abstract, but seeing something like

For i = k To j Step -1
    For n = 1 To 26
        If k * n > j * n Then
            n = i * j
        Else
        n = i * k
        End If
    Next
Next

Gives me no confidence that I'll be able to decipher what's happening.

You also test like this twice -

If Value2 <> "" And Dist2 <> "" Then
If Value3 <> "" And Dist2 <> "" Then

It seems like these should be optional arguments in the function, otherwise you're forcing the user to submit nulls.

Private Function IDWW(ByVal firstValue As Long, ByVal firstDistance As Long, _
        Optional ByVal secondValue As Long, Optional ByVal secondDistance As Long, _
        Optional ByVal thirdValue As Long, Optional ByVal thirdDistance As Long) As Long

You can also give them default values. If you don't give them defaults, they choose the default value of their Type.

Optional ByVal secondValue As Long = 0, Optional ByVal secondDistance As Long = 0,

You were testing for "" which has a name = vbNullString. But what you should have been testing for is the equivalent for a Variant

If IsEmpty(var) then

Something else you aren't testing for is whether the user passes something else in the Variant, like a Range. Or maybe a negative number. These are all things that can be eliminated with the right Type.

Like here -

If Value2 <> "" And Dist2 <> "" Then
    a2 = Value2 / (Dist2) ^ 2
    b2 = 1 / (Dist2) ^ 2
Else
    a2 = 0
    b2 = 0
End If

If a2 and a3 were Long you wouldn't need to set them, they are by default 0.

At the end

'Avoid a problem if all 3 distances are empty
 If b1 + b2 + b3 = 0 Then
    IDWW = 0

Is that really what you're doing? Adding variants to get 0. But what if I submitted a negative distance? What if I submitted both a negative value and distance?


Creating the buttons on a calculator using a for-loop

Basics
Classes in Java naming conventions should start with an upper-case letter: miniräknare should be Miniräknare.
Variables in Java naming conventions should start with a lower-case letter: Inmatning should be inmatning.
Refactoring
There are a few things in your code that can be refactored to improve the readability. Functions are a part of that. Consider a function that adds a digits to the display:
private void addDigit(String digit) {
    textField.setText(textField.getText() + digit);
}

That function removes the display logic from the action listener, and puts it in the miniräknare class itself.
Another trick in Java is that interfaces with a single method, like an ActionListener are implicitly a functional interface. This allows instances of them to be declared in functional shorthand....
nummerButton[i].addActionListener(e -> addDigit(((JButton)e.getSource()).getText())

One more thing is that the font can be extracted to a constant...
private static final Font keyFont = new Font("Tahoma", Font.BOLD, 20);

Code order
I know this one is pedantic, but when you have "setup code" and "use code", you should put all the setup code first before you use the instance you have set up.
In your case, you have the line of code:

frame.getContentPane().add(nummerButton[i]);

before you add the ActionListener to nummerButton[i].
Also, I would avoid the nummerButton array entirely until the button is complete....
Result
    int kolumn =((i-1)%3);
    int horisont=((i-1)/3);
    JButton key = new JButton(String.valueOf(i));
    key.setBounds((10+(kolumn*60)),(220-(horisont*60)),50,50);
    key.setFont(keyFont);
    key.addActionListener(e -> addDigit(((JButton)e.getSource()).getText());

    nummerButton[i] = key;
    frame.getContentPane().add(key);

If you want, you can put all the JButton creation code in a new function too, but that may be too much refactoring in your case depending on how much other code is in your method....
private JButton createKey(int value) {
    int kolumn =((value-1)%3);
    int horisont=((value-1)/3);
    JButton key = new JButton(String.valueOf(value));
    key.setBounds((10+(kolumn*60)),(220-(horisont*60)),50,50);
    key.setFont(keyFont);
    key.addActionListener(e -> addDigit(((JButton)e.getSource()).getText());
    return key;
}

and then your calling code becomes:
    nummerButton[i] = createKey(i);
    frame.getContentPane().add(nummerButton[i]);


I'd add only a couple of minor things.

The comments are more trouble than they're worth. I understand it's a tutorial, but if they're going to be in there, they should do more--right now they don't add value. Since it's a learning exercise, use those comments to teach them something, including terminology.

// Create a new GuessingGame instance to represent the current game.
// Begin playing by calling the startGame() method.

But I'd leave them out altogether, and have the corresponding text/lecture do the describing; you will achieve more by writing or talking about them outside of the code.

Secondly, I'd consider keeping the players in an array or a list. If not now, then in "part two". This simplifies the code conceptually, because you can directly represent "for each player, check their guess" in code. If not in "part one", then I'd at least move the guess-getting into another method--you only need to return a boolean, the players hold whether or not it's a right guess.

(IMO the player shouldn't maintain that state, rather the game should.)

Next, I'd refactor more; the startGame does more than starts the game. Either refactor, or rename. Right now, startGame starts, plays, and ends the game. By refactoring, the code becomes more story-like, at the cost of more methods. But good methods should be tightly focused and easy to reason about.

On a more theoretical level, the end conditions as implemented makes a certain assumption about the nature of the game. Asking if anyone can spot a potential "gotcha" with the current implementation might be a good "extra credit" problem.

In real life, what would happen if two players both guessed correctly? In the current implementation, the players are always checked in numerical order. In real life, a typical game would be either who guessed the fastest (which I supposed the player order could be said to represent), or multiple players could win, or...?

To put that into "real life" terms, let's say the guesses are access control votes, or search result weightings, etc. In those cases, a tie does matter. So instead of having a single winner, there would be a collection of "winners". How to decide if there should be a single winner, or a group, depends on the nature of the game.

Lastly, I'd make some of the things more configurable, although perhaps with reasonable defaults. This also mirrors real life a bit more accurately, and I tend towards adding a bit of complexity early, since it can be ignored.

Some of my suggestions are more appropriate for a "second round" implementation, while some make sense for what you have now. Pick and choose, or ignore them all :) I've appended everything in a single blob.

public class GuessingGameTester {

    public static void main(String[] args){
        GuessingGame game = new GuessingGame();
        game.startGame();
    }

}

public class GuessingGamePlayer {

    private int playerNumber;

    public GuessingGamePlayer(int playerNumber) {
        this.playerNumber = playerNumber;
    }

    int getGuess(){
        return new Random().nextInt(GuessingGame.MAX_GUESSING_NUMBER) + 1;
    }

    @Override
    public String toString() {
        return "Player " + playerNumber;
    }

}

public class GuessingGame {

    private int numberToGuess;
    private int roundsToPlay;
    private int numberOfPlayers;
    private List<GuessingGamePlayer> players;

    public static int MAX_GUESSING_NUMBER = 20;

    public GuessingGame() {
        init(100, 3);
    }

    public GuessingGame(int roundsToPlay, int numberOfPlayers) {
        init(roundsToPlay, numberOfPlayers);
    }

    public void init(int numberOfRounds, int numberOfPlayers) {
        this.roundsToPlay = numberOfRounds;
        this.numberOfPlayers = numberOfPlayers;

        numberToGuess = new Random().nextInt(MAX_GUESSING_NUMBER) + 1;

        initPlayers();
    }

    public void initPlayers() {
        players = new ArrayList<GuessingGamePlayer>();
        for (int i = 0; i < numberOfPlayers; i++) {
            players.add(new GuessingGamePlayer(i+1));
        }
    }

    public void startGame() {
        int currentRound = 0;
        GuessingGamePlayer correctGuesser = null;
        System.out.println("The number to guess is: " + numberToGuess);

        while((correctGuesser == null) && (currentRound <= roundsToPlay)) {
            ++currentRound;
            System.out.println("\nRound " + currentRound);

            for (GuessingGamePlayer player : players) {
                int playerGuess = player.getGuess();
                System.out.println("  " + player + " guessed " + playerGuess);
                if (playerGuess == numberToGuess) {
                    correctGuesser = player;
                }
            }
        }

        System.out.println();

        if (correctGuesser == null) {
            System.out.println("Nobody guessed the right number!");
        } else {
            System.out.println(correctGuesser + " guessed the number in round " + currentRound);
        }
    }

}


Feedback on Pitch Constellation/ Chromatic Circle in Python Project

Immutable sequences
Convert notes and the values in scale from list literals [] to tuple literals () since it's expected that they cannot and will not change.
Musical theory
Consider distinguishing between harmonic and melodic minor, which are different scales.
Global code
Move
rootkey = input("Enter the root Note: ").upper()

into your main(). Also, your constructor
def __init__(self, key):
    self.rootkey = rootkey

needs to refer to its key argument and not the rootkey global.
Shadowing
def shift(self, rootkey, index=0, s=0,):

has a number of issues:

You're shadowing the global rootkey with an identically-named argument
You shouldn't have a rootkey argument at all, since it's already a member on self

Loop like a native
Consider renaming index and s to first_index and first_s, so that you can replace your while with
for index, s in zip(
    range(first_index, 12),
    range(first_s, 12)
):

Inner prints
Delete the print from here:
            print(new_notes)
            return new_notes

If you want to print it, do so at the outer level.
Logic by exception
Consider writing
mode = input("Enter the mode: ").lower()
try:
    x = scale.get(mode)
    keymode = [key[i] for i in x]
    print(keymode)
except:
    if mode not in scale:
        print("Scale not in list. Please start the program again.")
    return

as
mode_name = input("Enter the mode: ").lower()
mode = scale.get(mode_name)
if mode is None:
    print(f"Scale {mode_name} not in list. Please start the program again.")
else:
    key_mode = [key[i] for i in mode]
    print(key_mode)

In other words, where possible do not rely on exceptions (especially with no type specified) to govern your logic; and avoid a double-dictionary lookup by using get.


Remove duplicates from array of non-equatable objects

First note that there is no need to make the SearchResult properties (implicitly unwrapped) optionals, as they are always initialized:

class SearchResult { // non-equatable
    var index: Int
    var score: Int

    init(_ index: Int, score: Int = 0) {
        self.index = index
        self.score = score
    }
}

Your approach is indeed not optimal, after determining a unique set of property
values, the original array must be searched for each value separately. This lookup can be improved slightly by using first(where:)

var noDupes: [SearchResult] = []
indices.forEach { (index) in
    guard let notADupe = withDupes.first(where: { $0.index == index }) else { return }
    noDupes.append(notADupe)
}

The advantage of first(where:) over filter + first is that it short-circuits and does not create an intermediate array.

But a better and faster solution would be to modify the removingDuplicates()
method so that it compares the array elements according to a given key (which is
then required to be Equatable).

Here is a possible implementation, using the “Smart KeyPath” feature
from Swift 4:

extension Array {
    func removingDuplicates<T: Equatable>(byKey key: KeyPath<Element, T>)  -> [Element] {
        var result = [Element]()
        var seen = [T]()
        for value in self {
            let key = value[keyPath: key]
            if !seen.contains(key) {
                seen.append(key)
                result.append(value)
            }
        }
        return result
    }
}

This can then simply be used as

let searchResults: [SearchResult] = [SearchResult(0), SearchResult(1), SearchResult(1), SearchResult(2), SearchResult(2)]

let withoutDuplicates = searchResults.removingDuplicates(byKey: \.index)

It might also be worth to add another specialization for the case that the key is
Hashable (as it is in your example) because then the seen array can be replaced by a set,
which improves the lookup speed from O(N) to O(1):

extension Array {
    func removingDuplicates<T: Hashable>(byKey key: KeyPath<Element, T>)  -> [Element] {
        var result = [Element]()
        var seen = Set<T>()
        for value in self {
            if seen.insert(value[keyPath: key]).inserted {
                result.append(value)
            }
        }
        return result
    }
}

Note that if seen.insert(key).inserted does the “test and insert if not present” with a single call.

Another (more flexible) option is to pass a closure to the function which determines
the uniquing key for each element:

extension Array {
    func removingDuplicates<T: Hashable>(byKey key: (Element) -> T)  -> [Element] {
        var result = [Element]()
        var seen = Set<T>()
        for value in self {
            if seen.insert(key(value)).inserted {
                result.append(value)
            }
        }
        return result
    }
}

Example:

let withoutDuplicates = searchResults.removingDuplicates(byKey: { $0.index })


Here are my thoughts:

Why is this a POST operation at all?  Why not GET, since you are not changing ANY data whatsoever? The "parameter" you pass is not meaningful (it is just the base URL of the remote service) and it is not really even used in the server side script other than to append to the image name.  If that is the case why not just remove it altogether since client already know the base URL of the site anyway.
Both the client-side cURL code and server-side code very heavily assume that everything is working correctly (the so called "happy path").  Some examples of that:

On server side, don't just do something like die() if the the request is mal-formed.  Good services will reply with an HTTP 400-series error if the request is bad. That allows the client-side code to potentially better understand what went wrong, rather just receiving an empty HTTP 200 response.
If you were actually passing a meaningful parameter, you might consider stronger server-side validation before working with it.  What happens if empty string is passed?  What happens if an extraordinarily long string (i.e. buffer overflow attack) is passed?
In your getImages function you actually start to handle the edge case by having a conditional around being able to read the directory.  Where is the else to handle a guess where directory is not readable?  You would likely need to send a 500 series response to client to let them know there is internal server problem that is preventing the request from being fulfilled.
On client side, what happens if the server is not able to get a good response?

You are kind of relying on undocumented JSON behavior that certain libraries allow when you are just JSON-encoded a string primitive.  Technically, the JSON specification requires that the only allowed root structures are objects or arrays.  Passing an encoded primitive is not reliable behavior, if you ever have other clients connecting to this service.  You should consider explicitly creating and passing an array like $image = array(randomImage($images))
You should just be echoing out json_encode($image) not print_r


Java Palindrome - Time & Space Complexity

First solution requires O(1) space and O(n) complexity.

The last one looks to be less than 100% efficient, because you could directly return false when you find out it is not a palindrome, but it continues until the loop ends.


Checking that a filename does not end with "Com.js"

By mechanical transformation, I arrive at:

function checkFile(file) {
    return file == null || !jQuery.endsWith(file, "Com.js");
}

The use of === strict equality checking is not necessary; == lumps null and undefined together.

I have my doubts about the whole function, though, as the function name gives no indication that it's going to check whether its argument ends in "Com.js".


script- loop through files and directories

There's no documentation. Even a comment at the top of the script summarizing what it does would be better than nothing.
There's no error handling. What if the user forgets the argument?
This script will break if the argument $1 contains a space. You need to write "$1" in several places.
You don't need to put ; at the end of lines like this:

echo "$line is a directory";

This code is really unclear:

length=${#1}
const=4
count=$((length-const))
DIREC=$(echo $1 | cut -b 1-$count)

First, the variable names are poorly chosen: length of what? why const? count of what? Second, this assumes that $1 ends with .zip and will go wrong if the file has any other name. Third, Bash has a feature ${parameter%pattern}  for removing a suffix from a string, so you can remove the extension from $1 like this:

DIREC=${1%.*}

But fourth and most importantly, how do you know that the ZIP file will unpack into a directory with the same name as the ZIP file? In the example below I create a ZIP file called b.zip that unzips into the directory a:

$ mkdir a
$ touch a/a
$ zip b a/a
  adding: a/a (stored 0%)
$ rm -r a
$ unzip b
Archive:  b.zip
 extracting: a/a

What you should do instead (that is, if you must unzip $1) is to use the -d option to unzip to extract it to a known place.

$ unzip -d b b
Archive:  b.zip
 extracting: b/a/a

Why is OUTPUTFIL misspelled? Why not spell it OUTPUT_FILE?
It's a bad idea to put temporary files like $OUTPUTFIL in the current directory. There might already be a file called out.xml in the current directory and then you would end up overwriting it. You should use the mktemp program to create a unique temporary file name or directory, for example like this:

OUTPUT_FILE=$(mktemp -t unzip-XXXXXX.xml)

These lines have several problems:

find $DIREC -exec echo {} \; >tmp.txt
exec<tmp.txt
while read line

First, this will go wrong if $DIREC contains a space: you need to use quotes.
Second, this will go wrong if $DIREC starts with a - (it will be interpreted as an option): you need to use the -f option to find.
Third, there's no need to run a separate echo command for each file: find has a -print option.
Fourth, you don't need to write the output to a temporary file in order to read it using while read line; you can pipe the output of find into the while loop. Like this:

find -f "$DIREC" -- -print | while read line; do

Inside your while loop you use [ -f ... ] to ensure that you only process plain files (not directories). But you could use the -type f argument to find to ensure that it only outputs plain files:

find -f "$DIREC" -- -type f -print | while read line; do

This line will go wrong if $line contains a space or starts with a -:

BASE=$(base64 $line);

You should write:

BASE=$(base64 -i "$line")

It's not a good idea to read the output of the base64 program into a variable like this: the output might be very large and cause Bash to use large amounts of memory. It is better to let base64 write its output directly to your output file, so that it does not have to be stored in a variable in Bash. Instead of:

BASE=$(base64 $line);
{
    echo "<inpu>${BASE}</inpu>"
} > ${OUTPUTFIL}

you should write:

{
    echo "<inpu>"
    base64 -i "$line"
    echo "</inpu>"
} > "${OUTPUT_FILE}"

However, there is no need for an OUTPUT_FILE at all here, because curl accepts the filename - meaning "standard input", so you can write:

{
    echo "<inpu>"
    base64 -i "$line"
    echo "</inpu>"
} | curl -u admin:secret --data-binary @- http://dp1-l2.com

<inpu> looks like a typo to me. Are you sure you don't mean <input>? If <inpu> is correct, you should probably add a comment to explain why.
It would be better to put configuration settings like admin:secret and http://dp1-l2.com in named variables at the top of the file. (It might be even better to accept them as command-line arguments.)
The way you have written this code means that each individual file in the archive gets uploaded as a separate XML file to the server. Is this really what you want? It seems more likely to me that you would want to upload the whole archive as one XML file. Otherwise, what's the point of using XML?
As you suspected, there is in fact no need to unzip the file, because you can use zipinfo -1 to get a listing of the contents, and then use the -p option to unzip to extract a file to standard output.

Putting all this together, I would write the script line this:

#!/bin/bash
# upload-zip.sh -- encode contents of ZIP archive as base64
# strings in an XML document, and upload it.

# Destination and credentials for upload.
UPLOAD_URL=http://dp1-l2.com
USER=admin
PASSWORD=secret

if [ "$#" != 1 ]; then
    echo "Usage: $0 zipfile"
    exit 1
fi
ZIPFILE=$1

zipinfo -1 -- "$ZIPFILE" | while read FILE; do
    echo "<input>"
    unzip -p -- "$ZIPFILE" "$FILE" | base64
    echo "</input>"
done | curl --user "$USER:$PASSWORD" --data-binary @- --url "$UPLOAD_URL"


Is it ok to use PHP's strpos and substr altogether in one statement?

Instead of raw string manipulation, I would use parse_url and parse_str:

<?php

// Note: parse_url is not intended for relative URLs
// (in other words, bare $_SERVER['REQUEST_URI'] will not work -- you'll have to build a full URL)
$url = 'http://mydomain.com/api/format/method?app_id=value&call=encrypted_request';

$path = explode('/', ltrim(parse_url($url, PHP_URL_PATH), '/'));
parse_str(parse_url($url, PHP_URL_QUERY), $query);

$api = array_shift($path);
$format = array_shift($path);
$method = array_shift($path);

$app_id = (isset($query['app_id'])) ? $query['app_id'] : null;
$enc_request = (isset($query['call'])) ? $query['call'] : null;

Yes, this code is a bit longer, but it's more readable to me. Also, raw string manipulation is hazard to failing border cases. If you use a well tested parser, problems less likely.

And, as an added bonus, this routing isn't tied to any globals. Off the top of my head I can't think of a reason, but at some point, it might be useful to be able to route a fake request. It definitely makes unit testing easier.


Overall, it looks clean, but here are some potential improvements:

XPaths, generally, don't handle multi-valued class attributes well - you would have to workaround it with concat to make reliable. A better way would be a CSS selector - here are all 3 XPaths replaced with a relevant CSS selector:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".ellipsis > a"))).click()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "li > a[data-name='Photo Shoot']"))).click()

# items
wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "h6.title")))

avoid using layout-oriented classes like col-xs-12 in your locators
I would rename items to title
since you are using lengthy expected condition names - what if you would extract them into more concise variable names, e.g.:

from selenium.webdriver.support.expected_conditions import visibility_of_element_located as is_visible
from selenium.webdriver.support.expected_conditions import presence_of_all_elements_located as all_present

it might be a good idea to use try/finally to quit the browser in case the driver fails
you can also submit the search by appending a \n to the search input - this will remove the need to look for the submit button and clicking it:

wait.until(is_visible((By.ID, "searchbar-input"))).send_keys("Paris\n")

All the above mentioned changes applied:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import visibility_of_element_located as is_visible
from selenium.webdriver.support.expected_conditions import presence_of_all_elements_located as all_present

driver = webdriver.Chrome()

try:
    driver.get("https://www.peerspace.com/")
    driver.maximize_window()

    wait = WebDriverWait(driver, 10)

    wait.until(is_visible((By.ID, "activity-input"))).click()
    wait.until(is_visible((By.CSS_SELECTOR, ".ellipsis > a"))).click()
    wait.until(is_visible((By.CSS_SELECTOR, "li > a[data-name='Photo Shoot']"))).click()

    wait.until(is_visible((By.ID, "searchbar-input"))).send_keys("Paris\n")

    titles = wait.until(all_present((By.CSS_SELECTOR, ".title")))
    for title in titles:
        print(title.text)
finally:
    driver.quit()

We can further improve on following the DRY principle and extract the common wait.until(is_visible(...)) part into a separate function.


It looks pretty clean to me.

The copy constructor doesn't have to be explicitly declared, you could = default it or just omit.
You shouldn't fill() the array. It is already default constructed, so that's just duplicated work. The default constructor again could be = default or omitted.
Actually, maybe could provide an explicit constructor that takes a fill value. That can be handy.
A size() method to return sizeof(arr_) / sizeof(arr_[0]) should be useful, for both internal and external uses.
Mark the class final? I'd probably do it, but that's probably a matter of personal preference.
If you're interested in making this class Standard compliant, well, there's a long road ahead ;). It needs iterators and several other methods ([c]begin/[c]end/front/back/at...). Look into std::array for the details.


Finding a Cartesian product of multiple lists

You can indeed create a cartesian product without recursion. What you need is to use the enumerator.

I used a non-generic enumerator to work with any types.

public static IEnumerable Cartesian(this IEnumerable<IEnumerable> items)
{
    var slots = items
       // initialize enumerators
       .Select(x => x.GetEnumerator())
       // get only those that could start in case there is an empty collection
       .Where(x => x.MoveNext())
       .ToArray();

    while (true)
    {
        // yield current values
        yield return slots.Select(x => x.Current);

        // increase enumerators
        foreach (var slot in slots)
        {
            // reset the slot if it couldn't move next
            if (!slot.MoveNext())
            {
                // stop when the last enumerator resets
                if (slot == slots.Last()) { yield break; }
                slot.Reset();
                slot.MoveNext();
                // move to the next enumerator if this reseted
                continue;
            }
            // we could increase the current enumerator without reset so stop here
            break;
        }
    }
}

Example:

var letters = new string[] { "A", "B" };
var numbers = new[] { 1, 2, 3 };
var symbols = new[] { "@", "#" };
var empty = new string[] { };

var collections = new IEnumerable[] { letters, numbers, symbols, empty };
collections.Cartesian()
    // this is just for show
   .Select(x => string.Join("", x.Cast<object>()))
   .OrderBy(x => x)
   .Dump(); // linqpad

result:

A1#
A1@
A2#
A2@
A3#
A3@
B1#
B1@
B2#
B2@
B3#
B3@


It appears the goal here is to provide parameters to a resolve operation using a different format, something string-based. This appears to be primarily useful in a service location (manually executing Resolve) scenario rather than true DI, so I would caution you to be careful.

Since this started as an Autofac solution, I'll post an answer based on Autofac.

My first recommendation would be to implement a new Parameter type rather than entirely separate handling of strings. This would make the solution more interoperable with other parameter types and Autofac on the whole. You can see how other parameter types like ResolvedParameter and NamedParameter are implemented to give you examples.

My second recommendation would be to look at how Autofac.Configuration handles parsing the string values into objects. Convert.ChangeType doesn't work on a lot of things and having a more robust mechanism will be valuable.

Finally... if possible, I might consider looking at the design that requires this and see if it can be changed. As I mentioned, this appears to be primarily useful in service location and it'd be better if you can switch your solution to use actual dependency injection. That'd mean the parameters need to be available either during registration time (e.g., read them from config and include their values when registering things); or during runtime, in which case you'd likely resolve a Func<Xy, Y, B> or something similar in your consuming class and not use a lifetime scope. In either case, the utility of this mechanism once you switch to DI is much more limited. It could be that just using Autofac.Configuration will suffice.


v2 - Adding a duplicate entry randomly into a list in haskell using random monad

I'd again advise against using monadic computations that produce lazy infinite lists. For most monads (including State) this does not work. For MonadRandom it works only very special cases, when the infinite list is the last randomized computation (if you add another randomized computation after the infinite list, it will diverge).

I can think of two possible solutions:

Find a way to properly formalize this idea of infinite randomized lists and get support from the library authors (or send patches yourself). Since this is for me an interesting problem as well, I started a discussion on this topic.
Use conduits or a similar pipe-like library (such as pipes). This way, you can separate the producer of your values, which can be infinite, and a consumer, that takes only as many values as it needs. The library then "switches" between them: each time a consumer requests input, the producer is asked to provide a new value and is suspended again. In your case this could be used as follows:

import qualified Data.Conduit as C
import qualified Data.Conduit.List as C
import Data.List
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Random

-- ...

-- Produces an infinite source of randomized lists.
duplicateListsSource :: (MonadRandom m) => [a] -> C.Source m [a]
duplicateListsSource xs =
    forever $ lift (addRandomDuplicate xs) >>= C.yield

main :: IO ()
main = do
    putStrLn $ "list comparison " ++ prettyList list
    g <- getStdGen
    shuffled <- evalRandT (duplicateListsSource list C.$$ C.take 5) g
    putStrLn $ "lists after \n"
               ++ intercalate "\n" (map prettyList shuffled)
  where
    count = 5
    list = ["a","b","c"]


Rapid color replacement for in-memory BMP

Computing rowsize inside bitfox_find_xy (that is, for each and every pixel)seems wasteful: row size never changes during the bitfox_color_replace_data invocation, and shall only be computed once.


Calculating the nth prime number for huge BigIntegers

Small nit:

if (candidate.compareTo(TWO) == -1)
    return false;

This is implementation dependence on BigInteger - better to use generic way:

if (candidate.compareTo(TWO) < 0) {
    return false;
}

Also - this is in general more readable and less error-prone to wrap the if statements in {}-brackets even for 1-liners.

Some tricks to possibly improve performance:

Precalculate Erathosphenes sieve till some number you can handle sieve completely in memory (don't use BigInteger for storing those) and check up to sqrt but iterating through primes only and when you exhausted sieve - switch back to your method.
Did you try BigInteger#isProbablePrime here? This will tell you much faster if current number is composite - so you will do less checks.


I haven't used it, however all of the documentation seems to suggest that you need explicitly free the memory allocated through:

IntPtr handle = Marshal.AllocHGlobal(bufferSize);

With a paired call to:

Marshal.FreeHGlobal(handle);

You don't seem to need the handle after you've performed the marshalling, so it could be as simple as updating the function to:

public static byte[] ToByteArray<T>(this T structure) where T : struct
{
    var bufferSize = Marshal.SizeOf(structure);
    var byteArray = new byte[bufferSize];

    IntPtr handle = Marshal.AllocHGlobal(bufferSize);
    try
    {
        Marshal.StructureToPtr(structure, handle, true);
        Marshal.Copy(handle, byteArray, 0, bufferSize);

    }
    finally
    {
        Marshal.FreeHGlobal(handle);
    }
    return byteArray;
}

Depending on the overhead of The AllocHGlobal / FreeHGlobal and if you're going to be marshalling the same structures over and over again you might be better off going with something like:

public sealed class Marshaller<T> : IDisposable where T : struct
{
    readonly IntPtr _handle;
    readonly int _bufferSize;

    public Marshaller()
    {
        _bufferSize = Marshal.SizeOf(typeof(T));
        _handle = Marshal.AllocHGlobal(_bufferSize);
    }

    public byte[] ToByteArray(T structure)
    {
        var byteArray = new byte[_bufferSize];

        Marshal.StructureToPtr(structure, _handle, true);
        Marshal.Copy(_handle, byteArray, 0, _bufferSize);

        return byteArray;
    }

    public T ToStructure(byte[] byteArray)
    {
        var packet = new T();

        Marshal.Copy(byteArray, 0, _handle, _bufferSize);

        return Marshal.PtrToStructure<T>(_handle);
    }

    #region IDisposable Support
    private bool disposedValue = false;

    ~Marshaller() {
       Dispose();
    }

    public void Dispose()
    {
        if (!disposedValue)
        {
            Marshal.FreeHGlobal(_handle);

            disposedValue = true;
        }

        GC.SuppressFinalize(this);
    }
    #endregion

}


Use indexes on products

class Product {

    private static $products = [];

    public static function initialize($url)
    {
        // Build the product from our JSON file
        $data = json_decode(file_get_contents($url));
        foreach($data as $item) {
            $product = new Product();
            $product->id = $item->id;
            $product->description = $item->description;
            $product->category = $item->category;
            $product->price = $item->price;

          self::$products[$product->id] = $product;
        }
    }

    public static function find($id)
    {
        if(isset(self::$products[$id])) {
            return self::$products[$id];
        }

        return false;
    }
}


Create a collection of functions tupled with a collection of parameters, and execute the collection in order in Scala

Unless I misunderstand your question, I think this is what you want:

type Subroutine[Param] = Param => Any

type Routine = Seq[(Subroutine[_], Seq[Any])]

def execRoutine(routine: Routine): Unit = routine foreach { case (sub, params) => execSubroutine(sub, params) }

def execSubroutine[SubParam] (subroutine: Subroutine[SubParam], params: Seq[Any]): Unit = {
    require(params.nonEmpty)

    subroutine(params.head.asInstanceOf[SubParam]) match {
        case sub: Subroutine[_] => execSubroutine(sub, params.tail)
        case () => require(params.tail.isEmpty) // Require correct number of params.
        case _ => throw new IllegalStateException()
    }
}

val add2 = (a: Int) => (b: Int) => println(a + b)
val add3 = (a: Int) => (b: Int) => (c: Int) => println(a + b + c)

execRoutine(List(
    (add2, List(3, 4)),
    (add3, List(3, 4, 5))
))

Try it online!

This program prints 7 and 12. Unfortunately, if the parameters are of the wrong type, a runtime exception occurs instead of a compile time one. Attempting to apply the less or more than the required parameters also results in a runtime exception.


You use yield properly, it's OK to yield from inside nested loops. But all the code behind your first foreach is kind of useless, it's not doing anything useful.

First the yield break is useless, cause there are no more yields following, there are no more return values produced no matter if IsLeaf true or false. Iteration ends anyway.

Second you fill up results with something, but the content of results is lost, then the Method exits.


Constructor function, prototype and making a modal

Here's some thoughts

function modal(width, height, backgroundColor, overlayColor, showOverlay, url) {

One problem some programmers rant with this is that if you forget a parameter, or forget the order. This would seriously impale your code. An alternative is to pass an object that contains the config.

new Modal({
  width : 100,
  height : 100
});

One advantage of this over the previous is that you become more verbose and don't need to remember the order of the params. Additionally, you can use $.extend to place in defaults, if they didn't exist on options.

function Modal(options){
  options = $.extend(options,{
    width : /*default width */,
    height : /*default height */
  });
  ...
}

this.createModal = function () {...};
this.themeModel = function () {...};

You lose the advantage of prototypal inheritance. Better put methods on the prototype so they are shared. Advantage is you save memory by not duplicating functions per instance. Disadvantage is you lose emulated private property - but everything is accessible one way or another, no point using privates.

$('.modalOverlay').css({
    'background-color': overlayBgColor
});

$('.modalContent').css({
  'background-color': this.backgroundColor,
  'width': this.width,
  'height': this.height
});

Suggesting you move this to CSS by adding/removing classes. That way, proper separation of concerns is attained. You don't want to be debugging and 1 hour later, realize that the styles were not in the CSS files but in JS files.

To clarify, this kind of code will bite back in the long run. Suggesting you add a class to the top-most element of your modal HTML, and then style relative to it. You can provide a custom class name to the constructor instead of the styles.

.blackish-modal a{/*style for links on modal with blackish-modal class*/}
.whitish-modal a{/*same goes, but for whitish-modal class*/}

$('.modalInner').load(url);

IMO, $.fn.load is just a convenience function. Suggesting you use the lower-level AJAX functions for more flexibility. But as a convenience function, if it works for you, that's fine.

result = 'rgba(' + r + ',' + g + ',' + b + ',' + opacity / 100 + ')';

String cocatenation in JS is really messy with all that quotes. Here's an alternative:

var rgba = [r,g,b,opacity/100].join(',');
result = 'rgba(' + rgba + ')';

var delegateLoginModal = new modal("90%", "", "", "", true, "");

// create your events
$('body').on('click', '.showModal', function (e) {
    e.preventDefault();
    delegateLoginModal.showModal();
});

Suggesting you look at how Bootstrap implemented their modal. It's in a form of a jQuery plugin. Your code looks cleaner if it did something as clean as:

$('someElement').modal(/*config|method*/);


The MSDN example is saving to a physical file, so the method incurs I/O - yours streams it to a MemoryStream, so it definitely feels more efficient.

I'm a bit (pun not intended) worried about the undisposed Bitmap and MemoryStream objects though, both of which implement the IDisposable interface, and I think some of the intermediate variables could be skipped - would this work?

using (var bitmap = new Bitmap(image))
using (var stream = new MemoryStream())
{
    var parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8L);

    var info = GetEncoderInfo("image/tiff");
    bitmap.Save(stream, info, parameters);

    return Image.FromStream(stream);
}

I'd be almost tempted to inline GetEncoderInfo too, unless it's reused elsewhere.

That would take this line:

    var info = GetEncoderInfo("image/tiff");

And turn it into...

    var info = ImageCodecInfo.GetImageEncoders()
                             .FirstOrDefault(info => info.MimeType == "image/tiff");

If the method is used in a number of places (hmm, well it's private so I doubt it), it could be interesting to turn the method (which is already static anyway) into an extension method:

public static Image To8bit(this Image image)


There is a reason why "Data Structures and Algorithms" has the data structures part added in, especially first. The reason why is data structures should be the first thing you think about even before writing any kind of algorithm.

Lets take the specification of the code that you are given:

  Write some code to find all the common elements in two arrays.

Now first thing is first this isn't specific enough, what do you mean by "common elements", does this include repeating elements so for example [1,1,2] and [1,1,3] would that be [1,1] or just [1]? For this I'm going to assume you mean elements non repeating.

Now after we have established the specification which is

  Given two arrays of numbers find the common unique elements.

I'd say these arrays are sounding a hell of a lot like a set data structure, and this set data structure, because we want to find the intersection between these two sets. In java this would be:

public static void main(String[] args) {
    List<Integer> alist = Arrays.asList(new Integer[] {1,1,2});
    List<Integer> blist = Arrays.asList(new Integer[] {1,1,3});

    HashSet<Integer> aset =  new HashSet<>(alist);
    aset.retainAll(blist);

    System.out.println(aset);
}

It's very important to consider two things when someone gives you a spec, first think through is it clear enough, and secondly, after you have got an idea of what they want you want to strongly consider the data structure as these are structures that have been tried and tested to be efficient at specific tasks.

In the program above, let A be the size of alist and B be the size of blist the time complexity is O(A + B) as it's O(1) to add an element to a hashset which we do for each element in A, then we loop though all elements in B because of the retainAll function needs to do a contains operation on each element, and that is O(1) for a HashSet. This is much more efficient than O(AB) ~ or O(n^2).

edit:

Thanks to nullbyte for pointing out that its more efficient to make one hashset and do ratainAll for just that single set. The code above has been adjusted.


if($originalArraySingle['original-price'] < $priceRange['original-price']['min']){
    $priceRange['original-price']['min'] = is_int($originalArraySingle['original-price']) ? number_format((float)$originalArraySingle['original-price'], 2, '.', '') : $originalArraySingle['original-price'];
}

You could write a function for this. And one for maximize.

protected function minimize($a,&$b){
    if($a<$b){
        $b = is_int($a)?number_format((float)$a,2,'.',''):$a;
    }
}

I would also write.

if($priceRange['price']['max']===$priceRange['price']['min'] ||  $priceRange['price']['max']===$priceRange['price']['min']){
        return null;
    }

and change

return $showRange ? $priceRange : null;

to

return $priceRange;

so you have one variable less.


Indentation:

From the Coding Style recommendation, I am using 2-space indentation, which works for me. The guide suggests that you should avoid tabs as well:

  Do not use TAB characters (ASCII HT, 0x09). There is no standard default TAB setting, so the look of source files using TAB characters will depend on client settings. This may result in a chaotic view of source files. Align by space characters (also see Indentation).

However, the same coding style says that you should not use space around operators, symbols...:

  Don't use spaces around operators, colons, parentheses etc. e.g. write p:=p+i; instead of p := p + i ;.

Since I am not using colored symbols, I've chosen to follow the "Guideline of the Lazarus 1.4.0 color preview":

As you can see, the color preview of the IDE uses spaces around symbols (:=, +, -, *, and so on). Whoever wrote this preview is a point out of curve like me.

Code:

Repeat is a posttest loop, and your code needs to run at least once, so why not a repeat..until loop.. In another words, you know the first key will always be different from #13, you hardcoded it. You can save a begin..end block, as well.
You do not need begin..end blocks for one line statements inside case conditions.

Structure:

For code reuse and exploration I would find it more practical to create a function that would only wait for and then return the password:

program HandlePassword;

uses
  crt;

function WaitForPassword: string;
var
  key: char;
  len: integer;
begin
  Result := Chr(0);
  key := Chr(0);
  repeat
    key := ReadKey;
    len := Length(Result);
    case Ord(key) of
      8: if len > 0 then Delete(Result, len, 1);
      else Result := Result + key;
    end;
  until key = Chr(13);
end;

begin
  ClrScr; // clear screen
  Write('Write the password:');
  WriteLn(WaitForPassword);
  ReadLn; // pauses the code
end.


It looks pretty good to me. I can only see a few things to consider:
More precise propertyName check You have if(e.propertyName.includes('flex')) { because Safari uses flex and others use flex-grow. Are you sure that the flex substring won't be present in any other possible CSS transitions? Even if you're sure, will readers of the code be sure? I'd change to an === test against both possibilities, or at least use startsWith (which is a bit more appropriate than .includes here, since both possibilities start with flex).
You can also move the comment about the transition event name to the JS as well as the CSS.
Concise classList setting When you want to either add a class name, or remove a class name, based on a condition, you can condense an if(...) classList.add(...) else(...) classList.remove into a single classList.toggle with a second argument that indicates whether to add or remove the class. Your
if(panel.classList.contains('open')) {
  panel.classList.add('open-active');
} else {
  panel.classList.remove('open-active');
}

simplifies to
const { classList } = panel;
classList.toggle('open-active', classList.contains('open'));

Browser compatibility Though, some ancient browsers don't support the 2nd argument, so consider what sort of browsers you need to support. If you only want to support reasonably up-to-date browsers, it's just fine. Another thing to keep in mind is that NodeList.prototype.forEach was only introduced a few years ago, around 2016 or 2017 IIRC; like startsWith, it's newer than ES6, so either use a polyfill or use iterators and Babel instead, eg:
for (const panel of panels) {
  // do stuff with panel

(if you want to support IE, you should be using Babel anyway, to transpile your code to ES5 syntax)
Void return? panels.forEach(panel => panel.addEventListener returns the value of calling addEventListener to the caller of forEach. Since forEach doesn't look at what its callbacks return, this doesn't do anything. It's not a real problem, but some might consider the code to make a bit more sense if the forEach callback returned void (no return statement or implicit return at all). (Described in TypeScript's TSLint here)
Clickable panels Since the panels are clickable, maybe change from the default cursor to cursor: pointer to make it more obvious to the user that they're meant to be clicked?
Space between elements in selectors I'd change .panel>* to .panel > * - it makes it a bit easier to read when separate elements are separated by spaces.
Repetitive panels Rather than

.panel1 {
  background-image: url(https://source.unsplash.com/gYl-UtwNg_I/1500x1500);
}

.panel2 {
  background-image: url(https://source.unsplash.com/rFKUFzjPYiQ/1500x1500);
}

Consider using :nth-child instead, allowing you to remove the extra panel# classes entirely.
.panel:nth-child(1) {
  background-image: url(https://source.unsplash.com/gYl-UtwNg_I/1500x1500);
}

.panel:nth-child(2) {
  background-image: url(https://source.unsplash.com/rFKUFzjPYiQ/1500x1500);
}

const panels = document.querySelectorAll('.panel');

panels.forEach((panel) => {
  panel.addEventListener('click', () => {
    const isOpen = panel.classList.contains('open');
    panels.forEach(panel => panel.classList.remove('open'));
    if (!isOpen) {
      panel.classList.add('open');
    }
  });
});

panels.forEach((panel) => {
  panel.addEventListener('transitionend', e => {
    /* Safari transitionend event.propertyName === flex */
    /* Chrome + FF transitionend event.propertyName === flex-grow */
    if (e.propertyName === 'flex' || e.propertyName === 'flex-grow') {
      panels.forEach(panel => {
        const { classList } = panel;
        classList.toggle('open-active', classList.contains('open'));
      });
    }
  })
});
html {
  box-sizing: border-box;
  background: #ffc600;
  font-family: 'helvetica neue';
  font-size: 20px;
  font-weight: 200;
}

body {
  margin: 0;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

.panels {
  min-height: 100vh;
  overflow: hidden;
  display: flex;
}

.panel {
  background: #6B0F9C;
  box-shadow: inset 0 0 0 5px rgba(255, 255, 255, 0.1);
  color: white;
  text-align: center;
  align-items: center;
  /* Safari transitionend event.propertyName === flex */
  /* Chrome + FF transitionend event.propertyName === flex-grow */
  transition:
    font-size 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11),
    flex 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11), background 0.2s;
  font-size: 20px;
  background-size: cover;
  background-position: center;

  flex: 1;
  display: flex;
  justify-content: center;
  flex-direction: column;

  cursor: pointer;
}

.panel:nth-child(1) {
  background-image: url(https://source.unsplash.com/gYl-UtwNg_I/1500x1500);
}

.panel:nth-child(2) {
  background-image: url(https://source.unsplash.com/rFKUFzjPYiQ/1500x1500);
}

.panel:nth-child(3) {
  background-image: url(https://images.unsplash.com/photo-1465188162913-8fb5709d6d57?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&w=1500&h=1500&fit=crop&s=967e8a713a4e395260793fc8c802901d);
}

.panel:nth-child(4) {
  background-image: url(https://source.unsplash.com/ITjiVXcwVng/1500x1500);
}

.panel:nth-child(5) {
  background-image: url(https://source.unsplash.com/3MNzGlQM7qs/1500x1500);
}

/* Flex Children */
.panel > * {
  margin: 0;
  width: 100%;
  transition: transform 0.5s;
  flex: 1 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.panel *:first-child {
  transform: translateY(-100%);
}

.panel *:last-child {
  transform: translateY(100%);
}

.panel.open-active *:first-child,
.panel.open-active *:last-child {
  transform: translateY(0);
}

.panel p {
  text-transform: uppercase;
  font-family: 'Amatic SC', cursive;
  text-shadow: 0 0 4px rgba(0, 0, 0, 0.72), 0 0 14px rgba(0, 0, 0, 0.45);
  font-size: 2em;
}

.panel p:nth-child(2) {
  font-size: 4em;
}

.panel.open {
  font-size: 40px;
  flex: 5;
}
<link href="https://fonts.googleapis.com/css?family=Amatic+SC" rel="stylesheet" type="text/css">

Hey

Let's

Dance

Give

Take

Receive

Experience

It

Today

Give

All

You can

Life

In

Motion


I haven't quite understood what Babel is used for at all.

Babel is used for transpilation - the process of converting unsupported/future syntax into one that is supported at the moment. For instance, your destructuring assignment:

const { Router,
        Route,
        IndexRoute,
        Redirect,
        Link,
        IndexLink
      } = ReactRouter

This syntax is not supported by all browsers. Babel makes it possible by transpiling it into something supported by all browsers:

"use strict";

var _ReactRouter = ReactRouter;
var Router = _ReactRouter.Router;
var Route = _ReactRouter.Route;
var IndexRoute = _ReactRouter.IndexRoute;
var Redirect = _ReactRouter.Redirect;
var Link = _ReactRouter.Link;
var IndexLink = _ReactRouter.IndexLink;

In the same way, JSX is not natively supported by any browser. It just so happens that Babel also supports transpiling of JSX, making it the de facto tool to convert JSX to something the browser understands. This:

var Header = React.createClass({
    render: function () {
        return (

{this.props.text}

        );
    }
});

becomes this:

"use strict";

var Header = React.createClass({
    displayName: "Header",

    render: function render() {
        return React.createElement(
            "h1",
            { className: "title" },
            this.props.text
        );
    }
});

JSX is an optional component of React. You can write it like the transpiled version. However, it somehow just feels better to construct the DOM with markup-like syntax than with a bunch of function calls and objects.

As for your code...

'title': 'Main Page' + (this.props.title ? ' - ' + this.props.title : '')

Since you have Babel (and even without Babel), you can construct strings with template strings. The above code would be as easy as:

'title': `Main Page ${title}`

And while it is possible to put logic in the point of interpolation, I suggest moving it out for readability.

Now everything looks fine in your code except when the About and Home start to use Page. The problem with this is that when Home and About sufficiently diverge in structure, Page will hinder you from easily rewriting either. For instance, what if About needed Sidebar just beside the content body. Where will you put Sidebar? You can't put it in Page otherwise, it will appear on all components using Page. You can't also put it on About just like that because it will sit at the side of the entire page content, not beside the content.

When building componentized UIs, it's best to think of the entire thing as a bunch of very small things. Think "Home has a header, content, footer, sidebar. About has a header, content, footer, and no sidebar" and not "Home and About are pages, therefore I make a Page component". The advantage of the former is if I needed a sidebar for About, I can just pop it in there. If I want to remove the header from Home, I can just take it out.


Class project: user-editing page for a haiku website

About the HTML

It’s typically a good idea to add a meta-charset element, which gives the character encoding of the page (e.g., "UTF-8"). This should be the first element in the head element:

  <meta charset="utf-8" />

The body element can’t have a background attribute (it’s obsolete).

You should associate each label with its input. This can be done with the for attribute or by nesting the input inside the label. You can easily test if it works correctly: click the label, and the corresponding input should get the focus.

You have the closing tag
, but miss the opening tag -- however, the br element has no closing tag to begin with, so you probably want to use
 or
. But it doesn’t seem to be correct to use br in this context anyway. br must only be used for meaningful line-breaks. If you just need some vertical space, use CSS instead.

The list seems to be navigation. If that’s the case, you could use the nav element:


Aligning '=' on protocol buffers .proto files

I think the second version is much easier to maintain. If you have a new variable with a longer name (like var_two_reaalllllly_looooooooong_name) you don't have to modify three other lines too to keep it nice. The first version also could cause unnecessary patch/merge conflicts.

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

  Do not align right sides of assignment statements

  [...]

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


The best way to unwrap the optional in java

I think you want flatMap.
Those returns and braces are unnecessary noise.
I would consider not throwing but returning Optional<UserConfiguration> instead. Part of learning this style is realising that unwrapping is rarely necessary. At the call site, you can do something along the lines of update(user).ifPresentOrElse(...). [*]

public Optional<UserConfiguration> update(User user) {
    return user.getConfigurationId() // Optional<UUID>
        .flatMap(configurationId -> userConfigurationRepository.findById(configurationId)) // Optional<UserConfiguration>
        .map(userConfiguration -> updateUserConfiguration(userConfiguration)); // Optional<UserConfiguration>
}

However, if you insist on unwrapping, nothing's stopping you, technically.

public UserConfiguration update(User user) {
    return user.getConfigurationId() // Optional<UUID>
        .flatMap(configurationId -> userConfigurationRepository.findById(configurationId)) // Optional<UserConfiguration>
        .map(userConfiguration -> updateUserConfiguration(userConfiguration)) // Optional<UserConfiguration>
        .orElseThrow();
}

consider method references. Sometimes they make code more readable, other times they don't. But mostly yes.

public Optional<UserConfiguration> update(User user) {
    return user.getConfigurationId() // Optional<UUID>
        .flatMap(userConfigurationRepository::findById) // Optional<UserConfiguration>
        .map(this::updateUserConfiguration); // Optional<UserConfiguration>
}

[*] - Getting into this mindset would help you a lot when you will start working with other wrapper types that rely on the same abstractions, such as the standard library's Stream, RxJava, Spring 5-reactive stack / Project Reactor, or classes provided by the vavr library. Although possible, unwrapping some of these is considered a very bad idea, e.g. in case of RxJava and Reactor it is a blocking action which you want to avoid at all costs when writing reactive software. But even in the case of Optional, why not have the fact that the value might be missing captured by the type system rather that throwing Exceptions around that might be invisible up the stack until there is actually an issue.


Parse user data in to student and teacher details

A short review;

You can avoid process typeless and admin users by using an upfront .filter()
obj is a terrible name (it implies the parameter is just an Object instead of an Array, list would be better, something meaningful like userDetails the best
If you want to go for slightly less efficient code, you could replace the whole loop with 2 filters
Dont go for fat arrow syntax unless you are coding and inline function

I would go for something like this;
function createUsersInfo(userDetails){
  const cleanUserDetails = userDetails.filter(user => (user.type && user.group != 'admin'));
  return {
    studentDetails: cleanUserDetails.filter(user => user.type === 'student'),
    teacherDetails: cleanUserDetails.filter(user => user.type === 'teacher')
  };
}


Summing same index values in 2D arrays in javascript

The problem is, that you create an array of length n for each operation (in the input array), and then sum them by calling reduce on the result and after that you finally find the maximum of that resulting array. But you only need one initial array to sum up in, and you can find the maximum in the same operation - here in a rather verbose form:

function arrayManipulation(n, arr) {
  var res = [];
  var max = 0;

  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < n; j++) {
      if (i === 0) {
        res.push(j >= arr[i][0] - 1 && j <= arr[i][1] - 1 ? arr[i][2] : 0);
      }
      else {
        res[j] += j >= arr[i][0] && j <= arr[i][1] ? arr[i][2] : 0;
      }
      max = Math.max(max, res[j]);
    }
  }
  return max;
}

which can be narrowed down to this more succinct form:

function arrayManipulation(n, arr) {
  var res = [];
  var max = Number.MIN_VALUE;

  for (var i = 0; i < arr.length; i++) {
    for (var j = arr[i][0]; j <= arr[i][1]; j++) {
      res[j] = (res[j] || 0) + arr[i][2];
      max = Math.max(max, res[j]);
    }
  }
  return max;
}

Here is used, that it is only needed to loop through the intervals of the array that is actually manipulated by each operation in the input array. So for instance in the example operations, it is for the first operation only necessary to add 3 to the values in places from 1 to 5 inclusive.

Update

Building on the idea from the comment by weegee a modification of my solution above could handle that:

function arrayManipulation(n, arr) {
  arr = arr.sort((a, b) => a[0] < b[0] ? -1 : a[0] === b[0] ? 0 : 1);
  var max = Number.MIN_VALUE;

  for (var i = 0; i < arr.length; i++) {
    var sum = arr[i][2];
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[j][0] <= arr[i][1])
        sum += arr[j][2];
      else
        break;
    }
    max = Math.max(sum, max);
  }

  return max;
}

First the operations are sorted according to their start position (first element in the sub array), and then the operations are iterated and summed up as long as there is an overlap from operation to operation. Finally the current sum is compared to the existing maximum sum in max.


ASP.NET MVC 3 ModelBinder with string sanitizing

Can't comment on whether there is a better way or a better place in the framework to do this but some general remarks:

This doesn't make much sense: stringVal.IsNullOrEmpty() - should be string.IsNullOrEmpty(stringVal).
You are inconsistent: In the first method you check the type and use a direct cast vs in the second method you check the type and then use as - either you trust the type is correct or you don't. Also in SetProperty you try to not pass null or empty strings to the sanitizer helper while in BindModel you don't.
It would make sense if the helper method would support null and empty strings.

With the above the cleaned up code for SetProperty should probably look like this:

   protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
   {
        if (propertyDescriptor.PropertyType == typeof(string))
        {
            value = HtmlCleaner.SanitizeHtml((string)value);
        }

        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
   }


Rather than going down the OOP route, I would just split this out into a few functions:

import csv

from similarweb import ContentClient

CLIENT_KEY = 'some_key'
FILE_IN = 'similarweb/domains.csv'
FILE_OUT = 'similarweb/new_domains.csv'

def extract_data(path, client):
    """Extract the data from the specified path using the client."""
    lines = []
    with open(path) as read_file:
        for line in csv.reader(read_file):
            url = ', '.join(line)  # see note below
            lines.append(' '.join(
                (url, client.category(url)['Category'])
            ))
    return '\n'.join(lines)

def save_data(path, data):
    """Save the data to the specified path."""
    with open(path, 'w') as csv_write_file:
        csv_write_file.write(data)

if __name__ == '__main__':
    save_data(FILE_OUT, extract_data(FILE_IN, ContentClient(CLIENT_KEY)))

Per the documentation:

  Each row read from the csv file is returned as a list of strings. No automatic data type conversion is performed.

so there is no need to explicitly convert to strings.


Some small nitpicks:

Instead of i <= j you can stop before j by doing: i < j in the last two while loops. That way, you'll save one iteration per while. If you weren't constraint by: "For the purpose of this problem, we define empty string as valid palindrome" you might've remove that as well
Here: ('a'<=source[i]<='z') you can remove the redundant parentheses and also write it like: source[i].isalnum()
It seems like you always forget to put a space between operators: i+=1 should be i += 1.
Add docstrings to your function

Reviewed code:
def check_valid(source):
    """ Return True/False if a string is a palindrome """

    i, j, source = 0, len(source) - 1, source.lower()
    while i <= j:
        while i < j and not source[i].isalnum():
            i += 1
        while i < j and not source[j].isalnum():
            j -= 1
        if i <= j:
            if source[i] != source[j]:
                return False
            else:
                i += 1
                j -= 1
        if i > j:
            return True

if __name__ == "__main__":
    print check_valid('A man, a plan, a canal: Panama')  # return True
    print check_valid('race a car')  # return False


Parameter validation
Because GetErrorLog() is a public method you should assume that any given parameter can be wrong so a at least basic validation should take place.
E.g assume a user of that method is passing a startRowIndex == -1 then the line pagedErrorLog.ImportRow(errorLog.Rows[i]); would throw with an IndexOutOfBoundException.
A much better way would be to validate that parameter at the beginning like so
if (startRowIndex < 0)
{
    throw new ArgumentOutOfRangeException("startRowIndex");
}

I would split that big method into several smaller ones which are having only one responsibility like
private static void FillErrorLogTable(DataTable table, string[] filePaths)
{
    foreach (string filePath in filePaths)
    {
        DataRow row = table.NewRow();
        row["fileName"] = Path.GetFileName(filePath);
        row["filePath"] = filePath;
        table.Rows.Add(row);
    }
}

private static void FillPagedErrorLog(DataTable source, DataTable destination, int lowerBound, int upperBound)
{
    int sourceRowCount = source.Rows.Count;

    for (int i = lowerBound; i < upperBound; i++)
    {
        if (i >= sourceRowCount)
        {
            break;
        }
        destination.ImportRow(source.Rows[i]);
    }
}

How should Rows.Count at this condition if (pagedErrorLog.Rows.Count <= 0) ever be < 0? That won't ever happen.
Summing up the changes with only the mentioned validation which should be extended to validate the remaining parameters as well, would lead to
public static DataTable GetErrorLog(int startRowIndex, int maximumRows, string sortExpression, string logPath)
{
    if (startRowIndex < 0)
    {
        throw new ArgumentOutOfRangeException("startRowIndex");
    }

    if (string.IsNullOrEmpty(sortExpression))
    {
        sortExpression = "fileName DESC";
    }

    DataTable errorLog = GetErrorLogDataTable();

    string[] filePaths = Directory.GetFiles(logPath);

    FillErrorLogTable(errorLog, filePaths);

    DataView dataView = new DataView(errorLog);
    dataView.Sort = sortExpression;
    errorLog = dataView.ToTable();
    DataTable pagedErrorLog = errorLog.Clone();

    FillPagedErrorLog(errorLog, pagedErrorLog, startRowIndex, startRowIndex + maximumRows);

    if (pagedErrorLog.Rows.Count == 0)
    {
        return errorLog;
    }
    else
    {
        return pagedErrorLog;
    }
}

Other than what I had mentioned, your code looks good, you are following the naming conventions and you have named your things well (except of the GetErrorLogDataTable() method which I would name Create..).


Decimal to Roman numeral conversion algorithm

This code has a bug as 14 and 16 give the same output, while the Roman representation for them should surely be different:

14 -> XVI
16 -> XVI


Ball Entity for a Entity/Component/System Soccer Game

Looking at the class from the outside, this is how it gets created:

public BallEntity(TextureAtlas atlas, RubeSceneHelper rubeSceneHelper, Camera camera)

How the class actually gets created requires jumping between a sequence of private constructors... that isn't needed at all.

public BallEntity(TextureAtlas atlas, RubeSceneHelper rubeSceneHelper, Camera camera) {
    this.camera = camera;
    this.ballFixture = rubeSceneHelper.getFixture(ballBody, "ball");

    Sprite sprite = new Sprite(atlas.findRegion(BALL))
    this.ball = ScaledSprite.createUsingHeight(sprite, SCALE_FACTOR).getSprite();
    this.ballBody = rubeSceneHelper.getBody("ball");
}

Here I've introduced an intermediate Sprite object variable, only because all those chained calls wouldn't look right.

Isn't it easier to follow? :)

This seems pretty verbose:

public Array<Component> getComponents() {
    Array<Component> components = new Array<Component>();
    components.add(PositionComponent.newInstance());
    components.add(CameraFollowerComponent.newInstance(camera));
    components.add(SpriteComponent.newInstance(ball));
    components.add(BodyComponent.newInstance(ballBody));
    components.add(BallContextComponent.newInstance());
    return components;
}

I'm more into C#, but I'm pretty sure (make it 51%) you could do this instead (assuming Array<T> is intended to work like a T[]):

public Component[] getComponents() {
    return new Component[] {
        PositionComponent.newInstance(),
        CameraFollowerComponent.newInstance(camera),
        SpriteComponent.newInstance(ball),
        BodyComponent.newInstance(ballBody),
        BallContextComponent.newInstance()
    };
}


Linked list abstraction using python arrays

asserts are not run if you use Python's optimized bytecode mode. And while nobody uses the -O switch, because the benefits are really meager, it still is not a good practice to you assert to validate user input. It is typically used to document invariants or assumptions, which roughly translates to it validating input that other parts of your code have generated, not users. Instead, you should raise an adequate exception, e.g.:

def first(s):
    """Return a first element of a linked list s"""
    if not is_link(s):
        raise TypeError("first only applies to linked lists.")
    if s == empty:
        raise IndexError("empty linked list has no first element.")
    return s[0]

Your is_link function, which is called by most of your other functions, has to scan the full list to validate it. That means that, especially with functions like count, which already need to scan the whole list, performance is going to end up being \$O(n^2)\$. That is not a good thing! You should probably go for a lazier is_link, that defers erroring until possible non-compliant items are actually used, e.g.:

def is_link(s)
    return s == empty or (isinstance(s, list) and len(s) == 2 and
                          (s[1] == empty or isinstance(s[1], list)))

You can simplify your count code a lot, by letting the recursion stack keep track of the number of items, rather than doing it yourself explicitly:

def count(s, value):
    if isempty(s):
        return 0
    return count(rest(s), value) + (1 if first(s) == value else 0)

While obviously doable, this reusing a list to make a linked list doesn't seem like a very good choice. It is very typical to use a dict of lists to represent a graph, rather than creating an explicit new class. And heaps also fit very well into a bare list with some helper functions, that's e.g. how the heapq module is implemented. But in your case, while it would be ok for a quick and dirty implementation where you directly accessed s[0] and s[1], if you are going to go through the trouble of writing all those helper functions, it is infinitely clearer to actually create a new class that embodies the abstraction.


Why are you storing them as lowercase words only to call toUpperCase on them? Store them in the form you intend to use them and save yourself a function call on each word. It's also more understandable to have the strings stored the same way
they'll be printed.


Create Excel file multiple times with different names

Short answer

Yes, there are shorter ways to do. Here is how I would save a workbook into a file:

private static File createFile(XSSFWorkbook wb, String folderTo) throws FileNotFoundException, IOException {
    LOG.debug("Create File");
    String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    File f = Paths.get(folderTo, "Bloomberg Rechnung-" + timestamp + ".xlsx").toFile();
    try (FileOutputStream fos = new FileOutputStream(f)) {
        wb.write(fos);
    }
    return f;
}

Note that I'm not totally comfortable with this method because it has 2 responsibilities: creating an excel file and filling it.

Long answer

Now you might wonder how I ended with the code above, so let's begin...

Filename requirement

You stated

  Note that if the file is not existing it should be created without counter

This kind of requirement is the kind of which clutters the code with at least one if/else and is in general irrelevant. If you are okay to have a number in the filename (going from 1 to n), then why not having 0 ?

After all, the requirement behind that is that no filename should be erased by another with the same name. So the real problem to resolve here is how to make sure this method won't create 2 files with the same name ?

Since you stated

  I want to create a new excel file if my program is run

I assumed using a timestamp should be enough (guaranteeing you one unique filename per second).

Here is createFile() after this refactor:

private File createFile() throws FileNotFoundException, IOException {
    LOG.debug("Create File");
    DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
    Date d = new Date(System.currentTimeMillis());
    File f = new File("C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + df.format(d) + ".xlsx");
    try (FileOutputStream outputStream = new FileOutputStream(
            "C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + df.format(d) + ".xlsx")) {
        wb.write(outputStream);
        outputStream.close();
        wb.close();
    } catch (Exception e) {
        LOG.debug(e.toString());
    }
    return f;
}

Using LocalDateTime

Since Java 8, there's a new API to use when you are using dates. I refactored the code to use this new API instead of the old one.

private File createFile() {
    LOG.debug("Create File");
    String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    File f = new File("C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + timestamp + ".xlsx");
    try (FileOutputStream outputStream = new FileOutputStream(
            "C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + timestamp + ".xlsx")) {
        wb.write(outputStream);
        outputStream.close();
        wb.close();
    } catch (Exception e) {
        LOG.debug(e.toString());
    }
    return f;
}

Removing duplication

You are creating the File twice. Instead just reuse the existing you already have.

private File createFile() {
    LOG.debug("Create File");
    String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    File f = new File("C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + timestamp + ".xlsx");
    try (FileOutputStream outputStream = new FileOutputStream(f)) {
        wb.write(outputStream);
        outputStream.close();
        wb.close();
    } catch (Exception e) {
        LOG.debug(e.toString());
    }
    return f;
}

Removing smells

In the current code, there are (to my sense) three code smells:

Exceptions are (badly) swallowed
wb is closed but not opened in this method. This could be a major flaw because it induces a nasty side-effect. It is a general idiom that the one who opens a resource is the one who closes it.
outputStream is declared in the try, no need to close it manually ! (it will be done automatically)

Since in the original method, you declared throws FileNotFoundException, IOException, I assumed it's ok to remove the try/catch.

private File createFile() throws FileNotFoundException, IOException {
    LOG.debug("Create File");
    String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    File f = new File("C:\\Users\\" + filepath + "\\Desktop\\Bloomberg Rechnung-" + timestamp + ".xlsx");
    try (FileOutputStream outputStream = new FileOutputStream(f)) {
        wb.write(outputStream);
    }
    return f;
}

Going further

So now, I could have stopped here. But something is still bothering me:

The hardcoded string for the path
The fact that you directly depends on wb, making the method hard to test

The method could event be marked static so anyone reading this code knows that this method doesn't have a side-effect on an object attribute.

private static File createFile(XSSFWorkbook wb, String folderTo) throws FileNotFoundException, IOException {
    LOG.debug("Create File");
    String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    File f = Paths.get(folderTo, "Bloomberg Rechnung-" + timestamp + ".xlsx").toFile();
    try (FileOutputStream outputStream = new FileOutputStream(f)) {
        wb.write(outputStream);
    }
    return f;
}

Going even further

As I said in the first chapter, the method has actually 2 responsibilities. I would split those in something like that:

private static File createFile(String folderTo) {
    String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    return Paths.get(folderTo, "Bloomberg Rechnung-" + timestamp + ".xlsx").toFile();
}

private static void saveWorkbook(XSSFWorkbook wb, File f) throws FileNotFoundException, IOException {
    try (FileOutputStream outputStream = new FileOutputStream(f)) {
        wb.write(outputStream);
    }
}

I also voluntarily removed the log statement. I'm not sure it really add any value when only logging "Create File". Either add more information such as where the file was created, with which name, etc. or get rid of it.

In the end you could use these methods like this:

saveWorkbook(wb, createFile("C:\Users\Desktop"));

or if you need to store a reference on the File:

File f = createFile("C:\Users\Desktop");
saveWorkbook(wb, f);

Update

Following your comment, this is how I would implement the file creation based only on a date + a counter (if needed)

private static File createFile(String folderTo) {
    String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    return createUniqueFileForDate(folderTo, date);
}

private static File createUniqueFileForDate(String folderTo, String date) {
    String index = "";
    File f = null;
    for (int i = 1;; i++) {
        f = Paths.get(folderTo, "Bloomberg Rechnung-" + date + index + ".xlsx").toFile();
        if (!f.exists()) {
            break;
        }
        index = " (" + i + ")";
    }
    return f;
}


Custom function to scroll spy on the jScrollPane plugin

I'd like to address a couple of style concerns over simplification.

Purely for debugging if you have function expressions then name them.

eg.
    setInterval(function(){

could become

setInterval(function _scrollDetectionInterval(){

When debugging the call stack will now show you at a glance what this function is (especially helpful if you have multiple).
you have define variables outside of the scope you are using them.

var $scrollSpy   = $('.jspPane'),           //the element to spy
height       = $scrollSpy.height(),     //its height
stepsTrigger = parseInt(height/total),  //trigger at "every" this distance
currentPos   = 0;                       //current position (active image)

This doesn't make sense unless you aren't going to change them again or you will be using them else where. Assuming this is all the code here I would at least put the currentPos inside the interval function scope.
you have a data-index="1" attribute on your elements. Is this actually needed? jQuery has an index you can use in the .each() method. just change your function to

$targets.each(function(index){

unless I am missing something it should work. You can also then change the line

$tgt = $('img[data-index="'+id+'"]');

to

$tgt = $targets.eq(Math.max(0, img - 1));

there is a lot going on in this line. $targets.eq( uses the 0-based index of the element in the array. Math.max( ensures it will never be less than 0.

The code will only work if there is one image wrapper on the page. If you are looking to extend this to multiple here is how i would change it:

$('.someImageWrapClass')
  .each(function _eachWrapper()
  {
    var $parentWrapper = $(this);

    //target all images and count them
    var $targets = $parentWrapper.find('> img'),
        total    = $targets.size();

    //for each found, set the CSS z-index
    $targets.each(function _eachImage(index){
        //revert order
        $(this).css({
            'z-index': total - index
        });
    });

    var $scrollSpy   = $('.jspPane'),           //the element to spy
        height       = $scrollSpy.height(),     //its height
        stepsTrigger = parseInt(height/total);  //trigger at "every" this distance

    setInterval(function _scrollDetection()
    {
        //current position (active image)
        //ascertain current position (ensure positive number)
        var currentPos = Math.abs(parseInt($scrollSpy.css('top'), 10));

        //ascertain the target image
        var img  = Math.round(currentPos/stepsTrigger)
            $tgt = $targets.eq(Math.max(0, img -1));

        //if different from the already active
        if (!$tgt.hasClass('active'))
        {
            $targets.removeClass('active').hide();
            $tgt.fadeIn().addClass('active');
        }

    }, 100);
  });


Make parent a list of ancestors as a path to the item:

new Item  { Name = "TestGranChild4", Path = {"Test", "TestChild2"} },

var menuItem = items.Where(x => x.Name == name);
menuItem.FirstOrDefault().Path.ForEach(a => app.tap(x=>x.Marked(a)));
app.Tap(x => x.Marked(menuItem.FirstOrDefault().Name));


Finding out the indices of common elements in two array lists having duplicate elements

Firstly, try to make sure that code you post here compiles. Now you have missing semicolons on the lines

List<String> distinct1 = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "2")
List<String> distinct2 = Arrays.asList["3", "3", "2", "4", "7"]

and also the last of these two lines has [...] instead of (...).

It was also a bit difficult to actually figure out what your code was supposed to do, but I think I understand it now.

It seems you want to create a list of pairs of some sort. So instead of ending with a List<List<Integer>>, you can create a Pair class

public final class Pair<S, T> {
  private final S left;
  private final T right;

  public Pair(S left, T right) {
    this.left = left;
    this.right = right;
  }

  public S left() {
    return left;
  }

  public T right() {
    return right;
  }

  // equals and hashCode
  ...
}

and have a List<Pair<Integer, Integer>> instead.

Then you can create a method which given two Lists creates the cartesian product

public List<Pair<S, T>> cartesianProduct(List<S> firstList, List<T> secondList) {
  return firstList.stream()
    .flatMap(x -> secondList.stream().map(y -> new Pair<>(x, y)))
    .collect(Collectors.toList());
}

During the construction of your cartesian list, you collect your intermediate results into a Map. This step is not needed as you can now immediately convert to a list of pairs. Also, it is usually not a good idea to have a List as keys of a Map as the List is mutable. Map expects the hash code of the keys to not change which is a possibility when using Lists as keys.

Removing the Map step in the process we get

List<Pair<Integer, Integer>> listWithoutDuplicates = result1.entrySet().stream()
        .filter(x -> result2.containsKey(x.getKey()))
        .flatMap(x -> cartesianProducts(result2.get(x.getKey()), x.getValue()).stream())
        .distinct()
        .collect(Collectors.toList());


VBA function that returns color RBG code of a referenced cell

I don't think you need to activate the cell, or use the selection, just inspect the range directly.

I've also made the function volatile so it will update when you calculate.

But, for Code Review purposes, you're only getting the interior color, but the cell might not actually appear in that color, for example:

If there is conditional formatting on the cell, the interior color will not be accurate.
If there is a style on the cell, and the style applies a fill, then the interior color will not be accurate.
If the cell's interior has a 2-color fill, then then the interior color doesn't necessarily reflect either color of the 2-color fill.

Also, you're using some nice concise bit-shifting, and you'll have noticed that VBA doesn't have any shifting operators, but you might consider using some bit-shifting functions to make the code slightly clearer (and you can re-use them everywhere else that you need to shift bits.

And finally, unless you're certain that reference will always be a single celled reference, the color will default to 0/0/0 if there are more than 2 cells in the range and they have different colors.

 Public Function ColorCode(Reference As Range) As Variant
   Application.Volatile
' Function to return RGB code of a single cell when referenced

Dim RGBColor As Long

Dim Red As Long, Green As Long, Blue As Long

RGBColor = Reference.Interior.Color

    Red = &HFF& And RGBColor

    Green = (&HFF00& And RGBColor) \ 256

    Blue = (&HFF0000 And RGBColor) \ 65536

ColorCode = Red & "/" & Green & "/" & Blue

End Function


Improve randomization function (from 1 to 2)

Randomness

This answer suggests that Random(2) would be okay for most uses. If you want more randomness, you could for example use an implementation of Mersenne Twister. This page lists a few options for Pascal/Delphi, for example this implementation.

Alternating values

Now that I know what you are looking for, I would write the code like this:

// If Value is divisible by 2 then return 1, otherwise return 2
procedure AlternateValue(Value) : ShortInt;
begin
    if Value mod 2 = 0 then Result := 1 else Result := 2
end;

// Your code
randomize();
RandomTurn := random(2)+1;
NumberOfMoves := RandomTurn

while (1) do
begin
    PersonTurn(AlternateValue(NumberOfMoves))
    NumberOfMoves := NumberOfMoves + 1;
end;

You should swap the two lines in the while loop if you want to start with the same number as Random gives. From what I gather, it should not matter much, however.

(I have never written any Pascal or Delphi before, so the code and/or syntax may not be perfect or correct.)


Handling with the 'error' parameter inside a callback function in node.js

If all of your functions adhere to this pattern you can wrap them in,
you guessed it, another function:

defaultError = function(handler) {
    return function(error) {
        if (error) {
            res.render('error', {
                error: error
            });
        }
        else {
            return handler.apply(null, Array.prototype.slice.call(arguments, 1));
        }
    };
};

This uses the
special arguments object,
which has to be converted to an array before you can slice off the error object, and apply on the passed-in function.

Now the previously repetitive code gets a bit shorter:

exports.update = function(req, res, next) {
    MyModel.findById(req.params.id, defaultError(function(event) {
        event['active'] === false ? event['active'] = true : event['active'] = false;

        event.update({
            'active': event['active']
        }, defaultError(function() {
            res.end('Success!');
        }));
    }));
};

Now obviously the defaultError can also customize the rendered error,
so as long as error is in a fixed position in the call, this pattern
can be used to build a small control flow abstraction.

The cost here is a possible speed penalty due to the manipulation of arguments and the apply call.

If you had promises a generic error handler would be equally
viable, but it looks like that is not an option.


Spring Boot should we always use interfaces even with one implementation

The answer to this question may vary depending on the opinions regarding the various so-called "good practices".
If we take into account the dependency inversion principle (In SOLID principles), then we should always aim for our classes to depend on abstractions and not on implementations.
However we could also take into account the "KISS" principle (Keep it stupidly simple) and in this way I could tell you that if your application is not very large or complex, then do not use an interface.
Answering your question: "what is better to use interface with one implementation and inject interface or just create a class without interface and inject class?"
I recommend using an interface even if it has only one implementation, so in the future if the implementation changes, the class that depends on said interface will not be affected by said change, unless the interface signature changes as well.


Converting javax.security.cert.X509Certificate[] to java.security.cert.X509Certificate[] keeping order

private X509Certificate[] x509Certificates;

private void setX509Certificates(javax.security.cert.X509Certificate[] certs) throws CertificateException {
    CertificateFactory certificateFactory = certificateFactory = CertificateFactory.getInstance("X.509");
    List<X509Certificate> x509List = new ArrayList<>();

    for (javax.security.cert.X509Certificate cert : certs) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(cert.getEncoded());
            X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(bais);
            if (x509Certificate != null) {
                x509List.add(x509Certificate);
            }
        } catch (CertificateEncodingException e) {
            e.printStackTrace(System.err);
        }
    }
    this.x509Certificates = x509List.toArray(new X509Certificate[]{});
}

Linked List which you have used for temporary purpose. This could be achieved in a single for loop. Since there will not be any duplicate certificate it is safe to use ArrayList for collecting the certifcates.

I am not sure your exception handling strategy. So I am throwing the CertificateException you are free to change it based on your exception strategy.


Outputting results from a conditional row count across multiple tables

MySQL

Your query looks fine, I'm not sure it could be further optimized of itself. What I would suggest though is to plug it into a stored procedure, and there are a few good reasons to do this.

Cleaner PHP script by only having your behavioral code in your script while just calling the procedure from there.
Easier to modify, e.g., if you found yourself using this SQL script in multiple PHP scripts and you had to make a change to it, you would have to change it everywhere, as opposed to just changing the stored procedure once.
Better SQL optimization. The way you have it now, every time you run the PHP script it sends an ad-hoc request to the SQL engine and it has to figure out the optimization each time. By storing the SQL script in the RDBMS the engine will optimize it ahead of time, so it will respond quicker each time.

Create procedure

You can run this just once:

DELIMITER |
CREATE PROCEDURE wcx_objects() AS
BEGIN

SELECT SUM(inactive_count) AS inactive_count
FROM (
    SELECT COUNT(article_active) AS inactive_count
        FROM wcx_articles WHERE article_active = 0
    UNION ALL
    SELECT COUNT(video_active)
        FROM wcx_videos WHERE video_active = 0
    UNION ALL
    SELECT COUNT(app_active)
        FROM wcx_apps WHERE app_active = 0
    UNION ALL
    SELECT COUNT(link_active)
        FROM wcx_links WHERE link_active = 0
) AS wcx_objects;

END|
DELIMITER ;

Call Procedure in PHP

Then from PHP all you need to do to get your result set is write this:

$query = "CALL wcx_objects();"