get_id2.php is expected to produce a json string, so make sure that it always does that.
Don't use die() because then you are not providing an informative json response.
Don't be too informative when the expected id is missing or invald -- be clear about the problem, but also vague.
Validate the incoming id using isset() then ctype_digit(), if it passes those checks, then your script may advance to the querying step.
I prefer object-oriented mysqli syntax since it is less verbose, but you can keep using procedural if you like.
Calling confirm_db_connect($result); after executing the query doesn't make any sense.  If you are going to bother checking the connection, you should be doing that before trying to execute the query.
You only need four columns in your result set, so I advise that you list those columns explicitly in your SELECT clause so that you don't ask for more than you need.
I don't see any value in declaring single use variables from the result set.

$id             = $photo['id'];
$caption        = $photo['caption'];
$filename       = $photo['filename'];
$description2   = $photo['description2'];

Just use the $photo[...] variables directly when sanitizing/preparing the data.
Those single character sanitizing/preparing functions are a bad idea.  Developers that need to read your script in the future (including yourself) will have no chances of instantly understanding what these calls do.  This will require manually jumping to another file to look up what action is being executed.  Use more meaningful function names and don't try to save characters at the cost of losing comprehensibility.  In fact, it only hurts your code to write a custom function that replaces a single native function call -- just use the native call and your script and developers will be happier.
As of PHP7.4, strip_tags() allows an alternative declaration of allowed tags.  So your second parameter could look like this:

['div', 'img', 'h1', 'h2', 'p', 'br', 'strong', 'em', 'ul', 'li', 'table', 'td', 'tr', 'th', 'tbody']

Admittedly, when using proper spacing between values, the expression ends up being longer; but it can be sensibly broken into multiple lines to reduce overall width.
I prefer to write the negative response before the positive responses in my projects for consistency.  This just means moving the No product. outcome earlier in the code.
It is not necessary to manually free the result nor close the db connection when this script resolves; php will do this clean up for you automatically.
write json_encode() just once and pass a variable to it -- for the sake of DRY-ness.

My untested suggestions:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");

if (!isset($_GET['id']) || !ctype_digit($_GET['id'])) {
    $response = ['message' => 'Missing/Invalid identifier provided'];
} else {
    include_once('config_setup.php');
    $sql = "SELECT id, caption, filename, description2 FROM photographs WHERE id = " . $_GET['id'];
    $result = mysqli_query($db, $sql);
    if (!$result) {
        $response = ['message' => 'Please contact the dev team.'];
    } else {
        $photo = mysqli_fetch_assoc($result);
        if (!$photo) {
            $response = ['message' => 'No product.'];
        } else {
            $url = 'http://localhost/photo_gallery/public/files/images/';
            $allowed = '

';
            $response = [
                'id'           => urlencode(htmlspecialchars($photo['id'])),
                'caption'      => htmlspecialchars($photo['caption']),
                'filename'     => $url . htmlspecialchars($photo['filename']),
                'description2' => strip_tags($photo['description2'], $allowed),
            ];
        }
    }
}

http_response_code(isset($response['message']) ? 404 : 200);
echo json_encode($response);

Granted, some developers will not wish to write three nested condition blocks and might prefer to write early json exits.  I am choosing not to do this because my script is not excessively wide and it makes only one call of http_response_code() and json_encode() at the end.  "To each their own."  Restructure the snippet however you like.

An alternative structure with multiple returns to avoid arrowhead code:

function getResponse() {
    if (!isset($_GET['id']) || !ctype_digit($_GET['id'])) {
        return ['message' => 'Missing/Invalid identifier provided'];
    }
    include_once('config_setup.php');
    $sql = "SELECT id, caption, filename, description2 FROM photographs WHERE id = " . $_GET['id'];
    $result = mysqli_query($db, $sql);
    if (!$result) {
        return ['message' => 'Please contact the dev team.'];
    }
    $photo = mysqli_fetch_assoc($result);
    if (!$photo) {
        return ['message' => 'No product.'];
    }
    $url = 'http://localhost/photo_gallery/public/files/images/';
    $allowed = '

';
    return [
        'id'           => urlencode(htmlspecialchars($photo['id'])),
        'caption'      => htmlspecialchars($photo['caption']),
        'filename'     => $url . htmlspecialchars($photo['filename']),
        'description2' => strip_tags($photo['description2'], $allowed),
    ];
}

$response = getResponse();
http_response_code(isset($response['message']) ? 404 : 200);
echo json_encode($response);


Looking for advice - Dependency Injection over Service Locator in Mef

Service locator is an anti-pattern because it tends to create implicit dependencies which are not easy to see and usually cause grieve when trying to write unit tests. Especially your implementation which references what seems like a singleton instance which can cause additional problems (i.e. you need to take care to reset it between tests).
Avoid it.

I can't say much about the MEF injection but it seems roundabout having to write all that code. It also creates an implicit dependency which will probably cause grieve when unit testing your class and makes it directly dependent on MEF while there is no need for it.
Avoid it.

Clean and simple. Explicit dependency, easy to unit test and injection can be easily manged by any IoC container of your choice (Unity, Ninject, Windsor, etc.).
The way to go.


Separate combined words in a sentence and convert them into Pig Latin

This is in addition to what @thecoder16 already said.

WordSeparator

Methods should be named using verbs instead of nouns.
They usually take some action on the input,
for example this method separates the words that were stuck together.
So separateWords would be better.

Also, this part is not great:

    // Checks for upper case characters
    if(Character.isUpperCase(str.charAt(i)))
    {
        //Inserting space
        str.insert(i, ' ');
        char ch = Character.toLowerCase(str.charAt(i+1));
        str.setCharAt((i+1), ch);
    }

Objections:

The str.charAt(i) and str.charAt(i+1) refer to the same character. This is repetitive, and can be prone to errors, as you have to remember to use i+1 the second time because of the inserted space
The comments only state the obvious. Unnecessary comments are like noise, and a waste of time to read. Let the code speak for itself.

It would be better this way:

    char ch = str.charAt(i);
    if (Character.isUpperCase(ch)) {
        str.insert(i, ' ');
        str.setCharAt(i + 1, Character.toLowerCase(ch));
    }

PigLatin

The biggest issue here is the latin = latin.concat(...) call for two reasons:

String concatenation is inefficient. You should use a StringBuilder like you did in your other method.
Reusing input parameters is not a good practice, as it can be confusing and error prone. It would be better to name local variables differently.

Issues similar to WordSeparator:

The method is poorly named. Perhaps toPigLatin would be better.
The comments are unnecessary noise

Other smaller issues:

Instead of printing output, it would be better to return the result
The String[] arr is unused, so it would be better to remove it
The counting for loop can be converted to an enhanced loop, for example: for (String str : tokens) { ... }
The input parameter revisedSentence carries information that's unnecessary for the functioning of this method. Just sentence would be enough.


Performance

It's the dedupe implementation that drags the performance of your solution down.
It's because Array.prototype.includes() does a linear search,
so your implementation becomes \$O(n^2)\$.
If you rewrite this function to be \$O(n)\$,
the solution will pass all tests.

Using arrays

The dedupe function takes as parameters an array and its size.
The size parameter is unnecessary and potentially confusing,
because you can always access that with .length.

Binary search

A common practice when implementing binary search over a list is to return the index of a value if it is found,
otherwise return a negative value from which the insertion point can be computed using the formula -1 -ret.
It would be cleaner to implement binarySearch(arr, value, low, high) in
a way to follow this common contract,
and another rank function that would use the result of binarySearch to compute the correct rank.

Also, the implementation is a bit complicated.
Simpler techniques exist, and the cache is not needed either.
Consider this, for example:

function binarySearch(arr, value, lowIndex, highIndex) {
    if (lowIndex > highIndex) {
        return -(lowIndex + 1);
    }

    let midIndex = lowIndex + Math.trunc((highIndex - lowIndex) / 2);
    if (value == arr[midIndex]) {
        return midIndex;
    }
    if (value > arr[midIndex]) {
        return binarySearch(arr, value, lowIndex, midIndex - 1);
    }
    return binarySearch(arr, value, midIndex + 1, highIndex);
}


Check if integer is a palindrome in base 10

Too many comments, and they do not serve any purpose.

Use all necessary #includes. atoi requires #include <stdlib.h>.

Separate IO from the business logic. Constructing the reversed number definitely belongs to a function.

There is no need to convert the number into a textual representation. Consider building the reversed number as you compute the digits of the original:
int reverse (int number)
{
    int reversed = 0;
    while (number != 0) {
        int last_digit = number % 10;
        number /= 10;
        reversed *= 10;
        reversed += last_digit;
    }
    return reversed;
}

As a side effect, many variables (quotient, remainder, number_update, i) disappear.


Collaboration of the two functions through multithreading

Your consumer thread locks out the producer for extended periods of time.

void ConsumeData()
 {
   while (true)
   {
    std::unique_lock<std::mutex> uniqueLock(mutex);
    conditionVariable.wait(uniqueLock, [] {return !queue.empty(); });
    while (!queue.empty())
    {
        // DO WORK
        queue.pop();
    }
    uniqueLock.unlock();
   }
}

I would rather see the consumer grab a single item from the queue then release the queue (so the producer can continue to add work while the consumer is processing a single job.

void ConsumeData()
{
    while (true)
    {
      {
        std::unique_lock<std::mutex> uniqueLock(mutex);
        conditionVariable.wait(uniqueLock, [] {return !queue.empty(); });

        // Note: Don't need to test queue.empty()
        //       If it is empty then the thread is re-queued on the
        //       condition variable it is only released when the test
        //       above is true.
        work = queue.front();
        queue.pop();
      }
      // You have the work item so you don't need the lock.
      // So out here you work on the item you just retrieved from
      // queue. When done you loop back around to get more work.

      // DO WORK
    }
  }
}

Your producer adds lots of items to the queue. But only signals once. You should signal once for every item added to the queue.

  for (std::uint8_t count = 0; (count < maxWordCount) || (count != '\0'); ++count) {
    queue.push(word);
    conditionVariable.notify_one();
  }

As a side note:

An indent of 2 is a bit on the low side (acceptable by some). But in my opinion makes the code too cluttered.


Grid Overlay For Browser Using HTML5 Canvas

You can use cssText to update the style properties all in one go.

This avoids the element being repainted after every style prop change.

i.e. var myStyleString = 'right: 30px'; // etc

getById('gridControls').style.cssText = myStyleString;

This way you also don't need the controls var.

you can read more about style here.


Safely & portably read a value into a predefined integral type of varying size like mode_t

An alternative would be to store the value, then test whether any truncation occured:

m = u;
if (m != u) goto error_too_big;

I think some of the single-character variables (e, u, c, etc.) could be given better names.  The next person to modify the code (which could be Future You) will pick it up more quickly if it has meaningful variable names.


Matching a randomly made colour using sliders

Here are the improvements to your program that I would suggest:

Performance issue

Whenever the user of your program presses one of the colors sliders, show_values() function is invoked and it create a new tk.Label() instance in addition to the formerly existing ones. This means your program consumes unnecessary memory that can be harmful when the user scrolls down and up, several times, the color sliders. This is clearly a performance issue that can incapacitate your program.

Solution to the performance issue

To resolve the performance issue, you can create a tk.Frame() instance to be the parent widget of the tk.Label() instances you create. This will allow you to clear the tk.Frame() parent widget before a new tk.Label() widget is created.

In my solution below, the color surface which results from the user's actions is wrapped by a tk.Frame() instance:

def create_estimated_color_area(self):
    self.frame = tk.Frame(self.master)
    self.frame.grid(row=0, column=1)

The callback function inherent to the tk.Scale() widgets clears the self.frame widget above:

def estimate_color(self, event):
    # Clear the frame before drawing a new label on it
    self.clear_widget(self.frame)
    # ...
    self.calculated_color_image = tk.PhotoImage(width=64, height=64)
    self.colorize_area(self.calculated_color_image, (r, g, b))
    self.calculated_color_area = tk.Label(self.frame, image=self.calculated_color_image)
    self.calculated_color_area.pack()

The clear_widget() function loops over the self.frame widget to look for its children and removes them away totally:

def clear_widget(self, widget):
    for child in widget.winfo_children():
        child.destroy()

Scalability issues

Your program, as designed, is not scalable. This is because you designed it using a mixture of sequential and functional approaches. But you are dealing with a GUI, and user graphical interfaces were the factor that soared the thrive of object-oriented design. Whether there are some philosophical dirty discussions about it, you should adopt an OOP approach to design your GUI: at least this is valid when it comes to Python and Tkinter. This will remedy to the scalability problem your program is suffering from.

Given this fact, my solution below consists in redesigning your program in an OOP approach. Of course, I end up by more code than you provided by now. But the difference is that my solution is open for adding any other future functionalities in the future, if you want to improve and scale your program. It is also a more disciplined and cleaner code. To understand my design below, you can refer to Tkinter best practices article.

Confusing names

I do not want to be rude, but honestly most of the variable and function names you used are confusing. This is the case, for example, of the pixel() function which does not redefine the notion of a pixel or anything like that. You rather used it to colorize a square area. In addition to this, as in all other programming languages, your function name should be a verb, not a noun. Why? Because a function does something. A function is a doer.

I could write a long text about the naming conventions regarding almost all your variables and functions names: no one, for instance, could find it easy to guess and understand without an additional effort, what are these variables supposed to do: w1, w2, and w3. I renamed everything accordingly in my solution (not to perfection, but to better, and surely you can choose better names than I provided below)

pixel() with one parameter less

The pos parameter in pixel() function is useless because, you always called it with the same starting position (0, 0). So simply get rid of it. Advantage? Less parameters in a function leads to simpler unit testing and cleaner code since parameters belong to a level of abstraction different than that of functions.

Solution

Taking in consideration the former remarks, but also other ones I did not mention such as the right way to import Tkinter, below are the new clothes to your program.

Note that the execution of the below program outputs the same result as yours:

As I said, I have more code below, but I provide you clan code which is scalable: which thing means, as your program becomes larger (in the future) you will write less code and in an easier way. Please, feel free if there is something you do not understand:

import tkinter as tk
import random

class ColorFinder(tk.Frame):

   def __init__(self, master):
       self.master = master
       tk.Frame.__init__(self, self.master)
       self.configure_gui()
       self.create_widgets()

   def configure_gui(self):
       self.master.title('Coulor Finder')

   def create_widgets(self):
       self.create_color_sliders()
       self.create_color_areas()

   def create_color_sliders(self):
       self.red_color_slider = tk.Scale(self.master, from_=0, to=255)
       self.green_color_slider = tk.Scale(self.master, from_=0, to=255)
       self.blue_color_slider = tk.Scale(self.master, from_=0, to=255)
       self.position_color_sliders()
       self.configure_color_sliders()

   def position_color_sliders(self):
       self.red_color_slider.grid(row=0, column=0)
       self.green_color_slider.grid(row=1, column=0)
       self.blue_color_slider.grid(row=2, column=0)

   def configure_color_sliders(self):
       self.red_color_slider.configure(command=self.estimate_color)
       self.green_color_slider.configure(command=self.estimate_color)
       self.blue_color_slider.configure(command=self.estimate_color)

   def create_color_areas(self):
       self.create_target_color_area()
       self.create_estimated_color_area()

   def create_target_color_area(self):
       r = random.randrange(256)
       g = random.randrange(256)
       b = random.randrange(256)
       self.target_color_image = tk.PhotoImage(width=64, height=64)
       self.colorize_area(self.target_color_image, (r, g, b))
       self.target_color_area = tk.Label(self.master, image=self.target_color_image)
       self.target_color_area.grid(row=1, column=1)

   def create_estimated_color_area(self):
       self.frame = tk.Frame(self.master)
       self.frame.grid(row=0, column=1)

   def estimate_color(self, event):
       self.clear_widget(self.frame)
       r = self.red_color_slider.get()
       g = self.green_color_slider.get()
       b = self.blue_color_slider.get()
       self.calculated_color_image = tk.PhotoImage(width=64, height=64)
       self.colorize_area(self.calculated_color_image, (r, g, b))
       self.calculated_color_area = tk.Label(self.frame, image=self.calculated_color_image)
       self.calculated_color_area.pack()

   def colorize_area(self, image, color):
       x = 0
       y = 0
       r, g, b = color
       for i in range(32):
           for j in range(32):
               image.put("#%02x%02x%02x"%(r , g, b), (y+i, x+j))

   def clear_widget(self, widget):
       for child in widget.winfo_children():
           child.destroy()

if __name__ == '__main__':
   root = tk.Tk()
   ColorFinder(root)
   root.mainloop()


This post from Martin R is a good step in the right direction toward generalizing your problem.

The helper function at the top of the post is already what you need for making a more generalized loop:

public func sequence<T>(first: T, while condition: @escaping (T)-> Bool, next: @escaping (T) -> T) -> UnfoldSequence<T, T> {
    let nextState = { (state: inout T) -> T? in
        // Return `nil` if condition is no longer satisfied:
        guard condition(state) else { return nil }
        // Update current value _after_ returning from this call:
        defer { state = next(state) }
        // Return current value:
        return state
    }
    return sequence(state: first, next: nextState)
}

And the first example he uses with the above function is also a good hint toward what you need:

for f in sequence(first: (0, 1), while: { $1 <= 50 }, next: { ($1, $0 + $1)}) {
    print(f.1)
}

As written, that loop prints the all the Fibonacci numbers up to 34, which is the largest Fibonacci number under 50.

So... how can we generalize this further?

First, let's make a function that simply sums and returns the value:

func sumFibonacciEvens(limit: Int) -> Int {
    // TODO: Implement
}

This is the basic form we want.  Now, after implementing, we'd just pass in 4 million to get the answer we want, but we can easily reuse for any limit.

I'd say let's go one further though.  Let's also make the "even only" part of this generic.

func sumFibonacciNumbers(lessThan limit: Int, condition: (Int) -> Bool) -> Int {
    // TODO: Implement
}

Now then, for this function, we pass in the limit (again, for the case we care about, four million).  But we also pass in a closure that defines what elements to sum and what elements to ignore.  So for your case, calling this function would look like:

let isEven: (Int) -> Bool = { number in
    return number % 2 == 0
}

let answer = sumFibonacciNumbers(lessThan: 4_000_000, condition: isEven)

This looks pretty good, right?  So... how do we do it?

We're going to keep the sequence function defined earlier exactly as is and use it in our sumFibonacciNumbers function, which should look something like this:

public func sumFibonacciNumbers(lessThan limit: Int, condition: (Int) -> Bool) -> Int {

    var sum = 0
    for f in sequence(first: (0,1), while: { $1 <= limit }, next: { ($1, $0 + $1)}) where condition(f.1) {
        sum += f.1
    }

    return sum
}


remove elements in one list according to the conditions on corresponding elements of another list

Rather than two comprehensions, it'd be simpler to just use one for loop. Make new_list_a and new_list_b start empty, and if the item is good add to both at the same time. This is simpler to understand, as you see clearly that both are being filtered by the same thing.

new_list_a = []
new_list_b = []
for a, b in zip(list_a, list_b):
    if a != '':
        new_list_a.append(a)
        new_list_b.append(b)

However, it looks like you'd be better served if you only create one list. This means you can have a tuple of (a, b). And so could implement something like:

[(a, b) for a, b in zip(list_a, list_b) if a != '']


Pick a column for each row by column-header name

The downside of all the functions, except pick0, is that the caller needs to know all the columns and their order. pick0 is even worse as it is not reusable.

I would rather implement something similar to csv.DictReader that would give me each row as a dict, or perhaps as a namedtuple

If the usage is as simple as in the given example, one could also simply do this:

key_index = headers.index(key)
for row in ((5, 6), ('f', 'g'), (1, 8)):
    print row[key_index]

Other comments:

Using locals() in pick0 is dubious. A caller trying to pick k or r would get unexpected results.
lambda is for creating nameless functions. Use def when you want to assign a name.


How would I format this JavaScript code so it's more readable

This is a very subjective question

I am a fan of separating things so each is identifiable and easily maintained in the future. However some will argue this does lead to more code, but more readable code in my opinion.

var animateCallback = function() {
    var props = {
        width: width + 'px',
        marginLeft: '0px',
        opacity: '1'
    };
    $(this).siblings('.card').animate(props, 500);
};
var clickHandler = function() {
    var props = {
        width: '0px',
        marginLeft: margin + 'px',
        opacity: 0.5
    };
    $(this).stop().animate(props, 500, animateCallback);
};
$(".card").click(clickHandler);


Evicting an entry from a size-limited HashMap

Improvement of the code
Your current code can be improved concerning the logic that is removing the key having the lowest value. You are doing 2 Stream pipelines: the first one to retrieve the smallest value and the second one to get the first key mapping to that value.
You can actually do this with a single Stream pipeline. For that, we can sort the Map according to a comparator comparing the values, keep the first entry and remove the key of that entry. There is a built-in comparator for that: Map.Entry.comparingByValue(). The following does just that:
set.entrySet()
   .stream()
   .sorted(Map.Entry.comparingByValue())
   .findFirst()
   .map(Map.Entry::getKey)
   .ifPresent(set::remove);

Note that instead of calling get() "blindly" on the Optional returned by findFirst(), this code maps it to an Optional containing only the key and, if it is present, removes that key from the map.
While in this case we know that the map won't be empty (and so that get() will never throw a NoSuchElementException), it is still preferable to not rely on that and write code that is as much generic as possible.
If / else and return statements
This is the sketch of your method:
if (set.containsKey(element)) {
    return false;
} else if (set.size() == length) {
    // do something
}
// ...
return true;

I feel that adding explicitely the else hides the fact that the method has a clear separate path when the map doesn't contain the element. I would remove it and have instead:
if (set.containsKey(element)) {
    return false;
}
if (set.size() == length) {
    // do something
}
// ...
return true;

The difference here is that it becomes quite clear that the first part of the method is dealing with the case where the map doesn't have the element, and so that the rest of method can safely assume that it is not the case. It shows that the method returns early in that case.
Worth mentioning but the fact that you're returning false when an element that is already contained in the map is given as argument is really great because this is what Collection.add also mandates (if the collection does not permit duplicates) and so it adheres with the principle of least surprise.
Namings
You have named your map set. This is confusing: it implies that we're dealing with a Set instead of a Map. I would suggest renaming that variable to something that conveys more its intent (that would depend on what you do with that map, so I can't really propose any name).
Also,
HashMap<T, Integer> set = new HashMap<>();

should be replaced with
Map<T, Integer> set = new HashMap<>();

It is preferable to always code against interfaces instead of implementation.


Continuous sequence against target number

In case there's no acceptable sequence, you have to go through all the elements anyway, so it can't be lower than O(n), and your code is already O(n).

The only optimization that you could add is a condition where if the current number alone is greater than the expected sum, you skip all values until the one just after the current value.

For instance, suppose you have [2, 3, 4, 25, 7, 8, 9] and you're looking for number 17. You don't want to check 2 + 3 + 4 + 25, 3 + 4 + 25, 4+25, you can skip directly to the index of 7.

Other than that I'd just remove the comments because I don't think they really add anything.


java code design puzzle for common function result module

I'm not sure I understood your question fully, but from what I could understand, you do not need to have both TypeOneResult and TypeTwoResult.  In fact, you probably do not need either of them.  You can use the value of the type member of the CommonResult class to distinguish among the different types.


Turning on/off setInterval locating - using React.js

Typo? I think you meant to set isDragged to false when dragging finishes:
onDragEnd={() => {
  setIsDragged(false);
}}

Note that you don't need to declare parameter you don't use (and probably shouldn't, to make the code easier to read).
Concise props When you have variables that you want to pass as props of the same name, you can make things a bit concise by using shorthand property names and spreading the object into props. For example:
<UserLocationTimer
  userLocation={userLocation}
  setUserLocation={setUserLocation}
  panTo={panTo}
></UserLocationTimer>

can be
<UserLocationTimer {...{userLocation, setUserLocation, panTo}} />

(it has no children, so it can be made self-closing)
Listing fewer identifiers while writing code means less chance of typos, and helps enforce consistent names for things.
Marker position props Rather than listing out the lat and lng properties of userLocation, you can pass the plain object itself to position:
<Marker position={props.userLocation}

Return early instead of long if/else blocks - if one sees if followed by a long block of code, followed by an else, keeping track of what condition the else is corresponding to can be harder to recognize at a glance than it needs to be. Consider returning the short branch first instead. See below.
JSX fragments are only needed when enclosing 2 or more tags - if a fragment only has one child tag, it can be removed completely, like this:
export const UserLocation = ({ userLocation }) => (
  if (!userLocation) {
    return null;
  }
  return (
    <Marker
      // ...

The same thing applies to the JSX returned by UserLocationTimer, but there's a better approach:
Consolidate UserLocation Since UserLocation is being rendered regardless, I think conditionally putting it inside UserLocationTimer isn't the right way to go. I'd remove the timer component completely, and implement its logic in the parent component instead, while unconditionally rendering UserLocation.
const intervalRef = useRef();
useEffect(() => {
  if (isDragged) {
    const intervalId = setInterval(locateMe, 2000);
    // Cleanup will run on dismount and when isDragged goes to false
    return () => clearInterval(intervalId);
  }
}, [isDragged]);

// ...

<GoogleMap
  onDrag={() => {
    setIsDragged(true);
  }}
  onDragEnd={() => {
    setIsDragged(false);
  }}
>
  . . .
  <UserLocation {...{userLocation}} />
</GoogleMap>

Naming The name UserLocation is very similar to userLocation, but one is a component, while the other holds data. Maybe rename them so that they're more distinct - perhaps UserLocationMarker and userLocationCoords?


Phrase matching between two Strings in Ruby

It seems that you are trying to get the longest common subsequence.
There are several implementation of this algorithm and you can find an example on Rosetta Code.

A working recursive implementation implementation could be:

# Split your sentence into words and manipulate the content. E.g.
# - downcase all chars
# - split by some chars such as space, punctuation and so on

def split_into_words(string)
  string.downcase.split(/[\s\.,;\'\"]/)
end

def longest_subsequence(xstr, ystr)
  return '' if xstr.empty? || ystr.empty?

  x, *xs = xstr
  y, *ys = ystr

  if x == y
    x + " " + longest_subsequence(xs, ys)
  else
    [longest_subsequence(xstr, ys), longest_subsequence(xs, ystr)].max_by {|x| x.size}
  end
end

def phrase_in_common(string1, string2)
  xstr = split_into_words(string1)
  ystr = split_into_words(string2)
  longest_subsequence(xstr, ystr).strip
end

This would pass all your specs, but it returns '' instead of nil when the longest substring is empty.

You can slightly change this implementation to include int inside class String eventually

Edit 2017-10-04

As remarked by moveson, in Rails we can easily make this method to return nil instead of an empty string:

def phrase_in_common(string1, string2)
  xstr = split_into_words(string1)
  ystr = split_into_words(string2)
  longest_subsequence(xstr, ystr).strip.presence
end


Correcting duplicate names in generic array - follow up

Because we are dealing now with objects, we need to create a copy of each FileContent to achieve the same result like in your previous question.

Instead of having var currentFile = file where file had been a string, we now use var currentFile = new FileContent() { Content = file.Content, Name = file.Name };.

In addition, we are using the HashSet<T> only for look up and return an IEnumerable<FileContent> instead of an array.

private IEnumerable<FileContent> ChangingDuplicateNames(FileContent[] files)
{
    var hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
    foreach (var file in files)
    {
        var currentFile = new FileContent() { Content = file.Content, Name = file.Name };
        int counter = 0;
        while (!hashSet.Add(currentFile.Name))
        {
            currentFile.Name = CreateFileName(file.Name, ref counter);
        }
        yield return currentFile;
    }
}

and call it like so

FileContent[] result = ChangingDuplicateNames(files).ToArray();


Your solution seems to me quite complex, with iterations, recursions, and the use of match.
Here is an alternative version with a simple linear recursion, where the result is given with lists and not with strings.
(define (missing-ranges nums lower upper)
  (cond ((> lower upper) '())
        ((null? nums) (list (list lower upper)))
        ((= lower (car nums)) (missing-ranges (cdr nums) (+ lower 1) upper))
        ((= (car nums) (+ 1 lower)) (cons (list lower) (missing-ranges nums (+ lower 1) upper)))
        (else (cons (list lower (- (car nums) 1)) (missing-ranges (cdr nums) (+ (car nums) 1) upper)))))

(missing-ranges '(0 1 3 50 75) 0 99)
'((2) (4 49) (51 74) (76 99))

(missing-ranges '(8) 0 99)
'((0 7) (9 99))

(missing-ranges '() 0 99)
'((0 99))

(missing-ranges '(3 9 88 99) 0 99)
'((0 2) (4 8) (10 87) (89 98))

(missing-ranges '(0 99) 0 99)
'((1 98))

(missing-ranges '(1 2 3) 1 3)
'()


In testing your code I noticed a crash with text longer than the max.  Not sure if you consider this simpler but it does handle the tails case.

public void PrintBetweenChars(string input, char c)
{
    // Require input be at most (_outputMaxLength - 4) chars to accomodate 1 beginning and trailing char and space
    // Shrink input if necessary
    string UserText = " " + input.Substring(0, Math.Min(OutputFormatter._outputMaxLength - 4, input.Length)) + " ";
    string DisplayText = UserText.PadLeft((OutputFormatter._outputMaxLength / 2) + (UserText.Length / 2) + (UserText.Length % 2), c);
    Console.WriteLine(DisplayText.PadRight(OutputFormatter._outputMaxLength, c));
}


Your main issue is this line:

 memset(sum1,0,sizeof(sum1)) ;

The whole array is being initialized to zero, even if you are only dealing with a range of one element.  You really only need to initialize the first element:

sum1[0] = 0; // initialize here

// copying into array1 from left to mid
index1 = 0 ;
for(index=left;index<mid+1;index++)
{
    if(index1!=0)
    {
        sum1[index1] = sum1[index1-1] + array1[index1-1] ;
    }

The rest is already assigned proper values.


K-combination recursive algorithm implementation

There're a few more problems with code: for instance, it crashes for k = 0 (which is a valid input).
You implementation is really hard to follow: it's not clear what the arguments index, limit and increment stand for. They're way too generic. index: What kind of index? Sure, it's a position in the original string or list. But what does it represent? It's not an arbitrary position, is it? It's the index of the element that should be changed, isn't it? Why not call it idx_to_change, pos_to_change or something like that? The same goes for limit: what kind of limit is it?
There's too much stuff going on in the get_combinations function (like choosing the next position, generating a new combination and so on). I suggest splitting into a few smaller function with meaningful names.
I didn't fully understand your code, but if you need to keep a set to avoid duplicated, you're doing it wrong. I don't see why you need to recursion here either.
Let's go back to the algorithm:

comb = [0..k-1]
do
    result.append(comb)
    // I assume that it returns null if there's no next combination
    comb = get_next_combination(comb)
while comb != null

Pretty simple, isn't it? Now we need to learn to generate the next combination. This part is already described in your post. So let's just create another function that does it.

Here's the code that implements this idea directly:

def get_pos_to_change(comb, n):
    """
    Finds the rightmost position in the comb list such that its value can
    can be increased. Returns -1 if there's no such position.
    """
    pos_to_change = len(comb) - 1
    max_possible_value = n - 1
    while pos_to_change >= 0 and comb[pos_to_change] == max_possible_value:
        pos_to_change -= 1
        max_possible_value -= 1
    return pos_to_change

def inc_value_at_pos(comb, pos):
    """
    Increments the value at the given position and generates the
    lexicographically smallest suffix after this position.
    """
    new_comb = comb[:]
    new_comb[pos] += 1
    for idx in range(pos + 1, len(comb)):
       new_comb[idx] = new_comb[idx - 1] + 1
    return new_comb

def get_next_combination(comb, n):
    """
    Returns the lexicographically next combination or None if it doesn't
    exist.
    """
    pos_to_change = get_pos_to_change(comb, n)
    if pos_to_change < 0:
        return None
    return inc_value_at_pos(comb, pos_to_change)

def combinations(n, k):
    """
    Generates all n choose k combinations of the n natural numbers
    """
    comb = [i for i in range(k)]
    while comb is not None:
        yield comb
        comb = get_next_combination(comb, n)

It's split into several smaller functions so that it's easier to read.

A few more technical details: I used yield here to implement a generator. It's useful if the number of combinations is huge. Not storing them in a collection helps to save a lot of memory in this case (stack overflow is not the only possible issue: you can also just run out of space to store all combinations).

Note that this implementation handles corner cases properly (like k = 0).

There're a few more things you might want to add, such as parameter validation (it makes sense to throw an exception if k > n or either of them is negative).


You have quite a few violations of the style guide. This isn't necessarily crucial to follow (although highly recommended!), but more important is that your code lacks consistency.

You have three functions, two named with CapitalizedWords and one with mixedCase; and
internalParse's parameters are a mix of lower_case_with_underscores and mixedCase.

Your whitespace is at least consistent, but spaces after commas makes it easier to read; compare:

def internalParse(internal_list,final_dict,countryDict,refr_list):

with:

def internalParse(internal_list, final_dict, countryDict, refr_list):

country_dict, final_dict and refr_list shouldn't be defined at the top level of the script; global variables are a bad idea. You could create country_dict in GetCountryDict and final_dict and refr_list in WikiParser.

The current country_dict seems a bit pointless - you fill it with 1s for some reason, but then only ever use the keys. I would suggest a set instead, and using foo in bar rather than bar.has_key(foo) (in would still work with a dictionary, by the way). This really simplifies GetCountryDict:

def get_countries():
    """Get a set of all valid country names."""
    return set(country.name for country in pycountry.countries)

Note that I have renamed the function in line with the style guide and provided a docstring to explain what it does.

internalParse has four parameters but only uses three of them; you should either remove internal_list or, better, explicitly pass it through to WikiParser (where it's currently accessed by scope).

WikiParser is currently called in two places - directly from the if __name__ == '__main__': block, and indirectly via internalParse. This makes it more difficult that it needs to be to figure out what the code is doing.

Given the output you want, a better structure might be:

if __name__ == '__main__':
    # 1. Get set of valid countries first
    valid_countries = get_countries()

    # 2. Add input validation
    country_name = input_valid_country(valid_countries)

    # 3. Call parser
    print wiki_parser(country_name, valid_countries)

Notes:

Already covered;
See Asking the user for input until they give a valid response;
Refactor wiki_parser to return the dictionary of lists that you want. You can still have something like internalParse, but as a private function that's only called via wiki_parser (conventionally, it would therefore be named with a leading underscore: _internal_parse).

  I don't have pycountry or wikipedia installed, so this is untested. The ideas should be useful, though!

Given the nature of the task, one option for wiki_parser would be to do it recursively. This has advantages in terms of clear and comprehensible code, although one issue can be with hitting the system recursion limit if you delve too deeply:

def wiki_parser(country_name, valid_countries, out=None):
    """Recursively parse Wikipedia for linked countries."""
    if out is None:
        out = {}
    out[country_name] = []
    for country in _parse_page(country_name, valid_countries):
        if country not in out:
            out[country_name].append(country)
            wiki_parser(country_name, valid_countries, out=None)
    return out

This uses out both to provide the output and to determine if we've already seen a given country - membership testing (foo in bar) is as efficient with a dict as a set, as they're both hash-based (O(1), vs. O(n) for a list/tuple).

If you're wondering why I've used out=None rather than out={}, see “Least Astonishment” in Python: The Mutable Default Argument.

def _parse_page(country_name, valid_countries):
    """Parse a single page and return list of linked countries."""
    try:
        wiki_resp = wikipedia.page(country_name)
    except Exception:
        return []
    return [link for link in wiki_resp.links if link in valid_countries]

Note that except Exception: is the bare minimum - bare except is a very bad idea. Ideally, you should figure out what errors wikipedia.page can raise and handle them explicitly. I've also used a list comprehension to build the list of linked countries in one step.

You currently create a dictionary of lists, but not JSON; if you actually want to, look into json.


Find 4 points which form a square with the biggest area

You're coding javascript the "old" way. With es6 you have a lot of new features available. Take a look at them.

Don't use self-invoking anonymous functions i.e. IIFEs

/// bad
(function(){
  // code here
})();

Use blocks

/// good
{
   // code here
}

Give meaningful names to your variables and methods. Functions should not have more than 2 parameters. If they do, you need to put them in an object.

/// bad
... pointsFormsQuadrangle = function(a, b, c, d){}

/// good
static FormsQuadrangle([point1, point2, point3, point4]){

}

Use the class syntax instead of function/prototype.

class Utils {
  static NumbersEqual(a, b){
    return Math.abs(a - b) < Number.EPSILON;
  }
}

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  distance(point) {
    return Math.sqrt((this.x - point.x) ** 2 + (this.y - point.y) ** 2);
  }

  equal(point) {
    return Utils.NumbersEqual(this.x, point.x) && Utils.NumbersEqual(this.y, point.y);
  }

  static FormsQuadrangle(a, b, c, d) {
    if (a.equal(b) || a.equal(c) || a.equal(d)) return false;

    if (b.equal(c) || b.equal(d)) return false;

    if (c.equal(d)) return false;

    const center = new Point((a.x + b.x + c.x + d.x) / 4, (a.y + b.y + c.y + d.y) / 4);

    const ac = a.distance(center);
    const bc = b.distance(center);
    const cc = c.distance(center);
    const dc = d.distance(center);

    return Utils.NumbersEqual(ac, bc) && Utils.NumbersEqual(bc, cc) && Utils.NumbersEqual(cc, dc);
  }

  static FormsSquare(a, b, c, d) {
    if (!Point.FormsQuadrangle(a, b, c, d))
      return false;

    const ab = a.distance(b)
    const ac = a.distance(c);
    const ad = a.distance(d);
    const [tr1, tr2] = [ab, ac, ad].sort((a, b) => a - b);

    return Utils.NumbersEqual(tr1, tr2);
  }
}


You said you built this specifically so you can use dictionaries as keys in other dictionaries?

In that case, you've got a problem. Consider the following demonstration:

var keyA = new Dictionary<string, int> { ["a"] = 4 };
var keyB = new Dictionary<string, int> { ["a"] = 4 };

var comparer = new DictionaryEqualityComparer<string, int>();
var dict = new Dictionary<Dictionary<string, int>, int>(comparer);
dict[keyA] = 10;

keyA["b"] = 5;
var x = dict[keyA];    // KeyNotFoundException: different hash
var y = dict[keyB];    // KeyNotFoundException: same hash, but not equal to original key

After modifying keyA, its hash-code is different, so a key lookup will fail. So far so good - this seems to be what you intended.

However, a lookup with keyB will also fail. Its hash-code is the same as keyA's original hash-code, so that part of the lookup succeeds, but because of hash collisions dict needs to compare it with the original key... which fails because keyA no longer has the same content.

That's why, generally speaking, the hash-code of an object should never change during its lifetime.

Also, the idea behind a hash-code is to have a quick, cheap way to filter out objects that are obviously not equal. Inspecting every single key and value seems fairly heavy-handed.

As for what you want to achieve... I suspect that will require a custom dictionary implementation, because you'll need to retain the original content of each key for future comparisons. At that point, I'd start thinking about why I even wanted to do this in the first place - there's likely a better solution for the original problem.


The logic for re.match() , sys.exit(1) does not make sense, plus why can't i use return True if the re.match regex matches

You seem confused about sys.exit is doing. It exits your program. You function verify_commit_text never exits. Your code after calling verify_commit_text is never executed. The program always hits a sys.exit in verify_commit_text and terminates. The first thing you need to do is eliminate all the sys.exit() except in the __main__ section. You should really only have sys.exit in there.


First, a baseline timing. Using this code to generate 5 random matrices:

import numpy as np

n, t = 1000, 5

with open("data", "w") as f:
    for _ in range(t):
        np.savetxt(np.random.randint(1000, size=(n, n)))

Your code takes about 10 seconds to execute on my machine.

Second, small stylistic fixes. Your try...except...else code is literally what Python basically does for every line anyway:

It tries to execute the line.
If this fails, raise an appropriate error.
Otherwise go on with the next line.

So you can just remove that. In any case, you should never have a bar except, unless you are really sure what this means. You will not be able to abort the process using CTRL+C, for example.

You should also rename your function from printImage to print_image, to adhere to Python's official style-guide, PEP8.

Then, to improve the speed. This is quite tricky (as you might have discovered yourself already). These are the things I tried, but which failed to improve the time:

Create the figure only once and reuse it. This was recommended here.
Get rid of the GUI drawing completely, by using the underlying objects. This was recommended here.
Use pandas.read_csv with a hack to read an iterator, as shown here.

What did make a huge difference is using 2. from above and using the multiprocessing module:

import itertools as it
import time

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

import matplotlib.pyplot as plt
import multiprocessing

def timeit(func):
    def wrapper(*args, **kwargs):
        starting_time = time.clock()
        result = func(*args, **kwargs)
        ending_time = time.clock()
        print('Duration: {}'.format(ending_time - starting_time))
        return result
    return wrapper

@timeit
def print_image_multiprocessing(n, t):
    print("print_image_multiprocessing")
    p = multiprocessing.Pool(4)
    with open("data", "r") as f:
        items_gen = ([list(map(float, i.split())) for i in it.islice(f, n)]
                     for i in range(t))
        p.starmap(print_image_no_gui, zip(items_gen, it.count()))

def print_image_no_gui(items, i):
    fig = plt.Figure()
    ax = fig.add_subplot(111)
    image = ax.imshow(items, interpolation='nearest')
    image.set_cmap('hot')
    fig.tight_layout()
    plt.axis('off')
    image.axes.get_xaxis().set_visible(False)
    image.axes.get_yaxis().set_visible(False)
    canvas = FigureCanvas(fig)
    canvas.print_figure('mult%05d' % i + '.png', bbox_inches='tight',
                        pad_inches=0, dpi=300)
    print(str(i) + '/' + str(t))

if __name__ === "__main__":
    print_image_multiprocessing(1000, 5)

This takes less than 3 seconds (with the 4 workers), compared to 10 seconds, on my machine. For 10 images it needs 6 seconds, instead of 14. Not ideal, but I don't see any other obvious improvements.

Note that I removed the tight_layout, because it raises a warning per plot. According to this issue here, one can work-around it by using fig.set_tight_layout(True), but this then raises a different warning, complaining about the axes not being drawable. Since you remove the axis anyways, removing that call does no harm.


I've got the idea you're trying to achieve, however, this would be too much work to do if you're going to implement it this way.

If you are still convinced that this is the only way, you can use struct and define the OS structure like you did, and keep it only for path something like this :

public struct SystemDisk
{
    private static string Drive => Path.GetPathRoot(Environment.SystemDirectory);

    //using Refelction, will give you the object's full name, we then convert it to string and adjust it to be parsed as an OS path.
    private static string GetPath(Type type) => @Drive + @type.FullName.Substring(type.FullName.IndexOf('.') + "SystemDisk".Length + 2).Replace('+', Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;

    public struct Windows
    {
        public static string Root => $@"{GetPath(typeof(Windows))}";

        public static string SystemIni => $@"{Root}System.ini";

        public struct System
        {
            public static string Root => $@"{GetPath(typeof(System))}";
        }

        public struct System32
        {
            public static string Root => $@"{GetPath(typeof(System32))}";
        }

        public struct Cursors
        {
            public static string Root => $@"{GetPath(typeof(Cursors))}";
            public static IReadOnlyList<string> Animated => GetFiles(Root, "*.ani");
        }
    }
}

if you're going to continue on this road, and you need to create a struct for each directory in the system folders, you can write a method to get the directories, and then design a model for it, then returning this model as string, then just copy and paste. To do that, you'll have to get first the directories, then get each directory name, after that, you'll remove any special chars from the name, then just make a  model template and pass the directory name to it, get the representative string, and copy / paste into the class.

Here is method to camel case the name :

public static string CamelCase(string str)
{
    str = str.Replace(".", " ").Replace("-", " ").Replace("_", " ");

    return str.Contains(" ")
        ? string.Join("", str.Split(' ').Select(x => char.ToUpper(x[0]) + x.Substring(1)))
        : char.ToUpper(str[0]) + str.Substring(1);
}

now we can do a method to build the model template :

public static string StructModelBuilder(string name, int indentlevel, string body = "")
{
    var sb = new StringBuilder(string.Empty);

    string indentLv1 = indentlevel == 0 ? string.Empty : new string(' ', indentlevel);

    string indentLv2 = indentLv1 == string.Empty ? new string(' ', 4) : new string(' ', indentlevel * 2);

    sb.Append(Environment.NewLine);
    sb.Append(indentLv1);
    sb.Append($"public struct {name}");
    sb.Append(Environment.NewLine);
    sb.Append(indentLv1);
    sb.Append("{");
    sb.Append(Environment.NewLine);
    sb.Append(indentLv2);
    sb.Append($"public static string Root => $@\"{{GetPath(typeof({name}))}}\";");
    sb.Append(Environment.NewLine);
    sb.Append(body);
    sb.Append(indentLv1);
    sb.Append("}");
    sb.Append(Environment.NewLine);

    return sb.ToString();
}

now, we can create a method where we get the directories list, and just pass them to the template to get the model

public static string GetStructureModel(string path)
{
    if (string.IsNullOrEmpty(path))
        return string.Empty;

    //Directory.GetDirectories($@"{path}", "*.*", SearchOption.AllDirectories);  // to include all sub-directories (recursively).
    var root_dir = Directory.GetDirectories($@"{path}");// just get the top level directories.

    // remove the last Directory Sparator Charcter (e.g. back-slash \) and get the name of the directory
    var root_name = path.TrimEnd('\\').Substring(path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1);

    var rootNameCamelCase = CamelCase(path.TrimEnd('\\'));

    var sb = new StringBuilder(string.Empty);

    var model = StructModelBuilder(rootNameCamelCase, 0, "@body");

    foreach (var dir in root_dir)
    {
        var dir_name = path.TrimEnd('\\').Substring(path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1);

        var dirNameCamelCase = CamelCase(dir_name);

        sb.Append(StructModelBuilder(dirNameCamelCase, 4));
    }

    return model.Replace("@body", sb.ToString());
}

now you just pass the path like this :

var model = GetStructureModel(@"C:\Windows");

you can from here take the model, paste it into the class, and adjust whatever needed. this is not perfect, but it should get the job done.

personally, I wouldn't go this far if I were in your seat, instead, I'll use Window Environment Variables instead, to not re-invent the wheels. also, I'll make use of Enum and make things shorter. For instance, instead of making a full path to the System32, I'll just use an Enum and define System32, and with a simple switch statement, it'll return the full path, and so on. this would make more sense to me and would be easier to maintain.


Re-write custom feature encoding function python

Just have the time to take a quick view on your code, but one of the first thing you have to learn to do (before using design pattern and such things), is to refactor your code.

By simply scrolling, we can see df_additional[col] more than ten times. For all the places where you just need to read this value, use a local variable to store it. If you need to write it, in that case leave it.

There is also df_additional = pd.concat([df_additional.iloc[:, :loc_col], df_additional_one_hot, df_additional.iloc[:, loc_col:]], axis=1).drop(col, axis=1) a couple of time, with just a local variable used as a parameter which changes between those calls. Maybe you can also refactor that?

It's also worth noting that if your if (or whatever loop or control statement) begins to be long (dozen of lines), and even more when you have several if like that, think about isolating each block in a separate function. Or at least all the complete if/elif block in a function.


Return the indices of the two numbers such that they add up to a specific target

sum

The word sum sounds like your taking an iterable of some sort and summing all the values in it. sumsTo would be a better name. Even then, I would expect to return all possible pairings, which the code doesn't currently do.

result

I wouldn't call it result. I'm not that familiar with Kotlin, but sometimes APIs will write to the value you pass in and so the function doesn't return anything but it modifies the result variable. Maybe target is a better choice?

Pair datatype

I would change your datatype from Array to Pair. You are returning a pair of integers satisfying the equation so why choose an array when there is a Pair data type object? I also suggest that if no solution is found that you, yes, return null.

null is often a bad design choice, but I strongly believe this is the exception. If there are no solutions we say that the solution set is null (or the empty set). So if there are no pairs the solution set is null. Reads just like math.

Generalizing to Iterable

You could just iterate over an array of values, but more generally you probably want to iterate over an Iterable collection of integers.

The one cost of this is you have to say arrayOf(...).asIterable().

The code

fun sumsTo(values: Iterable<Int>, target: Int): Pair<Int, Int>? {
  for ((i, e1) in values.withIndex()) {
    for ((j, e2) in values.drop(i + 1).withIndex()) {
      if (e1 + e2 == target) {
        return Pair(i, i + j + 1)
      }
    }
  }
  return null
}


Instead of the big indent block you make by doing if(strlen(seqbuffer1) > 0), do: if (strlen(seqbuffer1) <1) continue;, so the entire rest of the loop can be outdented a level, making it more readable.

Similarly, you can turn the if(!ambiguous) into if (ambiguous) continue; and outdent that block as well.

Depending on what version of C you're using, ambiguous could be a boolean instead of an int.

You could be a little more consistent with your NULL comparisons to the result of fgets() - the one in the while() condition is implicitly != NULL but the ones in the if() statements are explicitly == NULL. IMO you should be either explicit everywhere or implicit everywhere - either choice is fine, but mixing styles makes your code a bit more unclear.

assert(strncmp(seqbuffer1, ">", 1) == 0); is the same as the more-easily-understood assert(seqbuffer1[0] == '>'), right?

Also, you've got at least one potential bug: What if BUFFERSIZE is smaller than input line length and then seqlength > BUFFERSIZE?


Is ThreadPool QueueUserWorkItem best option for handling event?

Without seeing the rest of your code it's hard to know what's going on but this is always* bad:

string data = GetByteData(characteristic.Service.Device.BluetoothAddress).Result;

* as long as GetByteData is async and returning a Task<string>

You should queue an async delegate instead:

ThreadPool.QueueUserWorkItem(async x =>
    {
        GattCharacteristic characteristic = sender;
        string data = await GetByteData(characteristic.Service.Device.BluetoothAddress).ConfigureAwait(false);
        queue.Enqueue(new EventDataModel { IOData = characteristic, IOKey = characteristic.Service.Device.BluetoothAddress.ToString() });
    });

Note the use of await with ConfigureAwait(false). See Stephen Cleary's blog to learn more about why blocking on async code is such a bad idea.


Project Euler #4: Largest palindrome product

For increased performance I think it might make sense to enhance your loop:

Start with 999 each and count downwards, as the largest product will most likely involve bigger numbers. This allows you to implement a strategy for pruning and return earlier (see other answers and comments for details).
Count only in the range of 100-999, since 1-99 aren't 3-digit numbers.

For a cleaner code you should refactor your if clause into a separate method. Something like

private boolean isPalindrome(int product) {
    return ((product / 100000) % 10 == product % 10
         && (product / 10000) % 10 == (product / 10) % 10
         && (product / 1000) % 10 == (product / 100) % 10);
}

A cleaner code would for me also involve consistent formatting and use of brackets, e.g.

(product / 100000) % 10 vs product / 10000 % 10
for (int first = 1 vs for(int second = 1


I see a number of things that may help you improve this.

Don't manually write a Makefile

Since you're using standard tools such as gcc and ld, you could use: autotools (that is the collection of autoconf and related software) instead of writing and maintaining your own Makefile.  There is a learning curve, of course, but the benefits are considerable, especially if you're writing software that will become open source.  To do that here, you can start with these two files:

configure.ac

AC_PREREQ([2.69])
AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
AC_CONFIG_SRCDIR([foo.c])
AC_CONFIG_HEADERS([config.h])

AC_PROG_CC

PACKAGE_CFLAGS="-ffreestanding -nostdlib -gdwarf-4 -m32 -ggdb3 -Wall -Wextra -Werror -std=c11"
PACKAGE_LDFLAGS="--nmagic -m elf_i386 --script=os.lds"
PACKAGE_NASMFLAGS="-f elf32 -F dwarf -g -w+all"

AC_SUBST([PACKAGE_CFLAGS])
AC_SUBST([PACKAGE_LDFLAGS])
AC_SUBST([PACKAGE_NASMFLAGS])

AM_INIT_AUTOMAKE(foreign)
AC_CONFIG_FILES([Makefile])
AC_OUTPUT

Makefile.am

bin_PROGRAMS = os
os_SOURCES = foo.c ${asm_sources}
os_NASMFLAGS = @PACKAGE_NASMFLAGS@
os_LDFLAGS = @PACKAGE_LDFLAGS@
AM_CPPFLAGS = @PACKAGE_CFLAGS@
NASM = /usr/bin/nasm

asm_sources = thing1.asm thing2.asm

.asm.o:
        $(NASM) $(os_NASMFLAGS) $< -o $@

With these, you can execute autoreconf -i in the same directory.  Next, create a build directory anywhere (one of the advantages of automake) and execute the generated configure file from that directory.  That will create a nice Makefile for you which you can then execute in the usual way by typing make.

Another tool I use very often is CMake, which does something similar to autotools in that it creates build scripts for you, but it's not tied to Linux and BSD and can work with Windows-based compilers as well.

With that said, if you're determined to do it the hard way, there are some things you can improve in your existing file.

Define an implicit rule

GNU Make (which I assume that you're using) knows how to create object files from assembly files, but only by using as rather than nasm.  It's very simple to teach it a new trick, however, by defining an implicit rule.  Here's one:

.asm.o:
        $(NASM) $(NASMFLAGS) $< -o $@

This is a simple rule that tells make that the "recipe" to create a .o file from a .asm file is to run the command listed below.  That way you only need to list a dependency and not the rule each time.  That is:

thing1.o: thing1.asm

However, even this is often not necessary if you've defined the implicit rule.  The next suggestion explains.

Make make work harder

The purpose to having make is to offload some of the work of the programmer to quickly do only what's necessary to rebuild a new binary.  You can make it work harder than you currently are, while making things easier to maintain and a bit shorter as well.  If you're using GNU Make, you can define an implicit rule like this (note the slightly different syntax from the standard implicit rule listed above):

%.o : %.asm
        $(NASM) $(NASMFLAGS) $< -o $@

Then simply tell make the object files needed and let it figure out by itself that it needs to run the compiler on C files and nasm on assembly files:

os : foo.o thing1.o thing2.o
        ld $(LDFLAGS) $^ -o $@

Don't include paths in filenames

Inserting and maintaining paths everywhere is tedious and error prone.  Better is to use VPATH within the Makefile like this:

VPATH=../src

Now assuming your directory tree looks like this:

.
├── build
└── src

You can navigate into the empty build directory and type make -f ../src/Makefile.  All of the binaries will be created in the build directory and the source directory will be untounched.  VPATH tells make where to look for sources it needs.  This is a much nicer way to do things.

Mark phony targets .PHONY

There isn't really an all file created and there really isn't a clean file.  These are actually just tags that identify a target whose rules should always be run.  For this reason they should be explicitly declared as phony:

.PHONY: clean
clean:
        rm -rf os $(OBJECT_FILES)

Explicitly name sources

Lines like this one:

OS_C_SRCS := $(wildcard *.c)

generally should be avoided.  The reason is that if you create, say, a small test file to try out a concept while working on the source and then forget to delete it, it becomes part of the build whether you wanted it or not.  It's usually far better to explicitly name files rather than using wildcards.

Putting it all together

Here's a revised Makefile which implements these suggestions:

Makefile

CFLAGS= -ffreestanding -nostdlib -gdwarf-4 -m32 -ggdb3 -Wall -Wextra -Werror -std=c11
NASM=nasm
NASMFLAGS= -f elf32 -F dwarf -g -w+all
LDFLAGS= --nmagic -m elf_i386 -L$(VPATH) --script=os.lds
VPATH=../src
OBJECT_FILES=foo.o thing1.o thing2.o

.PHONY: all
all: os

%.o : %.asm
        $(NASM) $(NASMFLAGS) $< -o $@

os : foo.o thing1.o thing2.o
        $(LD) $(LDFLAGS) $^ -o $@

.PHONY: clean
clean:
        rm -rf os $(OBJECT_FILES)

Create libraries

One thing I forgot to mention was that it's often good practice to create libraries.  By grouping related object code together into a library, you gain a number of advantages.  First, recompiling the project typically becomes a bit faster.  Second, it allows (forces?) you to think carefully about the interface.  A well-defined interface to library code not only makes it easier to use (and potentially replace with an improved or alternate version) but also aids in testing.  Third, by having a separate library, testing can often be simplified by writing tests that thoroughly exercise each library.  When all libraries are tested, it's easier to test the main application with confidence.


The usual improvements we often suggest here on Code Review:
Using namespace:
Try not to using namespace std. Read a discussion about this here. Instead, just explicitly declaring the elements you are using would be better:
using std::cout;
using std::cin;
... etc...

Or don't do any of that and prefix library calls with std::. Not that much more typing anyway.
system("PAUSE") & friends:
The system() function asks the OS to run whatever program you specify as its argument. It just so happens that on Windows there are two programs in the default path called "PAUSE" and "CLS". This is not portable. On Unix those programs do not exist. But the biggest evil of system() is that it is a major security hole. For example, if a hacker manages to replace "CLS" with an exploit program, your program is going to be the one who fires it. So no serious code outside a learning demo should use those. Be aware of this issue.
Windows extensions:
_getch() and <conio.h> are Windows extensions. You can replace _getch() with the standard std::cin.get().
C++11 <random> library:
The new standard has introduced a more powerful pseudo-random number generation library: <random>. This library should be used instead of rand(), srand() for new code.
Funky if:
This
if (slot1 == slot2 == slot3)

As was noted in the comments, is nonsense. You have to use the && (AND) operator:
if ((slot1 == slot2) && (slot2 == slot3)) {  // If all three slots match, user getx 3x money


Determine if .deb package is installed using Bash

It seems odd that the function prints 0 in all cases, including when 1 has been printed.

For a utility like this, it's probably better to communicate via the exit status:

isInstalled() {
    !   dpkg-query -W -f'${Status}' "$1" 2>/dev/null | grep -q "ok installed" \
     || dpkg-query -W -f'${Status}' "lib$1" 2>/dev/null | grep -q "ok installed"
}

I'd be inclined to remove the !, returning zero (success) if the package is found.

If you have aptitude available, it's possible to ask it to search for any installed package of the given name, or providing the name:

aptitude -q2 search "~i~P?exact-name($1)|~i?exact-name($1)" >/dev/null

~i: installed package
~P: provides name
|: alternation
^$1\$
?exact-name: exactly what it says

This is less brittle, as it doesn't rely on the providing package being formed by prepending lib to the virtual package name.  For example, with www-browser, it finds all installed web browsers.  Also, it avoids matching superstrings of the supplied name.

If you know that $1 will always be the name of a virtual package, you can of course use just the ~P side of the alternation.


Optimize calculation of distances between pairs of points

What exactly your code does? It is not obvious, maybe you should name your variables better. Specially count = (a>b ? a-b : b-a) == k ? count+1 : count;
What a anb b is? count of what?

Instead of splitting line twice. Split it once and reuse the array. It also reduce count of space literal used.

String[] splittedLine = line.split(" ");
n= Integer.parseInt(splittedLine[0]);
    k= Integer.parseInt(splittedLine[1]);

And you are trying to use thread but you are not starting any. You are just wraping your implementation in Runnable object. See http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html for Thread useage examples.
Maybe you dont need threads at all, but i cant tell without knowing what exactly you are trying to solve. Running many threads may result into slower code because of switching from one thread to another and their creating take some time.


Vectorizing a pixel-averaging operation in Numpy

The function scipy.ndimage.measurements.mean takes a labelled array and computes the mean of the values at each label. So instead of:

for i in range(numSegments):
    tx = band[segments==i]
    avg = np.average(tx)
    band[segments==i] = avg

you can write:

segment_mean = scipy.ndimage.measurements.mean(band, segments, range(numSegments))
band = segment_mean[segments]

Though I should add that the last operation here (the reconstruction of band) seems quite wasteful to me: all the information you need is already in the array segments and the array segment_mean (which has just one value per segment). Why do you then need to reconstruct the full array, filling each segment with its mean value? Could you not refactor the subsequent processing to use segments and segment_mean directly?

Update: you clarified the question to explain that writing the mean values back to band was just for visualization and is not an essential part of your application. In that case, you just need the one call to scipy.ndimage.measurements.mean.


There is no (general) way of telling the difference between an infinite and a finite iterator.

types might be a generator that stops yielding after a million items have been yielded.  The only fool-proof way of telling would be to consume the generator up to the point where it stops yielding items.  Of course, even if we've consumed a billion items and it hasn't stopped, we can't be sure it wouldn't stop at a later point.

This is why I recommend you change the specification for your function.  The new version will yield items until values have been up.  If there are too few types, it raises ValueError.

def serialize(types, values):
    types_iter = iter(types)
    for value in values:
        try:
            type = next(types_iter)
        except StopIteration:
            raise ValueError("Too few types.")
        yield type.dump(value)

If you really want to, you can check with len() that the lengths of types and values are the same, but as you have said, this will only work for some iterables.

def serialize(types, values):
    try:
        len_types, len_values = len(types), len(values)
    except TypeError:
        pass
    else:
        if len_values > len_types:
            raise ValueError("Too many values.")
        if len_values < len_types:
            raise ValueError('Too few values.')

        for type, value in itertools.izip(types, values):
            yield type.dump(value)
        return

    types_iter = iter(types)
    for value in values:
        try:
            type = next(types_iter)
        except StopIteration:
            raise ValueError("Too many values.")
        yield type.dump(value)


One alternative is to transform it to the right shapes, then use moveaxis. I don't know how much simpler this is than what you've got, I guess it avoids one reshaping operation.

img = img.reshape(3, 32, 32)
img = np.moveaxis(img, 0, -1) # move the first axis to the end

or as a one-liner:

img = np.moveaxis(img.reshape(3, 32, 32), 0, -1)

Note that moveaxis returns a view, meaning that no data is copied.


Apply discount changes with Strategy pattern

The classes seem OK but the usage makes no sense:

                case "GOLD":
                    //Gold
                    clsBL blgold = new clsBL(new clsGoldDiscountStrategy());
                    blgold.costPrice = 5;
                    blgold.qty = 10;

                    result = blgold.GetfinalPrice(blgold.costPrice, blgold.qty);
                    break;

This code (and the other switch case) does not use the polymorphism that the interface IStrategy enables. Rather, you can have simply written this code as:

                case "GOLD":
                    double GetGoldPrice(double x, double y) => (x * y) * 0.8;
                    result = GetGoldPrice(5, 10);
                    break;

Here, all classes and interfaces are deleted. There is just a static method.

If you want to use the strategy pattern it must look something like:

IStrategy strategy = GetStrategy();
strategy.Calculate(...);

Here, GetStrategy() can return any object compliant with that interface and further code does depend on any concrete type.

Regarding naming, the classes do not have to be called "Strategy". I'd use the names IDiscountCalculator and GoldDicountCalculator. Or, instead of "Calculator" you could use "Model" or "Provider".


Tracks the number of calories consumed throughout the day

First, a small note. Your fields are public. There's no need for getters and setters if the fields are public.

Second, the getTodaysCalories() and check() methods seems a bit out of place in this class. I think it would be a lot better to have a 2nd class called DailyMeals. That class would then have a List<Meal> inside of it. That class would be the one to check if a duplicate is being added and what the daily totals are. However the checking for duplicates should be done at the time a meal is added. This would give the code more clarity and put the methods where they should be. As it stands now there isn't really any indication that a list of meals is for a single day and/or that it can't contain duplicates.

In addition, it may be some sort of rule that you can't have 2 of the same meal, but perhaps that would be better done by (instead of throwing an exception) prompting the user asking if they are sure they want to add a second lunch/dinner/breakfast etc. What happens if the person actually ate 2 meals and they consider them both lunch?

The general code structure could look something like this:

public class Meal {
    public enum Type {
        BREAKFAST,
        LUNCH,
        DINER,
    }

    private Type type;
    private double caloriesConsumed;

    public Meal(Type type, double caloriesConsumed) {
        this.type = type;
        this.caloriesConsumed = caloriesConsumed;
    }

    //ommitted getters, setters and equals for brevity...
}

public class DailyMeals {
    List<Meal> meals;

    //ommitted constructors for brevity...

    public void addMeal(Meal meal) {
        if (checkForDuplicate(meal))
            //throw error (or prompt if they're sure they want to add a duplicate)

        //rest of method code...
    }

    private boolean checkForDuplicates(Meal meal) {
        //code to check if multiple meals have the same type...
    }

    public int getCaloriesForDay() {
        //code returning total number of calories for the day
    }
}


== false is not very readable. Use ! instead.

If the "object value" is already of desired type (e.g. DateTime), it would be slower to convert it to string and then back again.

I would write instead

if (value is DateTime) return (DateTime)value;

I would not use var result = -999; as a return value.

If the conversion fails, you can either return Int32.MinValue (better than -999) or rather null.

Maybe also you would like to check for DBNull.Value?
So first I would check for null and DBNull.Value, then "value is DateTime" check and the last thing would be DateTime.TryParse.


Auto Filtering

  (auto-filtering would not solve this problem because I want the user to see the other files in the duplication group, i.e. see files from other owners with the same content as theirs)

Auto Filtering could definitely solve this problem.  The way to go about it would be to add a helper column, set the values in the column to "Show" if you want to show the column and then filter the helper column by the word "Show".  You could even hide this column.

Hiding Rows

  I had the idea of maybe hiding every row first (which I assume can be done much faster) and then de-hide what should be shown. But I couldn't find a command to mass-hide.

Yes, this undoubtedly faster.  Consider that you have 80K rows and you only need to see 1K rows.  Instead of performing 80K + 1 show/hide operations, hiding all the rows and then unhiding the rows you want will reduce the number of operations to  1K + 1.  Union() is much faster than Show/Hide. It would be even faster if you were to Union() all the ranges that need to be shown together and only have 1 hide operation amd 1 show operation.

Note: Concatenating the Range addresses is considerably faster than Union().  This can get somewhat complicated because there is a limit to the address length.  To maximize performance, use a combination of address concatenation and Union().

Option Explicit

MSDN - Option Explicit Statement

  Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.

One of the best of the "Best Practices" is to always declare and Type your variables.  The more information that you give the compiler the faster the compiler can catch errors.

Declaring Constants

MSDN - Declaring Constants

  By declaring a constant, you can assign a meaningful name to a value. You use the Const statement to declare a constant and set its value. After a constant is declared, it cannot be modified or assigned a new value.

A variable should be used when its value is either not know prior to compiling or will vary throughout the course of code execution.  A value that will remain always remain constant should be declared as a such.

 Const ownerCol As Long = 7

A Faster Way

Sub ShowUserDuplicates()
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Const OWNER_COLUMN As Long = 7
    Dim cell As Range, VisibleRows As Range
    Dim flagUser As Boolean
    Dim login As String

    login = Environ("Username")
    With Worksheets("Sheet1")
        'Hide All the Rows
        .UsedRange.Offset(2).EntireRow.Hide
        'Iterate though the cells in the Owner Column
        For Each cell In Range("A3", .Range("A" & .Rows.Count).End(xlUp)).Offset(0, OWNER_COLUMN - 1)
            If cell.Font.Bold Then flagUser = cell.Value = login

            If flagUser Then
                If VisibleRows Is Nothing Then
                    Set VisibleRows = cell
                Else
                    Set VisibleRows = Union(VisibleRows, cell)
                End If
            End If
        Next
        If Not VisibleRows Is Nothing Then VisibleRows.EntireRow.Hidden = False
    End With

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = False
    Application.EnableEvents = False
End Sub


Elegant solution to find a pair of Strings in a List

iA and iB can only take the values 0 and 1, so that

if ((1 == iA || 1 == iB) && (1 != iA || 1 != iB)) { ... }

can be simplified to

if (iA != iB) { ... }

Boolean variables would be more appropriate for this purpose, and the variable names can be improved, e.g.

boolean containsA = false;
boolean containsB = false;


Liveupdate phone number forms and test for international numbers

Regular expressions are a quicker way to get it done. Here's a naïve implementation that's (I believe) functionally equivalent to yours:

var mask = function (content) {
  var val = content.value.replace(/[^\d]/g, ''); // Remove anything that's not a digit
  if( val.length <= 10 ) { // US number
    content.value = val.replace(/^(\d{3})(\d{3})(\d*)$/, '($1) $2-$3');
  } else { // Other
    content.value = val.replace(/^(\d{2})(\d{3})(\d{3})(\d*)$/, '+$1 ($2) $3-$4');
  }
};

Here's a live demo

But this is far, far from perfect. There are many, many things to consider.

For starters, non-US numbers aren't necessarily longer than US ones. My own number is just 8 digits (or 10, if you count the country digits - or 12 if you use "00xx" instead of "+xx" for the country code). So if I wrote my phone number (as I normally would) as "+xx xx xx xx xx", it'd be formatted as a US number - which it isn't. If I wrote "00xx xx xx xx xx", I'd get "+00 ...", which is also wrong since it's an invalid country code.

On top of that, there's a ton of different local conventions for how to write phone numbers.

Point is that you can't go by the phone-number-length alone.

Regardless of how far you want to go with it, though, regular expressions will come in handy. Here's a nice interactive reg exp demo/tester to get you started.


Could this QuickSort be made more consise and "nicer"?

I'm more worried about the efficiency than conciseness.

Here are some sample inputs:

Equal new int[n]
Alternating Enumerable.Range(0, n).Select(x => x % 2).ToArray()
Sorted Enumerable.Range(0, n).ToArray()
Reverse sorted Enumerable.Range(0, n).Reverse().ToArray()

\begin{array}{ r | r | r | r | r }
 n & \text{Equal} & \text{Alternating} & \text{Sorted} & \text{Reverse sorted} \\
\hline
  10,000 & 7.9\text{s} & 1.8\text{s} & 7.8\text{s} & 7.7\text{s} \\
  100,000 & \text{N/A} & \text{N/A} & \text{N/A} & \text{OOM} \\
\end{array}

N/A is where I gave up waiting after a minute.

By comparison, Array.Sort on the same machine:

\begin{array}{ r | r | r | r | r }
 n & \text{Equal} & \text{Alternating} & \text{Sorted} & \text{Reverse sorted} \\
\hline
  100,000 & 4\text{ms} & 5\text{ms} & 2\text{ms} & 3\text{ms} \\
\end{array}

One advantage of QuickSort is that it can be done in-place, which is not happening here. If you're OK with allocating more memory, why not use Merge sort with its worst-case \$O(n \log n)\$ time guarantee?

Another issue is the choice of the pivot. Choosing the first element will give quadratic performance for sorted inputs. One option is to shuffle the input array before sorting; another is to choose the pivot at random (these are not the only options).

Robert Sedgewick* has a great page on QuickSort which touches on a lot of implementation issues. He also has a couple of implementations in Java, which translate easily to C#.

*Who did his Ph.D on QuickSort under Don Knuth, so well worth listening to :)


Find array index with element equality in Python

Better tests

Before anything, let's improve the test suite so that we can feel more confident updating the code.

At the moment, the tests:

rely on meaningless values printed on standard output which have to be compared to values in the comments - we'll see quickly why this is something to avoid
have somes values "untested": value for test1 is not printed
have variables with names that does not convey much meaning (testXXX)

Let's see how we can improve this. We could:

get rid of the testXXX variables
rename all arrYYY variables as arr
use assert to checking everything is working properly. If we want to do things properly, we could use a unit test framework such as unittest.

At this stage, we have:

def test_index_equals_value_search():
    arr = [-8,0,2,5]
    assert index_equals_value_search(arr) == 2
    arr = [-1,0,3,6]
    assert index_equals_value_search(arr) == -1
    arr = [0,1,2,3]
    assert index_equals_value_search(arr) == 0
    arr = [-6,-5,-4,-1,1,3,5,7]
    assert index_equals_value_search(arr) == 7

which gives:

Traceback (most recent call last):
  File "review212877.py", line 32, in <module>
    test_index_equals_value_search()
  File "review212877.py", line 28, in test_index_equals_value_search
    assert index_equals_value_search(arr) == 0
AssertionError

My job pretty much stops at this point but I'll give additional comments anyway.

You see how important my first comment was.
This error also shows something which is missing in your code: documentation. Indeed, the value returned is correct if we stricly refer to the function name. However, there should be a piece of docstring mentionning we want "the lowest index".
Algorithms relying on indices and in particular binary search are very easy to get wrong and are not always easy to test. However, a function doing the same thing using linear search is very easy to write. If I were you, I'd write such a function and use it to write a pseudo-oracle:

def index_equals_value_search_linear(arr):
    for i, x in enumerate(arr):
        if i == x:
            return i
    return -1

More comments

Style

Python has a style guide called PEP 8 which is worth reading and trying to apply.

Among other things, it says:

  Use 4 spaces per indentation level.


The game logic is broken in many respects.
First, the game may reach an "insufficient material" condition, in which checkmate is impossible. Infinite loop right away.
Second, the game may get into a stalemate. There is no legal moves in a stalemate, so pact would reject anything the user tries to enter. Yet another infinite loop.
Finally, the end of game condition shall be tested after each half-move. BTW, chess module conveniently offers a board.is_game_over() method, which encompasses everything above, plus three-fold repetition, plus 50 moves rule.

Board is printed only after a computer move. This is strange.

Listing the legal moves unconditionally is annoying. It should only be printed when the player enters an illegal one.

When you feel compelled to put a comment like
  def pact():  # Player's Action

it means that you fail to express yourself clearly in the code. Giving the function a meaningful name, like
  def player_action():

eliminates the need to comment it.


From a once over:

Be careful for js structure with cycles (like nodes in the DOM), you will get into an infinite loop.
This will also not find dupes, that may or may not be a problem
You also want to think about whether you want to prevent finding id in the inherited values with o.hasOwnProperty(p)
Dont check for if (obj.id === id) { in your loop, it's a waste of cycles. Check prior
Personally I tend to go either for the Spartan o or the full object, obj seems meh

I would use this version:

function findById(o, id) {
    //Early return
    if( o.id === id ){
      return o;
    }
    var result, p;
    for (p in o) {
        if( o.hasOwnProperty(p) && typeof o[p] === 'object' ) {
            result = findById(o[p], id);
            if(result){
                return result;
            }
        }
    }
    return result;
}


There are few improvements which I will recommend:

Use fetch API instead of XMLHttpRequest. Fetch is supported by almost every major browser and definitely serves as good replacement for XMLHttpRequest.
Utilize template literals properly. I can see template literals getting used properly at some places, but converting multiple strings into one template literal string will avoid cluttering. Also, instead of creating HTML as string, proper DOM elements can also be created using createElement but I am not sure which one is performant. Maybe someone else will give us some input here.
Utilize functional nature of JS to avoid cluttering. A lot of code can be broken even further into smaller logical pieces.
Use id in querySelector at line document.querySelector(".chat-list_members"). The reason being, you can have multiple HTML elements with same classname. This leads to a possibility of bug or wrong element getting selected. Id is a better choice in these cases.
Do error handling properly. The code seem to be handling cases when api is successful. A good code should also deal with cases when api fails or some error occurs.

Here is how, I will restructure the code:
function renderChatList() {
    fetch('http://localhost/domen/api/readCategories.php', { method: 'POST', })
      .then(response => response.json())
      .then(data => {
          data.forEach((category) => {
            getDoctorsGroup(category.id, category.title);
          });
      })
      .catch(error => {
        // Error handling here like alert/toast/popup etc
      });
}

renderChatList();

function getMemberHtml(doctorsArr, id){
    let html = ""
    doctorsArr.forEach(doctor => {
      if(doctor.category == id) {
        html += `

${doctor.name}

${doctor.job}

`;
      }
    })
    return html;
}

function getDoctorsGroup(id, title) {
    fetch('http://localhost/domen/api/readDoctors.php', { method: 'POST', })
      .then(response => response.json())
      .then(data => {
        let html = "";
        html += `

            ${title}

            ${getMemberHtml(data, id)}

`;

      // Insert group into list
      const container = document.querySelector("#chat-list_members");
      container.insertAdjacentHTML("beforeend", html);
    })
    .catch(error => {
      // Error handling here like alert/toast/popup etc
    });
}

Hope it helps. Revert for any doubts/clarifications.


Converts the JSON object to another structure of JSON

Your code had a lot of loops so I tried to squish it into one reducer for you. I think this will work;

var output = data.reduce(function (out, d) {
   var edges = [d.from, d.to].sort();
   var key = edges.join("<->");
   var obj = out.find(function (o) { return o.name === key; });
   if (!obj) {
     obj = {
       name: key,
       from: 0,
       to: 0
     };
     out.push(obj);
   }
   obj.to += edges[0] === d.from ? d.count : 0;
   obj.from += edges[1] === d.from ? d.count : 0;

   return out;
 }, []);

console.log(output);

Output:

[
  {
    "name": "B<->D",
    "from": 45,
    "to": 44
  },
  {
    "name": "A<->B",
    "from": 247,
    "to": 254
  },
  {
    "name": "C<->D",
    "from": 211,
    "to": 208
  },
  {
    "name": "A<->C",
    "from": 41,
    "to": 46
  },
  {
    "name": "A<->D",
    "from": 38,
    "to": 10
  },
  {
    "name": "B<->C",
    "from": 55,
    "to": 56
  }
]

Here's an example on JsBin

Reducers are super powerful when you need to convert an array into a different array or value.

In this case I'm iterating over the data array, and creating the key (A<=>B) by sorting the from and to values.

Then I check the output to see if we've already used that key, if so we append to that existing object, if not then we create it.


Optimisation XML handling within vb.net application

The indentation makes your snippet quite hard to read - the VB.NET syntax for inline delegates is fairly bulky (at least compared to C#), I'd give it more air; being able to read the code is step one.

Dim lst = (From t In DocElet.ChildNodes
           Select ID = t.item("ID").outerxml).Distinct()
                                             .ToList()

Parallel.For(0, lst.Count,
         Sub(i)
             Dim P As XmlElement = GetElement(lst(i))
             Dim ls = (From t In DocElet.ChildNodes
                       Where t.item("ID").innerText = P.InnerText
                       Select t)

             Parallel.ForEach(ls,
                      Sub(D)
                          Dim verif_date As String = D.Item("DAD").InnerText
                          Sej.ID = D.Item("ID").InnerText
                      End Sub)
         End Sub)

Ok. So you're running a Parallel.For, and inside that, you're running a Parallel.ForEach. That's quite a lot of overhead just there, it's likely that you're shooting yourself in the foot here, I'd first remove the inner Parallel.ForEach:

Parallel.For(0, lst.Count,
         Sub(i)
             Dim P As XmlElement = GetElement(lst(i))
             Dim ls = (From t In DocElet.ChildNodes
                       Where t.item("ID").innerText = P.InnerText
                       Select t)

             For Each foo In ls
                 Dim verif_date As String = D.Item("DAD").InnerText
                 Sej.ID = D.Item("ID").InnerText
             Next
         End Sub)

What's the purpose of verif_date? If it's not used, remove it:

             For Each foo In ls
                 Sej.ID = D.Item("ID").InnerText
             Next

Now the outer loop is making yet another selection:

             Dim ls = (From t In DocElet.ChildNodes
                       Where t.item("ID").innerText = P.InnerText
                       Select t)

I'd try to flatten that. I'm not very familiar with the LINQ syntax in VB.NET, but what you want is a SelectMany, where you'd select the child nodes where "ID"'s inner text matches the element's inner text for the node you're iterating - in other words the ls query gets outside the outer loop and into the lst query, so you only need a single loop (which can probably run in parallel).

If the XML is massive, it could be worth trying some PLINQ:

Dim lst = (From t In DocElet.ChildNodes
           Select ID = t.item("ID").outerxml)
          .Distinct()
          .AsParallel()
          .SelectMany(...)
          .ToList()

Now you can iterate lst with Parallel.ForEach (time it with a normal For Each first) and do your thing.

As an aside, I have to say your naming is inconsistent and hard to follow: Sub(i) looks good (Sub(index) would be better), Sub(D) doesn't. I realize VB.NET isn't case-sensitive, but if you're going to have a convention to make function parameters camelCase, by all means stick to it. lst would probably be better off as elements or whatever makes sense - use real, readable words for your identifiers, not just arbitrary abbreviations.


Things you did well

You initialize your variables when you declared them.
You initialize variables inside of your for loops.(C99)
Your pointer arithmetic looks pretty sound.

Things you can improve

Efficiency/Algorithm

Unfortunately, bubble sort is not a very good sorting algorithm if you are looking for speed.  Its average case performance is \$ O\left(n^{2}\right) \$.
If you are looking into greater speed with your sorting function, look at a quicksort algorithm.  Its average case performance is \$ O\left( n \log n \right) \$.

User experience

Is shutting down the program really necessary when your linked list doesn't actually exist, or that the size of your array is less than one?  Do something more useful than assert(), and return a specific error code that you can handle later on in your code.  This will greatly help you in debugging too.

Makefile

Makefile variables - Right now your Makefile isn't very expandable.  Variables help out a lot with that.

Put your compiler names into variables.

CXX = g++
CC = gcc

This is something I like to do, however, some variables like CC are declared already, so you generally don't need to.
Put your final executable into a variable name.

EXECUTABLE = bubble

Put your sources into a variable name.

SOURCES = bubble.c

Put your objects into a variable name.

OBJECTS = $(SOURCES:.c=.o)

.c.o:
    $(CC) $(CFLAGS) -o $@ $<

All of your compiler flags should be in one variable.  And tack on a linker flag variable while we are at it, for futures sake.

CFLAGS = -std=c99 -Wall
LDFLAGS =

Calling the variables is now a lot more easy and flexible.

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) -o $@ $<

Compiler flags - get the most out of your compiler so that you can code better.

You should change the standards you are using to C11 with --std=c11
-g adds symbols for debugging.  Without it, your debugger won't be able to give you variable or function names.  The don't slow down the program, and we don't care if the program is a kilobyte larger, so there's little reason to not use this.
-O3 indicated optimization level three, which tries every trick known to build faster code.  If, when you run the debugger, you find that too many variables have been optimized out for you to follow what's going on, then change this to -O0.

If you want to go above and beyond, here are all of the compiler flags I use.

CFLAGS = -std=gnu11 -c -s -O3 -Werror -Wall -Wextra -Wformat=2 -Winit-self -Wswitch-enum -Wstrict-aliasing=2 -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline -Wdisabled-optimization -Wunused-macros -Wno-unused

Standards

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

  C99 & C11 §5.1.2.2(3)

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

Syntax/Styling

Use Yoda conditions to prevent future bugs.

if (0 == sorted)

Placing the constant value in the expression does not change the behavior of the program. A common mistake is to accidentally assign a value instead of writing a conditional statement.  Using Yoda conditions will throw a syntax error if you accidentally do that, so your code won't compile.
You should return some status indicators from your sorting functions, so we can check that the sorting went okay.  This also makes for easier debugging.
You can simplify some of your test conditionals

if (sorted == 0)

That is actually harder for me to understand over my version.

if (!sorted)

If I were to read my version out loud, it would read "if not sorted", whereas your version is "if sorted is equal to 0".  It's odd, since you have this in one place, but not the other (always be consistent).
Declare your method parameters as void if you don't take any arguments in.

int main(void)