Count Words in Quotes Fetched from Website

For quote-word-count, there's a few things to note.

I think this is a good use of ->>. Personally, I would have started the threading with (range quote-count) instead of splitting that though. From my experience, needlessly elongating the thread call just hurts readability. I also recommend maintaining the same type of object being threaded all the way down. I find it makes the thread much easier to understand. If you're threading collections like you are here, I'd prefer that every object being threaded is a collection (whereas quote-count is a number).

It isn't a good idea to use map to run side effects (like starting a future task). map doesn't run its effect immediately, so the futures aren't started when (map (fn [_] (fetch-quote))) runs, they're started when the pmap begins requesting elements. I'd switch to mapv which is strict, so the future's are started right away.

I don't think that mapping a range is the right approach here though; which is hinted at by your use of a wrapper (fn [_]) function. repeatedly would be a better candidate for this situation. It's lazy though, so I'd probably add a call to vec after it to realize it right away.

Your zero is actually unnecessary. fnil can be used here instead:

(update word-counts word (fnil inc 0)))

I wouldn't have parameters called quote ideally. quote is a rather important built-in, and it's a good idea to avoid shadowing built-ins.

I'd probably use ->> in count-words:

(defn count-words
  [quote]
  (let [cleaned-quote (clean-input quote)]
    (->> (clojure.string/split cleaned-quote #" ")
         (reduce update-word {}))))

I personally find that to be much more readable than the nested version.

I'll note too that Clojure has the built-in frequencies that can do the work here:

(defn count-words
  [quote]
  (let [cleaned-quote (clean-input quote)]
    (->> (clojure.string/split cleaned-quote #" ")
         (frequencies))))

In clean-input, I wouldn't use comp. I think it would be much neater using ->:

(defn clean-input
  [input]
  (->> input
       (clojure.string/lower-case)
       (remove-author)
       (remove-commas)))

I really only like comp when it's being passed to another function. Writing out ((comp g f) x) just seems like an overly complicated way of applying x to f then g.

Your functions are in reverse order for some reason. I'm not sure where you're running this that's allowing for functions to be used before they're declared.

Personally, I like having the parameter vector on the first line unless I have a doc string. I find the functions look noisy otherwise.

You're writing clojure.string/ a fair amount. You may want to require that module to avoid verbose, qualified function calls. While you're at it, you might as well add a ns macro call, since each file should really have one anyways:

(ns your.file.path.here
  (:require [clojure.string :as s]))

Now, clojure.string/split can be written as s/split.

And for 3.:

  The function will take the number of quotes to download as an argument and return the atom’s final value.

It wants you to return the value of the atom, not the atom itself. They want you to update an atom inside the futures; although I don't think that's necessary, or even preferable.

Here's the final code I ended up with:

(ns your.file.path.here
  (:require [clojure.string :as s]))

(defn remove-author [quote]
  (s/replace quote #".\n-- .*\n" ""))

(defn remove-commas [quote]
  (s/replace quote #"," ""))

(defn clean-input [input]
  (->> input
       (s/lower-case)
       (remove-author)
       (remove-commas)))

(defn count-words [quote]
  (let [cleaned-quote (clean-input quote)]
    (->> (s/split cleaned-quote #" ")
         (frequencies))))

(defn fetch-quote []
  (future (slurp "https://www.braveclojure.com/random-quote")))

(defn quote-word-count [quote-count]
  (->> (repeatedly quote-count fetch-quote)
       (vec)  ; To ensure futures start before pmap begins processing chunks
       (pmap (comp count-words deref))
       (apply merge-with +)))


After spinning two routines main should wait for them to terminate. See sync package for common synchronisation primitives. fmt.Scanln is for input reading.
http.Get may return error. Proper way would be to handle it.
resp.Body will be closed when downloadData returns and readData won't be able to use it anymore.

Regarding your questions:

As stated by documentation resp.Body must be closed. Close it as soon as you don't need it anymore.
The code lacks error checks and proper routines synchronisation. Despite the fact this code is compiling, this is not acceptable Go code and it must be fixed.

I suggest you to read Effective Go for concurrency and error handling overview.


Selecting a subset of the data from a list

It looks like you want to split a large list of items to equal sized chunks.
I suggest using a helper generator:

def chunks(items, size):
    for start in range(0, len(items), size):
        yield items[start:start+size]

Using this, your main task becomes simply:

for day_list in chunks(all_dates, 24):
    print_dates(day_list)


"Browser-sniffing" is bad, usually because the methods used to detect them are usually "spoofable" and unreliable

User Agent string can be spoofed (changed) and can't be relied on. In fact, vendors change UAs to tell websites they are another browser, some for valid purposes. I think it was IE10 who added a "Mozilla" to their UA to tell websites to load non-IE versions of pages, with confidence that the newer IE will render "unhacked"/not modified for IE pages without breaking.

Even if you UA strings are fixed, you can't keep track of the 70+ (I think it was 70+, or something with a 7) different browsers in the wild today. Yes, there are browsers other than the major 5, like mobile browsers, command-line browsers, headless browsers. And don't forget to count the older versions, do still use them.

Recently, developers use feature testing instead, to check if certain features are available in the browser. Modernizr is an example of such frameworks.


There are 2½ things wrong with your code, otherwise it's fine.

Use exception handling with try/catch for exceptional circumstances, not for trivial bounds checking which you can do! The snippet

try {
      upperLeft = triangle[i - 1][j - 1];
} catch (ArrayIndexOutOfBoundsException e) {
     upperLeft = 0; //upperLeft is 0 if not found
}

throws an error if j == 0 – you already handled the i == 0 case. You can avoid this by starting the loop one index later, and just putting a 1 in the first field. The same considerations hold for the last array entry.

When we initialize the bounds outside of the loops, we get something like:

// init first row
triangle[0] = new long[]{ 1 };

for (int i = 1; i < depth; i++) {
    triangle[i] = new long[i + 1];

    // init first and last element
    triangle[i][0] = 1;
    triangle[i][i] = 1;

    for (int j = 1; j < i; j++) {
        long left  = triangle[i - 1][j - 1];
        long right = triangle[i - 1][j    ];
        triangle[i][j] = left + right;
    }
}

By handling these edge cases seperately, I can radically shorten the code, and can omit exception handling.
In- and Output should happen in the main method, not in helpers. You have written a printTriangle method, which hardcodes the System.out stream. It would be better to assemble a string representation in a toString() method, and then print out the result from that:

public String toString() {
  Formatter formatter = new Formatter(new StringBuilder(), null);
  for (long[] row : triangle) {
    for (long i : row) {
      formatter.format("%d ", i);
    }
    formatter.format("\n");
  }
  return formatter.toString();
}

Then in main: System.out.print(triangle.toString()).

What I haven't addressed until now is your usage of variables. You should declare your variables as close to their point of usage as possible, and in the tightest possible scope. Your upperLeft etc. is only relevant inside the else branch of your original code – if you look at my version, you see I declared the corresponding variable inside the loop as well.

Oh, and your names for the loop variables in printTriangle() are weird. The letters i and j usually denote integers in loops, a convention taken from mathematics into programming. It is better to use names that are actually connected to the problem you are solving. If you look at my snippet, you'll see that I iterate over each row in the triangle, and then over each long integer i in that row.


I want to focus on just the getGraphStartAndEndPointsInRadians() method of your class, as this is the area I see the most problems with a cursory glance.

First of all, from the method name alone, I can tell it does too much.  The word "and" should very rarely be used in method names.  It's usage is usually a sign that a method does too much.  And this one does.

First thing we can do is refactor out the percent-to-radians conversions into their own method.

func percentToRadians(percent: CGFloat) -> CGFloat {
    return (2 * CGFloat(M_PI)) / 100) * percent
}

Next, this logic has no business in the method:

    // make sure our starting point is at least 0 and less than 100
    if ( 0 > self.startPoint ) {
        self.startPoint = 0
    } else if ( 100 < self.startPoint ) {
        self.startPoint = 100
    } // if

    // make sure our fill percentage is at least 0 and less than 100
    if ( 0 > self.fillPercentage ) {
        self.fillPercentage = 0
    } else if ( 100 < self.fillPercentage ) {
        self.fillPercentage = 100
    } // if

Instead, this logic should go somewhere more closely related to the actual setting of these variables.  Like in the didSet method.

A method with get in the name definitely shouldn't have side effects like this.  (And we really don't use get in method names either.)

As an aside, all of your variables should have didSet methods that assure that the view is redrawn when their values are changed.

So, we're agreed that we'll move side-effecting logic out of this method, and that we'll refactor the percent-to-radian logic out, now we just need to split the methods.  We need one for the start point and one for the end point.  Why don't we do these as computer properties?

private var startingDrawPoint: CGFloat {
    return percentToRadians(CGFloat(self.startPoint) - 25)
}

private var endingDrawPoint: CGFloat {
    return percentToRadians(CGFloat(self.fillPercentage - self.startPoint) - 25)
}


Mean shift image processing algorithm for color segmentation

The following code is a first shot and it is still not vectorized. The major points here are the extraction of the creation of cLow and cUp (don't create arrays in loops, always 'preallocate' memory), the calculation of the tolerance levels can be done in one operation (under the assumption that broadcasting is possible at this point) and at last I removed the conditional case for copying the imgNew to img (I also doubt that you do not want to copy the last iteration back into img. If so you have to remove the copy line before the loop and move the copy at the beginning of the loop to its end.).

diff_height_gL = height - gL
diff_width_gL = width - gL
sum_gSmp_one = gSmp + 1

cLow, cUp = np.empty((gL, gL, 3)), np.empty((gL, gL, 3))

imgNew = img.copy()

for itr in xrange(itrs):

    img[:] = imgNew

    for x in xrange(gL, diff_height_gL):
        for y in xrange(gL, diff_width_gL):

            cGrid = img[x-gSmp:(x + sum_gSmp_one), y-gSmp:(y + sum_gSmp_one)]

            cLow[:] = img[x, y, :] - tol
            cUp[:] = img[x, y, :] + tol

            cBool = np.any(((cLow < cGrid) & (cUp > cGrid)), axis=2)

            imgNew[x, y] =  np.sum(cGrid[cBool], axis=0) / cBool.sum()

This problems seems to be perfectly shaped to do multiprocessing. This could be an alternative/extension to vectorization. If I have time I will try the vectorization...

Kind regeards


Checking if a number is palindrome or not in Java

Some tips:

Main is a confusing class name. In your case, an appropriate name might possibly be PalindromeChecker.
Your main method would usually be in a separate class called for example Application. That way

PalindromeChecker ends up with a public method for doing the actual check, making the class reusable and
the library and executable parts of your program are properly separated.

Why scan for numbers? You are reading from standard input, which by definition is just a byte stream, so you might as well avoid some conversion and just check whether each line that arrives is a palindrome. Number checking could be done elsewhere, if absolutely necessary.
The checker function should return a boolean, to avoid mixing logic and presentation. The function also becomes objectively simpler: return reverseStr.equals(numberStr);
Look into other ways of converting a string to an integer - they have different pros and cons.
Writing up some test methods could expose unexpected behaviour. For example, what does your code do with alternative numbering systems such as Roman or Chinese numerals? Does it handle 10.1 as one integer (101 or 10), two integers (10 and 1), or does it reject it? Does it expand numbers such as 1e5? Does it precompute arithmetic such as 10+1? Converting the int back to a String and comparing it with the original String input might be a useful way of telling whether any automagic conversion has occurred.
I believe tell, don't ask applies to the way in is used.

That said, your solution is simple and quick. Given the time & stress of an interview I'd say you nailed it. (Provided it works - I haven't actually run it :)


To pass a function or subroutine to another, you need to declare it with an interface block. The compiler also needs to be aware of the function/subroutine you are calling, which means either using a module to hold the RK4 subroutines or, with small enough code, a contains block.

I'm going to go with the latter since it's easier here due to code size, but the strategy really isn't that different with using a module. I'm also going to snip out most of the code, as I don't think much is needed to show how to do it.

program test_linsht
   implicit none
   ...
   call rk4(n, h, x, nstep, xprsysU, U)
   call rk4(n, h, x, nstep, xprsysV, V)
   ...
contains

subroutine xprsysU(n,x,f)
! x prime of system of equations
   real(8), dimension(0:n) :: x,f
   integer :: n
   ! time is introduced as a new differential equation
   f(0) = 1.d0
   f(1) = x(2)
   f(2) = 2.*x(0)/(1+x(0)*x(0))*x(2)- 2./(1.+x(0)*x(0))*x(1) + 1.0
end subroutine

subroutine rk4(n, h, x, nstep, sub, xout)
   real(8) :: x(0:n)
   real(8) :: y(0:n), f(0:n,4)
   interface
      subroutine sub(n, x, f)
         real(8), dimension(0:n) :: x,f
         integer :: n
      end subroutine sub
   end interface
   ...
   do k=1,nstep
      call sub(n, x, f)
   end do
   ...
end subroutine
end program test_linsht

Note that the interface block has the same structure as the declaration part of the subroutine, so it should be obvious that it is necessary for the inputs of the different functions to be the same, otherwise we'd have a compiler error.

Other odds and ends:

Fortran is 1-indexed, so it's more natural in the language to use dimension(1:n) (or even dimension(n), which is the same thing as the other), instead of defining it as dimension(0:n). Obviously it can handle an index of 0, but it's just not typical of Fortran programs.
I don't think the labels in# and out on the do loops are needed in this case. Typically, I'd only recommend them for the cases where an inner loop requires you to increment the outer loop, but that doesn't happen here, it's just clutter.
It's possibly due to copy-and-paste, but indentation matters for reading purposes. You've got some parts indented and others not, some indented further than others.
Fortran allows array math, use it. You can turn those do loops in the RK4 routine into y(:) = x(:) + h*f(:,1) etc.
It is not generally recommended to use real(8) syntax, it's possibly not what you think it is. The Fortran 90 standard introduced kind notation to give you portable definition of arbitrary precision numbers.
With a contains statement, the parameters are global, so you would not need to pass them to the subroutines. With a module, you would have to declare those parameters in the module as global variables.
I'd recommend declaring variables as intent(in) and intent(out) whenever and wherever possible, as it helps keep you straight with regards to variables usage (and possibly help optimize the code).


You could cut down on the repetitive elements with a local function binding.

echar =
  let
    yield :: Char -> Char -> Parsec String () Char
    yield c d = char c >> return d
  in
    (char '\\' >>
       (  yield 'b' '\b'
      <|> yield 'f' '\f'
       -- ...

Then perhaps cut out the repeated applications with a fold.

import Data.Foldable

-- ...
  in
    (char '\\' >>
       (  (asum . map (uncurry yield) $ [('b', '\b'), ('f', '\f') -- ...
      <|> (char 'u' -- ...

I'm not sure you need the Numeric import either, I would write that line as—

char 'u' >> count 4 hexDigit >>= return . chr . read . ("0x" ++)

And then to tie it all together with a bow.

import Control.Applicative        ((<|>))
import Data.Char                  (chr)
import Data.Foldable              (asum)
import Text.Parsec         hiding ((<|>))

echar :: Parsec String () Char
echar =
  let
    escapeCharacters = [('b', '\b'), ('f', '\f'), ('r', '\r'), ('t', '\t'), ('v', '\v')]

    yield :: Char -> Char -> Parsec String () Char
    yield c d = char c >> return d
  in
    (char '\\' >>
       (  (asum . map (uncurry yield) $ escapeCharacters)
      <|> (char 'u' >> count 4 hexDigit >>= return . chr . read . ("0x" ++))
      <|> (noneOf "u")
       )
    ) <|> noneOf "\\"


Collision detection

You can calculate the collision much easier with the Rectangle structure.

Use the Contains method if you are interested in single points that

  Determines if the specified point is contained within this Rectangle structure.

var pictureRect = new Rectangle(
    pictureBox.Location.X,
    pictureBox.Location.Y,
    pictureBox.Width,
    pictureBox.Height
);
var isCollision = pictureRect.Contains(player.Location.X, player.Location.Y);

If you want to know whether the rectangles have a collision then use the  IntersectsWith method that

  Determines if this rectangle intersects with rect.

var isCollision = pictureRect.IntersectsWith(player.Rectangle());

Create and an extension to easier get the rectangle from a PictureBox.

public static Rectangle Rectangle(this PictureBox pictureBox)
{
    return new Rectangle(
        pictureBox.Location.X,
        pictureBox.Location.Y,
        pictureBox.Width,
        pictureBox.Height
    );
}

Naming

foreach(PictureBox s in rocks)

You should use more meaningful names than just s. A variable like pictureBox or pb would be much better because it's derived from the collection. The s does not have any meaning. Although in this case a rock would be perfect.

Health & Damage

health -= 10;

This operation is not clear at first and maybe you have other places where you need to decrease health. Consider using constants and a helper method for this.

private static class Damage
{
    public const int WhenHitRock = 10;
}

void DecreaseHealth(int value)
{
     health -= value;
}

Everything together

The result of applying all suggestions and proper names would be a self-documenting code that no longer has to be commented.

When you write comments you only should explain why you are doing something because the code already shows what.

foreach (var rock in rocks)
{
    var isPlayerRockCollision = rock.Rectangle().IntesectsWith(player.Rectangle());
    if (isPlayerRockCollision)
    {
        DecreaseHealthBy(Damage.WhenHitRock);
        damagable = false;
        impactHit.Play();
        return;
    }
}

Notice that there is a return inside the if. You set the demagable to false so I think it's not necessary to test other rocks for a hit. You can stop at the first one.


SQL to list function - turning a table column into a delimited list string

In the context of the function

Function sql2List(sSql As String, Optional quote As String, Optional separ As String = ", ") As String
Static db As DAO.Database
Dim rs As DAO.Recordset
Dim result As String
'Debug.Print Now, sSql
If db Is Nothing Then Set db = CurrentDb
Set rs = db.OpenRecordset(sSql, dbOpenSnapshot)
Do Until rs.EOF
    result = result & quote & rs.Fields(0).Value & quote & separ
    rs.MoveNext
Loop
rs.Close
Set rs = Nothing
'Set db = Nothing
If Len(result) > Len(separ) Then sql2List = Left(result, Len(result) - Len(separ))
End Function

The static declaration of db is probably not a good idea.

This (my reformatting is just my preference) is probably better

Set db = CurrentDb
strList = sql2List(db, "select dt from planning where client = " & clientId)
Set db = Nothing

Function sql2List(db as DAO.Database,sSql As String, Optional quote As String, Optional separ As String = ", ") As String
Dim rs As DAO.Recordset
Dim result As String
Dim RetValue as string
  RetValue = ""
  'Debug.Print Now, sSql
  If not(db Is Nothing) = True Then
     Set rs = db.OpenRecordset(sSql, dbOpenSnapshot)
     Do Until rs.EOF
         result = result & quote & rs.Fields(0).Value & quote & separ
         rs.MoveNext
     Loop
     rs.Close
     Set rs = Nothing
     If Len(result) > Len(separ) Then
        RetValue = Left(result, Len(result) - Len(separ))
     endif
  ELSE
     RetValue =""
  endif
  sql2List= Trim(RetValue) ' I tend to want to remove leading and training spaces
End Function

There was nothing (much) wrong with what you did other that the static inside the function as that made the function less utilitarian because there was no way that function could ever be used for any connection other than the first one. It just so happens to work because you do not desire a different connection.


There's two things I usually consider in this kind of situation:

Use custom helpers and partials

The idea here is to break down your view in small components, and have one helper to build each component. Most of the time those helpers will just dispatch and render an appropriate partial :

def wysiwyg_title(text_object)
  if text_object.persisted?
    render 'components/wysiwyg/title/persisted', text: text_object
  else
    render 'components/wysiwyg/title/new_record', text: text_object
  end
end

sometimes you can also DRY it up a little by using 'peacemeal' helpers that only affect parts of a tag :

def wysiwyg_container_classes(text_object)
  classes = ['wysiwyg_container']
  classes << 'wysiwyg_container--draft' unless text_object.persisted?
  classes
end

(use it like that:)

= content_tag :div, class: wysiwyg_container_classes(@text)

and so on. You get the spirit.

Use presenters

Another option is to use the presenter pattern. The Draper gem, for instance, makes it easy.

The idea here is that instead of passing your model directly to the view, you decorate it with the appropriate presenter. You'll have for instance one presenter for the editable view, and one for the static view. Each presenter will have methods like title, container, etc. that know how to render a component of your view, format the values, etc. your actual view will simply be a layout that arranges the components.

As presenters are objects, you are free to use inheritance / composition / delegation to share some logic, which often helps DRYing the code while keeping it clear and readable.


Filtering or repeating elements as needed

I think if you look at the objects within the IEnumerable as a statistical numeric value than you could use the term Normalize. In this case you are "normalizing" your values (objects) to a desired count.

public static IEnumerable<T> NormalizeObjects<T>(this T[] items, int desiredCount)

If you dislike the term Objects you could replace it with Items or even Records depending on what your use case is.

If the only thing you dislike about your current name is "Trim" then you could replace that term with the opposite of Expand, which I would argue is Contract.

public static IEnumerable<T> ExpandOrContract<T>(this T[] items, int desiredCount)

I think either of the above are decent options based on what your method is currently doing.


Platform for creating data-oriented web apps

That coding style looks more like the WebMatrix Web Pages pattern rather than ASP.Net MVC. If this coding style is desired then it would be preferable to go ahead and use the data access library that is usually used with Web Pages, the WebMatrix.Data library. That will by default guard against SQL Injection as long as the convention of the parameterized queries is used, e.g.

    selectCommand = "SELECT URL, Name FROM Pages WHERE ID = @0 AND Date = @1";
    selectedData = db.Query(selectCommand, Request.QueryString["Id"], Request.QueryString["Date"]);

This should be OK for simple sites, but for larger or more complex sites you would be better to separate the data access from the presentation layer, using the full MVC pattern.  The downside of the pattern shown here is that is difficult to test or debug compared to MVC or WebForms and it tends to introduce duplication in the code.


Well, first of all you aren't trying a promise. What you're really doing is trying out a function that returns a promise. So the name is already misleading. Try something better.

Next, f and v doesn't really tell me anything. Only when I read through the code did I realize f was the function to try out and v is supposed to be a value. Additionally, even if you name v a value, it's still not correct. Most reject handlers often pass an error object.

Code that requires one to actually read to understand is a bad practice. In this case it's negligible due to the size of the function. But if you're in larger codebases, it's a nightmare to maintain. Name your functions and variables meaningfully.

Lastly, your function doesn't allow for function arguments. It would be nice to at least accept argument 3 onwards as the arguments, or accept an array that would be the arguments.

My take on it would be:

function tryPromiseFunction(functionToTry, retries, ...args){
  return functionToTry(...args).then(null, error => {
    return retries > 0 ? tryPromiseFunction(functionToTry, retries - 1, ...args)
                       : Promise.reject(error);
  });
}


This code does not seem right:

var optHTML = opts.reduce(function(html, opt) { return html+opt; });
this.each(function() { $(this).html(optHTML); });

Here your .reduce() function is aggregating ALL the HTML for ALL of the options, which I think is an appropriate use of reduce function.  But I do not understand why there is call to each() here as this can only refer to a single element.  In fact I am guessing this doesn't even have an each() method on it , since this is an Element object.  Shouldn't this just be:

var optHTML = opts.reduce(function(html, opt) { return html+opt; }, '');
$(this).html(optHTML);

I am not seeing great utility in separate map and reduce steps. This causes you to iterate your input options an extra time that could be considered removed if you wanted to simply consolidate all this logic into the reduce step.  If the use cases are for small lists, maybe this performance isn't important and the added "clarity" of having two separate steps is acceptable.

Does it truly makes sense to support this extension on an arbitrary jQuery collection?  Right now, as this code is written, if I had HTML like this:

<select class="foo-options">
</select>
<select class="foo-options">
</select>

And I called your extension on $('.foo-options'), you would end up with duplicated options for these two different selects. Is this desirable behavior?

Rather than writing HTML strings and having to hold the aggregated string in memory, you should give some consideration to actually creating the DOM Nodes and appending them.

Along with suggestion on removing redundant iterations over options, might have you function looking like this:

$.fn.injectOptions = function(opts) {
  // not shown - perhaps validate opts is array with at least 1 element
  // and fail out if this is not the case

  // simply iterate the passed options appending each element as you go
  opts.forEach( opt => {
      var val, txt;
      if (typeof opt === 'string') {
          val = opt;
          txt = opt;
      } else {
          val = opt.key;
          txt = opt.val;
      }
      $(this).append( $.('<option>', { value: val, text: txt }) );
}


Doubly linked list using C++ and templates

Includes
<iostream> isn't needed by the header, so don't include it there.
Null pointer
When I try to run the code, I get an attempt to dereference a null pointer at the first remove(0), which crashes the program.  This is because remove() returns a reference to local variable value, which is no longer in scope.  Return it by value instead:
    T remove(int pos);
 //^^^ not T&

Memory leak
If I add return 0; before the crash (or fix the bug), I do see a memory leak:
==29576== 168 (24 direct, 144 indirect) bytes in 1 blocks are definitely lost in loss record 7 of 7
==29576==    at 0x4835E2F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==29576==    by 0x109362: LList<double>::LList() (205728.cpp:27)
==29576==    by 0x10917F: main (205728.cpp:92)

I think ~LList() needs to do more cleanup:
template<typename T>
LList<T>::~LList()
{
    for (auto p = head->next;  p != tail;  ) {
        auto next = p->next;
        delete p;
        p = next;
    }
    delete head;
    delete tail;
}

Copy construction
205728.cpp:11:7: warning: ‘class LList<double>’ has pointer data members [-Weffc++]
205728.cpp:11:7: warning:   but does not override ‘LList<double>(const LList<double>&)’ [-Weffc++]
205728.cpp:11:7: warning:   or ‘operator=(const LList<double>&)’ [-Weffc++]

We need to fix this, and either make the list safely copyable, or totally uncopyable.
Prefer initialization to assignment
LList<T>::LList() : n_elements{0}
                   /^^^^^^^^^^^^^

Or just provide a default initializer, as with prev and next.
Don't pass primitive types by reference
T& get(const int& pos) const;
//             ^^^

Built-in types such as int are best passed by value rather than by const reference (and prefer size type to int for counting objects).  Also, in this case, we probably want to return a reference to const T from a const list, and a reference to mutable T from a mutable list (do as the standard containers do):
T const& get(std::size_t pos) const;
T& get(std::size_t pos);

Copying
Prefer to std::move() values where possible.  It's not hard to make the list able to accept move-only types:
template <typename T>
struct node
{
    T value;
    node* prev;
    node* next;
    node(T value, node *prev = nullptr, node *next = nullptr)
        : value{std::move(value)}, prev{prev}, next{next}
    {}
};

template<typename T>
void LList<T>::insert(T value, const int pos)
{
    node<T> *temp = new node<T>(std::move(value), prev, next);

Exception safety
Constructing a linked list requires memory to be allocated for head and tail.  If the first new succeeds, but the second fails, we end up leaking memory when the std::bad_alloc is thrown.
There's no reason not to make head and tail be plain sub-objects:
private:
    int n_elements = 0;
    node<T> head = { T{}, nullptr, &tail };
    node<T> tail = { T{}, &head, nullptr };

(adjust all head-> to head. and other head to &head; the same for tail).
Remove doesn't need to track prev and next
Once we've found the target for remove, we can easily access its neighbours:
template<typename T>
T LList<T>::remove(const int pos)
{
    node<T> *curr = head.next;
    for (int i = 0; i < pos; i++) {
        curr = curr->next;
    }
    curr->prev->next = curr->next;
    curr->next->prev = curr->prev;
    T value = std::move(curr->value);
    delete curr;
    --n_elements;
    return value;
}

The insert method can be simplified in a similar way.
The node type needn't be public
Since node isn't exposed in the public interface, it can be a private type within LList:
template <typename T>
class LList
{
    struct node
    {
        T value;
        node* prev;
        node* next;
        node(T value, node *prev = nullptr, node *next = nullptr)
            : value{std::move(value)}, prev{prev}, next{next}
        {}
    };

    // ...

    node head = { T{}, nullptr, &tail };
    node tail = { T{}, &head, nullptr };

};

Modified code
I've made some other minor changes to simplify further.
#include <cstddef>
#include <utility>

template <typename T>
class LList
{
    struct node
    {
        T value;
        node* prev;
        node* next;
        node(T value, node *prev = nullptr, node *next = nullptr)
            : value{std::move(value)}, prev{prev}, next{next}
        {}
        node(const node&) = delete;
        void operator=(const node&) = delete;

        friend void swap(node& a, node& b) {
            using std::swap;
            swap(a.value, b.value);
            swap(a.prev, b.prev);
            swap(a.next, b.next);
        }
    };

public:
    LList() = default;
    LList(const LList<T>&);
    LList(const LList<T>&&);
    LList& operator=(LList<T>);
    ~LList();

    T const& get(std::size_t pos) const;
    T& get(std::size_t pos);

    void insert(T value, std::size_t pos);
    T remove(std::size_t pos);

    template<typename U>
    friend void swap(LList<U>&, LList<U>&);

private:
    std::size_t n_elements = 0;
    node head = { T{}, nullptr, &tail };
    node tail = { T{}, &head, nullptr };
};

template<typename T>
LList<T>::LList(const LList<T>& other)
{
    // work from back to front, so we always insert at position 0
    // (which is the cheapest)
    for (auto i = other.n_elements;  i > 0;  --i) {
        insert(other.get(i-1), 0);
    }
}

template<typename T>
LList<T>::LList(const LList<T>&& other)
{
    swap(*this, other);
}

template<typename T>
LList<T>& LList<T>::operator=(LList<T> other)
{
    swap(*this, other);
    return *this;
}

template<typename T>
LList<T>::~LList()
{
    for (auto p = head.next;  p != &tail;  ) {
        auto next = p->next;
        delete p;
        p = next;
    }
}

template<typename T>
void swap(LList<T>& a, LList<T>& b)
{
    using std::swap;
    swap(a.head, b.head);
    swap(a.tail, b.tail);
    swap(a.n_elements, b.n_elements);
}

template<typename T>
const T& LList<T>::get(std::size_t pos) const
{
    auto p = head.next;
    while (pos--)
        p = p->next;
    return p->value;
}

template<typename T>
T& LList<T>::get(std::size_t pos)
{
    auto p = head.next;
    while (pos--)
        p = p->next;
    return p->value;
}

template<typename T>
void LList<T>::insert(T value, std::size_t pos)
{
    auto p = &head;
    while (pos--)
        p = p->next;
    auto next = p->next;
    next->prev = p->next = new node(std::move(value), p, next);
    ++n_elements;
}

template<typename T>
T LList<T>::remove(std::size_t pos)
{
    auto p = head.next;
    while (pos--)
        p = p->next;
    p->prev->next = p->next;
    p->next->prev = p->prev;
    auto value = std::move(p->value);
    delete p;
    --n_elements;
    return value;
}

From this position, you could consider more advanced topics, such as providing iterators.  Actually, providing full iterator support is quite a lot of work - 12 methods and a pair of classes - but there are some good reviews here that may give you a metaphorical "leg-up".
Or you might consider your own choice of next steps - don't let me constrain you!


Declare variables as late as possible. int i, k, j, n, l, tabl; What do these variables do? It is quite difficult to figure that out. If you declare and initialize them when needed it would be clear.
Keep variables as local as possible. A loop such as for(i = 0; i < str.length(); i++) makes me think the result of i is required later which it is not (I think). Prefer for (int i = 0; i < str.length(); i++).
People do not like using namespace std;.
tab[10000] and char c = 179; have magic numbers. Why 10000 and 179? Since you know how to use vector it is hard to guess why you thought having 10000 stings twice is a good idea.
This seems to be a major performance problem (you are supposed to profile because obvious performance problems can get fixed by the optimizer and the line between what the optimizer thinks is obvious and which is not is very hard to predict):

while(getline(in, str2)){
    str += str2;
    str += ' ';
}

This produces a string to hold a single line. Then it adds a line, but it is out of memory, so it allocates new memory for 2 lines, copies 2 lines and throws the memory for 1 string away. Then it allocates memory for 3 lines, copies 3 lines and throws 2 lines of memory away. When you start allocating memory for 100 lines, copy 100 lines and throw 99 lines worth of memory away things get slow. I would suggest counting words one line at a time instead of reading the whole file at once.
Use functions. Some people do not allow more than 10 lines per function, otherwise it must be re-factored into multiple functions. 10 lines are a bit strict, but you should separate concerns. One function to get the input, one function to do the word counting, one function to do the output. Maybe some functions will be too complicated and need to be split up further. The point is that if you need to change a part of the program you see from the function names where to change what.
I looked at your loops and indexes and I don't even want to try to understand what is going on. You can replace almost all of that with a map<string, int>.

This is what I came up with (it is 4:35 am here). My code kind of deserves a review of its own because it makes me look a bit hypocritical.

    #include <iostream>
    #include <string>
    #include <map>
    #include <algorithm>
    #include <cctype>
    #include <vector>
    #include <sstream>
    #include <fstream>
    #include <iomanip>

    void removeNonAlphabeticalCharacters(std::string &s){
        s.erase(std::remove_if(std::begin(s), std::end(s), [](char c){ return !isalpha(c); }), std::end(s));
    }

    template<class Iterator>
    //constraint: Iterator::value_type == std::pair<std::string, int>
    void displayRanking(Iterator begin, Iterator end, int wordcount){
        int index = 1;
        while (begin != end){
            std::cout << '|' << index << ".\t|" <<
                begin->first << "\t|" << begin->second << "\t|" <<
                std::fixed << std::setprecision(2) << begin->second * 100.f / wordcount << "%\n";
            ++begin;
            index++;
        }
    }

    int main(){
        std::map<std::string, int> wordcounter;
        std::string input;
        int totalwords = 0;
        std::ifstream in("file.txt");
        while (in >> input){
            removeNonAlphabeticalCharacters(input);
            wordcounter[input]++;
            totalwords++;
        }
        if (totalwords == 0){
            std::cout << "failed reading words from file\n";
            return 0;
        }

        //how many words to display in the ranking
        const int top = std::min((size_t)20, wordcounter.size());
        //copy wordcounter to vector for sorting
        std::vector<std::pair<std::string, int>> toplist;
        toplist.reserve(wordcounter.size());
        std::copy(std::begin(wordcounter), std::end(wordcounter), std::back_inserter(toplist));
        auto comparator = [](const std::pair<std::string, int> &lhs, const std::pair<std::string, int> &rhs){return lhs.second > rhs.second; };
        std::partial_sort(std::begin(toplist), std::begin(toplist) + top, std::end(toplist), comparator);

        displayRanking(std::begin(toplist), std::begin(toplist) + top, totalwords);
    }

There are many ways to improve readability and performance still, but let me know how long my code takes with your input file.


Follow the naming convention of the language
For scala, this is here. Spell methods and variables in lower camel case:
drop_Val_In_List
drop_Val_List_In_List
in_ls

Use the most appropriate data structure
To me, it seems like you want a set, not a sequence/list. Set also has the method you want:
val KeepCols = Set("id", "type", "month", "car", "road")
val tmp = KeepCols.diff(Set("id", "type", "month"))

If you don't want to use a set, Seq also has diff.


Print the number of subarrays of an array having negative sums

Consistency

                for(j=0;j<i;j++){
                    sum += arr[j+k-1];
                }
                if(sum<0)
                    count++;

It's more common to write the latter control structure

                if (sum < 0) count++;

That is the clearest way to write the single statement version.

But if you're doing that, why not say

                for (int j = 0; j < i; j++) sum += arr[j+k-1];

How do you choose when to use or not use the single statement form?

I find it easiest to never use it.  So I'd say

                if (sum < 0) {
                    count++;
                }

Then I don't have to consider whether I should use it this time or not.

There are also advantages if someone has to edit it in the future.  In particular, it's harder to make editing mistakes.

Keep it simple

        for(int i=1,k,j;i<=N;i++){
            for(k=1;k<=N-i+1;k++){
                for(j=0;j<i;j++){
                    sum += arr[j+k-1];

Consider

        for (int i = 0; i < arr.length; i++) {
            for (int k = 1; k <= arr.length - i; k++) {
                for (int j = 0; j <= i; j++) {
                    sum += arr[j+k-1];

In the second for, you had N-i+1, which is the same as N-(i-1).  But you can change the bounds of i from 1 to N to 0 to N-1.  Then you don't need the extra 1.  But then you need to change the third for loop to j <= i.

I would rather use arr.length than N, as that's the actual limiting factor.

I added some whitespace for readability.

        for (int i = 0; i < arr.length; i++) {
            for (int k = 0; k < arr.length - i; k++) {
                for (int j = 0; j <= i; j++) {
                    sum += arr[j+k];

In the summation step, you have j+k-1.  But if we change the bounds of k from 1 to N-i to 0 to N-i-1, we can just do j+k.

I find this version easier to follow when I read it.

        for (int i = 0; i < arr.length; i++) {
            for (int k = 0; k < arr.length - i; k++) {
                long sum = 0;
                for (int j = 0; j <= i; j++) {
                    sum += arr[j+k];

You declare sum outside all the for loops.  That's not necessary.  You could define it just before the third.  Then you don't have to reset it at the end of that loop.  It will be automatically set whenever you need it.

Using long instead of int avoids the possibility of overflow.

Alternatives

If you have plenty of space or are willing to modify the input array, you can do this with only two levels of loop nesting.  You can calculate the sums prior to checking them.

        long[][] sums = new long[arr.length][arr.length];
        for (int i = 0; i < arr.length; i++) {
            sums[i][i] = arr[i];
        }

        for (int start = 0; start < arr.length; start++) {
            for (int end = start + 1; end < arr.length; end++) {
                sums[start][end] = sums[start][end - 1] + arr[end];
            }
        }

        int count = 0;
        for (int start = 0; start < arr.length; start++) {
            for (int end = start; end < arr.length; end++) {
                if (sums[start][end] < 0) {
                    count++;
                }
            }
        }

But we can actually do better.

        long[] sums = new long[arr.length];
        sums[0] = arr[0];
        for (int i = 1; i < arr.length; i++) {
           sums[i] = sums[i - 1] + arr[i];
        }

        int count = 0;

        // count the arrays starting with the first element
        for (int end = 0; end < arr.length; end++) {
            if (sums[end] < 0) {
                count++;
            }
        }

        // count the arrays starting with start+1
        for (int start = 0; start < arr.length; start++) {
            for (int end = start + 1; end < arr.length; end++) {
                if (sums[end] - sums[start] < 0) {
                    count++;
                }
            }
        }

Less space but the same runtime growth.

Both solutions make use of the fact that a sum of N elements is equal to a sum of N-1 elements plus the Nth element.  So we don't have to keep recalculating that, which is the slow part of the original code.


Git script that fast forward merges and deletes the old branch

The order of the arguments is backwards, I think. Compare against git-rebase(1):

  Synopsis

  git rebase [<upstream>] [<branch>]

  Description

  If <branch> is specified, git rebase will perform an automatic git checkout <branch> before doing anything else. Otherwise it remains on the current branch.

The git-rebase order is also better since the git checkout can be considered optional.  You should probably make yours optional as well.

The help message needs to be much more informative about what the command does and how to use it. Git is hard enough to use as it is.

Accidental branch deletion is unlikely to be tragic, since you used -d and not -D.


Your CSV parse is somewhat simplistic, it assumes the comma's are "simple" (no quoted commas, etc. This is not a bad thing, just an observation, but it leads on to the next thing... the cumbersome splitting and rejoining of the field values using awk, etc. I have a confession to make here, I dislike using awk. To clarify, there are often simple ways to do things, and then there are times the simple routes are not enough. You don't need awk for the simple stuff, and you need perl, or python for the complciated stuff. I like the concept of awk, I just don't like having to know three tools when two is enough.

So, I immediately look at your code and think "simplify" it.

If you are using a simple CSV parse, you may as well do it all at once, and use a simple regex and expand your sed use....

I assume you are running on a reasonably recent linux version.

the basename program has the suffix argument: basename -s .csv file/to/test.csv will return test (the base name of the file with the suffix .csv removed).
you are tagged as bash so I will recommend here-strings instead of the echo commands you use. Instead of $(echo $1 | cut -d'.' -f 1) do $(cut -d'.' -f 1 <<< "$1"). It saves an echo.
you should have a shebang line #!/bin/bash as the first line.

So, to strip out all the awk, and more, I would have:

function parseCsvAdv2Db {
    local table=$(basename -s .csv $1)
    local ins="INSERT INTO $table$2 VALUES"
    local data=""

    while read line
    do
        # expand variable names inside the line.
        line=$(eval echo $line)

        # add parenthesis and quotes to the data.
        # Internal quotes still missing.
        data+="('$line')"
    done < $1

    # Add internal quotes, and add comma between value sets.
    data=$(sed -e "s/,/','/g" -e 's/)(/),(/g' <<< "$data")

    ins+="$data;"

    sqlite3 $dbfile "$ins"
    #echo $ins

}

By sacrificing the per-field parsing from awk you instead gain the simplicity of bulk modifications of the comma values using sed, to expand them to quote their respective values. Combined with adding the surrounding ('...') structure for each line, it just works....


Haskell - saving content of HTTP request in selected file

Right from the top I notice you could benefit from some factoring.
prompt :: String -> IO String
prompt str = do
    putStr str
    hFlush stdout
    getLine

Then getURL is prompt "URL: " (and maybe doesn't even need to exist separately!) and confirmOverideOrGetNewPath and getOutputFilepath both lose two lines at the top. You'll notice that I also wrote this function with do-notation, it's a stylistic preference but I just don't like to run monads into one line like that, not sure if I have a great reason why. I guess it just feels right to make imperative-y monadic code look like an imperative language would.
The diversion through shouldOverride in confirmOverideOrGetNewPath is unnecessary, just put your expression in the case-statement.
case decision == "y" of
  True -> ...

But then I'd also skip the check for equality entirely and just pattern match on the returned string.
case decision of
    "y" -> return filepath
    "n" -> getOutputFilepath
    _   -> do
      putStrLn "Unrecognized input"
      confirmOverrideOrGetNewPath filepath

I changed the logic to make the behavior more elucidating. If a user actually enters "n", it's not really necessary to tell them to provide a new path since getOutputFilepath will prompt them for a new one immediately. The user presumably expects that, given their input. If they type something other than "y" or "n", instead of requiring them to input a new path, just check again if they're cool with the override.
In getOutputFilepath all I'd note is that file_exists should be camel cased for consistency.
Over the rest of your program, the only thing I'd switch up would be the whole logic around response codes. In performGetRequest I'd just change the return type to be ResponseCode instead of Int, and push your display logic into printHttpStatusCode (which should probably be printResponseCode). Since ResponseCode is just a type alias for tuples, you can also pattern match in the function call (i.e. in your original version responseCodeToInt (x, y, z) = ... instead of the let). And then it also probably makes more sense to have a pure showResponseCode and leave printing up to the caller.
showResponseCode :: ResponseCode -> String
showResponseCode (i, j, k) = concatMap show [i, j, k]

Then I'd just carry the changes through to main and reorder things for clarity and truth in logic.
main = do
    ...
    (content, statusCode) <- performGetRequest url
    putStrLn $ "Response status: " ++ showResponseCode statusCode
    writeFile filepath content
    putStrLn "Content saved"


Storing and processing large arrays to compute dot products

This is a fairly straightforward implementation that seems to get the job done at least for the simple input you posted. Overall, it's easy to read and understand, given the problem description. Here are some ways I think it could be improved.

Naming

You've named all the variables similarly to how they are named in the problem statement. That's fine for an assignment or exercise, but it would be a real pain to maintain later on. You have a comment describing the names, but it assumes the person reading it has the problem statement. That's rarely the case in the real world.

The variable names n, i, and j aren't terrible. I'd leave i and j, but rename n to something descriptive like numElements (or, if you prefer num_elements).

The names q, l, ch, r, and c are terrible and confusing. I'd make q something like numLines or numInputLines or something like that. l and r are the start and end of the range of indexes you want to modify, so I'd name them start and end.

c and ch are likely to be confused. Also, ch seems like it's a remnant from an earlier version when it was declared as a char type instead of a long. It's used to get the user's input, so you could name it userInput or mode or something more appropriate. c is the value you're adding to all the inputs. Since this is an exercise, it's just an abstract value that doesn't have any real meaning. Normally, I'd suggest calling it whatever it is, but that's hard in this case. Something generic like value or operand could work.

Functions

Your code does a few different things:

Gets the size of the arrays and number of lines of input
Creates and initializes the arrays
Processes the inputs

You should separate those into functions like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int getNumberOfElementsAndLines (size_t* outElements, size_t* outLines)
{
    long numScanned = scanf("%zu %zu", outElements, outLines);
    int result = (numScanned == 2);
    if ((*outElements < 1) || (*outElements > 1000000000) || (*outLines < 1) || (*outLines > 200000))
    {
        result = 0;
    }

    return result;
}

int allocateAndInitArrays (const size_t numElements, long** outA, long** outB)
{
    // Make sure the inputs are valid
    if ((outA == NULL) || (outB == NULL) || (numElements == 0))
    {
        return 0;
    }

    // Allocate and clear A and if successful, allocate and clear B
    *outA = calloc (numElements, sizeof(**outA));
    *outB = calloc(numElements, sizeof(**outB));

    if (*outB == NULL)
    {
        free(*outA);
        *outA = NULL;
    }

    return ((*outA != NULL) && (*outB != NULL));
}

int getAndProcessInput (long* a, long* b, const size_t numElements, const size_t numLines)
{
    for (size_t i = 0; i < numLines; i++)
    {
        long mode   = 0;
        int numScanned = scanf("%ld ", &mode);
        if (numScanned != 1)
        {
            return 0;
        }

        long l, r, c;
        switch (mode)
        {
            case 1:
                scanf("%ld %ld %ld",&l,&r,&c);
                l--;
                for(long j = l; j < r; j++)
                    a[ j ] += c;    //Adds c to every element of a
                break;

            case 2:
                scanf("%ld %ld %ld",&l,&r,&c);
                l--;
                for(long j = l; j < r; j++)
                    b[ j ] += c;    //Adds c to every element of b
                break;

            case 3:
                scanf("%ld %ld",&l,&r);
                l--;
                c=0;
                for(long j = l; j < r; j++)
                    c += a[ j ] * b[ j ];   //Adds the product
                printf("%ld\n",c%1000000007);   //Prints the value after using mod
                break;

            default:
                // Error in input
                return 0;
                break;
        }
    }

    return 1;
}

Then your main would look something like this:

int main()
{
    int     result  = 0;
    size_t  numElements = 0;
    size_t  numLines = 0;
    result = getNumberOfElementsAndLines(&numElements, &numLines);

    long*   a = NULL;
    long*   b = NULL;
    if (result == 1)
    {
        result = allocateAndInitArrays(numElements, &a, &b);
    }

    if (result == 1)
    {
        result = getAndProcessInput(a, b, numElements, numLines);
    }

    free(a);
    free(b);

    return result;
}

Memory

You'll notice above that I used calloc() to allocate the memory on the heap instead of the stack. Stack space is limited, and there's a lot more memory available on the heap. That may fix your issue getting a segfault.

Error Handling

I added a little bit of error handling. It needs more. You should check to make sure you got valid results from functions like scanf(), for example. What if the user entered a negative number? What if they entered 0? Etc.


Another approach, the first one to come to my mind actually, would be using a std::type_index as key in your unordered_map. That's exactly what type_index was designed for, and it is more specific about its purpose than a raw size_t integer.
BTW, size_t is a member of namespace std in C++, so if you are going to use it, make sure to properly qualify the type as std::size_t. The C++ standard does not require it to also be available in the global namespace. You should also include <cstddef> somewhere (the header that defines std::size_t). At the moment you rely on some other standard header that imports this dependency.
I really don't like this:

void (*f)(Shader*, T& )

reinterpret_cast< void(*)(Shader* shd, T& t) >(rp)( shd, obj );

First issue here is the duplicate typing of this function's signature. If you introduce a typo in any of the declarations, that could very well crash de program, because it would be using a different signature from the actual function. This can be improved with a local typedef. Second is the type cast from RenderFunctionPointer to the actual pointer type. It looks dangerous. Third, std::function would be a much better and type-safe option.

According to feedback from a comment, this approach was taken to account for different functions for different types of objects. The template type T can be anything, however the map has to store a known type.

Since you are already paying for the price of an indirect function call, then perhaps a cleaner approach would be to use polymorphism. Make the object type inherit from a Renderable interface that has a onRender(Shader & shd) virtual method. That would also remove the need to store function pointers into the renderer, cleaning up the interface as well. Instead of telling the renderer how to draw an object, let the object know how to draw itself.
You don't need these typedefs:

typedef std::unordered_map< size_t, Shader* >::iterator ShaderIterator;
typedef std::unordered_map< size_t, RenderFunctionPointer >::iterator FunctionIterator;

If your sole objective is to reduce typing in places like this:

ShaderIterator i = Shaders.find( type );

That is what auto is for (C++11).
I see that you have a macro wrapping your log system (LOG_WARNING()). However, even if you mute your log by changing an internal verbosity parameter, the log calls would still be evaluated. I'm assuming this will be used for software like video games, where you probably don't need the overhead of logging on a released title. So I would suggest that you change you logging macros a little bit to avoid evaluating the log calls if you ever wish to mute the log system permanently (such as in a release build):

#define LOG_WARNING(msg) do { MyLog::getInstance() << msg << "\n"; } while (0)

That's one possibility. Then if you need to disable it, just make the macro a no-op:

#define LOG_WARNING(msg)

Now when using the log, a small change:

LOG_WARNING("Couldn't find shader for object: " << typeid( T ).name());

For the muted/disabled log, the logging calls would not be evaluated at all, incurring no runtime cost.
A final comment: The ownership of the Shader instances added to the renderer via AddObjectType() if quite unclear. Who is supposed to free those pointers? The renderer? The caller? No one? In such situations, the best solution is almost always to use a smart pointer. Perhaps a std::shared_ptr would be adequate in this case, if ownership is meant to be shared. Otherwise, a std::unique_ptr would be the best course of action.


Formatting
The formatting could be nicer and doesn't follow Java conventions.

The indention isn't correct (maybe a copy and paste error).
Opening braces belong on the same line as the method header/statement.
There are random superfluous spaces (after int curr and root.right == null) and missing spaces around the + operator in curr+root.data
There should be a space between keywords and opening brackets (if (...).
Braces should always be used around a conditional block, even if it only contains a single statement.
There shouldn't be more than a single blank line at a time and there shouldn't any at all inside leafsum in my opinion.

Names
The parameter names could be better:

root should be node.
There is no need to abbreviate curr. It should be current or maybe even currentSum.
The list should have a plural name: sums.

The method itself should also have a plural name such as leafSums.
Early return
In order to minimize indention depth return early out of leafsum instead of putting the complete method body inside the if block:
void leafsum(TreeNode root, int curr, List<Integer> sum) {
    if (root == null) {
      return;
    }
    // method body here.
}

DRY
You are repeating the sum curr + root.data three times.
Handling results
I'm not a big fan creating, carrying around and mutating a list for the results, however your way is probably the least convoluted way with Java's standard collection library. Personally I'd do something like:
static List<Integer> leafSums(TreeNode node, int currentSum) {
    if (node == null) {
        return Collections.emptyList();
    }

    int newSum = currentSum + node.data;

    List<Integer> leftSums = leafSums(node.left, newSum);
    List<Integer> rightSums = leafSums(node.right, newSum);

    List<Integer> sums = new ArrayList<>(leftSums);
    if (node.left == null && node.right == null) {
        sums.add(newSum);
    }
    sums.addAll(rightSums);

    return sums;
}

except I'd look for alternative to ArrayList that allows more efficient list concatenation with a nicer API.


It solves the problem, and that's good. Period.
But you're presenting your code here to get advice how to improve your programming skills, so here are a few remarks. Take them as a hint where to go from here, as soon as you feel ready for the "next level".
Separate user interaction from computation
Your main method contains both aspects in one piece of code, even within the same line (e.g. System.out.println(celsius * 1.8 + 32 + " \u2109 \n");). Make it a habit to separate tasks that can be named individually into methods of their own:

input a Celsius value (a method double readCelsius())
input a Fahrenheit value (a method double readFahrenheit())
convert from Celsius to Fahrenheit (a method double toFahrenheit(double celsius))
convert from Fahrenheit to Celsius (a method double toCelsius(double fahrenheit))
output a Fahrenheit value (a method void printFahrenheit(double fahrenheit))
output a Celsius value (a method void printCelsius(double celsius))

With separate methods, it will be easier to later change your program to e.g. use a window system, or do bulk conversions of many values at once, etc.
More flexible workflow
Your current program always forces the user to do exactly one C-to-F and then one F-to-C conversion. This will rarely both be needed at the same time. I'd either ask the user at the beginning for the conversion he wants, or make it two different programs. By the way, doing so will be easier if the different tasks have been separated.
Minor hints
Combine variable declaration and value assignment. You wrote double fahrenheit, celsius; and later e.g. celsius = input.nextDouble();, I'd combine that to read double celsius = input.nextDouble();. This way, when reading your program (maybe half a year later), you immediately see at the same place that celsius is a double number coming from some input.
I'd avoid the special characters like \u2109 and instead write two simple characters °F. Not all fonts on your computer will know how to show that \u2109 Fahrenheit symbol, so this might end up as some ugly-looking question mark inside a rectangle or similar. Using two separate characters does the job in a more robust way.


FutureTask in Android, wait for a thread to execute the next one

There is no need for the FutureTask, the executor service will create a future that you can use to wait on the task and get the result (if any).

executor.submit(futureWifiInfo).get();

This is basically the same as just calling futureWifiInfo.run(); (or call) In other words you aren't quite there yet with making this properly asynchronous.

It does let you set a timeout on the get simply by adding the timeout parameters:

Future<String> futureWifiInfo = executor.submit(wifiInfo);
try {
    futureWifiInfo.get(1, TimeUnit.SECONDS);
    executor.submit(scanResults);

} catch (TimeoutException e) {
    // get timed out -> cancel it
    futureWifiInfo.cancel(true);

} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}


I am looking for ... entirely different fixes that are better.

Turn the brightness down using your operating system, graphics card software, or monitor.


Reordering an array: Even elements descending, odd elements ascending

Putting everything in the main method is bad practice, and is hard to maintain. Separate it into methods. This also removes duplicate code, such as when you swap values.
// TODO Auto-generated method stub is generated in eclipse, and is only there to remind you to finish the method. It is not really to stay.
Don't use one-letter variable names, except for counters. a should be array.
Don't be lazy when you print something out. Still follow conventions.
The two if statements are doing identical things. Combine them with an OR.

Final code:

public class ArrayRearrange {

    public static void main(String[] args) {
        int[] array = { 2, 1, 4, 6, 5, 3, 7 };

        rearrange(array);

        for(int i = 0; i<array.length; i++) {
            System.out.print(a[i] + " ");
        }
    }

    private static void rearrange(int[] array) {
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if ((i % 2 == 0 && array[i] < array[j]) || (i % 2 != 0 && array[i] > array[j])) {
                    swap(array, i, j);
                }
            }
        }
    }

    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

}


I think there is probably more that could be offered as the code like something that could do with a makeover, but here's a couple of minor points for consideration.

To avoid any potential full enumeration of the items to retrieve the count of items in the list use either the .Count property or the option I prefer .Any(). e.g. Planning.ActiviteitAardItems.Where(aa => aa.IsChecked == true).Any()
I personally think lines like aa.Checked == true is unecessary noise.  You can achieve the same result by just going .Where(aa => aa.IsChecked).
If you are using the same IEnumerable multiple times consider first assigning it to a local variable and doing a ToList() on it.  This means that you will avoid any potential multiple enumerations of the dataset as ToList() will force it all back into memory.

For example

var ardCheckedItems = Planning.ActiviteitAardItems.Where(aa => aa.IsChecked).ToList();

You can now use this same variable in a couple of places in your code.
Does 1.0 and 0.1 mean anything?  You could perhaps convert them to constants to avoid any repetition.  See example below.
Here is an attempt to reduce the Arrow code effect we sometimes find ourselves writing and seems evident in this case.

public double Opacity
{
    get
    {
        const double returnOne = 1.0; // for lack of better names
        const double returnTwo = 0.1;

        var ardCheckedItems = Planning.ActiviteitAardItems.Where(aa => aa.IsChecked).ToList();

        if(!ardCheckedItems.Any()) return returnOne;

        tijdBlokkenItems = this.Tijdblokken.Where(t => t.Activiteit != null && t.Activiteit.ActiviteitAard != null).ToList();

        if(!tijdBlokkenItems.Any()) return returnTwo;

        Tijdblok tijdblok;
        var tijdblokken = new List<Tijdblok>();

        // See Edit below for an example of how to possibly re-write this
        foreach (var item in ardCheckedItems)
        {
            tijdblok = tijdBlokkenItems.Where(t => t.Activiteit.ActiviteitAard.Code == item.Code).FirstOrDefault();
            if (tijdblok != null)
                tijdblokken.Add(tijdblok);
        }

        tijdblok = tijdblokken.OrderByDescending(tb => tb.Activiteit.RoosterKleurPrioriteit).FirstOrDefault();

        var objectsNotNull = tijdblok != null && tijdblok.Activiteit != null && tijdblok.Activiteit.ActiviteitAard != null;
        var anyCheckedItems = ardCheckedItems.Any(x => x.Code == tijdblok.Activiteit.ActiviteitAard.Code);

        return objectsNotNull && anyCheckedItems ? returnOne : returnTwo;
    }
}

EDIT:  After Trevor pointed me in the right direction in order to improve the foreach statement I did a quick search on if it would be easy enough to do an extension method to return items that are not Null.  Stack overflow to the rescue https://stackoverflow.com/questions/14469159/linq-selectmany-and-where-extension-method-ignoring-nulls.  So altering that slighty I came up with and extension method like so:

public static IEnumerable<TResult> WhereNotNull<TSource, TResult>(
            this IEnumerable<TSource> source, Func<TSource, TResult> selector)
            where TResult : class
{
    return source.Select(selector).Where(sequence => sequence != null);
}

which means I believe we can re-write the foreach like so:

var tijdblokken = ardCheckedItems.WhereNotNull(ard => tijdBlokkenItems.FirstOrDefault(t.Activiteit.ActiviteitAard.Code == ard.Code)).ToList();


Reading a file representing word frequencies in Wikipedia, for clustering analysis

Avoid reinventing-the-wheel, especially with common tasks that are likely to have optimized implementations. In this case, I recommend trying pandas.read_csv() to read the file. Then, the matrix can be fed to sklearn.cluster.KMeans().


Per the comments, this isn't really a "pool" because things don't go back into it when you're done using them. It's just an "incremental allocator" that does allocation in "chunks". A better name for it might be shared_ptr_chunk_allocator (and chunk_size instead of pool_size).

Given that pool_size is used only on the codepath that also allocates memory (so it's not a super speed-critical path where one more memory load would hurt performance), and shared_ptr_pool<...> has non-static data members (so there's no harm in adding one more non-static data member), surely it would make more sense to make pool_size a runtime parameter to shared_ptr_pool's constructor.

// your current code:
shared_ptr_pool<myclass, 16> pool;
// versus my suggestion:
shared_ptr_pool<myclass> pool(16);

This would even allow you to provide a member function for modifying the chunk size on the fly, in case maybe your code could detect that its particular workload demanded a bigger chunk size.

if (memory_usage_low && still_spending_lots_of_time_in_allocation) {
    pool.set_chunk_size(pool.chunk_size() * 2);
}

The actual code implementation looks fine to me; nothing to complain about there. :)

You might be pleased to (or, you might already) know that std::shared_ptr<T[]> is part of the Library Fundamentals v1 Technical Specification, which I think means it ought to be coming to C++1z. However, it's not in the working draft yet as of N4567 (November 2015).


In the function get_letter_grade you were checking more conditions then necessary. Try to follow the logical difference between your function and my code. It is simple math which I used to optimize it. Also structuring it as an if-elif-...-else is better for readability.
In get_average and get_class_average I use a thing called list comprehension. A simple google search will tell you what it is and why it is better. Google it in python tutorials if you have problem.

Edited Functions

def average(values):
    return sum(values) / len(values)

def get_average(student):
    keys = ['homework', 'quizzes', 'tests']
    factors = [0.1, 0.3, 0.6]
    return sum([ average(student[key]) * factor for key, factor in zip(keys, factors)])

def get_letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

def get_class_average(classlist):
    return average([get_average(student) for student in classlist])

get_class_average(classlist)


Produce an array of strings from a single string

Validate is a misleading name for what the function does. It does not validate anything - rather it checks if the given character is one of a special set. So it should be named IsSpecial or IsTokenDelimiter.
Growing an array one entry at a time is quite a bit of overhead. There are some ways of mitigating this.
Consider creating a local variable like currentCharacter in which Chain[i] - this would make it a little bit easier to read.


Evaluating a hashing function used to create secure API key

No, it isn't secure.

Inventing your own hashing algorithms is a horrible idea. When doing password hashing, use something invented by cryptographers that was made for password hashing, e.g. bcrypt. Because I'm not a cryptographer either, I can't give you a full explanation why your code is insecure. In short, the mistake you made was hashing each character of the password on its own. A few things I spotted:

The final output has a length proportional to the length of the password. This can be abused for denial-of-service attacks or to limit the search space when cracking via brute force.
In your final hash, the letters of $salt2 will occur more often. Therefore the resulting hash isn't evenly distributed over the output domain.
Same letters in the password obviously have the same hash. But as that is directly reflected in the output, this can be used as an attack vector (even if I don't know which letter is repeated).
It is not possible to extract the salt(s) from a given hash because you shuffle the string – therefore it is impossible to say whether a given password is the same as the hashed password (we can only check whether the lengths are the same). This makes your hash function unsuitable for authentication – but for what are you using it then? For an API key, an unique random number that does not depend on user input would be better.
…

Your code also uses, but does not define the $salt variable – it assigns $salt1 and $salt2. The $salt1 variable isn't used anywhere.

Secure password hashing is only difficult if you try to use a home-brewed solution. I outlined suggested authentication workflows in another answer which includes a list of recommended password hashing solutions (neither your code, SHA-512, nor MD5 is on that list, don't use them for passwords).


Threshold an image for a given range and Sobel kernel

as things are now, there is little use for the class in this case. the self argument is never used in the functions.

This is easily factored into different functions

def grayscale(img):
    return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

Whether this deserves a separate function or can be inlined is your choice. If you need to type this a lot, or if the method of grayscaling can change in the future, it will be easier to put it in a separate method.. You could also move the colorspace to the arguments to make this more versatile and also accept HSV or Luv encoded images.

def sobel_xy(gray, sobel_kernel=3, absolute=True):
    sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
    if absolute:
        sobel_x, sobel_y = np.absolute(sobel_x), np.absolute(sobel_y)
    return sobel_x, sobel_y

This calculation is done in all methods, so refactoring it is simple and effective

def gradient_magnitude(gray, sobel_kernel=3):
    return np.hypot(*sobel_xy(gray, sobel_kernel))

def gradient_direction(gray, sobel_kernel=3):
    return np.arctan2(*sobel_xy(gray, sobel_kernel))

This part is pretty straightforward. All I changed was use np.hypot to calculate the magnitude

def gradient_abs_sobel(gray, orient='x'):
    dx, dy = (1, 0) if orient == 'x' else (0, 1)
    sobel = cv2.Sobel(gray, cv2.CV_64F, dx, dy)
    return np.absolute(sobel)

def gradient_abs_sobel2(gray, orient='x'):
    orientation = {'x': 0,'y': 1}[orient]
    sobel = sobel_xy(gray)
    return sobel[orientation]

Depending on taste and the expense of the sobel calculation you can pick either of the 2

def scale(sobel, MAX=255, dtype=np.uint8):
    return dtype(MAX * sobel / np.max(sobel))

def mask(img, lower, upper):
    return (img >= lower) & (img <= upper)

Are pretty straightforward too. Instead of the np.zeros_like you can directly use the boolean array of the comparison

Now instead of calling 1 function, you just call the 4 elements subsequently. If this is too much work you can still make 1 compound method for the 3 cases.

gray = grayscale(img)
abs_sobel = gradient_abs_sobel(gray)
result = mask(scale(abs_sobel), 10, 130)


Option Parsing

As mentioned in comments, your option passing raises some issues.

The parsing does nothing to enforce the sequence given in the usage
Any argument at any position that is not recognised as part of an option is treated as a filename.

This opens the risk of a range of silent errors, which worries me about a utility which I should trust to operate safely on a (potentially large) number of files.  There is a simple fix:

Move the filename match to the second slot, just after the Nil match.
Have it throw an exception if the Options map does not already contain 'searchPattern and 'replacePattern

That will eliminate all the worrying errors, leaving only the harmless possibility of multiple '-a' and '-t' options.  There are more functional ways to manage the options but that will do enough for this relatively simple requirement.

It seems you've found and adapted the code from the second-highest scoring answer from this SO question.  I'm surprised that was voted up so much.  It's simple, yes, but also

Fragile
Requires a lot of code repetition to do even simple things
Hard to extend without rewriting most or all of the code
Poor example of both style and good practice

(Not that the third point is so important.  But...  nextOption doesn't return the next option, it returns a map of options - it's badly named to reflect an internal implementation detail.  Using list, map and string as variable names is terrible practice, map in particular)

Which library to use

scopt, from the accepted answer in that link, is pretty good.  I know the example looks a mess, but it's been made deliberately overcomplicated to show off every single feature.  For your code, it would be small, much simpler and more expressive.  It groups all the information relevant to an option in one place, including the validation code (and it handles the validation for you, halting as soon as an invalid option is processed, rather than processing them all and then validating them).  It provides a clear way to distinguish between options and parameters.

The documentation could be a bit more detailed and it does assume you know which methods are automatically generated for case classes (e.g. copy, which is used everywhere in the example).  Note that your config class does not have to be a case class - it just saves you some typing.kj

class FileRanameByPattern

In both rename and printFileNamePairs, why use map?  One returns List[Boolean] while the other returns List((), ()) but since you use them both in an if expression, the result is List[Any].  The result is meaningless, so why not use foreach and just return Unit?


Iterating an array of nodes, each of which can have children

Collection initializer
You can improve and simplify your code by first tuning the Node.

make it IEnumerable<T> and consequently remove the Children and HasChildren properties because now we can use LINQ's Any
let the Name property take care of the formatting and keep the value clean in a dedicated field
replace AddChild with the Add method to be able to use collection initializer
replace the array with a root node

Example:
public class Node<T> : IEnumerable<Node<T>>
{
    private readonly T _value;

    private readonly List<Node<T>> _children = new List<Node<T>>();

    public Node(T value) => _value = value;

    public T Value => _value;

    public string Name => $"Node #{_value}";

    public void Add(Node<T> node) => _children.Add(node);

    public override string ToString() => Name;

    public IEnumerator<Node<T>> GetEnumerator() => _children.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

Enumerator
Now you can improve the algorithm by using the Enumerator. There is no need for any indexes or tuples. What you need to do is to GetEnumerator from each node and MoveNext on it until it is now longer possible to continue or continue from a sub node if it contains Any.
The enumerator will keep the current state allowing you to continue iterating on child nodes and resume from the parent node later that's why you need to re-push the current node back to the stack.
An extension for the Node<T> could look like this:
public static IEnumerable<Node<T>> Flatten<T>(this Node<T> root)
{
    var stack = new Stack<IEnumerator<Node<T>>>();
    stack.Push(root.GetEnumerator()); // start with the root node

    yield return root; // return the root node

    while (stack.Any())
    {
        var node = stack.Pop();
        while (node.MoveNext())
        {
            yield return node.Current;
            if (node.Current.Any())
            {
                stack.Push(node); // re-add the node to continue later
                stack.Push(node.Current.GetEnumerator()); // continue from here now
                break; // we'll continue from "node" later, when node.Current is enumerated
            }
        }
    }
}

Example
You can now create nodes like arrays without confusing parenthesess when adding subnodes:
var nodes = new Node<int>(0)
{
    new Node<int>(1),
    new Node<int>(2),
    new Node<int>(3)
    {
        new Node<int>(4),
        new Node<int>(5)
        {
            new Node<int>(6)
            {
                new Node<int>(7)
            },
            new Node<int>(8)
            {
                new Node<int>(9),
                new Node<int>(10)
            },
            new Node<int>(11)
        }
    },
    new Node<int>(12)
};

after flattening it
nodes.Flatten().Select(n => n.Name).Dump();

you'll get:

Node #0
Node #1
Node #2
Node #3
Node #4
Node #5
Node #6
Node #7
Node #8
Node #9
Node #10
Node #11
Node #12


Avoiding verbose compositional class design

Question

*"...so how is one supposed to avoid all the duplicated methods in choosing composition over inheritance?"

I assume you are talking about JavaScript.
It might be a minor point but In JS we use functions, methods are reserved for the engine where the name comes from the language it is written in V8 for example is written in C++
Duplicating functions
There is no need to duplicate functions no matter how you create your object in JavaScript.
I just can not workout why you would want to do
From your bottom snippet

mthTen() {                // WHY??????
    this.math.mthTen()
}

Examining your example via rewrites
Defining the objects
const Events = () => ({evOne() {}, evTwo() {}});
const Maths = () => ({mthOne() {}, mthTwo() {}});

BTW Use literal if you don't need closure
BTW  you would only define objects (using this pattern) via functions if you were closing over some encapsulated data. They are better defined as literals in this case, avoiding the creation of unused closure for each object
const events = {evOne() {}, evTwo() {}};
const maths = {mthOne() {}, mthTwo() {}};

At the object level
If you want the functions to be accessible at the object level you may build it as follow
const createFoo = (math, events) => ({...math, ...events});
const obj = createFoo(math, events);

// Calling
obj.evOne();
obj.mthOne();

At the object property level
To create them as named properties
const createFoo = (math, events) => ({math:{...math}, events:{...events}});
const obj = createFoo(math, events);

// Calling
obj.events.evOne();
obj.math.mthOne();

As static functions
In many cases you would use them as static functions.
// static instance reference. There is only one math and events for many Foos
const Foo = (math, events) => ({math, events});
const obj = Foo(math, events);

// Calling
obj.events.evOne();
obj.math.mthOne();

Or
// Static instance. There is only one instance of math and events referenced by the constructor  Foo
const Foo = Object.assign(() => ({}), {math, events});
const obj = Foo();
// Note access via the instantiation function  Foo
Foo.events.evOne();
Foo.math.mthOne();
obj.event.evOne(); // will throw as it does not exist.

Or
// Static instance functions. There is only one instance of math and events
// referenced via functions of the constructor  Foo
const Foo = Object.assign(() => ({}), {...math, ...events});
const obj = Foo();

// Note access via the instantiation function  Foo
Foo.evOne();
Foo.mthOne();
obj.evOne(); // will throw as it does not exist.

Note there is no formal way to define static functions its only static by how it is used and instanced (Via the class syntax static is just syntactical sugar for (assign to constructor, rather than prototype))
If you must duplicate
Warning Don't do this at home, it is only as an example. Doing this in any code can result in severe confusion and eventual application death.
If you really wanted to have a second copy of each function. eg obj.evOne and obj.event.evOne You can automate the function creation, binding the copied function references to the object you want as this

const events = {evOne() {}, evTwo() {}};
const logger = {
    logA() { console.log("A" + this.count++)},
    logB() { console.log("B" + this.count++)},
    count: 0
};

const addFunctions = (obj, ...instances) => {
    for (const instance of instances) {
        for (const [name, func] of Object.entries(instance)) {
            func instanceof Function  && (obj[name] = func.bind(instance));
        }
    }
    return obj;
}

const createFoo = (a, b) => addFunctions({logger: a, events: b}, a, b);
const foo = createFoo({...logger}, {...events});

foo.logger.logA();  // should be A0
foo.logA();         // should be A1
foo.logger.logB();  // should be B2
foo.logB();         // should be B3

Question

"What would the draw backs be compared the style of composition where each class you compose with is given a field name (I'm calling this named composition)?"

This question is way too subjective to answer in any death.
There are drawbacks to every pattern, how the drawbacks effect the code quality is very dependent on the coders skill and level of experience.
If you are comfortable with a pattern and have the experience your proficiency outweighs any pattern's drawbacks.
The biggest drawback to any pattern is how experience a coder is in using it.
To be a well rounded coder you must gain proficiency in all the patterns.


I can suggest a bit of math trickiness here. I highly doubt that would improve the readability of your code, but these reduce the amount of required computations. And one remark, I haven't worked with Python, so, no code. Sorry about that. Only performance suggestions.

Keep your angles constant

The heaviest part you have in your vertex computation is constantly recomputing sine and cosine, as you're creating a circle by "rotating the radius" and its angle is constantly changing by a fixed value.

You can reduce this to computing only a single pair of sine and cosine by relying on the rotation matrix. Once computed, it allows you to rotate an arbitrary point around zero by a constant angle.

You push in the first "radius" yourself, then you rotate it by rad, then by 2*rad (and you're forced to compute its sine and cosine again) and so on. But you don't really need it! Instead, you can take the previous computed radius and rotate it by rad again, using the same sine and cosine. The math looks like:

x_new = x * cos(rad) - y * sin(rad)
y_new = x * sin(rad) + y * cos(rad)

There's only one thing to be cautious of: floating point isn't perfect and absolutely precise. And in extreme cases the error will add up with each iteration and may become noticeable. You can't really counter that in any way but reducing the number of iterations. And yes, you can do that too.

Exploit your axes

You have 2 orthogonal axes. And you're drawing a circle which has a neat property of having all the points within a specific distance from its center. Assuming the circle is centered at (0; 0) for brevity, how many points can you get by performing a single rotation? One? No, actually eight. Here are 3 independent things you can do with a single point to get some others, each doubles the amount of points you get:

Negate X
Negate Y
Swap X and Y

  1 * 2 * 2 * 2 == 8 # Yeah, okay.

Imagine you're traversing the circle only knowing 1/8th of its points.

You start from angle 0 (right), you reach pi/4 and...
You follow your pointset in reverse with coordinates swapped, until you reach pi/2.
You swap coordinates back, negate X and follow the pointset straight again, you reach 3pi/4.
You swap coordinates and follow the pointset in reverse again until you reach pi.
You swap coordinates, negate Y and traverse the lower semicircle the same way as above.

So it makes sense to only compute 1/8th of the circle, points in [0; pi/4]. This takes 8 times less point computations, but you should store the results and reuse them when drawing the circle. This requires some extra memory.

Of course, this does not relieve you of benchmarking the improvement. The above is math, just theory.


Determining the HTTP status code to return for a request

You should learn more about partial functions. Everything you need to know is written in the documentation.

It is a structure that allows you to do a basic check on something and if it succeed, it does something. It is composed of two methods :

apply(v1: A): B
isDefinedAt(x: A): Boolean

It applies the apply method on your input parameter only if the isDefinedAt method returned true when called with your input parameter.

The great thing about partial functions is that you can chain them easily with the andThen, compose and applyOrElse operators. Also, they can be written very easily by using the case syntax :

val divideByTwo: PartialFunction[Int, Int] = { case d: Int if d%2 == 0 => d/2 }

But there is another way to write it :

val divideByTwo = new PartialFunction[Int, Int] {
  def apply(d: Int) = d / 2
  def isDefinedAt(d: Int) = (d%2 == 0)
}

Here is a great article about it.


Booting up my Ruby social aggregator app

You can see the answer to Implementing plugins in my Ruby social aggregator app to see some general observations on your code style.

The most important thing I have to point out on this code is that your run loop is not a loop, but a recursion. This is especially bad, since it will eventually kill your whole application on a StackOverflow exception (pun?)

You should always use iteration over recursion when the loop is infinite:

def start
  until @@stop
    @@plugin_manager.run

    logger.debug "Aggregation done. Next aggregation in #{setting.aggregate_timer} seconds."

    sleep setting.aggregate_timer
  end
end

Also, you seem to mix instance scope and class scope. You allow for multiple Aggregators, but there is only a single shutdown. Either design your class for multiple uses, in which case state and methods should be of the instance, or that it is a Singleton, for which there are patterns in ruby.

You seem to have a lot of comments in your code. Ruby encourages less comments, and more expressive method names. There is no point in a comment, if it does not add anything to the code itself. This code:

# Initialize aggregator
app = Aggregator.new(true, ARGV)

has no advantage to simply writing

app = Aggregator.new(true, ARGV)

Using static members (@@stop) is also not advisable. If you are writing inside the self scope (inside def self.shutdown) simple members (@stop) are actually in the class scope, being effectively static. To access them from outside this scope, add a getter:

def self.stop
  @stop
end

Which will be accessible by calling Aggregator.stop.

Refactored Aggregator:

class Aggregator
  include Logging
  include Setting

  AGGREGATOR_VERSION = '0.0.1'

  def self.version
    AGGREGATOR_VERSION
  end

  attr_reader :environment, :plugin_manager, :stop

  def initialize(internal_server = false, arguments = [])
    options = ArgumentParser.parse(arguments)

    Logging::environment options.environment
    Logging::quiet = true if options.quiet

    logger.info 'Starting up aggregator now'

    logger.info "Using #{options.environment} environment"
    @environment = options.environment

    DatabaseInitializer.new(options.environment)

    return if options.environment == :test

    if options.console
      ConsoleInitializer.new(options.environment)
    else
      @plugin_manager = PluginManager.new

      ServerInitializer.new if internal_server

      logger.info "Aggregator is up and running"

      Signal.trap("SIGINT") do
        Thread.current.exit
      end

      start
    end
  end

  def shutdown
    @stop = true
  end

  private

  def start
    until stop
      @plugin_manager.run

      logger.debug "Aggregation done. Next aggregation in #{setting.aggregate_timer} seconds."
      sleep setting.aggregate_timer
    end
  end
end