Generating Norwegian National Identification Numbers in Python

I only started Python about 3 months ago, so take my advice with a grain of salt.

(also my first review here :)

PEP8

Try to follow the PEP8 styleguide. Most of the issues I have with this are some whitespace issues. For example:

Two empty lines between import calendar and def is_valid_date(d):
Two empty lines between def pad(n): and def generate(d):
Put some whitespace between variable declaration and operators for increased readability. See dd, mm, yyyy = [int(i) for i in [d[:2],d[2:4],d[4:]]]
Most variable names in the functions don't really have descriptive names. For example d of the is_valid_date or generate
Try not to put if-statements on a single line. (Not sure if this is PEP8, but still a good practice).
None of your functions have docstrings. Documenting your code is great if you need to modify the code later on. Try not to reiterate how the function does something (e.g. explaining the code - that's what the code is for), but rather on why you chose to make this function.

Now on to actual code.

The days dictionary of the is_valid_date function is not being modified. Rather than creating it every time the method is called, perhaps consider making it a global variable, and making it more readable:

days = {
    1: 31,
    2: 29 if calendar.isleap(yyyy) else 28,
    3: 31,
    4: 30,
    5: 31,
    6: 30,
    7: 31,
    8: 31,
    9: 30,
    10: 31,
    11: 30,
    12: 31
}

def is_valid_date(date):
    ...

However another way of doing this, is by using the already imported calendar module. This has the function calendar.monthrange(year, month), which also returns the number of days in the given month. This automatically takes care of leap years or other irregularities. Be wary that this returns 2 values though. To return only the amount of days in a month, you could use calendar.monthrange(year, month)[1].

In pad(n) you return either a formatted string, or a number. This means the there are two return types. You could have it return a string always:

def pad(n):
    return '{:03}'.format(n) if n < 100 else str(n)

or

def pad(n):
    n = str(n)
    if n < 100:
        return n.zfill(3)
    return n

which makes it a bit more readable. However, the pad function is not necessary, as the string.zfill(width) function can take of that for you:

>>>'75'.zfill(3)
'075'
>>>'655'.zfill(3)
'655'
>>>'{:03}'.format(75)
'075'
>>>'{:03}'.format(655)

Both functions only pad if necessary. This means you can do str(n).zfill(3) instead of the entire pad function.

In generate(d), your string type check is not python2 and 3 compatible. See this link for a better answer on string type checking.
The first line of the generate(d) function check for != True. As is_valid_date already returns a boolean value, using not would be a better choice:

def generate(d):
    if not isstring(d) or not is_valid_date(d):
        raise ValueError('Expected date string in format ddmmyyy, but got {}'.format(d))

Some more!

In get_range(year) you use

if year >= 1990 and year <= 1999:
    return range(500)

but this can also be written as:

if 1990 <= year <= 1999:
    return range(500)

or even:

if year in range(1990, 2000):  # more 'human' like.
    return range(500)

... which are both slightly more succinct. The first option (interval comparison) can also be applied in the is_valid_date function:

if 1900 > yyyy > 2039:
    return False
if 1 > mm > 12:
    return False
if 1 > dd > calendar.monthrange(yyyy, mm)[1]:
    return False

Another completely different direction you could go into, is converting the given date string to a datetime object:

from datetime import datetime

birthdate = datetime.strptime('%d%m%Y', datestring)

A nice bonus that comes with this, is that date validation is already done, as it will throw a ValueError if it's given an invalid date, thus eliminating the entire is_valid_date function.

This answer is already long enough, so I will keep it at that :)


The code looks pretty good, but a few things that can get you into trouble should be addressed:

Don't #include <bits/stdc++.h>. See this answer on Stack Overflow for an explanation of why. TL;DR - it includes everything and you don't need all that it includes. It's just making your compile times take much longer than they should.

There's no need to use long long for values up to and including 1,000,000. A 32-bit long will do just fine with plenty of room in case you go over.

You should avoid global variables. In a program of this size it's no big deal, but it's a bad habit to get into. If your program grows to a larger size, it can become very difficult to reason about why and where a global variable is being changed, making it harder to find and fix bugs or to extend the application's functionality.

Be careful creating such large arrays. In this case, because they are global, they are in your program's data segment rather than on the stack so it's not an issue. However, if you were to create them on the stack in this manner, there is a chance that you could end up with a stack overflow error. 1 million bools will take up at least 1 Megabyte of memory. Many applications have a stack that is smaller than that, or only a little larger by default.

For readabliity, I recommend using more spaces in your code. In particular, I always leave a space before and after any operator. So your main() function would look more like this:

int main()
{
    gencriba();
    int c;
    cin >> c;
    cout << criba [ c ] << endl;
    return 0;
}

It makes it easier to see at a glance what's a variable and how they're being operated on.

In terms of performance, the best optimization is usually a better algorithm. This Stack Overflow Question asks which algorithms are fastest and has several answers.


With totally zero context of what's going on and I'm not a math person, why "normalize"? What does "normalize" mean? As a front-end developer, normalize.css comes into mind, but it's not related to CSS. So I'm clueless. If you can give a better name, that would be great.

Also, a more compact way to write this is using a for loop

function normalize(n) {
  for(var x = 0, i = 0; i < n; i++){
    x += Math.random();
  }
  return (x / n);
}


Generating string primary keys with sequence in SQLAlchemy

literal_column("'DIVISION_ABC_REQUEST'").concat... (note the double quotes, since you want an SQL string expression).

literal_column() essentially means "I hand you this string which is a valid SQL expression and can be used in any column expression-ish context".


Time complexity of common ancestor algorithm

The runtime of the code in the post is \$Ω(n)\$, even if the tree is balanced, because checkSubtree has to visit all the nodes in the subtree.

In the worst case (where none of the nodes has a left child), the code is the post is \$O(n^2)\$ for the same reason.

So if you are going to visit all \$n\$ nodes, you might as well do this in just one pass over the tree, to make sure that you don't have quadratic behaviour in the worst case. See this answer for how to go about it.


Looked at your script and found a few things that can be improved in terms of code quality as well as performance. On my local machine i was able to cut the runtime in half with the code changes.

The default separator value of str.split() is whitespace character(s) (space, tab, newline, return, formfeed). Combining it with a ' '.join() will return a proper string. The unicode chars ('xa0') in your example are also handled by this approach. In general a good way to deal with unicode is to use the normalize function from the unicodedata package.
Instead of define and manipulate an index for your loop you can simply use enumerate in your for-loops.
I prefer to store the values per row in a simple list and create the dict after the loop is done via the zip function. The performance improvement is minor but i think it improves readability of the code quite a bit.
In general you should maybe have a look at the PEP-8 guide - your variable names are not PEP-8 conform.

Improved version:

    table_res = []
    column_headers = table.xpath(".//tr//th/span/text()")
    for row in table.xpath(".//tr")[1:]:
        cells = []
        for i, cell in enumerate(row.xpath(".//td")):
            if i != 1:
                cells.append(' '.join(cell.text_content().split()))
            else:
                cells.append(' '.join(''.join(cell.xpath('.//a/text()')).split()))

        table_res.append({k: v for k, v in zip(column_headers, cells)})

When you compare the outputs of both versions you will find some small differences. This is mainly due to the fact that your strings sometimes have a trailing whitespace or the date is missing some whitespace.


You need loop/recur very rarely in most code, and almost never for operating on collections/sequences.  Using the standard library sequence functions, it’s possible to do the main pile shuffle with just a handful of expressions:

(->> (range (dec n) -1 -1) (mapcat #(take-nth n (drop % cards))) reverse)

It takes some getting used to, and familiarity with the Clojure standard library.  When I was first getting started, I found it immensely helpful to read the clojure/core.clj code.  It isn’t all idiomatic because it’s building the support for the idioms as it goes, but it demonstrates what Clojure makes possible and how it makes those things possible.


If you would pass in your paramaters at sendPost(), you could reuse your created object for other URLs and Parameters, and would not need a specific constructor.

Generally, calling a Method in a constructor is defying the purpose of a constructor - to initialize an object. When rereading your code 2 months later, you would be wondering, where you'd be calling the actual POST.

Clean Code wise, it's generally a bad sign if you create subsections in your method using comments, such as //add reuqest header. Create seperate private methods in your class just for doing that. Your code will be more readable and reusable.

Exceptions; use them! Throw detailed Exceptions and declare them as such. So you can react in your other code to that exception.

String USER_AGENT = "Mozilla/5.0"; this should be either declared as private static final in your class, because when introducing other methods such as sendGet you'd be using the same variable again.

Generally, don't use System.out.println other than in very early stages of your code. Create a Response class, where you set the things such as the response code or others and return this, don't just write it to the console, you can't use it and your console is going to be littered with such output everywhere in your program, which makes it difficult to debug.

You could generalize the method creating your params String as well, so you could pass in an arbirtrary amount of parameters and it would serialize these parameters just right.


Input as reference-to-const

Change your signature to:

std::string repeat_string(std::string const& str, std::size_t N);

First, this avoids an unnecessary copy when users don't pass their strings in by rvalue (which seems more typical?). Secondly, this allows for copy elision on the returned object, as you can't have copy elision from a function parameter. So if I called repeat_string with an lvalue, I just saved two copies.

Also, note the name change. Either use camelCase or snake_case or function names, don't just jamlotsofwordstogether. It's much harder to read.

The new signature makes some of the other code easier.

if (n == 0) {
    return {};
}

...

if (str.size() == 1) {
    return std::string(n str[0]);
}

repeat_size

This is a weird variable at best. Once you make str a reference to const, you can just access str.size() which makes much more sense. repeat_size isn't really the size of the repeat - that's what n is...

Powers of 2

std::log2 and std::pow aren't cheap, and you need neither. For the former, you can just multiply by two until you're done:

std::string result = str;
result.reserve(str.size() * n);

std::size_t m = 2;
for (; m <= n; m *= 2)
{
    result += result;
}

Now m is the first power of 2 larger than n. So you can replace

n -= static_cast<decltype(n)>(std::pow(2, m));

with:

n -= m/2;

And:

str.append(std::cbegin(str), std::next(std::cbegin(str), n * repeat_size));

is a really complicated way of writing what now becomes:

result.append(result.c_str(), n * str.size());


You can take help of variables to reduce the methods calling also to reduce the number of repeated statements you can go with for loop:

$(".squareProgress")
  .append("

")
  .change(function() {
    $(this).trigger("updateProgress");
  }).on("updateProgress", function() {
    var wW = $(window).width();
    var wH = $(window).height();
    var $li = $(this).find("li");

    max = wW * 2 + wH * 2 - 30;
    progress = max * (parseInt($(this).attr("progress")) / 100);

    for(var i = 0; i < 4; i++){
      if(i % 2 == 0){
        $li.eq(i).width(progress > wW ? wW : progress);
        progress -= wW;
      }else{
        $li.eq(i).height(progress > wH ? wH : progress);
        progress -= wH;
      }
    }
  }).trigger("change");
body {
  padding: 0;
  margin: 0;
}

.sqaureProgress {
  position: absolute;
  width: 100%;
  height: 100%;
}

.squareProgress ul {
  padding: 0;
  margin: 0;
  list-style-type: none;
}

.squareProgress ul li {
  position: absolute;
}

.squareProgress ul li:nth-child(1) {
  left: 0;
  top: 0;
  width: calc(100% - 10px);
  height: 10px;
  background: blue;
}

.squareProgress ul li:nth-child(2) {
  right: 0;
  top: 0;
  height: calc(100% - 10px);
  width: 10px;
  background: red;
}

.squareProgress ul li:nth-child(3) {
  right: 0;
  bottom: 0;
  width: calc(100% - 10px);
  height: 10px;
  background: green;
}

.squareProgress ul li:nth-child(4) {
  left: 0;
  bottom: 0;
  height: calc(100% - 10px);
  width: 10px;
  background: yellow;
}


Mock/Stub out filesystem in F# for unit testing

Even though the SOLID principles are known to be principles related to Object-Oriented Design, I'd still take a cue from the Dependency Inversion Principle. As APPP states it (ch. 11): "clients [...] own the abstract interfaces".

You can apply this principle in FP as well, in the sense that you can start by defining the overall behaviour of the function you're interested in, and then see what happens.

As an example, I'd approach the ensureDirectoryExists function like this:

let private ensureDirectoryExists destination =
    let directoryExists = dirExists destination
    if not directoryExists then
        createDir destination

Now, the above version doesn't compile, because dirExists and createDir aren't defined. However, that's easy to fix: just promote them to function arguments:

let private ensureDirectoryExists dirExists createDir destination =
    let directoryExists = dirExists destination
    if not directoryExists then
        createDir destination

Viola: now you have a higher-order function; it's type is

('a -> bool) -> ('a -> unit) -> 'a -> unit

No interfaces are required.

This is already intriguing for a couple of reasons:

It's no longer about files or directories: 'a could be string values containing file names or directory names, but it could also be DirectoryInfo or something not at all related to files.
Although it looks complex, it only involves two types: 'a and unit. That should make us pay attention as well.
You can use partial application to apply the ensureDirectoryExists with the two first arguments, and then use this partially applied function to test any number of different directories.

You can still 'implement' dirExists and createDir, and apply them like this:

open System.IO

let directoryExists path =
    let fileInfo = FileInfo path
    fileInfo.Directory.Exists

let ensureDirectoryExists' =
    ensureDirectoryExists directoryExists (Directory.CreateDirectory >> ignore)

Notice that the createDir 'implementation' is so simple that I chose to inline it. I could also have inlined the dirExists 'implementation' with (fun path -> (FileInfo path).Directory.Exists), but I chose to do this as a separate function in order to illustrate the various options available.

The partially applied ensureDirectoryExists' function has this simple function signature: (string -> unit), which is comparable to the OP version of the function.

While I think I'll leave the rest of the functions as an exercise, I'd like to return to the thought-provoking signature of the ensureDirectoryExists function:

('a -> bool) -> ('a -> unit) -> 'a -> unit

There's nothing here about files or directories, so a more generic name might be in place. It looks like the Tester-Doer idiom, so we could call it testDo instead.

One of the great benefits of making the interface more generic is that you don't need to involve the file system at all for testing. Instead, you can test this function using integers, strings, or some other 'easy' values. If the logic is unconstrained generic and works for numbers and strings, it'll also work for directories and files.


I'm posting this with an assumption that the JsFiddle is missing something since it throws a "setTween is not a function" error. But given your code...

What you really want is a factory object, which gets provided some config data. Perhaps something in this format:

{
    "tween": {
        "duration": 0.7,
        "options": {
            "opacity": 0
        }
    },
    "scene": {
        "options": {
            "triggerHook": "onEnter",
            "offset": 500,
            "reverse": true
        }
    }
}

Let's just call this "animation factory" AnimationFactory:

function AnimationFactory() {
    this.controller = new ScrollMagic.Controller();
    this.scenes = [];
}

AnimationFactory.prototype = {

    controller: null,

    scenes: null,

    constructor: AnimationFactory,

    createAnimation: function(element, args) {
        element = typeof element === "string"
            ? document.getElementById(element)
            : element;

        var tween = TweenMax.to(element, args.tween.duration, args.tween.options),
            scene = new ScrollMagic.Scene(args.scene.options);

        scene.setTween(tween)
        scene.addTo(this.controller)
        scene.addIndicators();

        this.scenes.push(scene);

        return this;
    }

};

Then to use it:

var animationFactory = new AnimationFactory();

window.onload = function() {
    animationFactory
        .createAnimation("animation1", {
            tween: {
                duration: 0.7,
                options: {
                    opacity: 1
                }
            },
            scene: {
                options: {
                    offset: 200,
                    reverse: true
                }
            }
        })
        .createAnimation( ... );
};

Not you've got a nice clean API to use. But you said there are 50 of them on the page, and I imagine that number could change. Additionally, you have a disconnect between the animations and the elements that require them. Why not marry the two in wedded bliss using HTML5 custom data attributes?

function AnimationFactory() {
    this.controller = new ScrollMagic.Controller();
    this.scenes = [];
}

AnimationFactory.prototype = {

    controller: null,

    scenes: null,

    constructor: AnimationFactory,

    createAnimation: function(element, args) {
        ...
    },

    createAnimations: function(element) {
        var tween = null,
            scene = null,
            elements = element.querySelectorAll("[data-animation]"),
            i = 0,
            args;

        for (i; i < elements.length; i++) {
            args = JSON.parse(elements[i].getAttribute("data-animation"));
            this.createAnimation(elements[i], args);
        }
    }

};

And to use this:

var animationFactory = new AnimationFactory();

window.onload = function() {
    animationFactory.createAnimations(document.body);
};

And a little HTML for good measure:

Animation 1

Animation 2

This gives you unlimited potential. The configs for creating the animations are embedded right in the markup. If different pages had different animations, no need to keep different JavaScript files around. Every page can be different.

Since the AnimationFactory encapsulates all of the animations, you can tweak the work flow behind the scenes if you run into performance problems, like staggering the creation of the Tweens so you don't have 50 opacity tweens run all at once on the page (which I image might draw enough electricity from the CPU to power a small Tesla).

If you AJAX in some HTML, then insert it into a DIV after page load, the AnimationFactory#createAnimations method can be called, and pass in the HTML element that just had its innerHTML replaced and you'll get animations after AJAX, not just on page load.

// xhr is an XMLHttpRequest object that just got some HTML from the server
var div = $("#someDiv").html(xhr.responseText);

animationFactory.createAnimations(div[0]);


SQLite database for a micro/tumble blog application

Everything is good by this point but I'd change the relation between posts and tags from one-to-many to many-to-many.

You can do this with this code:

tags_to_posts = db.Table(
    "tags_and_posts",
    db.Column( "post_id", db.Integer, db.ForeignKey( "posts.id" ) ),
    db.Column( "tag_id", db.Integer, db.ForeignKey( "tags.id" ) )
)

class Post(db.Model):
    # ...
    tags = db.relationship(
        "Tag",
        secondary=tags_and_posts,
        backref=db.backref( "posts", lazy="dynamic" ),
        passive_deletes=True,
    )

Then tags will be just a list. Assuming my_tag and my_post exist, you'll be able to do something like this:

# Add tag to post
my_post.tags.append(my_tag)
db.session.add(my_post)
db.session.add(my_tag)
db.session.commit()

# Remove tag from post
# You need to be sure that my_tag is in my_post.tags
my_post.tags.remove(my_tag)
db.session.add(my_post)
db.session.add(my_tag)
db.session.commit()

I hope, it helps.


Encrypting messages using the XOR operation

Looks okay, perform-xor can be both simpler and the variables in the
let should be each on a single line.  You don't need the double map,
so just map over bigmap and then you also don't need the take, as
map will only run till one of the arguments runs out, thus:

(defn perform-xor []
  (let [bigmap (repeat 12 0xFF)
        xorkey [1 2 3 4 5]]
    (map (fn [x y] (bit-xor x y))
         bigmap (cycle xorkey))))

The -main function can be simpler, given that you don't (in principle)
care about the garbage from the mapv (mapv because it's eager):

(defn -main [& args]
  (mapv print (get-string-output))
  (newline))

newline just for giggles, or (more seriously) clarifying intent.


All possible lists from ups and downs between elements in python list

Your comparison function is the same as the builtin cmp function.

Your filtering technique to find the matching lists may be not the most efficient. Permutations will generate a lot of lists which fail the test. On the other hand, itertools is written in C, which means it'll probably be faster for small data sets.


Comparing two implementations of smoosh()

I think there are issues with both implementaitons, though I do find the first more readable.

The main problem is that neither makes it immediately clear that we are assigning a new value to each element of the input array. I would expect an implementation to look something like this:

public static void smoosh(int[] input) {
  for (int i = 0; i < input.length; i++) {
    input[i] = ...
  }
}

This makes it clear to the reader that each element of the input array will be assigned to.

Now we can keep track of where the next element for our array is coming from:

public static void smoosh(int[] input) {
  int j = 0;
  for (int i = 0; i < input.length; i++) {
    input[i] = j < input.length ? input[j] : -1;
    j++;
    while (j < input.length && input[i] == input[j]) {
      j++;
    }
  }
}

It's getting hard to read again, so let's split the logic for j into its own method:

public static void smoosh(int[] input) {
  int j = 0;
  for (int i = 0; i < input.length; i++) {
    input[i] = j < input.length ? input[j] : -1;
    j = getNextDifferentIndex(input, j);
  }
}

/** Get the smallest integer j such that j > i and input[i] != input[j].
 * If no such element exists, return an integer greater than or equal to
 * input.length. */
private static int getNextDifferentIndex(int[] input, int i) {
  int j = i + 1;
  while (j < input.length && input[i] == input[j]) {
    j++;
  }
  return j;
}

Or if you want to stick to the 14-line limit mentioned in the previous question,

public static void smoosh(int[] input) {
  for (int i = 0, j = 0; i < input.length; i++, j = getNextDifferentIndex(input, j)) {
    input[i] = j < input.length ? input[j] : -1;
  }
}

private static int getNextDifferentIndex(int[] input, int i) {
  int j = i + 1;
  while (j < input.length && input[i] == input[j]) {
    j++;
  }
  return j;
}


Project Euler # 95 in Haskell - kind-of finding longest cycle in a graph

If something can't happen, put your money on it and make it crash if it does anyway instead of silently carrying on.

maximumOn deserves its own name to lift our burden of manual tuple juggling.

Adding elements to the end of a list smells. Let me reverse the list order to fix that.

The scanl with the booleans looks degenerated, there must be a better way - let me undo its introduction. The booleans can be replaced with conditional recursion. The set need not be returned in the cases that used to return True. The list entries that are to be later returned need not be passed deeper into the recursion - and then the list need not be passed down at all. Incidentally, this restores the original list order.

Let's look what I got so far:

maximumOn f = fst . maximumBy (comparing snd) . map (id &&& f)

main :: IO ()
main = print $ maximumOn amicableChainLength [2..lim] where
  amicableChainLength x
    | sumOfProperDivisors x == x = 1 -- perfect numbers
    | otherwise = (\list -> case elemIndices (last list) list of (a:b:_) -> b - a)
      $ include x Set.empty
      $ iterate sumOfProperDivisors x
  -- tries to include number into set/list and also tell when to stop
  include x set (n:ns)
    -- number is member of observed numbers
    | Set.member n set = if x==n
        then [n] -- chain should start at that number
        else error "otherwise no meaning"
    -- this cannot be answer since we are required to find minimum element of that chain
    | n > lim || n < 2 || n < x = error "out of bounds or an number earlier encountered"
    -- New number, add it & continue
    | otherwise = n : include x (Set.insert n set) ns

This code kinda looks like the error cases do happen regularly. Were your comments under the assumption that we are currently looking at the x that is going to win the maximumBy contest? Let me use list comprehension syntax to skip through erroring xs without hacking our way through the data we happen to be working with too much. (Sadly this requires pulling back of parts of maximumOn.) Also the perfect numbers case seems to be subsumed by the other. Also the last element of the list is x if we're interested in it. Also the two positions of x are always in the front and back so we can just compare lengths, and we need not even pass the list out of include.

main :: IO ()
main = print $ fst $ maximumBy (comparing snd)
  [ (x, l)
  | x <- [2..lim]
  , let Just l = include x Set.empty $ iterate sumOfProperDivisors x
  ] where
  -- tries to include number into set/list and also tell when to stop
  include x set (n:ns)
    -- number is member of observed numbers
    | Set.member n set = if x==n
        then Just 0
        else Nothing
    -- this cannot be answer since we are required to find minimum element of that chain
    | n > lim || n < 2 || n < x = Nothing
    -- New number, add it & continue
    | otherwise = (+1) <$> include x (Set.insert n set) ns

I now notice that list comprehensions don't actually use the Alternative instance of lists within let expressions. Ah well, since the Ord instance for Maybe happens to make Nothing smaller than Just anything, I can get rid of the list comprehension again, and restore maximumOn!

main :: IO ()
main = print $ maximumOn (\x -> include x Set.empty $ iterate sumOfProperDivisors x)
  [2..lim] where
  -- tries to include number into set/list and also tell when to stop
  include x set (n:ns)
    -- number is member of observed numbers
    | Set.member n set = if x==n
        then Just 0
        else Nothing
    -- this cannot be answer since we are required to find minimum element of that chain
    | n > lim || n < 2 || n < x = Nothing
    -- New number, add it & continue
    | otherwise = (+1) <$> include x (Set.insert n set) ns

n<2 is subsumed in n<x, the chain length is monotonous with the set size, and do notation feels like it might help with include.

main :: IO ()
main = print $ maximumOn (\x -> include x Set.empty x) [2..lim] where
  -- set keeps track of previously seen numbers
  include x set n = do
    guard $ n <= lim && n >= x
    if Set.member n set
      then guard (x == n) >> Just (Set.size set)
      else include x (Set.insert n set) (sumOfProperDivisors n)

I have a hunch there's a way to decompose include completely, but I don't see it.


Should I call this extension method Remove or RemoveMany?

Your method is removing a collection of entities that exist in some set.

When I see Remove, I'd say it removes a single item from something. Now if that collection actually existed in the set, then it would be perfect, but alas it's a collection of items to remove.

One thing to consider, assuming you're making an extension method for the EF5 DbSet, it already has a Remove method that removes a single item, I think an overload to remove more items doesn't sound like a bad idea to me.

On the other hand, LINQ to XML defines a Remove() method on enumerables of XNode.  But that's an extension on the collection of entities, not the parent set.  I'm a little on the fence on this one.

RemoveMany, while better as it indicates we're removing many items, doesn't fit well with me.  It mimics SelectMany by name but I'd associate the "Many" part with a projection, certainly not with a remove operation.  I'd avoid that one.

I might consider ExceptEntities to be similar to the LINQ method Except.  Except returns the set difference of two collections where the result contains unique values.  Since this operation isn't quite the same, we'll still need to make this distinguishable hence the added "Entities".  Since you are dealing with a set (?), this sounds perfect to me.  But after thinking about this more, I'm not quite sure this is the better option since this modifies the collection.

I think RemoveEntities might be a better fit.  "Remove" makes it sound as though we're modifying something.  RemoveAll doesn't cut it for me as it is named the same as List.RemoveAll which removes all that matches a predicate.  There's also a List.RemoveRange which removes a range of consecutive values in the collection, not quite the same.

So I'd go with RemoveEntities but an overload of the Remove name might be fine, just beware of the similarities of the names in other objects.


Rewrite from .. where .. select to more compact one

This can be accomplished with a slight modification to your method signature and an extension method:

Here, the signature now can return null if there are no records selected:

public DateTime? GibSomeStartDate(IEnumerable<int> partnerNumbers, DateTime startTime)
{
    return (from contract in this.databaseContext.Contract
         where partnerNumbers.Contains(contract.Pnr) && contract.SomeDateTime >= startTime
         select contract.SomeDateTime).SafeMin(someDateTime => (DateTime?)someDateTime);
}

This extension method will trap Min's exception and return null instead:

public static U? SafeMin<T, U>(this IEnumerable<T> source, Func<T, U?> selector) where U : struct
{
    try
    {
        return source.Min(selector);
    }
    catch
    {
        return null;
    }
}


Template with boost::operators extremely verbose and repeating

Easy, with default template arguments:

template < class _Coeff,
       unsigned _nVars,
       typename _Expo=int,
       template <class, class> class _Map = _Map
       typename Poly = Polynomial<_Coeff,_nVars,_Expo,_Map>,
       typename Pair = std::pair< std::array<_Expo,_nVars>, _Coeff > >
class Polynomial
      : boost::ring_operators< Poly
      , boost::addable       < Poly, _Coeff
      , boost::addable       < Poly, Pair
      , boost::subtractable  < Poly, _Coeff
      , boost::subtractable  < Poly, Pair
      , boost::multipliable  < Poly, _Coeff
      , boost::multipliable  < Poly, Pair
                > > > > > > > {


CSVReader
Reading a CSV file can be a complex task.  While many CSV files are just comma-separated-values, if a value contains a comma, it would be surrounded by double quotes, and if the value contains double quotes, the double quotes themselves are doubled.
To handle these more that just a basic CSV files, you really should use a CSV library, such as OpenCSV (com.opencsv:opencsv:5.0) or Apache Commons CSV (org.apache.commons:commons-csv:1.7).
HTML
Valid HTML
Your code essentially just writes
...table data...
.  This isn't proper HTML.  You're missing ... tags around the entire document, and ... around the content.  You should probably also have a ..., perhaps with a nice <title>...</title>.
Escaping
If your CSV data contains any special characters, like <, >, and &, you really must escape them in the generated HTML table.
Table Headings
It looks like the first line of your table contains headings, not data.  The first table row should probably be formatted with ...	 tags instead of ...	 tags.
Line by Line processing
You are reading the entire CSV file into memory, and only when it has been loaded in its entirety are you writing it back out as HTML.  This is very memory intensive, especially if the CSV file is huge!
Instead, you could:

open the CSV
open the HTML file
write the HTML prolog
for each line read from CSV file:

format and write line to HTML file

write HTML epilog

Untested, coding from the hip, without handling quoting in CSV or escaping any HTML entities in output:
        try (BufferedReader reader = new BufferedReader(new FileReader(csvFile));
             FileWriter writer = new FileWriter(outputFile)) {

            writer.write("
\n");

            String currentLine;
            while ((currentLine = reader.readLine()) != null) {
                writer.write("
");

                for(String field: currentLine.split(","))
                    writer.write("" + field + "	");

                writer.write("
\n");
            }

            writer.write("
\n");

        } catch (IOException e) {
            e.printStackTrace();
        }

XML & XSLT
You may want to consider creating a CSV to XML translator.
Your XML output might look like:
<data input-file='ExampleInput.csv'>
  <person>
    <Name>Ulbrecht</Name>
    <Vorname>Klaus Dieter</Vorname>
    <Alter>12</Alter>
  </person>
  <person>
    <Name>Meier</Name>
    <Vorname>Bertha</Vorname>
    <Alter>102</Alter>
  </person>
</data>

And then you could use an XSLT Stylesheet to translate the XML to HTML, possibly in a browser without ever writing the HTML to a file.


Binary search tree implementation in golang

Some quick remarks:

The type BNode is public, but the insert function isn't. This is quite strange.
insert(null, 0) causes a panic. That's no good.
&BNode{data: data, left: nil, right: nil} can be just &BNode{data: data} since the default value for a pointer is null.
How would someone use a tree once you've added members to it? I'm guessing you have more functions than just insert, so would be good to share these as well.

You may want to have a separate type for the tree (that just contains a root) - this is a clean way of handling the empty tree case. In addition, insert seems more suitable as a method rather than a function, bringing the final result to something like this:

type BTree struct {
    root  *node
}

type node struct {
    left  *node
    right *node
    data  int64
}

func (t *BTree) Insert(data int64) {
    if t.root == nil {
        t.root = &node{data: data}
    } else {
        t.root.insert(data)
    }
}

func (n *node) insert(data int64) {
    if data <= n.data {
        if n.left == nil {
            n.left = &node{data: data}
        } else {
            n.left.insert(data)
        }
    } else {
        if n.right == nil {
            n.right = &node{data: data}
        } else {
            n.right.insert(data)
        }
    }
}

Usage:

var tree BTree
tree.insert(50)


Python / Numpy running 15x slower than MATLAB - am I using Numpy effeciently?

In the heat function, simply vectorizing the inner loop, drops the time from 340 sec to 56 sec, a 6x improvement.  It starts by defining the first column of Z, and calculates the next column from that (modeling heat diffusion).

def heat(D,u0,q,tdim):
    xdim = np.size(u0)
    Z = np.zeros([xdim,tdim])
    Z[:,0]=u0;
    for i in range(1,tdim):
        #for j in range (1,xdim-1):
        #    Z[j,i]=Z[j,i-1]+ D*q*(Z[j-1,i-1]-2*Z[j,i-1]+Z[j+1,i-1])
        J = np.arange(1, xdim-1)
        Z[J,i] = Z[J,i-1] + D*q*( Z[J-1,i-1] - 2*Z[J,i-1] + Z[J+1,i-1] )
    return Z

some added improvement (10x speedup) by streamlining the indexing

    Z1 = Z[:,i-1]
    Z[j,i] = Z1[1:-1] + D*q* (Z1[:-2] - 2 * Z1[1:-1] + Z1[2:])

Better yet.  This drops time to 7sec, a 45x improvement.  It constructs a matrix with 3 diagonals, and applies that repeatedly to the u vector (with a dot product).

def heat(D,u0,q,tdim):
    # drops time to 7sec
    N = np.size(u0)
    dq = D*q
    A =  np.eye(N,N,0)+ dq*(np.eye(N,N,-1)+np.eye(N,N,1)-2*np.eye(N,N,0))
    Z = np.zeros([N,tdim])
    Z[:,0] = u0;
    # print u0.shape, A.shape, (A*u0).shape, np.dot(A,u0).shape
    for i in range(1,tdim):
        u0 = np.dot(A,u0)
        Z[:,i] = u0
    return Z

Based on further testing and reading, I think np.dot(A,u0) is using the fast BLAS code.

For larger dimensions (here xdim is only 25), scipy.sparse can be used to make a more compact A matrix.  For example, a sparse version of A can be produced with

sp.eye(N,N,0) + D * q * sp.diags([1, -2, 1], [-1, 0, 1], shape=(N, N))

But there isn't a speed advantage at this small size.


Interp1 linear extrap from Matlab to C++

duplicated math

The two statements

double res = y0 + (y1 - y0)*(x - x0) / (x1 - x0);

and

double res = y0 + ((x - x0) / (x1 - x0)) * (y1 - y0);

are equivalent.

They both expand to

$$\frac{x y_0-x y_1+x_0 y_1-x_1 y_0}{x_0-x_1}$$

as can be seen in W\$\alpha \$ of the first and W\$\alpha \$ of the second (as the alternate forms are neatly in the same location, you can toggle between both tabs)

Even without the additional brackets around ((x - x0) / (x1 - x0)), it would still be the same thing.

That's somewhat plausible I'd say, because no matter if you are interpolating or extrapolating, you are still applying the formula for a line and that's the same whether you are between two points that define the line or outside of them.

duplicated code

For the code, that means the following block is a duplicate:

//y = y0 + (y1-y0)*(x-x0)/(x1-x0);
double y0 = varSurf[i];
double y1 = varSurf[i + 1];
double x = detail_sensativity;
double x0 = alpha[i];
double x1 = alpha[i + 1];
double res = y0 + (y1 - y0)*(x - x0) / (x1 - x0);
return res;

To simplify your code, move the block to the end. All code beforehand basically just figures out the right index i to use, then perform the code block. Here's an untested implementation of that. (only last else part of your code shown) // !!!!!!!!!! indicates lines of significant change.

else // we need linear interpolation/extrapolation.
{
    double max = *std::max_element(alpha.begin(), alpha.end());
    double min = *std::min_element(alpha.begin(), alpha.end());

    size_t i = 0;                                           // !!!!!!!!!!

    if (detail_sensativity >= min && detail_sensativity <= max) //interpolate
    {
        for (; i < alpha.size(); ++i)                       // !!!!!!!!!!
        {
            if (detail_sensativity >= alpha[i] && detail_sensativity <= alpha[i + 1])
            {
                break;                                      // !!!!!!!!!!
            }
        }
    }
    else //extrapolate
    {
        if (detail_sensativity >= alpha.end)
        {
            i = varSurf.end() - varSurf.begin() - 1;
        }
    }

    double y0 = varSurf[i];
    double y1 = varSurf[i + 1];
    double x = detail_sensativity;
    double x0 = alpha[i];
    double x1 = alpha[i + 1];
    double res = y0 + ((x - x0) / (x1 - x0)) * (y1 - y0);
    return res;
}

Changes I made:

moved intreaxtrapolation block to the end
used size_t i to top and used it for both cases
used break to end for loop. If you are a real C programmer, you'd shove all the condition of if (detail_sensativity >= alpha[i] && detail_sensativity <= alpha[i + 1]) into the condition of the for loop, just so you could have a loop without a body … just kidding, that wouldn't be very readable.

possible out of bounds error

Not sure if this is correct, just something looking suspicious:

Your loop ends at i < alpha.size();, thus i might end up being as big as alpha.size() - 1, which is the last valid index of the vector. However, you then do double x1 = alpha[i + 1];, which appears to be out of bounds in this case.

code organisation

You are writing a math utility function here. I would not put it into a Model namespace

         v--------------this
double Model::Inte....

I'm not a math expert, but I know that there are other ways to interpolate (cubic, bi-linear, Q-spline, slitherin, yoda, you name it). Maybe your Model asks for linear interpolation, but the function you are posting here is not a member function (assuming Model is a class). It doesn't depend on the state of an object and only uses the parameters passed to it (as far as I can tell). This looks like a free function and should possibly live in some Math namespace (or similar), independent from any Model that's using it.

Math is abstract and the same math is applied in many different fields in many different ways. Keep the abstraction by having the pure math functions separate and not tied to some Model that's interesting to your domain.

naming

It took me quite a while to figure out what the function is doing, because I was wondering what the heck detail_sensativity is supposed to be. Sure there's a typo in it, but still: what does it mean?

double Model::Interp1
(
    const std::vector<double>& alpha,
    const std::vector<double>& varSurf,
    double detail_sensativity
)

It's part of a bigger problem that's related to the former paragraph: you use domain specific names which are very cryptic to anybody outside your field.

I know what an interpolation function should be doing and with the clue that you are trying to duplicate griddedInterpolant(X,V,method) I knew what's going on. With your code alone, that would have been much harder. What is alpha? varSurf? detail_sensativity? And again, given there are many interpolation methods, what is Interp1?

Here's how this could look like:

double Interpolation::linear
(
    const std::vector<double>& x,
    const std::vector<double>& y,
    double x_value
)

simplification

I feel like this code could be simplified further. The case for extrapolation could be included in the for loop without being explicitly coded. After all, extrapolation just means using the same slope as the first and last interpolation steps. Checking max and min values feels like an overcomplication.

handling problematic input

At the moment, there are no error checks. One can happily pass in two std::vectors of different lengths and the algorithm will go bananas.
There should be some error checks.

Also, it could make a lot more sense to use different input parameter types. There's a pair class for example. The x and y values should always come in pairs, so why not do that? (code untested, just to illustrate)

double Interpolation::linear
(
    const std::vector<std::pair<double, double>>& x_y_points,
    double x_value
)

Now you only have to check if the length is > 1. I mean you're having a Model there, so you probably model something. I think std::pair<double, double> models the fact that the values come in pairs pretty well. Definitely more so than having two vectors. You can always provide an overload for the naysayers.


ERP-system with UserForm that transfers data to next available row in an archive spreadsheet

Ouch. I say this in a kind way - the code is painful to read.

Use Option Explicit at the top of every module - always!
Properly indent your code - it makes it easier to read, easier to pick up inconsistent logic and easier to maintain.

Arrays, and Excel's ability to convert values of ranges to arrays is your friend in this instance. No need for loops.

Private Sub CommandButton2_Click()
Dim inputs as Variant 'Variabler for inputs
    inputs = Array(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, _
                   TextBox10.Text, TextBox6.Text, TextBox7.Text, TextBox8.Text, _
                   TextBox9.Text)
    ' order is important for you here.
    ' shipFrom, shipTo, shipDate, NP, desc, gramEx, tareWeight, weight, dims

Dim nextRowB As Range
    Set nextRowB = Sheets("Arkiv").Range("B" & Rows.Count & ":J"& Rows.Count).End(xlUp).Offset(1, 0)
    nextRowB.Value = inputs

    ' Now that we put everything into the array, the individual ranges and the ".copy" is not longer required
    ' sf.Copy nextRowB etc <-- not needed, see line of code above!

Dim ID As Range
    Set ID = Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
    If IsEmpty(Sheets("Arkiv").Range("B2").Value) Then '<-- This is your logic, but not sure if this is really what you want.
    ' Is it really only row 2 that you check?
        MsgBox "Please fill in the <Ship From> box"
    Else
        'Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Offset(1, 0) = "1"
        Sheets("Arkiv").Range("A2").Value = "1"
    End If
    If Not IsEmpty(Sheets("Arkiv").Range("C2").Value) Then ' added "Not" here, why have an empty code block?
    'Else <-- why have an empty code block?
        ID = Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Value + 1
    End If
    Sheets("Arkiv").Activate
    MsgBox "The ID number for this data is: " & Sheets("Arkiv").Range("A" & Rows.Count).End(xlUp).Value
End Sub

Two other things to look at to make this more readable:

Consider assigning "Sheets("Arkiv")" to a variable (e.g. ws) and
using that throughout.
Consider using With Sheets("Archiv") block.

And finally, ensure that all references to range objects and methods are fully qualified. This includes the Rows elements within the Range(...) code.

Edit (From Stack Overflow @AhmedAU, alternate way of inserting the values - this has been tested and works according to OP):

Dim inputs As Variant
inputs = Array(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox10.Text, TextBox6.Text, TextBox7.Text, TextBox8.Text, TextBox9.Text)
Dim nextRowB As Range
Set nextRowB = Sheets("Arkiv").Range("B" & Rows.Count).End(xlUp).Offset(1, 0)
nextRowB.Resize(1, UBound(inputs) + 1).Value = inputs


Count sub-sequences of an array having median lying in that subsequence itself

Don't #include  <bits/stdc++.h> but explicitly include proper requested headers.
Try to limite uses of using namespace std;, it lead to painfull errors and weird bug.
Don't use preprocessor constants. Instead, use const and constexpr values.
Don't use macro, write directly code or use (inline) (constexpr) function  if you use the same code at much places.
Try to return value instead of taking an input reference.
Avoid old array in favour of std::array.
Don't use register keyword in c++
Don't assign 1 or 0 to a bool, use true and false instead.
getchar return int, why trying to convert to T.
Try to use C++ iostream instead of getchar or putchar
Instead of magical values, use const char (eg 'A') to express chars bound..
Use curly braces for your statement
Don't try to be smart putting many statement on the same line, separated by comma. It's not.
The expression n *= -1 can by simplified in n = -n
Don't use for loops if you don't want Initialization+Condition+Operation. It's ugly.
Take care about indents.


Emacs module that generates templates for my blog's static site generator

DRY-ing it up:

It looks like variation is in:

how the filename is obtained
the contents of the inserted text
the name of the file to write to.

Also note that if format is given extra arguments not needed by its format-spec that they are ignored.

So you could define a function which takes 3 arguments: the function to call to get the filename to read from, the file-name to write to, and a the format-spec string.

In order to pass a named function to a method you need to quote it as in the example:

(mapcar '1+ '(1 2 3))

If you want to pass an anonymous function to a function you defined it with #'(lambda ...). For example:

(mapcar #'(lambda (x) (1+ x)) '(1 2 3))

Making a configuration setting

I'd suggest changing your hakyll-site-location function into a variable. Use defvar to define it and then you can simply setq it in your emacs dotfiles.


Handling Many Unexpected States with except

Handling "too many" return statements.

If your linter tells you, that you have too many return statements, this is a hint. A linter is supposed to  support you in writing quality code.
If however your code needs that specific exception handling this is what you need to implement and you can ignore the linter's hint.
I am not sure whether you can break down the code into several methods, each handling only a part of the possible exceptions, since you decided not to share this essential part of the code with us (# Some other stuff that throw meaningful exceptions).

Re-use of exception handlers

If you want to re-use the exception handlers, you can refactor them into the __exit__ method of an appropriate context manager.
Then you can do something like:

@app.route("/sayHello")
def sayHello():
    with ErrorHandler as error_handler:
        name = get_session_data("user", "name")

        # Some other stuff that throw meaningful exceptions

        return someTemplate

    return error_handler.retval

And re-use the respective context manager ErrorHandler accordingly.


Storing temporary data in ETS - for example, using ETS in a web wizard

Yes, using ETS for this sort of temporary data is totally fine, as long as you realize of course that all that intermediate state is lost whenever you restart your server. In fact, if you dig into Phoenix and Elixir a bit, you will see a lot of ETS usage - it's not so much a thing you turn to in exceptional circumstances, but more a tool in the extensive toolbox at the same level of, say, GenServer.


Bubble or Insert?

#1 and #2 are both implementations of insertion sort (*).  The way you insert the element is not so important: whether you copy one by one, use arraycopy, or bubble it down is up to implementation.  I'd imagine arraycopy to be the best for larger inputs.

#3 would be closer to selection sort, a relative of insertion sort, though there's no advantage in allocating a new array. (Or maybe I misunderstand.)

Both build a sorted part in the array, guaranteeing that at step i, array[0..i] is sorted.  Both do their sorting in-line, not requiring extra array allocations.  And both select an element from the unsorted part and then insert it.  The difference between insertion and selection is in how they select the next element to be inserted.

Insertion sort doesn't care which element is next, so it selects whichever.

Selection sort specifically select the littlest element from the rest of the array.  This makes it more costly, but adds the additional guarantee that not only is array[0..i] in order, but it also contains the littlest elements of the entire array.

(*) Though #1 is related to bubble sort in a way his parents won't talk about.

Optimise?

A strong point of insertion sort is that it performs very well for input that is already (mostly) sorted.

#1 unconditionally runs in quadratic time: i:[0..len-2], j:[i+1..0], which is in the order of n² - n steps.

#2 is smarter about it, and doesn't run back comparing if it won't need to.  This means it has the potential to run in close to linear time.  Specifically, it will be in the order of n + d*n steps, with d being the number of elements out of order.

#1 can be 'fixed' with a simple addition:

for (...) {
    for (...) {
        if (cond) {
            swap;
        } else {
            break; // <--
        }
    }
}

... or, depending on your style preference:

for (...) {
    for (... && cond) { // <-- as in #2
        if (cond) {
            swap;
        }
    }
}

... after which it's pretty much the same as #2.


Is the signature of the function imposed ? Your solution would work for any kind of iterable objects and would be probably more idiomatic than passing a pointer and a size. Also, the logic would work for any (comparable) types and not just int so it might be worth making it a templated function.
In your search of the most common element, do you want to return the number of occurences or the element itself ?
In your sum of the two biggest, I think you can compare to largest only once.

You just need to do something like :

   if (arr[i] > secondLargest) {
       if (arr[i] > largest) {
           secondLargest = largest;
           largest = arr[i];
       } else {
           secondLargest = arr[i];
       }
   }


You might change:

void release(T* element, unsigned int index) {
    if (&m_objects[index] != element) {
            std::cerr << "no match index and element\n";
            return; // or exit(1);
    }
    m_occupied_registry[index] = false; // mark the released element as free
    m_releaser(element); // call release functor
}

and at the acquire  change the return line:

    return pointer(&m_objects[index], [this,index](T* element)->void{release(element,index);});

The above will improve the efficiency of the release operation, as you don't need to search for the element.


Compare 2 List to get a List with active players

Please use conventional naming of properties. Chatters instead of chatters for example.

Also, why do you use for instead of foreach if you use index only to get an element of collection? Use foreach and your code will be much clearer.

First thing that should come into your mind when you encounter many Contains and !Contains calls which need to determine if an element should be added into a collection is to use HashSet. Use HashSet<string> for TotalPlayerNames and TC.Chatters.Viewers.

Main problem of your code is a lot of repeating loops and duplications like TC.chatters.viewers[i]. Please learn programming basics and particularly C# basics.

All your code can be rewritten like:

var viewers = TC.Chatters.Viewers;

TotalPlayers.AddRange(viewers.Where(v => TotalPlayerNames.Add(v))
                             .Select(v => new PlayerReal(v)));

var activePlayers = new List<PlayerReal>();
foreach (var player in TotalPlayers)
{
    player.Active = viewers.Contains(player.DisplayName);
    if (player.Active)
        activePlayers.Add(player);
}

ActivePlayers = activePlayers;


Using a for-loop to fill 20 picturebox number 'i' with image

Assuming you have a container for each of your PictureBox controls do the following:

Use a List control:

  List<PictureBox> boxes = new List<PictureBox>();

Search for your picture boxes:

  foreach (Control c in YourContainerName.Controls)
  {
    if (c is PictureBox)
    {
      boxes.Add(c);
    }
  }

Then in your method:

public void afficheuneimagecombo()
{
  foreach (PictureBox pb in boxes)
  {
    Item imguse = new Item();
    pb.Load(imguse.getImage());
    pb.SizeMode = PictureBoxSizeMode.StretchImage;
  }
}


You should separate the actual data from the logic. Make your function capable of working on any QVectorq of QPairs (or pair of QVectors but that's not as normalized).

Variable names a,b,c,d don't make sense. Especially since a and b really ought to be input parameters.

You should be able to get both the min and max with one pass over the list. You'll probably have to write a custom mapreduce-style function.

For the circles in the QGraphicsScene: Are they supposed to have their center at the point in question, or the topleft of their bounding rect?


I've also commented on the julia slack, but just if anyone else is reading, as I see you've not updated the question according to my comments.

You can see Julia's general performance tips here. I suggest you read this. You are falling into at least two of the performance gotchas:

You are initializing dUx, dUy and dUz as Ints first, but change their type to Float64s in the first assignment. That trips the compiler. The solution is to initialize them to 0.
You are using degree and CS that appear to be captured global variables, which makes it impossible for the compiler to specialize. The solution is to pass them as arguments to the function.

Not that the second issue also means that your code is not runnable, because we don't have access to degree and CS. If your code is not runnable it's very hard to comment on.

Here's what you can do yourself to fix this:

Use the Traceur.jl package to check your code, using @trace func(). That will check your code for the common performance gotchas.
Use the BenchmarkTools package (with @btime) to evaluate any improvements.
Once you've done that, use the Profile module (or even better, Juno's inbuilt profiler to see which lines in your code are slow.

Once you've done that, if you still have problems, please comment here with the results from the profiler, and update your code to be runnable, and we'll be happy to take a look again.


Push an item onto the end of array in Java

Is this really needed?

int[] newArray = (int[]) Array.newInstance(oldArray.getClass().getComponentType(), len + 1);

I would do something like:

public static int[] arrayIntPush(int item, int[] oldArray) {
    int len = oldArray.length;
    int[] newArray = new int[len+1];
    System.arraycopy(oldArray, 0, newArray, 0, len);
    newArray[len] = item;

    return newArray;
}

So for an array of length 10 you make a new array or length 11, copy all existing data into it and then assign the last index to the item.


Project Euler problem 37: truncatable primes

Some small notes on style:

if h.prime? == true should be if h.prime?; never use method? == true or method? == false, use if and unless.
I would replace your if h.prime? with next unless h.prime? and unindent the entire inner block; I hate having the entire body of your loop wrapped in a single if statement.
You should really, really choose better variable names. Single character names are a terrible practice. This is borderline obfuscated, who wants to figure out what a blob of uncommented difficult to read code does, in order to help you improve its performance?

Here's a simple refactor which is (on my system) 4x faster than your code, mostly because I'm aborting the outer loop early if the first inner while fails:

#!/usr/bin/ruby -w

require 'prime'

h, y, x = 9, 0, 0

while x < 11
  h += 2
  next unless h.prime?

  boo, f, n, c = true, 0, h, 0

  while n > 0
    f += (n % 10) * 10 ** (10 - c)
    n /= 10
    boo = false if !n.prime? && n != 0
    c += 1
  end

  # Don't keep checking if we already know this number fails
  next unless boo

  n = h
  c = 10

  while c > 0
    n %= (10 ** c)
    boo = false if !n.prime? && n != 0
    c-=1
  end

  f /= 10 while f % 10 == 0

  if boo
    y += h
    x += 1
    p h
  end
end

p y


Took this from your blog post:

  What I need to do is this:

  take a directory on the URL, which by default will be the current directory;
  list the files / directories;
  for each entry, convert the filesystem path to a URL, using the current HTTP host and port;
  also provide a "parent directory" link too, for browsing upstream.

Knowing these requirements, your code is way too complicated. That's quite normal for a beginner with PHP, so it's no problem. PHP offers built-in solutions that from time to time make experienced PHP programmers think: "Why didn't I find that before?" -- So what you missed, is glob(), and maybe some other neat functions.

// Directory to create listing for, defaulting to the current one
$dirCurrent = '';
if (!empty($_GET['dir'])) {
    // Remove leading and trailing slashes
    $dirCurrent = trim($_GET['dir'], '/.');
}
if (!empty($dirCurrent)) {
    $dirCurrent .= '/';
}
$dirBase = realpath($_SERVER["DOCUMENT_ROOT"]);

// Since we make $dirCurrent relative, a basedir check is not needed
if (is_dir($dirBase . '/' . $dirCurrent)) {
    // Provide a link to go up a level
    if (!empty($dirCurrent)) {
        $parentDir = dirname($dirCurrent);
        $parentLinkUrl = $_SERVER["SCRIPT_NAME"] . "?dir=" . $parentDir;
        echo "[Parent Directory]
";
    }
    echo "
";
    foreach (glob("$dirBase/$dirCurrent*") as $entry) {
        // Hidden files (those starting with a dot) are not returned by glob
        $linkText = basename($entry);
        if (is_dir($entry)) {
            // We just want to link back to this file, passing the dir
            $linkUrl = $_SERVER["SCRIPT_NAME"] . "?dir=" . urlencode($dirCurrent . basename($entry));
            $linkText .= "/"; // Just to make it more clear it's a dir
        } else {
            // we want a link to the actual file
            $linkUrl = $dirCurrent . basename($entry);
        }
        echo "
$linkText
";
    }
    echo "
";
} else {
    header("HTTP/1.0 404 Not Found");
}


Tell your instructor to become familiar with the Standard Guidelines.  You can find presentations on youtube where Stroustrup introduces this as a keynote speech, and many others speaking on them since.

Don’t use naked new (and delete).  Make your vector of unique_ptr instead.

The srand48 is not a standard function.  And the old C rand/srand are infamous for poor quality random numbers.  See the <random> header file.

Why does one location use 0. (funny way to write 0.0, a double) and the other use 1 as an int?

You don’t need to put private: at the top of the class; that is assumed.

Does visit modify the object? You did not make it const.  Also, use the override keyword in the derived version!  That is very important in real code for maintainability as well as error checking.

for(int j=0; j<10; j++)  v.push_back(Location());

Did you know that vector elements are always initialized? And what will it use do you suppose?  The default constructor of the element, of course!

So just write:  v.resize(10+v.size())  to add 10 default locations to the end.

Location a(0.1, 0.1);

Use uniform initialization syntax.

Location a{0.1, 0.1};

Thou hast scribed an olde dialect.  You’re using the ranged for loop so your textbook must be written after 2011; perhaps it is just a slightly updated lesson plan from 1998?

Location() {
    x_ = drand48();
    y_ = drand48();
}

A random-initialized location might be handy for this specific program, but it’s sufficiently bizzare that it hinders the understanding of the code.  Make a function to return a random location instead!

double getx() {return x_; }
bool operator<(const Location & L) { return x_ < L.x_; }

You are definitly missing const on your member functions.

Writing good relational operators is a whole lesson and not the point here — this is probably fine for the class as it stands, but reviewers will wonder why you didn’t make it a non-member and supply all the relational and equality operators.

Since the (partial) ordering exists specifically for your algorithm, you might want to make it a named function instead. Consider the future maintainer that writes a test using > and then has to figure out why it didn’t compile, and of course documenting that less means East and is not a complete ordering.

double distance(const Location & L) {
    return std::sqrt(std::pow(x_ - L.x_, 2) + std::pow(y_ - L.y_, 2));

Besides being const, just call std::hypot.  It will be faster and more accurate.

Salesman(const Location & start, std::vector<Location>::iterator it1, std::vector<Location>::iterator it2)
: start_(start), tobevisited_(it1, it2)
{ }

Very interesting that you allow salesman to be initialized with a segment of a larger vector.  Is that a use case you anticipate (e.g. a huge list divided up among several salesmen)?

It’s enlightened but only part way to what we expect: it is limited to segments of another vector, and can’t take begin/end iterators to locations in general (anything that can be iterated).

Also, you should be using the const_iterator.

Here is the simple/direct way to take that information in the constructor.

      ⋮
    Location start_;
    std::vector<Location> tobevisited_;
public:
    Salesman (start, std::vector<Location> locations)
      : start_{start}, tobevisited_{std::move(locations)}
      { }

Get a post-it note and write using a fat marker, “Can it be const?”. Stick that on the edge of your monitor.


Improve mixin that outputs page-specific CSS

This uses mappings, which are part of Sass 3.3. You can do the same thing without mappings, it's just not as pretty. In addition to allowing multiple selectors, it allows for more options than just light/dark colors (eg. background images, etc):

$themes:
    ( blog:
        ( default: red
        , light: lighten(red, 20%)
        )
    , portfolio:
        ( default: orange
        , light: lighten(orange, 20%)
        )
    , profile:
        ( default: green
        , light: lighten(green, 20%)
        )
    , impressum:
        ( default: blue
        , light: lighten(blue, 20%)
        )
    );

@mixin themify($property, $color: default) {
    @each $theme, $colors in $themes {
        .page--#{$theme} & {
            #{$property}: map-get($colors, $color);
        }
    }
}

.foo, .bar {
    @include themify(background-color);
    @include themify(color, light);
}

Output:

/* line 27, ../sass/test.scss */
.page--blog .foo, .page--blog .bar {
  background-color: red;
}
/* line 27, ../sass/test.scss */
.page--portfolio .foo, .page--portfolio .bar {
  background-color: orange;
}
/* line 27, ../sass/test.scss */
.page--profile .foo, .page--profile .bar {
  background-color: green;
}
/* line 27, ../sass/test.scss */
.page--impressum .foo, .page--impressum .bar {
  background-color: blue;
}
/* line 27, ../sass/test.scss */
.page--blog .foo, .page--blog .bar {
  color: #ff6666;
}
/* line 27, ../sass/test.scss */
.page--portfolio .foo, .page--portfolio .bar {
  color: #ffc966;
}
/* line 27, ../sass/test.scss */
.page--profile .foo, .page--profile .bar {
  color: #00e600;
}
/* line 27, ../sass/test.scss */
.page--impressum .foo, .page--impressum .bar {
  color: #6666ff;
}

However, as you can tell from the output, it generates fairly inefficient CSS if you're using more than one property per selector.  You can deal with this by manipulating global variables (again, 3.3 syntax):

$colors: null; // private, don't touch

$themes:
    ( blog:
        ( base: red
        , light: lighten(red, 20%)
        )
    , portfolio:
        ( base: orange
        , light: lighten(orange, 20%)
        )
    , profile:
        ( base: green
        , light: lighten(green, 20%)
        )
    , impressum:
        ( base: blue
        , light: lighten(blue, 20%)
        )
    );

@mixin themify {
    @each $theme, $c in $themes {
        .page--#{$theme} {
            $colors: $c !global;

            @content;
        }
    }
}

@function theme($color: base) {
    @return map-get($colors, $color);
}

@include themify {
    .foo, .bar {
        background-color: theme(base);
        color: theme(light);
    }
}

Output:

/* line 42, ../sass/test.scss */
.page--blog .foo, .page--blog .bar {
  background-color: red;
  color: #ff6666;
}

/* line 42, ../sass/test.scss */
.page--portfolio .foo, .page--portfolio .bar {
  background-color: orange;
  color: #ffc966;
}

/* line 42, ../sass/test.scss */
.page--profile .foo, .page--profile .bar {
  background-color: green;
  color: #00e600;
}

/* line 42, ../sass/test.scss */
.page--impressum .foo, .page--impressum .bar {
  background-color: blue;
  color: #6666ff;
}


Close on destruction

You shouldn't need to explicitly close your file member on destruction. Since it's a safe variable and not an unsafe pointer, fstream's own destructor will be called and the file will be closed.

Const members

You should make path const, since it doesn't change over the course of the object's lifetime.

File object scope

inFile is not opened in the constructor, and it's always used in open/close pairs in your methods. That means that it shouldn't be a member at all; just use local variables. One benefit is that you won't need to explicitly close those files; when the variable goes out of scope the file will be closed.

Error handling

If you want to drink more of the OOP kool-aid, you shouldn't be using boolean return values, which is a pattern inherited from C code. Instead, your methods would be void-typed, and you'd throw an exception if something goes wrong.


Interesting question, in that you gave away most of the answer in this function:

    function changeName(imgName) {
       var pos = imgName.indexOf("_");
       var first = imgName.substring(0,pos);
       return first.concat("","_unselected.png");
    }

You know that all unselected images end with "_unselected.png" and by extension you know that all selected images end with "_selected.png". As a side note I would not have used indexOf, and substring, I would have used a split and string concatenation thru +:

    function deriveUnselectedVersion( imagePath ){
       var firstPart = imagePath.split("_")[0];
       return firstPart + '_unselected.png';
    }

I am not 100% confident about deriveUnselectedVersion but it sure sounds better (and is more meaningful) than changeName.

Anyway, this is how I would write the click handler:

 $(".tt").click(function(event) {
       var image = event.target,
           title = image.getAttribute("title"),
           sourceInfo = image.getAttribute("src").split("_"),
           base = sourceInfo[0],
           version = sourceInfo[1];

       resetOtherImages(title);

       if( version == "selected.png" ){
         $(this).attr('src', base + "_unselected.png");
       } else {
         $(this).attr('src', base + "_selected.png");
       }

       //Or we could go really (too) fancy
        $(this).attr('src', base + ( version == "selected.png" ? "_unselected.png" : "_selected.png" ) );

    });

You will notice:

No missing semi colons at the end of statements
1 var statement on top to rule them all
Only 1 $() statement executed (these are expensive)
This will work for all new buttons as long they follow the same naming scheme
Much shorter
I am still ambivalent about using var title, since title is used in only one place..

A final advice is that writing code follows the same rules as writing prose, dont repeat yourself (too much) aka DRY.

    function resetOtherImages(title) {
    $('.tt').each(function(){
        if($(this).attr('src') !== title)
        {
          var newName = changeName($(this).attr('src'))
          $(this).attr('src',newName)
        }
    });
    }

See how many times you repeat $(this).attr('src') ? You can and should do better than that.


My first login class in PHP with PDO and bcrypt

Your class manages Users. Its job is to handle users. So connecting to a database is not its job! Inject the database connection to the class like so:

public function __construct(\PDO $connection) {

Return values from __construct() are discarded when used from new Object.
When you return, the function ends. So in your LogIn method anything after return $data won't run. Basically, you won't verify the password, and $data will almost always mean true when checked against a boolean. (Basically, you are accepting any password to an existing account).
password_verify() returns a boolean, you can simplify to:

return password_verfiy($pass, $hash);

A user's logged in status should normally not be kept in the database, but in a session.
There's no point in initializing variables with '' if you're immediately overwrite those values with other literals. (It only makes sense if you append data to them in a loop or something similar).
Using stripslashes() and strip_tags means that passwords with certain characters in them would be changed. You don't care about a password having HTML tags because you are not displaying that password as HTML, ever.
if (SOMETHING == true) can be simplified to if (SOMETHING).
If you determined that the class's responsibility is to manage the authentication of your users, all of the authentication logic should be in that class. It's pointless if you do it outside the class :)
What's the point of a token in a session? A token is usually used in a cookie for the purpose of "remember me". It has no meaning in a session.
"Not logged out" is not really a good error message. Explain what went wrong.
Coding style, spacing and indentation - functionNames() and $variableNames should be camel cased, ClassNames should be camel caps. Indent your lines according to the structure block they are found in. Sometimes you use param,param,param and sometimes param, param, param. Pick one and stick with it.


There're several places you could optimize your code.

First, though, I suggest profiling your current code, so you'd know which are your bottlenecks, and where you should concentrate your efforts.

The detection of the black pixels is a CPU intensive process, which means it could benefit from the techniques mentioned above.

The copying of the black pixels, on the other hands, is an I/O intensive process, which you can optimize in two ways:

Instead of copying the pixels as they are discovered to the other window, build a data structure - in memory - that represents the data for this other window, and then do the copy as one memory image copying, instead of a set of single pixels. Or,
Break the pixel copying into several threads/processes that will work in parallel. Note that this may not be possible, depending on your algorithm.


Concatenating CSV filenames into a single file

As soon as you find an outdated file,
you can break out from the first loop:

    foreach ($scripts_array as $script) {
            if (filemtime($script) > filemtime($cached_script)) {
                $cache_expired = true;
                break;
            }
    }

And instead of accumulating the script content in a variable,
you can write to a file and echo directly:

if ($cache_expired) {
    unlink($cached_script);
    foreach ($scripts_array as $script) {
        $script = '/public_html/assets/scripts/' . $script;
        if (file_exists($script)) {
            $content = @file_get_contents($script);
            file_put_contents($cached_script, $content, FILE_APPEND);
            echo $content;
        }
    }
} else {
    echo @file_get_contents($cached_script);
}


Okay, let me point out some stylistic things first:

Doing traceback.print_exc() in an except block feels somewhat odd. Either you hide the stack trace by printing your own error message—which is actually helpful to the end user—or you leave the exception as it is.
Exceptions should be caught locally near to the code which may raise them. So having a big try block with that many lines is not really a good idea. Especially when you are catching all exceptions in the end—you are just hiding stuff that could be totally your fault.
The finally is useless? If you want to do nothing in a block, then use pass; but in your case, you can just leave the finally block out.
For exceptions your program could actually recover from, you really should do exactly that. When the user gets prompted for a number and enters something else, give him an error but let them try again.
In regards to the previous point, you actually have some hint of letting the user try again, with the while number < 0:. However, if the user enters a non-number int() will throw a ValueError and the program will just exit.
Using sys.exit(1) is like shutting your computer down by plugging the cable. Provide a better way to shut down your program. Use the existing exception mechanism to shut it down.
if number == 0: sys.exit(1) — if you’re not accepting a zero either, why don’t you change the while loops condition to “lower or equals zero”?
printlexnum(i, 10, number) — if the second parameter is always a 10, why have it as a parameter?
return — No need to explicitely return from a function when that’s the last statement of the function and no value is specified.

Moving on to the algorithm:

The order is not correct. For example 100 is being sorted after 19, when it should be sorted after 10 (like 10 is sorted after 1).
The for-loop in the “main” program should really be handled by the algorithm too. There should be some high-level printlexnum(n) which just prints all numbers from 1 to n.

The easiest way to get a lexicographic order of numbers is when you sort their string representations because strings are always sorted lexicographically. You can actually do this in a single line:

print('\n'.join(sorted(map(str, range(1, number + 1)))))


Edit one table from another table in a Windows Form DataGridView

As I explain here, you should never initialize reference navigation properties in an entity's constructor. They prevent EF from loading the reference from the database and they impair relationship fixup.

This initialized navigation property ties your Person class to one specific use case: setting Sobriquet. For other cases where loading of the Nickname is required, it has become useless, or crippled at best.

Another downside of your implementation is that you'll never see a Sobriquet until you set it, because _sobriquet will never be set by EF. (I assume that the real property has a [NotMapped] attribute; it can't possibly be mapped).

And then of course there is this golden rule to keep unexpected behavior and side effects away from property setters (and getters, for that matter). By setting Sobriquet, one expects to set Sobriquet only. It is not expected that NickName.PersonId is set too.

Finally, in the two instances where you set NickName.PersonId, i.e. in the property setter and in new NickName(Id), the value of Person.Id can be anything. It's highly unlikely that in every imaginable scenario, Person will have its Id value on time. I'm even pretty confident that in the constructor this will never be the case.

So, as usual, if you want your view to show anything that differs from the model classes, use a view model (or DTO) and map it from/to the model classes, for example using AutoMapper.


if command == 0:
        insort(flips, start)
        insort(flips, end + 1)

Well, the main reason it's slow is insort. As the doc says,

  Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.

That said, there's a significant performance improvement possible here without changing data structure. Flipping coins from a to the end and then flipping coins from a to the end is equivalent to doing absolutely nothing. So rather than always insert, toggle whether or not the value is in flips. I see an execution time reduction from about 30s to about 16s with

def toggle(flips, val):
    idx = bisect_left(flips, val)
    if idx < len(flips) and flips[idx] == val:
        del flips[idx]
    else:
        flips.insert(idx, val)

and

    if command == 0:
        toggle(flips, start)
        toggle(flips, end + 1)

Obviously if you want speed then you need to switch to using a better data structure than a list, but within the constraints of list I think this is fairly efficient.

    elif command == 1:
        flip_start = bisect_left(flips, start)
        flip_end = bisect_left(flips, end + 1)
        flips_temp = flips[flip_start:flip_end]
        insort(flips_temp, end + 1)
        if flip_start % 2:
            insort(flips_temp, start)
        print(sum(flips_temp[1::2]) - sum(flips_temp[:-1:2]))

The first thing that's suspicious here is insort. However, to my surprise, using flips_temp.append(end + 1) and flips_temp.insert(0, start) made things slightly slower. The real speedup comes from eliminating the copying. Careful analysis shows that the logic is equivalent to

    elif command == 1:
        flip_start = bisect_left(flips, start)
        flip_end = bisect_left(flips, end + 1)

        accum = sum(flips[flip_start+1:flip_end:2]) - sum(flips[flip_start:flip_end:2])
        if flip_start % 2:
            accum = -start - accum
        if flip_end % 2:
            accum = accum + end + 1
        print(accum)

This gave me a further speedup from 16 seconds to 12 seconds.

IMO it would make sense to implement the difference of sums using functools.reduce(operator.sub, ..., 0), but that's much much slower (~40 seconds).


Proper integer conversion

Right now, as it stands, you're just converting any user input to a integer, using the int function. What do you suppose happens if the user enters something like "abc"?

What you need to do is set up a try-except block, like this:

try:
    user_integer = input("Enter an integer: ")
    user_integer = int(user_integer)
except ValueError:
    print("You must enter a valid integer!")

To set up something like this in your code, you'd change your code to something like this:

...

while True:
    print("Guess a number between 1 and 100.")
    guess = input()

    try:
        integer_guess = int(guess):

        ...
    except ValueError:
        ...

Tracking the number of "rounds"/"tries"

Rather than printing a message saying that if the user got below a certain amount of tries, they win, you can implement it into the code. The easiest way to do this would be to use a for ... in range( ... ) loop, like this:

rounds = ...
for _ in range(rounds):
    ...

(This has been implemented below, for reference.)

Design

This is not a very extensible design, again, I'd recommend creating a function that allows you to create custom games, like this:

def number_guessing_game(low, high, rounds):
    print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
    number = random.randint(low, high)

    for _ in range(rounds):
        guess = input("Enter an integer: ")

        try:
            integer = int(guess)
            if integer == number:
                print('You won!!!')
                return
            elif integer < number:
                print('Try Higher')
            elif integer > number:
                print('Try Lower')

        except ValueError:
            print("You must enter a valid integer.")

    print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))

An example function call might look like this:

number_guessing_game(1, 100, 6)

In short, all of your code becomes the following:

import random

def number_guessing_game(low, high, rounds):
    print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
    number = random.randint(low, high)

    for _ in range(rounds):
        guess = input("Enter an integer: ")

        try:
            integer = int(guess)
            if integer == number:
                print('You won!!!')
                return
            elif integer < number:
                print('Try Higher')
            elif integer > number:
                print('Try Lower')

        except ValueError:
            print("You must enter a valid integer.")

    print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))

number_guessing_game(1, 100, 6)

Hope this helps!


For a first application in Java, good job!
I have some suggestions for your code.
When using regex, try to uses the java.util.regex.Pattern class instead of the java.lang.String#matches method.
When using the java.lang.String#matches method, the regex pattern is recompiled each time the method is called. This can cause a slowdown in your method execution.
How to uses the matcher
Pattern pattern = Pattern.compile("[*/+-]");
while (true) {
   //[...]
   if (pattern.matcher(operation).matches()) {
      //[...]
   }
   //[...]
}

Extract some of the logic to methods.
Extracting code can make the code shorter and easier to read. Also when you have logic that does the same thing, you can generally move it into a method and reuse it.

You can make a method that asks a question and read the next float; this will allow you to reuse the same method.

public static void main(String[] args) {
   //[...]
   firstNum = askQuestionAndReceiveFloat(scanner, "Type in first number");
   secondNum = askQuestionAndReceiveFloat(scanner, "Type in second number");
   //[...]
}

private static float askQuestionAndReceiveFloat(Scanner scanner, String question) {
   System.out.println(question);
   return scanner.nextFloat();
}

You can extract the logic to parse the operation.

private static String askForOperation(Pattern pattern, Scanner scanner) {
   String operation;
   while (true) {
      System.out.println("Select operation (*,/,+,-)");
      operation = scanner.next();

      if (pattern.matcher(operation).matches()) {
         break;
      } else {
         System.out.println("Invalid operation");
      }
   }
   return operation;
}

If you are using Java 14, you can use the newer version of the switch-case and return the value.

private static float getResult(float firstNum, float secondNum, String operation) {
   return switch (operation) {
      case "*" -> multiply(firstNum, secondNum);
      case "/" -> divide(firstNum, secondNum);
      case "+" -> addition(firstNum, secondNum);
      case "-" -> subtraction(firstNum, secondNum);
      default -> 0;
   };
}

Those's changes will make the main method shorter and easier to read!
Use java.io.PrintStream#printf instead of java.io.PrintStream#println when you have to concatenate
java.io.PrintStream#printf offer you to use patterns to build the string without concatenating it manually. The only downside is you will be forced to add the break line character yourself; in java you can use the %n to break the line (portable between various platforms) or uses the traditional \n / \r\n.
System.out.printf("Result of your operation is %s%n", result);

Refactored code
public static float multiply(float a, float b) {
   return a * b;
}

public static float divide(float a, float b) {
   return a / b;
}

public static float addition(float a, float b) {
   return a + b;
}

public static float subtraction(float a, float b) {
   return a - b;
}

private static float askQuestionAndReceiveFloat(Scanner scanner, String question) {
   System.out.println(question);
   return scanner.nextFloat();
}

private static String askForOperation(Pattern pattern, Scanner scanner) {
   String operation;
   while (true) {
      System.out.println("Select operation (*,/,+,-)");
      operation = scanner.next();

      if (pattern.matcher(operation).matches()) {
         break;
      } else {
         System.out.println("Invalid operation");
      }
   }
   return operation;
}

private static float getResult(float firstNum, float secondNum, String operation) {
   return switch (operation) {
      case "*" -> multiply(firstNum, secondNum);
      case "/" -> divide(firstNum, secondNum);
      case "+" -> addition(firstNum, secondNum);
      case "-" -> subtraction(firstNum, secondNum);
      default -> 0;
   };
}

public static void main(String[] args) {
   Pattern pattern = Pattern.compile("[*/+-]");
   Scanner scanner = new Scanner(System.in);
   float firstNum, secondNum, result;
   String operation = askForOperation(pattern, scanner);

   firstNum = askQuestionAndReceiveFloat(scanner, "Type in first number");
   secondNum = askQuestionAndReceiveFloat(scanner, "Type in second number");
   result = getResult(firstNum, secondNum, operation);

   System.out.printf("Result of your operation is %s%n", result);
}

Also, I suggest to handle the x / 0 case :)


Which products should be purchased with the given amount of money: Hackerrank?

Your algorithm is slow in some cases because of the time complexity O(n^2). (starting the second loop from i+1 makes it twice faster than starting from 0, but it doesn't change the time complexity which has much greater impact on performance)

To improve your time complexity you need to reduce the amount of times you look at items in the array. One way of doing it is by first sorting it (more precisely, sorting index-value pairs to keep record of the original indexing) and then iterating over the sorted array once (O(n)) while taking advantage of the fact that it is sorted. I'll leave you the task of learning about integer sorting algorithms (of time complexity O(n log n)), and only explain how to use the sorted array to find the final answer.

You can look at both edges of the array (smallest and biggest number), if their sum is too small you can increase it by advancing the lower-edge index to look at a bigger number, and if the sum is too big you can decrease it by advancing the higher-edge index to look at a smaller number. Repeat it until you reach the needed sum, then get the original indices and increment them to get the IDs you need for the output.

As @vnp hinted, there is a better solution than mine (with time complexity O(n)) using a hash table.


Nice job!  I hope you find the comments below useful as you progress.

Variable names: Try to have variable names which describe what the variable actually represents or holds.  For example, I have no idea why you named your Scanner "kb".
Method names: Method names should always be verb phrases (actions) which describe what the method does.  So for example, your addition() method might be better named performAddition() or some such.  Even just add() might work, though that might be a bit misleading and lead someone reading your code to believe that all the method does is add two numbers, when really the core functionality is user interface.
Redundancy: Any time you are copy-pasting code, alarm bells should go off in your head.  You do this in multiple places.  Most notable is:

System.out.print("\nFirst Number: ");
nOne = kb.nextInt();

System.out.print("\nSecond Number: ");
nTwo = kb.nextInt();

What that means is that this is a prime candidate for encapsulation into its own method.  Something like this:

private static int[] getNumbers() {
    int[] numbers = new int[2];
    System.out.print("\nFirst Number: ")
    numbers[0] = scanner.nextInt();
    System.out.print("\nSecond Number: ");
    numbers[1] = scanner.nextInt();
    return numbers;
}

Now we can simply call this method whenever we need to get numbers from the user.  Much easier, and we've reduced the complexity of our code.

Another thing that's redundant is your constant re-declaration of kb = new Scanner(System.in).  You really only need to do this once.  If it were me, I'd have it as a static field for the entire class, e.g.,

private static final Scanner STDIN = new Scanner(System.in);

This is the basic rule for how constants are defined in Java.  I named the variable STDIN because this is a convention for referring to the "standard input" stream, but SCANNER or something would be just as good.

Some other small things

You should consider using a switch statement on your choice variable:

switch(choice) {
case 1:
    performAddition();
    break;
case 2:
    performSubtraction();
    break;
case 3:
    performDivision();
    break;
case 4:
    performMultiplication();
    break;
default:
    System.out.println("Invalid choice!");
    break;
}

... or you could write it all in-line, if it looks better to you, since each block only really does one thing:

switch(choice) {
case 1: performAddition(); break;
case 2: performSubtraction(); break;
// etc.
}

This would also be a perfect use-case for enums, but that my be getting a bit too complicated for a starting project.

Small final note: I think you have a bug.  The line where you display the results always says "sum", even when you're doing division, multiplication, or subtraction. :)


Apply a function to each element of a tuple ("map" a tuple)

transform, or map ?

I wouldn't name this function transform, because it's very different from that stl algorithm. std::transform can be used to modify a range in place, and can be called with either unary or binary operations. What you implement is generally called map and has its roots in functional languages; so I would call it tuple_map, for instance. Then the convention is to put the function first in the argument list, and the sequence second.

Or, you could try to implement transform, but then it gets tricky, because there are three "semantic inputs" to be considered: the tuple, its elements and the function signature. I haven't had the time to consider it thoroughly, but I believe that using decltype(fn(std::get<0>(tuple))) as a semantic clue is a good approximation. If it's void, you know that the semantic is at the tuple level; if it's an lvalue reference, you use std::tie to return a tuple of references; if it's an rvalue reference, std::forward_as_tuple is the most adapted; and if it's a value, you can return a new tuple.

A sketch for transform

For instance, with C++ 17 enabled:

#include <tuple>
#include <type_traits>

template <typename Fn, typename Argument, std::size_t... Ns>
auto tuple_transform_impl(Fn&& fn, Argument&& argument, std::index_sequence<Ns...>) {
    if constexpr (sizeof...(Ns) == 0) return std::tuple<>(); // empty tuple
    else if constexpr (std::is_same_v<decltype(fn(std::get<0>(argument))), void>) {
        (fn(std::get<Ns>(argument)),...); // no return value expected
        return;
    }
    // then dispatch lvalue, rvalue ref, temporary
    else if constexpr (std::is_lvalue_reference_v<decltype(fn(std::get<0>(argument)))>) {
        return std::tie(fn(std::get<Ns>(argument))...);
    }
    else if constexpr (std::is_rvalue_reference_v<decltype(fn(std::get<0>(argument)))>) {
        return std::forward_as_tuple(fn(std::get<Ns>(argument))...);
    }
    else {
        return std::tuple(fn(std::get<Ns>(argument))...);
    }
}

template <typename Fn, typename... Ts>
auto tuple_transform(Fn&& fn, const std::tuple<Ts...>& tuple) {
    return tuple_transform_impl(std::forward<Fn>(fn), tuple,
                          std::make_index_sequence<sizeof...(Ts)>());
}

Helper function

I can't see how you would avoid to use a helper function (besides using a tuple_transform function, which you're currently implementing).

You'll see I use a forwarding reference for the function argument, since it can be expensive to copy.

I keep the const lvalue reference for the tuple argument, because it's more simple (a forwarding reference wouldn't allow to constrain the type, and sizeof... wouldn't be possible either), but mainly because I can't see a case where the tuple would be consumed differently as a rvalue reference.