Design

you should consider to define the properties of the page in factory, that's where it should be located.

public PageBase GetPage(String pageType) {
    switch (pageType.toUpperCase()) {
        case "A4": return new Page(0.15, 0.25, 0.10, 0.20);
}

Programming

 1. Page

you should not try to subclass the page since it is not required, the only difference between each page are the prices (so far). Therefore you don't need subclasses - it is just a page (not a base Page or anything else)

And even more you should could instanciate the class with all properties during construction (as shown above, dependency injection)

public class Page {

    private final double blackWhiteSinglePageUnitCost;
    private final double colorSinglePageUnitCost;
    private final double blackWhiteDoublePageUnitCost;
    private final double colorDoublePageUnitCost;

    public Page(double bwSingle, double colorSingle, double bwDouble, double colorDouble){
        blackWhiteSinglePageUnitCost= bwSingle;
        colorSinglePageUnitCost= bwDouble;
        blackWhiteDoublePageUnitCost= bwSingle;
        colorDoublePageUnitCost= colorDouble;
    }

what can be kept ist GetCost but should be renamed int getCost() but you can totally skip CalculateUnitPrice, see below

 2. PageType

if you use a certain format you should use Enums to define the Format of the sheet. that would free you from abusing Strings as datatypes

enum PageType {A4, A5, LETTER };

 3. bringing things together

when we use all these hints from above we have to adjust some more code, to make the programm run again

Page.class must be modified we can calculate the price on-the-fly because we already know anything required to calculate the price:

public double getCost(int total, int color, boolean isSingleSided){
    int bw = total - color;
    if(isSingleSided){
        return bw * blackWhiteSinglePageUnitCost + color * colorSinglePageUnitCost ;
    else{
        return bw * blackWhiteDoublePageUnitCost + color * colorDoublePageUnitCost ;
    }

}

PageFactorymust be modified - first the method signature must be java conform, namely getPage not GetPage. then you switch over the enum type instead of an String. That lets you handle invalid inputs.

public Page getPage(PageType pageType) {
    switch (pageType) {
        case PageType.A4:
            return ...;
        case PageType.A5:
            return ...;
        case PageType.LETTER:
            return ...;
    }
}

if you use this in action (in your main method ) it would be finally that appearance:

public class Main {
    public static void Main() {
        PageFactory pageFactory = new PageFactory();
        Page page = pageFactory.getPage(PageType.A4);
        double cost = page.getCost(0,0,false);
    }
}


Finding the largest absolute difference in a list

A more idiomatic and readable solution would be to use itertools.combinations(list, 2) to take all pairs.

max(abs(a) - abs(b) for a, b in itertools.combinations(int_list, 2))

However, that is O(n2). A smarter O(n) solution would be to subtract the minimum absolute value from the maximum absolute value.

absolutes = [abs(elem) for elem in int_list]
print max(absolutes) - min(absolutes)


Recursive Error Handling in Python with a limited amount of tries

I know a possible suggestion is to make error handling more specific, given the requests library myriad exceptions, but I figured that any exception should just be handled by trying X amount of time and then quitting if it doesn't work.

I disagree here. Not just any exception should be handled. It's possible to have typo'd a bug into your code inside the try, and you definitely don't want try masking a bug.

If you check the source (or documentation), you'll see that the requests exceptions all seem to inherit from RequestException. If you really want to handle every possible request exception the same, I would catch the base class RequestException instead. I still don't think this is a good idea though without doing any logging. There may very well be a RequestException that gets thrown at some point which indicates that you accidentally gave the request bad data, not that there was a problem with the request being carried out using good data. I'd check the docs for the methods used and figure out what exact exceptions you want to retry on.

This also doesn't need to be recursion. In this case, nothing bad will likely happen because you have a limit of 20 retries, which isn't enough to exhaust the stack any sane case. If you ever increase that limit up to 1000 though, you may run into real problems.

I think this could be done pretty easily using a while True loop. The first two lines of the function seem to be essentially constants, so they don't need to be recomputed every time. Everything under those lines though can be stuck in a loop.

def getRequest(self, endpoint, max_attempts=20, retry_delay=3):
    baseUrl = self.baseUrl
    url = baseUrl + endpoint

    attempts = 0
    while True:
        if self.expirationT <= datetime.datetime.now():
            self.token, self.expirationT = self.auth(client_id, client_secret)

        try:
            response = requests.get(url, auth=BearerAuth(self.token))
            response.raise_for_status()
            return response

        except requests.RequestException as e:
            attempts += 1

            if attempts < max_attempts:
                time.sleep(retry_delay)

            else:
                raise RuntimeError("Max number of retires met.")

                # Or to preserve in the trace the original problem that caused the error:
                # raise RuntimeError("Max number of retires met.") from e

Things to note:

To retry now, instead of manually recursing, I'm just letting control fall out of the except so that the while can restart again.
Instead of attempts being a parameter, I just made it a local variable which is incremented inside of the except.
I'm throwing a more specialized exception with an informative error message. Throwing the generic Exception makes life more difficult for the users of your code. Ideally, they should be able to pick and choose what exceptions they handle and when. Throwing Exception though forces them to catch your errors. RuntimeError isn't really the best exception here, but I couldn't think of a good built-in one for this purpose. You may want to make a custom exception for this case:

class TooManyRetries(Exception):
    pass

. . .

raise TooManyRetries("Max number of retires met.")

I got rid of the else: pass. That isn't necessary.
You had two "magic numbers": 20 and 3 to mean the max number of attempts and the retry delay. I don't think it's a good idea to have those hard coded though. What if you want to change either at some point? You'd have to edit the code. I made them parameters of the function, defaulting to the values that you had. If you don't specify them, the behavior will be as you had before, but now they can be easily changed as needed.


Feedback on Erlang Lists processing function

Your Insert lambda doesn't use any context so you could rewrite it as a top-level function or move its body to the clause.
And you could use lists:member/2 instead of --.

I'd write first clause like this:

duplicates([Head | Tail], Acc) ->
   NewAcc = case lists:member(Head, Acc) of
               true ->
                  Acc;
               _ ->
                  [Head | Acc]
            end,
   duplicates(Tail, NewAcc);


Performing operations on a processed int vector

Never use using namespace std;.
Some reasons why here
Part 1 is fine other than the error Bogdan Yarema pointed out. I would personally just start at 1 instead thought.

for (int i = 1; i < intVector.size(); i++){

    int k = intVector[i] + intVector[i - 1];
    cout << k << endl;
}

In case the size of the vector is odd and the element in center should be added to himself (as Bogdan Yarema pointed out as swell), it would be better to get the ceiling of intVector.size() / 2

int half = (intVector.size() + 1 )/ 2;
int last = intVector.size() - 1;
for (int i = 0; i < half; i++) {

    int k = intVector[i] + intVector[last - i];
    std::cout << k << std::endl;
}


Scanning a directory and listing contents in an HTML file

Files and Paths

Since Java 7, the recommended way of traversing a file system is to rely on the new Path class and associated Files and Paths helper classes.

Furthermore, since you are on Java 8, there is the Files.list(Path) method that lets you iterate through a given directory as a form of Stream<Path>, so that you can leverage on the stream-processing features.

For example, just to pad each entry in the given directory with
...
, the following snippet does something similar to your for-loop:

List<String> contents;
try {
    // assuming directoryPath is validated as a directory already
    contents = Files.list(directoryPath)
                    .map(v -> "
" + v + "
")
                    .collect(Collectors.toList());
} catch (IOException e) {
    // handle accordingly
}

To write contents out to a file, there's also Files.write(Path, Iterable, OpenOption):

try {
    Files.write(outputPath, contents);
} catch (IOException e) {
    // handle accordingly
}

However, since you need to write the header and 'close' the end of the HTML document, you can rely on the forEach() terminal operation of a Stream:

private static void writeDirectoryFilesToHTML(Path directoryPath,
                                                Path outputPath) throws IOException {
    try (FileWriter target = new FileWriter(outputPath.toFile());
            BufferedWriter buffered = new BufferedWriter(target);
            PrintWriter writer = new PrintWriter(buffered)) {
        writer.write("\n\t\n\t\t
Contents of "
                        + directoryPath.toRealPath()
                        + ":
\n\t\t
\n");
        Files.list(directoryPath)
                .map(v -> "\t\t\t
 " + v + "
")
                .forEach(writer::println);
        writer.write("\t\t
\n\t\n");
    }
}

Here, writer::println is used as a method reference.

HTML output and OS-dependent newlines

You can also consider using some sort of a HTML output library so that you do not have to manually specify "...
...
..." (for example).

You are currently hard-coding your newlines to be \n, so you may want to create a helper method that writes the OS-dependent newlines for you, after every call to write().

Other observations

As you can see from above, it's recommended that your method takes in the output path as well, instead of assuming "output.html".


What would be the computationally faster way to implement this 2D numerical integration?

A very low hanging fruit, namely lifting the constant factor

0.5 * (1 / (np.sqrt(2 * np.pi) * 2))

out from the integral, reduces time by a quarter. On my system the original code took

294.532276869

while the fixed one took

224.198880911

Another fruit, a bit above, is to abandon dblquad whatsoever. It is just a wrong tool here.

Notice that the only dependency on q is in j0(q * t), and that it does not depend on z either. From the mathematical viewpoint it means that an integral of erf(...) * exp(...) over dz can be tabulated once as a function of t, say F(t) for the lack of better name, which then can be fed into the final integration as t * j0(q*t) * F(t).

Of course you'd need a lambda to interpolate tabulated values, and to manually take care of precision, and maybe do something else that dblquad does under the hood. Nevertheless, expect a thousand-fold speedup.


Auto move files to a sub folder with Ruby

The constructor, initialize should only prepare the state of the object but not execute methods like move_file. You could call FileAction.new(filename, event).move_file instead.

You use a lot of instance variables that could replaced by local variables and method arguments. It follows the principle of minimum scope. That makes your code more functional. As result the methods become independ of the context of the class.

The class is not necessary since you have no real state to encapsulate.

FileWatcher.new(@doc_files).watch do |filename, event|
  move_file(filename) if event == :new
end

Hope it helps.


This won't scale if you entire application is one large object.

If you seperated it into multiple objects

var application = []

application.push({
  wrapper: $("#wrapper"),
  init: function () {
    this.wrapper.on(bla, this.foo)
  },
  foo: function () {

  }
})

...

applications.forEach(function (app) { app.init() })

it will becomes significantly more maintainable.

You may also want to look into techniques for spreading application infrastructure across multiple files. For example ncore uses browserify for it's module system, and uses dependency injection and an expected object format to stitch multiple "modules" together.


Readability would be greatly enhanced by splitting the code into stanzas, using more line breaks, and adding comments.

Why do you like drawing backwards?  Going forward is much easier to understand.  The first two lines inside the procedure, for example, could be replaced by this code, which draws a counterclockwise path going forward, rather than a clockwise going backward:

to gnome
    ; Outline of conehead
    rt 7
    repeat 180 [fd 1 lt 1/4]
    lt 97
    repeat 180 [fd 1 lt 1/4]
    repeat 180 [fd 1 lt 1]

    pu lt 83 fd 50
    …

There would then be an extra rt 7 command, and it finishes with lt 83 instead of lt 90, but I think that that's a good thing, because it emphasizes that the shape is skewed, not symmetrical.

Some initialization code would be a good idea, to ensure that the turtle is in an expected state.  For example, ht pd would hide the turtle and put the pen down.  You might also want to set the heading and colour as well.

I don't know what dialect of Logo you are using, but setfillcolour instead of setfillcolor seems unusual.


I guess a prefix tree might help.

Build a parallel array of pointers (sorry for a C-speak) into an original text.
Sort it.
Scan it for a longest match in two consecutive entries.

Overall complexity is \$O(ns)\$

Where \$n\$ is the length of the text and \$s\$ is the length of the longest recurring substring.


How to delete last element in java.util.Set efficiently?

First of all, you should always use block statements with the for loops. The original formatting of the question was this:

for(Stop stop:stops)
 listOfStopNames .add(stop.getStopName());
 listOfStopNames .remove( ((TreeSet<String>) listOfSources).last());

It's hard to read. Readers could think that the remove call is part of the for loop since it's the same indetation level as the line before.

for (final Stop stop : stops) {
    listOfStopNames.add(stop.getStopName());
}
listOfStopNames.remove(listOfSources.last());

Hungartion notation is redundant, try to avoid it. A few new names:

listOfRoutes -> routes
listOfStopNames -> stopNames
listOfSources -> sources

As @luketorjussen already mentioned, downcasting is nasty. If the implementation of listOfSources changes it may return another type and the compiler will not warn you but you'll get exceptions at runtime. At least change the casting to SortedSet instead of the TreeSet. TreeSet implements SortedSet and SortedSet has the required last method.

I'd extract out some method for better readability. For further review you should share some code from the routeStopsService, Router and Stop classes.

private Set<String> getStopNamesWithoutLast(final Route route) {
    final Set<String> result = getStopNames(route);
    final String lastStopName = ((SortedSet<String>) sources).last();
    result.remove(lastStopName);
    return result;
}

private Set<String> getStopNames(final Route route) {
    final Set<String> result = new TreeSet<String>();
    final Set<Stop> stops = routeStopsService.getStops(route);
    for (final Stop stop : stops) {
        final String stopName = stop.getStopName();
        result.add(stopName);
    }

    return result;
}

final List<Route> routes = routeStopsService.getAllRoutes();
final Set<String> allStopName = new TreeSet<String>();
for (final Route route : routes) {
    final Set<String> stopNames = getStopNamesWithoutLast(route);
    allStopName.addAll(stopNames);
}


getword that properly handles undersores, string constants, comments, or preprocessor control lines

I don't didn't immediately see a bug in it and you're doing a lot of things well; so some minor comments.

while(isspace((c = getch())))
    ;

This will often cause a compiler warning "possible missing or empty statement". If you use a compound statement instead that may suppress that warning:

while(isspace((c = getch()))) { }

int ordinaryKeyWord = 0;
int comment         = 0;
int stringConstant  = 0;

These are mutually exclusive, so a 3-valued enum might be better.

for(; --lim; w++)

I don't think your lim testing is strict enough: for example if lim is 8 then /*this*/ would overrun (write past the end of) the input buffer; even an ordinaryKeyWord will write its last '\0' past the end of the buffer.

return *--w;

That's a bit tricky. It would be clearer to return word[0]; everywhere consistently.

    if(ordinaryKeyWord && (!isValidKeyWord(*w))) {
        ungetch(*w);
        break;
    }

That's compact (few lines) but could be expanded to make the logic clearer for a tired reviewer:

    if(ordinaryKeyWord) {
        if (isValidKeyWord(*w)) {
            continue;
        }
        ungetch(*w);
        break;
    }
    if (stringConstant) {
        ... break or continue ...

else if(c == '/') {
    *w++ = c;
    c = getch();
    if(c == '*') {
        *w++ = c;
        comment = 1;
    }
    else {
        *w = '\0';
        return *--w;
    }

You're missing ungetch in the else case.

Is there any way to show end-of-input: pressing <Ctrl>-D for EOF for example? If so, how does getword signal that?

I don't know an easy way to automate code which reads from the keyboard using getch and ungetch.

That's a pity because I'd like to see the automated unit tests which define how well your code works.

For example, this question includes its unit tests: 6 different tests of the function being coded. I was able to identify one or two bugs in the function, not by reading the function but by reviewing the set of unit tests, to find a condition (a set of input data) that wasn't being tested.

My boss wasn't a programmer but used to user-acceptance-test the software before shipping it: he said, not 'you get what you expect' but "You get what you INspect".

Especially when you're beginning you should learn to do unit testing, and take pride in constructing a good/complete set of test cases, which is able to detect bugs in the earlier versions of your software.


You could take an object and check if the action exists. If so, take the value as key for assignment.

const actions = {
        accept: 'showAcceptButton',
        reject: 'showRejectButton',
        transfer: 'showTransferButton'
    };

for (const element of actionsReferences) {
    if (element in actions) {
        this[actions[element]] = true;
    }
}


Find first non-repetitive char in a string

Some of what constitutes a "good" solution here depends on how much value you place on (for example) CPU time vs. memory usage. Another point to take into account is what size of strings you expect to process, and whether you expect them to be mostly unique, mostly repeats, basically random, or exactly what.

As it stands, this uses almost no extra space, but uses \$O(N^2)\$ CPU time. If you expect the input strings to be long, this could be quite prohibitive.

If you didn't mind using extra space, you could (for example) walk through the string, and use a hash table to count the number of occurrences of each character. Then walk through the hash table, and find the characters in the string that only occur once. Mark those, then do a final walk through the string to find which occurred first. This requires two walks through the string, and one walk through a hash table the same size as the number of unique elements in the string, so it's basically 3N operations, or \$O(N)\$ (well, we expect linear complexity, anyway--in the true worst case, it's still \$O(N^2)\$). For a long string (say, a few million or even a few thousand characters) that could be a huge win (but at the expense of approximately doubling the memory usage. If you're concerned with worst case performance more than average, you might want to use a balanced tree instead of a hash table, so insertions are \$O(N log N)\$ (both expected, and worst case).

Which one is preferable will (mostly) come down to questions like those in the first paragraph. For typical short strings (less than 20 characters long is very common), either is likely to be fast enough that a more efficient algorithm won't make much real difference. On the other hand, if the input might be megabytes instead, the faster algorithm is likely to pay off--and even if it's several megabytes, allocating an extra several megabytes on a modern desktop (or server) machine rarely matters a whole lot.


Inverted index in Clojure - performance vs. idiomatic code

You should be able to use reducers to get a good speed boost as the consumption and building of your index can be parallelized.

I have found the best docs for reducers to be the doc strings themselves:
Reducers -- Github

(ns ...
  (:require [clojure.core.reducers :as r]
            [clojure.java.io :as io]
            [clojure.string :as str]))

(defn invert [file]
  (let [f (.getName file)
        tokens (str/split (str/lower-case (slurp file)) p)]
        (->> tokens
             (r/mapcat #(hash-map % #{f}))
             (into {}))))

(defn build-index
  [dirname]
  (->> dirname
       io/file
       (.listFiles)
       (r/map invert)
       (r/fold (r/monoid (partial merge-with union) hash-map))))


With this implementation, it would not throw a stackoverflow exception but there could be an unusual behavior. Maybe there could be some better exception message to handle this case.

OverflowQueue q = new OverflowQueue(n);

Now, let's say I want to enqueue n+1 number of elements and then dequeue the same number of elements. Here it doesn't throw any error to enqueue n+1 elements. However deQueue method will throw NullPointerException as soon as the method is executed (n+1)th times.

I would prefer to "resize the array" to avoid Stack overflow exception. There is a possibility of unused space in memory in case of resize array implementation if enqueue and dequeue are executed randomly. This can be handled by sinking the array if required.


Find index of the nearest larger number of a number

EDIT: I mistook "nearest" to mean "numerically closest" but the problem asks for minimum distance from the index.  As the other answer points out, there are faster methods than visiting every element.

The answer to the followup question is "yes."

"Larger" is ambiguous: if you ask someone for a "large negative number" they probably don't answer "negative one."   Attribute this to sloppiness on the author's part, unless you've reason to suspect trickery.

I'm not a fan of these variable names: idx1 should be idx0, or i0 or initialIndex.  nearestLargest isn't the largest anything and nearestLarger would be more accurate.  num is a number, but so is everything else—maybe minimum or baseline or mustBeGreaterThan. nearestLargestNumber contains an index, not a number, while the number is held in nearestLargest.

I suggest one common prefix for your index variables and another prefix for value variables (though you don't really need more than one).

const nearestGreater = (arr, i0) => arr.reduce(
        (iNearestGreater, val, i) =>
            ( val > arr[i0] && ( iNearestGreater===null || val < arr[ iNearestGreater ] ) ) ?
                i : iNearestGreater,
        null
    );


Compressing string in Scala, how to do this immutably?

Here's my take using foldLeft:

def compress(s: String) = {
    val a : List[(Char,Int)] = List()
    s.toCharArray.foldLeft(a)((acc, elem) => acc match {
        case Nil => (elem, 1) :: Nil
        case (a, b) :: tail =>
            if (a == elem) (elem, b + 1) :: tail else (elem, 1) :: acc
    }).reverse
    .map{ case (a, b) => a.toString + b }
    .mkString("")
}

Note: I have assumed that order matters. That is, aabbbaa will reduce to a2b3a2


public interface IFaker<T> where T : class
{
    Faker<T> GetFaker();
}

I don't think you need this interface and the additional call to GetFaker. Instead you can derive your class from the Faker<T> and use the constructor to set everything up:

public class DogFaker : Faker<Dog>
{
    public DogFaker()
    {
        RuleFor(dog => dog.Name, f => f.Name.FirstName(Name.Gender.Male));
        RuleFor(dog => dog.IsGoodBoy, f => f.Random.Bool());
    }
}

private Faker<T> GetFaker<T>() where T : class
{
  if (!_fakers.ContainsKey(typeof(T)))
  {
      throw new ArgumentException($"Type: {typeof(T).FullName} not registered with FakerService");
  }
  var faker = (Faker<T>)_fakers[typeof(T)];
  return faker;
}

In this case it would be much clener to query the dictionary only once with TryGetValue if you are going to use the value anyway rather then doing it twice, once with ContainsKey and then with the [] indexer. At the same time you can tun it into a ternary operator ?::

private Faker<T> GetFaker<T>() where T : class
{
    return
        _fakers.TryGetValue(typeof(T), out var faker)
            ? (Faker<T>)faker
            : throw new ArgumentException($"Type: {typeof(T).FullName} not registered with FakerService");
}

Since ´InitialiseFakers´ does not require any instance data I suggest making it static. I like the way you created this initializer. Instead of letting it set the _fakers dictionary you return it as a result and assign it in the construtor. This way it's much cleaner and all the initialization-assignment stays inside the construtor so a big plus for that.

// Can we do better than <Type, object> ?
private Dictionary<Type, object> _fakers;

I'm afraid we cannot because Faker<T> isn't derived from any other collection-friendly interface. All you have is:

public class Faker<T> : IFakerTInternal, ILocaleAware, IRuleSet<T> where T : class

and this is not very useful so object is the only possible generalisation in this case. But this isn't that bad. It's an object so it doesn't cost you a penny to cast it. But sure, some general interface would be nice.


Strategy design pattern in C++ using unique_ptr

This looks like a standard use of PIMPL.  Is that all the member functions you need?  If just 2 or 3, just manually forwarding each one is fine.

Does the Activation class do anything besides have those forwarding functions?  If not, don’t bother with the wrapper and forwarding at all!  Just make an instance of the concrete class and use it.  (If there are other functions, see if they can simply be non-virtual in the base and inherited)

Correct, unique_ptr has a destructor — that is part of its defining nature.  Don’t write one for the class, and the compiler knows it should just call the destructors of all the members.

The usage is a little clumsy:

Neuron n( std::make_unique<Identity>() );

How about adding a wrapper so you can write

auto n = Neuron_with<Identity>();

As a matter of style, leading underscores are generally criticized here.  Some compilers had and still support special keywords and extensions in this format.  You have to remember to never use a capital initial letter after the underscore.

It is perfectly OK and idiomatic to just name the constructor arguments the same as the members.


Rotate square matrix clockwise by 90degrees

has a time complexity of O(n^2).

I think you are incorrectly using "n" as if it is the size of the n×n matrix.

The "n" in O() notation refers to the total size of the input data.

So, for a m×m matrix, the "n" value for complexity would be m2.

Your algorithm is O(n).

  This code doesn't use extra memory

Is there a specific reason for doing the swap trick the way you did rather than simply using the more obvious method with an auto int temp; on the stack?

auto memory is allocated on a stack, so it exists only during the invocation of the function.
After that, it can be reused by other functions.
Unless a function is called recursively, there's no cumulative problem with using temporary stack space; that's what it's for.

And if an algorithm should ever actually require persistent storage, it would be done using static rather than auto.

  This is C using the Original K&R C.

The biggest drawback to using that is that you don't get the benefit of typechecking, which was introduced in C89.

The compiler won't notice any problem with this:

swap(&_matrix[i][j],&_matrix[j][i]);
swap(_matrix[i][j],_matrix[j][i]);
swap("me", "you");

but at runtime things will fail.

I hope you are at least using lint on the source to check for such problems.


Bash script to capture error message and change exit status

Pretty nice job for someone new to bash.
I have a couple of tips though.

Instead of this:

# capture the exit status of the call to p4 unshelve
if [ $? -eq 0 ]
then
    flag0=0
else
    flag0=1
fi

You can write simply:

flag0=$?

It's not exactly the same, because the error code might not be 1, but we can make it work with this lazy way too, see below.

Similar to earlier, instead of this:

if [ "$std_err_output" = "$error_message" ]
then
   flag1=1
else
   flag1=0
fi

You can do simpler:

[ "$std_err_output" = "$error_message" ]
flag1=$?

Similarly, instead of this:

exit_status="expr $flag0 | $flag1"

exit "$($exit_status)"

You can benefit from the fact that the exit code of the script will be the exit code of the last command. So you can simply write:

[ $flag0 = 0 ] && [ $flag1 = 0 ]

Lastly, I suggest to move the rm tmp_file higher, to get it done as soon as you no longer need that file. No need to keep it around any longer than necessary.


You can get rid of the variables result and res and shorten the code by changing it into a generator. If you really need to get a list in the end, wrap the call with list(parse(root, tree)).

def parse(node, tree):
    if node not in tree:
        yield [node]
    else:
        for next_node in tree[node]:
            for r in parse(next_node, tree):
                yield [node] + r


changing root password with an ansible playbook

For starter, I’d remove debug messages: they do nothing except leaking sensitive information. If you want a deeper sense of what is going on when running your playbook, you can always invoke Ansible with the verbose (-v) option.

Second, I would not use vars to store a password. Instead, I would ask it to the user using a vars_prompt. In fact, using a prompt to update a user password seems so common a need that Ansible itself provide this very possibility; but here you want to automatically append something else, so I’d reuse part of your approach.

The playbook I’d use would be:

- hosts: test

  vars_prompt:
    - name: shared_string
    - prompt: "Common base for your passwords? "
    - private: yes

  tasks:
   - name: Extract last digits of remote host ip
     set_fact:
        last_digits: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] | regex_search(regexp) }}"
     vars:
        regexp: '\d{1,3}$'

   - name: Compose and encrypt the password as shared_string@last_digits
     command: openssl passwd -crypt "{{ shared_string }}@{{ last_digits }}"
     register: crypted_password

   - name: Change root password
     user: name=root update_password=always password={{ crypted_password.stdout }}


This isn’t a bad idea for a learning project, and I’d say it’s implemented quite well.
Before I dive into the code itself, I’m going to do a high-level design review.
Design review
You’re using std::map backwards
So you want a list of pairs of values, where one value is the tax rate and the other income lower bound for that tax rate. In your code you made the tax rate the lookup key, and the lower income bound the value.
The problem with that is that what you want to do is use the income to lookup the tax rate. Since the tax rate is the key in your map, that means you actually have to manually go through the map, checking each entry and inspecting the value.
If your map were the other way around—with the thing you actually want to lookup, the income, as the key—the lookup code would be trivial:
// income lower bound is the key, tax rate is the value
auto const taxRate = std::map<double, double>{
    {499'999, 0.35},
    {349'999, 0.31},
    // and so on
};

double HighestRate(double income)
{
    // lower_bound() finds the key that is NOT LESS than the argument given
    // (in other words, the key that is greater or equal). So whatever income
    // you give it, it will give you the NEXT greater tax bracket. That means
    // we have to BACKWARDS one tax bracket to get the proper answer.
    //
    // If the data were encoded differently, this could be much simpler, but
    // you have to be careful not to change the logic.

    auto p = taxRate.lower_bound(income);

    // If we got the first tax bracket, there is no lower tax bracket... so
    // no taxes due.
    if (p == taxRate.begin())
        return 0.0;

    // Go backwards one tax bracket.
    --p;

    // Now just return the rate.
    return p->second;
}

Actually, the code is even simpler if you don’t use HighestRate():
double TaxesDue(double income)
{
    double totalTaxes = 0.0;

    // Starting tax bracket:
    auto p = taxRate.lower_bound(income);

    // Convert the starting tax bracket iterator to a REVERSE iterator so we
    // can go backwards (from highest tax bracket down to lowest).
    for (auto r = std::map<double, double>::reverse_iterator{p}; r != taxRate.rend(); ++r)
    {
        // For each tax bracket:

        // 1) subtract the lower bound from the income to get the amount
        //    taxable in that bracket
        auto taxable_amount = income - r->first;

        // 2) calculate the taxes, and add to the total
        totalTaxes += taxable_amount * r->second;

        // 3) the remaining income is everything not yet taxed... which is
        //    the same as the lower bound of the bracket
        income = r->first;
    }

    return totalTaxes;
}

Don’t take the two functions above too seriously; I didn’t test them, and I didn’t really think too hard writing them, so there may be mistakes.
The point I want to make here is about the shape of your map. You should ask what you’re using the map for; what are you using to search? In your case, you are using the income to search the map (to find the tax rate). That means the income should be the key… not the tax rate.
An extra map tip
Notice in the functions I wrote above that I had to go backwards and use reverse iterators, all of which increased the complexity quite a bit. Well, the cause of that is that std::map will store its elements in increasing order, starting from the lowest to the highest. But when you’re calculating taxes, you want to go the opposite way: you want to start at the highest tax bracket, and work your way down. That’s the way you wrote the data, too: from the largest to smallest tax bracket.
There is way to flip the order of std::map. std::map has 3 template parameters (well, actually 4, including the allocator). The third template parameter is the comparator function, which defaults to std::less. So to flip the order, all you got to do is use std::greater instead.
Observe:
auto const taxRate = std::map<double, double, std::greater<>>{
    {499'999, 0.35},
    {349'999, 0.31},
    // and so on
};

double TaxesDue(double income)
{
    double totalTaxes = 0.0;

    // Easy peasy.
    //
    // (Just note we switched to upper_bound() because the
    // greater-than/less-than logic is reversed.)
    for (auto p = taxRate.upper_bound(income); p != taxRate.end(); ++p)
    {
        auto taxable_amount = income - p->first;

        totalTaxes += taxable_amount * p->second;

        income = p->first;
    }

    return totalTaxes;
}

One more thing I should mention: I noticed you used the tag “hash map”. You’re not actually using a hash map; you’re using a normal map. In the standard library, the hash map is named std::unordered_map… but you do not want to use that for this case, because it is—as the name says—unordered… and you want ordering to make searching and doing calculations easier.
A note about money and floating point values
While it’s fine for practice code, you should never, ever use floating point types like double for currency.
To see why, try running this simple program:
#include <iostream>

auto main() -> int
{
    auto my_cash = 100.0;

    // Set up cout to print cash values nicely:
    std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
    std::cout.precision(2);

    std::cout << "I have in my account: " << my_cash << "\n\n";

    my_cash += 1e24;
    std::cout << "The bank screwed up and deposited a septillion dollars!\n";
    std::cout << "I have in my account: " << my_cash << "\n\n";

    my_cash -= 1e24;
    std::cout << "The bank took their septillion dollars back.\n";
    std::cout << "I have in my account: " << my_cash << "\n\n";

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

Example output:
I have in my account: 100.00

The bank screwed up and deposited a trillion dollars!
I have in my account: 999999999999999983222784.00

The bank took their trillion dollars back.
I have in my account: 0.00

:(

A better idea is to use an integer type fixed to the smallest money fraction you could want to work with. For example, instead of using a double value of 100.0 dollars, you might use an int value of 10000 cents. Or if you need more precision, you might use millionths of a dollar, so $100 would be an int with value 100'000'000. If int is too small, you’d use long or long long or std::int_fast64_t instead.
Then what you’d do is make a class for monetary values, to make working with them painless and transparent. The class would simply wrap your integer type, and then provide a nice interface so you could write code like:
class money_t
{
    // ...

private:
    std::int_fast64_t _value;
};

constexpr auto calculate_taxes(money_t income)
{
    return income * 0.05; // 0.05 is the tax rate
}

auto income = 100_dollars;

auto taxes = calculate_taxes(income);

std::cout << "you pay " << taxes << " in tax.\n";
std::cout << "you have " << (income - tax) << " left over.\n";

// the output is automatically nicely formatted as:
//      you pay $5.00 in tax.
//      you have $95.00 left over.

I would recommend starting with something as simple as:
using money_t = std::int_fast64_t; // or "= long long;" or whatever

… then building up to a proper money_t class. That could be your next project! C++ is a strongly-typed language, and I always tell my students that if you get the types right in C++, then everything else because easy. Making a monetary value type isn’t hard, but doing it well will take some work, and teach you a lot about the language along the way.
Code review
#include <stdio.h>

This is not a C++ header. The proper header here would be <cstdio>… but honestly, I can’t see why you need it.
You also don’t use anything from <cmath> or <iomanip> so far as I can tell.
But you do use std::stod()… which is in <string>… which you don’t include. It “works” probably because <string> is being included by something else… but you can’t count on that.
double TaxesDue(double &income);
double HighestRate(double &income);

It is very rare to take function parameters by non-const lvalue reference. There are only a few special cases where that’s normally done.
When you take an argument by a non-const reference, you are telling the people reading your code that you intend to change that value. So when I see TaxesDue(income), I assume income’s value is going to change after the function call. The compiler will also assume that, which can prevent optimizations.
If you’re not going to change the value of the argument, it should be const:
double TaxesDue(double const& income);
double HighestRate(double const& income);

However, double is a fundamental type, so you don’t really need to take it by reference at all. It doesn’t hurt, though.
Also, note that the standard practice in C++ is to put the type modifier with the type:

double &income: this is C style.
double& income: this is C++ style.

std::map<double, std::string> taxRate =

You might want to make this const.
    double income;

    std::cout << "Enter your income: " << std::endl;
    std::cin >> income;

Couple things here. You should put the variable declaration as close as possible to the point of initialization. This is better:
    std::cout << "Enter your income: " << std::endl;

    double income;
    std::cin >> income;

It’s also wise to avoid uninitialized variables. It’s kinda okay if you do what I did just above, and put the double income; RIGHT above the std::cin that actually initializes it. But the way you wrote it, with the double income; several lines away from where it’s initialized… that’s dangerous.
One way to avoid initialized variables is to use the more modern practice of “always auto”:
// double income;       // <- bad, uninitialized
auto income = double{}; // <- better, cannot possibly be uninitialized

Finally, avoid std::endl. I know lots of tutorial code shows to use it, but it’s almost always wrong (or more charitably: unnecessary). Every use of std::endl in your code is wrong; in every case it forces a flush of the output stream unnecessarily.
If you want a newline, don’t use std::endl. Just use \n:
int main()
{
    std::cout << "Enter your income: \n";

    auto income = double{};
    std::cin >> income;

    auto taxesDue = TaxesDue(income);
    std::cout << taxesDue << '\n';
}

TaxesDue() is cool. It could be simplified and made much more efficient, but the problems aren’t actually in the function, they’re in the way the data is structured, as I mentioned in the design review.
The only big problem in TaxesDue() is the magic number 29999. You shouldn’t hard code that in the function. You should use the tax rate map; just get the income lower bound from the lowest tax bracket… which, with your current design, is just std::stod(taxRate.begin()->second). (But if you swapped the map key and value, and used doubles, it would be taxRate.begin()->first.)
So that leaves HighestRate():
double HighestRate(double &income)
{
    /*
    std::map<double, std::string> taxRate =
    {
        {  0.35, "499999" },
        {0.31,"349999"},
        {0.25,"249999"},
        {0.21,"169999"},
        {0.18,"119999"},
        {0.14,"79999"},
        {0.10,"44999"},
        {0.05,"29999"}
    };
    */

    if (income > std::stod(taxRate[0.35]))
    {
        return 0.35;
    }
    if (income > std::stod(taxRate[0.31]))
    {
        return 0.31;
    }

    // ...

There is a lot of unnecessary repetition here. Take the tax rate for example: 0.35 is repeated three times, once in the tax rate map (which is fine), then twice in HighestRate().
Unfortunately, this can’t be simple, because you have the map backwards. If the income were the key, no problem, you just do a normal map lookup with lower_bound() (like I demonstrated in the design review section). But because the income is the value, and the rate is the key, you have to do this the hard way.
What you have to do is iterate through the map, checking the value. Not only that, you also have to make sure you get the largest value. Something like:
double HighestRate(double income)
{
    auto highest_amount = 0.0; // or "= std::numeric_limits<double>::lowest();"
    auto result = 0.0;

    for (auto&& [rate, amount_s] : taxRate)
    {
        auto amount = std::stod(amount_s);

        if ((income > amount) and (amount < highest_amount))
            result = rate;

    }

    return result;
}

Which, as you can see, is pretty complicated. That’s why you really want the income to be the key.


Multiple similar event handlers for input validation

You can use functions for those validations:

var validations = {
    '.js-mandatory-notnull': function(val) {
        return val.length > 0;
    },
    '.js-mandatory-2words': function(val) {
        return val.match(/^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+/i);
    },
    '.js-mandatory-numb': function(val) {
        return val.match(/^(?=.*\d)\d*[\.\,]?\d*$/);
    }
}

And then install those via a loop:

$.each(validations, function(selector, validate) {
    $(document).on('keyup change focusout', selector, function(e){
        validateInput(e, $(this), validate(this.value));
    });
});


Calculating a total price by using switch statement and sentinel controlled loop

Prefer not to use single characters as variable names (except for simple loop counters).  Saving a few keystrokes is not worth it if your readers cannot understand your code.

Based on the context, it looks like n and q should respectively be named productNumber and productQuantity.
The sum += 0 in the default looks unnecessary.  Just remove it if so, even if it's only there to have the default do something.  Keep things simple.


Which of these two paren-matching functions is better?

I would propose an even less performant solution, but maybe you can improve it...

balance xs = head cumulated == 0 && all (>= 0) cumulated where
  cumulated = scanr (+) 0 $ map depth xs
  depth '(' = -1
  depth ')' = 1
  depth _ = 0

Note that I work "backwards" (scanr and inverted parens values) in order to avoid a call to last cumulated.


Program that reads 4 files and outputs contents of it into another file after formatting it

I think that zip can save you some work:

with open('a.txt', 'r') as file_a, open('b.txt', 'r') as file_b, \
     open('c.txt', 'r') as file_c, open('d.txt', 'r') as file_d:
         for content in zip(file_a.readlines(), file_b.readlines(),
                            file_c.readlines(), file_d.readlines()):
             print(content)

The above is just a basic example, you will want to:

Add error checking (asserting for example)
Add an output file
Add necessary spaces


SDL Initialization and Management wrappers

Throwing in a noexcept function

This is legal, see https://stackoverflow.com/questions/39763401/can-a-noexcept-function-still-call-a-function-that-throws-in-c17. However, you already have doubts about it, so that's telling you it's probably not a very proper thing to do. Compilers will also warn about this.

If you want your program to terminate when it can't create a window, I would make this explicit, and instead of using throw, call std::terminate() explicitly.

Define a namespace for your library

All your classes and structs have names with SDL prefixed, for good reasons. However, you can make it more explicit to the compiler that you want everything in a separate namespace. The advantage is that within that namespace, you don't have to use the prefix anymore. For example, you can write:

namespace SDL {
  class Window {
    friend class Context;
  public:
    ~Window() noexcept = default;
    ...
  };

  class Context {
  public:
    explicit Context(Opts const &options) noexcept;
    ~Context() noexcept;

    Window Window() const noexcept;
    Renderer Renderer() const noexcept;

  private:
    Opts options_ {};
    SDL_Window *window_ {};
    SDL_Renderer *renderer_ {};
  };
}

In your application, you can instantiate an Window like so:

SDL::Window myWindow;

Avoid forward declarations whenever possible

Forward declarations should only be used if really necessary. Otherwise, they are just duplicating code, with the potential to make mistakes. If you are using a SDL_Window * in your header files, just make sure you #include <SDL.h> in it.

Avoid friend classes

Why is SDLContext a friend class of SDLWindow? If it needs to access some private member variables, maybe you should add public accessor functions instead? From the code you posted I don't see any reason why a friend class is necessary. In general, it is something to be avoided, since it bypasses the usual member protection scheme.

Use of std::experimental

While we all would like to have the latest and greatest language features available, consider that your code might be compiled by others using older compilers. Using experimental C++20 features might prevent them from using your code. Furthermore, observer_ptr<> is not doing anything really, it's just there as an annotation. It's there to convey to other users that this pointer is not owned. SO it is more useful to use this for the public API than for private member variables. But, that also brings me to:

Have classes own their own pointers to SDL2 objects

It looks a bit weird that SDLWindow has a private constructor that takes a pointer to an SDL_Window. Why not have SDLWindow call SDL_CreateWindow() itself in its constructor? The same goes for SDLRenderer.

When you do this, then SDLContext should no longer store pointers to SDL_Window and SDL_Renderer, but it should instead store a SDLWindow and SDLRenderer directly:

class Context {
  Window window_;
  Renderer renderer_;

public:
  Context(...);
  ...
};


Strategy pattern for four arithmetic operations

Overkill

This program is using dynamite to crack nuts. Choosing one operation of four is a very simple problem, easily handled with an enum and a switch. Indeed, your program already contains those, so the strategy classes are just unnecessary complexity.

I'm going to ignore that and review this program as just an exercise in using strategies. But if you were actually trying to solve a problem, this would be a horribly complex design.

Unfortunately, this makes it hard to judge how well you're using strategies, because you aren't using them for anything. It's also hard to advise how to simplify the program, because everything is unnecessary complexity.

How to use strategies

The Design Patterns movement is not a good guide to how to structure programs. Most of the techniques it teaches are rather specialized, and strategies are one of those. They're a useful tool to know, but they're only one tool of many, and you won't use them regularly.

When implementing strategies, you should prefer λ to custom classes. Fall back to classes only if λ isn't available or won't work — for example, if the strategy has more than one operation, or needs to be saved to a file.

Using λ is also a better way to learn to use strategies. If you're comfortable with first-class functions, and use them without thinking they're a Fancy Design Pattern, then strategies look like an obvious (but clumsy) variation, so it will be easy to use them correctly.

If you aren't already comfortable with λ and functional programming, that's far more important to learn than design patterns.

Repetition

Now for some actual code review.

The three private members of Operation (m_Result, m_Value1, m_Value2) are unused. And they're private, so the subclasses can't use them either, and must redefine them! If they're part of Operation's interface, they should be public or at least protected.

Unnecessary state

There's no reason for the strategies to store m_Value1, m_Value2 or m_Result. Calculate can simply take them as arguments and return the result. The interface could be like this:

class Operation {
    virtual int Calculate(int a, int b) = 0;
};

Similarly, Test::SetOperation modifies this for no good reason. Is this just to have an excuse to store an Operation somewhere? It could simply return an Operation, or it could perform the operation directly without storing it anywhere. Then there's no reason for Test to be a class at all. It could simply be a function.

C++

Don't make a habit of using std::endl: it flushes the stream, which is seldom what you want.

Test leaks its Operations. This is harmless in a toy program, but you should habitually use std::unique_ptr for owned data, so you don't have leaks when they matter.

Superficial details

I see from stdafx.h that you're writing in Microsoft style, so I won't complain about the m_ prefixes.

There are a lot of unnecessary blank lines. I don't know if these are also a deliberate stylistic feature, but they're usually thought to make the program harder to read, because you can't see as much of it at once.

I suppose the std::cin >> x at the end is a hack to make the program's window not disappear instantly? You shouldn't have to do this. If you're running the program from an IDE, it should have an option to fix this for you; if you run it from the command line, this problem should not arise.

A better strategy problem

If you'd like a better problem to practice using strategies, try implementing a game like fairy chess, where there are a wide variety of pieces with unique moves. Don't make a subclass for each one; instead, the constructor should take a strategy (represented as a function) to generate the piece's possible moves. The usage might look like this (with functions that return move generators):

Piece camel("camel", "L", Leaper(1, 3));
Piece rook("rook", "R", Rider(1, 0));

If that's too complicated or doesn't sound fun, try a simpler game with a variety of pieces or cards or actions, where each one takes a function (not a class) to calculate what it does.


Clearing filters, copying a range, and then pasting a formula down a row

This should be much faster:

We get rid of the .Select and .Activate. They will slow the process down because it is telling excel to do something, that takes time.
Since we only want the values we assign them directly avoiding the clipboard.  Again just the moving of data into the clipboard takes an extra step and then moving them out again is another step.  We can do it in one.
When using R1C1 we can put the formula in bulk, so no looping.  The R1C1 references will adjust accordingly.
Using the With block and proper . notation allows us to limit typing the sheet over and over again, but still allowing the proper parentage to be assigned.

Sub testingme2()

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

Dim myvalue As Double, lastrow As Long, paster As String

lastrow = Worksheets("x").Cells(Rows.Count, 1).End(xlUp).Row
myvalue = Worksheets("y").Cells(6, 2).Value
paster = "formula"

If Sheets("x").FilterMode Then
    Sheets("x").Cells.AutoFilter
End If

Sheets("Z").Range("A6:AG5000").Value = Sheets("x").Range("A6:AG5000").Value

With Worksheets("x")
    .Range(.Cells(6, (myvalue) + 20), .Cells(lastrow, (myvalue) + 20)).Value = .Range(.Cells(6, (myvalue) + 20), .Cells(lastrow, (myvalue) + 20)).Value
    .Range(.Cells(6, (myvalue) + 21), .Cells(lastrow, (myvalue) + 21)).FormulaR1C1 = paster
End With

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub


This might not be quite what you've got in mind, but one big improvement you could make would be to use meaningful variable names and insert whitespace.

def decrypt():
    cyphertext = raw_input('Give me the word to decrypt:')
    shift = input('What was it shifted by?')

    cypher_chars = list(cyphertext)
    str(b) # this does nothing; you should remove it
    cypher_ords = [ord(x) for x in cypher_list]
    plaintext_ords = []
    for i in cypher_ords:
        plaintext_ords.append(i - shift)

    plaintext_chars = [chr(i) for i in plaintext_ords]
    plaintext = ''.join(plaintext_chars)
    print 'Decryption Successful, your word is', plaintext, '!'

Of course you could actually compress much of this into a one-liner. But for a new programmer, I'd suggest sticking with readable variable names that make it clear what's going on.

Still, you could do that while compressing the code a bit:

def decrypt():
    cyphertext = raw_input('Give me the word to decrypt:')
    shift = input('What was it shifted by?')

    cypher_ords = [ord(x) for x in cyphertext]
    plaintext_ords = [o - shift for o in cypher_ords]
    plaintext_chars = [chr(i) for i in plaintext_ords]
    plaintext = ''.join(plaintext_chars)
    print 'Decryption Successful, your word is', plaintext, '!'


Naming

class Rosa tells me nothing. The name should scream out that it is a dependency injection container.

PSR

There is a standard interface for DI containers.
https://github.com/php-fig/container/blob/master/src/ContainerInterface.php

You might want to have you container implement it.

Exit vs. Exception

Implementing the PSR interface would automatically answer your question about exit vs. exception. In short, yes throw exception. Don't call exit generaly from anywhere.

Shared vs one-time services

Your container keeps references of services that you have registered but will instantiate a new one every time if not registered explicitly.

This is rather unintuitive. Consumers of the container should either be able to choose whether a service is shared or should get new instance every time. Or they should always receive consitent behaviour for all services (only one of them is supported).

On demand instantiation

Assuming you have chosen to support shared services, it is common that only a recipe for the service is provided and the actual service object is instantiated on first demand.

Configuration of Services

It would be more precise to say that your container does not just have autowiring feature, but that the autowiring is almost unevitable. You either register instantiated service (for which you have had to resolve dependencies manually) or it autowires all constructor arguments (potentialy recursively).

This is somewhat related to the previous section. If you had recipes for service instantiation, you could define which values parameters should be autowired and which should receive value defined by the consumer.

Services Dependant on Interfaces

You assume that a constructor parameter is a class or a primitive type with default value. Recipes could again help with primitives without default.

If it is not a primitive it still does not mean it is a class, it can be an interface. But you dont have any mechanism autowire interfaces because you dont keep track of interfaces implemented by services.

Service Identification

You save services by class name, making it impossible to have multiple services of the same class. It is common that it is possible to set a name for a service. Again this could be property of a service recipe.

Single Responsibility Principle

Autowiring is quite a big topic and it could be useful in conjunction with other things that a DI container. Therefore it makes sense to separate the autowiring mechanism to a separate class and have the container just depend on it.


Find all needles in the haystack and return their sum

First, you should have a look at PEP8 again, specifically the part about function names. It recommends using lower_case_with_underscores. It also recommends leaving two blank lines between function definitions on the module level.

Next, open already opens the file read-only by default, there is no need for 'r'. Also, f.readlines() returns a list, which you then convert into a string representation of that list. However, you can just use f.read() here, which directly returns the full string. Note that reading in the full file content at once might be quite memory-consuming, so don't do it with files larger than your RAM.

Last but not least, your function calculate_sum could just be the built-in sum, if the elements of results were already numbers. So I would change get_numbers to return actual numbers (like the name implies), by using map:

import re

def get_numbers(file_name):
    with open(file_name) as f:
        return map(int, re.findall('[0-9]+', f.read()))

def main(file_name='haystack.txt'):
    print sum(get_numbers(file_name))

if __name__ == "__main__":
    main()

In Python 3.x, you could use the yield from keyword to make your get_numbers into a generator and avoid the memory issue, because the file is read one line at a time (at the cost of executing the regexp for every line):

def get_numbers(file_name):
    with open(file_name) as f:
        for line in f:
            yield from map(int, re.findall('[0-9]+', line))

In Python 2.x this could be implemented like this:

def get_numbers(file_name):
    with open(file_name) as f:
        for line in f:
            for item in map(int, re.findall('[0-9]+', line)):
                yield item


If you try the following :

class Program
{
    static void Main(string[] args)
    {
        Foo<string>(null);
        Foo<string>("asd");
        Foo<int>(1);
        Console.ReadKey();
    }

    public static void Foo<T>(T test)
    {
        if(test == null)
        {
            Console.WriteLine("ho ho it's null");
            return;
        }

        Console.WriteLine(test.GetType());
    }
}

You will realize that both the options are, excuse me, useless. The language already supports this behavior and if T is a struct, test == null will simply return false all the time.


Use SelectMany. As in, allPersons.SelectMany(s => s);. This flattens the sequence for you.


Switch case implementation in Java for an integer pair combination

Neither is good, but surely we can all agree that the Java example is way uglier. The biggest problem, however, is that both examples hard code data into code.

Separate data, i.e. stream and subject IDs and their titles into a data class and in that class implement code that accesses the data structure without detailed knowledge about the actual data. Responsibility of setting up the data structure to resemble your stream and subject numbering is left to a separate component (load it from file or set up in static code).

Whether the data class is a recursive structure or just a wrapper for a HashMap depends on the complexity of your data.


Rock Paper Scissors in one single method in Java - Good or bad?

I would make some changes, although your code is quite simple.

First, get rid of the magic Strings for rock/paper/scissors, and create an enum.

I would possibly also move the logic of checking if it's a win/draw/loose inside that enum, so it would be much easier to add new entries (imagine you want to extend that to a Rock/Paper/Scissors/Lizard/Spock.

My main recomendation is to separate getting the input from the user, and the logic of the actual program.

If these two concepts are completely separated, you could reuse the logic to build, for instance, a web interface, or get the user input in any other way (or even get two inputs from two users, and use the same logic to decide who wins!).

Check this, for instance, for an enum representation of Rock/Paper/Scissors:

https://stackoverflow.com/a/9858163/432806

Overall I would advise you to have a structure like:

main:
    input = getUserInput
    enumValue = getEnumFromInput
    secondValue = getEnumFromComputerRoll
    testWhoWins(enumValue, secondValue)

That last line could also be something like:

    enumValue.getResult(secondValue)

If you implement the logic inside the enum.

update

There's also another big downside to that monolithic approach, that hasn't been discussed yet: testing.

There is no simple way of writing unit tests for a program written in such a fashion.

To be able to have decent unit tests, you need to break up your programming logic into small pieces that can be tested independently from each other.

Think about:

How would you test transforming a String (user input), to the correct Enum/String?
How would you test generating a value in the right range, and converting into an Enum?
How would you test the logic of, given two "moves", choosing the result?

I think this is a good way of figuring out how to break up your logic: Think about how you would write tests for it.


I would consider an approach were you think of the array as a circular buffer, with the top of the stack being position 0. Each of your operations becomes a rotation. One position clockwise and one anticlockwise.  Or even both clockwise (or anticlockwise), one a single position rotation and one a size-1 rotations.

If you can change the data structure so that the top of the stack can be any position in the circular buffer the these rotations become trivial, just set the top of value.


There is a nice language extension in GHC called ViewPatterns. Together with LambdaCase that fature allows you to shorten your code, I think. And do notation will be much more readable for imperative part.

runGameLoop game panel | victory game = return Victory
                       | otherwise = continue
    where
      anyEvent = gatPanelWindow panel >>= flip getEvent (Just 1)
      isRestart = (EventSpecialKey (KeyFunction 2) ==)
      isQuit = (EventSpecialKey (KeyFunction 10) ==)
      continue = do
          refreshGamePanel game panel
          render
          anyEvent >>= \case
              Just (isRestart -> True) -> return Restart
              Just (isQuit -> True) -> return Quit
              Just (EventSpecialKey (keyToDirection -> Just dir)) ->
                  runGameLoop (makeMove game dir) panel
              _ -> runGameLoop game panel

Another variant is to consider using of Monad Maybe instance

runGameLoop game panel = nextStep where
    anyEvent = gatPanelWindow panel >>= flip getEvent (Just 1)
    nextStep = if victory game then return Victory else do
        refreshGamePanel game panel
        render
        liftM react anyEvent >>= \case
            Just continuation -> continuation
            Nothing -> runGameLoop game panel
    react event' = do
        event' >>= \case
            EventSpecialKey (KeyFunction 2) -> return (return Restart)
            EventSpecialKey (KeyFunction 10) -> return (return Quit)
            EventSpecialKey key -> do
                dir <- keyToDirection key
                return (runGameLoop (makeMove game dir) panel)
            _ -> Nothing


Umm… this is a complicated solution that makes no sense.  Why not keep it simple?

NSString *intToString(NSInteger numberToConvert)
{
    return [NSString stringWithFormat:@"%ld", numberToConvert];
}

If, on the other hand, the exercise is to implement your own solution from scratch, then I would consider it cheating to use NSMutableString stringWithFormat:.  Either way, I would consider your solution to be a failed response in an interview situation.


Although you should comment your work, some of your comments seem unecessary. Let's look at some lines to see why:

# parse the list until it is sorted
until @sorted == true

The comment seems redundant. Your line of code until @sorted == true reads clear enough for me to understand that you want to keep doing something until the list is sorted.

# if the first is greater than the second, swap them with parallel assignment
if list[i] > list[i+1]
  list[i], list[i+1] = list[i+1], list[i]

This code is also pretty self explanatory. If you did have a comment you should be explaining why you do this. However, bubblesort is pretty well known so you probably don't even need a comment on this.

# increase the number of swaps performed in this run by 1
swaps += 1

Again why? I can read the code, it is obvious you're incrementing the number of swaps. I would omit.

# compare the next 2 elements
i += 1

Based of the if statement I would know that this the purpose of i. I would omit it, but it does explain why you increment i, so there is some grey zone here.

You write some good comments toward the end, let's analyze why they are good:

# If any swaps took place during the last run, the list is not yet sorted
if swaps > 0
    @sorted = false
# no swaps? Everything is in order
else
  @sorted = true

It explains why we need to check if swaps > 0 and how the sorting algorithm depends on this.


Instead of using while to count a specific number of times and manually handle the number, you should use for _ in range(num_of_retries). It works the same except that you don't need to manually change num_of_retries. And this way num_of_retries wont be modified from the initial value, in case you need to access it again for any reason.

There is one small change to make this work. You need to use the for ... else syntax to raise if the loop is not broken. An else block after a for block will be executed if the for loop never reaches a break statement. This fits your case perfectly as break is called on success, but if there's never success then it will run through all the iterations and reach the else block where you can raise:

for _ in range(num_of_retries):
    try:
        request_id = str(uuid.uuid4())
        params = [('requestId', request_id)]
        url = 'service.com'
        url = url + urllib.urlencode(params)
        request = urllib2.Request(url, data=html)
        request.add_header('Accept', 'application/pdf')
        request.add_header('Content-Type', 'text/html')
        handle = urllib2.urlopen(request)
        pdf_blob = handle.read()
        break
    except Exception:
        typ, val, tb = sys.exc_info()
        logger.error(traceback.format_exception(typ, val, tb))
        time.sleep(time_interval)
else:
    raise

Without any explicit argument, raise will just use the last exception that has been raised and handled. See the SO answer here about it. Basically when you try except an exception, its details are being retained by Python and are passed to raise in the absence of any explicit exception passed to raise.


I'm afraid your sorting is in vain because the normal dictionary does not guarantee that the items will be enumerated in the same order as you added them:

  For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey, TValue> structure representing a value and its key. The order in which the items are returned is undefined.

If they are, then this is a pure coincidence.

You'll be safe if you use the SortedDictionary instead which:

  Represents a collection of key/value pairs that are sorted on the key.

If we assume for a moment that a Dictionary<TKey, TValue> can be sorted the way you do it then it can be also achieved with a simple LINQ query:

private Dictionary<string, string> sortMacroDictionary(Dictionary<string, string> source)
{
    return source.Keys.OrderBy(k => k).ToDictionary(k => k, k => source[k]);
}

You first get all keys, order them, then you create a new dictionary based on the new key order. This is virtually the same as what you are doing now but much shorter.

As far as your code is concerned there is no need to check whichDictionary.Count > 0 becasue if the dictionary is empty your loops won't run. The same applies to this query.

My advice is to use the SortedDictionary. This dictionary maintains the order the entire time. It sorts itself so to speak, as you add/remove items. You don't have to sort it manually.


Extract last delivery for each name on each date

You could short-hand your max() function with the use of Comparator.comparing()

byOrderDateList.stream()
  .max(Comparator.comparing(Delivery::deliveryTime)).get()
  .setIsLatest(true);


Counting the number of domino tilings for a rectangular grid

Looks like a decent translation of your algorithm into C++. However, if you're looking for speed, this code is very "heavyweight".

It uses strings such as "drldurlrld" to represent each row of the grid, when bit-strings would suffice. (If you mark each "d" with the bit 1, and everything else with the bit 0, you'll still have an unambiguous encoding. This trick is similar to the trick used by Eller's maze-generation algorithm.)
It copies around vector<string> to memoize the "next possible rows" for a given row.
It doesn't use move semantics.

Now, I said that your code memoizes "next possible rows" — this is the purpose of dictionary — but if you look closely, you'll see that the variable dictionary is unused!

I can tell from context that what happened is you forgot to add a single line of the form dictionary[row] = prev; at the end of nextRows. But if the compiler can't read your mind as well as I can, then you'll have to learn to be more on guard — otherwise your code will run slowly and you won't know why!

On the plus side, this one-line difference is nice because it means you can test your code with and without the memoization and see if the memoization is actually worth it. I think it will be worth it, but I'm not 100% sure.

    if (currentRow == height) {
        for (char cell : previousRow)
            if (cell == 'd')
                return 0;
        return 1;
    }

This code, which rejects tilings with dominos that stick off the bottom of the grid, is important enough that I would recommend putting a comment on it.

    if (currentRow == height) {
        // Count this tiling, unless it dangles off the edge of the grid.
        return (previousRow.find('d') == std::string::npos) ? 1 : 0;
    }

To address the lack of move semantics: There are a couple of places in firstRow where you make copies of strings (or even whole vectors of strings), when you actually don't care about the right-hand side of the assignment anymore and might as well just move the string (or vector) into the left-hand variable. For example:

    string candidate = prev.back();
    prev.pop_back();

    switch (candidate.back()) {
    // ...
    case 'r':
        next.push_back(candidate + 'l');
        break;
    }
}

prev = next;

Here once you've finished the switch statement you don't care about the value of candidate, so you could

next.push_back(std::move(candidate) + 'l');

to save a copy. (Yes, this will in fact do the efficient thing: see overload #11 on the cppreference page.)

And you certainly don't need to make a copy of next when you assign it to prev! Replace that vector copy with a quick vector move:

prev = std::move(next);

Move semantics are more subtle (and probably less important) than I'm making them sound here; I won't go into detail here. But there is no shortage of material for learning more about move semantics if you want/need to.

int count() {
    if (!done) {
        tilingCount = countTiling(height, width, "", 0);
        done = true;
    }

    return tilingCount;
}

This is a common anti-pattern I see in a lot of student code for some reason: you want to compute a value, so you make a ValueComputor class, give it a computeTheValue() method, and then add memoization so that the computeTheValue() method won't be so darn slow the second time you call it.

This is an anti-pattern because it takes a notionally const operation (counting the number of tilings) and makes it a non-const member function. That is, it breaks this reasonable-looking code:

DominoTilingCounter tc(4, 4);
const DominoTilingCounter& param = tc;
std::cout << param.count() << std::endl;  // oops! can't call count() on a const object!

But it's also super easy to fix. Just take that code that computes the number of tilings, and move it straight into the constructor of your class!

DominoTilingCounter(int height, int width) : height(height), width(width)
{
    if (height <= 0 || width <= 0 || height * width % 2) {
        tilingCount = 0;
    } else {
        tilingCount = this->countTiling(height, width, "", 0);
    }
}

int count() const { return tilingCount; }

Much cleaner! And a tiny bit faster in the case that you call count() multiple times, because you don't have to check done anymore. (And much slower in the case that you construct a DominoTilingCounter object and never call the count() method — but why on earth would you construct this single-purpose object if you're never going to use it?)

Now notice that you don't use this->height or this->width anywhere in the code — instead, you pass around the caller's original height and width as parameters. And with the refactoring above, you don't use done. So what you're left with here is a class DominoTilingCounter that is effectively the same thing as an int. So, get rid of the useless class!

int count_domino_tilings(int height, int width);

This is the function you want to be writing. There's no reason to drag object-orientation into it at all. Your main function had been multiple lines long because of the mutation involved (and honestly it's not clear from reading this code that all the expensive work occurs on line 2 — so that's another downside to the anti-pattern above)...

int main() {
    DominoTilingCounter tc(4, 7);
    std::cout << tc.count() << std::endl;
}

...but with a nice clean function, it becomes simply

int main() {
    std::cout << count_domino_tilings(4, 7) << std::endl;
}

With such a drastic savings in lines of code, you have room left over to write some test cases! :)


Sorting numeric  tags without omitting the attributes

There are a few clear improvements I can see when you are reinserting the nodes back into the DOM tree.

for (i=0; i<nEntryArray.length; i++)
{
  nList.appendChild(nEntryArray[i]);
}

1)  You may benefit from using a documentFragment to build up your elements then submit them all at once to the nList

2)  (micro), cache the length of your array in the for loop.

var df = document.createDocumentFragment();
for( var i = 0, l = nEntryArray.length; i < l; i++) {
    df.appendChild(nEntryArray[i]);
}
nList.appendChild(df);

Otherwise I do not see any issues with this code. http://jsfiddle.net/rlemon/faY3Z/


Efficiently find all the Pythagorean triplets where all numbers less than 1000

Some optimizations and style suggestions:

After finding a solution you can break:
for a in range(1,1001):
    for b in range(1, 1001):
        for c in range(1, 1001):
            if pow(a, 2) + pow(b, 2) == pow(c, 2):
                print(str(a) + "," + str(b) + "," + str(c))
                break

Use ** which is faster than pow, or just multiply for itself a*a.
Use Python formatter to print the result: print(f"{a},{b},{c}").
Calculate c as \$c=sqrt(a^2+b^2)\$:
for a in range(1,1001):
    for b in range(1, 1001):
        c = int(math.sqrt(a ** 2 + b ** 2))
        if a ** 2 + b ** 2 == c ** 2 and c < 1001:
            print(f"{a},{b},{c}")

The solution now takes \$O(n^2)\$ instead of \$O(n^3)\$.
Instead of checking if a ** 2 + b ** 2 == c ** 2:, it's enough verifying that c is an integer:
for a in range(1,1001):
  for b in range(1, 1001):
      c = math.sqrt(a ** 2 + b ** 2)
      if c.is_integer() and c < 1001:
          print(f"{a},{b},{int(c)}")

As already said, you can also start the second for-loop from a to avoid duplicated solutions.
Put everything into a function:
def triplets(n):
  for a in range(1, n):
      for b in range(a, n):
          c = math.sqrt(a * a + b * b)
          if c.is_integer() and c <= n:
              print(f"{a},{b},{int(c)}")
triplets(1000)

Runtime on my machine:
Original: 868.27 seconds (~15 minutes)
Improved: 0.27 seconds

EDIT:
Since this question got a lot of attention I wanted to add a couple of notes:

This early answer was for OP's original problem that I interpreted as "find all the triplets in a reasonable amount of time".
There are definitely more efficient (and advanced) solutions than this one. If you are interested in finding out more, have a look at other excellent answers on this thread.
As noted in the comments, the runtime in my answer is a rough calculation. Find a better benchmark on @Stefan's answer.


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


Ad-hoc analytics script to module/package

You may want to start by converting the process under __main__ into a function called main and then have it take command line arguments. That way, you separate user-configurable items from the actual program.

For example:

import re
import string
import sys
import os

import pandas as pd
from nltk.corpus import stopwords

def main(cmd_line_args):
  path_to_data_folder = cmd_line_args[1]
  os.chdir(path_to_data_folder)

  # regular expression containing punctuation to be removed from strings
  regexp = re.compile('[%s]' % re.escape(''.join(p for p in   string.punctuation)))

  # set of stopwords to remove from text from NLTK
  stops = stopwords.words('english')

  # my data frame, containing only columns of text
  data_frame_filename =  cmd_line_args[2]
  df = pd.read_csv(data_frame_filename+".csv")

  # clean each column
  for col in df.columns.values:
      df[col] = clean_and_map_column(col, df, regexp)

  cleaned_filename = cmd_line_args[3]
  df.to_csv(cleaned_filename+".csv")

if __name__ == '__main__':
  main(sys.argv)


Parent with N-Childs where each child can have N-Childs

It's not strange at all. It's just a tree, or graph, which is very common.

You don't even need two methods: a single one is sufficient.  You should define a single recursive method that takes in a list (or some other collection) of id's and returns those id's and all their  children and grand-children, etc.  If you want the children of a single element instead of a list of id's, you can just pass a list of one element (or define a method that does that).

Actually, it might be better to use a set instead of list of id's as the argument to the method since it would then handle duplicates and circular references.  ALso, if you use a list instead, you would have to specify in the documentation what the ordering of the returned list means.


Easy Bit IO. Very simple interface works up to N == 64

The code is relatively short and well-written, so I didn't find many nits to pick.  With that said, here's my review:

Include all needed files

Since std::ostream_iterator is declared in <iterator> that should be among the includes in main:

#include <iterator>

Use appropriate type for template parameter

The std::bitset template is defined as taking std::size_t rather than int, so it would make sense to define the BitIO template similarly:

template<std::size_t S>
class BitIO
{
    // ...
};

One can, of course, still abuse the interface by passing negative numbers but at least the user of the code is forewarned that they will be interpreted as std::size_t rather than as signed numbers.

Consider implementing a move constructor

At the moment, this potential usage cannot compile:

std::cout << BitIO<16>(std::bitset<16>{ 99 });

It's easily fixed by adding this constructor:

BitIO(std::bitset<S>&& data)
    : data(data)
{}

Maintain parallelism with existing practice

I was surprised to see spaces separating the outputs when none had been specified in the output ostream_iterator.  Although having the space is arguably useful, the choice of separator (if any) should be left up to the user of the template instead of being hardcoded in the operator << function.  I'd omit the trailing space to allow usage like this:

std::copy(std::begin(values), std::end(values),
        std::ostream_iterator<BitIO<16>>(std::cout,":"));


the following does not address any desired updates to findmatch()

But does address the request for improvements to the program.

improvements include:

no implicit conversion warnings from the compiler
does not use a well known system function name
uses system function: strlen() to find the length of the string
does not produce any compiler warnings
uses fgets() to read whole line in one operation
uses strchr() to eliminate any newline read by fgets()
follows the axiom: only one statement per line and (at most) one variable declaration per statement, resulting in much easier to read/understand code
the 'magic' numbers were either eliminated or replaced with meaningful names

and now, the revised code:

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

#define MAX_INPUT_LEN (40)

// prototypes
size_t myReadLine (char* text, int n);
char* findmatch(char* pattern, char* text, size_t pl, size_t tl);
void printmessage(char* position, char* text, size_t pl, size_t tl);

int main( void )
{
    char text[ MAX_INPUT_LEN ];
    char pattern[ MAX_INPUT_LEN ];
    char *position;
    size_t textlength;
    size_t patternlength;

    printf("Enter text: ");
    textlength = myReadLine( text, (int)(sizeof text) );

    printf("Enter pattern: ");
    patternlength = myReadLine( pattern, sizeof pattern );

    position = findmatch(pattern, text, patternlength, textlength);
    printmessage(position, text, patternlength, textlength);
}

size_t myReadLine( char* text, int n)
{
    size_t i = 0; // initialize to no chars read

    if( NULL != fgets( text, n, stdin ) )
    {
        // eliminate trailing newline, if any
        char * newline;
        if( NULL != ( newline = strchr( text, '\n' ) ) )
        {
            *newline = '\0';
        }

        i = strlen( text );
    }
    return i;
}

char* findmatch(char* pattern, char* text, size_t pl, size_t tl)
{
    size_t indexp = 0;
    char* position = NULL;
    size_t x=0;

    for( ; x<tl; x++)
    {
        int pc = *(pattern+indexp);
        int tc = *(text+x);

        if(pc == '?' || pc == tc)
        {
            indexp++;
            if(indexp == pl)
            {
                position = (text+x)-indexp+1;
                break;
            }
            printf("status: pass\n");
        }

        else
        {
            indexp = 0;
            printf("status: fail\n");
        }
    }
    return position;
}

void printmessage(char* position, char* text, size_t pl, size_t tl)
{
    if(position == NULL)
    {
        printf("no match\n");
    }

    else
    {
        size_t p = (size_t)(position-text)+1;
        printf("%s: %ld. %s\n",
               "The pattern was found at char",
               p,
               "The remaining text chars are: ");
        size_t i =  p+pl-1;

        for(; i<tl; i++)
        {
            printf("%c", *(text+i));
        }
        printf("\n");
    }
 }


Extract code and convert special characters to HTML entities

"Extracter" should be spelled "extractor".

It's nice that you broke up the functionality into smaller functions.

In get_string_between(), you don't appear to be properly handling the $start and $end strings not being found.  Consider:

$ini = strpos($string,$start);
if ($ini == 0) return FALSE;

Did you mean to write

if ($ini === FALSE) return FALSE;

instead?  strpos() is tricky, in that you have to carefully distinguish between 0 and FALSE return values.

For $last = strpos($string,$end,$ini), you don't check the return value at all, and just use it.

Flag variables are an ineffective way to control execution flow.  If possible, restructure the code to avoid them.  For example,

$components = array();
$exists = TRUE;
while ( $exists ) {
    $st = get_string_between($string, $start, $end);//decompose if token found
    if( !$st )
        return $string;// return the original string if nothing found
    $string = $st['end'];
    $components[] = $st;        $exists = strpos($st['end'], $start) !== FALSE;//check if another code exists in the string
}

… should be written as an equivalent do-while loop:

$components = array();
do {
    $st = get_string_between($string, $start, $end);//decompose if token found
    if( !$st )
        return $string;// return the original string if nothing found
    $string = $st['end'];
    $components[] = $st;
} while (strpos($st['end'], $start) !== FALSE); //check if another code exists in the string

However, even that is dissatisfying, since the strpos() test is redundant with the strpos() operation within get_string_between().

$components = array();
while (($st = get_string_between($string, $start, $end))) {
    $components[] = $st;
    $string = $st['end'];
}
return empty($components) ? $string    // return the original string if nothing found
                          : reconstruct($components, $this->InputFilter);

In reconstruct(), your loops are too complex.  The original code…

$count = count($strings);
$i = 0;
$str = '';
$code = array();
$uniq = uniqid();//i create a unique key to prevent confusion if users insert the same token i'm using
foreach ($strings as $key => $val) {
    $i++;
    foreach ($val as $k => $v) {
        if( $k == 'start' )
            $str .= $v;
        if( $k == 'inside' ){
            $str .= '['.$uniq.$i.']'; //creat a token in the string
            $code[$i] = htmlspecialchars($v);
        }
        if( $i == $count )
            if( $k == 'end' )
                $str .= $v;
    }
}

… could be simplified to

$str = '';
$code = array();
$uniq = uniqid();
foreach ($strings as $i => $component) {
    $str .= $component['start'];
    $str .= "[$uniq" . ($i + 1) . "]";  // Create a token in the string
    $code[$i + 1] = htmlspecialchars($component['inside']);
}
$str .= $component[count($component) - 1]['end'];

It's unconventional that $code is a 1-based array, and there doesn't seem to be any advantage to starting from 1 rather than 0, so just use $i instead of $i + 1 everywhere.  Just adjust $j accordingly.

Nobody likes to read low-level string manipulation code, especially when it's not clear what the code is supposed to do.  Now that I've understood it, I would write a comment on the function like this:

/**
 * Runs HTML purifier on $string.  Sections of the string between $start
 * and $end delimiters are taken literally: instead of being filtered through
 * the HTML purifier, they are escaped using htmlspecialchars() instead.
 * The $start and $end delimiters themselves are discarded.
 */


Both classes have undefined or unused class properties. The first class does not use the $url property and never defines the $total or $like properties. The second class just doesn't use the $total property. If these properties really aren't being used, then you can just remove them from the class. However, if you meant to use them, then you will have to do so using the following syntax: $this->url.

PHP will soon be deprecating default method types. In other words, methods must be explicitly defined as public, private, or protected. Right now they are all public by default, but there's no telling how long that will last. Plan for the future and start defining them now so you won't have to later.

I'm not sure where the object_2_array() function is coming from as this is not a function included in the default PHP library. If you are just trying to get the JSON object into an array, then you can do the same thing you did for your twitter JSON object and set the second parameter of json_decode() to TRUE.

Instead of explicitly defining the first array index, just shift the first element off the initial array. Makes it a little more pleasant to read and removes ambiguity as to where the "0" index came from. If you don't want to modify the existing array, you can just assign the value of the first array element to a different variable. However, as it stands this does not appear to matter as the initial array is not being used anyways. Both methods are shown below.

$results = $fb_array[0];
//OR
$results = array_shift( $fb_array );

$this->total = $results['total_count'];
$this->like = $results['like_count'];

When using foreach loops to iterate over an array, it is not always necessary to define the array key as a parameter, only if you are planning on using that value. So, on your first foreach loop in the twitter constructor you can remove the $key => bit as it is unnecessary. Also, keep in mind, it is usually a bad idea to overwrite a variable and should be avoided if not explicitly meant. Even though it is unused, you are overwriting your first $key variable with the second foreach loop. This is bad practice as it could lead to mistakes later. If you need another $key variable you can call it $key2 and the first $key1, or keep the first as it is and call the second key $index. Or anything else really, just so long as it makes sense.

With all that being said, I don't think it was necessary to create these as classes. These are simple enough to where you could have more easily created these procedurally. Additionally, please make sure code you submit for review is functional. As it stands, many of these errors looks like they could have been made from copy-pasting code together.


You have a bug

Don't run this code when the current time is 58 or 59 minutes. The loop will never end. You can fix that by adding a modulo in the switch statement:

switch (findNextDeparture % 60) {

This way, it will be ok even if findNextDeparture overflows, you will still get the correct time until the next departure. For example starting from 58, 70 % 60 will match case 10:, giving you 70 - 58 = 12 minutes.

Remove the duplication

In every case statement you do essentially the same thing. You could reduce that to this:

switch (findNextDeparture) {
    case 10:
    case 20:
    case 30:
    case 40:
    case 50:
    case 52:
    case 55:
    case 56:
    case 57:
        System.out.print("Departure in " + Math.abs(initialTime - findNextDeparture) + " min.");
        break loop;
}

Simplify calculations

You're setting findNextDeparture to the same value as initialTime. Instead of spelling out that long expression, it would be better to reuse it:

int initialTime = (int) (time / (1000 * 60) % 60);
int findNextDeparture = initialTime;

Since findNextDeparture starts from the same value as initialTime, and it always increases, you don't need Math.abs(initialTime - findNextDeparture), you can do simply findNextDeparture - initialTime for the same effect.

Improving the implementation

First of all, as others have suggested, the main logic of finding the next departure date should be extracted to its own method, and return the minutes to next departure instead of printing it. Consider this signature:

int findMinutesToNextDeparture(int initialTime) { ... }

This transformation helps with the while loop too: instead of using the loop label, you could just return. Simpler, and more natural, because labels are not a usual practice in Java, and it probably indicates code smell. This transformation helps with another thing: it makes the method testable, see more on that later.

Second, the while loop, the switch, the list of case statements... Not cool! For one thing, stepping through values one by one, sounds silly, doesn't it. If the values are in a list, you could make bigger jumps than doing it 1 by 1. But there's something even better: binary search!

Consider this implementation:

public static int findMinutesToNextDeparture(int initialTime) {
    List<Integer> times = Arrays.asList(10, 20, 30, 40, 50, 52, 55, 56, 57);
    // index of the search key, if it is contained in the array;
    // otherwise, (-(insertion point) - 1).
    // The insertion point is defined as the point at which
    // the key would be inserted into the array:
    // the index of the first element greater than the key, or a.length
    // if all elements in the array are less than the specified key.
    // Note that this guarantees that the return value will be >= 0
    // if and only if the key is found.
    int index = Collections.binarySearch(times, initialTime);
    final int nextDeparture;
    if (-index > times.size()) {
        nextDeparture = times.get(0) + 60;
    } else if (index < 0) {
        nextDeparture = times.get(-index - 1);
    } else {
        nextDeparture = times.get(index + 1);
    }
    return nextDeparture - initialTime;
}

Note that the times list would be probably better as a parameter. I left it inside the method just for the sake of this example. Now, the logic looks quite tricky. I included the JavaDoc of Collections.binarySearch for reference and because it's kind of hopeless to remember this stuff.

Keep in mind that the list must be sorted for binary search to work. If you make a mistake when typing the elements like this it, it will be broken:

List<Integer> times = Arrays.asList(10, 30, 20, 40, 50, 52, 55, 56, 57);

To make sure you cannot make mistakes, you can wrap the list inside a sorted collection, and then again in a random access list like this:

List<Integer> times = new ArrayList<>(new TreeSet<>(Arrays.asList(10, 30, 20, 40, 50, 52, 55, 56, 57)));

Unit testing

I'll be honest: getting the binary search technique right was not easy. It helped that I already had unit tests for the original working implementation. Before you refactor something, make sure you have solid unit tests. This way you can protect yourself from accidentally breaking your working code.

@Test
public void testMinutesBeforeFirst() {
    assertEquals(10, TrainDepartures.findMinutesToNextDeparture(0));
    assertEquals(7, TrainDepartures.findMinutesToNextDeparture(3));
}

@Test
public void testMinutesInBetween() {
    assertEquals(7, TrainDepartures.findMinutesToNextDeparture(13));
    assertEquals(7, TrainDepartures.findMinutesToNextDeparture(43));
}

@Test
public void testExactMatches() {
    assertEquals(2, TrainDepartures.findMinutesToNextDeparture(50));
    assertEquals(3, TrainDepartures.findMinutesToNextDeparture(52));
}

@Test
public void testMinutesBeyondLast() {
    assertEquals(12, TrainDepartures.findMinutesToNextDeparture(58));
    assertEquals(11, TrainDepartures.findMinutesToNextDeparture(59));
    assertEquals(9, TrainDepartures.findMinutesToNextDeparture(61));
}


Entity Framework Core DbFunction for square root

Here I capture the main essence of the comments.
Facts

As the OP has mentioned the Sqrt functionality is no exposed on the EF.Functions in EFCore

EF 6 exposed it through SqlFunctions

Math.XYZ functions can be used in Linq2Entities

Not all of the functions have translator to the corresponding SQL function, current state
As a part of this issue more function translators will in v5

Solutions

Math.Pow can be used as well, like this: Math.Pow(a.someColumnWithDoubleValue, 0.5)

This will be translated into POWER

Math.Sqrt can be used as well, like this: Math.Pow(a.someColumnWithDoubleValue)

This will be translated into SQRT
If the data type would be decimal then explicit cast is needed:

Math.Pow((double)a.someColumnWithDecimalValue)
Translated into SQRT(CONVERT(Float, ...)