Entering two integers and returning a decimal fraction

import java.io.*;

It's often a bad practice to import everything in a package. this will clutter your IDE's Ctrl + Space functionality, and makes it harder for other people to see exactly which things you are using from a package.

/**
 * Class: GetRationalNumber

I like the Javadoc, but it's totally overkill to specify the class name in the javadoc. The class name is already displayed in the javadoc functionality itself, you don't need to duplicate that when you write javadoc.

int p, q;

Make it a habit ASAP to avoid one-letter variable names like these. numerator and denominator would be much better.

Possible improvement: Catch NumberFormatException (or use a regex in advance to make sure that it is a number, but that might a bit over your head right now).

System.out.println(
    "Divison by zero can cause serious trouble to the universe!"
);

I would write this on one line:

System.out.println("Divison by zero can cause serious trouble to the universe!");

System.exit(0);

The zero here indicates the exit status, which can be used by scripts and other stuff. If a program terminates normally, that is exit status zero. Is a possible division by zero really a normal program termination? In my opinion it is not. I would do System.exit(1); or System.exit(42); or something.

Overall, there's nothing object-oriented about what you have done, but I guess you haven't gotten that far yet, huh? :) Your code is quite fine for being beginner code. Now take it to the next level :)


In my opinion, a factory should create a specific class, global ones like this one shouldn't be used. For instance, having a PizzaFactory is something like this:

class PizzaFactory
{
    public static function createPizza($type)
    {
        switch ($type) {
            case 'salami':
                return new SalamiPizza();
                break;

            case 'hawai':
                return new HawaiPizza();
                break;
        }
    }
}

  I just want to get some opinions on the the topic of a Factory. Is this a good method? are there others that are considered superior? If so, what have I overlooked?

An upcomming design pattern is depedency-injection. Just search for some resoures about that and keep reading. It is used in all modern frameworks (ZF2 and Symfony 2 uses it).

See also this article serie by Fabien Potencier: "What is Dependency Injection?"


You can use Laravel's form requests to keep rules and validation logic out of controllers.


Squeezing decorators into functional extensions

IMO the first version is easier to maintain, and I don't see from the shown code, what you gain by the second.

In the second version:

Each FileProvider class doesn't need to explicitly inherit IDecorable<IFileProvider> because that is inherited via IFileProvider.

I maybe overlooking something or you may find it too obvious to show, but I don't like that you implement the interface IFileProvider in all the provider classes, because they then are forced to implement all (I can see there aren't any (yet)) possible common members, which could be taken care of in a base class. Therefore I would create an abstract base class for the providers like:

  interface IDecorable<T>
  {
    T DecorateWith(Func<T, T> createDecorator);
  }

  interface IFileProvider : IDecorable<IFileProvider>
  {

  }

  abstract class FileProvider : IFileProvider
  {
    public virtual IFileProvider DecorateWith(Func<IFileProvider, IFileProvider> createDecorator)
    {
      return createDecorator(this);
    }
  }

  class PhysicalFileProvider : FileProvider
  {
    public static PhysicalFileProvider Create()
    {
      return new PhysicalFileProvider();
    }
  }

  class RelativeFileProvider : FileProvider
  {
    public RelativeFileProvider(IFileProvider fileProvider, string basePath)
    {

    }

    public static Func<IFileProvider, RelativeFileProvider> Create(string basePath)
    {
      return decorable => new RelativeFileProvider(decorable, basePath);
    }
  }
  ...

In this way you gain both the benefits of normal OOP inheritance/polymorphic behavior and the decorator pattern and at the same time are still free to chain .DecorateWith(...) with other implementers of IFileProvider

Madness is a strong word. The shown chain looks a little nicer than a chain of new xx() statements, and you explicitly "explain" the pattern and behavior. And the first version doesn't need much attention when first written, so no harm done at least.


First off I noticed a problem in how the quiz chooses the numbers:

It can easily happen that two (or more) numbers are the same. Especially when picking number between 1..5. In that case it can be confusing to the user, which of the two equal numbers should he click.

The main problems with the code resides in tight coupling between UI logic and business logic. For example the createPoints() function:

function createPoints(count) {
    let contentInner = document.getElementById('contentInner');

    for(let i = 0; i <= 2; i++) {
        let num_ = Math.random() * count;
        let num = Math.ceil(num_);

        let pointEl = document.createElement('div');
        pointEl.className = 'point';
        pointEl.id = 'point_' + i;
        pointEl.setAttribute('data-num', num);
        pointEl.innerHTML = num;

        contentInner.appendChild(pointEl);
    };
};

This function both:

generates three random numbers and
displays the numbers on page.

Would be better two have two functions that separately perform the tasks, something that could be used like so:

displayNumbers(randomNumbersBelow(10))

Also note the naming: the original name createPoints() seems to be talking about some coordinates, which doesn't sound correct to me.

By separating the two, it should be also easier to improve randomNumbersBelow() function so that it would not return duplicates, without having to modify anything inside displayNumbers().

Additionally:

num_ variable can be easily eliminated by inlining the expression: Math.ceil(Math.random() * count).
Instead of modifying the contentInner element by itself, it could just return the new contents (e.g. as a DocumentFragment). That would eliminate the need for the existence of clearContent() function.


Reduce square root to simplest radical form

Style

Give your code some love and help readers by adding blank lines to separate logical sections of code. It is recommended to use two blank lines before function definition.

Space after commas and around operators also help make the code more readable.

Some of your comments would be better suited as docstrings and some other barely state what you are doing, which we could read from the code already. Comment should focus on why instead.

Lastly using meaningful variable names play a large role in making your algorithm understandable. Avoid abreviations.

from math import sqrt

def perfect_square(limit):
    accumulation_list = [1]
    index, increment = 0, 3
    while accumulation_list[-1] + increment <= limit:
        accumulation_list.append(accumulation_list[iindex] + increment)
        index += 1
        increment = 2 * index + 3
    return accumulation_list

def reduced_sqrt(n):
    """Print most reduced form of square root of n"""

    if n < 0:
        print('Negative input')
        return

    if sqrt(n).is_integer():
        print(int(sqrt(n)))
        return

    # Find perfect squares that are factors of n
    factors = [square for square in perfect_square(n/2) if n % square == 0 and square > 1]
    if len(factors) == 0:
        print('\u221A', n) # Square root is irreducible
    else:
        a = int(sqrt(max(factors))) # Coefficient
        b = int(n / max(factors)) # Argument of the square root
        print(a, '\u221A', b) # Reduced square root

Unnecessary work

Why compute the perfect squares starting from 1 if you are going to filter this value later on?
Why compute all these values at all if you're only going to take the max of all factors?
You also compute sqrt(n) and max(factor) several time when you could store the result in a variable.
Most importantly, you compute the perfect squares rather expensively only to recompute its fairly expensive sqrt when you find one as factor.

Instead you could iterate from the nearest integer lower than sqrt(n) down to 1 and see if its square is a factor of n. Once found you have your factor without computing the remaining values. If none can be found, you know that you have an irreducible square root.

A first draft could be:

from math import sqrt

def reduced_sqrt(n):
    """Print most reduced form of square root of n"""

    if n < 0:
        print('Negative input')
        return

    root = int(sqrt(n))
    found = False

    for factor_root in range(root, 1, -1):
        factor = factor_root * factor_root
        if n % factor == 0:
            found = True
            reduced = n // factor
            if reduced == 1:
                # n was a perfect square
                print(factor_root)
            else:
                print(factor_root, '\u221A', reduced)
            break

    if not found:
        # irreducible square root
        print('\u221A', n)

Reusability

It is bad practice to encore computation and output in the same function as it makes it harder to test and reuse. You should instead return a couple "coefficient/reduced square root" so that the caller can handle the logic of pretty printing the output.

This also means you need better handling of you error case. The standard in Python being to raise an exception. Here raise ValueError('negative input') should be enough. But you don't even need that as sqrt of a negative number already raise a ValueError:

>>> sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Lastly, returning values let you short circuit your computation and remove the need of the found flag:

from math import sqrt

def reduced_sqrt(n):
    """Return most reduced form of square root
    of n as the couple (coefficient, reduced_form)
    """

    root = int(sqrt(n))

    for factor_root in range(root, 1, -1):
        factor = factor_root * factor_root
        if n % factor == 0:
            reduced = n // factor
            return (factor_root, reduced)

    return (1, n)

def print_reduced_sqrt(n):
    coefficient, reduced = reduced_sqrt(n)
    if coefficient == 1:
        print('\u221A', reduced)
    elif reduced == 1:
        print(coefficient)
    else:
        print(coefficient, '\u221A', reduced)


Efficient element-wise function computation in Python

You can avoid the nested loops using numpy.meshgrid to build a table of entries in x and y, and numpy.vectorize to apply a function to all entries in the table:

def tabulate(x, y, f):
    """Return a table of f(x, y)."""
    return np.vectorize(f)(*np.meshgrid(x, y, sparse=True))

For example:

>>> import operator
>>> tabulate(np.arange(1, 5), np.arange(1, 4), operator.mul)
array([[ 1,  2,  3,  4],
       [ 2,  4,  6,  8],
       [ 3,  6,  9, 12]])

This is about twice as fast as proxy_kernel:

>>> from timeit import timeit
>>> X = Y = np.arange(2000)
>>> timeit(lambda:proxy_kernel(X, Y, operator.mul), number=1)
2.174600816098973
>>> timeit(lambda:tabulate(X, Y, operator.mul), number=1)
0.9889162541367114

but it still has to evaluate the slow Python code in f for each entry in the table. To really speed things up you need to use whole-array operations throughout. Depending on how you've written f, it may be possible to do this directly. For example, if you have something like:

def f(x, y):
    return np.exp(-0.5 * np.abs(x - y))

then this is already suitable for applying to whole arrays:

>>> f(*np.meshgrid(np.arange(4), np.arange(4), sparse=True))
array([[ 1.        ,  0.60653066,  0.36787944,  0.22313016],
       [ 0.60653066,  1.        ,  0.60653066,  0.36787944],
       [ 0.36787944,  0.60653066,  1.        ,  0.60653066],
       [ 0.22313016,  0.36787944,  0.60653066,  1.        ]])

and this is about five times as fast as using numpy.vectorize:

>>> timeit(lambda:f(*np.meshgrid(X, Y, sparse=True)), number=1)
0.1973482659086585


Android layout with equal spacing between elements

I don't know what the standards are for Layout Naming on Android, but I can tell you that these names are not very good.

textView2
btn_distance_walked
textView3

none of these accurately describes what they do.

you should probably look for naming schemes on Google.

btn_distance_walked doesn't tell us what the button is going to do. What is it going to do with the distance walked? It should be something like calculate_Distance or calculateDistance (my preferred naming scheme camelCasing)

Update:

I recently answered a question similar to this one and came up with a name scheme for buttons, action_ObjectActedUpon  this may be more specific to the naming issue in your code as well.

Your indentation seems to be off as well, it should look like this

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:text="" />

    <Button
        android:id="@+id/btn_distance_walked"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:clickable="false"
        android:text="Distance walked = " />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:text="" />

    <Button
        android:id="@+id/btn_exersise_time"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:clickable="false"
        android:text="Exercise time = " />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:text="" />

    <Button
        android:id="@+id/btn_average_speed"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:clickable="false"
        android:text="Average speed = " />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:text="" />

    <Button
        android:id="@+id/btn_calories_burned"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:clickable="false"
        android:text="Callories burned = " />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:clickable="false"
        android:text="" />

    <Button
        android:id="@+id/btn_back"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:text="Back" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:text="" />
</LinearLayout>

I just answered a similar question and I think that I should add a little bit of that answer to this one..

Another way that you can reduce clutter in the layout is to define some styles by creating an xml file in the res/values/ folder of your project and do this

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyStyle1">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">0dip</item>
        <item name="android:layout_weight">1</item>
        <!-- etc. -->
    </style>
</resources>

and then in your Layout XML you add the style to the layout element like this

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:orientation="vertical" >

    <TextView
        style="@style/MyStyle1"
        android:id="@+id/textView2"
        android:text="" />

    <Button
        style="@style/MyStyle1"
        android:id="@+id/btn_distance_walked"
        android:clickable="false"
        android:text="Distance walked = " />

    <TextView
        style="@style/MyStyle1"
        android:id="@+id/textView3"
        android:text="" />

    <Button
        style="@style/MyStyle1"
        android:id="@+id/btn_exersise_time"
        android:clickable="false"
        android:text="Exercise time = " />

    <TextView
        style="@style/MyStyle1"
        android:id="@+id/textView4"
        android:text="" />

    <Button
        style="@style/MyStyle1"
        android:id="@+id/btn_average_speed"
        android:clickable="false"
        android:text="Average speed = " />

    <TextView
        style="@style/MyStyle1"
        android:id="@+id/textView5"
        android:text="" />

    <Button
        style="@style/MyStyle1"
        android:id="@+id/btn_calories_burned"
        android:clickable="false"
        android:text="Callories burned = " />

    <TextView
        style="@style/MyStyle1"
        android:id="@+id/textView6"
        android:clickable="false"
        android:text="" />

    <Button
        style="@style/MyStyle1"
        android:id="@+id/btn_back"
        android:text="Back" />

    <TextView
        style="@style/MyStyle1"
        android:id="@+id/textView1"
        android:text="" />
</LinearLayout>

note that I am not a professional, but I found Styles and Themes from doing a quick search for styles.xml android example

Don't forget about Developer.Android.com it can be very helpful.


Multiple jQuery statements in one function

First off, don't use the onclick attribute. You have jQuery, so use it to set the appropriate event handler:

$(".accordionHeadingDiv").click(function (event) {
  ...
});

That will add a click-event handler to all the headings.

Now, as far as I can tell, your code then removes the active class from all other accordion elements, adds it to the one that was clicked, and does the arrow-replacement.

This is simpler with the event handler setup above:

$(".accordionHeadingDiv").click(function (event) {
  $("#accordion .active").removeClass("active"); // remove "active" from others
  $(this).addClass("active"); // add it to the heading that was clicked
});

For the arrows, I'd advice a better class name system and more CSS. Call the class simply "arrow", and don't bother changing it via JS. Since you set the heading to active all you need is CSS like this

.accordionHeadingDiv .arrow {
  /* default style (i.e. arrow pointing down) */
}

.accordionHeadingDiv.active .arrow {
  /* active style (i.e. arrow pointing up) */
}

No need for JS.

While I'm at it, I'd advice you to make better use of semantic HTML and CSS:

Don't call a class accordionHeadingDiv. The class should be independent of the element type. If you want to style based on element and class, the basic CSS syntax of div.accordionHeading is better.
Actually, don't call it accordionHeading either. It's nested inside the #accordion element, so you don't need to prefix the class name. You can style it with just #accordion .heading
Actually, don't even use heading: Use a heading element! You've already got one, but there's no need for the DIV around it.

What you get is something like

    Transport logistics

    <?php require 'templates/dummyBedrijven.php'; ?>

  ...

Much cleaner. (P.s. I'd use include instead of require)

However...

That's all well and good, but if I understand you correctly, jQueryUI is handling all the accordion stuff. And jQueryUI adds its own "active" class to the opened accordion-element. So you can actually get rid of all you custom JS and just stick to CSS:

#accordion .ui-accordion-header .arrow {
  /* default style (i.e. arrow pointing down) */
}

#accordion .ui-accordion-header-active .arrow {
  /* active style (i.e. arrow pointing up) */
}

All you need in the JS is:

$('#accordion').accordion();

Here's a demo


Extracting the timestamp, minimum score, and maximum score from hundreds of arrays

I'm a little unsure of why scoresDates starts with a 56-item array and the rest are 2-item arrays.

Just to be sure, this is your data model, correct? Please let me know if I've totally misread things.

scoresDates is [
    [date, score, score, score...],
    [date, score],
    [date, score],
    ...
]

Working forwards from your current code, here are some suggestions. I've used some functions like Array.filter that require IE > 9; if you need to support old Internet Explorer then a utility library like Lodash would provide polyfills for these.

In general, you're doing more loops through the data than should be necessary. For example:

Sorting is extra work

  // Next step is sorting the scoreSorted1 array from lowest score to highest score.
  scoreSorted1.sort(function(a,b){
    return a-b;
  });

  // Find maximum and minimum scores in the array and finally push them into the scoreSortedPrimer array.
  var primerMin = Math.min.apply(Math, scoreSorted1);
  scoreSortedPrimer.push(primerMin);
  var primerMax = Math.max.apply(Math,scoreSorted1);
  scoreSortedPrimer.push(primerMax);

scoreSorted1 seems to only be used for calculating min and max. Sorting is more work than min and max, each of which go through the entire array anyway. Here are a few faster options:

keep the sorting, in which case you will know that min is the first item and max is the last
don't sort, just call Math.min and Math.max.
write your own function that calculates both min and max in just one pass of the array, as opposed to two (Math.min + Math.max)

Array.filter

Using higher-level functions like forEach and filter can simplify some of your loops, by letting you ignore array indexes.

For example, this:

var scoreSorted1 = [];

// First level for loop that goes through the unique scores array and ignores the date, while pushing all the scores into the scoreSorted1 array.

for(var z = 0, zz = uniqueDaysScores[i].length; z < zz; z++){
  if(uniqueDaysScores[i][z] < 1000){
    scoreSorted1.push(uniqueDaysScores[i][z]);
  }
}

becomes

var scoreSorted1 = uniqueDaysScores[i].filter(function(score) {
  return score < 1000;
});

And, at a higher level, your entire program becomes two parts: merging all the scores for each date, then applying a function [scores] -> [min(scores), max(scores)] to each item in that merged object.

Comments

Comments should explain why, rather than describe the code, unless it is particularly hairy. This is a little subjective, but, for example, you can easily read scoreSorted1.sort(... and see that it is sorting the scores, comment or not.

Instead, I recommend saving comments for more confusing passages and for higher-level overviews of your functions or logic. Using descriptive variable and function names is often enough of a comment.

// Logic to take all the scores, sort them from decreasing to increasing order, then package the date, lowest and shortest score into the finished array, scoreSorted.

for(var i = 0, ii=uniqueDaysScores.length; i < ii; i++){
  var scoreSorted1 = [];
  var scoreSortedPrimer = [];

// First level for loop that goes through the unique scores array and ignores the date, while pushing all the scores into the scoreSorted1 array.

  for(var z = 0, zz = uniqueDaysScores[i].length; z < zz; z++){
    if(uniqueDaysScores[i][z] < 1000){
      scoreSorted1.push(uniqueDaysScores[i][z]);
    }
  }

  // Next step is sorting the scoreSorted1 array from lowest score to highest score.
  scoreSorted1.sort(function(a,b){
    return a-b;
  });

  // Find maximum and minimum scores in the array and finally push them into the scoreSortedPrimer array.
  var primerMin = Math.min.apply(Math, scoreSorted1);
  scoreSortedPrimer.push(primerMin);
  var primerMax = Math.max.apply(Math,scoreSorted1);
  scoreSortedPrimer.push(primerMax);

  // Finally, find the date and push it into the scoreSortedPrimer array, so it can be pushed into the main scoreSorted array.

  for(var x = 0, xx = uniqueDaysScores[i].length; x < xx; x++){
    if(uniqueDaysScores[i][x] > 1000){
      scoreSortedPrimer.unshift(uniqueDaysScores[i][x]);
    }
  }
  uniqueDaysScores.push(scoreVarianceSortedPrimer);
}

becomes, more sparsely,

// Calculate min and max score for each date, appending to uniqueDaysScores.

uniqueDaysScores.forEach(function(dateAndScores) {

  var date = dateAndScores.filter(function(score) {
    return score >= 1000;
  })[0];

  var scores = dateAndScores.filter(function(score) {
    return score < 1000;
  });

  uniqueDaysScores.push([
      date,
      Math.min.apply(Math, scores),
      Math.max.apply(Math, scores)
  ]);
});

and would be even simpler if the date was stored somewhere specific so that you don't need to use loops or filter to find it.

Let's rewrite the initial score-merging step to accommodate this.

Merging/grouping scores for each date

I think this is where a lot of the extra complexity is coming from.

Using an object, with the dates as keys and the arrays of scores as values, would be natural, but your array of [date, scores...] arrays would also work.

The important thing is to make sure the date is easy to find, not mixed into your scores, so you don't need to search for it later (by checking what score is > 1000).

// Logic that stacks all the scores per unique day from all the user's game scores. All unique dates with subsequent scores are stored in the uniqueDaysScores array.

uniqueDaysScores = [];
uniqueDaysScores.push(scoresDates[0]);

for(var i = 0, ii = scoresDates.length; i < ii; i++){
  var tempArray = [];

  if(scoresDates[i][0] == uniqueDaysScores[0][0]){
    uniqueDaysScores[0].push(scoresDates[i][1]);
  } else{
    tempArray.push(scoresDates[i][0]);
    tempArray.push(scoresDates[i][1]);
    uniqueDaysScores.unshift(tempArray);
  }
}

becomes, using an object of {date: scores},

// Group scores by date

var scoresByDate = {};

scoresDates.forEach(function(scores) {
  var date = scores[0];
  scores.shift();  // Remove date

  if (!(date in scoresByDate)) {
    scoresByDate[date] = scores;
  } else {
    scoresByDate[date].concat(scores);
  }
}

I've used forEach here, but your original loop-with-index would also work just fine.

With this scoresByDate structure, finding min and max for each date becomes very easy:

var maxMinByDate = Object.keys(scoresByDate).map(function(date) {
  return scoreMinMax(date, scoresByDate[date]);
};

or you could just not bother with a separate scoreMinMax function.

Altogether

With fewer, more high-level comments and a better data model, you end up with something more like this:

var scoresDates = [...];

// Group scores by date.

var scoresByDate = {};

scoresDates.forEach(function(scores) {
  var date = scores[0];
  scores.shift();  // Remove date

  if (!(date in scoresByDate)) {
    scoresByDate[date] = scores;
  } else {
    scoresByDate[date].concat(scores);
  }
}

// Calculate min and max score for each date.

var minMaxByDate = Object.keys(scoresByDate).map(function(date) {
  var scores = scoresByDate[date];
  return [
    date,
    Math.min.apply(Math, scores),
    Math.max.apply(Math, scores)
  ];
});

which could be further accelerated by writing a extrema(arr) function that would return the pair [min(arr), max(arr)] in one pass.


It's a good idea to profile your code (which is easy if you use stack – instead of stack build, just type stack build --profile, and run your program with the options +RTS -p) to find out exactly where the bottle-necks are. See the GHC profiling guide for more information.

If you do that, you'll find that a significant amount of your program's time is spent splitting up strings into words, and parsing them into Ints. Remember that a Haskell string is a linked list of characters, and thus not particularly efficient – I found that using the Text type from the text package results in the revised program taking only 40% of the time of your version. (Contrary to the other comment here, the binary search you've implemented seems fairly efficient, that's not where the slow-down is.)

Instead of getLine from the standard Prelude, use the version of getLine from Data.Text; instead of parsing a line of text using read . word, I'd suggest something like the following:

import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.Text (Text)

-- ...

forceEither :: Either a b -> b
forceEither (Right r) = r

parseLine :: Text -> [Int]
parseLine txt =
  map (fst . forceEither . T.decimal) $ T.splitOn (T.pack " ") txt

(Possibly a hand-coded loop might be even faster than T.splitOn, but I didn't check that.)

I'd also suggest splitting out the parsing of input from the actual solving of the problem - no advantage is gained by putting everything into main. I'd further suggest that writing sum makes your intent clearer than foldl (+) 0; and that you use Vectors instead of Arrays, since this will (a) get rid of extra bits of cruft in the code and (b) allow you to use the vector-algorithms package, which already contains a binary search function. It's usually far better to use someone else's de-bugged search routine than write your own. However, if you are submitting for an online competition, that package may not be available. Nevertheless, it provides useful inspiration on how the search may be sped up.

This gives code along the following lines:

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}

import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.Text (Text)
import qualified Data.List as L

import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed.Mutable as VMut

import Control.Monad  ( replicateM )

import System.IO.Unsafe
import Data.Bits (shiftR)

-- adapted from "vector-algorithms" package:

{-# INLINE binarySearchPBounds #-}
binarySearchPBounds p vec = loop
 where
 loop !l !u
   | u <= l    = return l
   | otherwise = VMut.unsafeRead vec k >>= \e -> if p e then loop l k else loop (k+1) u
  where k = (u + l) `shiftR` 1

{-# INLINE binarySearchL #-}
binarySearchL vec e = binarySearchPBounds (>= e) vec 0 (VMut.length vec)

{-# INLINE binarySearchR #-}
binarySearchR vec e = binarySearchPBounds (> e) vec 0 (VMut.length vec)

forceEither :: Either a b -> b
forceEither (Right r) = r

parseLine :: Text -> [Int]
parseLine txt =
  map (fst . forceEither . T.decimal) $ T.splitOn (T.pack " ") txt

bisectLeft :: Int -> Vector Int -> Int
bisectLeft n xs = unsafePerformIO $ do
  xs' <- V.unsafeThaw xs
  binarySearchL xs' n

bisectRight :: Int -> Vector Int -> Int
bisectRight n xs = unsafePerformIO $ do
  xs' <- V.unsafeThaw xs
  binarySearchR xs' n

getInput :: IO [Text]
getInput = do
  res@[n, as, bs, cs] <- replicateM 4 T.getLine
  return res

sortedVec :: t -> Text -> Vector Int
sortedVec n txt =
  V.fromList $ L.sort $ parseLine txt

parseProblemInput
  :: [Text] -> (Int, Vector Int, [Int], Vector Int)
parseProblemInput [nStr, asStr, bsStr, csStr] =
  let [n] = parseLine nStr
      as =  sortedVec n asStr
      bs =  parseLine  bsStr
      cs = sortedVec n csStr
  in (n, as, bs, cs)

solve :: (Int, Vector Int, [Int], Vector Int) -> Int
solve (n, as, bs, cs) =
  sum $ map (\ b -> bisectLeft b as * (n - bisectRight b cs)) bs

main = do
  ls <- getInput
  print $ solve $ parseProblemInput ls

This may not be as concise as your code, but should be much easier to follow and to modify - and importantly, for your purposes, it runs in less than half the time.

Other notes - the Unboxed versions of Vectors will normally be faster than the boxed versions, if you can use them; if you're submitting code for review, then I'd think a few more comments in your code wouldn't go astray. I hope that helps.


What is the best way to format a large has_many through line?

This is what I would do:

has_many :owning_artists, {
  :through => :artist_tracks,
  :source => :artist,
  :conditions => {
    :artist_tracks => {
      :artistic_role_id => 1,
      :another_memeber => 42
    }
  }
}


Sorting an array of bands by omitting articles

I would consider using a regex instead:

const articlesRegex = /^(The|An|A)\s+/i;

const sorted = bands.sort((previous, next) => {
  previous = previous.replace(articlesRegex,'');
  next = next.replace(articlesRegex,'');

You should also return 0 when the items are equal.


This is actually rather unconventional code.  The head node of this list, test, resides on the stack.  All of the subsequent nodes are allocated from the heap using malloc().  Since you never call free() on the memory returned by malloc(), you have a memory leak.  When you eventually try to fix your memory leak, you're very likely to get confused: you need to free() all the nodes except test.

Furthermore, linked lists are usually terminated by a NULL pointer.  After this program finishes, though, the tail of the list is an uninitialized chunk of memory from malloc(), which you should consider to return random garbage.  (In practice, you are likely to get lucky and receive pre-zeroed memory since your program is running on a virgin heap, but you should not count on that behaviour.)

I suggest that you build the linked list all on the heap.  Also, build it backwards, starting from the tail, so that your pointer is always pointing to the head.  When you're done, you'll be holding a pointer to the head, which is useful.

#include <stdlib.h>

int main(void)
{
    struct list
    {
        int x;
        struct list *next;
    };

    /* Create the list */
    struct list *head = NULL;
    /* Just use an int for the counter. A char is just weird. */
    for (int counter = 0; counter < 6; counter++)
    {
        struct list *node = malloc(sizeof(*node));
        node->next = head;
        head = node;
    }

    /* Destroy the list */
    while (head) {
        struct list *node = head;
        head = head->next;
        free(node);
    }
    return 0;
}


(long) 0 scructures should be written as 0L.
Access modifiers of numList and result should be private:

private ArrayList<Long> numList = new ArrayList<Long>(5000001);
// status of whether a number is power number
private boolean[] result = new boolean[5000001];

ArrayList<...> reference types should be simply List<...>. See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces

private List<Long> numList = new ArrayList<Long>(5000001);

5000000 is a magic number. Using named constants instead of numbers would make the code more readable and less fragile. If you have to modify it's value it's easy to forget to do it everywhere. 2237 is also a magic number and a computed value. I'd create a MAX constant:

private static final int MAX = 5000000;

and use it everywhere, for example:

private boolean[] result = new boolean[MAX + 1];

then change 2237 to the following:

final int maxSquare = (int) Math.ceil(Math.sqrt(MAX));
for (int i = 2; i <= maxSquare; i++) { ... }

numList only used in the constructor, so it could be a local variable there instead of a field. Try to minimize the scope of variables. See Effective Java, Second Edition, Item 45: Minimize the scope of local variables.
Actually, I'd rename numList to perfectPowers since it stores perfect powers. I'd make the code more readable and easier to maintain.
You set the initial capacity of the list to 5000000 while it contains only about 2500 elements. It's a huge memory wasting. I'd use the default constructor of the ArrayList which use less memory.

final List<Long> perfectPowers = new ArrayList<Long>();

Math.pow uses floating point numbers which are not always precise. For small numbers it's correct, but for big numbers it not:

final long a = 97761243;
final long aa = a * a;
System.out.println("long            " + aa);
System.out.println("Math.pow        " + ((long) Math.pow(a, 2)));
System.out.println("BigInteger.pow: " + BigInteger.valueOf(a).pow(2).longValue());

It prints:

long            9557260632905049
Math.pow        9557260632905048
BigInteger.pow: 9557260632905049

So, I'd change the while loop to the following:

long value;
while ((value = BigInteger.valueOf(i).pow(j).longValue()) <= MAX) {
    perfectPowers.add(value);
    j++;
}

Some additional changes on the same loop would result the following:

while (true) {
    final long value = BigInteger.valueOf(i).pow(j).longValue();
    if (value > MAX) {
        break;
    }
    perfectPowers.add(value);
    j++;
}

It does the same but I think it's easier to read.
In the first for loop I'd rename i to base and j to exponent, and the parameters of the howMany method to lowerBound and upperBound.
The empty static block is unnecessary:

static {
}


Makefile and main header file for a shell

What is the header file's name?  The point being that the name of the header file, like xopen.h should have some connection to the items inside.  Further, the objects declares and macros defines are all over the name space.  Consider some convention. Put do_...() in do.h, CommandEntry in CommandEntry.h.
Strange #define.  Did you mean #define VERSION "v0.1a"?

#ifndef VERSION
//#define VERSION2 "v0.1a"
#define VERSION "v0.1a"
#endif

static struct option options[] will create a options[] with each *.c this include file is used.  Certainly not a good idea because it is static.  `static objects are best for the *.c file and not *.h header files.
Odd to have #define _XOPEN_SOURCE 500 and #define VERSION "v0.160429-21-g54bb-dirty" outside the include guard #ifndef OPENSHELL_OPENSHELL_H.  Suggest putting them inside unless you are attempting something novel.
Line spacing is odd.  Why no line space after a struct definition, yet spaces between similar function declarations.

struct command {
    char *const *argv;
};
extern void freeChunks(void);

extern char **str_split(char *a[], char *a_str, const char a_delim);

extern int do_checkenv(int argc, const char **argv);

The horizontal space is odd here - perhaps an effect of using tabs?

#define    CMD_LEN        1024
#define    EXPAND_ALLOC    1024
#define    PATH_LEN    1024
#define    isBlank(ch)    (((ch) == ' ') || ((ch) == '\t'))
#define    isDecimal(ch)    (((ch) >= '0') && ((ch) <= '9'))
#define    MAX_SOURCE    10

All UPPERCASE identifiers are often considered macros.  Code with CHUNK may confuse viewers of your code.  Re:typedef struct chunk CHUNK;
Not using all UPPERCASE for defines like with #define isBlank(ch) is a problem as a user of that macro does not benefit from the all uppercase hint that it is a macro.  That macro uses ch twice (((ch) == ' ') || ((ch) == '\t')).  Consider the effect of this usage

int ch;
while (isBlank(ch = getchar())) { ... }

Standard suggestion.  Add name and date (year) to your code.

// 2016 Programmer 400

C has a boolean _Bool.  By using <stdbool.h> , code has access to bool, true, false.  Suggest true rather than TRUE in #define    DEBUG TRUE.
Order:  In general, it is cleaner to do the define first, struct, union, typedef, then global variables and lastly function declaration.  This is highly a style issue though.
Unclear why some function have a preceding extern and others do not.  With function declarations, extern is not necessary.  To use or not is a style issue, but it should certainly be consistent within a *.h file.

// to extern or not to extern, that is the question.
extern int do_kill(int argc, const char **argv);
int spawn_proc(int in, int out, struct command *cmd);


I remember having read somewhere (possibly in another Code Review answer) that for an e-mail address, the simplest and most effective validation you can do is to make sure it contains an @. Making it more restrictive than that can often be a risk of invalidating some valid e-mails. You'd be surprised at some examples of valid e-mail addresses.

As an additional example, see the "almost RFC 822 compatible regex" in this answer.

Keep it simple, and don't mark some e-mail addresses that are actually valid as invalid.

email.contains("@")

If you want to be more restrictive than this, use an existing and trusted library for the validation, don't try to make another regex.

For further reading:

http://en.wikipedia.org/wiki/Email_address#Validation_and_verification
list of email addresses that can be used to test a javascript validation script on Stack Overflow
http://codefool.tumblr.com/post/15288874550/list-of-valid-and-invalid-email-addresses


`set_includes` (string subsequence-containment) in Python 2

AFNP. The loop condition j != hn is more idiomatically expressed as an exception:

try:
    for c in needle:
        while haystack[j] < c:
            ....
except IndexError:
    return False

No naked loops. Factor the while haystack[j] < c: into a function. Among other benefits, it'd allow

    j = search_character(haystack[j:], c)

The binary search for c seems more performant than linear. See bisect module.


Your conversions are... pretty WTF :)

void insert_if_product(string const& factor1, string const& factor2, string const& product) {
    auto p = std::stoul(product);
    if (std::stoul(factor1, nullptr, 10) * std::stoul(factor2, nullptr, 10) == p) {
        products.insert(p);
    }
}

I mean why use an intermediate stream? Why, if you're using a stream, build it using string concatenation? Also, why pass in copies of read-only strings?!
avoid unnecesary allocations:

string factor1 = perm.substr(0, 1);
string factor2 = perm.substr(1, 3);
string product = perm.substr(4, 5);

is gonna do a lot of allocations. Probably more than you'd think. At least, reuse factor1,factor2 and product capacities? (My sample below makes them static)

  Edit Squeezing a few more drops out:

avoiding strings in more places avoids the temps from perm.substr(). Now I just directly assign by indices:

    factor1.assign(perm.begin()+0, perm.begin()+1);
    factor2.assign(perm.begin()+1, perm.begin()+4);
    product.assign(perm.begin()+4, perm.begin()+9);

using unordered_set seems to shave off milliseconds on average :)

Quick performance comparison (g++ -std=c++11 -march=native -O3`) shows the time taken goes down from ~1.036s to ~0.116s.

So, roughly 8.9x speed effectively.

Full code:

#include <iostream>
#include <string>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <sstream>

// store the products, a set is ideal because of the HINT:
std::unordered_set<unsigned> products;

/**
 * Insert to products if string arguments is a proper product
 */
void insert_if_product(std::string const& factor1, std::string const& factor2, std::string const& product) {
    auto p = std::stoul(product);
    if (std::stoul(factor1, nullptr, 10) * std::stoul(factor2, nullptr, 10) == p) {
        products.insert(p);
    }
}

/**
 * magnitudes needs to add up: I'm checking
 * 9 digits total
 * m1 * m3 = m5
 * m1 * m4 = m4
 * m2 * m3 = m4
 * Is this all?
 *
 * @param check this permutation
 */

void check_products(std::string const& perm)
{
    static std::string factor1, factor2, product;
    // all permutations are coming from perm, so no need to perm stuff here.
    factor1.assign(perm.begin()+0, perm.begin()+1);
    factor2.assign(perm.begin()+1, perm.begin()+4);
    product.assign(perm.begin()+4, perm.begin()+9);

    insert_if_product(factor1, factor2, product);

//  factor1.assign(perm.begin()+0, perm.begin()+1);
    factor2.assign(perm.begin()+1, perm.begin()+5);
    product.assign(perm.begin()+5, perm.begin()+9);

    insert_if_product(factor1, factor2, product);

    factor1.assign(perm.begin()+0, perm.begin()+2);
    factor2.assign(perm.begin()+2, perm.begin()+5);
//  product.assign(perm.begin()+5, perm.begin()+9);

    insert_if_product(factor1, factor2, product);
}

int main() {
    std::string s = "123456789";

    do {
        check_products(s);
    } while(std::next_permutation(std::begin(s), std::end(s)));

    std::cout << "Sum:" << std::accumulate(products.begin(), products.end(), 0u) << "\n";
}


Using custom negotiator and custom formatter in Web API 2

ProductFormatter

The WriteToStreamAsync() method could be improved by using the using keyword with the StreamWriter. By using using the flushing and disposing of the stream is done automatically.

Having a string.Format() like it is used together with the string.Join() is suboptimal. You should better add the product details to the List<string> and let the string.Join() to the work.

Implementing this points will lead to

public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
    List<string> productStrings = new List<string>();
    IEnumerable<Product> products = value is Product ? new Product[] { (Product)value } : (IEnumerable<Product>)value;
    foreach (Product product in products)
    {
        productStrings.Add(product.ProductID);
        productStrings.Add(product.Name);
        productStrings.Add(product.Price);
    }

    using (StreamWriter writer = new StreamWriter(writeStream))
    {
        await writer.WriteAsync(string.Join(",", productStrings));
    }
}

You should also take into account that object value could be null. Assuming that it is an IEnumerable<Product> if it isn't a Product type is suboptimal.

CustomNegotiator

The retrieving of the formatter should be extracted to a separate method otherwise the Negotiate() method would do to many things and would violate the single responsibility principle.

The way how you are doing the search is ok, but could be improved by extracting the "application/x.product" to a class constant.

This if

if (request.Headers.UserAgent.Where(x => x.Product != null
&& x.Product.Name.ToLower().Equals("chrome")).Count() > 0 && formatter != null)

should be improved by first checking if formatter != null and to use Any() instead of Count() > 0. By using Count() > 0 all of the items will be iterated over and counted. Using Any() will iterate only until any item is found for which the condition is true. Instead of x.Product.Name.ToLower().Equals("chrome") you should use the overloaded Equals() method which takes a StringComparision enum as second parameter. This buyes you two things. The first is the call to ToLower() isn't needed anymore and the second is that your code will pass the turkey test.

Implementing this points will lead to

private const string mediaType = "application/x.product";
private MediaTypeFormatter FindFormatter(IEnumerable<MediaTypeFormatter> formatters)
{

    foreach (var formatter in formatters)
    {
        var foundMediaType = formatter.SupportedMediaTypes.Where(mt => mt.MediaType == mediaType).SingleOrDefault();
        if (foundMediaType != null)
        {
            return formatter;
        }
    }

    return null;
}

public class CustomNegotiator : DefaultContentNegotiator
{
    public override ContentNegotiationResult Negotiate(Type type,
                HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
    {

        var formatter = FindFormatter(formatters);

        if (formatter != null && request.Headers.UserAgent.Any(x => x.Product != null
                                 && x.Product.Name.Equals("chrome", StringComparison.OrdinalIgnoreCase)))
        {
            // if client is chrome then return superproduct and use custom formatter for it
            return new ContentNegotiationResult(formatter,
                            new MediaTypeHeaderValue(mediaType));
        }
        else
        {
            return base.Negotiate(type, request, formatters);
        }
    }
}


Error-handling / Self-Validating mechanism

isValid Method
If you have a validator, I would expect a method to check if it is valid.
If you add an isValid method, you would get rid of the errorInfo == null check, which isn't a good idea. It exposes how the validator works internally, and relies on this never changing.
errorMessage Type
Why is your error message a String? You are creating a new StringBuffer and calling toString every time an error is appended. Just make errorMessage a StringBuffer or StringBuilder and call toString when the error message is retrieved (which should be done via a getter, not direct access).
Naming
setErrorMessage: What this actually does is appendErrorMessage
Spacing
I know it's knit-picking, but please follow the general conventions regarding spacing. Before and after ?, :, and + should be a space.
General Idea
I'm not too sure what this is good for (maybe I'm missing something?). It doesn't seem like the SelfValidator class can be reused for any other data. The three fields and their types are hardcoded, as is the validation mechanism (no empty string and no null allowed). Couldn't all your code be replaced with something like this:
  private boolean isValid = true;

  public MyClass(String object1, String object2, int value1) {
    super();
    if (object1 == null || object2 == null || object1.equals("") || object2.equals("")) {
        this.isValid = false;
    }
  }

  public isValid() {
    return isValid;
  }

It seems just as flexible as your approach, but is easier to read.


How do I add memoization to this problem?

Finally my memoization technique worked and the result appears in less than a sec

    cache = []
for i in range(20):
    cache.append([])
    for j in range(20):
        cache[i].append(0)

def step(i,j):
    if(i==2 or j==2):
        return 1
    if(cache[i][j]>0):
        return cache[i][j]
    cache[i][j] = step(i+1,j)+step(i,j+1)
    return cache[i][j]
print step(0,0)

Another optimization I have added (since step(i,j) is same as step(j,i))

    cache = []
for i in range(20):
    cache.append([])
    for j in range(20):
        cache[i].append(0)

def step(i,j):
    if(i==20 or j==20):
        return 1
    if(cache[i][j]>0):
        return cache[i][j]
    cache[i][j] = step(i+1,j)+step(i,j+1)
    cache[j][i] = cache[i][j]
    return cache[i][j]
print step(0,0)


Recursively walking a tree to build up a new one

It can indeed be factored as a reduce, but I don't know if the result is "better".

So, to anyone who still has this problem so long after the question was asked, and god knows I hated Backbone for the lack of data tree-spanning Model and Collection classes, here is the treeReduce function, analogous to Array.prototype.reduceRight but for trees, first written in a simple fashion:

Assuming that each tree object has a value property (of type a which may be anything) and a children property which is an array of child tree objects,

Assuming that f :: a -> [b] -> b in Haskell notation (i.e. to an element of type a and an array of elements of type b, f associates another b-typed element),

Assuming that ini has type [b],

function treeReduce(tree, f, ini)
{
    // If we're at a leaf, use 'ini'
    if (tree.children.length === 0) {
        return f(tree.value, ini);
    }

    // Else, recursion!
    return f(tree.value, children.map(function (child) {
        return treeReduce(child, f, ini);
    }));
}

For your problem, we have to adapt treeReduce to use _.map and to not assume that the tree has the value and children properties, etc:

// Using this, we can customize the way to get the value and children of a tree
// in our treeReduce function
function treeReduceFactory(getValue, getChildren)
{
    return function customTreeReduce(tree, f, ini)
    {
        var children = getChildren(tree);
        if (children.length === 0) {
            return f(getRoot(tree), ini);
        }

        return f(getValue(tree), _.map(children, function (child) {
            return customTreeReduce(child, f, ini);
        }));
    };
}

// Our treeReduce is defined like this:
var treeReduceForBackbone = treeReduceFactory(
    // There really is no such thing as getting the 'value' of the current node
    // in our case
    function (data) {
        return data;
    },

    // How to get the "children" of something that can be an array or an object?
    function (data) {
        // If data is an array then it is itself its own children (??!)
        if (_.isArray(data)) {
            return data;
        }
        // If it's an object then its children are in the values
        if (_.isObject(data) && !_.isDate(data)) {
            return _.map(data, function (val, key) { return [key, val]; });
        }
        // If it's neither of those, it doesn't have children
        return [];
    }
);

// Finally, we define 'modelify', and indeed it looks somewhat more elegant
exports.modelify = function (data) {
    return treeReduceForBackbone(
        data,

        function (data, modelifiedDataArray) {
            if (_.isArray(data)) {
                return new Backbone.Collection(modelifiedDataArray);
            }
            if (_.isObject(data) && !_.isDate(data)) {
                return new Backbone.Model(_.object(modelifiedDataArray));
            }
            return data;
        },

        []
    );
};

And this is where we realize that because our data tree does not have a coherent interface throughout (different ways to get the children depending on the type of the node in the tree, object or array), we end up repeating checks in the node children getter and in the f function. This could obviously be fixed with yet another modification to treeReduce, but sincerely at this point I like your initial solution better.

To note, though: an iterative version of your function, as opposed to recursive, would certainly be faster, and may counterbalance the lack of readability factor in your choice of implementation.


Basic JavaScript template engine using replace, match and RegExp

RegEx

[ ]* vs \s*

[ ]* which is same as *(space followed by a star) matches zero or more occurrences of space. This is not flexible as it only allows users to use spaces. If user use tabs, this regex will fail. Use \s*, which matches all the space characters.

Quoting from http://www.regular-expressions.info/shorthand.html

  \s stands for "whitespace character". Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a line break, or a form feed. Most flavors also include the vertical tab

RegExp Constructor vs RegEx Literal

new RegExp() is used to create a new regex. This form of regex accepts a string as the first argument and returns new regex. This is used when creating regex from a variable. Since this uses string, the backslash is used to escape following character. This will produce unexpected results when regex itself contains a backslash. Example, new RegExp('\s') will return /s/. When using a backslash in this form, they need to be escaped new RegExp('\\s'). This is not necessarily difficult but requires to take care of escaping.

Passing regex literal syntax to the constructor is same as literal syntax to create regex. So, new RegExp(/({{=[^}]*}})/g) is same as /({{=[^}]*}})/g.

Mistake

The regex for object /{{\s*([^}.]*)\s*}}/g doesn't work for all cases. [^{.]* means to match anything which is not { AND .. If the key of object contains ., this regex will fail. Check this demo. Removing . solves this problem.

Not a mistake, but a validation. Using + quantifier instead of *. * says, match zero or more of the previous pattern. For example, {{=[^}]*}} will match {{=}} which you might not want to match and process.

Better use of capturing groups

The regex /({{=[^}]*}})/g will match the string starting with {{= to the }} literal and put the complete string in first captured group. Then inside replace, {{= and }} are again replaced

token.replace("{{=", "").replace("}}", "")

This can be improved by removing those characters from capture group.

/{{=([^}]*)}}/g

This regex will match only string contained in {{= and }}. Thus, removing the need of those two replace statements. The same thing can be used for the other two regexes.

With above improvements, the regex will be as below:

/{{=([^}]+)}}/g
/{{\s*([^}]+)\s*}}/g
/{{\s*(\d+)\s*}}/g

If the expressions do not contain spaces in between them, [^}]+ can be replaced by \S+(one or more non-space characters).

JavaScript

match => map => n * replace

In the three functions, you're first using match to get the matches then iterating over it and using replace inside it. This is not at all necessary. Simple replace is sufficient in this case.

Rewritten evaluateString

// Note: I've removed `call()` here
return string.replace(/{{=([^}]*)}}/g, function(m, $1) {
    return eval($1);
});

$1 is the actual expression inside delimiters here. Similarly, other two methods can be written.

Other small improvements:

Naming: something, string.
Using _ prefix when variables are not local/private to the method: _tokensToReplace, _values, _array
Missing strict mode: What does “use strict” do in JavaScript, and what is the reasoning behind it?
Really need those comments? Guessing a number, but comments concerning
Use === to compare variables. Which equals operator (== vs ===) should be used in JavaScript comparisons?
For default values, || can be used instead of ternary.
The default value for _array should be [] instead of {}.

Demo:

(function() {
  this.amirTemplateEngine = function() {
    var self = this;

    self.evaluateString = function(string, options) {
      return string.replace(/{{=([^}]*)}}/g, function(m, $1) {
        return eval($1);
      });
    };

    self.replaceGivenObject = function(string, options) {
      var _values = options && options.values || {};

      return string.replace(/{{\s*([^}]*)\s*}}/g, function(m, $1) {
        return _values[$1.trim()];
      });
    };

    self.replaceGivenArray = function(string, options) {
      var _array = options && options.array || [];

      return string.replace(/{{\s*(\d+)\s*}}/g, function(m, $1) {
        return _array[$1];
      });
    };

    self.format = function(string, options) {
      string = self.evaluateString(string, options);
      string = self.replaceGivenArray(string, options);
      string = self.replaceGivenObject(string, options);

      return string;
    };

    return self;
  };
})();

(function() {
  var self = this;
  something = "something else!";
  var template = "\

{{0}} {{1}} {{2}}
\

{{= 4 > 0 ? 'good' : 'bad'}}
\

{{= something }}
\

{{name}}
\
                ";

  var result = "\

seyed amir hossein
\

good
\

something else!
\

amir
\
                ";

  var templateObj = new amirTemplateEngine();

  testResult = templateObj.format(template, {
    array: ["seyed", "amir", "hossein"],
    values: {
      name: "amir"
    },
    context: self
  }) == result;

  console.log("Test is" + (testResult ? "" : " NOT") + " passing!");
})();

My Take I'd use constructor pattern with overridden toString method and single regex for replacement.

function MyTemplate(str, config) {
  this.str = str;
  this.config = config;
}
MyTemplate.prototype.toString = function() {
  var object = this.config && this.config.values || {};
  var array = this.config && this.config.array || [];

  return this.str
    .replace(/{{(=?.*?)}}/g, function(m, $1) {
      $1 = $1.trim();

      return $1.startsWith('=') ? eval($1.substr(1)) :
        /^\d+$/.test($1) ? array[$1] : object[$1];
    });
};

(function() {
  var self = this;
  something = "something else!";
  var template = `
{{0}} {{1}} {{2}}

{{= 4 > 0 ? 'good' : 'bad'}}

{{= something }}

{{name}}
`;

  var result = `
seyed amir hossein

good

something else!

amir
`;

  var templateObj = new MyTemplate(template, {
    array: ["seyed", "amir", "hossein"],
    values: {
      name: "amir"
    },
    context: self
  });

  var testResult = templateObj.toString() === result;
  console.log("Test is" + (testResult ? "" : " NOT") + " passing!");
})();


Merge sort implementation with various improvements

Mandatory stability note: the sequence

    if(array[left_index] < array[right_index]){
        temp_holder[temp_index++] = array[left_index++];
    } else {
        temp_holder[temp_index++] = array[right_index++];
    }

causes loss of stability (equal elements are merged in the wrong order).
The code still does unnecessary copying (from tmp back to array). It is unnecessary because it can be avoided. Allocate a temporary array once, then

    merge_sort subrange 0 of arr into corresponding subrange of tmp
    merge_sort subrange 1 of arr into corresponding subrange of tmp
    merge subranges from tmp to arr

The insertion sort implementation is suboptimal. Testing two conditions in

    while(before >= left && array[before] > temp)

can be avoided. Take a look at the Alex Stepanov's technique (he is talking about quicksort, but the first 4 methods, which you are are only interested in, are equally applicable to your case).
The algorithms of this kind generally look better at the semi-open ranges. Try to rewrite the code with the assumption that highBound does not belong to the range.


REST API for random number generation using Falcon

This is a small code, but there are some improvements to make:

useless copy-paste, what if you had 5 conditions?:

if 'min' not in req.params:
    raise falcon.HTTPMissingParam('min')

if 'max' not in req.params:
    raise falcon.HTTPMissingParam('max')

when you can do:

for c in ['min','max']:
  if c not in req.params:
      raise falcon.HTTPMissingParam(c)

don't test with == False

if min_n.isnumeric() ==  False:

should be

    if not min_n.isnumeric():


The documentation for sort, to pick a common example, says:

You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion).

One benefit of returning the object is to chain calls. If consumers of your code expect to be able to chain calls, perhaps returning the object makes sense. Otherwise I would say the more common behavior in Python is to return None from functions that mutate their arguments.
(Other languages may have other conventions.)


Graph implementation to be used for finding Cycles, Paths, closest path between two nodes, etc

That depends on what is good in some sense. It's a pretty standard adjacency list implementation, and it's nothing wrong with that. Whether it's good depends on what query you gonna ask the data structure. If doing path search or minimal spanning tree for sparse graph that is good. If you want to do some clustering, then maybe an adjacency matrix is better.

On the API level, I like that chaining add methods. It's nice and easy to use. Storing pointer to aliases avoided the problem of memory leakage, but it makes the programmer feel a bit silly to declare a variable for each node, with only one character in it. What if the number of nodes dynamically grows, which is one of the strength of using an adjacency list? Why can't I do like graph.AddNode('a')? And add child by graph.get('a').AddChild('b') or something.

Also if the node local variables goes out of scope, the graph must die or in danger of facing segmentation fault, or even some security issues. Not very flexible.


Definitely not optimal as you are holding locks longer than you need too.

   boost::unique_lock<boost::mutex> lk(_frameCacheMutex);

   /// Here create the data for cache...

   // You are creating data here.
   // But you should not be interacting with the cache here.
   // So why are you holding a lock?

   // You should only hold a lock while you are trying to update a shared resource.

   _frames_cache.push(data);

So I would expect it to look like this:

   /// Here create the data for cache...

   boost::unique_lock<boost::mutex> lk(_frameCacheMutex);
   _frames_cache.push(data);

As a side note.
Using _ as a prefix on identifiers in C++ user applications is frowned upon (as in _frames_cache). Do you know the exact rules on when identifiers are reserved? You did not break them; but I would still advise against it because you don't know the exact rules.

This looks wrong:

while (0 == _frames_cache.size()) {
       //tell Producer to push data into cache
     _fill_cache_wait_cond.notify_one();
      //wait for the data to arrive(will be signaled by worker thread)
     _get_frame_wait_cond.wait(lk);

}

It is in a while loop because the thread was woken early but another thread has grabbed the work. So I would not expect you notify_one at this point. Also You are notifying the producer when the cache is empty. I would rather notify the producer as soon as there is any space available. So each time you grab something notify the producer (because if you take something then there is space available.

  while (0 == _frames_cache.size()) {
      //wait for the data to arrive(will be signaled by worker thread)
     _get_frame_wait_cond.wait(lk);
  }
  //tell Producer to push data into cache
  // We are about to take one item so there will be space available,
  _fill_cache_wait_cond.notify_one();

Your usage of wait() is a bit cumbersome. With the new lambda expressions you can express the wait and loop in a single expression.

  _get_frame_wait_cond.wait(lk, [this](){return 0 != _frames_cache.size();});

You are using Yoda Conditionals.

  while( 0 == _frames_cache.size() ) {}

This is a bit dated. And does not provide any real protection but also imposes a mental tax on the reader of your code as it is not the natural way to express the condition.

You get much better protection by making the compiler detect the problems you are looking for.

 // You are trying to solve this problem
 while( _frames_cache.size() = 0 ) {}
                       //   ^^^  accidental assignment.

Turn you compiler warning level up (it should already be at the highest level). And treat all warnings as errors (as they are logical errors in your thinking of how the code works). Do that and this is no loger an issue as it is a compiler error detected for you and the reader of your code gets readable code.

Your indentation and blank lines in your code make it look real messy. Tidy it up.

Some (most) of your comments are usless and parat what the code says.

  // notify worker thread to continue caching
  _fill_cache_wait_cond.notify_one();

When you write a comment it should be a description of WHY or an explanation of some complex algorithm that you are trying to implement. Writing a comment like the above one is actually worse than not writing a comment because now you have to maintain the comment to be the same as the code (and I can already read the code and see what it is doing I don't need the comment to say the same thing).

You also seem to be using two different naming conventions for your identifiers:

 _frames_cache         http://en.wikipedia.org/wiki/Snake_case
 _frameCacheMutex      http://en.wikipedia.org/wiki/CamelCase

Personally I prefer CamelCase but am not that ground in. Follow the standards of the place you work (but pick one).

I use CamelCase. But a leading uppercase character indicates a User Type while a leading lower case character indicates a variable/method/function name (something I can take the address of). I don't use special prefixes to mark members (I just name the members very well so there usage is obvious).

Cleaned up code:

Consumer

// Consumer: Get one item from the cache.
//           If the cache is empty then wait until
//           data is available.
uint8_t* Worker::GetFrame() {

    std::unique_lock<std::mutex> lk(frameCacheMutex);
    getFrameWaitCond.wait(lk, [this](){return framesCache.size() != 0;});

    uint8_t* fr = framesCache.front();
    framesCache.pop();

    fillCacheWaitCond.notify_one();
    return fr;
}

Producer

// Producer: run in infinite loop
//           Generate the data.
//           Get the lock and wait for space to be available before
//           continuing. This way you pre generate the data and
//           can push it as soon as there is space.
void Worker::operator () () {

    while (isRunning) {

       /// Here create the data for cache...

       std::unique_lock<std::mutex> lk(frameCacheMutex);
       fillCacheWaitCond.wait(lk, [this]{return framesCache.size() != cacheMaxSize;});

       framesCache.push(data);

       getFrameWaitCond.notify_one();
    }
}


Using a final class for string constants

There won't be any GC overhead since there won't be any instantiated instances to collect.

I think there's a small overhead by accessing a class' static field rather than an in-scope variable ; however, I would consider it largely worth the improved readability/maintainability.

I guess you could also argue you'll use up a little bit more of your permGen / Meta space, but I've never heard it be a consequent problem.


I looked through your code and it is a valid solution, but you could reduce your code base by better leveraging the functions that JavaScript already provides, such as Array.prototype.indexOf().

For example, instead of building a new class-like-function (Element) to track the appearance of a certain index, I simply made a deep copy of the the initial array and parsed it with indexOf().

Moreover, in your code, when you first declare this.objects = [], this actually refers to the global scope (window object). As you can see, you are calling pairwise without building a new instance (new keyword). In this case, thus the this keyword is bound to the global window object.

Please find below my take on it:

function pairwise(arr, arg) {

  var result = 0,
      newArr = [],
      //Used to hold the indices that we have already used to form our sum
      indices = [];

  //Loop through arr and create a deep copy of it in newArr
  for(var k = 0; k < arr.length; k++) {
    newArr.push(arr[k]);
  }

  //Loop through arr
  for(var i = 0; i < arr.length; i++) {

    //Loop through newArr
    for(var j = 0; j < newArr.length; j++) {
      //Since we want to add different elements of the array, we want to avoid adding the same element
      if(i !== j) {
        //If the sum of two elements is equal to arg AND the indices that we have in i and j are not part of the indices array
        //Indices array is used to hold the already used indices, thus ensuring the accurate parsing of the parameters
        if(arr[i] + newArr[j] === arg && indices.indexOf(i) === -1 && indices.indexOf(j) === -1) {
          //Sum the indices up
          result += i + j;
          //Push the indices in the indices array in order to not use them in further iterations
          indices.push(i, j);
        }
      }
    }
  }

  return result;
}

pairwise([1,4,2,3,0,5], 7);


C++ class for aligning objects on the stack

Silent bug: Bad move constructor

Your move constructor will perform a copy because your parameter is aligned_type const&&; you cannot move from a const value because moving implies modifying what you're moving from. Simply change the signature to:

aligned(aligned_type &&other);
//      ^^^^^^^^^^^^^^^ no more const

Bug: Bad dereference operator

Your dereference operator is defined like so:

T operator*() const {
// we don't really want to copy the value out every single time we deref, do we?
  return *ptr_;
}

It simply returns T, it should return T&. Note that this is a source of a bug in your code. You end up creating a temporary when you assign by using the dereference operator. This can (and did on my system) result on a crash due to the memory access violation.

Only align to alignments that are powers of 2.

Your test code aligns to 7 and 13.

From [basic.align] in the C++ Standard (emphasis mine):

  Alignments are represented as values of the type std::size_t. Valid
  alignments include only those values returned by an alignof expression
  for the fundamental types plus an additional implementation-defined
  set of values, which may be empty. Every alignment value shall be a
  non-negative integral power of two.

T* aligned_position();

This function is used in only one place. Unless you've got plans of using it elsewhere, I recommend erasing it and simply putting the code at the relevant location.

You don't have to index into the first element to get the address. You can use the fact that arrays decay to pointers.

uint8_t *p = storage_; // equivalent to uint8_t *p = &storage_[0];

However, there is a faster way than looping in order to align an address to some boundary:

auto aligned_position() const noexcept
{
    return reinterpret_cast<T*>(
        (reinterpret_cast<std::uintptr_t>(&storage_) + Align - 1) & ~(Align - 1));
}

Do we really need aligned_position(); and ptr_?

No. Here is an alternative solution:

You currently allocate Align - 1 + sizeof(T) bytes. This is wasteful. You can use exactly as much space as you need by declaring your storage any of these two ways:

alignas(Align) std::uint8_t storage_[sizeof(T)];
std::aligned_storage_t<sizeof(T), Align> storage_; // from the <type_traits> header

Option 1 might be preferable because option 2 is not guaranteed to align to your requested boundary if Align > alignof(std::max_align_t). In such a case, it will depend on the implementation of the standard library you're using; the Microsoft implementation does this.

Before: sizeof(aligned<8, double>) == 20

After: sizeof(aligned<8, double>) == 16

Wait, we're not done yet. We shouldn't align to the specified alignment blindly either because we can then specify an alignment of 4 for a double, which requires 8. Unaligned data like that becomes very slow to access (two reads instead of one) or can simply not work (crash) in certain systems.

The fix:

alignas(Align < alignof(T) ? alignof(T) : Align) std::uint8_t storage_[sizeof(T)];

Note that we no longer need ptr_ because the first byte of storage_ now corresponds to a properly aligned byte for our type.

Before: sizeof(aligned<8, double>) == 20

After: sizeof(aligned<8, double>) == 8

We save quite a bit of space. In fact, with this solution, your class takes no more space than a T when aligned to alignof(T). You have to replace all uses of ptr_ with an appropriate statement; I recommend replacing all instances of ptr_ with a call to get(). This call will almost surely be optimized away.

Provide non-const versions of your accessor/modifier functions.

You want your type to be usable in non-const contexts, so provide non-const overloads for your operations. For example, define get() like so:

T* get() noexcept {
    return reinterpret_cast<T*>(&storage_);
}

T const* get() const noexcept {
    return reinterpret_cast<T const*>(&storage_);
}

You can provide this functionality wherever needed.

Final thoughts:

The class is basically a wrapper around a aligned_storage<> like storage. However, it is a good learning experience I suppose.
I've left out basic language features advice such as declaring functions constexpr or giving them exceptions specifications through type traits. Please look into that yourself.


Especially in such simple cases you don't want to create a repository over an EF (I assume it's EF -- but the same goes for Linq2SQL) context.

The DbContext basically is an implementation of the repository pattern. Your repository on top just creates another layer of complexity without actually providing any serious benefit.

In more complicated cases wrapping the DbContext with a specific interface may make sense of course.


Most of your code can be greatly reduced.

Doing string addition is often a bad idea in Python, especially if you are doing it in a loop. Also note that a + "" == a for any string a. I would replace your mix of global code and the word_processor function with this short function:

import string

WHITELIST = set(string.ascii_letters + string.digits + string.whitespace)

def get_words(file_name):
    with open(file_name) as f:
        for line in f:
            line = "".join(c for c in line.casefold() if c in WHITELIST)
            yield from line.split()

This filters each line of the file to only contain ASCII letters and whitespace and splits it by whitespace afterwards (the default behavior of str.split). The yield from effectively flattens the output into a stream of words (the whole function is a generator, so you can consume the output one at a time without keeping the whole list in memory). It also uses the with keyword to ensure your files are closed, even in the event of an exception interrupting the program. I used str.casefold instead of str.lower, as recommended by @AJNeufeld in the comments.

You should put the actual code into a function as well. I would call it similarity, since it does not actually measure distance, but similarity (from 0 to 100). For this you can use collections.Counter instead of using list.count repeatedly (each of which is \$\mathcal{O}(n)\$).

from collections import Counter
from math import sqrt

def similarity(words1, words2):
    words1, words2 = Counter(words1), Counter(words2)
    dot = sum(words1[k] * words2[k] for k in words1.keys() & words2.keys())
    norm1 = sqrt(sum(v**2 for v in words1.values()))
    norm2 = sqrt(sum(v**2 for v in words2.values()))
    return dot / (norm1 * norm2)

Here I used the fact that Counter can take any iterable (like the output of get_words) and counts how often each item occurs (it returns a kind of dictionary). Also, dictionary keys behave like sets, so we can do a set intersection so we don't have to check for every key if it is also in the second words counter. I would also leave scaling the similarity to the caller.

Use it within a if __name__ == "__main__": guard to allow importing from the module. You might want to add a simple CLI interface with sys.argv (or do it properly and use argparse if you want more functionality). Throw in a f-string to make formatting the output to the user easier (and make it a percent with not too many digits shown).

import sys

if __name__ == "__main__":
    file1, file2 = sys.argv[1:3]
    sim = similarity(get_words(file1), get_words(file2))
    print(f"Similarity of {file1} and {file2}: {sim:.2%}")

Usage:

python3 similarity.py file.txt file_old.txt
# Similarity of file.txt and file_old.txt: 92.19%

For these two small files (21KiB), your code takes 0.3s, whereas my code only takes 0.05s on my machine.


Loading site configuration from ini file

What kind of things are you looking to improve? Your solution looks pretty straightforward. The only problem with an ini file is that ColdFusion can't instantly/natively parse it. Whereas XML/JSON can be parsed directly into a Coldfusion Struct.

<cfscript>
public struct function loadini( required string configFile) {
    var stResult = {};
    var iniFilePath = "#GetDirectoryFromPath(GetBaseTemplatePath())##arguments.configfile#";
    var stSection = getProfileSections(iniFilePath);

    // loop over the sections
     for (section in stSection) {
        // loop over the list of variables in the ini file
        for (var i=0;i<=listLen(stSection[section]);i++) {
            // result.section.variable = value
            stResult[section][listGetAt(stSection[section],i)] = GetProfileString(iniFilePath, section, listGetAt(stSection[section],i) ) ;
        }
     }
    return stResult;
}
</cfscript>

<cfdump var="#loadini('test.ini')#">


I think you're overcomplicating this a bit. Something like delete certainly shouldn't need reverse or ++ to implement.

For the initial list, there are two cases - it either contains an element, or is empty. That much exists in your code. The empty case is simple, just return the empty list:

delete' :: (Eq a) => a -> [a] -> [a]
delete' y [] = []

Ok, so what about when the list is not empty. Well, in that case, we can simply think about it as follows: if the next element is equal to the element we want to remove, then remove it and return the rest of the list. Otherwise, append the next element and remove the first occurrence from the tail of the list. In code, this looks like:

delete' y (x:xs) = if x == y then xs else x : delete' y xs


Finding all neighbors of any given element in a matrix like structure

You could use a 2-dimensional loop to iterate over neighbors as follows:

public IEnumerable<Coordinates> GetNeighbors(int numberOfRows, int numberOfColumns)
{
    var canIncreaseRow = Row < numberOfRows - 1;
    var canIncreaseColumn = Column < numberOfColumns - 1;
    var canDecreaseRow = Row > 0;
    var canDecreaseColumn = Column > 0;

    var maxRow = canIncreaseRow ? Row + 1 : Row;
    var minRow = canDecreaseRow ? Row - 1 : Row;
    var maxColumn = canIncreaseColumn ? Column + 1 : Column;
    var minColumn = canDecreaseColumn ? Column - 1 : Column;

    for (int row = minRow; row <= maxRow; row++)
    {
        for (int column = minColumn; column <= maxColumn; column++)
        {
            if (row != Row || column != Column)
            {
                yield return new Coordinates(row, column);
            }
        }
    }
}


Calculate last month, last 3 months, and last 6 months from today

Try the DateTime class. In combination with the DateInterval class you can do something like this:

$until = new DateTime();
$interval = new DateInterval('P2M');//2 months
$from = $until->sub($interval);
echo 'from' . $from->format('Y-m-d') . 'until' . $until->format('Y-m-d');

Also, you have to set the $until variable only once, before the switch statement.


I am a bit late, I hope the answer is still useful. Some notes:

First, my tradicional advice: don't use imperative programming! I mean, it's ok if you are writing assembler or C, but in a language like Ruby you're squandering its potential. Try to learn to program in functional style, favouring the good old math expressions (with its abstractions, immutability, higher-order functions, modulatization and many other cool things).
I'd use regular expressions to get the rhyming substring of each verse, no custom code can beat their compactness and expression power.
There are two ways of solving the problem, one is traversing the verses only once, folding the verses into an output. The second one is more modular, traverse the verses to build the intermediate data structures needed to calculate the solution. This second approach is, in this case, less verbose.

I'd write (second approach):

def rhyme_scheme(verses)
  ending_regexp = /((?:[aeiou]|\By\B)+[^aeiou]*)$/
  endings = verses.map { |verse| verse.strip.downcase[ending_regexp, 1] }
  ending_scheme_pairs = endings.uniq.compact.zip([*"a".."z", *"A".."Z"])
  schemes = ending_scheme_pairs.to_h.merge(nil => " ")
  schemes.values_at(*endings).join
end


All in all this code does, what you want it to do and you separate responsibility by splitting the code in meaningful functions.

I don't like that CheckPalindrome(...) expects the input to be in a certain format (case). In other words: it should do the preparation of the originalStr by it self and check for invalid input:

 static bool CheckPalindrome(string orginalStr)
 {
    if (string.IsNullOrEmpty(originalStr)) return false;

    originalStr = originalStr.ToLower();

    //call the string reverse method
    var reversedStr = ReverseString(orginalStr);

    if (reversedStr.Equals(orginalStr))
        return true;

    return false;
 }

The palindrome check by comparing the original string with its reversed string is rather inefficient. Instead you can compare each char from the start of the string with the same position from the end of the string. You then only have to iterate through the half of it:

static bool IsPalindrome(string word)
{
  if (string.IsNullOrWhiteSpace(word)) return false;

  word = word.ToLower();

  for (int i = 0; i < word.Length / 2; i++)
  {
    if (word[i] != word[word.Length - i - 1])
      return false;
  }

  return true;
}

EDIT

If you go multilingual, you may find this approach useful:

static bool IsPalindrome(string word)
{
  if (string.IsNullOrEmpty(word)) return false;

  StringInfo stringInfo = new StringInfo(word.ToLower());
  int length = stringInfo.LengthInTextElements;

  for (int i = 0; i < length / 2; i++)
  {
    if (stringInfo.SubstringByTextElements(i, 1) != stringInfo.SubstringByTextElements(length - i - 1, 1))
      return false;
  }

  return true;
}

Disclaimer: I have only tested it on Latin strings, so don't hang me if...


How to improve my auto-reconnection Python script

I'd move the contents of the script into a main function and then use the if __name__ == '__main__' boilerplate to start it.
I wouldn't use external tools like bash/sed/grep to do additional logic. I'd implement that logic in python.
I'd use the communicate method for POpen objects rather then reading the stdout attribute
Your POpens are all very similiar. I'd write a function that takes a command line executes it and returns the standard output
You check if you are connected in multiple places, write a am_connected() function which returns True or False and use it multiple times
I'd probably write a function for each external command you execute even if they are not repeated because it'll make your code cleaner.


Determining if a given square is a magic square

Answering your first question, yes there is a better way. Efficiency doesn't matter in your case but in this instance the more efficient thing is also easier on the eyes.

The usual idea would be to make a hash set of the elements, then you have O(1) look up of whether you have already inserted an elements, making the task O(n^2).

I'm not that familiar with Java sadly so to answer your second question I just propose the fairly imperative thing of doing everything in one traversal (I think probably it can be done with the functional constructs that Java has), like so.

private static boolean magical(int[][] square) {
    Set<Integer> seenInts = new HashSet<>();
    var leftDiagonalSum = 0;
    var rightDiagonalSum = 0;
    var rowSums = new int[square.length];
    var colSums = new int[square.length];

    for(var i = 0; i < square.length; i++) {
        for(var j = 0; j < square.length; j++) {
            var currentElement = square[i][j];

            seenInts.add(currentElement);
            leftDiagonalSum += (i == j) ? currentElement : 0;
            rightDiagonalSum += (i == square.length - 1 - j) ? currentElement : 0;
            rowSums[i] += currentElement;
            colSums[j] += currentElement;
        }
    }

    Set<Integer> sumSet = new HashSet<>();

    sumSet.add(leftDiagonalSum);
    sumSet.add(rightDiagonalSum);

    for(var i = 0; i < square.length; i++) {
        sumSet.add(rowSums[i]);
        sumSet.add(colSums[i]);
    }

    var noDuplicates = seenInts.size() == square.length * square.length;
    var allSameSums = sumSet.size() == 1;

    return noDuplicates && allSameSums;
}

Edit - While I may not know much Java, there's no reason to specify the implementation of Set used, so the type of seenInts and sumSet can just be Set


Check your if expression in review part:

if (note <= 4 || note >= 1) {
    System.out.println("Thanks for your review.");
}else {
    System.out.println("That's better, we'll do our best the next time");
}

This will always print "Thanks for your review" since whatever the value of note will be always true either for <= 4 or >= 1.

Using an IDE (for example IntelliJ, netbeans, eclipse) helps you mitigate this kind of problems, but it's still better to always review your code.

Confusing result and advise:

I'm not sure if the application is happy that I drank enough water or sad because I only drank 1 bottle.

As stated in your question:

  The objective is to calculate the amount of water one has drunk in a
  day. Depending on the user's input, the app tells him or her if the
  amount of water drunk is great or not.

Then I think you don't need to tell them how many bottles they drink or at least remove the sad face to avoid confusion.

User input problems:

Case 1: What if the user input a letter instead of number? This will happen:

Case 2: What if the user input a negative number? Then this will happen:

As you can see in case 1, this will break your program. Although in case 2 the program will not crash, I think it's impossible to drink negative amount of water.

To solve this kind of issue, you can use try/catch expression. Something like this:

double litre = 0;
boolean isInvalidInput = false;
do {
    try {
        System.out.print("Amount of water your bottle can hold: ");
        // entering amount of water bottle can hold
        litre = sc.nextDouble();
        isInvalidInput = false;
    } catch (InputMismatchException e) {
        isInvalidInput = true;
    }
    sc.nextLine();
} while(isInvalidInput || litre < 0);

If you use the code above, this will be the output:

As you can see, the program will ask the same question repeatedly until the user enters a correct input


Are my methods correct?

That depends on what you want to accomplish. Since you are "learning python and image processing with python", it seems you picked some related methods to explore, which is good. But since your project is called "Classification of breast cancer images with deep learning", and you're not using deep learning, maybe you didn't pick the right methods...

See below for some more concepts.

  Are the outputs correct? Do I find the right areas?

Again, that depends on what your goal is. Do you know what these images represent? If no, then you need to start there. Understand what the image represents, what is relevant in it, and understand what the output of your algorithms will be used for. Then you will be able to answer your question yourself.

It looks like you found mostly the nuclei, the results are quite OK if that is what you're after.

  Did I use the K-Means algorithm correctly?

You've copy-pasted this from the OpenCV tutorial, so it's correct. But it also is a bit redundant, since the values of center are not useful to you in this case. The output label is an image with values 0 and 1, representing background and foreground. You should be able to directly display that (maybe multiply by 255 first).

Also the line where you convert BGR to RGB is redundant, the k-means result will be the same regardless, and you don't need the colors after that.

When dealing with brightfield microscopy, as you are, you might want to consider separating the stains instead of directly using the RGB values. These images are all H&E stain (Hematoxylin and Eosin). These are purple and pink, respectively. Because we're dealing with transmitted light, and the dyes absorb light of specific wavelengths, we see darker pixels of specific colors. The absorption is characterized by the Beer-Lambert law. This law states that the amount of light transmitted (and thus seen by the camera) is given by \$10^{-A}\$, with \$A\$ proportional to the amount of dye. Thus, given a pixel value \$v\$ and the illumination intensity \$v_\text{max}\$ (the whitest area in the image), you can compute \$-log(v/v_\text{max})\$, which is proportional to the amount of dye. You can do this separately for each of the channels R, G and B. Each dye has a different absorption coefficient for each channel. If you know these (you can compute them from the image data), you can now do a linear unmixing (solve a linear set of equations) to derive, for each pixel, the relative amount of Hematoxylin and the relative amount of Eosin at that location on the slide. These two values is what you should be working with.


PHP Dictionary class accepting objects as keys

First, I do have to say that you look like you are re-inventing the wheel. You can get all of that with SplObjectStorage. Since you're using OutOfBoundsException, you're already using the Spl types.

To your specific questions:

It is hard to think of such a situation, but that doesn't mean that it is inconceivable.
While spl_object_hash is not guaranteed unique, it is highly likely that you will run out of memory far before encountering a hash collision. As the documents state: A string that is unique for each currently existing object and is always the same for each object. It is both faster and cheaper than keeping/maintaining your own internal state.
Yes, the internal keys will not be quite as ordered in the internal arrays, but it will only make a substantial difference if you actually have a problem keeping the two arrays synced — basically, if you can get #1 to work consistently and without fail, then unset will not matter here.


Declaring a large number of 2D arrays to be used as 2D graphic sprites

You're trying to store data in code. While that is not bad idea by itself, you shouldn't overuse it and I think that's what you're doing here.

If your data is bitmaps, store them in some bitmap format (BMP or maybe PNG) and then load them into your program from that. As an additional advantage, you will be able to edit your images using normal image editing software (like Paint), instead of having to edit your code.

If you want to keep having your bitmaps in code, you want to decrease the verbosity and you're willing to lose some type-safety, you could encode your bitmaps as strings and then transform them into 2D array using a helper function.

It could look something like:

Color[,] frame1 = FormatMatrix("010 111 010", Color.Red, Color.Blue);

Or even:

Color[,] frame1 = FormatMatrix(@"
010
111
010", Color.Red, Color.Blue);

The helper function would look something like this:

static T[,] FormatMatrix<T>(string format, params T[] values)
{
    var formatParts = format.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);

    T[,] result = new T[formatParts.Length, formatParts[0].Length];

    for (int i = 0; i < formatParts.Length; i++)
    {
        var formatPart = formatParts[i];

        for (int j = 0; j < formatPart.Length; j++)
        {
            if (formatPart[j] >= '0' && formatPart[j] <= '9')
                result[i,j] = values[formatPart[j] - '0'];
            else
                throw new ArgumentException("format");
        }
    }

    return result;
}


How should I pass settings to a module in Perl that also exports symbols?

I would stay away from changing the normal workings of import(). I've never seen a module mix exporting and configuration at the same time (maybe you have, though), so leave those out (options 1 and 3). I think you are right in thinking that option 2 isn't too pretty. That leaves us with none of those options.

I think instead of this you should just allow calling version_ok and version_all_ok with the options hash.

version_ok({ is_string => 1, has_version => 0 });

Clear and standard, nothing odd going on.  From the way it seems like the module is going to be used this isn't a burden on the user (since there will normally only be one call to this in the entire test suite).


You will probably get better performance from the sieve of Eratosthenes. The key difference is that the sieve never performs modulo. Instead it assumes primes, and then crosses them off as you find multiples of primes.

def sieve(n):
   """Return a list of the primes below n."""
   prime = [True] * n
   result = [2]
   append = result.append
   sqrt_n = (int(n ** .5) + 1) | 1    # ensure it's odd
   for p in range(3, sqrt_n, 2):
       if prime[p]:
           append(p)
           prime[p*p::2*p] = [False] * ((n - p*p - 1) // (2*p) + 1)
   for p in range(sqrt_n, n, 2):
       if prime[p]:
           append(p)
   return result


No. This is just a worse Caeser cypher.

steps to break:

Convert each string to an int in the output
Subtract everything from the min output value - ord('A')
Everything is now between 0 and 26
If the message is readable, you are done (this will be true if the message contains an 'a')
Otherwise, add 1 to the each character
After repeating this between 1 and 24 times, the message will be decrypted.


JavaScript implementation of Pascal's Triangle

I see your code is split into 3 phases: Initializing the triangle, calculating the values and then rendering the HTML. You can actually skip the first phase, and create the triangle on-the-fly, as you calculate.

The last phase we can eliminate one loop (the one that loops through cells) by using some array trickery. Since we're just constructing a string, we can use an array's join method to put markup between array elements. Then we prepend and append the missing markup of the resulting string.

Also, I think you should improve on your variable names. a, b, i, j, y and z don't really mean anything. They're "assumend" to be for iteration purposes. However, someone might see y and z as axes in a graph or something, which may be confusing.

And I think it's easier if you calculate the triangle by assuming that the row will always start with a 1. That way, the second item in the current row (essentially the first one we're actually calculating) is in line with the first item of the previous row. That way, summing is a matter of getting the value of the previous row at the same index, and the one to its right. At the end of the row, the "right" value will be undefined (accessing an out of bounds index) which you can easily replace with a 0.

        1
      1 1
    1 2 1
  1 3 3 1
1 4 9 4 1

With that, here's my take on it:

var rows = 10;

function range(n) {
  return Array.apply(null, Array(n)).map(function(_, i) { return i; });
}

// I use range to create a zero-indexed array of things to iterate.
// It's an alternative to using loops.
var pascalsTriangle = range(rows - 1).reduce(function(carry, index) {
  // Using the previous row, we calculate the next row and add to the tree
  carry.push(carry[index].reduce(function(carry, left, index, previousRow) {
    // Determine the "right"
    carry.push(left + (previousRow[index + 1] || 0));
    return carry;
  // Assume the row always starts with 1
  }, [1]));
  return carry;
// Our initial 1
}, [[1]]);

var html = pascalsTriangle.map(function(row) {
  // Instead of looping through a second time, I use `.join` to fill
  // the markup between. Then prepend and append the missing markup.
  return '

' + row.join('

') + '

';
}).join('');

document.getElementById("container").innerHTML += html;
.container {
  display: block;
}
.row {
  text-align: center;
}
.cell {
  border: 1px solid black;
  border-width: 1px 0px 0px 1px;
  display: inline-block;
  width: 40px;
  padding: 10px 0px;
}
.row .cell:last-child {
  border-right-width: 1px;
}
.container .row:last-child .cell {
  border-bottom-width: 1px;
}