Simple word translator taking advantage of Wikipedia

Don't use the multiple-arity syntax for defn unless you actually need to:

(defn url-decode
  [text]
  (URLDecoder/decode text "UTF-8"))

Your code could use some line breaks here and there. This is how clojure is usually indented:

(defn translate
  [term src-lg tgt-lg]
    (let [translations (get-translations (fetch-url (get-url src-lg term)))]
      (if (contains?  translations tgt-lg)
        (s/replace-str  "_" " " (url-decode (get translations tgt-lg)))
      "<NOT FOUND>")))

and:

(defn prompt-translate
  []
  (let [src-lg (prompt-read "Source language (en, fr, de ...)")
        tgt-lg (prompt-read "Target language  (en, fr, de ...)")
        term (prompt-read "Term to translate")]
    (println (str "\"" term "\" translated from " src-lg " to " tgt-lg " : " (translate term src-lg tgt-lg)))))

Instead picking out the regexp groups by index, you should use destructuring:

(defn get-translations
  [cnt]
  (apply sorted-map
    (flatten
      (for  [[_ a b] (re-seq #"interwiki-([^\"]+).*wiki\/([^\"]+)\".*/a>" cnt)]
        [a b]))))

... or better yet, I think, would be to do something like this:

(defn get-translations
  [cnt]
  (apply sorted-map
    (mapcat
      rest
      (re-seq #"interwiki-([^\"]+).*wiki\/([^\"]+)\".*/a>" cnt))))


spaghetti code for lunch: refactoring a bunch of fields that always get initialized

Does any code set those fields?

Turn them into properties, then extract the interface that includes the properties. I recommend against letting any code set them, if at all possible.


rippleCarryAdder is very hard to read. We can make it a lot easier to read if we use local bindings with let … in …:

rippleCarryAdder :: Nibble -> Nibble -> Nibble
rippleCarryAdder (a0, a1, a2, a3) (b0, b1, b2, b3) =
   let (r3, c3) = fulladder a3 b3 False
       (r2, c2) = fulladder a2 b2 c3
       (r1, c1) = fulladder a1 b1 c2
       (r0, _ ) = fulladder a0 b0 c1
   in (r0, r1, r2, r3)

We also don't have to recalculate fulladder a3 b3 False four times.

The functions faccess and saccess already exist and are called fst and snd.


This is a bug:

else if( record.size() > hash_table.rbegin()->second.size() )

As implemented, insertion stops once your program encounters the longest line in the file.

For example, suppose the input contains:

2
abcdefghijklmop
a
ab
abc
abcd

Your program will output:

abcdefghijklmop
a

The fix is simple: Change rbegin to begin.

Another potential issue is your use of a std::map as opposed to some other container. Your concept is fine, but not necessarily for "I'm the best hacker!" type sites that place strong emphasis on execution time. A vector-based solution could be faster. With the red-black tree-based hash, search, insertion, and delete are \$O(log n)\$ (but with large constants). With a vector-based solution, search would be \$O(log n)\$ (but potentially much faster than a red-black search), deleting the tail is \$O(1)\$ (which is a big win), but insertion is \$O(n)\$ (which is of course a big loss). However, for small enough values of n, a fast \$O(n)\$ algorithm can and will beat a slow \$O(log n)\$ algorithm.

One last remark: Rather than your void print() member, a stream insertion operator would be more C++-like:

class fixed_hash
{
    ...
    friend std::ostream& operator<<(std::ostream& os, const fixed_hash& hash);
    ...
};

std::ostream& operator<<(std::ostream& os, const fixed_hash& hash)
{
    auto end = std::rend(hash.hash_table);
    for( auto it = std::rbegin(hash.hash_table); it != end ; ++it )
    {
        os << it->second << "\n";
    }
    return os;
}


Number of ways to make change for an amount

Any Clojure style / best practices

Your nested if statements in get-ways might be nicer as a cond:

(defn get-ways
  [n coins]
  (cond
    (= n 0) 1
    (= 0 (count coins)) 0
    :else (let ...)))

There may be other things, but I'm not a clojure pro.

Why it won't pass the timing tests on HackerRank.

I suspect your with-redefs isn't doing what you expect.  with-redefs will redefine get-ways for the duration of the with-redefs block.  But all you're doing in that block is returning the re-defd function.  So your initial call will call the memoized function, but every recursive call just calls the orignal function, so you lose all the benefit of memoizing in the first place.

You may be better off wrapping your (println (get-ways-memoized n coins))) in with-redefs, or maybe just redfining get-ways to always be memoized:

(def get-ways
  (memoize (fn
    [n coins]
    ...)

Is there a way to do this manually.

Not sure, I'll leave that to someone else to try and answer.


Modifying the class after defining it smells. That is, its not necessarily a bad idea but one should explore options before resorting to it.

When "decorating" a function you should use the functools.wraps decorator. It will make the decorated function look more like the original.

The code you are replacing looks like:

def importance_changed(self):
    return_value = super(Model, self).importance_changed()
    self.modelChanged.emit()
    return return_value

Your code is harder to read and longer then just writing those two functions. Its not really worth implementing what you've done just for two functions. However, if you have a lot of functions then the situation changes.

Your emit_decorator function isn't a decorator. Dectorators have to take exactly one argument, (the function they are wrapping) to be used with the @syntax.


Pulls href tags using BeautifulSoup with Python

General Observations

instead of manually looking for a tag a desired position and handling pos increment in the loop, I think you could just simply get the value by index:

curpos = tags[int(pos_1) - 1].get('href', None)

count = count - 1 could be simplified as count -= 1
follow the PEP8 lower_case_with_underscores variable naming guideline
what if you prefix the variable names containing user-defined values with input_ (see below)?
and, I think a "for" loop with a negative step would be a simpler solution that the while loop here:

for count in range(int(Count_) + 1, 1, -1):
    # ...

Or, to bring it one step further, what if we apply a generally easier to follow recursive flow instead of the iterative approach you currently have. The base condition for the recursion could be the input count reaching 1. And, we'll improve on DRY with that function as well.

Web-Scraping

you don't have to call .read() on the result of .urlopen() as BeautifulSoup also accepts file-like objects:

soup = BeautifulSoup(ur.urlopen(url), "html.parser")

switching from html.parser to lxml may help drastically improve HTML-parsing performance
instead of using urllib(), you could switch to requests and re-use a session which would help avoid an overhead of re-establishing network connection to the host on every request
you could use SoupStrainer to let BeautifulSoup parse only the a elements
you should also account for relative links and use urljoin() to combine base urls and relative links

The code with the above and other improvements applied:

from urllib.parse import urljoin

import requests
from bs4 import BeautifulSoup, SoupStrainer

only_links = SoupStrainer('a')

def follow_link(session, url, position, count):
    """Follows a link at a given "position" "count" number of times."""
    if count <= 1:
        return

    print('Retrieving: ', url)
    response = session.get(url)

    soup = BeautifulSoup(response.content, "lxml", parse_only=only_links)
    links = soup('a')
    next_url = links[position - 1].get('href', None)

    return follow_link(session, urljoin(url, next_url), position, count - 1)

if __name__ == '__main__':
    input_url = str(input('Enter URL- '))
    input_count = int(input('Enter count: '))
    input_position = int(input('Enter position: '))

    with requests.Session() as session:
        follow_link(session, input_url, input_position, input_count)

Afterthoughts

what if there is no link at the desired position available on some page?
if we once get a link which links itself, this code in this state would get stuck on this page alone until the count is exchausted

  The goal is to have cleaner code, with a #comment on each line (unless extremely basic) so as to improve my annotation habits.

Comments on each line could overall decrease readability of the code and they are, in essence, extra information and weight you need to make sure stay up to date with the actual code. Self-documented code is something you should strive to achieve, using comments as an extra measure used to explain the "why" some decisions were made and not the "how".


Do not use "enum in class" for public usage. You should use namespace for the purpose. (If your compiler supports C++0x, then use enum class.)

The problem with "enum in wrapper class" is header dependency. When declaration code wants to use some "enum in wrapper class" type, then it should also references the whole class information. Because you cannot physically separate enumeration from the wrapper class (one definition rule), it'll introduces heavier header dependency.

Moreover, because in C++, there can't be two separate definitions for one class so you cannot use forward declaration technique with "enum in wrapper class" like below.

// a.h
namespace A {
  enum Type {
    a,
    b
  };
}

// b.h
namespace A {
  enum Type; // forward declaration
}
A::Type function();


Inserting and updating data for a website monitoring app

You can optimize it so that it's just 2 DB queries:

    $allSites = $this->get('SiteRepository')->CustomQuery(); // Returns Site array indexed by id

    $allStatuses = $this->get('StatusRepository')->CustomQuery(); // Returns Status array indexed by id

    $results = $this->getScanManager()->scanBatch($allSites); // scans all the sites and returns results array

    $em = $this->getDoctrine()->getManager();

    foreach ($results as $result) {

        $history = new History();
        $history->setSite($allSites[$result['id']]);
        $history->setTime(date('h:i:s d-m-Y'));
        $history->setStatus($allStatuses[$result['status']]);
        $history->setResponseTime($result['speed_download']);

        $em->persist($history);

        $site = $this->findSiteById($result['id'], $allSites);
        $site->setSiteStatus($allStatuses[$result['status']]);
        $site->setSitePingTime($result['speed_download']);
        $site->setSiteLastUpdate(date('h:i:s d-m-Y'));
    }

    $em->flush();

    return $this->render('default/index.html.twig');

Of course this should be adjusted to your app, if you allways ping all the sites, then it's ok, but i you just ping a few, then it might be inefficient, but at least you get the idea.

BTW, if your setter methods return $this, you could write it in a prettier way:

$history->setSite($allSites[$result['id']])
   ->setTime(date('h:i:s d-m-Y'))
   ->setStatus($allStatuses[$result['status']])
   ->setResponseTime($result['speed_download']);


Create an array of objects from array of arrays

I don't see any significantly better way of doing this. It can be written in different ways (like below), but yours is pretty simple and straightforward.

That said, you'll probably want your function to actually return the new array instead of just logging it.

And you'll want some error checking. I'd say you should assume that an array has been passed in (if it isn't, well, that's not really this function's responsibility. Garbage In, Garbage Out), but don't assume it's actually populated. So check that it contains at least 2 rows.

You may also want to check that the items in the array are also arrays, though again: GIGO.

And I'd rename the function. It doesn't "make an object property" as its name suggests; it converts an entire array to objects, following some scheme. I can't quite say what that better name might be, though. The input resembles tabular data (header row, etc.), so maybe something along those lines.

If you're targeting modern browsers, you could do some map/reduce stuff instead:

function rowsToObjects(table) {
  var keys = table[0],
      rows = table.slice(1);

  if(rows.length === 0) return [];

  return rows.map(function (row) {
    return keys.reduce(function (memo, key, index) {
      memo[key] = row[index];
      return memo;
    }, {});
  });
}


1) I would change the inner for loop this way (very little optimization, unlikely it will bring better performance)

int ans=0;
int y=index-1;
for(int j=0; j<y; j++)
{
    int diff = a[y] - a[j];

    if(diff > 0)
        ans += diff;
    else
        ans -= diff;
}

2) You never store ans in the map.


The way your code is today this should work fine.  But if you ever decide to add a RemoveItem method you can have issues.  Since you are checking if the key exist with TryAdd then accessing assuming the key is there.  This works because nothing can remove a value from the ConcurrentDictionary as it stands.  But if you add the ability to remove an item from the ConcurrentDictionary then calling a TryAdd then assuming it's there is dangerous since the RemoveItem could have been processed between those statements.   This is why the ConcurrentDictionary has a GetOrAdd method to handle that situation for you.

With using a TaskCompletionSource you would struggle to know if you should call the factory method or not from the GetOrAdd since you wouldn't know if your thread was the one to add it.  This is where the Lazy<> version shines as it doesn't matter who added the Lazy<Task<TValue>> both threads can await it since it was passed in the valuefactory.

To me it would be a natural path that RemoveItem might be added later as most caching has a way to invalidate the cache items, for example if the Task threw an Exception maybe I want to remove it from the cache to try again.  Someone coming after to add a RemoveItem might not catch the subtle bug they introduced in the AddItem that was working.

In a nutshell it will work today but might not be as future proof as you want it to be.


Getting multiple inputs from single EditText

I think I would consider using three controls to achieve this and resetting their visibility on submission.

Reusing whatever you have used to create the userInputs control, rename that to nameInput and create two others weightInput and shelfLifeInput. Importantly when creating the other two controls set their visibility.
In XML:

<TextView
            android:id="@+id/weightInput"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:hint="@string/weightHint"
            android:visibility="gone" />

or programatically:

weightInput.setVisibility(View.GONE);

It is import to use View.GONE as opposed to View.HIDDEN as a HIDDEN control still takes up space in the page.

Each of your three inputs can have a handler similar to the one you have created above, but now each handler performs a slightly different function.
Name Input:

userInput.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                userInput.setVisibility(View.GONE);
                weightInput.setVisibility(View.VISIBLE);
                break;
            default:
                break;
            }
         }
         return false;
     }
 });

Weight Input:

weightInput.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                weightInput.setVisibility(View.GONE);
                shelfLifeInput.setVisibility(View.VISIBLE);
                break;
            default:
                break;
            }
         }
         return false;
     }
 });

Shelf Life Input:

shelfLifeInput.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                //this can probably be locally scoped now.
                //Users is an odd name for what this class appears to be.
                //assume validation will have been added.
                Users newUser = new Users();
                newUser.setUsersName(userInput.getText().toString());
                newUser.setUnitWeight(Integer.parseInt(weightInput.getText().toString()));
                newUser.setShelfLife(Integer.parseInt(shelfLifeInput.getText().toString()));
                uList.add(newUser);
                adapter.notifyDataSetChanged();
                shelfLifeInput.setVisibility(View.GONE);
                userInput.setVisibility(View.VISIBLE);

                break;
            default:
                break;
            }
         }
         return false;
     }
 });

You would probably want to break the user creation code out into a separate function so that it is not tightly bound with the view, but for brevity I have followed more closely to your original code.


I have to admit, the actual "solving the problem" component of this is a little over my head. But, I thought I'd try to answer your questions and give you some style/structure feedback, for what it's worth :)

You can simplify your ns declaration like this:

(ns cookie-clicker
  (:require [clojure.string :refer (split)]
            [clojure.java.io :as io]
            [clojure.test :refer :all]))

(:require foo :refer (bar) does the same thing as :use foo :only (bar), and is generally considered preferable, especially as an alternative to having both :use and :require in your ns declaration)

I think Double/parseDouble is a good approach to parsing doubles in string form. Integer/parseInt is usually my go-to for doing the same with integers in string form. This is just a hypothesis, but Double/parseDouble might be faster and/or more accurate than read-string because it's optimized for doubles.

FYI, you can leave out the java.lang. and just call it as Double/parseDouble in your code. In light of that, you might consider getting rid of your parse-double function altogether and just using Double/parseDouble whenever you need it. The only thing is that Java methods aren't first-class in Clojure, so you would need to do things like this if you go that route:

(defn parse-row [line]
  (map #(Double/parseDouble %) (split line #"\s+")))

(Personally, I still like that better, but you might prefer to keep it wrapped in a function parse-double like you have it. It's up to you!)

I think needing to mess with the locale might be a locale-specific problem... I tried playing around with (format "%.7f" ... without changing my locale and it worked as expected. Granted, I'm in the US :)

I think the legibility issues you're seeing might be related to having too many functions. You might consider condensing and renaming things and see if you like that better. I would re-structure your program so that you parse the data into the data structure at the top, something like this:

(defn parse-test-cases [in-file]
  (with-open [rdr (io/reader in-file)]
    (let [rows (rest (line-seq rdr))]
      (map (fn [row]
             (map #(Double/parseDouble %) (split row #"\s+")))
           rows))))

(I condensed your functions parse-row, parse-test-cases and half of spit-answers into the function above)

Then define the functions that "do all the work" like min-time, and then, at the end:

(defn spit-answers [answers out-file]
  (with-open [w (io/writer out-file :append false)]
    (.write w (clojure.string/join "\n" answers)))

(def -main []
  (let [in  "resources/cookie_clicker/B-large-practice.in"
        out "resources/cookie_clicker/B-large-practice.out"
        test-cases (parse-test-cases in)
        answers (map-indexed (fn [i [c f x]]
                               (format "Case #%d: %.7f" (inc i) (min-time c f x)))
                             test-cases)]
    (spit-answers answers out)))

I came up with a few ideas above:

In your answers function you use (map ... (rest (range)) (test-cases)) in order to number each case, starting from 1. A simpler way to do this is with map-indexed. I used (inc i) for the case numbers, since the index numbering starts at 0.
I condensed (str "Case #" n ": " (format "%.7f" t))) into a single call to format.
I used destructuring over the arguments to the map-indexed function to represent each case as c f x -- that way it's clearer that each test case consists of those three values, and you can represent the calculation as (min-time c f x) instead of (apply min-time test-case).

As for your min-time function, I don't think loop/recur is necessarily a bad thing, and I often tend to rely on it in complicated situations where you're doing more involved work on each iteration, checking conditions, etc. I think it's OK to use it here. But if you want to go a more functional route, you could consider writing a step function and creating a lazy sequence of game states using iterate, like so:

(note: I'm writing step as a letfn binding so that it can use arbitrary values of c, f and x that you feed into a higher-order function that I'm calling step-seq -- this HOF takes values for c, f and x and generates a lazy sequence of game states or "steps.")

(defn step-seq [c f x]
  (letfn [(step [{:keys [factories time-cost cookie-rate total-time result]}]
            (let [new-time-cost (+ time-cost (/ c cookie-rate))
                  new-cookie-rate (+ cookie-rate f)
                  new-total-time (+ new-time-cost (/ x new-cookie-rate))]
              {:factories (inc factories)
               :time-cost new-time-cost
               :cookie-rate new-cookie-rate
               :total-time new-total-time
               :result (when (> new-total-time total-time) total-time)}))]
    (iterate step {:factories 0, :time-cost 0, :cookie-rate 2.0,
                   :total-time (/ x 2.0), :result nil})))

Now, finding the solution is as simple as grabbing the :result value from the first step that has one:

(defn min-step [c f x]
  (some :result (step-seq c f x)))


For the second question you can use type_traits(is_unsigned) and enable_if.
http://en.cppreference.com/w/cpp/types/is_unsigned
http://en.cppreference.com/w/cpp/types/enable_if

For the first question:
The main difference between memmove and memcpy is that memmove can be used to relocate a piece of memory to somewhere that overlaps the memory block that you're trying to move. And therefore the original pointer will no longer be valid. So I think it's up to you how you want your function to behave, if you want the parts to be zeroed or not or leave it too the user.


At first, I was confused what exactly did the implementation of IObservable<T> mean. You should properly document that.
You don't need to have a separate lock objects. If you're locking on a specific object, I think you should use that object in the lock.
If you're just calling a single method in your lambda, you can use more succinct syntax: new Disposable(() => this.Unsubscribe(observer)).
If you want to make your code thread-safe, you need to lock all your reads too. In Unsubscribe() you don't do that, which means someone could write to the list while you're reading it. The same problem is in Peek().
Dequeue() shouldn't return default(T) if the queue is empty. This can be problematic especially with value types. Instead, you should have a method like bool TryDequeue(out T result).
You're accessing Count outside of a lock. I wouldn't rely on the fact that doing this is safe, I think you should lock before accessing it too.
Since you're using Rx, you might as well use their Disposable.Create() instead of creating your own.


def get_payact_list(id)
  ## Dont use class instance variables ( prefixed with @ ) for method scoped variables
  @temp="" # temp = ""
  ## In this case, you dont need the temporary variable, but lets keep it, but turn it into an array.
  # temp = []

  ## No need for the temp variable here, and still using class instance variables.
    @payacts=PayAct.find(:all, :conditions => {'product_id' => "#{id}".chop_space})
    @payacts.each do |item|
  # PayAct.find(:all, :conditions => {'product_id' => "#{id}".chop_space}).each do |item|

      @temp = @temp + "str1" + ": " + item.date + ", " + "str2" + ": " + item.summ + " " + "str3" + ", "
      ## Lets simply push each item onto the array.
      ## While we are at it, we remove the trailing comma string.
      # temp << "str1" + ": " + item.date + ", " + "str2" + ": " + item.summ + " " + "str3"

    end
    # No need to mangle the end of the string, as we can simply join the temp array with a comma, which will not add to the end.
    @temp = @temp[0,@temp.length-2] if @temp.length > 1
    # temp.join ", "

    # no need for an explicit return. Ruby will return the value of the last expression.
  return @temp
end

Complete example, without changing too much.

def get_payact_list(id)
  temp = []
  PayAct.find(:all, :conditions => {'product_id' => "#{id}".chop_space}).each do |item|
    temp << "str1" + ": " + item.date + ", " + "str2" + ": " + item.summ + " " + "str3"
  end
  temp.join ", " # is implicitly returned.
end

We can do away with the temp variable by using collect() instead of each() and pushing to an array.

def get_payact_list(id)
  list = PayAct.find(:all, :conditions => {'product_id' => "#{id}".chop_space}).collect { |item|

    "str1" + ": " + item.date + ", " + "str2" + ": " + item.summ + " " + "str3"
  }
  list.join ", "
end

Lets go the whole way, here are our new methods

This still looks and feels like duplication, but without a bit more
metaprogramming than I want to go into right now, it will do.
At least the separate concerns are factored out.

  def get_payact_list id
    format_act_list PayAct.find_by_product_id(id).collect { |item|
      [item.date, item.summ]
    }
  end

  # Note: the get_data method should be encapsulated on the item, leaving as is for now.
  def get_stageact_list id
    format_act_list StageAct.find_by_product_id(id).collect { |item|
      [ get_data(item.type_id,"type"), item.summ ]
    }
  end

  def get_resentact_list id
     format_act_list ResentAct.find_by_product_id(id).collect { |item|
       [ get_data(item.shop_id,"resentact"), item.cost ]
     }
  end

  def format_act_list list
    list.collect { |item| format_tuple(item) }.join ', '
  end

  # Takes an array and correctly formats the output
  # Ideally this would live in a presenter or a view.
  def format_tuple tuple
    "str1: %s, str2: %s str3" % [ tuple[0],  tuple[1] ]
  end

And this is the supporting code.

class Act
  # I've moved this common finder method up the (fake) chain of inheritance I invented.
  # It could also live in each of the child objects i.e ( PayAct StageAct ResentAct )
  def self.find_by_product_id (product_id)
    self.find(:all, :conditions => {'product_id' => "#{product_id}".chop_space})
  end
end

class PayAct < Act;end
class StageAct < Act; end
class ResentAct < Act; end


I think you can simplify your code quite a bit if you drop the implicit restrictions you have on parent.

Consider the following:

parents(X,Y,Z) :- (father(X,Z), mother(Y,Z)); (father(Y,Z), mother(X,Z)).

father(X,Y) :- parent(X,Y), man(X).
mother(X,Y) :- parent(X,Y), woman(X).

This gets rid of the implicit genders in your definitions (see your parents declarations). It means you'll need a few more lines, but it allows you to define parentship as data.

It also makes the definition for siblings a tad easier:

siblings(A,B) :- father(F,A), father(F,B), mother(M,A), mother(M,B) A\=B.

this can will make half-siblings (and step-parentship) a lot cleaner, especially considering Zeus' significant number of illegitimate offspring in case you want to extend the family tree... Greek Gods have quite the messy family if you look closer.

It also makes uncle and aunt slightly easier to follow:

uncle(U,N) :- man(U), ((siblings(U,M), mother(M,N)) ; (siblings(U,F), father(F,N))).

it can be even easier if you go for a definition with parent:

uncle(U,N) :- man(U), siblings(U,P), parent(P,N).

making the rest of the family relationships cleaner and easier to follow from here should be rather obvious. It especially eases up the grandparent definitions...

On that note: grandparent has a "small" bug. Since you implicity gendered parents, your grandparent relationship only includes the father's father and the mother's mother. A similar bug has shown itself in son and daughter... The gender of the parent doesn't influence whether the child is a son or a daughter ... father and mother respectively should be replaced by parent in that definition.

As a closing note: You should strive to build your data in a "simplistic" way of atomic units with as little "implicit relation" as possible. This might seem more effort, it will drastically reduce the chance of such bugs to happen though.


Optimizing a jquery user interface application

Without actual code, we cannot review it if it actually contains significant issues. Thus, I've set forth guidelines instead.
Compression
The real help that compression does is actually speeding up loading times. Unless you are actually loading scripts on demand on mouseover, then you might need to compress them.
However, a better solution is to actually preload these resources, or load them in parallel, and execute once available. That's pretty much how RequireJS does things. That way, you are not actually waiting for resources. The same thing is also true for other resources like fonts, images, cursors, videos and all the rest.
Other scripts
Anyways, there are a lot of things that could cause your script to go wrong, and that includes other scripts on the page. Due to the fact that JS is naturally single-threaded (unless made to thread), any blocking operation, be it in other scripts or within your script, could potentially be slowing down your entire operation. An example is a very long loop, or SJAX (Synchronouse XHR).
To make sure that it's not your script that's breaking apart, try isolating your development enviroment to only your script and a minimal version of the UI and without other scripts. Also, test other functionalities on the page without your script to verify that it's another script that is causing the problem.
>700ms === lag
Yes, that's true. According to a YUI video on their YouTube channel, 200ms is considered "instant" in the perspective of the user. That also explains that game latencies of <200 are best. However, in your case, 2-3 seconds? The user has already left your page by then.
Aim for responsiveness that are less than or are in the range of 200-300ms. And yes, your boss is for real and knows what he's doing.
Hey! Cache!
Your script is potentially DOM heavy by its looks and description. But DOM manipulation is heavy work. Cache as much as possible whenever possible, especially on elements that don't change over the lifetime of the page.
Also, minimize fetching stuff on the DOM.


JSON serializer using generics rather than System.Object

Nice try, however there are potential optimization and code quality improvements.

First obvious thing is handling of the trailing comma.

If you try to generalize your code for the other possible underlying string output component (Stream, for example), you would discover that a string editing operation is not readilly available. Not all the streams support positioning, for example.
In a good implementation, i would not expect the trailing comma at all:

Following is a pseudocode with an abstracted Append method.

using (var iterator = items.GetEnumerator())
{
    if (iterator.MoveNext())
        Append(json, iterator.Current);
    while (iterator.MoveNext())
    {
        Append(json, ',');
        Append(json, iterator.Current);
    }
}

In this code, json could be a StringBuilder or a Stream, or whatever your implementation would use.

Using formatting is a performance killer.

Append format creates at least one excess array object on heap (as for the current implementation of NET 4.5), and parses the format string, which is suboptimal.
If you want your code to be performant, use just the append method of the string builder:

json.Append('[').Append(value).Append(']');

Following part makes feeling like i would never rely on such an implementation:

if (json.Length > 11)

It's a bad way of checking for an empty collection and a bad usage of magic constant in your code. Solve the former, and get rid of the latter.

Using reflection is another performance killer.
There are many techniques to do all the reflection on a type beforehand, and then use a compiled delegate. You can find information on Expression.Compile, which uses Assembly.Emit to generate code dynamically at runtime only the first time a particular type serialization is used.

I would say code comments inside methods lead to unmaintainable code, and the comments like:

// iterate through the IEnumerable

..

if (value == null)// make sure value is not null or empty

..

json.Append("},");// add another row in the array (another dictionary)

...are pretty much useless.

Just assume that every person reading your code knows that foreach means iterating an ienumerable, if means a conditional statement, and } in json means the end of dictionary.

Using comments on parts of the code blocks inside a method indicates that the method could be composed of smaller ones with descriptive names and possibly add xmldoc comments:

    /// <summary>
    /// Appends multiline value <paramref name="value"/> with special formatting based on newline charactes.
    /// </summary>
    /// <param name="stringBuilder">Output builder.</param>
    /// <param name="value"></param>
    public void AppendMultiline(StringBuilder stringBuilder, string value)
    {
        // ...
    }


Use correct capitalization of file names
Be careful with upper case and lower case in filenames. While Windows might not treat filenames case sensitively, other operating systems might. The correct #include is:
#include <SFML/Graphics.hpp>

Avoid operating specific functions
You use Sleep(), which is not a standard C function, but rather Windows specific. Since you are using SFML, you can use sf::sleep() instead, like so:
sf::sleep(sf::milliseconds(60));

You can then also remove #include <windows.h>, and then your code compiles and runs on other platforms without errors.
Add error checking
Your code ignores errors trying to open the texture files. Make sure you report an error and exit if any of the required files cannot be found.
Split off more functionality into their own functions
You already created a function update() to handle moving the snake one frame. However, it would be nice to move more functionality out of main() into their own functions, so that the game loop in main() becomes something simple like:
while (window.isOpen()) {
    handle_input();
    update();
    draw();
    sleep(milliseconds(60));
}

Avoid moving the whole body each frame
Instead of moving the position of every element of snake[], use a std::deque to hold the positions, and inside update(), just pop the tail and add a new head:
#include <deque>

struct position {
    int x;
    int y;
};

std::deque<position> snake;

void update() {
    // Calculate the new head position
    position new_head = snake.front();
    if (direction == 'u') new_head.y--;
    else if ...;

    // Handle wraparounds here
    if (new_head.x < 0) new_head.x += ...;
    if (...) ...;

    // Remove the tail and add a new head
    snake.pop_back();
    snake.push_front(new_head);
}

Using std::deque, the container knows its own length, and this makes it easy to use range-for loops. For example, to draw the snake:
for (auto position: snake) {
    sn.setPosition(position.x * size, position.y * size);
    window.draw(sn);
}

Use struct position for all positions
You can also use struct position to store the coordinates of the fruit:
position fruit;

This makes the code more consistent, and if position would have added comparison operators, it would save you from manually comparing the x and y coordinates separately. Which brings me to:
Use sf::Vector2<int> for the positions
SFML has a handy class to store coordinates for you, so you can write:
std::deque<sf::Vector2<int>> snake;
sf::Vector2<int> fruit;

This type also has x and y member variables. But, it also overloads things like operator=(), so instead of comparing x and y coordinates manually, you can write:
if (snake.front() == fruit) {
    // Handle the snake eating the fruit
}

Code formatting
Your code has inconsistent formatting, sometimes there are spaces between operators and around braces, sometimes not. It doesn't really matter that much which code style you use, as long as you are consistent. Instead of manually fixing style issues, consider using a code formatting tool (either an external one like Artistic Style, or your editor's built-in code formatting functions) to keep your code looking tidy.


I recently got told that LINQ slows down your code.

Tell them they are wrong.

  Is there any better way to do this?

No. You first code for convenience and pretty code.

  Is the speed much different?

It doesn't matter unless you need to optimize it for speed but you do this only for parts that you have and can measure. You don't optimize code that you believe might by slow because someone heard from someone who heard from someone else that something might be slow.

Your ConfigHandler doesn't have to be IDisposable. You are not using any resources and clearing a dictionary isn't doing anything useful.

if (!File.Exists(configFile) || FileUtilities.IsFileLocked(new FileInfo(configFile)))

You should check only one condition at a time and log a precise message.

  "Either your config file couldn't be found, or its open somewhere else."

You are not helping yourself with this message. Each time any of these occurs you'll need to check both cases instead of only one.


How does it look?

Not so good.

Not thread safe.

Does not handle negative numbers well.

Forms "" with 0.

Prone to buffer overflow.

itoa() is not a standard function, yet it commonly returns a pointer.

A test harness
int main(void) {
  char buf[100];
  int test[] = {123, 456, 0, - 42, INT_MAX, INT_MIN};
  int n = sizeof test / sizeof *test;
  for (int i = 0; i < n; i++) {
    itoa(test[i], buf);
    printf("%-11d <%s>\n", test[i], buf);
  }
  return 0;
}

Output
123         <123>
456         <456>
0           <>
-42         <,.>
2147483647  <2147483647>
-2147483648 <./,),(-*,(>

It is not thread-safe due to the static, but is that an issue for a function such as this?

Yes.  Thread safety is expected.

If so, how could I update that? What other ways could I make improvements to it?

I really do not think this is a good place to use recursion given the potential for buffer overflow is a fair complication.
But if one must use recursion, consider adding error checking and test for various sorts of int including 0, INT_MAX, INT_MIN.
static char* itoa_helper(int number, size_t sz, char buffer[]) {
  if (sz == 0) {
    return NULL;
  }
  if (number <= -10) {
    buffer = itoa_helper(number / 10, sz - 1, buffer);
    if (buffer == NULL) {
      return NULL;
    }
    number %= 10;
  }
  *buffer = (char) ('0' - number);
  return buffer + 1;
}

char* itoa_recursive_alt(int number, size_t sz, char buffer[sz]) {
  if (sz == 0 || buffer == NULL) {
    return NULL;
  }
  char *s = buffer;

  if (number >= 0) {
    // Flip pos numbers to neg as neg range is greater.
    number = -number;
  } else {
    sz--;
    if (sz == 0) {
      *buffer = '\0';
      return NULL;
    }
    *s++ = '-';
  }
  s = itoa_helper(number, sz-1, s);
  if (s == NULL) {
    *buffer = '\0';
    return NULL;
  }
  *s = 0;
  return buffer;
}

int main(void) {
  char buf[100];
  int test[] = {123, 456, 0, -42, INT_MAX, INT_MIN};
  int n = sizeof test / sizeof *test;
  for (int i = 0; i < n; i++) {
    // char *s = itoa_recursive_alt(test[i], sizeof buf, buf);
    char *s = itoa_recursive_alt(test[i], sizeof buf, buf);
    if (s == NULL)
      s = "NULL";
    printf("%-11d <%s> <%s>\n", test[i], s, buf);
  }
  return 0;
}

Output
123         <123> <123>
456         <456> <456>
0           <0> <0>
-42         <-42> <-42>
2147483647  <2147483647> <2147483647>
-2147483648 <-2147483648> <-2147483648>


Seems like instead of re.findall, you should be using re.match on each line of the input individually. Something like this:

for line in text.splitlines():
    m = re.match(r'([12]\d{3}-[0-3]\d-[01]\d \d{2}:\d{2}:\d{2},\d{3}) .*rest_server::log_request:\d+ - REST call: <(\w+) (.*) .+?> with args ({.*?})(?: and content ({.*}))?.*?', text)
    # and then do something with m

The main problem with your original regex is that the first instance of .* could reasonably match a whole lot of the string; if you're not going to split the lines apart first, then at least you'd want to change .* to [^\n]* and so on throughout.

As a micro-optimization, you may find that re.compileing your regex first produces faster results; and if you're not compiling it ahead of time, I wouldn't be surprised if

([12]\d{3}-[0-3]\d-[01]\d \d{2}:\d{2}:\d{2},\d{3})

is outperformed by a simple

(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d)

Basically, don't try to be clever and you'll do fine.


how to optimize vba looping code using variables?

For a start:

Sub Testingloop()
' Move this to the top. It doesn't affect your code, but it is good practice
' to put statements like these at the top and bottom of your code to make them
' easy to find.
Application.ScreenUpdating = False

' This should be a number type and not a string
Dim endrown As Long

Dim ex As String
Dim ez As String
Dim eh As String
Dim eg As String
Dim el As String
Dim ee As String
Dim es As String
Dim ef As String
Dim ei As String
Dim i As Integer
Dim LastRowColumnA As Long

' Better method of loading in multiple args, this will allow you to get
' all of your args in one go, and thus will speed up performance a bit.
' Practicing this early will also make it easier to develop more complex
' projects in the future.
Dim arrArgs as Variant

' Create objects to hold the main workbook and worksheet you reference
' This allows for accurate range references.
Dim wb as Workbook, Dim ws as Worksheet

' Thisworkbook refers to the workbook containing the code.
Set wb = ThisWorkbook
Set ws = wb.Sheets("looping")

' Create a variable to hold the usedrange.
Dim rUsed as Range

' Qualified your cells reference with 'ws' to ensure the proper range is set
LastRowColumnA = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

ws.Activate ' Use Activate over select, but it is best to avoid either

endrown = ws.Range("I1000").End(xlUp).Row
    For i = 3 To endrown
        ' When referring to the same object repeatedly, use a with block
        ' This does a few things, first it allows your code to skip evaluation
        ' of your 'ActiveSheet' reference since it is already told where to look.
        ' It also makes your code easier to read, cleaner, and more efficient.
        With ws
            ee = .Cells(i, 9).Value ' Be sure to qualify your cells references
            ex = .Cells(i, 10).Value
            ez = .Cells(i, 11).Value
            es = .Cells(i, 12).Value
            ef = .Cells(i, 13).Value
            ei = .Cells(i, 14).Value
            eh = .Cells(i, 15).Value
            eg = .Cells(i, 16).Value ' I am assuming you intended to get the value here
            el = .Cells(i, 17).Value
        End With

        ' Instead of referring to the different ranges you could do something like
        ' arrArgs = ws.Cells(i, 9).Resize(8, 1).Value

        ' Using a declared variable is good practice, and may improve performance slightly
        Set rUsed = ws.UsedRange
        With rUsed
             .AutoFilter Field:=1, Criteria1:=ee
             .AutoFilter Field:=2, Criteria1:=ex
             .AutoFilter Field:=3, Criteria1:=ez
             .AutoFilter Field:=4, Criteria1:=es
             .AutoFilter Field:=5, Criteria1:=ef
             .AutoFilter Field:=6, Criteria1:=ei
             .AutoFilter Field:=7, Criteria1:=eh
        End With

        On Error Resume Next
        With ws
            .Range("H2:H" & LastRowColumnA).SpecialCells(xlCellTypeVisible).Value = eg
            .Range("I2:I" & LastRowColumnA).SpecialCells(xlCellTypeVisible).Value = el
            .ShowAllData
        End With
    Next i
End Sub

This won't make a tremendous impact on performance, but it will make your code easier to work with. I also strongly encourage you to use the array instead of creating a separate string for each value you need to filter by. Again, not a big performance impact, but a good start on improving your coding.

Finally, depending on what your code is attempting to do you could try performing the operations in an array. You may also want to consider changing the calculation mode of the worksheet to xlCalculationManual (or something like that).


Simple converter: Is it better to use a function within a function?

I think it depends on how self-evident the code is. If it's clear from context what the intent of a calculation or function call is, then I agree with @Sam that the code will be more concise without giving it a name.

On the other end though, depending on the context, 9 * x / 5 + 32 might not be obvious in what it's doing. You may find that giving that equation a name helps readability in general, which may trump conciseness.

In this exact case though, I don't think there's a ton of benefit to giving it a name unless you strongly suspected that you'd need it elsewhere in the future, or you personally like the way having a name reads. I think that that formula is well-known enough that most people would be able to tell what it's doing; especially when it's inside of a function called temperature.

In this case though, there's no good reason that the function should be inside of temperature. Defining one function inside of another suggests that the inner function has no meaning outside of enclosing function, which may be the case if you're forming a closure over a local variable or something similar. In this case though, cel_to_far is just simply taking a parameter and returning an output. It isn't using anything local to temperature. If you wanted to have a standalone function, I would definitely move cel_to_far outside of temperature. If you want it to be "private" to the module, prefix the name with an _:

def _cel_to_far(x):
    return 9 * x / 5 + 32

def temperature():
    . . .

You're only using two spaces of indentation. Please use four-spaces, as per PEP8.

t = user_in isn't useful. You're taking a line to rename an already short variable name to something obscure. If you need to reduce line lengths, there are other more readable ways of achieving that. Here though, the longest line is only 76 characters long after fixing the indentation and getting rid of t. That's not very long, and user_in is a much more descriptive name.

In both your main functions, you're getting float input from the user manually with a while True and try. In an effort to reduce duplication and centralize how you're handling input, I'd make a helper function:

def _ask_for_float():
    while True:
        try:
            return float(input('Number to convert:> '))

        except ValueError:
            print('Enter numbers only!')

Instead of repeating the while True: try . . . part, make that a function, then call the function. Notice how much neater this makes each of the functions:

def _ask_for_float():
    while True:
        try:
            return float(input('Number to convert:> '))

        except ValueError:
            print('Enter numbers only!')

def _cel_to_far(x):
    return 9 * x / 5 + 32

def temperature():
    user_in = _ask_for_float()
    result = 'is: {} degrees Fahrenheit'.format(_cel_to_far(user_in))

    print('Input: {} degrees Celcius'.format(user_in), result)

def milli():
    user_in = _ask_for_float()
    n = 1 * user_in / 25.4

    print('Input: {} millimeters is: {} inches'.format(user_in, n))

That immediately fixes any line-length issues by removing two levels of indentation, and makes each function trivial.

Finally, lines like:

print('Input: {} degrees Celcius'.format(user_in), result)

Can be written inline using f-strings. I'd collapse result back into the literal for readability as well:

def temperature():
    user_in = _ask_for_float()

    print(f'Input: {user_in} degrees Celcius is: {_cel_to_far(user_in)} degrees Fahrenheit')


Code will look much better once OP can use own functions.

  how can I improve my solution?

Meaningful names

Why is the credit card number called j.  How about cc_num?

Many others names need like-wise improvements.

Use bool

For flags, consider bool.

#include <stdbool.h>

bool flag;

Auto format

Use a development environment that supports auto formatting.  Do not format manually - just not efficient.

#include<stdlib.h>
#include<cs50.h>

int main() {
  long long x, j = 0;
  int len, i, len_flag, flag = 0, flag_val = 0, sp_len = 0, check_flag = 0; //basic integers related  to loop etc
  int res, sum, fin_sum = 0, h = 0, d2_sum = 0, d1_sum = 0, ff_num = 0; // variables  related to extracting numbers
  int sum_len = 0, in_sum = 0, in_fsum = 0, len_sum = 0, m = 0; // extraing numbers from more than single  sum result
  int sum_f = 0, sum_final = 0;

  do {
    x = get_long("enter a valid card number \n");
    j = x;
    len_flag = 0;
    len = 0;
    while (len_flag != 1) {
      x = x / 10;
      if (x == 0) {
        len_flag = 1;   //finding the lenght of the number
      }
      len++;
    }
    if (len == 15 || len == 16 || len == 13) {
      flag = 1;
      sp_len = 1;
    } else {
      flag = 1;
    }

  } while (flag != 1);
  ...

Define variables where needed

Rather than a sea of objects up front, defined them where needed.

Example: Refactor x.  Other variables can like-wise get defined closer to their usage.

  // long long x, j = 0;
  long long j = 0;
  ...

  do {
    // x = get_long("enter a valid card number \n");
    long long x = get_long("enter a valid card number \n");
    j = x;
    ...

    if (sum_len > 1) {
      // x = 0;
      int x = 0;

Spelling

//finding the lenght of the number
  finding the length of the number

Clean-up

For review purposes, no need for dead debug code.
Eliminate //printf("multi_res : %d \n",sum), etc.

Eliminate unused variables like m.

Comment code

Each chunk of code deserves to be a function, yet I understand that is prohibited for now.

I'd comment the chunks of code to help aide understanding.

  // Read input CC number
  // Set j as the CC#, len_flag as the CC# length, flag to 1, ...
  do {
    long long x = get_long("enter a valid card number \n");

Simplify

flag only used as 1.

  do {
    ...
      flag = 1;
  } while (flag != 1);

Replaceable with

  {
    ...
  }

Same for later do {  ... } while (check_flag != 1);.

Documentation

Within code I'd add an algorithm link:

// https://en.wikipedia.org/wiki/Luhn_algorithm

Why space before '\n' ?

// "enter a valid card number \n"
"enter a valid card number\n"

Chunks of code seem verbose

len_flag = 0;
len = 0;
while (len_flag != 1) {
  x = x / 10;
  if (x == 0) {
    len_flag = 1;   //finding the lenght of the number
  }
  len++;
}

versus

// decimal digit length of x
len = 0;
do {
  len++;
} while (x /= 10);


Few tips

For code quality, consider to give variables/fields more understandeable names.
For immutable Cell fields add readonly, it may affect the performance.
If you know how many items will be put in the collection, construct it with capacity new List<Cell>(count), capacity means initial size for the underlying storage not max items limit.
FirstOrDefault == null can be replaced with !Any.
You may add items directly to listValues i guess, and optimize out tempList or vice-versa. Then Sort by field with Linq, or custom comparer, or implement IComparable for Cell.
Cell can be struct? If yes, you can try to take an advantage of stack allocations (for small amount of data) instead of heap using Span<T>-related optimizations.

For 5th tip, this code (as far as I got the idea)
var listValues = new List<int>();
foreach (var item in tempList)
{
    listValues.Add(item.v);
}
listValues.Sort();
for (int i = 0; i < tempList.Count; i++)
{
    mat[tempList[i].r][tempList[i].c] = listValues[i];
}

Can be optimized as
int i = 0;
foreach (var item in tempList.OrderBy(x => x.v))
{
    mat[tempList[i].r][tempList[i].c] = item.v;
    i++;
}

Btw, I've tested various optimizations from listed above and more but got only insignificant performance boost. The slowest point is here FirstOrDefault(x => x.r == newR && x.c == newC). I have no idea how to improve it without moving the solution to different approach.
Ok, let's do it.
public int[][] DiagonalSort(int[][] mat)
{
    int width = mat[0].Length;
    int height = mat.Length;
    List<int> values = new List<int>(height);
    for (int j = 2 - height; j < width - 1; j++)
    {
        for (int i = 0; i < height; i++)
        {
            int offset = j + i;
            if (offset >= 0 && offset < width)
                values.Add(mat[i][offset]);
        }
        values.Sort();
        for (int i = 0, count = 0; i < height; i++)
        {
            int offset = j + i;
            if (offset >= 0 && offset < width)
                mat[i][offset] = values[count++];
        }
        values.Clear();
    }
    return mat;
}

~15% faster than initial solution.


Flattening a HashMap of (String → ArrayList) to an ArrayList

If it's really a list of entries that you want, then this is about as fast as it gets.

But it can be better:

Use interface types instead of implementations, for example List instead of ArrayList and Map instead of HashMap
Java 6 is no longer supported, and in Java 7 you should use the diamond operator to create new instances, for example: Map<String, List<String>> map1 = new HashMap<>();
Use better, more natural names, for example:

entry is better than ent
list is better than ls

Use unit tests to verify your implementation

Based on the above, here's an alternative implementation:

public static List<String> concatMapEntries(Map<String, List<String>> map) {
    List<String> finalList = new ArrayList<>();
    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        List<String> list = entry.getValue();
        for (String string : list) {
            finalList.add(entry.getKey() + " = " + string);
        }
    }
    return finalList;
}

And unit test:

@Test
public void testExample() {
    Map<String, List<String>> map1 = new HashMap<>();

    List<String> map11 = new ArrayList<>();
    map11.add("a");
    map11.add("b");
    map1.put("1", map11);

    List<String> map12 = new ArrayList<>();
    map12.add("c");
    map12.add("d");
    map1.put("2", map12);

    assertEquals("[1 = a, 1 = b, 2 = c, 2 = d]", concatMapEntries(map1).toString());
}


A few observations :

Numbers in javascript are IEE754 double precision float. All of them. There is no integer type. Which means that only 53 bits are available to describe the integer part. So it doesn't make sense to try to do integer operations on numbers bigger than that. Your numbers are wayyy too big and the results will be undefined. If you want to compute bigger numbers, you'll need to define your own format, you can't use the native numbers of javascript.

Using setTimeout or using a recursion might be amusing solutions but they're not terribly efficient (at least until we have tail call optimization in javascript). You'd better use a simple boring loop.


Right away, I see two bugs:

First, it is not valid to say

if (text.equals(EMPTY_STRING) || pattern.equals(EMPTY_STRING)) {
    return false;
}

… because a non-empty pattern can certainly match an empty string.

Second, it takes a state machine to do regular expression matching properly; all I saw in your code were a few pointers.  (What are indexP1, indexP2, and indexT supposed to stand for?  Is there some invariant stateabout them that you could write out in a comment?)  It seems that you are matching * and + greedily.  That can't be right; sometimes you might need to backtrack and consider another possibility in order to get a match.

I didn't analyze the code too deeply, but those two serious concerns suggest that you will need to work at this code a lot more anyway.


Guessing a unique 4 random digits number

As this part of the question has been skipped so far, I'll take it:

Do you think this is too hard?

I think it is. Similarly to your game, in classic Mastermind, the player has to guess a combination of 4 non-unique coloured pegs, and each time is given a mark for the number of correct position and colour combinations.

64 = 1,296 possible combinations

However, with your game (to borrow the nomenclature), there are 10 possible pegs, and as they're unique the combinations are:

10 x 9 x 8 x 7 = 5,040 possible combinations

Which is an increase of 288.8%, furthermore you're only giving the user 5 attempts to guess, as opposed to Mastermind's 6, 8 or 12. The reason Mastermind plays with a minimum of six, is that you get to test every combination, e.g:

However, when you increase the number of possibilities to 10, and reduce the guesses to 5, you can no longer do this, and the chances of never guessing a correct number increase dramatically, e.g.:

Therefore, I think you need to either increase the number of guesses to 10 (at the least), or chose a smaller set of things to guess, like A-F, 1-6, or something GUI based like Mastermind.


Find all consecutive sequences in an ordered set

You cannot get better than O(n²) because the result has the size of O(n²)

The Output has (n+1)*n/2 elements therefore you will always need O(n²) time to do the output.

You can only try to reduce the constant factor.


Convert data (adding and sorting) with JavaScript

My solution

I came with something more concise, readable and effective:

const convertData = data => {
  const obj    = {}, // Intermediate object {year => {letter => number}}
        result = [];

  data.forEach(array => {
    const [letter, year, number] = array;
    obj[year]         = obj[year] || {}; // Creating object if it doesn't exist
    obj[year][letter] = obj[year][letter] + number || number; // Create or increment property
  });

  Object.keys(obj).forEach(year => {
    Object.keys(obj[year]).forEach(letter => {
      result.push([letter, parseInt(year), obj[year][letter]]);
    });
  });

  return result;
};

/* ===== DEMO ===== */

const data = [
    ['a', 2010, 12], ['a', 2010, 20], ['a', 2011, 43], ['a', 2012, 25], ['a', 2012, 15],
    ['b', 2010, 40], ['b', 2012, 65], ['b', 2013, 20], ['b', 2013, 10], ['b', 2013, 15],
    ['c', 2010, 13], ['c', 2010, 17], ['c', 2011, 22], ['c', 2011, 32], ['c', 2011, 10], ['c', 2012, 45], ['c', 2013, 10], ['c', 2013, 20]
];

console.log(JSON.stringify(convertData(data)));
/* Output console formatting */
.as-console-wrapper { top: 0; }

Explanation

First part of my function (data.forEach()) builds intermediate object obj that looks like this afterwards:

{
  2010: {
    a: 32,
    b: 40,
    c: 30
  },
  2011: {
    a: 43,
    c: 64
  },
  2012: {
    a: 40,
    b: 65,
    c: 45
  },
  2013: {
    b: 45,
    c: 30
  }
}

The second part just iterates by years and for every year by it's letters and builds result array.

Optimized version

First part of my function (data.forEach() loop) can be replaced with

for (let i = 0; i < data.length; i++) {
  const [letter, year, number] = data[i];
  obj[year]         = obj[year] || {}; // Creating object if it doesn't exist
  obj[year][letter] = obj[year][letter] + number || number; // Create or increment property
}

It's simply change to the for loop, but it gives significant performance boost without compromising readability at all. Interestingly, despite .forEach()es are generally slower, replacing the rest of the code with regular loops has negative impact on performance.

ES5 version

function convertData(data) {
  var obj    = {}, // Intermediate object {year => {letter => number}}
      result = [];

  for (var i = 0; i < data.length; i++) {
    var letter = data[i][0],
        year   = data[i][1],
        number = data[i][2];
    obj[year]         = obj[year] || {}; // Creating object if it doesn't exist
    obj[year][letter] = obj[year][letter] + number || number; // Create or increment property
  };

  Object.keys(obj).forEach(function objForEach(year) {
    Object.keys(obj[year]).forEach(function yearForEach(letter) {
      result.push([letter, parseInt(year), obj[year][letter]]);
    });
  });

  return result;
}

/* ===== DEMO ===== */

var data = [
    ['a', 2010, 12], ['a', 2010, 20], ['a', 2011, 43], ['a', 2012, 25], ['a', 2012, 15],
    ['b', 2010, 40], ['b', 2012, 65], ['b', 2013, 20], ['b', 2013, 10], ['b', 2013, 15],
    ['c', 2010, 13], ['c', 2010, 17], ['c', 2011, 22], ['c', 2011, 32], ['c', 2011, 10], ['c', 2012, 45], ['c', 2013, 10], ['c', 2013, 20]
];

console.log(JSON.stringify(convertData(data)));
/* Output console formatting */
.as-console-wrapper { top: 0; }

Benchmark

@Flambino's solution:      17,241 ops/s ±1.2%
My solution:                      19,433 ops/s ±3.02%
My solution (optimized):  33,490 ops/s ±3.25%

Remarks to your code

Formatting

There are a few minor formatting problems:

You could combine multiple vars together,
Lack of spaces here and there, and multiple ones in other places,
Few semicolons are missing (despite optional, it's a good practice to have them),
Minor indentation issues.

Also you could add more spacing to all your blocks of code to aid readability.

Unnecessary continue

continue is very often a useful statement, although it shouldn't be used if it can be avoided without compromising readability. This in my opinion

for(var i = 0; i < data.length; i++) {
  if(namesFound[data[i][0]]) { continue; }
  nameArr.push(data[i][0]);
  namesFound[data[i][0]] = true;
}

could be replaced with

for (var i = 0; i < data.length; i++) {
  if (!namesFound[data[i][0]]) {
    nameArr.push(data[i][0]);
    namesFound[data[i][0]] = true;
  }
}

Loop iterator declaration

These two lines suggest that you treat variable i like if it had block scope, which is not the case:

for (var i = 0; i < data.length; i++) {
for (var i = 0; i < nameArr.length; i++) {

The way the code looks right now, after i is declared for the first time, it's available everywhere in the function containing it, or worse yet ― if it's all in a global scope, it's global variable. Block scope variable can be declared with ES6's let. If you don't want to or can't use it, you could declare i before both loops, and then go with i = 0 without var keyword.

Use strict equality operator whenever possible

This line

return arr[0] == nameArr[i];

could be easily replaced with

return arr[0] === nameArr[i];

That way no type conversion will be performed.

Don't declare functions within loops

You declare function withing your loops in your code. That way on each iteration you in fact create a completely new function.

Name your anonymous functions

Named function expressions may come in handy when it comes to debugging. Quoting "Named function expressions demystified" by Juriy "kangax" Zaytsev:

  In a nutshell, named function expressions are useful for one thing only — descriptive function names in debuggers and profilers.

Don't push it

sortByName[i] = result;

would be much more efficient than

sortByName.push(result);

Here's the benchmark:


Avoid converting data structures to string unnecessarily
Just store tuples of values in indegrees instead of strings:
if i == a:
    indegrees[i].append((i, b))
    indegrees[i].append((b, i))

Iterate over the keys in indegrees directly
In this piece of code:
for i in range(n):
    for j in range(n):
        if f'{i}-{j}' or f'{j}-{i}' in indegrees[i]:
            ...

What you are basically saying is: for every possible pair of integers, check if it's in indegrees, and if so, do something with it. That's very inefficient if there only few elements in indegrees. Why not just iterate over the keys of indegrees instead? You can do it with strings, but then you have to parse each key back into two values, if you store tuples instead it becomes really simple:
for i, j in indegrees:
    ...


Strip a newline and add more text to a Go bytes.Buffer

I believe you are over-complicating the handler function by introducing the deferred function with the start time closure. Additionally, you are performing 2 writes to accomplish the logging, when one would be better.

So, Why have the "defer"? This code:

    var b bytes.Buffer
    hand := handlers.CombinedLoggingHandler(&b, h)

    defer func(start time.Time) {
        prefix := bytes.TrimRight(b.Bytes(), "\n")
        os.Stdout.Write(prefix)
        fmt.Printf(" completed in %v\n", time.Since(start))
    }(time.Now())

    hand.ServeHTTP(res, req)

would be simpler to understand as:

    start := time.Now()
    var b bytes.Buffer
    hand := handlers.CombinedLoggingHandler(&b, h)

    hand.ServeHTTP(res, req)

    prefix := bytes.TrimRight(b.Bytes(), "\n")
    os.Stdout.Write(prefix)
    fmt.Printf(" completed in %v\n", time.Since(start))

Then, in addition, I would manipulate the bytes to trim and add the completion message, and then output them...., so I would change the last part of the code to be something like:

    msg := bytes.TrimRight(b.Bytes(), "\n")
    msg := append(msg, []byte(fmt.Sprintf(" completed in %v\n", time.Since(start)...)
    os.Stdout.Write(msg)

That still irks me a bit, because i don't like the os.Stdout.Write being a constant value in there.... I would make that a parameter somehow, or a constant of some sort....

var logDest io.Writer = os.Stdout


I suppose this code is used like:

var twitch = new Twitch();
twitch.update(function(){
  // called each time a site responds
});

A few things:

First, I see little benefit of this functionality being written using a constructor. It appears to be a singleton by functionality as it makes no sense spawning multiple instances. Consider a singleton instead:

var Twitch = (function(){

  // stuff

  return {
    update: function(){...}
  };

}());

Next is your AJAX. As pointed in the comments, use $.when to listen to multiple jqXHR objects and call the callback once everyone is resolved. The native counterpart to $.when is Promise.all.

Next is to make update return a promise instead of handing it a callback. This way, your caller is allowed to listen not only for the success but also the failures.

Next is to take advantage of array methods like map instead of loops.

Your code could be simplified into:

var Twitch = (function(){

  var baseUrl = 'https://api.twitch.tv/kraken/streams/';
  var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff"];

  return {
    update: function(){
      var promises = channels.map(function(channel){
        return $.getJSON(baseUrl + channel).then(function(data){
          var result = {};
          result[channel] = data;
          return result;
        });
      });

      return $.when.apply(null, promises).then(function(){
        var args = Array.prototype.slice.call(arguments);
        return args.reduce(function(results, result){
          return $.extend(results, result);
        }, {});
      });
    }
  };

}());

// Usage
Twitch.update().then(function(results){
  // Succeeded
}, function(){
  // Failed
});

Now if you have ES6 available (via transpiler, or a modern browser), this can be simplified further by using the new syntax and making it more compact.

var Twitch = (function(){

  var baseUrl = 'https://api.twitch.tv/kraken/streams/';
  var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff"];

  return {
    update(){
      var promises = channels.map(channel => {
        return $.getJSON(`${baseUrl}${channel}`)
                .then(data => ({[channel]: data}));
      });

      return Promise.all(promises)
                    .then((...args) => args.reduce((results, result) => Object.assign(results, result), {}));
    }
  };

}());

// Usage
Twitch.update().then(function(results){
  // Succeeded
}, function(){
  // Failed
});


Merge two sorted arrays, make more efficent (O(a+b))

Current code

The time complexity of your current code is indeed quite high and can be made \$O(a+b)\$ as you suggest.

But first, a few remarks about the code (some of these were already covered by @Tushar while I was writing this answer):

Nested functions: It's not very efficient to define a function inside a function. As far as I know, most JS interpreters would actually construct a new closure (simply – a new function) each time mergeArrays gets called. There's no harm in defining countInArrays next to mergeArrays, instead of inside it, and it will probably make your code faster.
Scope of variables:

The for-loop variables x and i in function mergeArrays are not declared with the var or let keyword, which makes them global. That means they will exist even after your function returns. For example, you could call your function, and after it returns you could print the value of x, because it's in global scope and therefore accessible from everywhere. You probably don't want that, so it's better to use the var keyword, as you do in the countInArray function.
However, a variable declared in a function using the var keyword has function scope. That means, if you use i in the first for and also in the second for, then the second var i = 0 is in fact a re-declaration of an already-existing variable. Fortunately ECMAScript 6 introduced the let keyword, which declares a variable within the scope of the block. That means a variable declared as for (let i = … will "cease to exist" after that for loop.
Ergo, if using i just within the for-loop, it's preferable to do it this way:

for (let i = 0; i < a.length; i++) …

Optimized version

@Tushar has posted a more performant version. However, if I'm not mistaken, the asymptotic time complexity of his improved version is the same as – or very similar to – the complexity of your original version.

Here is an implementation with \$O(a+b)\$ asymptotic time complexity.

A few things to note:

there is some code duplicity and it surely could be written more nicely,
I have not tested it very thoroughly – only on the samples you provided in your question,
EDIT: performance benchmark.

function mergeArrays2(a, b) {

    let res = [];
    let wasInBoth;  // Indicates whether a repeating value
                    // was in both `a` and `b`.

    let i = 0;
    let j = 0;

    while (i < a.length && j < b.length) {
        const elemA = a[i];
        const elemB = b[j];

        if (elemA === elemB) {
            // Same elements – add them both if not already present.
            if (!(elemA === res[res.length - 1] && wasInBoth)) {
                res[res.length] = elemA;
                wasInBoth = true;
            }
            i++;
            j++;
            continue;
        }

        // Different elements – check if either of them is already
        // in `res` and was in both `a` and `b`. If yes, remove it
        // from `res`, because its number of occurrences in `a` and `b`
        // is not the same.
        if (wasInBoth) {
            wasInBoth = false;  // Not any more.

            if (elemA === res[res.length - 1]) {
                // `a` contains more occurrences of the element than `b`.
                // Remove the element from `res` and skip
                // all the occurrences of the element in `a`.
                res.length--;
                while (a[++i] === elemA);
                continue;
            }
            else if (elemB === res[res.length - 1]) {
                // `b` contains more occurrences of the element than `a`.
                // Remove the element from `res` and skip
                // all the occurrences of the element in `b`.
                res.length--;
                while (b[++j] === elemB);
                continue;
            }
        }

        // Different elements – select the least.
        // Add it if not already present.
        if (elemA < elemB) {
            if (elemA !== res[res.length - 1]) {
                res[res.length] = elemA;
            }
            i++;
        }
        else {
            if (elemB !== res[res.length - 1]) {
                res[res.length] = elemB;
            }
            j++;
        }
    }

    // Process the rest of `a` or `b`, whichever is not done.
    let [rest, idx]  = (i < a.length)? [a, i] : [b, j];

    while (idx < rest.length) {
        const elem = rest[idx];

        if (wasInBoth) {
            wasInBoth = false;

            if (elem === res[res.length - 1]) {
               // Same as before – remove from `res`
               // and skip all further occurrences.
                res.length--;
                while (rest[++idx] === elem);
                continue;
            }
        }

        // Same as before – add if not present.
        if (elem !== res[res.length - 1]) {
            res[res.length] = elem;
        }
        idx++;
    }

    return res;
}


Thread-safe callback registration and invocation in C++11

From your concerns:

EventGenerator::{Add,Remove}Handler should be safe to call from EventDelegate::Invoke, though any updates won't be reflected in the current loop iteration in ThreadTask.
Your shared_ptrs are pointing to the same EventDelegate class, and you're using an atomic bool. This should behave properly.

My concerns are more minor. Your test code is too simple to catch many bugs (if they exist). Your ThreadTask function should use a for loop rather than while(true). You should consider using the remove/erase idiom in RemoveHanler. Finally, your code allows multiple copies of the same handler to be added. I don't know if that's intentional or not.


Print Consecutive numbers by comparing two parameters

The function name is weird.  What is it testing?  A more appropriate name might be printInclusiveRange(…, …).

Since the bounds are inclusive, I would expect that for input 3,3, the output should be 3.  Yet you output nothing.

I would also expect the output not to end with a Tab character.

Here's one solution that corrects those two problems, and also combines the loops:

public static void printInclusiveRange(int a, int b) {
    System.out.print(a);
    if (a != b) {
        int i = a;
        int step = (a < b) ? +1 : -1;
        do {
            i += step;
            System.out.print("\t" + i);
        } while (i != b);
    }
    System.out.println();  // Perhaps you want a newline here?
}


What is the difference between this two way and Which one is best? What do you suggest?

The difference is that you seperate the concerns in the second example. This means that you can change from database type (e.g. a SQL database, a XML file, an array, ect.) without changing to much code. In fact, you only create a new Model and you are ready!

  Whether this is a good example of mvc? How can fix 2 example above for good mvc?

I think you mean that you want to know if this is correct MVC and, if not, how to change it. It is better to put all those logic (except the first line) inside a Model and call that specific method inside your controller. I have used CI once, so I can't help you with code examples...


How to deal with elimination of duplicate logic vs. cost of complexity increase?

Why not something like...

static void Main(string[] sargs)
{
    try
    {
        var urls = new DirectTrackRestUrls();
        var restCall = new DirectTrackRestCall();
        var logger = new ConsoleLogger();
        Args args = (Args)Enum.Parse(typeof(Args), string.Join(",", sargs));
        if (args.HasFlag(Args.Campaigns))
        {
            GetAndSaveResources(urls.ListAdvertisers, true);
        }
        if (args.HasFlag(Args.Advertisers))
        {
            GetAndSaveResources(urls.ListAdvertisers, true);
        }
        if (args.HasFlag(Args.CampaignGroups))
        {
            GetAndSaveResources(urls.ListCampaignGroups, false);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.InnerException);
        Console.WriteLine(e.StackTrace);
    }
}

void GetAndSaveResources(IList list, bool setAccessId) {
    var getter = new ResourceGetter(logger, list, restCall);
    if (setAccessId)
        restCall.UriVariables.Add("access_id", 1);
    getter.GotResource += new ResourceGetter.GotResourceEventHandler(getter_GotResource);
    getter.GetResources();
    SaveResources();
}


Searching for an idiomatic Rust implementation of Minimum Edit Distance (LeetCode #72)

The first thing I noticed about both versions of your code is the plenitude of single-letter names, something you can improve upon.  Incidentally, Rust uses snake_case for variables, so the compiler would have warned you about D.
Now, let's talk about the struggles I presume you have by reading the Rust code.
First of all, you probably felt forced to convert between i32 and usize all the time.  The decision to return i32 instead of usize is a typical indicator of the less-than-ideal quality of LeetCode interfaces (as usual).  In fact, it goes worse - impl Solution is not a good idea in Rust, and there is no reason to take the ownership of strings here.  My advice here would be to perform all calculations using usize and only convert to i32 at the very end.
I assume HashMap<(i32, i32), i32> results from the lack of multi-dimensional vector support in Rust.  Indeed, my first choice would be to use ndarray in this scenario, which is not available in the standard library.  You can make a small wrapper for this:
struct Vec2<T> {
    elements: Vec<T>,
    n_rows: usize,
    n_columns: usize,
}

and derive Index<(usize, usize)> and IndexMut<(usize, usize)>.  Or you could sacrifice some performance and use Vec<Vec<usize>>.
Instead of
let w1: Vec<char> = word1.chars().collect();
let w2: Vec<char> = word2.chars().collect();

I would simply use .as_bytes(), assuming that LeetCode doesn't consider multi-byte characters.

Here's how I reassembled everything according to the Java version: (not tested)
pub fn min_distance(word_a: String, word_b: String) -> i32 {
    let word_a = word_a.as_bytes();
    let word_b = word_b.as_bytes();

    let len_a = word_a.len();
    let len_b = word_b.len();

    let mut matrix = vec![vec![0; len_b + 1]; len_a + 1];

    for i in 0..=len_a {
        matrix[i][0] = i;
    }
    for j in 0..=len_b {
        matrix[0][j] = j;
    }

    for i in 1..=len_a {
        for j in 1..=len_b {
            matrix[i][j] = if word_a[i - 1] == word_b[j - 1] {
                matrix[i - 1][j - 1]
            } else {
                1 + matrix[i - 1][j - 1]
                    .min(matrix[i - 1][j])
                    .min(matrix[i][j - 1])
            };
        }
    }

    matrix[len_a][len_b] as i32
}

The restriction of LeetCode (poor interface, no external crates) caused me to be lazy, so I used nested Vecs.  In a real-world scenario, ndarray::Array2 would be a far better choice.
Besides, this is still far from optimal for Rust, where we tend to avoid manual indexing and - 1.  Taking into account the algorithmic nature of this application, I won't go deeper into this.


How to stop a Python script if the input values do not make sense within the environment in which they will be analyzed?

To me you're kind of handling the exception in two ways:

you are acting like a library in the sense that you talk about an exception to be raised;
you are acting like an application in the sense that you print out error messages and then continue running.

I think you are mainly having the script / function be used as a library, as you return the matrix rather than printing it out. If you talking about handling the exception for a library function, which seems most reasonable, then you should raise an exception rather than returning a magic value (m = 0) that you can check. Make sure that the exception has a clear message that may be put into a stacktrace in case it isn't handled. So you catch and re-raise.

In your case it is probably best to throw a more specific exception in _get_coords though, e.g.:

raise ValueError(f'source_points = {source_points}' +
                 '\n could not be broadcasted as a numerical array' +
                 '\n with shape = (n, 3).')

  It works fine to me, because I can check if m == 0 in the other script to stop it

That's exactly what exceptions are for. Just let the other script catch it and stop. The situation could be different if you would want to keep on running with a different matrix.

Magic values are often unclear to the reader, and may be skipped on accident. Try to avoid them as much as possible. You don't want to run on with the magic value as invalid state, so raise and make sure you don't.

The same thing happens when you print Processing... to the output stream. Generally library functions don't print to the output stream. If you want to have a progress indication, then allow some kind of progress reporting function to be present as parameter or class field, and report progress that way. If you just want to indicate that it started progressing then you should however just let the user of the library report that a function is called.

Using a logger rather than output stream would be highly advisable.

You can find more information about listeners here. Logging is also mentioned over there, which is likely not coincidental.


Well, if it's for the life of the program as you say, then no. When the program ends, all memory will be released.

Second, this all looks like one class. So root references will be removed when the class is GC'd and no memory leak will occur.

Lastly, write

        if (btnSync.Enabled == true)
            btnSync.Enabled = false;
        else
            btnSync.Enabled = true;

as

        btnSync.Enabled = !btnSync.Enabled;

Much more concise.


The flaw in your algorithm is that you're summing for each item in each array. That means you get \$O(n^2)\$ for time complexity.

Sum once, then add to the left side whilst removing from the right side. This will give a time complexity of \$O(2n)\$ (once to sum, another to move each element over from the left to the right side).

Additionally, once you have found 1 case in which both sides match, you can stop looking for that testcase.


Leetcode: Flatten binary tree to linked list C#

The first condition is a bit conservative:

if (root == null || (root.left == null && root.right == null))

Just if (root == null) would be enough, the rest of the implementation naturally handles the cases of root.left == null && root.right == null.

Evaluating curr != root for every node, when it's only useful for the first node is a bit ugly.
You could get rid of that by not adding root itself on the stack, but its children. (In the right order, and when not null.)

head is a misleading name for a variable that traverses all the nodes,
especially since the end result is effectively a linked list,
where "head" usually means the first element.
I'd rename this to node.

All the curr.right = null; can be safely dropped,
because curr.right will either get overwritten with the intended value,
or it's null to begin with (in the very last node).

An \$O(n)\$ solution exists without using a stack:

When left is null and right is not, advance over right
When right is null and left is not, move left to right and advance over right
When both not null of node, then:

traverse through all the right descendants of node.left, and append at the end node.right
move node.left to node.right and advance over it


There is no need for sleep and work to take the time as an argument. Just return what the user enters and calculate in the main function. The main part of the code should be guarded by a if __name__ == "__main__": guard, which ensures that that code is only executed when running the script but not when importing from it.

Python 2 will soon be no longer supported. If you are starting to learn Python now, learn Python 3 straight away. In the code below the main differences are that raw_input is now input (and the Python 2 input no longer exists), print is no longer a statement, but a function (so surround it with (), instead of ), division is now float division by default (use // for integer division) and finally string formatting has become a lot easier in Python 3.6 with f-strings.

def ask_time(message):
    while True:
        try:
            hours = float(input(message))
            if 0 <= hours <= 24:
                return hours
        except ValueError:
            pass
        print("Please enter a number between 0 and 24")

def see_percent():
    reply = input("Would you like to know the percent of your waking time is free time? (Y/N): ").lower()
    return reply == "y"

if __name__ == "__main__":
    total_time = 24.  # hours
    sleep_time = ask_time("How many hours do you sleep a night?: ")
    work_time = ask_time("How many hours do you work each weekday?: ")

    waking_time = total_time - sleep_time
    free_time = waking_time - work_time
    print(f"You have {free_time:.2f} hours of free time.")
    print(f"Of the 24 hours in a day, you are awake for {waking_time:.2f} of them.")

    if see_percent():
        percent_free = free_time / total_time
        print(f"{percent_free:.2%}.")

I also made a more general ask_time function which ensures that the user enters a valid number between 0 and 24 and keeps on asking if they didn't and used four spaces throughout, as recommended by Python's official style-guide, PEP8.


Throwing exceptions in a database wrapper

Are you sure you want your database wrapper to be static? What if you want to mock it in your unit tests?

I would make it a plain old class, pass the connection string through the constructor and do any kind of checks that I want right there, because that means your database wrapper won't be allowed to even exist without a valid connection string. With your current design, you're forced to check the connection string in each method, therefore duplicating code, and duplication is generally a no-no.

Static classes do have their use cases, but this is really not one of them. You usually want to write static classes to group methods that don't deal with any specific object, but here you are indeed dealing with something that, being a database, is about as specific as it gets.

Also, what's the GetHighestID method for?
I'm asking because I had to deal with codebases that, instead of letting the database do the auto-increment, would exactly do a SELECT MAX(Id) and add 1 before doing INSERTs.

In case that is what you're doing, then stop, because it defeats the purpose of having an auto-increment column at all. Also, the fact that the column is set to auto-increment is something your code shouldn't need to know about. As far as your code is concerned, all it needs to know is the name of the field that is the designated key for the table.
Plus, a database can handle auto-increments much better than you ever will, even more so when it comes to concurrent writes.

Last but not least, exceptions. Don't throw NullReferenceExceptions. That's the job of CLR, not yours. Now, with my design the need to throw it just goes away, but I just thought I would mention this. Throwing a NullReferenceException manually stinks.

Edit

  Well, the reason why I made it static is because the class has to be
  used in several classes. I have for ex. classes like Item, Person,
  Factory, ... which all have an interaction to the database. Each class
  has an Insert, Update, ... method. In my POV it looks easier to set
  the connection once e.g. while starting the application and then be
  able to use the class everywhere without having to initialize it every
  time.

You're right that it looks easier, but it really is not.

Let's examine the options we have here:

a static database wrapper, this would be your design
a non-static class
a non-static class implementing an interface

Option 2 would look like this:

class ClientClass
{
    private readonly Database _database;

    public ClientClass()
    {
        _database = new Database(ConnectionString);
    }
}

Now, the problem with options 1 and 2 is that, should you ever want to write unit tests for one of the classes that uses your database wrapper without actually issuing queries to the database, you would be out of luck.

And since you should be writing unit tests, you are indeed out of luck.

Why is that, though? Because you can't create a class that looks like your database wrapper but, for instance, returns the data you decide upon calling a hypothetical Select method.

Option 1 doesn't allow that because, even if you wrote such a class, you would have no way of substituting your FakeDatabase class without physically replacing FakeDatabase with Database in all the classes that use it. Static classes are initialized only once, so how are you going to swap the real implementation with a fake one?

Option 2 doesn't allow that either, because the name of your database wrapper is wired in the constructor of the class. There is still no way you can swap Database with FakeDatabasewithout touching the code.

Plus, option 2 is just bad because now your client classes need to know that a connection string exists at all, when they really shouldn't.

Option 3 is described down here:

  From what you say I understand that I should initialize the
  class each time and pass the connection string before calling the
  method. If not, what approach would you suggest?

That's correct. As @craftworkgames said, classes that need to communicate with the database get an instance of the database wrapper passed in, generally through the constructor.

To be even more precise, once your database wrapper is ready, you will want to extract an interface, let's call it IDatabase, that exposes all the wrapper's public method, and have your wrapper implement it.

Client classes, then, will have a constructor such as this:

class ClientClass
{
    private readonly IDatabase _database;

    public ClientClass(IDatabase database)
    {
         _database = database;
    }
}

Now you're golden, because if FakeDatabase implements IDatabase too, when writing a unit test you can pass in an instance of FakeDatabase with your client class none the wiser.

Client classes only need to know that the class you pass in exposes a certain set of methods. It does and should not know anything about how and from where that class pulls the data it returns, or where it writes to. Is it a RDBMS? Is it an XML file? Something else altogether? Client classes don't have to care about that, which is good, because it gives you the option to swap data stores without changing anything else.

Option 3 is called dependency injection. All the information you need is just a google away.

You could also read about:

programming to the interface, not the implementation
unit testing
mock objects

Lastly, this concept of making classes as unaware of the workings of other classes as possible, applies to every level of your architecture. A database layer just happens to be one of the prime examples.

Gosh, I hope all of that made sense.


It seems strange to me for Get to be a specific way of getting all items, and GetAll should always return all items. Introduce a GetSome helper for clarity.

public T Get(Func<T, bool> predicate) {
    return GetWhere(predicate).FirstOrDefault();
}

public IEnumerable<T> GetAll() {
    return GetWhere(null);
}

public IEnumerable<T> GetWhere(Func<T, bool> predicate) {
    IEnumerable<T> result = _dbContext.Set<T>().AsEnumerable();
    return (predicate == null) ? result : result.Where<T>(predicate);
}

  Caveat: I don't write C# so perhaps this doesn't match the standard pattern there.


Thread safe reader-writer queue with C++11

There's no way to notify locked consumers of the write end. You might want to modify PopFront and NotifyWriteEnd to return a special null value to every awaiting consumer (or otherwise wake up all the awaiting consumers and notify them the queue is exhausted) when NotifyWriteEnd() is called. Otherwise you'll need a rather serious contract inherent in your application design, that every consumer should know in advance that it would be able to get a matching producer before starting awaiting on the queue.


Likely logic flaw

In the first conditional:

if (regex.test(pattern) && (arr.filter(s => s.includes(pattern)) != 0)) {

Array.filter() "creates a new array"1 so the second conditional expression compares an array with zero. Those two should never be loosely equal so that conditional always evaluates to true. Perhaps you intended to check the length property of the array.

Improving efficiency

The code has repeated operations - e.g. arr.filter(s => s.includes(pattern)) appears twice, and then there are multiple calls to pattern.match(). The call to arr.filter() could be stored in a variable and then used whenever needed instead of re-filtering.

Also, the regular expression stored in regex could be used with String.match() to get an array of matches. Because the regular expression has capturing groups, those capturing groups can be used instead of calling pattern.match(/\./g) multiple times to check for the number of dots. Instead, check if the array returned by String.match() isn't null and then if the 2nd and 3rd elements are undefined.

See a comparison in this jsPerf.

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter


Hope this might be helpful -

function getRelativeTime(ms){
    var SECOND_MS = 1000;
    var MINUTE_MS = 60 * SECOND_MS;
    var HOUR_MS = 60 * MINUTE_MS;
    var DAY_MS = 24 * HOUR_MS;
    var WEEK_MS = 7 * DAY_MS;
    var MONTH_MS = 30 * DAY_MS;

    var lookup = ["months", "weeks", "days", "hours", "minutes", "seconds"];
    var values = [];
    values.push(ms / MONTH_MS); ms %= MONTH_MS;
    values.push(ms / WEEK_MS); ms %= WEEK_MS;
    values.push(ms / DAY_MS); ms %= DAY_MS;
    values.push(ms / HOUR_MS); ms %= HOUR_MS;
    values.push(ms / MINUTE_MS); ms %= MINUTE_MS;
    values.push(ms / SECOND_MS); ms %= SECOND_MS;

    var pretty = "about ";
    for(var i=0 ; i <values.length; i++){
        var val = Math.round(values[i]);
        if(val <= 0) continue;

        pretty += val + " " + lookup[i] + " ago";
        break;
    }
    return pretty;
}

getRelativeTime(10000);

Output :

about 10 seconds ago

You can easily customize above code for your "xx hours and xx mins ago" use-case. Just change the for loop like this -

for(var i=0 ; i <values.length; i++){
    var val = Math.round(values[i]);
    if(val <= 0) continue;

    pretty += val + " " + lookup[i];

    var nextval = Math.round(values[i+1]);
    if(i+1 < values.length && nextval > 0){
      pretty += " and " + nextval + " " + lookup[i+1] + " ago";
    }
    else {
      pretty += " ago";
    }
    break;
}

Output

getRelativeTime(100000);

about 2 minutes and 40 seconds ago

getRelativeTime(1000000);

about 17 minutes and 40 seconds ago

UPDATE:

  Math.round is causing wrong result in above code, Math.floor is more
  appropriate.


This is not entirely only in your imagination

Random objects are meant to be reused. Recreating a Random object each time may cause a specific pattern in the result. This depends a bit on the Java version. There is no need to pick a seed, Java picks a seed for you based on a varying number, and the current system time (see Java 6 source). Newer versions of Java uses a better seedUniquifier method. I am not sure about what implementation the Android platform uses.

Additionally, Java variable names should start with lowercase letters by the coding conventions.

I would also use a StringBuilder for better efficiency and lower memory usage.

To avoid confusion with the Charset class, I would name your String variable chars and your int variable length.

private static final Random random = new Random();
private static final String CHARS = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ234567890!@#$";

public static String getToken(int length) {
    StringBuilder token = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
        token.append(CHARS.charAt(random.nextInt(CHARS.length())));
    }
    return token.toString();
}


stack_delete only returns true. If a return value from a function carries no information, better make it void.
There is no consistency in testing parameters. Some functions test for self not being null, other directly proceed to calculating self->root.
The Stack existence is only justifiable if it has more data members than just root. As @glampert mentioned in comments, tracking size is one of the candidates. On the other hand,  abandoning Stack for good, and letting client manage the root, as in

Node * stack_push(Node * root, data);
....

root = stack_push(root, data);

is also a viable strategy.
It would be nice to provide a non-destructive top() interface to access the root data. There is even a popular belief that a pop-like function should only pop an element from the top of stack (as opposed to pop element and return data); in this school of thought top() is a must.


Yes, I believe it's equivalent to the third duality theorem which states that for any finite list xs,

foldr op u xs = foldl (flip op) u (reverse xs)

Without appealing to the theorem, we can still prove your definition correct for any finite list xs. We'll need  definitions of foldl and foldr:

Definition

(1) foldr _ u [] = u
(2) foldr op u (x:xs) = op x (foldr op u xs)

Definition

(3) foldl _ u [] = u
(4) foldl op u (x:xs) = foldl op (op u x) xs

And the following:

Lemma For finite lists xs, ys, foldr op u (ys ++ xs) = foldr op (foldr op u xs) ys.

Case []

RHS = foldr op (foldr op u xs) []
    = foldr op u xs -- by (1)
    = foldr op u ([] ++ xs)
    = LHS

Case y:ys

RHS = foldr op (foldr op u xs) (y:ys)
    = op y (foldr op (foldr op u xs) ys) -- by (2)
    = op y (foldr op u (ys ++ xs)) -- by induction hypothesis
    = foldr op u (y:ys ++ xs) -- by (2)
    = LHS

∎

Claim For any finite list xs, foldr (flip op) u (reverse xs) = foldl op u xs.

Case []

LHS = foldr (flip op) u (reverse [])
    = foldr (flip op) u []
    = [] -- by (1)
    = foldl op u [] -- by (3)
    = RHS

Case x:xs

LHS = foldr (flip op) u (reverse (x:xs))
    = foldr (flip op) u ((reverse xs) ++ [x])
    = foldr (flip op) (foldr (flip op) u [x]) (reverse xs) -- by the lemma
    = foldr (flip op) ((flip op) x (foldr (flip op) u [])) (reverse xs) -- by (2)
    = foldr (flip op) ((flip op) x u) (reverse xs) -- by (1)
    = foldl op ((flip op) x u) xs -- by induction hypothesis
    = foldl op (op u x) xs -- by definition of flip
    = foldl op u (x:xs) -- by (4)
    = RHS

∎