Ruby implementation for Hacker Rank connected cells in a grid

I really like clear and speaking method names, I quickly tried to refactor the first method but have had not much time, I hope this helps anyway.

I have not understand the other initialization of the visited hash in the area_count method (yet).

The new neighbors method indeed looks some kind of overloaded with information, no good idea yet how to change it, if needed at all as you described.

require 'json'
require 'stringio'

def connectedCell(matrix, visited = {})
    (0...matrix.length).each do |row|
        (0...matrix[0].length).each do |col|
        next if visited[[row, col]]
            if matrix[row][col] == 1
              return update_count_stats(row, col, matrix, visited)
            end
        end
    end
end

def update_count_stats(row, col, matrix, visited)
    result = area_count([row, col], matrix)
    visited.merge(result[1])
    result[0] > 0 ? result[0] : 0
end

def area_count(pos, matrix)
    q = [pos]
    visited = {}
    count = 0
    while q.length > 0
        tile_pos = q.shift
        if !visited[tile_pos]
            count += 1
            visited[tile_pos] = true
            q += neighbors(tile_pos, matrix)
        end
    end

    return [count, visited]
end

def neighbors(pos, matrix)
    right = [pos[0], pos[1] + 1]
    left = [pos[0], pos[1] - 1]
    top = [pos[0] + 1, pos[1]]
    bottom = [pos[0] - 1, pos[1]]

    top_right = [top[0], right[1]]
    bottom_right = [bottom[0], right[1]]
    top_left = [top[0], left[1]]
    bottom_left = [bottom[0], left[1]]

    positions = [right, left, top, bottom, top_right, bottom_right, top_left, bottom_left]
    positions.select{|npos| in_bounds?(npos, matrix.length, matrix[0].length) && matrix[npos[0]][npos[1]] == 1}
end

def in_bounds?(pos, number_of_columns, number_of_rows)
    pos[0] >= 0 && pos[0] < number_of_columns && pos[1] >= 0 && pos[1] < number_of_rows
end

number_of_rows = 4 # just for testing, was gets.to_i
number_of_columns = 4 # just for testing, was gets.to_i
matrix = Array.new(number_of_rows)

# sample input
# 1 1 0 0
# 0 1 1 0
# 0 0 1 0
# 1 0 0 0

number_of_rows.times do |i|
    matrix[i] = gets.rstrip.split(' ').map(&:to_i)
end
result = connectedCell matrix
puts result
```


Cosine similarity of one vector with many

I'm using Microsoft R (with Intel MKL) which makes matrix multiplications faster, but for fair comparison I set it to be single threaded.

setMKLthreads(1)

In my tests this pure R version cosine_x_to_m is twice faster than yours.

cosine_x_to_m2 = function(x,m){
  x = x / sqrt(crossprod(x));
  return(  as.vector((m %*% x) / sqrt(rowSums(m^2))) );
}

Rewriting rowSums(m^2) in C/C++ makes it even faster, about four times faster than the original.

library(ramwas)
cosine_x_to_m2 = function(x,m){
  x = x / sqrt(crossprod(x));
  return(  as.vector((m %*% x) / sqrt(rowSumsSq(m))) );
}

Initial performance:

Final version performance:


Insert array items into jQuery / JavaScript variable

I just see three issues:

You're making the view harder to read and you're missing a chance to reuse your code.
You're not properly escaping e-mail address (see RFC5322 and Wikipedia). If you don't then you're open to Code Injection attack (see later).
Some (older) browsers won't accept the trailing comma after the last array item (see MDN).

To solve the first issue you may write an extension method to build a JavaScript array string from an IEnumerable<T>:

static string AsJsArrayString<T>(this IEnumerable<T> items)
{
    var array = new StringBuilder();
    array.Append('[');
    array.Append(String.Join(",", items.Select(x => $"'{x}'")));
    array.Append(']');

    return array.ToString();
}

This code could be optimized and make more terse but I guess you understand the point:

$("#email").emailautocomplete({
    domains: @Html.Raw(Model.Organisations.Select(x => x.EmailDomain).AsJsArrayString())
});

This function may also be reused elsewhere.

Now we can look at second issue. E-mail addresses may contain invalid characters for a JavaScript string (for example " or '), JavaScript escaping is not the same as JSON escaping (done with Json.Encode()) but fortunately we have an ad-hoc function HttpUtility.JavaScriptStringEncode() (JavaScriptEncoder for .NET Core, see later):

static string AsJsArrayString(this IEnumerable<string> items)
    => "[" + String.Join(",", items.Select(x => "'" +  HttpUtility.JavaScriptStringEncode(x) + "'")) + "]";

Using String.Join() we also quickly fixed last issue in the list. If you can't/don't want to use an extension method you may also inline this function.

Last thing to change is that @Html.Raw() declaration into something less error-prone (I don't know you but I often forget @Html.Raw() if it does not always produce an invalid output):

@functions {
    public static string ToJsArrayString(IEnumerable<string> items)
    {
        return "["
          + String.Join(",", items.Select(x => "'" + HttpUtility.JavaScriptStringEncode(x) + "'"))
          + "]";
    }
}

Now we may simply write:

$("#email").emailautocomplete({
    domains: @ToJsArrayString(Model.Organisations.Select(x => x.EmailDomain))
});

HttpUtility is a .NET thing, in .NET Core you have a brand you class JavaScriptEncoder. Let's write an extension method for that:

public static string Encode<T>(this JavaScriptEncoder encoder, IEnumerable<T> items)
{
    return '[' + String.Join(",", items.Select(x => EncodeAndQuote(x))) + ']';

    string EncodeAndQuote(string text)
        => '"' + encoder.Encode(text) + '"';
}

Used like this:

$("#email").emailautocomplete({
    domains: @JavaScriptEncoder.Encode(Model.Organisations.Select(x => x.EmailDomain))
});

Code injection. Unfortunately I've not been clear, domain names can contain characters that need to be escaped. In case you think it's not an issue: would you allow your users to have a perfectly valid and usable email address that, however, will break your Javascript code (I guess in an administrative page) with a chance to execute arbitrary code? I would not.

Let's pick this perfectly valid e-mail address: john.smith@(here\I\can\write\anything)example.com. If not escaped then it will break your JavaScript code. An easy way to block your service until you will find the issue and fix the problem.

Worse that that, they can execute code with the privileges of the user of that page (and it seems an administrative page). Imagine they write this perfectly valid e-mail address:

john.smith@(",$.post('/api/customers/delete'),")example.com

Your JavaScript code isn't broken but you're executing code they injected, in this case an innocent AJAX POST.

In short: do not EVER trust user input, even when you think you do not need escaping.


"Functionalizing" this tree walking method and cleaning it up

You have selected the right tool (case classes) but are not using it properly.  In functional programming, a tree is an Algebraic Data Type.  In Scala, these are constructed with case classes but this is done with a sealed base trait (or abstract class) and a set of case classes which represent the different states/components of the type.  Here is how yours might look:

  sealed abstract class CrockPotTree[+A]
  case object Empty[A] extends CrockPotTree[Nothing]
  case class Node[A](value: A, negative: CrockPotTree[A],
      positive: CrockPotTree[A]) extends CrockPotTree[A]

Now all I need do is create functions which can add to, prune or walk the tree.  These will do so recursively, using pattern matching to do the appropriate thing depending on the type of the node.  There is more than one way to do this, but first let me say a few things about the example code above:

I used a sealed abstract as the base.  This class can only be used within this module and not elsewhere.  This means code for walking/fetching/manipulating CrockPotTrees will not fail because somebody extended the class and added something crazy and unpredictable.  It is abstract because only the derivative case classes have meaningful state (Empty, not Empty etc).
I could have used a trait.  There are still different opinions about this.
I have made it generic: CrockPotTree[+A] rather than CrockPotTree[String], so it can hande all types of objects.  You can use it (once an apply method has been added to the companion object) to create a CrockPotTree[String] or CrockPotTree[Int] or whatever.
I have made it covariant (CrockPotTree[+A] rather than CrockPotTree[A]).  This opens the possibility that if you add a Bear value to a tree full of Wolf objects, you will get back a CrockPotTree[Animal] rather than a simple error.
There is no need for Option[CrockPotTree] because of the Empty crockpot type.  I will explain later.

Now, the functions that work should be recursive (or fold over a path through the tree, which is a kind of recursion).  Why?  Because this is a recursive data type.  The first point to consider about this is that your steps type in WalkTree is wrong.  It is almost certainly better to have it a list than an array.  That way, each recursive iteration of walkTree can look something like this:

  steps match {
      Case Nil => // Return Some(value) if this is a Node or Nothing if it is an Empty
      Case x :: xs => walkTree(walk(x), xs)
  }

Note how walkTree still returns Option[value] even though Option[CrockPotTree] is no longer part of the structure.

Using the list is both faster and simpler than using an array.  That said, the next important question is where to put these functions.  You have 2 basic choices:

In the companion object.  In this case, functions should use pattern matching to decide what is the appropriate option for the particular case class.
Abstract methods defined in the abstract class (where appropriate) and concrete implementations in the case classes.

(If you use a trait rather than abstract class, you also have the choice of making some functions concrete in the parent trait).

Option 1 is the functional approach as seen in functional languages which don't offer OO.  I've written tree types in Haskell code and that's just how it is done there.  Option 2 is more OO (pattern matching goes away because each case class knows how to deal with itself) while still being good functional code if you do it right.  Option 2 is the way most functions in the Scala collections library are done.

Ironically, your function is very much Option 1 style despite the fact that you put it into the class.  It could be moved into the companion object with almost no modification, because it doesn't use polymorphism properly.

Since I have already given an example of how walkTree would look in Option 1 style (which is how your code is effectively done), here's how some simple functions would be done Option 2 stylee:

  sealed abstract class CrockPotTree[+A] {
    def isEmpty: Boolean
    def size: Int
  }
  case object Empty[A] extends CrockPotTree[Nothing] {
    def isEmpty = true
    def size = 0
  }
  case class Node[A](value: A, negative: CrockPotTree[A],
      positive: CrockPotTree[A]) extends CrockPotTree[A] {
    def isEmpty = false
    def size = positive.size + negative.size + 1
    /* This implementation of size is *not* tail recursive
     * and could create a stack overflow.  There is a better
     * way to do it but this way is chosen for simplicity here
     */
  }

Now, despite my warning about the stack overflow risk, look at the size function.  It works because an empty tree will return a size of zero.  A non-empty tree will add 1 (for itself) to the combined sizes of its positive and negative trees.  I want to make two points about this:

You should now have enough knowledge to create an Option 2 style walk, if you think hard enough.
This is why we seal algebraic data types so they cannot be extended.  My size function knows that the answer will always be 0 or more, because there are only two CrockPotTree types and they both return a proper value.  If some idiot added an new case class which returned something else (null, for example), things could explode.

My final two observations...

Firstly, you should have an apply function in the companion object, so that you could create a CrockPotTree like this

  val cpt = CrockPotTree(values)

where values is some collection of booleans and values which CrockPotTree will know how to build into a tree.  the apply function would need to call an append function recursively.  In Option 2 style, Empty and Node classes would both have their own recursive append function.

Secondly, I am not at all sure that Boolean is an appropriate type here.  You might want to create your own binary type (if that really is appropriate for this tree structure).  Guess what?  It would also be an ADT (algebraic data type).

I leave you with some useful links:

https://gleichmann.wordpress.com/2011/01/30/functional-scala-algebraic-datatypes-enumerated-types/
https://gist.github.com/mbbx6spp/5548937
http://twitter.github.io/effectivescala/#Functional%20programming-Case%20classes%20as%20algebraic%20data%20types


A couple of observations:

You said:

  ... there is an opinion that force-unwrapping should be avoided at any cost to not introduce an error-prone code which might crash the app.

Obviously, “at any cost” is too strong. If it was to be avoided at all costs, it wouldn’t be part of the language. But avoid it if you reasonably can. But we use it all the time (e.g. @IBOutlet references). So use it where appropriate, but avoid it if you can (without contorting yourself too much).
You go on to say:

  The idea behind having actions property force unwrapped instead of optional is because it’s actually not supposed to have a nil value, as it may get somewhat confusing: what is meant by nil?

I’d buy that argument if you didn’t then have a constructor that accepted nil and then supplied that default “close” action.

Personally, I’d embrace that it is optional and then have setUpActions handle the nil and empty scenarios.

Thus, perhaps:

public struct Action {
    let title: String
    let action: (() -> Void)?

    init(title: String, action: (() -> Void)? = nil) {
        self.title = title
        self.action = action
    }
}

class DescriptionViewController: UIViewController {
    private var actions: [Action]? = nil

    // MARK: Lifecycle

    init(actions: [Action]? = nil) {
        self.actions = actions

        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let actionStackView = UIStackView(axis: .horizontal, spacing: 20)
        view.addSubview(actionStackView)
        actionStackView.fillSuperView()
        setUpActions(for: actionStackView)
    }

    func addAction(_ action: Action) {
        if actions == nil { actions = [] }
        actions!.append(action)
    }
}

// MARK: - Private methods

private extension DescriptionViewController {
    func setUpActions(for stackView: UIStackView) {
        if actions?.isEmpty ?? true {
            actions = [Action(title: "Close")]
        }

        actions?.map { action in
            CustomButton(title: action.title) { [weak self] in
                    action.action?()
                    self?.dismiss(animated: true)
                }
            }
            .forEach { stackView.addArrangedSubview($0) }
    }
}

A few observations in the above:

Note, I’ve replaced the named tuple scenario with a custom type, Action. That seems better than repeating the tuple definition repeatedly.
I’ve also changed it to add that default “close” action if nil or isEmpty, though if you want it to only do that in the nil scenario, that’s a simple change, too.
You don’t need that strongSelf pattern in the “close” closure. self?.dismiss(...) achieves the same thing. Besides, if you did need that strongSelf pattern, since Swift 4.2, you’d just do:

guard let self = self else { ... }

See SE-0079.
I’ve deferred the setUpActions until viewDidLoad, permitting a flow where you initialize it without any actions and then subsequently set the actions (but presumably still before you present it).

I’ve also simplified this, eliminating this concept of adding actions after the view controller has already been presented. Go ahead and keep that stuff if you need it, but it has a hint of code smell.

For example, in what situation will you have this presented and then subsequently add new actions. That might not be a great UX (where the user may be in the processing of trying to tap the screen and then everything shifts around as new buttons are added, possibly resulting on a tap on something other than what they originally intended).
As part of this refactoring, I’ve also removed the observer on actions. In general, one should hesitate to add observer to a collection. E.g. what if the app developer is adding one button at a time to the array. By the time they add the fifth button, the setUpActions actions will have been called five times. Sure, you probably won’t do that, but it’s the sort of thing that bites you later on, when you forget what’s going on. Admittedly, there are likely so few items that it matters, but as a general rule, be careful with observers on collections. Besides, it’s better to defer the building of UIKit controls until viewDidLoad.
I’ve tweaked this so that the setUpActions routine adds the self?.dismiss(animated: true) itself. That way, when the app developer adds their own actions, they don’t have to worry about dismissing the DescriptionViewController itself, but rather every button will, after running the supplied closure (if any) will automatically, dismiss the DescriptionViewController. Then, you can do things like:

let actionSheet = DescriptionViewController()
actionSheet.addAction(Action(title: "Save") {
    // put save logic here
})

actionSheet.addAction(Action(title: "Cancel")) // no closure needed as we don't need to do anything

We can avoid the cruft of dismissing the DescriptionViewController from every added action.
By the way, you’ve said that you’ve omitted some 500 lines of code. Hopefully that’s an exaggeration or much of that code isn’t actually in the view controller (e.g. the UIStackView extension, the CustomButton, the UIView extension, etc.). But if you are saying that there are 500 more lines in the view controller, you might want to think creatively about refactoring that. (E.g. in the spirit of Dave DeLong’s A Better MVC.)


remove all nodes with same value in a linked list

Iterate through the list and remember the pointer to the first element in the group node. Then check if the current element has the same value as the first element in the group. Remove the current element and set some flag to remember to remove the first element in this group. Then if you have a new value, set the first element pointer to this value and do it all over again.


Not much to say: your code works as advertised, code is readable, formatting is consistent.

Things that could be better though: don't use raw arrays with new unless you absolutely have to. Prefer std::vector, it has a nice interface and manages its own memory. It also has a constructor that lets you fill it with a given value.

std::vector<int> cache(num+1, -1);
cache[0] = 0;
cache[1] = 1;

Then pass that as a std::vector<int>& to your Fibonacci function. No more open-coded loop, no more new[]/delete[], so less chances of bugs and leaks.

Another technique that would avoid that vector at all would be to have the Fibonacci function do its own memoizing, without external state. That's easier on the user, and you can do a more general technique with a static std::map in the function being memoized to keep the state. (This is not thread-safe as is, but a shared vector or raw array isn't either.)

Here's an example:

#include <iostream>
#include <map>

int fibonacci(int num)
{
  static std::map<int, int> cache{{0, 0}, {1, 1}};

  auto found = cache.find(num);
  if (found != std::end(cache)) {
    // For debugging purposes, to check that the cache is doing something
    std::cout << "Found in cache: " << num << " -> " << found->second << '\n';
    return found->second;
  }

  int result = fibonacci(num - 1) + fibonacci(num - 2);
  cache[num] = result;
  return result;
}

And the corresponding main: I've moved the call to fibonacci out of the printout statement, don't hide important function calls in there.

int main()
{
  int num;
  std::cout << "i: ";
  // TODO: input validation
  std::cin >> num;

  int res = fibonacci(num);
  std::cout << num << "th fibonacci number: " << res << std::endl;
}

Of course this is a bit overkill for the situation at hand. There are more general techniques, you'll find some for example here: Writing Universal memoization function in C++11.

The iterative approach is much more efficient and pretty simple. In pseudo code:

fib(n):
  prev = 0
  curr = 1
  i = 2
  while i <= n
    next = prev + curr
    prev = curr
    curr = next
    i++
  return curr


Good conduct of including numbers in css classes

Perfect naming in any language allowing freedom for your names are:

Descriptive. (Makes it clear what it means at a glance)
Short. (less chance for typos, types faster and therefore easier to work with.)

In your case, the names only mean to affect the text size. So appropriate names would be something like:

text-medium {
    font-size: 1.4rem;
}
text-big {
    font-size: 1.6rem;
}

Since this makes it clear what they do.


Write millions of lines to a file - Python, Dataframes and Redis

I'm not a hard core Pythonista, but a few points I can think of are:

The assignments of key1, val1, ... appear unneeded as they're used only once in the call to format()
Terminate each if with a continue, or use else, as it appears that only one branch is executed in each iteration of the range. Order the conditions according to data's expected distribution if possible (i.e. most frequently evaluated to true condition comes first)
Try writing less, e.g. see if you can use MSET to shave a few bytes in each iteration (times millions this may have significant effects ;))

Lastly, it looks that you're not using the last two arguments you pass to format, so if that isn't a typo you can remove them as well.


Groovy optimize method to convert JSON to map

In order to convert String to Map, use JsonSlurper:

new JsonSlurper().parseText(requestString)


It's good to have single method to control flow as you have in B, but this method should be mostly calling other methods of your class (you also call there checkQuantity for example, which is also in A). That way add is still very flexible - you can override those methods (probably protected methods, not public), that it calls or as last resort override that method itself.

If you think B is more readable, imagine, there would be something like this->addToCart instead of this bit (and that extracted to separate method):

   $product_id = $this->request->post->product_id;
    $cart = $this->getCart();
    $product = $shop->getProduct($product_id);

    $cart->items->add($product);
    $added = $cart->save();

I'd google for "single responsibility principle".


while i < arr.length

In your loop, we are only accessing the current element and not doing any index arithmetic.  Use arr.each{}.

    if hash.has_key? e
        hash[e] += 1
    else
        hash[e] = 1
    end

When we encounter a key, we just want to increment by 1.  If a key doesn't exist, use the default value and increment by 1.  You can initialize your hash to have a default value of 0 by hash = Hash.new(0).

# Find most common character
hash.each do |k,v|
    if(v > max)
        max = v
        ge = k
    end
end

This can simply be written using hash.max_by{} and it does the work for you of returning a key-value pair.

Putting it all together, you get

def most_common_letter(string)
  hash = Hash.new(0)
  string.split('').each{ |ch| hash[ch] += 1 }
  hash.max_by{ |ch,count| count }
end

And if you want to clean it up so its a single chained statement.

def most_common_letter(string)
  string.split('')
        .each_with_object(Hash.new(0)) { |ch,hash| hash[ch] += 1 }
        .max_by{ |ch,count| count }
end

  What are the disadvantages of my solution ?

The biggest issue is that it only returns 1 letter/count pair.  What happens if you call most_common_letter("aabb").  Your function returns the pair that is first encountered that sets max {'a', 2} rather than {{'a', 2}, {'b', 2}}.  If you want to return all of the max pairs, build your count hash, find the max value, then return all elements from your hash that has that max value using Hash#select{}.


Duplicating Rails model for a form with meta-programming

Few things I have noted in your design are listed below. Beware all of this is purely from a design perspective rather than application.

Source is defined as attr_accessor which essentially violates encapsulation. Inject it from outside in constructor call.(I am not able to understand why you have not gone for attr_reader instead of accessor.
Ideally self.compose can be split into different method calls. It is violating SRP by doing too many things at one place. That is same for other methods as well.
Speaking from a puritan view, the branched if condition is also a smell.

In general, metaprogramming is considered to be something which must be avoided unless you have enough justification to keep it.


Delete all occurrences of an item in linked list

Yes, your code can be improved by not handling the head as a special case. Yes, that means using a double-pointer, but the structure gets much more straight-forward and shorter:

void LinkedList::DeleteAllOccurences(int key) {
    Node** p = &head;
    while(*p)
        if((*p)->item == key) {
            Node* tmp = (*p)->next;
            delete *p;
            *p = tmp;
        } else
            p = &(*p)->next;
}


Run your comments and any UI text through spellcheck. In particular, your problem statement had a few errors in it.

for number in range(1, max_number + 1):
    sheet['A' + str(number+1)].font = font
    sheet['A' + str(number+1)] = number

Is this not equivalent to:

for col in range(1, max_number + 1):
    ind = f'A{col+1}'
    sheet[ind].font = font
    sheet[ind] = col

Note that you should never call something "number". Call it what it actually does (it's a column index). Also, factor out common expressions to a variable. The same applies in your code elsewhere.

I browsed through the openpyxl.utils.cell package and couldn't find anything like this: I suggest that you write a utility function that accepts two zero-based coordinate integers and outputs a ready-to-use row/column cell reference.


I have a writeOnFile() method with too many fwrite().  ...

A way to reduce fwrite() calls is to simply write all text to a large char buffer[] and then write that once per for (int i = 0; i < global_index; i++) loop.
Use the return vale of snprintf() to speed calculation of next offset.  Use  *printf() features for padding.
for (int i = 0; i < global_index; i++) {
    char buf[N];
    int offset = 0;

    //snprintf(strNumber, 50, "%f", instants[i]);
    //fwrite(strNumber, 1, strlen(strNumber), out);
    //for (int i = 0; i < strlen(header1) - strlen(strNumber); i++)
    //    fwrite(sp, 1, 1, out);

    //                                           vv---- pad on right
    int len = snprintf(buf+offset, N - offset, "%-*f", (int) (sizeof header1 - 1), instants[i]);
    assert(len >= 0 && len < N - offset);
    offset += len;

    //snprintf(strNumber, 50, "%d", playing[i]);
    //fwrite(strNumber, 1, strlen(strNumber), out);
    //for (int i = 0; i < strlen(header2) - strlen(strNumber); i++)
    //    fwrite(sp, 1, 1, out);

    len = snprintf(buf+offset, N - offset, "%-*d", (int) (sizeof header2 - 1), playing[i]);
    assert(len >= 0 && len < N - offset);
    offset += len;

    ....

    fwrite(buf, 1, offset, out);
}

Some other ideas to linearly improve performance.
Why run down string again to find length?
//snprintf(strNumber, 50, "%f", instants[i]);
//fwrite(strNumber, 1, strlen(strNumber), out);
int len = snprintf(strNumber, 50, "%f", instants[i]);
fwrite(strNumber, 1, len, out);

No need for strlen() for a constant string
char header1[] = "Instant        ";
// fwrite(header1, 1, strlen(header1), out);
fwrite(header1, 1, sizeof header1 - 1, out);

Questionable "safe:" concerns
sprintf() is certainly faster (or as fast) as snprintf() ....
// snprintf(strNumber, 50, "%d", playing[i]);
sprintf(strNumber, "%d", playing[i]);

... yet by some coding standards, better to use snprintf() even though "%d" will not overfill 50 char array.
What is curious about this "safe" code is the lack of checks of fwrite() return, a more likely issue.
    // fwrite(strNumber, 1, strlen(strNumber), out);
    size_t nmemb = strlen(strNumber);
    size_t written = fwrite(strNumber, 1, nmemb, out);
    if (written != nmemb) Handle_Error();

Watch out for unsigned bugs
Consider what happens when strlen(header1) < strlen(strNumber)
for (int i = 0; i < strlen(header1) - strlen(strNumber); i++)

is like
for (int i = 0; i < strlen(header1) + (SIZE_MAX - strlen(strNumber) - 1); i++)

due to unsigned  math wrap around.
Better coded as
for (size_t i = strlen(strNumber); i < strlen(header1); i++)
// or
for (size_t i = strlen(strNumber); i < sizeof header1 - 1; i++)

Watch out for long "%f"
"%f"  may takes 100s  of characters for large FP values.
Consider "%g".

Curious that OP's code did not start with fprintf() rather than snprintf()/fwrite().  This is another option.
Conceptually, fprintf() is effectively doing the char buffer[] mentioned above albeit without many fwrite()/fprintf() calls.
Switching to fprintf()  and using the suggested padding format will be sufficient for a first level speed-up.
For me, I do like the idea of writing a line with one I/O call.   It is symmetric with the idea of reading one line on input code with fgets().


Checking for viruses in uploaded files using ClamAV

there seems to be logical falacy: what if ClamAVClient.isCleanReply() returns false but no exception is thrown? there is no else clause there, and checkVirus would return no virus found.
instead of returning String, why doesn't checkVirus() re-throw the exception? that way, it can also return a String of a virus name (or whatever is produced from ClamAVClient)
instead of passing the String, make it public. then any class can refer to it as FileUpload.NO_VIRUS_FOUND
better still, make an enum out of the constant. that way, you can add values to the enum (like VIRUS_FOUND ...)

though it is arguable, Coding by exception is considered an anti pattern.  Exceptions should be reserved for error conditions, not as indicator that a virus  was found.

EDIT:

with regards to the question how to implement pt 2:
First, I would create a custum exception that signifies a failed virus check

public class VirusCheckException extends Exception {
    public VirusCheckException(Throwable cause) {
        super(cause);
    }
    public VirusCheckException(String message, Throwable cause) {
        super(message, cause);
    }
    // also rest of constructors...
}

then, instead of returning the exception message, throw the custom exception. the return value is freed to return more rich data from the scan (if possible):

public static String checkVirus(FileConfig fileconfig, InputStream inputStream, String noVirusFound)
throws VirusCheckException {
    try {
        ClamAVClient cl = new ClamAVClient(fileConfig.getClamavHost(), fileConfig.getClamavPort(), DEFAULT_TIMEOUT);

        Object response = cl.scan(inputStream);
        if (ClamAVClient.isCleanReply(response)) {
            return noVirusFound;
        } else {
            return ClamAVClient.getVirusName(response);  // assuming there is such...
        }
    } catch (Exception e) {
        return new VirusCheckException("Virus Found!", e);
    }
}

now you will have to catch that exception in the callng method and handle it:

public void checkFile(...) {
    try {
        antiVirusResult = FileCheckClass.checkVirus(getConfig(), file.getInputStream(), NO_VIRUS_FOUND);
    } catch (VirusCheckException e) {
        generateAntiVirusMessages(e.getMessage());
        throw new ValidatorException(msgs);
    }
}


This is already pretty short. Making it shorter doesn't seem a good objective, and risks hurting readability.
That being said, there are a few things you could do.

You could do this in one step:

min_coin = [sys.maxint] * 20
min_coin[0] = 0

Like this:

min_coin = [0] + [sys.maxint] * 19

While at it, why are there 20 elements? Your program will find the minimum number of coins up to 19, and I have a feeling that you actually want it for 20. In which case you would need:

min_coin = [0] + [sys.maxint] * 20

And then use range(21) in the loop. However, you shouldn't hard code this number, give it a name, like target_amount, and use that.

Speaking of names, many of the names in your code can be better:

min_coin is a list, so plural min_coins would be better
min_of_i is actually an amount

One more optimization is possible by flipping the order of the nested loops.
In the current code you need an if statement to skip the amounts that are too small for the coin.
If you make the loop over coins to be the outer loop,
then you can set a starting value for the inner value to make the if statement unnecessary.

def get_min_coins(coins, target_amount):
    n = len(coins)
    min_coins = [0] + [sys.maxint] * target_amount
    for i in range(1, n + 1):
        for j in range(coins[i - 1], target_amount + 1):
            min_coins[j] = min(min_coins[j - coins[i - 1]] + 1, min_coins[j])
    return min_coins


I find the way you go back and forth between as and x a bit annoying.  You should be able to collapse the nested match into one match that covers three cases.

The :+ operator, which appends an element to a sequence, should be avoided at all costs, because it involves traversing to the end of the sequence.  That makes your algorithm O(n2), when it should ideally be O(n).

Anyway, the solution can be much simpler than that.

def toPairs[A](xs: Seq[A]): Seq[(A,A)] = xs.zip(xs.tail)


Number Guessing Game in C++ without global varibles

rand() is bad; don't use it.

Instead, use the <random> library for generating random numbers:

static std::mt19937_64 engine(std::random_device{}());
std::uniform_int_distribution<> dist(1, 100);
std::cout << dist(engine);

You'll then have:

int makeNum() {
    static std::mt19937_64 engine(std::random_device{}());
    std::uniform_int_distribution<> dist(1, 100);
    return dist(engine);
}

The name calc() doesn't make sense with the expected return and it doesn't even calculate anything. You can rename it to hasWon() and rename the variable to won.

Moreover, I would move the output to main() since it shouldn't really be responsible for printing to the console. Just have it do the comparison and then return the value.
Do you really need the program to sleep? It may not be worth that call, plus it prevents it from being portable to other systems. You can always use std::cin.get() to "pause" the program by asking the user to enter a character before proceeding.


Calculating shortest possible route between two given nodes

I think you choice of a data table is really bad. You should consider creating nodes similar to an trie.
struct node {
    unsigned houseID;
    unsigned firstVisited = 0;
    std::vector<node*> houseLinks;
    explicit node(unsigned id) : houseID(id) {}
};

Then your initial code would look like this:
unsigned numHouses, numLinks;
std::cin >> numHouses >> numLinks;

std::vector<std::unique_ptr<node>> houses;
for (unsigned house = 0; house < numHouses; ++house) {
    houses.push_back(std::make_unique<node>(house));
}

I have to say, that my compiler hat home complains about make_unique. In any case this should work too houses.push_back(std::unique_ptr<node>(new node (house)));

Now you have to add the links between the houses
for (unsigned link = 0; link < numLinks; ++link) {
    unsigned house1, house2;
    std::cin >> house1 >> house2;
    houses[house1-1]->houseLinks.push_back(houses[house2-1].get());
    houses[house2-1]->houseLinks.push_back(houses[house1-1].get());
}

Your checking part seems right, although i would suggest to group everything as it belongs:
unsigned start, end;
std::cin >> start >> end;
start--;end--;

std::vector<bool> visited(numHouses, false);
visited[start] = true;

EDIT: this is no longer relevant but i dont know how to cross it out. However, i would suggest, that you keep track of your jump length via the queue. So rather than haveing a queue<node*> have a queue<std::pair<node*, size_t>>
New: I would now suggest to store the first visited field in the struct itself, which simplifies the code a lot
std::queue<node*> jumpQueue;
jumpQueue.push(houses[start].get());

Now while you are adding something to the queue you just increment the jump index.

Now to your breadth first search. Obviously you can ignore any occurrence of a house that was reached before, as that would lead to an at least equally large jumping series.
size_t result = 0;
while (!jumpQueue.empty()) {
    auto oldHouse = jumpQueue.front();
    jumpQueue.pop();
    for (auto newHouse : oldHouse->houseLinks) {
        if (!visited[newHouse->houseID]) {
            visited[newHouse->houseID] = true;
            newHouse->firstVisited = oldHouse->firstVisited+1;
            jumpQueue.push(newHouse);
        }
        if (newHouse->houseID == end) {
            result = oldHouse->firstVisited+1;
            std::queue<node*> swapQueue;
            std::swap(swapQueue, jumpQueue);
        }
    }
}

Note, that one can directly terminate the traversal of the trie by swapping the current queue with an empty one.

Finally now that you have the result, or 0 if you never found the villan then print result. All together you now have:

Solution
#include <iostream>
#include <memory>
#include <queue>
#include <vector>

struct node {
    unsigned houseID;
    unsigned firstVisited = 0;
    std::vector<node*> houseLinks;
    explicit node(unsigned id) : houseID(id) {}
};

int main()
{
    unsigned numHouses, numLinks;
    std::cin >> numHouses >> numLinks;

    std::vector<std::unique_ptr<node>> houses;
    for (unsigned house = 0; house < numHouses; ++house) {
        houses.push_back(std::unique_ptr<node>(new node (house)));
    }

    for (unsigned link = 0; link < numLinks; ++link) {
        unsigned house1, house2;
        std::cin >> house1 >> house2;
        houses[house1-1]->houseLinks.push_back(houses[house2-1].get());
        houses[house2-1]->houseLinks.push_back(houses[house1-1].get());
    }

    unsigned start, end;
    std::cin >> start >> end;
    start--;end--;

    std::vector<bool> visited(numHouses, false);
    visited[start] = true;

    std::queue<node*> jumpQueue;
    jumpQueue.push(houses[start].get());

    size_t result = 0;
    while (!jumpQueue.empty()) {
        auto oldHouse = jumpQueue.front();
        jumpQueue.pop();
        for (auto newHouse : oldHouse->houseLinks) {
            if (!visited[newHouse->houseID]) {
                visited[newHouse->houseID] = true;
                newHouse->firstVisited = oldHouse->firstVisited+1;
                jumpQueue.push(newHouse);
            }
            if (newHouse->houseID == end) {
                result = oldHouse->firstVisited+1;
                std::queue<node*> swapQueue;
                std::swap(swapQueue, jumpQueue);
            }
        }
    }

    std::cout << result << "\n";
}


Transform an entity from a type to another

public static dynamic Transform(Type type, string path)

If I should return an object of any type I'd rather use the object type for it then dynamic. I don't know how you actually use it so I assume that all objects have some set of common properties but don't share a any common interface.

In that case I think it would make more sense to create an artifical wrapper for those objects so that you can read those properties (or methods) without having to use dynamic everywhere.

public class Fruit // = ExternalDllTwoEntityWrapper
{
    private readonly dynamic _value;
    Fruit(object obj) => _value = obj;
    public string Name => (string)_value.Name;
}

Whether you use dynamic or reflection internally to access those properties is another question.

If you however can change one of those external dlls then an abstraction would be the obvious way to solve this:

public interface IFruit
{
    string Name { get; }
}


Visualize the runtimes of list algorithms

An even more vital question than does it deviate from best practices, is whether it actually does what you intend for it to do! Does it accurately time exection of the function in you are testing?

I believe not due to the following reasons:

Using time one a single run is at best inaccurate. Any code when run only once is kind of a random indicator as to how long time it'll take to do on the average. The shorter time it takes to execute, the more repeats you should have. You might also run into issues related to which current platform you are on, and imprecision in the time.time() call, as the documentation only promises a precision of a second.
You're setting up the time testing method within the actual time taking. You're timing on the outside of the runtime_generator, and do functools.partial and ThreadPoolExecutor within that function. In the best situations this only skew all of your data, in a more likely situation your method disappears in the time to set up the test run. This effect will be worse the faster your tested function are.

Lets say that test setup takes 100 ms, and your method 1 ms for 1 item, and 10 ms for 1000 ms. Your total time will vary from 101 ms to 110 ms, so you'll likely conclude that it is almost constant time, as 101 ms ~ 110 ms, but the real situation is that is has ten-doubled, 1 ms ~ 10 ms.

Best practice in Python, seems to use the timeit module for timing executions. This module can setup your runs, and execute them multiple times and eliminate some of these caveats.

Although you really gotta keep your head straight even when using this module, as timing execution depends on a lot of sub parameters like:  operating system, python interpreter, other load on testing platform, memory issues, code issues, sub effects of memoisations or other programming paradigm, and list goes on.


Coloured bash prompt including git status and previous exit code

Solid script, nicely done.

"less lines of code"

__colour_enabled is used only once,
when setting __colourise_prompt, which in turn is also used only once.
It seems an unnecessary indirection.
You could drop this line:

unset __colourise_prompt && __colour_enabled && __colourise_prompt=1

And change this condition:

if [[ $__colourise_prompt ]]; then

To this:

if __colour_enabled; then

Some color variables are defined but never used.
But I would keep them anyway,
in case you (or somebody else) want to adjust the colors later
(they are not exactly easy to remember).

To shorten the code, you could rewrite some of the if statements in cmd && ... || ... form, but I don't recommend that.
In its current form it's nicely readable and good that way.

Undefined variables

When you detect that colors are enabled, you set a bunch of variables, for example Red, BRed, Mag, None. If colors are not enabled, you don't clear these variables, but they may be used anyway later in the script.

Although it may seem unlikely that these variables are set outside this script, it can happen,
and that will be confusing and possibly annoying.
The clean solution is to make sure to set those variables to blank when colors are not enabled.

Condition without pattern matching

The == operator in [[ is useful for pattern matching.
In this example you don't need pattern matching,
so I suggest to replace it with =, which will do simple literal comparison.

if [[ ${EUID} == 0 ]]; then

Coding style

You mixed two styles of function declaration:

__colour_enabled() {
    # ...
}

__set_bash_prompt()
{
    # ...
}

It would be better to use consistent style (I prefer the first one).


Can I optimize two for loops that look for the closest zip code based on lat/lon?

So a better approach may be to :

covert your myFile to a Numpy array [[lat0, long0], [lat1, long10], ...].

lat_long = np.asarray(myFile)

Sort this array on latitude

lat_long = np.sort(lat_long, axis=0)

find the closest western points to the target point

closest_point_to_west = lat_long[lat_long[:, 0] >= myPoint[0]]

Do the same for the other wind directions, this will give you the four closest points using Numpy's efficient slicing operations and you can do a distance measurement on only 4 of the points and not all of them.


Return the correct object type in Javascript

1)   I am currently wondering if the following piece of Javascript code could be simplified?

yes, something like this, would be more accurate and simpler to read

var defaultValues = {
  "Array": [],
  "Boolean": true,
  "Object": {},
  "String": ""
}

function getObjectProperty(object,field,type){
  if (object.hasOwnProperty(field)) return object[field]
  return defaultValues[type]
}

  2) I would like to return the correct {},[],"" without having to pass a type as argument. Is it possible?

This is only possible, if the field exist.
Otherwise whats the type of foo in {bar: "bar"} ?

But what are you actually doing:

check if the field is in the object
If true, return the value, otherwise a defaultValue

So you could simplify it to this:

function getValue(obj, field, defaultValue) {
   return obj.hasOwnProperty(field) ? obj[field] : defaultValue
}


You're not quite correct saying that IConnection has no ideas about protocol layer - in your defininition IConnection provides events about authentication process. So your code should have some connections between IConnection and protocol layer. I have no clue about entire relationships between layers in your application, but I can suggest some method:

provide function for calling events (like you suggested)
implement IConnection in protocol layer
realization of IConnection listens what happens in protocol layer (i.e. AssignAuthentificationService function)
implement IAuthentifiedConnection that knows about protocol layer


You chose to represent the “list of sequences” as a dictionary

var sequences: [Int: [Int]] = [:]

and here you test if a sequence for the given index already exists, and then either append a new element or create the initial sequence for that index:

if var sequence = sequences[seq] {
    sequence.append(y)
    sequences[seq] = sequence
} else {
    sequences[seq] = [y]
}

That can be greatly simplified by using a subscript with a default value:

sequences[seq, default: []].append(y)

But actually, instead of representing the “list of sequences” as a dictionary I would represent it as an array (of arrays) instead:

var sequences: [[Int]] = Array(repeating: [], count: n)

The number of sequences is a-priori known, so that there is no advantage of using a dictionary. Appending a new element to a sequences (query type 1) then becomes

sequences[seq].append(y)

and for query type 2 we get

lastAnswer = sequences[seq][index]
answerlist.append(lastAnswer)

without the need of forced-unwrapping for the dictionary subscripting.

This should also be more efficient, because (array) index lookups are faster than dictionary lookups.

Some more remarks:

The type of a variable should not be part of the variable name, e.g. answers instead of answerList.
Multiple (related) assignments can be combined to a tuple assignment, e.g.

let (queryType, x, y) = (query[0], query[1], query[2])

We know that the query type can only be 1 or 2, but a fatalError() in the default case helps to find programming errors.

Putting it together, the function could look like this:

func dynamicArray(n: Int, queries: [[Int]]) -> [Int] {
    var sequences: [[Int]] = Array(repeating: [], count: n)
    var lastAnswer = 0
    var answers = [Int]()
    for query in queries {
        let (queryType, x, y) = (query[0], query[1], query[2])
        switch queryType {
        case 1:
            let seq = (x ^ lastAnswer) % n
            sequences[seq].append(y)
        case 2:
            let seq = (x ^ lastAnswer) % n
            let index = y % sequences[seq].count
            lastAnswer = sequences[seq][index]
            answers.append(lastAnswer)
        default:
            fatalError("Bad query type")
        }
    }
    return answers
}

In addition, it seems that most of the time is spent while reading the input data into the queries array, done by the (HackerRank supplied template) code

guard let queriesRowTemp = readLine()?.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) else { fatalError("Bad input") }

let queriesRow: [Int] = queriesRowTemp.split(separator: " ").map {
    if let queriesItem = Int($0) {
        return queriesItem
    } else { fatalError("Bad input") }
}

Instead of removing trailing whitespace with a regular expression search we can split the input row and ignore empty components:

guard let queriesRowTemp = readLine() else { fatalError("Bad input") }
let queriesRow: [Int] = queriesRowTemp.split(separator: " ",
                                             omittingEmptySubsequences: true).map {
    if let queriesItem = Int($0) {
        return queriesItem
    } else { fatalError("Bad input") }
}

In my test that cut the time to read 100000 queries down from 3.7 to 1.7 seconds.


From the readability point of view, I'd suggest to keep some maximum line length, like 72 or 80 characters. Beyond that it's difficult to read. Also instead of having Either (Either X Y) Z, declare your own data type with 3 constructors. Not only it'll be simpler, but the constructor names will also be more descriptive and it'll be easier to understand what's going on. You should also document the function better, it's not clear what the Int argument is without thoroughly inspecting the code. A small improvement is also replacing nested ifs with a case statement.

In general, I'd say that it's not really possible to make a genuine single-pass solution.

Obviously we can't avoid checking the last element, if the list is a palindrome, and we need to have the first element to compare it to. So we'll always have to either get to the last element at the beginning, or keep the elements as we traverse the list, to have them for comparison when we get to the end,  So we can't get to the situation when we just traverse the list from the beginning to the end, releasing the elements already traversed.

In your case, you're also traversing the list twice, although it's somewhat hidden. The first pass is the recursive call to walk, which gets to the end of the list. And the second traversal is occurring in the line

Left (Right (y:ys)) -> if y == x then
                            (if n > 0 then Left (Right ys) else Right True)
                          else Right False

where we're traversing ys as walk returns to its parent call.

(The above nested ifs can be rewritten as

  ... -> case () of
           _ | y /= x    -> Right False
             | n > 0     -> Left (Right ys)
             | otherwise -> Right True

using case.)

Furthermore, since walk calls itself recursively and examines the result of the recursive call, it can't be optimized to tail recursion, so you're building a chain of n calls on the stack.

Another thing to notice is that the whole original list is kept in memory until the whole chain of walks finishes.

My attempt to solve this problem would look like this:

isPal' :: (Eq a) => [a] -> Bool
isPal' xs = f [] xs xs
  where
    f ss xs []              = ss == xs
    f ss (_:xs) [_]         = ss == xs
    f ss (x:xs) (_:_:es)    = f (x:ss) xs es

We're traversing the list at two different "speeds" at the same time in a tail-recursive loop, to get to the middle. During that we compute the reverse of the traversed part in ss. When we hit the middle after n/2 steps, we just compare the accumulated reversed first half with the rest. The combined length of ss and xs is always n and if we find out in the middle a difference, like in "aaabcaaa", we finish and release resources early.

Since all suggested algorithms are O(n), it's hard to decide which one will be more efficient just by reasoning. We'd have to do some measurements, for example using the criterion package.

Update: The problem could be actually solved in a genuine one pass using a rolling checksum, at the cost of having false positives in (rare) cases of hash collisions. Just compute two rolling checksums while traversing the list, one forwards and one backwards, and compare them at the end.

 import Control.Arrow ((&&&), second)
 import Data.Foldable (foldMap)
 import Data.Function (on)
 import Data.Hashable
 import Data.Monoid
 import Data.Word

 -- see https://en.wikipedia.org/wiki/Rolling_hash
 -- and https://en.wikipedia.org/wiki/Lehmer_random_number_generator#Parameters_in_common_use
 modulus :: Word64
 modulus = 2^31 - 1

 expG :: Word64
 expG = 7^5

 data RKHash = RKHash { rkExp :: Word64, rkVal :: Word64 }
   deriving (Eq, Show)

 inject :: (Hashable a) => a -> RKHash
 inject = RKHash expG . (`mod` modulus) . fromIntegral . hash

 instance Monoid RKHash where
     mempty = RKHash 1 0
     mappend (RKHash e1 v1) (RKHash e2 v2) =
         RKHash ((e1 * e2) `mod` modulus) ((v1 * e2 + v2) `mod` modulus)

 isPalindrome :: (Hashable a) => [a] -> Bool
 isPalindrome = uncurry (on (==) rkVal) . second getDual
                . foldMap ((id &&& Dual) . inject)


Resume code of a SQL selecting function in Java

Pool your connections

To set up a DB connection is usually very expensive, relative to the other tasks your application does:
The steps which are necessary to get a connection go right through:

your application
the JDBC Driver
your application's JVM
the network stack on the application machine
the network
the network stack on the DB machine
the DB's authentication mechanism, checking roles and grants etc.

.. the acquired connection is then passed back through the same channels

If you do this for every Statement you would like to run on the DB, your application will spend most of its time waiting for connections to be established (and torn down after the Statement).

I would strongly suggest to read up on JDBC connection pooling.
Which pooling library you would like to use depends on your project setup:
Some Application Servers have a JDBC Connection Pool bundled with them.

Two stand alone JDBC connection pools are C3P0 and apache common's DBCP:
Example with C3P0
Example with DBCP

But more importantly:

Try not to re-invent the wheel

Your code is fine as a proof-of-concept / a worked out example of how a JDBC connection works. (Yes, it can be improved, as jrtapsell and J_H show, but as a proof-of-concept it's OK).

The underlying question is more interesting:
Should you write something yourself, which has many excellent solutions already?

Let's have a look at what you do:

You establish a DB Connection (which should be pooled, see above):

  Connection c = DriverManager.getConnection("jdbc:sqlite:"+DBname);

You use this DB Connection to run a query against the DB

  ResultSet rs = c.createStatement().executeQuery(query);

You create a Java Object / Java Objects from the results of the queries (in your main method)

   while(dbo.rs.next()){
     id=dbo.rs.getString("compte_id");
     password=dbo.rs.getString("password");
     ..
     numtelephone=dbo.rs.getString("numtelephone");
   }

These are requirements of almost all applications, which have a multitude of well established, stable and convenient solutions.

I suggest, you read up on O/R Mapping (Wikipedia, hibernate) and a couple of its implementations (e.g. Hibernate getting started, JPA, Spring Data)

Of course, which tools and libraries you end up using in your application is up to you, but to my experience, it's better to have someone else make and fix an error than to have to make all errors yourself :-)


It's reasonable to require GNU Make - it's available on all platforms that have their own Make (as far as I know), and trying to cope with the vagaries of all vendors' Make implementations is an exercise in futility.  So I think you've taken the right approach here.

You're working against Make by putting build products into subdirectories.  It's easier to build them into the working directory, and the sources can be found using VPATH, then there's no need to copy all the built-in rules (not so bad when all your source files are C++, but when you need to add a few assembler and C files, then the maintenance starts to grow).
Creating separate debug and release binaries in the same build tree is problematic - it can mean a total rebuild when switching from one kind to another.  It's more usual to have separate build directories for the two, so you can incrementally build either at any time (of course, they can share the same source files, using VPATH, and can share most of the Makefile the same way).
That would look something like this:
debug/Makefile
CXXFLAGS += -g3 -DDEBUG
VPATH = ../src:../include
include ../Makefile

release/Makefile
CXXFLAGS += -O2
VPATH = ../src:../include
include ../Makefile

Then, building the release version doesn't affect the objects used to build the debug version, and vice versa.

This target is problematic for a parallel build:

release: distclean $(PROGRAM)

We'll lose some of the files as the distclean isn't sequenced with respect to $(PROGRAM).
I don't like the explicit strip invocation in the release target: since install depends on release, this makes it impossible to build debug-symbol Debian packages the usual way.  Just let the packager do the stripping.

I see no value in redefining COMPILE.cc and LINK.cc: CXXFLAGS and LDFLAGS are provided specifically for you to add your own flags to these lines - just use them.
Speaking of which, we normally use += to add to the flags:
CPPFLAGS += -I$(INCDIR)
CXXFLAGS += -std=c++17 -Wall -Wextra -Wpedantic
CXXFLAGS += -flto

LDFLAGS += -ffunction-sections -fdata-sections
LDFLAGS += -Wl,-gc-sections

DEPFLAGS = -MT $@ -MMD -MP -MF $(DEPDIR)/$*.Td
CPPFLAGS += $(DEPFLAGS)

$(RM) is provided as a more portable alternative to rm -f; we could use that in a few places.
.DELETE_ON_ERROR is often missed - kudos for remembering that.
DESTDIR?= is a no-op - undefined Make variables already expand to nothing.  Just omit this line.  It's good that you're correctly allowing this to be set by packaging systems etc.


If you need to use python for being crossplattform and if you need to do this in one line then this is the way to go, yes.
For some reason
Alternatives to consider:

put the code in a file so you can make it more readable
create a Makefile and run this under a target (like clean:)
use os instead of pathlib to see if you like that better (pathlib is fine, though)
use map and a lambda instead of list comprehension, to see if you like that better (probably not though)

I would have expected that a one-line for loop would work, but it doesn't seem to in python -c when there is a command before it.
I think there is no much cleaner solution


(Java) Read .txt and organize activities for hours / minutes

I revised your code and ran some tests.

Here is the input to my last test.

Correr 60min
Estudar 30min
Ler 45min
Escrever 60min
Caminhar 45min
Cutting of steel sheets 60min
Jogar 30min

Here is the output from my last test.

09:00 Correr 60min
10:00 Estudar 30min
10:30 Ler 45min
11:15 Escrever 60min
12:15 Almoço 60min
01:15 Caminhar 45min
02:00 Cutting of steel sheets 60min
03:00 Jogar 30min

The first major change I made to your code was to write a method to convert elapsed minutes to time.

I only needed one List to hold the events.  Actually, I didn't need the List at all.  I could have written the string out as I created it, but I left the List in.

I also simplified the processing of each line.  All I need is the number of minutes that the event lasts.  This code can handle any number of minutes, not just 30, 45, or 60.

Edited to add: I revised the code to handle an input line with an event that has spaces in the event text.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class Schedule {

    public static void main(String[] args) throws IOException {
        // TODO code application logic here

        List<String> events = new ArrayList<>();

        String path = "C:\\Eclipse\\Eclipse-2020-workspace\\"
                + "com.ggl.testing\\resources\\input.txt";
        String outputDir = "C:\\Eclipse\\Eclipse-2020-workspace\\"
                + "com.ggl.testing\\resources\\output.txt";

        FileReader arq = new FileReader(path);
        BufferedReader lerArq = new BufferedReader(arq);

        // Output
        File file2 = new File(outputDir);
        FileWriter arq_output = new FileWriter(file2, true);
        PrintWriter gravarArq = new PrintWriter(arq_output);

        if (!file2.exists()) {
            file2.createNewFile();
        }

        int totalMinutes = 0;
        int lunchMinutes = 180;
        boolean beforeLunch = true;

        String linha;
        while ((linha = lerArq.readLine()) != null) {
            String[] fields = linha.split(" ");
            int lastIndex = fields.length - 1;
            int endIndex = fields[lastIndex].lastIndexOf("min");
            int duration = Integer.valueOf(
                    fields[lastIndex].substring(0, endIndex));

            String output = "";
            for (int i = 0; i < fields.length; i++) {
                output += fields[i] + " ";
            }
            output = toTime(totalMinutes) + " " + output;
            events.add(output.trim());

            totalMinutes += duration;

            if (beforeLunch && totalMinutes >= lunchMinutes) {
                output = toTime(totalMinutes) + " Almoço 60min";
                events.add(output);
                totalMinutes += 60;
                beforeLunch = false;
            }
        }

        for (String cont : events) {
            System.out.println(cont);
            gravarArq.println(cont);
        }

        lerArq.close();
        gravarArq.close();
        arq.close();
    }

    private static String toTime(int minutes) {
        int hours = minutes / 60 + 9;
        hours = hours % 12;
        hours = (hours == 0) ? 12 : hours;
        minutes = minutes % 60;
        return String.format("%02d:%02d", hours, minutes);
    }

}


One problem I see with your code is that you first collect all the data points you want to average, and then you take the average. This has O(n) complexity and extra storage requirements, as you have to append all the data points into a list.

An easy way to fix this is to keep track of the sum and the number of data points, and then divide to get the average. This uses O(1) extra memory instead of O(n), as for each data point, you increment the number of data points and add the value to the accumulated sum, and then continue on to the next one.

For example, instead of:

for stopRow in stops:
    # some code
    arrivals.append(arrival_delay)
    # more code

avg_arrival = np.mean(arrivals)

you should use:

total_arrival_delay = 0
number_arrival_delays = 0

for stopRow in stops:
    # some code
    total_arrival_delay += arrival_delay
    number_arrival_delays += 1
    # more code

avg_arrival = total_arrival_delay / number_arrival_delays

While this approach makes your code a bit longer, it will allow it to work on larger datasets, as you no longer need to store lots and lots of data points while processing, and instead need only to store a few integers


Fetch an array from API endpoint in async function

I've improved a few things to your script, making it more consistent over all:

;(function () {
  const jokeContainer = document.querySelector('.joke-container')

  async function fetchCount() {
    const url = 'https://api.icndb.com/jokes/count'
    const { value } = await (await fetch(url)).json()

    return value
  }

  async function fetchJokes(length = fetchCount()) {
    const url = `https://api.icndb.com/jokes/random/${await length}`
    const { value } = await (await fetch(url)).json()

    return value.map(({ joke }) => joke)
  }

  jokeContainer.addEventListener('click', async event => {
    if (event.target.value === 'Fetch') {
      const jokes = await fetchJokes()

      console.log(jokes)
    }
  })
}())

Fetch some jokes bro!!

    <button type="button" value="Fetch">Fetch Jokes</button>

Wrapped your script in an IIFE to avoid polluting the global scope.
Removed your bizarre usage of the global length variable, which you defined without using var, let, or const, and is considered bad practice.
Used object destructuring to improve the readability of your code in some places.
Declared your event listener as async in order to take advantage of await instead of using a then() chain to improve consistency and readability.
Converted your imperative initialization of jokesData into a functional idiomatic approach using Array#map() in order to further improve readability.


I sort includes alphabetically, making it easier to keep track of which headers are included in long lists.

I would write:

#include <algorithm>
#include <iostream>
#include <vector>

In a long, unsorted list of includes it's hard to see if a header is included twice:

#include <vector>
#include <list>
#include <algorithm>
#include <new>
#include <fstream>
#include <set>
#include <stdexcept>
#include <list>
#include <cstdlib>

Imagine this problem increasing if you have a couple dozen includes!

arr is very undescriptive, and in this case even misleading. This isn't an array, it's a std::vector. vec would be slightly better, but try to describe what the data structure contains or does rather than what kind of data structure it is. Even something as simple as numbers is better than vec (or arr), and you can probably improve that even further. Naming is very important to ensure readability.
Consider using <cstdint> to control the size of numbers. This makes porting a whole lot easier.
In C++, it's a good habit to prefer prefix increment- and decrement-operators, because they are usually more efficient for non-built-in types. It doesn't really matter for built-in types, but consistency is nice.
Consider using using-declarations, i.e. using std::vector; and so on, to make the code more readable.
I'd usually make SieveHelper::cur private and control access to it, but I presume you know that and did it this way on purpose. It's fine for a small program, but remember that programs grow.
Use std::vector::at(), which is bounds-checked, whenever array indexing is not in the speed-critical path. The exception is when you're 110 % sure you can never, ever go out of bounds - but better safe than sorry!
Consider making sieve() take and return an argument, rather than just manipulate an output argument. This is definitely a trade-off, so use your own judgement, but output parameters are generally less readable.

On the plus side, this is mostly good. Extra points for using built-in algorithms, lambda and other juicy C++11 stuff :)


Excel macro to move data across workbooks using an ADO connection

The first thing is that you do not seem to be using Option Explicit because there are some variables (strQuery, cmd1 and cmd2) that are not declared. You should always use Option Explicit and this can be turned on in Tools -> Options, on the Editor tab check the "Require Variable Declaration" checkbox. The IDE will add Option Explicit at the top of every new module.

You are currently mixing the "standard" Excel data access methods (cells, ranges, etc) with using sql which makes it harder to keep track of what your code is doing. This can be simplified by using just sql to get data from the csv file. You don't need to read down through the csv file looking for keywords, you can include the keyword in your sql with a WHERE clause. This also means you do not need to open the csv file. In sql the % character is the wildcard for zero or many characters.

If you are retrieving data using ADODB, then you only need to use Recordset, you don't need to use a Command object and a Recordset. If you will be repeatedly opening a recordset and copying the data to a range then you could put that code into a separate procedure. In my code below, I have the CopyFromFileToRange procedure.

Some of your variable names are good but some are too short/unclear (cn, rst1 and cmd) and strQuery looks like you might be thinking of using Hungarian notation. See this post for a discussion of Hungarian. The main thing is to be consistent in your choice/style.

Option Explicit

Public Sub MoveData()

    '**defines the project name as a variable
    Dim fileName As String
        fileName = Worksheets("Cover").Range("B5").Value

    '**defines the path of the CSV summary from BlueBeam
    Dim filePath As String
        filePath = "C:\Users\(users)\Documents\(folder)\"

    '**defines the destination workbook
    Dim currentWB As Workbook
    Set currentWB = ThisWorkbook

    '**connects using ADODB to transfer the data
    Dim dbConn As ADODB.Connection
    Set dbConn = New ADODB.Connection

    With dbConn
        .ConnectionString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" & filePath _
            & ";Extensions=asc,csv,tab,txt;"
        .Open
    End With

' Added declarations
Dim measurementQueryString As String
Dim notesQueryString As String
Dim keyword1 As String
Dim keyword2 As String

    keyword1 = "some_value"
    measurementQueryString = "SELECT [Measurement] FROM [" & fileName & "] " _
        & "Where Subject LIKE '%" & keyword1 & "%';"
    Call CopyFromFileToRange(dbConn, measurementQueryString, currentWB.Worksheets("Bms").Range("C7"))

    keyword2 = "some_value"
    notesQueryString = "SELECT [Notes (C)], [Col Top (C)], [Col Base (C)] FROM [" & fileName & "] " _
        & "Where Subject LIKE '%" & keyword2 & "%'"
    Call CopyFromFileToRange(dbConn, notesQueryString, currentWB.Worksheets("Cols").Range("B7"))

    dbConn.Close

End Sub

Private Sub CopyFromFileToRange(ByRef dbConn As ADODB.Connection, ByRef queryString As String, ByRef targetRange As Range)

' Opens a recordset using queryString as the source
' Writes the data to targetRange

Dim dataFromCsv As ADODB.Recordset

    Set dataFromCsv = New ADODB.Recordset
    dataFromCsv.Open Source:=queryString, ActiveConnection:=dbConn
    If Not dataFromCsv.EOF Then
        targetRange.CopyFromRecordset dataFromCsv
    Else
        ' No data found
    End If

    dataFromCsv.Close

End Sub


About the naming, and grouping your code.

First improvement, change name of the variable from truncate to should_truncate, than you get

if should_truncate

instead of

if truncate

It is suggested to use methods to encapsulate code that is inside a block, for example code that is execute inside if statement, loops, or any other block of code. In your case

  def content(should_truncate)
    content = article.content
     if should_truncate
       content = truncate_article_content
     end
     content.gsub!(READ_MORE_REGEX, '')

     html = MarkdownService.instance.render content
     content_tag :div, html
  end

private

  def truncate_article_content
    index_at = article.content.index(READ_MORE_REGEX)
    if index_at
      truncate_length index_at
    else
      first_characters
    end
  end

  def truncate_length(length)
    url = _h.article_url(article)
    _h.truncate(article.content, length: length, omission: " [Show more](#{url})")
  end

  def first_characters(length= DEFAULT_LENGTH)
    _h.truncate(article.content, length: length)
  end


I'm sure there is a more elegant way of doing this.

Indeed. With LINQ. You can generate multiple instances with Repeat and join them with string.Join

var symbol = "\xE77B";
var separator = " ";
var count = 5
var result = string.Join(separator, Enumerable.Repeat(symbol, count));

This will work with count = 0 too and generate an empty string.


Basic iterator supporting vector implementation

The range-based for loop
This works via the begin() and end() functions.
So for any class X if there are stand alone functions begin(X&) and end(X&) the range based for will work. Normally this will default to the std::begin() and std::end() but if you have written explicit versions of these functions in the same namespace as X these will be used.
Example:
#include <iostream>

namespace Y
{
    class X
    {
        public:
            char data[14] = "This is text";
    };

    char* begin(X& obj) {
        return obj.data;
    }

    char* end(X& obj) {
        return obj.data + 10;
    }
}

int main()
{
    Y::X   x;
    for(auto const& a: x) {
        std::cout << a;
    }
}

OK. So what happens if you don't write your own begin() and end() functions?
In this case it will use the standard versions of these functions. std::begin() which will call the begin() method on the object and std::end() which will call the end() method on the object.
Example 2:
#include <iostream>

namespace Y
{
    class X
    {
            char data[14] = "This is text";
        public:
            char* begin() {
                return data;
            }

            char* end() {
                return data + 10;
            }
    };
}

int main()
{
    Y::X   x;
    for(auto const& a: x) {
        std::cout << a;
    }
}

How to think of range based for
You can think of ranged based for as a compiler shortcut.
for(<Type> <Var> : <Obj>) {

}

Is just short hand for:
{
    using std::begin;
    using std::end;

    auto __end = end(<Obj>);

    for(auto __loop = begin(<Obj>); __loop != __end; ++__loop) {
        <Type> <Var> = *__loop;

    }
}

Implementation of Iterators
The implementation of an iterator is based on the "Iterator Concept". There are actually five types of iterator in C++. But since you are using vector as your example implementation we should consider the "Random Access Iterator Concept".
To qualify as a random access iterator you have to uphold a specific contract. Here is some documentation on it.
https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator
Not only does the iterator need to define certain methods (with specific requirements on how they work together). But your type also needs to define certain types via std::iterator_traits.
Types
You need to define the following types:

value_type:
When the iterator is de-referenced this is the type you get.
difference_type:
When you subtract two iterators this is the type of the result
pointer:
A type that points at type value_type
reference:
A type that can be used as a reference to a value of type value_type
iterator_category:
A type that represents the category of the iterator.

So you could have written your own specialization of the iterator_traits class
namespace std
{
    template<typename T>
    class iterator_traits<Vector<T>::Iterator>
    {
        using value_type = T;
        using difference_type = std::ptrdiff_t;
        using pointer = T*;
        using reference  = T&;
        using iteratory_category = std::random_access_iterator_tag;
    };
}

But that is a little bit like actual hard work. The designers of the STL actually got smart and the default implementation of this type refer back to the iterator type to get these types. So you can define these types in your iterator (and not define a specialization of the iterator_traits class).
Rather do this:
template<typename T>
class Vector
{
    class Iterator
    {
        using value_type = T;
        using difference_type = std::ptrdiff_t;
        using pointer = T*;
        using reference  = T&;
        using iterator_category = std::random_access_iterator_tag;
    };
    ....
}

Note: If you follow the advice above and use a pointer as your iterator. The iterator_traits for pointer types are well defined in the standard and no work is required.
Properties of an Iterator
The basic properties of an iterator are:

Default Constructible    *** Currently not supported.
Copy Constructible
Copy Assignable
Destructible
Swappable      *** Currently not supported.
Equality Comparable  *** Currently not supported (you need ==)
objects returned via de-referencing need to be mutable (not supported)

Supported actions for a random access iterator:
*i                  // returns the current value
*i  = v             // Assign value `v` to the value dererenced.
++i                 // increments the iterator (returns a reference)
--i                 // See above
i++                 // increments the iterator (but returns a reference to the original)
i--                 // See above
*i++                // returns the current value and increments the iterator
*i--                // See above

i += n              // Moves the iterator forward
i -= n              // Same as last one
i + n               // Creates a new iterator moved forward from i
n + i               // Same as last one
i - n               // Same as last one

i1 - i2             // returns the distance between the iterators.

i[n]                // returns the item n steps forward from this iterator.
i->m                // Access the member `m` referenced by i

i1 <  i2            // Compare iterators
i1 >  i2
i1 <= i2
i1 >= i2
i1 == i2
i1 != i2

OK So I have dumped an all lot of requirements on iterators here. But it is not as bad as it seems. Have a look at an iterator I built for a stack overflow question.
https://stackoverflow.com/a/1120224/14065
This iterator is only a forward iterator (so it has fewer requirements). But it shows you how to implement the main basic requirements very quickly. The rest should not be too hard to implement for random accesses iterator.
Got bored so here:
class Iterator
{
public:
    using value_type = T;
    using pointer    = T*;
    using reference  = T&;
    using difference_type = std::ptrdiff_t;
    using iterator_category = std::random_access_iterator_tag;

    Iterator():                    v(nullptr), i(0) {}
    Iterator(Vector<T>* v, int i): v(v),       i(i) {}
    // Default Copy/Move Are Fine.
    // Default Destructor fine.

    reference       operator*()             {return (*v)[i];}
    const reference operator*()       const {return (*v)[i];}
    pointer         operator->()            {return &((*v)[i]);}
    const pointer   operator->()      const {return &((*v)[i]);}
    reference       operator[](int m)       {return (*v)[i + m];}
    const reference operator[](int m) const {return (*v)[i + m];}

    Iterator& operator++()       {++i;return *this;}
    Iterator& operator--()       {--i;return *this;}
    Iterator  operator++(int)    {Iterator r(*this);++i;return r;}
    Iterator  operator--(int)    {Iterator r(*this);--i;return r;}

    Iterator& operator+=(int n)  {i += n;return *this;}
    Iterator& operator-=(int n)  {i -= n;return *this;}

    Iterator operator+(int n)   const {Iterator r(*this);return r += n;}
    Iterator operator-(int n)   const {Iterator r(*this);return r -= n;}

    difference_type operator-(Iterator const& r) const {return i - r.i;}

    // Note: comparing iterator from different containers
    //       is undefined behavior so we don't need to check
    //       if they are the same container.
    bool operator<(Iterator const& r)  const {return i <  r.i;}
    bool operator<=(Iterator const& r) const {return i <= r.i;}
    bool operator>(Iterator const& r)  const {return i >  r.i;}
    bool operator>=(Iterator const& r) const {return i >= r.i;}
    bool operator!=(const Iterator &r) const {return i != r.i;}
    bool operator==(const Iterator &r) const {return i == r.i;}

private:
    Vector<T>* v;
    int        i;
};

The Container.
Since you were asking about Iterators I will not give input on the Vector just yet (but lets say it needs work).
I have written a couple of articles on implementing the vector that you can have a look at.
http://lokiastari.com/series/


Parallel quicksort algorithm taking way too long

The problem seems to be the fact that you are not dealing with threads (as you should), but rather entire processes (which is more computationally demanding). Refer to this page for details on how to spawn threads.

Also, as a side node, it makes no sense to keep spawning new threads over and over again, since spawning a thread can take easily a couple of milliseconds, which would obliterate all performance gain. Instead, ask the user to pass the maximum amount of threads allowed, and do not spawn any more than that. Furthermore, it would be reasonable to cancel spawning a new thread in case the range to sort it receives is too small.

Hope that helps.


Use Python's math library

You can either import the whole math library, or just import the modules you need.

from math import sqrt, floor

Use a dictionary instead of a list

Yes, if b*c in a iterates through the list. However, if you use a dictionary, it takes only a single operation to look up any value. This is because Python stores dictionary keys and values as a hash table.

You can use Python's dict comprehension syntax.

d = {key: value for (key, value) in iterable}

The result looks like this:

from math import sqrt, floor

def prime_gen(n):
    a = {k: 0 for k in range(2, n+1)}
    for b in range(2, floor(sqrt(n))):
        c = 2
        while b*c <= n:
            if b*c in a:
                a.remove(b*c)
            c += 1
    return(a)


Count the number of discrete values in a slice

Code review:
1. Use  discrete++ instead of discrete = discrete + 1
2. Use if i != j && xi == xj instead of

if i != j {
    if xi == xj {
        is_discrete = false
        break
     }
}

Don't use underscores in Go names: is_discrete, simply use discrete or isDiscrete.
You may use slice ...string instead of slice []string like the following code:

// O(n**2)
func distincts(x ...string) int {
    result := 0
    for i, xi := range x {
        unique := 1
        for j, xj := range x {
            if i != j && xi == xj {
                unique = 0
                break
            }
        }
        result += unique
    }
    return result
}

Also note the result += unique instead of if ....

Using map, the following code has the time complexity (asymptotic notation): O(n)

package main

import "fmt"

func main() {
    r := distincts("a", "b", "c", "a")
    fmt.Println(r) // 2

}

// O(n)
func distincts(slice ...string) int {
    result := 0
    m := map[string]int{}
    for _, str := range slice {
        m[str]++
    }
    for _, v := range m {
        if v == 1 {
            result++
        }
    }
    return result
}


More elegant way to construct the S3 path name with given options

The local variables make this very verbose:
each variable is declared, initialized, re-assigned, and referenced.
(They each appear 3-4 times in the code.)
You could instead accumulate values in a list.

Creating an array that may contain null values,
then filtering out the null values in a second step feels like a waste that's easy to avoid.
You could instead accumulate non-null values in a list.

Using StringJoiner is efficient to join a string from multiple parts.
Then at the end the filePath.toString() + "/" is an inefficient string concatenation that could have been easily avoided by appending an empty string to filePath.

And instead of using StringJoiner, you could use String.join.

Consider this alternative:

private String generateFullQualifiedS3KeyPrefix(DataStream dataStream, Options options) {
    List<String> values = new ArrayList<>();

    if (dataStream != null) {
        values.add(dataStream.getEnvironmentName());
        values.add(dataStream.getApplicationName());
        values.add(dataStream.getStreamName());
    }

    if (options != null) {
        values.add(String.valueOf(options.getYear()));
        values.add(String.format("%02d", options.getMonth()));
        values.add(String.format("%02d", options.getDate()));
        values.add(options.getGroupById());
    }

    values.add("");

    return String.join("/", values);
}


Rooms and trapdoors - for-loop and while-loop efficiency

First things first, stop caring about the number of lines. Unless you are trying to make a code golf competition entry, minimizing the number of lines is the last thing you want to optimize for. This code is hard to read and follow because it is deeply nested and there is very little context to describe what is being done on each line. This code should be broken down into sub functions that encapsulate sections of work.

Compare this line

if knownSafe(roomwidth, roomheight, e, ns0):

to this line

if trapdoor[ns0/roomwidth][ns0 % roomwidth] is "0":

Without knowing anything about the code, I know that the if block is executed if the given arguments describe a location that is known to be safe. Meanwhile, I have no idea why you are indexing into this nested list structure or what the "0" represents.

is does an identity comparison. == does an equivalence comparison. The fact that Two string containing just the character 0 might not always be represented by the same object. The fact that they are is an implementation detail of the Python interpreter you are currently using. Do not use is when you are checking if two values represent the same thing.

for i,m in enumerate(hazardflr):
safetiles.append((m,step))

This is not valid Python. It is likely an issue with posting the question, but as of now, the code in the question does not compile.

Use the Python variable name conventions. Currently, you have a mix of all lower case and camel case. The Python convention is underscore_spaced.

Single letters are rarely good variable names. i is a common convention for index. However, I have no idea what m of e stands for. You also use ns0. From that code, I can see that it is the first element in the nextSafe list. However, that doesn't tell me anything. Why is nextSafe[0] different fromnextSafe[1]? If it is just the current safe location as you iterate over all of the locations, make the variable name curr_safe_location.

You need to pick better data types to represent your state. Lists and strings are great, but they aren't the best way to represent all things. A large portion of your question is describing how your code is structured and what value represent what. This is an indication that the code is hard to read and can be written better. Even if it not required, sometimes making a class is very helpful because it will give value clear descriptive names.

If strings like "X" and "0" are going to have special meanings, at the very least, you should define them as constants. This will give your code more context. Then, if the representation changes, you don't have to look for all instances of "0" and hope every occurrence means the same thing.


Your code is alright, really. However, by your using redis, I suspect you're after a fast way to store tiny bits of data. The varname $cache somewhat confirms my suspicion.
If  this is the case, your using lrange might not be the best choice, nor is exists really meaningful: INCR creates a new key, if required, and it returns the new value of that key in every case, so you can ditch the use of put, and simplify your first loop to:

foreach ($words as $word)
{
    if ($cache->incr($word) == 1)
        $cache->lpush('words', $word);
}

Both these functions are atomic, so I don't think you can much improve on that.

lrange has a time-complexity of O(S+N) according to the documentation. Given that you're just fetching the entire words collection, I'd opt for the O(n) alternative SMEMBERS.
If you are going to use lrange, if you want to use pagination, for exampe, I'd consider using SCARD first, to determine the total number of members of your words collection.

Anyway, here's how I'd write the second loop:

$list = $cache->smembers('words');
foreach ($list as $word)
{
    $data[$word] = $cache->get($word);
}

I'll look into using redis itself a bit more, because it's quite easy to do away with that words collection, too:

foreach ($words as $word)
    $cache->incr($word);
$data = array();
$list = $cache->keys('*');//get all keys in collection
foreach ($list as $word)
    $data[$word] = $cache->get($word);

But this would imply the entire database contains nothing but words, which isn't what you want, probably. If I find the time, I'll attempt to put together a function or script that simply iterates over that words collection, and performs something like this

EVAL "return {KEYS[1], redis.call('get', KEYS[1])}" 1 <a word>

for each word, returning a series of redis objects that look like this:

1) <a word>
2) 123

where the 2) actually is the occurance count

Unrelated
I notice you're constructing an object of the Redis class. This, to me, tells me you're using a library other than the official one. The PRedis class was, last time I checked, the preferred one. Perhaps consider changing to that lib, and see if it works for you. Anyway, look into the libs with a star next to their name :)


malloc
You should not cast the return value from malloc() in C.  Instead, include its header file, and let the compiler's conversion from void* to specific pointer happen naturally.:
KdNode *temp = malloc(sizeof (KdNode));

It's often better to use the size of the actual object(s) you're allocating, rather than the size of the type.  This isn't an issue here, where your declaration is on the same line as the allocation, but consider this:
temp = malloc(sizeof (KdNode));

If you can't see the declaration, then it's harder to be sure that sizeof KdNode is the right size.  Instead we can write:
temp = malloc(sizeof *temp);

This also eliminates some irritating parentheses, which is nice!
error behaviour
What should happen when you misuse the function?  Here, you have two different behaviours:
if (temp == NULL || left == NULL || right == NULL) {
    exit(1);
}
if (numberElements == 0) {
    return NULL;
}

If anything, these are the wrong way around - you abort the whole program for an unpredictable run-time failure from malloc(), but nicely return a null value when you're (avoidably) given nonsense arguments.  It's generally best not to invoke exit() from a function you want anybody to be able to use anywhere; I'd make both cases return NULL.  And change the test for numberElements to be <= 0, or its type to unsigned.
comparators
Comparators for qsort can return any positive value or any negative value or zero as results.  So they don't need to be coerced to -1/0/+1; however, as you've noticed, the difference may be out of range for an int.  However, there's an easier way to obtain a value of correct sign, and the default conversion will work for us:
#include <math.h>
int x_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = v1;
    const Point2D *p2 = v2;
    return copysign(1, p1->x - p2->x);
}

I took out the unnecessary casts from void* here, too.
avoid floor() with integer division
This has an unnecessary round-trip through floating-point and back:
median = floor(numberElements / 2);

Integer division rounds down, so numberElements / 2 is sufficient.
possible simplification of if/else
Most of this is invariant between the two branches:
if (splittingAxis == 0) {
    qsort(data, numberElements, sizeof(Point2D), x_comparator);
} else {
    qsort(data, numberElements, sizeof(Point2D), y_comparator);
}

You might choose to make only the comparator argument dependent on the condition:
qsort(data, numberElements, sizeof *data, splittingAxis ? y_comparator : x_comparator);

If that's too opaque, then you could define a variable:
int (*const comparator)(const void*, const void*)
    = splittingAxis ? y_comparator : x_comparator;

qsort(data, numberElements, sizeof *data, comparator);

In honesty, the original may well be the best option here (but using sizeof *data rather than sizeof (Point2D) helps ensure a type match).
One approach that works well is to use splittingAxis to index an array.  To me, this looks compact and clear :
/* qsort-compatible comparator functions */
typedef int Comparator(const void*, const void*);
Comparator *const comparators[] = {x_comparator, y_comparator };

    qsort(data, numberElements, sizeof *data, comparators[splittingAxis]);

copy whole struct
Here you copy a Point2D member-by-member:
tPoint->x = data[median].x;
tPoint->y = data[median].y;

We can write that as:
*tPoint = data[median];

always check allocators' return value before use
You got this right early in the function, but tPoint is accessed immediately after allocation with no check it isn't null.

Modified version:
I've reordered some code and eliminated some local variables to give something that reads better to me.  See whether you agree.
#include <math.h>
#include <stdlib.h>
#include <string.h>

typedef struct Point2D {
    double x;
    double y;
} Point2D;

static int x_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = v1;
    const Point2D *p2 = v2;
    return copysign(1, p1->x - p2->x);
}

static int y_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = v1;
    const Point2D *p2 = v2;
    return copysign(1, p1->y - p2->y);
}

typedef struct KdNode {
    Point2D *p;
    struct KdNode *left, *right;
    int splittingAxis;
} KdNode;

/* qsort-compatible comparator functions */
typedef int Comparator(const void*, const void*);
Comparator *const comparators[] = {x_comparator, y_comparator };

KdNode* build(Point2D data[],
              unsigned int splittingAxis,
              unsigned int numberElements)
{
    if (numberElements <= 0 || splittingAxis > 1) {
        return NULL;
    }

    KdNode *temp = malloc(sizeof *temp);
    KdNode *left = malloc(sizeof *left);
    KdNode *right = malloc(sizeof *right);
    if (!temp || !left || !right) {
        return NULL;
    }

    temp->p = malloc(sizeof *temp->p);
    if (!temp->p) {
        return NULL;
    }

    qsort(data, numberElements, sizeof *data, comparator[splittingAxis]);

    const unsigned int median = numberElements / 2;
    const unsigned int numberElementsLeft = median;
    const unsigned int numberElementsRight = numberElements - median - 1;
    Point2D leftSide[numberElementsLeft];
    Point2D rightSide[numberElementsRight];

    memcpy(leftSide, data, sizeof leftSide);
    memcpy(rightSide, &data[numberElements - median], sizeof(rightSide));

    const int other_axis = 1 - splittingAxis;

    *temp->p = data[median];
    temp->left = build(leftSide, other_axis, numberElementsLeft);
    temp->right = build(rightSide, other_axis, numberElementsRight);
    temp->splittingAxis = splittingAxis;
    return temp;
}

Performance improvement
Given that we're allowed to modify data and that we're not using it after finding the median value, we don't need to copy its elements into new arrays - we can sort its sub-arrays in-place:
KdNode* build(Point2D data[],
              unsigned int splittingAxis,
              unsigned int numberElements)
{
    if (numberElements <= 0 || splittingAxis > 1) {
        return NULL;
    }

    KdNode *temp = malloc(sizeof *temp);
    KdNode *left = malloc(sizeof *left);
    KdNode *right = malloc(sizeof *right);
    if (!temp || !left || !right) {
        return NULL;
    }

    temp->p = malloc(sizeof *temp->p);
    if (!temp->p) {
        return NULL;
    }

    qsort(data, numberElements, sizeof *data, comparator[splittingAxis]);

    const unsigned int median = numberElements / 2;
    const int other_axis = 1 - splittingAxis;

    *temp->p = data[median];
    temp->left = build(data, other_axis, median);
    temp->right = build(data + median + 1, other_axis, numberElements - median - 1);
    temp->splittingAxis = splittingAxis;
    return temp;
}

Side note: if you ever re-write this in C++, you'll find std::partial_sort() useful for finding the median with less computation than a full qsort().


Limiting the maximum amount of goroutines run simultaneously

You can use the Golang Concurrency Manager goccm to limit the maximum number of goroutines to run concurrently:

Example:

package main

import (
    "fmt"
    "goccm"
    "time"
)

func main()  {
    // Limit 3 goroutines to run concurrently.
    c := goccm.New(3)

    for i := 1; i <= 10; i++ {

        // This function have to call before any goroutine
        c.Wait()

        go func(i int) {
            fmt.Printf("Job %d is running\n", i)
            time.Sleep(2 * time.Second)

            // This function have to when a goroutine has finished
            // Or you can use `defer c.Done()` at the top of goroutine.
            c.Done()
        }(i)
    }

    // This function have to call to ensure all goroutines have finished
    // after close the main program.
    c.WaitAllDone()
}


Determine if one string is a permutation of the another

I would say yes, use an array.

Arrays afford very good memory locality, which is good for cache performance. They essentially are the most basic and efficient hash map if the key is the index.

You only need one array with 256 elements: first count up the number of times each character appears in the first string, and then count down for the number of times each character appears in the second string. Precisely if the two strings are permutations, the array will finish with all zeroes.

As a further hint at relative complexity, according to godbolt.org, your code produces 849 lines of assembly when compiled on the most recent GCC with -O3 optimisation.
The following code produces 53 lines.

bool is_permutation(const std::string& s1, const std::string& s2)
{
    if(s1.length() != s2.length())
        return false;

    // There are usually 256 possible characters but on rare architectures may be more.
    constexpr possible_char_count = std::numeric_limits<unsigned char>::max()+1;
    std::array<size_t, possible_char_count > m1 = {}; // Zero initialized all places

    for(char c : s1) { // Count up for each character in the first string
        m1[static_cast<unsigned char>(c)]++;
    }
    for(char c : s2) { // Count down for each character in the second string
        m1[static_cast<unsigned char>(c)]--;
    }

    for (size_t t : m1) {
        // If any character appears a net nonzero number of times,
        // the two strings are not anagrams.
        if (t != 0) {
            return false;
        }
    }
    return true;
}

Lines of code are not, of themselves, a perfect indicator of what is the most efficient algorithm. After all, you can implement a nice short version of bubble sort! Nevertheless when the underlying approach is the same (that of counting characters) it is a fairly good indicator that one implementation is doing unnecessary work.

One reason to prefer a map to an array is that when the input strings are very short or very homogenous, then the map is likely to be more memory efficient. This may translate into speed improvements by avoiding allocation and inialisation overhead. As always, the only reliable way to decide is to profile with your real world inputs.