Return total balance from unsorted purchase items that may have specials

Paraphrasing Kent Beck (IIRC), I'd design my types so that concerns that change together are kept together, whereas concerns that change separately should be kept as separate as possible.

With that in mind, I'd start defining shopping basket items as simply as possible:

type Good = { SKU : string; Price : int }

This also enables you to define the price table, independently of the discount rules:

let prices = [
    { SKU = "A"; Price = 50 }
    { SKU = "B"; Price = 30 }
    { SKU = "C"; Price = 20 }
    { SKU = "D"; Price = 15 } ]

// string -> Good option
let scan sku = prices |> List.tryFind (fun x -> x.SKU = sku)

This code snippet also defines a simple scan function that can be used to look up a string in the price table in order to turn it into a Good value.

I don't think modelling the product as a discriminated union (e.g. A | B | C | D) is a good idea, because that's going to make it hard if you want to add an E product, or if you want to remove the C product.

The same type of argument goes for price rules. List prices change according to business decisions, and the same goes for discounts, but at different rates. Discriminated unions define a finite set of options, but I don't think a set of discounts ought to be a finite set of hard-coded options. You should be able to add or remove discount rules according to business decisions.

Instead, I'd be inclined to define a discount with the type Good list -> int * Good list. The idea here is that you input a list of Good values, and you get back a price (int) and the remaining Good values where a price has yet to be calculated.

You can, for example, implement the rule about the A products like this:

// Good list -> int * Good list
let aRule items =
    let xs, others = List.partition (fun x -> x.SKU = "A") items
    let hits, rest =
        xs |> List.chunkBySize 3 |> List.partition (fun l -> l.Length = 3)
    let xTotal = hits.Length * 130
    xTotal, rest |> List.concat |> List.append others

This looks, perhaps, a bit complicated, but it works like this:

First, it partitions all items into A items (xs) and all other items (others).
It then divides xs into chunks of 3. This produces a list of lists, where most of the lists have the length 3. There may, however, be a residual list with one or two items, so these are partitioned into the rest value.
The total for all the hits is calculated. Each hit is a list of three A items, which has the special discount price 130. You may have three, six, nine, etc. A items, so the special price 130 is multiplied with the length of hits, which is a list of lists.
Finally, xTotal is returned, together with all the items that didn't trigger the discount. These include all non-A items, but also residual A items.

Likewise, the discount for B items can be defined in the same way:

// Good list -> int * Good list
let bRule items =
    let xs, others = List.partition (fun x -> x.SKU = "B") items
    let hits, rest =
        xs |> List.chunkBySize 2 |> List.partition (fun l -> l.Length = 2)
    let xTotal = hits.Length * 45
    xTotal, rest |> List.concat |> List.append others

This function is almost identical to aRule, so is a candidate for some refactoring. Here, however, I decided to apply the rule of three, so I left them as is.

Apart from these discount rules, you'll also need a 'default' price calculation rule:

// Good list -> int * 'a list
let defaultRule items = List.sumBy (fun x -> x.Price) items, []

Notice how Good list -> int * 'a list also fits the desired type of Good list -> int * Good list. This enables you to define a set of rules as a list:

// (Good list -> int * Good list) list
let rules = [aRule; bRule; defaultRule]

Calculating a total price is now easy:

// ('a -> int * 'a) list -> 'a -> int
let total rules items =
    let acc (tot, rest) f =
        let tot', rest' = f rest
        tot + tot', rest'
    rules |> List.fold acc (0, items) |> fst

This function performs a left fold over rules, while accumulating the total so far, and the rest of the items.

Tests

This implementation passes all the tests in the original kata formulation:

open Xunit
open Swensen.Unquote

[<Theory>]
[<InlineData("", 0)>]
[<InlineData("A", 50)>]
[<InlineData("AB", 80)>]
[<InlineData("CDBA", 115)>]

[<InlineData("AA", 100)>]
[<InlineData("AAA", 130)>]
[<InlineData("AAAA", 180)>]
[<InlineData("AAAAA", 230)>]
[<InlineData("AAAAAA", 260)>]

[<InlineData("AAAB", 160)>]
[<InlineData("AAABB", 175)>]
[<InlineData("AAABBD", 190)>]
[<InlineData("DABABA", 190)>]

// Incremental
[<InlineData("A", 50)>]
[<InlineData("AB", 80)>]
[<InlineData("ABA", 130)>]
[<InlineData("ABAA", 160)>]
[<InlineData("ABAAB", 175)>]
let ``total returns correct result`` (items : string) expected =
    let actual =
        items |> Seq.choose (string >> scan) |> Seq.toList |> total rules
    expected =! actual

Flexibility

Is this the simplest possible implementation? Most likely not, but it's fairly flexible.

Imagine, for example, that you're being asked to implement a new 'bundle' discount where you get A, B, and C for 85 if you buy them together. You can implement this without changing any of the existing code:

// f:('a -> bool) -> ('a list -> 'a option * 'a list)
let tryFindFirst f =
    let acc (found, others) x =
        match found with
        | Some hit -> Some hit, x :: others
        | None -> if f x then Some x, others else None, x :: others
    List.fold acc (None, []) >> (fun (found, others) -> found, List.rev others)

// Good list -> int * Good list
let bundleRule items =
    let aOpt, rest = tryFindFirst (fun x -> x.SKU = "A") items
    let bOpt, rest = tryFindFirst (fun x -> x.SKU = "B") rest
    let cOpt, rest = tryFindFirst (fun x -> x.SKU = "C") rest
    match aOpt, bOpt, cOpt with
    | Some a, Some b, Some c -> 85, rest
    | _ -> 0, items

As you can see, bundleRule has the desired type, so can be used together with the other pricing rules:

[<Theory>]
[<InlineData("ABC", 85)>]
[<InlineData("BAC", 85)>]
[<InlineData("ABBA", 145)>]
[<InlineData("ABCAA", 185)>]
let ``bundle rule is applied correctly when having high priority``
    (items : string)
    expected =

    let actual =
        items
        |> Seq.choose (string >> scan)
        |> Seq.toList
        |> total (bundleRule :: rules)
    expected =! actual

Notice the test case for ABCAA. This combination fits both the bundle discount, and the triple-A discount. Since bundleRule comes first, however, it wins, and removes ABC from further calculation, thereby correctly preventing the triple-A rule from being applied.

If your business experts ask you to prioritise the triple-A rule over the bundle rule, that's possible as well:

[<Theory>]
[<InlineData("ABC", 85)>]
[<InlineData("BAC", 85)>]
[<InlineData("ABBA", 145)>]
[<InlineData("ABCAA", 180)>]
let ``bundle rule is applied correctly when having low priority``
    (items : string)
    expected =

    let actual =
        items
        |> Seq.choose (string >> scan)
        |> Seq.toList
        |> total [aRule; bRule; bundleRule; defaultRule]
    expected =! actual

In this test, notice that the order of the rules is different. This causes aRule to trigger before bundleRule, and for that reason, the ABCAA test case has a different outcome.

State

Did I just come up with all of this myself? Not quite, I was leveraging my knowledge of functional programming 'design patterns'.

Functions with the type 's -> 'a * 's are part of the State monad. All the price functions have the type Good list -> int * Good list, which make them State 'instances'.

In fact, you can make use of the state monad easier by introducing the standard monadic functions like return, bind, map, and so on. In F#, you can further sprinkle on syntactic sugar by implementing a state computation expression. Here are some notes on doing that.

Sometimes, it helps to define a type alias for the monadic type in question:

type State<'a, 's> = ('s -> 'a * 's)

This isn't strictly necessary, but I think it makes is a bit easier to reason about some of the following code.

Next, you can define a module to implement the most important functions:

module State =
    // 'a -> State<'b,'a> -> 'b * 'a
    let run state (f : State<_, _>) = f state

    // 'a -> 'b -> 'a * 'b
    let lift x state = x, state

    // ('a -> 'b) -> State<'a,'c> -> 'c -> 'b * 'c
    let map f x state =
        let x', newState = run state x
        f x', newState

    // ('a -> State<'b,'s>) -> State<'a,'s> -> 's -> 'b * 's
    let bind (f : 'a -> State<'b, 's>) (x : State<'a, 's>) state =
        let x', newState = run state x
        run newState (f x')

    // 'a -> 'a * 'a
    let get state = state, state

    // 'a -> 'b -> unit * 'a
    let put newState _ = (), newState

    // ('a -> 'a) -> ('a -> unit * 'a)
    let modify f = get |> map f |> bind put

You can define more, but here, I only added the functions I'll need in the coming examples.

The most important functions are lift and bind. Often, in other languages, the lift function is called return, or pure, but both of these are reserved keywords in F#. These two functions define the monad. The rest are useful extra functions (apart from the map function, which could be used to define State as a Functor in Haskell).

Computation expression

Using the functions in the State module, you can implement a computation expression builder for the State monad. Again, I only add the absolute minimum required in order to make the examples below compile:

type StateBuilder () =
    // State<'c,'d> * ('c -> State<'e,'d>) -> ('d -> 'e * 'd)
    member this.Bind (s, f) = State.bind f s
    // 'a -> ('b -> 'a * 'b)
    member this.Return x = State.lift x

As you can see, the Bind and Return methods simply delegate to the State module's functions.

Refactored price functions

With these new tools, you can now refactor the above price functions.

First, I decided to implement a single function that you can use to define n for x discounts:

// int -> int * string -> (Good list -> int * Good list)
let forOnly price (n, sku) = state {
    let! xs = List.partition (fun x -> x.SKU = sku)
    let hits, residual =
        xs |> List.chunkBySize n |> List.partition (fun l -> l.Length = n)
    do! State.modify (residual |> List.concat |> List.append)
    return hits.Length * price }

If you keep in mind the definition of the State type, you can also view this function as having the type int -> int * string -> State<int, Good list>. It can be used like this to define a price rule:

// Good list -> int * Good list  .. or, alternatively:
// State<int, Good list>
(3, "A") |> forOnly 130

Notice that it's possible to use the existing, built-in function List.partition with a let! binding. This is possible because the type of List.partition is ('a -> bool) -> 'a list -> 'a list * 'a list. Notice how 'a list -> 'a list * 'a list can also be viewed as State<'a list, 'a list>. This means that the first let! expression binds xs to the items that satisfy the predicate passed to List.partition, while the items that don't match are being threaded through the computation expression as the underlying state.

Once you've found any residual, you'll need to put it back into the underlying state. You can do this with do! State.modify. Finally, you return the result of the price calculation.

The same sort of refactoring can be done for bundleRule:

// Good list -> int * Good list
let bundleRule = state {
    let! originalItems = State.get
    let! aOpt = tryFindFirst (fun x -> x.SKU = "A")
    let! bOpt = tryFindFirst (fun x -> x.SKU = "B")
    let! cOpt = tryFindFirst (fun x -> x.SKU = "C")
    match aOpt, bOpt, cOpt with
    | Some a, Some b, Some c -> return 85
    | _ ->
        do! State.put originalItems
        return 0 }

Compared to the previous incarnation of bundleRule, this implementation is actually a bit longer, but IMO more readable. Again, the underlying state is implicitly threaded through the computation, but as you can tell, you can retrieve it with State.get and 'write' it with State.put.

I find this version more readable because I don't have to declare intermediary state values (rest) and pass them around. In the previous version, if I forgot to pass them around in the correct manner, the calculation would be incorrect.

It's almost as though the State-based implementation looks more imperative. The same would be the case in Haskell, and there's a saying that Haskell is the best imperative language that exists. Here we see that F# is no slouch either.


Like I've said in an answer to a previous question of yours: implement MVVM. Do not work in the code-behind, instead bind from the XAML in your View to its ViewModel.

But more importantly: first you need to stop using DataTables and start using well-defined objects. Your code already shows that currently you need to add comments to remember that for instance the sixth item of an ItemArray that's attached to your row contains the Company Telephone. Now what if you simply had a List<Company> where each Company had a property called Telephone -- wouldn't that be far easier and less error-prone?

Note that your code still contains the same bad practices we warned about in your two previous questions, e.g. OleDbDataAdapter is IDisposable so it needs to be inside a using. You need to apply our remarks not just to the small bit of code you offer for review, but you need to apply those lessons to all of your code.


On the Database class
In my experience, a language layer never creates a database. It would require a create database privilege for one thing. Although it's sort of OK for the local environment but would you like your live application to connect the database under the root account? I highly doubt so.
Hence I find the create() method superfluous. But just for sake of refactoring I would make the connect method to accept a parameter that would tell it to use or not to use the dbname DSN argument so it could connect with or without setting the database.
What I would rather add to the database class is a handy "prepare and execute in one go" method like:
public function query($sql, $data = []) {
    $stmt = $this->pdo->prepare($sql);
    $stmt->execute($data);
    return $stmt;
}

as it will make all methods of the User class to lose a lot of weight. As a general rule, when you see repetitive code, think of creating a function to do all the repetitions in one go.
Also it would make sense to make $pdo a public property of the database class.
Now to the User class
First of all, I think that all your doubts with static class is for naught. Yes, in theory it's simple to call User::something() from anywhere without the need to pass around the instance of the user class. But... you need to pass around the instance of PDO anyway! The same problem, different angle.
So you can make your code much cleaner and doubtless by making all methods dynamic, and putting the pdo (or rather a Database class) instance inside. Then you will have to pass around the instance of the user class instead of the instance of the PDO class.
Another repetition that can be spotted is two methods that select a user by username. That's nearly identical code! Always try to reuse the code that already exists in your class. Moreover, for some reason login method runs these two identical queries one after another. But why? Is once not enough?
Another problem is signup function. It's a no-go when it just silently returns false when a user exists. It should be vocal about that. The generic solution is to throw a custom built exception that can be caught and conveyed to the user.
On the return values: Most of time it's not needed. After all, what would you do with that return value from the verify() method?
On the names: it is Better to be more explicit with the function names. "verify" is ambiguous - you never can tell what does it verify and why. The same goes for "exists".
The ActiveRecord vs. DataMapper controversy
From the way you are asking, I can tell you already feel the ambiguity of your class, which serves for two purposes at once, being both a user and a User persistence layer. That's always so with the ActiveRecord pattern to which your class belongs even if you don't probably realize that. You even tried to mae a distinction between these two roles, where static methods are manipulating the database and dynamic methods and properties are manipulating the class data.
You need to make just a logical step further and separate these roles explicitly. A better approach to be considered is to split this class in two - User class and a UserMapper class, where the latter one would do all the database work.
the Username controversy
As long as there is an email to identify the user, there is absolutely no sense in using a dedicated username field. In practice, it adds helluvalot of confusion. A user signs up with a user name and n email, then forgets it and signs up again with email as a username and everything becomes so entangled that it makes it really hard for the support staff. Make it only email to identify the user and get rid of that username nonsense completely. In case you plan to use it as a display name then make it a display name that is not used in the login process at all.
The code
So according to the above suggestion I would create three classes. The User itself
<?php
class User {
    public $uid;
    public $username;
    public $email;
    public $hash;
    public $created;
    public $verified;

    public function login($password)
    {
        return password_verify($password, $this->hash);
    }

}

A class with a custom exception
class UserException Extends InvalidArgumentException {}

And a UserMapper class
class UserMapper
{
    private $db;
    private $table = 'users';
    private $class = 'User';

    public function __construct(Database $db) {
        $this->db = $db;
    }
    public function signUp($email, $password)
    {
        if ($this->getByEmail($email)) {
            throw new UserException("User already exists");
        }
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $sql = "INSERT INTO `$this->table` SET `email`=?, `hash`=?";
        $this->db->query($sql, [$email, $hash]);
        return $this->getById($this->db->pdo->lastInsertId());
    }
    public function getByEmail($email)
    {
        $sql = "SELECT * FROM `$this->table` WHERE `email` = ?";
        return $this->db->query($sql, [$email])->fetchObject($this->class);
    }
    public function getById($uid)
    {
        $sql = "SELECT * FROM `$this->table` WHERE `uid` = ?";
        return $this->db->query($sql, [$uid])->fetchObject($this->class);
    }
    public function setVerified()
    {
        $sqk = "UPDATE `$this->table` SET `verified` = 1 WHERE `uid` = ?";
        $this->db->query($sql, [$this->uid]);
    }
}

then it can be used like this
$userMapper = new UserMapper($db);
try {
    $user = UserMapper->signUp('john.doe@sample.org', '12345');
} catch (UserException $e) {
    $error = $e->getMessage;
    // show it back to user, etc
}

$user = $userMapper->getByEmail($_POST['email']);
if ($user && $user->login($_POST['password'])) {
     // authorize
} else {
     // invalid login or password
}


Find minimum value in a BST: using boolean operators, and using conditionals

The aspect of the code that may cause difficulty to those new to Lisp appears to be the fact that in Common Lisp, nil has two meanings.  It's the value of an empty list () and it's also false when used in boolean context.  So when we have something like (or '(1 2 3) ()) the first non-NIL list is returned.  When we use and it returns the last item if all items are true (that is, all lists are nonempty if we pass in lists).  If you keep those facts in mind, you'll see that the first code is both consistent and logical.  See also https://stackoverflow.com/questions/23826145/what-is-the-exact-difference-between-null-and-nil-in-common-lisp

I'd probably write the code the first way because it's a more compact way of expressing what you've done with if and also only evaluates node-l once instead of twice.  But then, I'd still write car instead of first, so maybe I'm a relic of former days as well.  :)


Method or helper function to return objects from EntityFramework with Linq

Besides the naming that should more C# friendly (PascalCase), the application should have a clear separation between data models and view models.

Data models are usually generated automatically in database first scenarios or POCOs classes defined by the programmer (code-first approach) and should be separated from view models or data returned by the service layer which usually consists in aggregated information.

Ok, for your particular case, data model is Patient:

public partial class Patient
{
    public DateTime BirthDate { get; set; }
    public String City { get; set; }
    public String Cpatient { get; set; }

    // rest of properties come here
}

and your view model can be called PatientViewModel:

public partial class PatientViewModel
{
    public DateTime BirthDate { get; set; }
    public DateTime BirthDateStr
    {
        get { return BirthDate .ToShortDateString(); }
    }

    public String ChartNumber { get; set; }
    public ChartRecid { get; set; }
    public String City { get; set; }
    public String Cpatient { get; set; }
}

So, as you can see, the view model hold the properties required by the view, which are aggregated from multiple data models.

Getting data model extra data

One method I found convenient (although not exactly orthodox, since it pollutes data models) is to extend the data model with properties that provide extra needed data, like this:

// this is another part of the partial class
public partial class Patient
{
    public String ChartNumber
    {
       get { return Chart.chart_number; }
       set { Chart.chart_number = value; }
    }

    public ChartRecid
    {
       get { return Chart.ChartRecid; }
       set { Chart.ChartRecid = value; }
    }

    // other "computed" properties come here
}

An alternative to this approach is to have custom map these properties when transferring data model -> view model and vice-versa (so, this also supports data persistence, not just data fetch).

Actual mapping

As already suggested, AutoMapper was specially designed for this kind of chores. Its usage is simple as:

setup the mapping:

(this is deprecated in the last version, as described here (and also mentioned by the compiler, if last NuGet package is referenced))

Mapper.CreateMap<Patient, PatientViewModel>();
Mapper.CreateMap<PatientViewModel>();

using it:

var patientDataModels = ctx.patients.
   .Include(p => p.Chart)               // eager load chart data
   .Where(p => cpatient == cpatient)
   .ToList();

var patientVms = new List<PatientViewModel>();
// Mapper should also handle collection mapping automatically, if type mapping is set up
Mapper.Map(patientDataModels, patientVms);

// if data model is not extended, you have to manually map Chart type properties

Eager load is recommended to avoid separate queries generated when Chart object properties are required (less SQL verbosity, significantly faster for large collections).

AutoMapper will automatically map properties having the same (and type, if type is different and no implicit conversion can be done, it will throw an exception) and not ignored (IgnoreMap attribute).


Java - Functional interface for merging two lists

The thing is that the merge function is never called in your case, because all you are doing is reordering an existing map, so IMO you don't really need to worry about it.
Personally in such cases I just use (m, n) -> m, because it's short and doesn't distract.
Another variant would be to use a function that throws an exception when called. The JDK does this itself when you use the toMap overload that doesn't take a merge function:
private static <T> BinaryOperator<T> throwingMerger() {
  return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
}

Another thing you may want to consider it not to use a (Linked)HashMap at all here, but simply collect the Entrys into a list. If you need to lookup an entry by key later, then just keep the original map around.

EDIT: In cases where the merge function is used, your implemention is fine. You may want to just put it in a variable, so that its name can describe its function.
One thing you could consider is using a function that creates a new list instead of "reusing" one of the existing lists. That would reflect the functional style of the code better, where one normally uses immutable data structures.
The basic problem is that Java's List interface isn't intended for functional/immutable situations and doesn't have a simple method to concatinate two lists.
If you are open to additional libraries you'd have more options. For example, Apache's Commons has a union method.


Just turning some of the comments into an answer, more specific I'm going to address these issues in your code:

No need to double the lookup table – By using char.ToLower(c) you could half the size of the lookup table.
Shift the offset by (char) 'a' – If you shift the offset by the value of a you get a zero-based index.
No need longer for the char dictionary – Since we now have a zero-based index we could simply do a lookup in a byte table. (Update: And it could be a simple array also, no need for a List<byte>)
Since we shifted the offset, no need to include empty entries – By shifting the offset, we don't need a sparse 256 byte array. It does however, fail miserably like your code if trying to convert non-alpha characters.
Wouldn't it be nice to convert longer texts also? – Wouldn't you need to convert longer texts, and not only single characters? For good measure, I've added a ToString(string) to the code below.

This leads to the following code (extending on the char value):

using System.Text;

public static class MyExtensions
{
    static byte[] braille = new byte[]
      { 0x20, 0x30, 0x24, 0x26, 0x22, 0x34, 0x36, 0x32, 0x14, 0x16,
        0x28, 0x38, 0x2c, 0x2e, 0x2a, 0x3c, 0x3e, 0x3a, 0x1c, 0x1e,
        0x29, 0x39, 0x17, 0x2d, 0x2f, 0x2b
      };

    public static string ToBraille(this char c) {
      return Convert.ToString(braille[ (byte) char.ToLower(c) - (byte) 'a'], 2).PadLeft(6, '0');
    }

    public static string ToBraille(this string s) {
      StringBuilder result = new StringBuilder();
      foreach (char c in s) {
        result.Append(c.ToBraille()).Append(" ");
      }

      return result.ToString();
    }
}


Finding the number of permutations of an integer array with equaling difference (not in order)

You are using a class just to be able to able to mess with some kind of global values. This makes your code very hard to understand. It took me a while to unroll it all and get the following code :

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        run(read());

        run(fake_read());
    }

    static int[] fake_read() {
        int[] a = {1, 4, 2, 5, 7, 6, 9, 8, 3};
        return a;
    }

    static int[] read() {
        Scanner scan = new Scanner(System.in);
        int N = scan.nextInt();
        int [] array = new int [N];
        for (int i = 0; i<N; i++) {
            array[i] = scan.nextInt();
        }
        return array;
    }

    static int [] first_difference(int[] array) {
        int N = array.length;
        int [] temp = new int [N-1];
        for (int i=0; i < N-1; i++) {
            temp[i] = array[i+1] - array[i];
        }
        return temp;
    }

    static void run(int[] array) {
        int [] first_diff = first_difference(array);
        int n = permute(array,0, first_diff);
        System.out.println(Integer.toString(n));
    }

    static public int permute(int[] array, int k, int [] first_diff)
    {
        int result = 0;
        for(int i=k; i<array.length; i++)
        {
            int temp = array[i];
            array[i] = array[k];
            array[k] = temp;
            result += permute(array, k+1, first_diff);
            temp  = array[i];
            array[i] = array[k];
            array[k] = temp;
        }
        if (k == array.length-1)
        {
            result += calculate(array, first_diff);
        }
        return result;
    }

    static int calculate(int [] array, int [] first_diff) {
        int [] diff_values = new int [array.length-1];
        for (int i = 0; i < array.length-1; i++) {
            diff_values[i] = array[i+1] - array[i];
        }
        return compare(diff_values, first_diff);
    }

    static int compare(int [] values, int [] first_diff) {
        int result = 0;
        boolean [] used_new = new boolean [values.length];
        boolean [] used_first = new boolean [values.length];
        for (int i = 0; i < values.length; i++) {
            used_new[i] = false;
            used_first[i] = false;
        }
        for (int i = 0; i < values.length; i++) {
            for (int j = 0; j < values.length; j++) {
                if (!used_new[j] && first_diff[i] == values[j]) {
                        used_new[j] = true;
                        used_first[i] = true;
                        break;
                }
            }
            if (!used_first[i]) break;
        }
        if (areAllTrue(used_new) && areAllTrue(used_first)) {
            result += 1;
        }
        return result;
    }

    static public boolean areAllTrue(boolean[] array)
    {
        for(boolean b : array) if(!b) return false;
        return true;
    }
}

I'll be honest with you, I was hoping that once this was done, I'd be facing something somewhat easier to understand but it is not the case (the poor documentation and the function names do not help at all). I guess one could find a simpler (and faster ?) solution but the thing is that I don't even understand what is expected. The question might need clarification.


Different versions of the Operate method

You can try to extract the common piece of code into a helper method:
private static Either<ErrorList, TResult> Operate<TResult>(ErrorList[] errorLists, Either<ErrorList, TResult> success)
{
    var errorList = errorLists
        .SelectMany(x => x.ToEnumerable())
        .Aggregate((x, y) => new ErrorList(x.Concat(y)));

    return success.ValueOr(() => errorList);
}

Then you can reduce the overloads' body only to calculate the helpers inputs:
public static Either<ErrorList, TResult> Operate<T1, T2, T3, T4, T5, TResult>(
    Either<ErrorList, T1> a, Either<ErrorList, T2> b, Either<ErrorList, T3> c, Either<ErrorList, T4> d, Either<ErrorList, T5> e,
    Func<T1, T2, T3, T4, T5, Either<ErrorList, TResult>> onSuccess)
  => Operate<TResult>(
    new [] { a.LeftValue, b.LeftValue, c.LeftValue, d.LeftValue, e.LeftValue },
    onSuccess(a.RightValue, b.RightValue, c.RightValue, d.RightValue, e.RightValue));


Get index of value in ObservableCollection

The documentation for IndexOf() clearly states how it looks for a matching value.

  This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list.

Which brings you to the documentation for EqualityComparer<T>.Default

  The Default property checks whether type T implements the System.IEquatable<T> interface and, if so, returns an EqualityComparer<T>that uses that implementation. Otherwise, it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

You need to be overriding Equals not the == operator. Changing the behavior of the == operator to something other than Object.ReferenceEquals() for reference types should only be considered in rare cases.


Graph Implementation in Java using Set and Map

As of now, you only use LinkedHashSet and LinkedHashMap, thus declaring edgeSet and vertexMap as HashSet and HashMap is pointless. You could deploy Inversion of Control in order to demand some Set and Map at construction.

Method getEdges(...) could possibly return null, so you may want to wrap the return value in an Optional. Using Optional, you can also unify the behaviour of Map#get(Object) (which may or may not throw a NPE if a null is passed as argument):

public Optional<Set<Edge>> getEdges(Vertex vertex)
{
    Optional<Set<Edge>> result = Optional.empty();
    try
    {
        result = Optional.ofNullable(vertex);
    }
    catch (NullPointerException e)
    {
        // No action needed, we return an empty Optional
    }
    return result;
}

Your remove...(...)-methods throw a NPE if the Vertex/Edge provided is not contained within the graph or is null. As with Map#get(Object), Set#remove(Object) may or may not throw a NPE. You can rewrite them to not throw:

public void removeVertex(Vertex vertex)
{
    Optional<Set<Edge>> deleteEdges = getEdges(vertex);
    if (deleteEdges.isPresent())
    {
        vertexSetMap.remove(vertex);
        edgeSet.removeAll(deleteEdges.get());
        vertexSetMap.keySet().forEach(vertex1 ->
                vertexSetMap.get(vertex1).removeAll(deleteEdges.get()));
    }
}

public void removeEdge(Edge edge)
{
    try
    {
        if (edgeSet.remove(edge))
        {
            Vertex v1 = edge.getVertex1();
            Vertex v2 = edge.getVertex2();
            vertexSetMap.get(v1).remove(edge);
            vertexSetMap.get(v2).remove(edge);
        }
    }
    catch (NullPoionterException e)
    {
        // No action needed, there is nothing to remove.
    }
}

When you add methods

public boolean containsVertex(Vertex vertex)
public boolean getOther(Vertex vertex)

To your Edge-class, you can rewrite getNeighborsOf(...) to use Streams

public Set<Vertex> getNeighborsOf(Vertex vertex) {
    return vertexSetMap.get(vertex).stream()
          .filter(edge -> edge.contains(vertex))
          .map(edge -> edge.getOther(vertex))
          .collect(Collectors.toSet());
}

What is missing is a Set<Vertex> getVertices() method (you have one for Edges, so I would expect one for Vertexs as well). This would probably require creating an additional field Set<Vertex> vertices in your Graph class.


Creating and calling objects sequentially in Tkinter with Python 3

I don't exactly know what you mean by "call" the object. Objects aren't typically something you call. I'm going to assume that in this context you meant "show".

The code you copied was for having completely different "pages" which could be shown by name in any order. However, you want several identical "periods" that you want to access sequentially, or perhaps by number (eg: "show period 1", "show period 2", etc.)

So, assuming that each period is identical except for it's number, the first step is to create a single Period class. It seems reasonable that each period know it's number so you might want to add that to the constructor:

class Period(tk.Frame):
    def __init__(self, parent, controller, number):
        tk.Frame.__init__(self, parent)
        self.number = number
        ...

Next, in your Game, instead of looping over a list of classes, you need a simpler loop that runs as many times as you want to have periods. For example, if you are creating a game with four periods, you might modify the loop in Game to look like this:

self.periods = []
for period_number in range(4):
    period = Period(container, self, period_number)
    self.periods.append(period)
    period.grid(row=0, column=0, sticky='nsew')

With that, self.periods[0] refers to the first period, self.periods[1] is the second, and so on.

You then need to modify show_frame to take a number rather than a class or name of a class. It should also be renamed to something like show_period to make the intent more clear (I've left error checking out to keep it short):

def show_period(self, period_number):
    frame = self.frames[period_number]
    frame.tkraise()

With that, you now have the ability to show by number any period you want. Since you want to be able to step through them sequentially, I recommend creating a method named next_period which can show the next period and handle any logic about what to do after the last period.

The simplest implementation will be to have show_period remember what the current period is, and then in next_period you simply need to add one:

def show_period(self, period_number):
    ...
    self.current_period = period_number

The implementation of next_period is pretty easy:

def next_period(self):
    if self.current_period == len(self.periods):
        <special code to handle the last period...>
    self.show_period(self.current_period+1)

With that, you can add a button to your Period class that will automatically take it to the next period, without it having to know what the next period is:

class Period(tk.Frame):
    def __init__(self, parent, controller, number):
        ...
        self.next_button = tk.Button(self, text="Next", command=self.next)
        ...

    def next(self):
        self.controller.next_period()

Note: This is not necessarily the best way to structure this program, it is simply one way of doing it. The point was to illustrate how to create multiple instances of a single class, and step through them one at a time.


The places where I have worked, as well as a number of articles I have read, have taught me that echoing HTML is bad practice, and really if you think about it from a maintenance perspective you want that clear separation of PHP and HTML. An example of your code with that separation:

<?php
    $terms = get_the_terms($post->ID, 'category');

    if(!empty($terms)){
        $term = array_pop($terms);
        $custom_field = get_field('category_image', 'category_' . $term->term_id );
?>
    <a href="<?php echo get_field('category_link', $custom_field); ?>">
        <img src="<?php echo $image; ?>" alt="<?php echo get_cat_name($cat->term_id); ?>" class="item-image" />

<?php } ?>

Or if you wanted to simplify it a bit for future readers:

<?php
    $terms = get_the_terms($post->ID, 'category');

    if(!empty($terms)){
        $term = array_pop($terms);
        $custom_field = get_field('category_image', 'category_' . $term->term_id );
        $href = get_field('category_link', $custom_field);
        $cat_name = get_cat_name($cat->term_id);
?>
    <a href="<?php echo $href; ?>">
        <img src="<?php echo $image; ?>" alt="<?php echo $cat_name; ?>" class="item-image" />

<?php } ?>

Or you could build an array out of the values if you wanted to "encapsulate" the link or something instead. Either way, a setup like this is much clearer and more maintainable than if you were to concatenate everything into one giant string and echo it.

Hope this helps.


Saving the output of find in a variable and looping over it is not a good idea in general: filenames with white-space (space, tab, newline) will be split, so the loop will not work on them.

It would be a little bit better to use a while loop instead:

find ... | while read file
do
        # ...
done

But this is still not great, as it won't protect you from newlines.
But for your use case, it might be good enough.
For a more robust solution,
see this other post.

The \( ... \) is pointless here:

find $path -maxdepth 1 ! \( -name "*.zip" \) -type f ! -newermt "$yestdayend"

This is the same, but shorter and simpler:

find $path -maxdepth 1 ! -name "*.zip" -type f ! -newermt "$yestdayend"

It's a bit odd to quote "logbackup-" here:

if zip -rv $path/"logbackup-"$moddate.zip $file; then

Literal strings like that don't need quoting in Bash.
On the other hand, it would be good to quote $path:

if zip -rv "$path"/logbackup-$moddate.zip $file; then


You want to use classify and constantize:

require 'set'
AUTHORIZED = Set[Product, Status, Industry]
def get_record(id, item)
  model = item.classify.constantize
  raise "Go away, hacker" unless AUTHORIZED.include? model
  model.find(id).name
end

Be careful about security, as without the unless this will access any class in your system. This is just an example.


Bubble Sort Implementation | C-ish and Modern C++

As you're already working with iterators you might as well accept iterators as arguments instead of the std::vector (as all STL algorithms do). That way it will work with other containers as well, even with raw pointers.

The comparison can also be customized like in std::sort. Maybe the caller wants to sort in descending order or compare structures by some field.


I'm not a Python programmer but I would take this approach, as if I understand the problem correctly, it seems like an easy solution. Along side that I believe it makes us of the language features also.

#!/usr/bin/env python3

# open word files
wordlist = open("wordlist.txt", "r").read().split()
words = open("words.txt", "r").read().split()

s = list()

# loop through scrambled words
for word in words:
    # break scrambled word into characters
    chars = sorted(list(word))
    # loop through comparison list
    for compare in wordlist:
        if sorted(list(compare)) == chars:
            s.append(compare)

# create comma separated list of words
print(",".join(s))

This works on the bases that we do not care for order, so an ordered list of each will be a good check.

I have not broken out of the inner loop, as it is unclear weather multiple words could match and all of those words should be returned or not.

This is untested, as stated, I'm not a Python programmer.


If your problem is speed and the generated HTML is as easy as it look in your example code, then I would not use the Nokogiri Builder.

Take a HTML-Template and build your files according this template.

Example (without an example XML I was not able to check it):

# search taxonomy.xml for nodes with the attribute 'atlas_node_id'
# to get a NodeSet of all the destinations
destinations = tax_file.css('[atlas_node_id]')

destinations.each do |destination|
# temp variable to make code easier to read later on
id = destination.attribute('atlas_node_id').value

# write file using destination name as filename
filename = destination.children[1].content + ".html"
File.open(File.join(directory,filename),'w'){|html|
  html << <<HTML % destination.children[1].content
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

<title>%s</title>
<link rel='stylesheet' href="all.css">

HTML
  html << "
%s
\n" % destination.children[1].content

      # check if there is a destination higher in the taxonomy and display
      # the relevant link if so.
      if !(destination.parent.attribute('atlas_node_id').nil?)
        file = destination.parent.children[1].content + ".html"
        html << '%s' % [file,destination.parent.children[1].content]
        html << "\n"
      end

      # I chose to show the overview content since this exists for every
      # destination
      node = dest_file.xpath("//destination[@atlas_id = #{id}]").first
      html << "
%s
\n" % node.xpath(".//introductory/introduction/overview").text unless node.nil?
      html << ""
  }

end


num is only used within the while loop and not outside of it.
A for loop is more appropriate for such pattern.

The solution looks as if you forgot to perform a final refactoring to clean things up.
The function starting with let longestStreak = 1; looks like a good idea,
as the exercise is looking for the longest streak, and at this point,
my expectation is that this variable will be probably returned at the end.
But no, to my surprise it is reset to 1 in the forEach,
and at the end the function returns max.

All that to say, it would make more sense to use a local length variable inside the forEach, and update longestStreak when a higher value is found,
and return it at the end.

var longestConsecutive = function(nums) {
  const set = new Set(nums);
  let longestStreak = 0;
  set.forEach(x => {
    if (!set.has(x - 1)) {
      let length = 1;
      for (let num = x + 1; set.has(num); num++) { ++length; }
      longestStreak = Math.max(longestStreak, length);
    }
  });
  return longestStreak;
};


Using std::size_t. You asked:

  Is it ok to use std::size_t all over the code?

I think that's perfectly alright.
Use of const std::size_t

Using const std::size_t for the type of an argument has no advantage over using just std::size_t. It adds unnecessary verbosity. I would change them all to use std::size_t.
Inconsistent member function names.

Function names are better that start with a verb, such as addEdge. However, all other member functions don't follow that naming convention.

I would recommend the following changes:

  Vertices  -> getNumVertices
  Edges     -> getNumEdges
  degree    -> getDegree
  maxDegree -> getMaxDegree
  minDegree -> getMinDegree

Variable names

I think it's more appropriate to use numVertice and  numEdges instead of vertices and edges.
Checking for negative inputs

An object of std::size_t will never have a negative value. It's pointless to check whether an input is negative when it is of type std::size_t. I would recommend removing those checks altogether.
Range checking

In addEdge, you have:

if (a < 0 || b < 0) {
    throw std::out_of_range{"negative values"};
}

The check for negative values is not necessary. However, it is necessary to check whether those are within the upper bound. I would replace that check with:

if (a >= numVertices || b >= numVertices ) {

Better initialization of matrix.

I would change the constructor to:

AdjMatrix::AdjMatrix(std::size_t& vertsize) : numVertices{vertsize},
                                              edges{0},
                                              matrix{vertsize, std::vector<std::size_t>{vertsize, 0}}
{
}

Using std namespace in member function implementations.

If the member functions are implemented in a .cpp file, I would add

using std::size_t;
using std::vector;

in the .cpp file to reduce the amount of typing.
Remove if/else from minDegree().

Initialize min to std::numeric_limits<std::size_t>::max. Then, you don't need the if/else check. You can replace the lines:

if (i == 0) {
    min = d;
} else {
    min = min < d ? min : d;
}

with

min = min < d ? min : d;


I would only call the method startGame() inside the main function and handle from there the entire logic of the game. The main method shouldn't be aware of the exact procedure of a game. It just wants to start a game and wants to know who won. As an output from that method you could return true if the user wins and false if the computer wins. If you want to handle a tie separately you can return an int value instead for indicating the outcome (-1 computer wins, 0 draw, 1 user wins).

Inside the startGame() method you can call the game logic functions/your algorithm. In pseudo code it would look sth like this:

public int startGame()
{
    userChoice();
    computerChoice();
    return evaluateWinner(); // Evaluate winner and returns -1, 0, 1 depending on the user and computer choice (i.e. who the winner is or if its a tie)
}

You can make the other methods of the RPS class private to have a clean interface for this class, allowing other classes only to start a game and prevent them interfering the game algorithm itself.


Your code has a bug.  I can reproduce it fairly consistently by changing your run method to:

@Override
public void run() {
    try {
        for(int i=0;i<100;i++) {
            uniSexBathroom.occupy(person);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Notice, that I've increased the number of times that each thread tries to occupy the bathroom.  Starting/Stopping threads is a fairly slow process so in order to encourage more contention I used a loop so more time is spent trying to get into the bathroom.  It results in a null pointer in the acquireGenderSemaphore method on this line:

if (!personSex.type.equals(currentGender.type)) {

It's happening because currentGender is null.  We can be confident about this, because personSex is the same for every call for a given thread.  How is it null?  Well, because this isn't safe:

if (currentSize.get() == 0) {
    currentGenderSemaphore.acquire();
    currentGender = personSex;
}

The problem is that context switches can happen at any time, so just because currentSize wasn't 0 for the if evaluation, it doesn't mean that it's still zero during the execution of the if block.

So:

Thread2 is currently in the bathroom (Size 1)

Thread1 comes in to acquire the lock, checks the value of current size and finds it's 1, skip the if block

if (currentSize.get() == 0) {  // Size still 1

Thread2, which is currently using the bathroom leaves:

noOfEntriesSemaphore.release();
currentSize.decrementAndGet(); // Size becomes 0

Thread2, then checks if they were the last one out, which they were:

if (currentSize.get() == 0) {
    currentGenderSemaphore.release();
    currentGender = null;  // Gender becomes null
}

Thread1 then proceeds, assuming there is still somebody in the bathroom:

if (!personSex.type.equals(currentGender.type)) {

But since currentGender has been set to null by Thread 2 when it left.... Bang.


I tried to improve it myself and it is much faster than before!
Here's my new code, feel free to comment on what can be further done to improve it.

    .filter('searchProjects', ($rootScope, $filter) => {
        return (projects, query) => {
            if (projects) {
                //Create project leader search object
                let projectLeaders = {};
                $rootScope.profiles.forEach(profile => {
                    profile.projects.forEach(role => {
                        let projectRole = role.masterData['Projektrolle'];
                        //864 = Projectleader Tag ID
                        if (projectRole && ~projectRole.indexOf(864)) {
                            let projectLeader = profile.firstName + " " + profile.lastName;
                            if (projectLeaders.hasOwnProperty(role.project)) {
                                projectLeaders[role.project].push(projectLeader);
                            } else {
                                projectLeaders[role.project] = [projectLeader];
                            }
                        }
                    });
                });

                return projects.filter(p => {
                    //delete customers' contacts to exclude from search
                    if (p.kunde && p.kunde.contacts) {
                        //Only leave the selected Reference Contact in Customer's Contacts for Search
                        p.kunde.contacts = p.kunde.contacts.filter(contact => p.reference === contact.id);
                    }
                    //if project has leaders, add them to it for searching
                    if (projectLeaders.hasOwnProperty(p.id)) {
                        p["projectLeaders"] = projectLeaders[p.id];
                    }
                    return Boolean($filter('filter')([p], query).length);
                });
            }
        };
    })


Remember how you solve Sudoku boards manually - you write a list of allowed numbers into each cell, and whenever you add a new number somewhere to the grid, you update the other cell's lists accordingly.

So one obvious optimization is to implement the same kind of bookkeeping in your program, that will speed up the process heavily: instead of having a test like this

1.upto(9) do |k|
      next if in_row(grid,i,k) || in_col(grid,j,k) || in_grid(grid,i,j,k)

your program can just grab the allowed numbers from the cells's list, without the need of calling the functions in_row, in_col, and in_grid. Of course, the assignment of the number will need some additional time now for the bookkeeping, but if you do this right, I am sure the bookkeeping will pay off.

Moreover, such bookkeeping will allow some further optimizations: for example, when the list of allowed numbers of one cell becomes empty, you can stop the recursion immediately. The same is true when the union of all numbers of the "allowed numbers" lists of a row, a column or a 3x3 subgrid does not contain all values from 1 to 9 any more.

Note that for this approach, it will be beneficial to replace your grid array by a data structure or class which holds not only the cell values, but also the "allowed numbers" list of each cell, and supports adding and removing of numbers.

For removing a number, you will need to reset the grid including the internal "allowed number" lists to the state before the number was added. A simple implementation is to make a copy of the whole grid beforehand and replace the current grid by the copy afterwards, when the "move" was not accepted.


A logical optimization here would be to remember the primes you have already calculated. Consider the theory:

  A prime is a number that is divisible by itself and 1 only

It follows that, to test if any number X is prime, you only need to find 1 prime number less than X which divides in to X without a remainder. There is no need to test non-prime numbers, because if a non-prime divides cleanly in to X, then the prime factors would also divide in to X.

So, if you keep a record of the previously calculated primes, then you only need to scan those values to see if they divide in to X. In essence, each time you print a prime, also add it to a list.

This will require 'seeding' the prime list with the value 2.

A second optimization is that a number X is only prime if it has a factor. A factor is a number, multiplied by another number, that is equal to the original value X.

The useful theory here, is that, as the value of the first factor increases, the value of the second factor decreases. There is a point when the first and second factors 'cross over' and the second factor becomes less than the first.

The cross-over point is the square-root of the number X. When you pass the square-root of the number, you have tested all the possible factors... there's no need to scan values larger than the root, because, if they were factors, you would have found them already by identifying the small factor that matches the larger factor.

Putting these two items together, you should modify your code to:

Have a special case for 2, which is prime, and store it in the seed array.
preserve the prime numbers you find in the same array.
for values larger than 2, you only need to use values from the pre-identified prime array to test for factors
you only need to look for prime factors that are less than, or equal to the square-root of the value.


Managing configs to use scripts on different computers

You have a value (hostname in this case) that you want to use to select among
various data choices (config modules in this case). When you have situations
like this, use a data structure. Sensible
data is always simpler than logic. For example, see Rule 5 from Rob
Pike.
An illustration based on your code:
import socket
import DConfig
import AConfig
import MConfig

configs = {
    'host-D': DConfig,
    'host-A': AConfig,
    'host-M': MConfig,
}

hostname = socket.gethostname()
Conf = configs.get(hostname, MConfig)


Using Support Vector Machine algorithm to analyze satellite image

When you want to parallelize a program you have to actually do it. When you're using C, you can hope that the compiler will spread the CPU "tension" to other CPU, which it will do with the right compiler command. But you're using Python so it cannot do the optimization since there is no (separate) compiler.

But even with C it doesn't work that well. Normally you have to do it yourself with threads. If you can make your calculation on threads you should do it. I didn't read your code in details, but when it comes to SVN I guess that the calculation doesn't depend on previous calculation. If that's the case you might be able to parallelize your program with as many threads as you have cores.

But I think that you have to do that step of parallelizing by yourself, you can't count on the machine to guess where it can or cannot parallelize.

And that will possibly reduce the execution time by the number of threads. (even if that not exactly true, that's a max).


Function to combine arrays of associative arrays

I know that the question is already answered with cFreed answer but I want show another approach.

While I was finding if there are some function that do that I found this on php.net

function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
  $merged = $array1;

  foreach ( $array2 as $key => &$value )
  {
    if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
    {
      $merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
    }
    else
    {
      $merged [$key] = $value;
    }
  }

  return $merged;
}

basically is the same that you want but only for two args so...
I tried to do this
pick args and send to that function in pairs

so, I write this. I tried to keep the soul of your code intact so you will see  $asObject = (T_OBJECT_CAST == $args[count($args)-1]);  and also     if($asObject) array_pop($args);

function array_merge_recursive_unique_keys(){
    $args     = func_get_args();
    $asObject = (T_OBJECT_CAST == $args[count($args)-1]);
    if($asObject) array_pop($args);

    $ret = $args;

    if(count($args)>0){
        $partial = current($args);

        for($i = 1; $i< count($args); $i++){
            if(is_array($args[$i]) && is_array($partial)){
                $partial = array_merge_recursive_distinct($partial, $args[$i]);
            }
        }

        if($asObject) {
            $ret = json_decode (json_encode ($partial), FALSE);
        }else{
            $ret = $partial;
        }

    }

    return $ret;
}


In Java and C# you can simply put

return !empty($this->_source);

and

return isset($this->_source[$input]);

since the evaluation of that is a boolean by itself and thus there is no need for the additional ternary operation. I would suspect that this is the same in PHP.


Area calculator for shapes as an OOP interview test

I see some things that may help you improve your code.

Don't overcomplicate your code

The only thing required of the Shape and Triangle classes is the calculation of area.  For that reason, the code can be considerably simplified if the constructor calculates and stores the area.

Use const where practical

The Area() function probably shouldn't alter the underlying Shape object, so it makes sense to declare it const.

Use a standard exception where appropriate

There's really nothing, well... exceptional about the Exception class, so it seems not really to be required.  Maybe std::domain_error could be used instead like this:

throw std::domain_error("Any two sides of a triangle must be longer than one");

Provide a test driver

This is more about getting a good review rather than the code itself, but it's often good to give reviewers a complete, compileable example to allow them to see the code in context.  Here's what I used:

#include <iostream>
int main() {
    Triangle t1{3, 4, 5};
    std::cout << t1.Area() << '\n';
    try {
        Triangle t2{3, 4, 15};
    }
    catch (std::exception &e) {
        std::cout << e.what() << '\n';
    }
    Triangle t3{3, 4};
    std::cout << t3.Area() << '\n';
}

Use std:: for math functions

The sqrt function is often in the global namespace, but it's required to be in the std namespace.  For that reason, it's probably safer to write std::sqrt than just sqrt.

Use standard keywords

Instead of _NOEXCEPT which is not standard, the code could use noexcept.

Reworked example

#include <string>
#include <cmath>
#include <stdexcept>

class Shape
{
public:
    virtual double Area() const = 0;
};

class Triangle : public Shape
{
public:
    Triangle(double base, double height);
    Triangle(double a, double b, double c);
    double Area() const override { return area;}

private:
    double area;
};

Triangle::Triangle(double base, double height)
    : area{(base * height)/2}
{
}

Triangle::Triangle(double a, double b, double c)
    : area{(a-b-c)*(-a+b-c)*(a+b-c)*(a+b+c)/16}
{
    if (area < 0)
        throw std::domain_error("Any two sides of a triangle must be longer than one");
    area = std::sqrt(area);
}


Defining array contents using multiple statements on one line

I'd go with the second snippet. They're instructions, and instructions read more naturally from top to bottom, rather than from left to right.

Cramming multiple instructions into a single line is a bad habit IMO - it's not because the language supports it that it's necessarily a good idea; the array has 2 columns.. what if it were 10? Would you consider cramming 10 instructions on the same line?

Your indices seem to go (row,column), which amounts to (y,x), which is a bit counter-intuitive, and if you wanted to write that array into a worksheet range, you'd have to transpose it:

Range("A1:B" & UBound(arrAmountColumns,2)) = arrAmountColumns

wouldn't produce the expected result.

By using the first index as your "column" (X) and the second as you "row" (Y), you eliminate that ambiguity and the code would read (x,y), which is a much more intuitive way of visualizing 2D arrays.


Since I didn't want to setup a webserver for this, I added a bare class, which should behave in the same way as your request.GET:

class request:
    GET = dict(a1=34, a2=37, c1=50, c2=75)

You should avoid setting keys in globals(), it clutters the namespace too much. Instead just use the default keyword of the get method of a dictionary, which will give you the specified value if the key is not present.

get_dimension = request.GET.get(dim, 'None')

You can make your string formatting a bit easier to understand if you split it up a bit. I made the string itself a constant (avoiding having to allocate it multiple times) and used positional arguments, instead of keywords (which, admittedly, hurts the readability slightly).

Instead of doing a string addition every loop, it is better to append to a list and do one join at the end, because string addition means creating an intermediate new string, since strings are immutable.

sql = "SELECT * FROM t_wishbone_dimensions WHERE 1=1" + "\n".join(sql_where)

I would also use itertools.product to replace your double loop, so something like:

directions = {'1': '>', '2': '<'}
dimensions = ['a', 'b', 'c', 'd', 'e', 'f', 'f2', 'g']
for dimension, i in itertools.product(dimensions, ('1', '2')):
    direction = directions[i]
    ...

To improve readability you should separate the ANDs with a newline each (like you did in your example output).

Lastly, python has an official style guide, PEP8, which recommends having a blank after a comma in an argument list (in dimensions after 'a', one was missing), as well as not adding unnecessary whitespace (so usually no str( something ), but just str(something)).

Final code:

import itertools

class request:
    # should handle the same same as your `request.GET`
    GET = dict(a1=34, a2=37, c1=50, c2=75)

dimensions = ['a', 'b', 'c', 'd', 'e', 'f', 'f2', 'g']
DIRS = {'1': '>', '2': '<'}
AND_STR = "AND ( `{0}` {1}= '{2}' OR '{2}' = ('None' OR '') )"

sql_where = ['']
for dimension, i in itertools.product(dimensions, ('1', '2')):
    val = request.GET.get(dimension+i, 'None')
    sql_where.append(AND_STR.format(dimension, DIRS[i], val))
sql = "SELECT * FROM t_wishbone_dimensions WHERE 1=1" + "\n".join(sql_where)
print sql

Output:

SELECT * FROM t_wishbone_dimensions WHERE 1=1
AND ( `a` >= '34' OR '34' = ('None' OR '') )
AND ( `a` <= '37' OR '37' = ('None' OR '') )
AND ( `b` >= 'None' OR 'None' = ('None' OR '') )
AND ( `b` <= 'None' OR 'None' = ('None' OR '') )
AND ( `c` >= '50' OR '50' = ('None' OR '') )
AND ( `c` <= '75' OR '75' = ('None' OR '') )
AND ( `d` >= 'None' OR 'None' = ('None' OR '') )
AND ( `d` <= 'None' OR 'None' = ('None' OR '') )
AND ( `e` >= 'None' OR 'None' = ('None' OR '') )
AND ( `e` <= 'None' OR 'None' = ('None' OR '') )
AND ( `f` >= 'None' OR 'None' = ('None' OR '') )
AND ( `f` <= 'None' OR 'None' = ('None' OR '') )
AND ( `f2` >= 'None' OR 'None' = ('None' OR '') )
AND ( `f2` <= 'None' OR 'None' = ('None' OR '') )
AND ( `g` >= 'None' OR 'None' = ('None' OR '') )
AND ( `g` <= 'None' OR 'None' = ('None' OR '') )


Web scraping JSON-data from API put into Dataframe

Assuming you have a multi-core processor, you can use the multiprocessing module to do your scraping in parallel. Here's a good article that explains how to use it: An introduction to parallel programming using Python's multiprocessing module (you only need to read the first half of the article)

The simplest way to parallelize this would be to do your 2017 loop in a separate process from your 2018 loop. If you need it faster than that, you could further subdivide your 2017 and 2018 ranges. It also depends on how many cores you have. If you only have 2 cores, you won't benefit from dividing it into more than 2 processes (or 4 processes for 4 cores).

Other than that I can't see anything in your code structure you could change to speed it up.

Update: I'm not familiar with the API you're using, but if there's a way to make one API call that returns a list of games with their box scores instead of making a separate request for each game, that would be the best way to speed it up.

Also, according to Mathias in the comments, multiprocessing.Pool.map would be particularly helpful in this case. I'm not familiar with it, but it does look like it would be convenient for this.


Your implementation uses Enum for the suits, but not for the values.  Thus it is harder to validate the card values, and would as you noted, allow a joker card to be created, even though you didn't want that ability.

Card Value Enum:

A card value enum provides the ability to give the cards a value and a descriptive name, while limiting possible values to valid ranges:

class CardValue(Enum):
    Ace = 1
    Deuce = 2
    Three = 3
    Four = 4
    Five = 5
    Six = 6
    Seven = 7
    Eight = 8
    Nine = 9
    Ten = 10
    Jack = 11
    Queen = 12
    King = 13

Immutable Types

For something like a card, an immutable type can provide some advantages.  One big one, is that the same value and suit will always key the same in a set or dict. Inheriting from tuple will achieve imuutability.  Note that the class is setup in __new__ not __init__ since it is immutable.

class Card(tuple):

    def __new__(cls, value, suit):
        assert isinstance(value, CardValue)
        assert isinstance(suit, CardSuit)
        return tuple.__new__(cls, (value, suit))

property decorator

The property decorator makes it easy to access the value and suit.

    @property
    def value(self):
        return self[0]

    @property
    def suit(self):
        return self[1]

__str__ method

Since we are using Enum's for all of the values, a fully descriptive __str__ method is quite straight forward:

    def __str__(self):
        return "{} of {}s".format(self.value.name, self.suit.name)

So something like:

print(Card(CardValue.Ace, CardSuit.Club))

gives:

Ace of Clubs

Make sure we stay immutable

Suggest adding some boilerplate to help avoid abusing the class instances.

    def __setattr__(self, *ignored):
        raise NotImplementedError

    def __delattr__(self, *ignored):
        raise NotImplementedError

Deck class

So the Deck class can be made much simpler with the new Value class and a set comprehension like:

class Deck:
    def __init__(self):
        self.cards = {
            Card(value, suit) for value in CardValue for suit in CardSuit
        }

Whole Listing:

from enum import Enum

class CardValue(Enum):
    Ace = 1
    Deuce = 2
    Three = 3
    Four = 4
    Five = 5
    Six = 6
    Seven = 7
    Eight = 8
    Nine = 9
    Ten = 10
    Jack = 11
    Queen = 12
    King = 13

class CardSuit(Enum):
    Club = 1
    Heart = 2
    Diamond = 3
    Spade = 4

class Card(tuple):

    def __new__(cls, value, suit):
        assert isinstance(value, CardValue)
        assert isinstance(suit, CardSuit)
        return tuple.__new__(cls, (value, suit))

    @property
    def value(self):
        return self[0]

    @property
    def suit(self):
        return self[1]

    def __str__(self):
        return "{} of {}s".format(self.value.name, self.suit.name)

    def __setattr__(self, *ignored):
        raise NotImplementedError

    def __delattr__(self, *ignored):
        raise NotImplementedError

class Deck:
    def __init__(self):
        self.cards = {
            Card(value, suit) for value in CardValue for suit in CardSuit
        }


Profile and you will find your bottlenecks, you can do that with gprof under gcc/g++. You have to set the -g -pg on compile and then run your program like you would do normally. It will then produce a gmon.out file which you can open with gprof main gmon.out (assuming main is the name of your executable).

It will show you, in which functions your program spends most of the time.


Basic game engine: timer, FPS and logic loop

The whole tick tock mechanism is not needed for your main loop.

You've set up this elaborate contraption (it took me a while to understand) which measures how long your last "frame" took. Then, when deciding on how long you'll need to wait to get to the next frame, you retrieve that time, and subtract that from the current time plus how long you want to wait.

All this is a very elaborate mechanism for this:

long sleep = (long) (GameTimer.ONE_SECOND / desiredFPS);
try {
    while(true){

        // tick and print fps
        long lastTick = System.nanoTime();
        timer.tick();
        System.out.println(timer.getFPS());

        // input, update and draw (abstract methods of my engine class)
        input();
        update();
        draw();

        // sleep
        long wake = lastTick + sleep;
        do {Thread.sleep(0);}
        while (System.nanoTime() < wake);
    }
} catch (InterruptedException e) {
    // oh someone paused the game
}

This rewrite doesn't really help so I'll explain:

What you have made is something that keeps track of ticks. That's okay. But to then use the tick timer in the calculation makes no sense - you already HAVE the time you started the tick - it's when you entered the loop!

Your GameTimer is useful for doing things like showing debug information in graph form, or finding patterns in lagspikes. But for this usecase, just a single long will do.

And first and last are wrongly named. It's not a pointer to the first and last item in the circular buffer, it's a pointer to the first and last frame of the past second. This should be encoded in the variable name.


Implementation of Graham Scan algorithm in Haskell

Here are some improvements you may apply.

You can combine pattern matching and records. It allows you to avoid unnecessary numerous calls to xcoord and ycoord. It also makes your code easier to read.

You can force strictness on xcoord and ycoord fields.

These two improvements help with performance.

You can also do the following:

simplify pattern matching py reordering the patterns (see filterByList)
drop lots of parenthesis since space has bigger precedence than operators
simplify comparePoints with keeping only one level of guards
use more standard library functions (see lowestYPoint)

Most of these were given to me by hlint ;-)

import Data.List
import Data.Function (on)
import Control.DeepSeq

data Point = Point {
    xcoord :: !Double,
    ycoord :: !Double
} deriving Show

data Direction = ToRight | Straight | ToLeft  deriving (Show, Eq)

distance :: Point -> Point -> Double
distance (Point xA yA) (Point xB yB) = sqrt ((xA - xB)^2 + (yA - yB)^2)

direction :: Point -> Point -> Point -> Direction
direction (Point xA yA) (Point xB yB) (Point xC yC)
    | s <  0    = ToRight
    | s == 0    = Straight
    | otherwise = ToLeft
    where
        s = (xC - xA) * (yA - yB) + (yC - yA) * (xB - xA)

directions_ :: [Point] -> [Direction]
directions_ (a:b:c:xs) = direction a b c : directions_ (b:c:xs)
directions_ _ = []

directions :: [Point] -> [Direction]
directions xs = ToLeft : ToLeft : directions_ xs

lowestYPoint :: [Point] -> Point
lowestYPoint = minimumBy (compare `on` ycoord)

cosineAB :: Point -> Point -> Double
cosineAB a@(Point xA _) b@(Point xB _) = (xB - xA) / distance a b

comparePoints :: Point -> Point -> Point -> Ordering
comparePoints x a@(Point xA yA) b@(Point xB yB)
    | cA > cB   = LT
    | cA < cB   = GT
    | xA < xB   = LT
    | xA > xB   = GT
    | yA < yB   = LT
    | yA > yB   = GT
    | otherwise = EQ
    where
        cA = cosineAB x a
        cB = cosineAB x b

sortByAngle :: Point -> [Point] -> [Point]
sortByAngle x = sortBy (comparePoints x)

grahamScanDirections :: [Direction] -> [Bool]
grahamScanDirections [] = []
grahamScanDirections [_] = [True]
grahamScanDirections (ToLeft:ToRight:xs) = False : grahamScanDirections (ToLeft:xs)
grahamScanDirections (ToLeft:ToLeft:xs)  = True  : grahamScanDirections (ToLeft:xs)
grahamScanDirections (ToLeft:Straight:xs) = False : grahamScanDirections (ToLeft:xs)
grahamScanDirections _ = error "Impossible scenario"

filterByList :: [Bool] -> [a] -> [a]
filterByList (True :xs) (y:ys) = y : filterByList xs ys
filterByList (False:xs) (_:ys) = filterByList xs ys
filterByList _ _               = []

grahamScan :: [Point] -> [Point]
grahamScan ps = filterByList bool_list ps1
    where ps1       = sortByAngle (lowestYPoint ps) ps
          bool_list = grahamScanDirections $ directions ps1

pss = replicate 1000000
                [ Point 1 0
                , Point 1 2
                , Point 0 3
                , Point 2 3
                , Point 2 2
                , Point 3 2
                , Point 2 1
                ]

instance NFData Point where
    rnf a = a `seq` ()

main = (map grahamScan pss) `deepseq` putStrLn "Done"


Micro-optimizing Python is a bit of a quixotic endeavour — if you wanted the fastest possible performance then you wouldn't be using Python. But so long as we understand the nature of the exercise, then it's just a matter of trying lots of changes and measuring the results to see which ones are improvements:

Here's the baseline measurement for comparison with the improvements:

>>> from timeit import timeit
>>> timeit(lambda:totalNQueens(13), number=1)
4.241301966001629

Move the mask against all_ones out of the loop. That is, instead of:

possible_slots = ~(ld | column | rd)
while possible_slots & all_ones:

write:

possible_slots = ~(ld | column | rd) & all_ones
while possible_slots:

This saves about 6%:

>>> timeit(lambda:totalNQueens(13), number=1)
3.999626944991178

Accumulate count via a variable local to totalNQueens instead of returning it from helper:

def totalNQueens(n):
    all_ones = 2 ** n - 1
    count = 0

    def helper(ld, column, rd):
        nonlocal count
        if column == all_ones:
            count += 1
            return
        possible_slots = ~(ld | column | rd) & all_ones
        while possible_slots:
            current_bit = possible_slots & -possible_slots
            possible_slots -= current_bit
            next_column_bit = column | current_bit
            next_rd_bit = (rd | current_bit) << 1
            next_ld_bit = (ld | current_bit) >> 1
            helper(next_ld_bit, next_column_bit, next_rd_bit)

    helper(0, 0, 0)
    return count

This saves another 3% or so:

>>> timeit(lambda:totalNQueens(13), number=1)
3.8595934879995184

Avoid the local variables next_column_bit and so on:

def totalNQueens(n):
    all_ones = 2 ** n - 1
    count = 0

    def helper(ld, column, rd):
        nonlocal count
        if column == all_ones:
            count += 1
            return
        possible_slots = ~(ld | column | rd) & all_ones
        while possible_slots:
            current_bit = possible_slots & -possible_slots
            possible_slots -= current_bit
            helper((ld | current_bit) >> 1,
                   column | current_bit,
                   (rd | current_bit) << 1)

    helper(0, 0, 0)
    return count

This saves roughly another 4%:

>>> timeit(lambda:totalNQueens(13), number=1)
3.706758002997958

That's about 13% improvement in all.


You should have a class PriceComputer that computes prices and their discounts. This should be the central class of the whole design.

Then, make separate data types for the input and output of that class. That way the compiler prevents you from mixing these during the calculations (which will get quite complicated once you add more rules).

The input just needs to be the basket that you already have. You should change the HashMap to a LinkedHashMap, to keep the products in the same order they were inserted.

Each output element should have the properties product, quantity, resultingPrice, discount, discountPercent (only if applicable). All its fields should be final, since once computed, there is no reason to change them.

The general structure of your classes looks good. You might have a look at Project Lombok (which will save you from writing boring code), and you should make clear what the class Offer stands for, since it wasn't clear to me from the name alone.

Also, given an Offer, there are two ways of reaching a Product (offer.product and offer.discount.product). Are these products always the same? If so, one of them must be removed from the code.

Product.equals should not depend on the name of the product. Instead, only the SKU should be compared. Or, even simpler, make sure that you only have a single Product object per product, and don't override hashCode/equals at all.


Improving python3 processing speed (against a reference perl script)

#!/usr/bin/python3
import sys
import re

scripttitle="PYTHON SIMPLE PROCESSOR (regex parsing)"

Python convention is to put constants in ALL_CAPS

linecount=0
commentary=0
unknownline=0
DATA={}

This isn't a constant, so it really shouldn't be all caps.

pattern_data=re.compile(r"^(\d+)\s+(\S+)\s+(\S+)\s+(\d+(?:\.\d+)?)")

print("#",scripttitle,"\n#TRANSFORMED INPUT",sep='')

Its best to put all your actual logic inside a function rather then at the main level of a script. It'll run a bit faster that way.

for line in sys.stdin:
    linecount+=1
    if line.startswith("#"):
        commentary+=1
        continue

I find code is almost always more readable when you put thing in the else block rather then use continue

    line=line.replace(',','')
    m=re.match(pattern_data,line)
    if m:

Typically we'd explicit check for none with if m is not None

        i,k1,k2,value = m.group(1,2,3,4)

Actually you could use m.groups() here. I'd also avoid such unhelpnames as i, k1, and k2

        i=int(i)

I'm not sure why you bother doing this if you are just going to print it out anyways

        value=float(value)
        try:
            DATA[k1][k2]+=value
        except KeyError:
            if k1 not in DATA: # Can't automaticaly create missing key and do the insert?
                DATA[k1]={}
            if k2 not in DATA[k1]:
                DATA[k1][k2]=value
            else:
                DATA[k1][k2]+=value

Python has a useful class called defaultdict. It lets you provide the default value for a dictionary. It also has a class called Counter for counting things So you could do this:

DATA = collections.defaultdict(collections.Counter)

Then

DATA[k1][k2] += value

will always work because the default cases are handled.

        print("{0},{1:.0f},{2},{3}".format(i,value,k2,k1))

It'd probably be easier to follow using sep=',' rather then what you've done here

    else:
        unknownline+=1

print("#DATADUMP")

keystat=0

for k1 in sorted(DATA):

Instead use for k1, items in sorted(DATA.items): Then items will be DATA[k1] and you can relooking up the data

    print(k1,':',sep='',end='')
    for k2 in sorted(DATA[k1]):

Same here, use the .items() to fetch keys and values together

        keystat+=1
        print(' (',k2,':',int(DATA[k1][k2]),')',sep='',end='')
    print()

report="#{0}\n#{1}\nparsed line: {2}, commentary line: {3}, unknown line: {4}, keystat: {5}.".format(
               scripttitle, sys.version.replace("\n"," "), linecount, commentary, unknownline, keystat)

print("#REPORT\n"+report,file=sys.stdout)
print(report,file=sys.stderr)

As for performance, remember that Perl is the practical extraction and report language. This kinda thing is perl's bread and butter, so its gonna be hard for python to win. Doesn't mean I'm not gonna try though.

EDIT: Performance

I've played with improving performance, a few points:

    m=re.match(pattern_data,line)

A better way is to use

    m = pattern_data.match(line)

They both do the same thing, but the first has a speed penalty associated with it.

        print(' (',k2,':',int(DATA[k1][k2]),')',sep='',end='')

The print function is expensive, probably due to its versatility. Rewriting your code to use sys.stdout.write() directly gave much better performance.

    try:
        DATA[k1][k2]+=value
    except KeyError:
        if k1 not in DATA: # Can't automaticaly create missing key and do the insert?
            DATA[k1]={}
        if k2 not in DATA[k1]:
            DATA[k1][k2]=value
        else:
            DATA[k1][k2]+=value

Replacing this with defaultdict or counter harmed performance. I rewrote it as

        try:
            row = DATA[k1]
        except KeyError:
            row = DATA[k1] = {}
        try:
            row[k2] += value
        except KeyError:
            row[k2] = value

Which gave me a speed boost because it avoids looking up the same values in the dictionary more then once.

With those changes I was able to get within one second of the speed of the perl script. But I was still slower. My semi-educated guess is that perl wins due to builtin support for sorting the keys of a hash during iteration. In python the sorting is done in an seperate function and may not be able to take advantage of the same things the perl version can.

FURTHER PERFORMANCE

Put everything in a function. Python optimizes functions more then other code outside of functions.

Replace

for key, value in sorted(data.items()):

with

for key in sorted(data):
    value = data[key]

The first looks nicer, but it requires python to sort a list of tuples rather then a list of strings which ends up more expensive.

Replace

sys.stdout.write(' ({}: {})'.format(k1, math.trunc(v)))

With

sys.stdout.write(''.join([' (', k1, ': ', str(math.trunc(v)), ')']))

String formatting is expensive since python has to parse through the string every time to find the formatting positions.

You can add

write = sys.stdout.write

And then use write instead of sys.stdout.write for a bit of a speed boost. See my tweaked version here: http://pastebin.com/wmaR2Bmx.


Vue.js code to update selection on screen

One technique would be to apply fundamentals of event delegation by adding a method to handle all clicks. For instance, an event listener could be added to the root element (or one if child its child nodes, like a
)

mounted: function() {
    this.$el.addEventListener('click', this.clickHandler);
}

Then have the method accept the click event argument:

clickHandler(clickEvent){

That method could check if the target of the event was a table cell by checking the tagName attribute (for TD). To restrict to only certain table cells, add a class attribute - e.g. team. If that class is found in the target element's classList, set the team property to the innerHTML of the target.

clickHandler(clickEvent){
    const target = clickEvent.target;
    if (target.tagName == 'TD' && target.classList.contains('team')) {
        this.team = target.innerHTML;
    }
}

See a demonstration in the sample below. Notice how there is now a clean separation of the event handling logic (JS) and the markup for display (HTML).

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    team: ''
  },
  mounted: function() {
    this.$el.addEventListener('click', this.clickHandler);
  },
  methods: {
    clickHandler(clickEvent) {
      const target = clickEvent.target;
      if (target.tagName == 'TD' && target.classList.contains('team')) {
        this.team = target.innerHTML;
      }
    }
  }
})

Selected Team: {{ team }}

      WHU
      20 Oct
      BHA

      CHE
      21 Oct
      WAT


Just some quick pointers here to get the more obvious details out of the way.  First, you should not use using namespace std;, but rather explicitly state which namespace you are using like this std::cout.  This prevents namespace clashes, and is discussed in great detail here.

Second, you should use braces around your if/else statements and loops even when there is only one statement after it:

if (soilMoist == wetCheck)
    cout << "It's a sunflower!";
else
    cout << "It's a dandelion!";

Should be:

if (soilMoist == wetCheck)
{
    std::cout << "It's a sunflower!";
}
else
{
    std::cout << "It's a dandelion!";
}

Right here, you should not indent your braces:

if (soilTemp > 75)
    {
    if (soilMoist == wetCheck)
        cout << "It's a sunflower!";
    else
        cout << "It's a dandelion!";
    }

You do not do this in other areas, so I don't know why you did it here.

You should also not indent your cins:

cout << "Enter the soil temperature: ";
    cin >> soilTemp;

You should have your prompts always specify exactly what the input should be.  Here, it looks as if you expect lowercase input: "Is the soil dry or wet? "  However, the program checks for uppercase input.  The best way to fix this would be to allow both "wet" or "Wet".

Otherwise, this looks pretty good.  However, one way you may want to consider expanding your program in is ensuring the user put in the right values instead of merely assuming the right values will be input.  You could do this with a do-while loop, among other ways.

This code is an example of what I mean:

string input = "";

do {
    if (input == "")
    {
        std::cout << "Is the soil dry or wet? ";
    }
    else
    {
        std::cout << "Invalid response.\nIs the soil dry or wet? ";
    }

    std::cin >> input;

} while (input != "Wet" && input != "wet");


Java program to detect the Java class File Format magic number, in a given file

Interface

For clarity, isMagicPresent() should accept a java.io.File (or java.nio.file.Path) to emphasize that the argument is a path and not the contents of a file.

The default constructor should be suppressed.

Implementation

To read a big-endian int, use DataInputStream.readInt().  Then you can compare the magic number to 0xCAFEBABE rather than four bytes.

Driver

I recommend returning a non-zero exit code to indicate that an error has occurred.

When no argument is given, the error message should go to System.err.  (If you supported a -h or --help option, then its output should go to System.out, because that would be the requested output.)

Instead of System.out.println(String.format(…)), you should just call System.out.format(…).  Here, I've chosen to combine both cases into one print statement, but you don't have to.

Suggested implementation

import java.io.*;

public class Magic {
    private Magic() {}

    public static boolean isMagicPresent(File f) throws IOException {
        try (InputStream inStream = new FileInputStream(f);
             DataInputStream dataInStream = new DataInputStream(inStream)) {
            return dataInStream.readInt() == 0xCAFEBABE;
        }
    }

    public static void main(String[] args) {
        if (args.length < 1) {
            System.err.println("Usage: java Magic <FILE>");
            System.exit(1);
        }

        File f = new File(args[0]);
        try {
            System.out.format(
                "'%s' %s the magic number.%n",
                f,
                isMagicPresent(f) ? "contains" : "doesn't contain"
            );
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
            System.exit(1);
        }
    }
}


Get the first positive value that does not exist in array

Review

There are 3 answers already, yet none have addressed the flaws or reviewed your code.

Thus I will give a detailed review and an alternative solution

Your solution has bugs that make a estimation of complexity impossible.

To help review your code I have numbered the lines. See Snippet (B) for line numbers

Flaws AKA bugs

There are many cases where your code can not run. 3 different errors the last is the worst type of error uncatchable.

solution([-1,-2]) will throw an error.
solution([1,2e100]) will throw an error.
solution([1,2**31]) will crash the page after a long hangup on all but the top end machines.

Your code is not \$\mathcal{O}(n^2)\$ but rather it is incomplete or if run on a perfect machine \$\mathcal{O}(\infty)\$ (and same storage) as that is the largest number that the function Math.max can return.

Or if you have a max value less than the array size max then the complexity is \$\mathcal{O}(2^{m+1})\$ where \$m\$ is the max value in the array.Thus the complexity for input [1,2**32-1] is a whopping \$\mathcal{O}(n^{33})\$ and storage of \$\mathcal{O}(n^{32})\$

By the lines

The following numbered items (bold numbers 1) refer to your source code by line number

1 A is a very poor name, arr, array, nums, numbers or many more. Even a would be better as we do not capitalize variable names unless they are instantiatable objects defined as functions or using the class syntax.
2 len should be a constant. eg const len as it  is not to be reassigned at any point in the code.
3, 16 and 17. The if statements can be rearranged to reduce complexity.
4 max should be a constant. Its almost 2019 and the spread operator ... has been available for 4 years, Use it!!! Line 4 becomes const max = Math.max(...A);
5 Use constant const range =. You create an array of indexes from 0 to max. Which is a major problem, (See intro above) The irony is that you can (and do) calculate all the values from 0 to max via the for loop on the next line making line 7.  A.include(range[i]) is identical to A.include(i)
6 range.length is the same as max so use the shorter form for (let i = 0; i < max; i ++) {
7 Use the shorter form for not true if (! A.includes(range[i])) {
8 Use the shorter form is truthy. All numbers  !== 0 are truthy true thus this line can be if (range[i]) {
9 Could be return i;
11 and line 13 the continue is not needed as you are at the bottom of the for loop at those lines already.
16 Use the strict equality operator len === 1. use the shorter not form of  val < value || val > value as val !== value, making the line } else if (len === 1 && A[0] !== 1) {
18 Use the strict equality operators, There is no need for the  () around each clause } else if (len === 1 && A[0] === 1) {

General points.

If you return inside a statement block, you should not include the else at the end as It will never be used. Thus lines 16 and 17 do not need the else and can be moved down one line (away from the closing })
Though not a must it is cleaner to put spaces after for, if, else etc, before else, between ){
When you find you are needing to search a set of values repeatedly it pays to consider using a Map or Set to find the matches as they use a hash to lookup values and have a complexity of \$\mathcal{O}(1)\$ for the search, however to create the lookups is \$\mathcal{O}(n)\$. Thus using a Map or Set you can easily reduce complexity from \$\mathcal{O}(n^2)\$ to \$\mathcal{O}(n)\$. There is a storage penalty meaning you can go from \$\mathcal{O}(1)\$ to \$\mathcal{O}(n)\$.

Rewriting you code

Using a Set to remove the \$\mathcal{O}(n)\$ overhead of each Array.includes

The Set positiveInts can be created as we iterate the array, saving a little complexity.

I assume array items are less than or equal to Number.MAX_SAFE_INTEGER

Snippet (A)

function solution(array) {
    var min = 1;
    if (array.length === 1) {
        min = array[0] === 1 ? 2 : min;
    } else if (array.length) {
        const positiveInts = new Set();
        for (const val of array) {
            if (val > 0) {
                positiveInts.add(val);
                if (val === min) {
                    while (positiveInts.has(min)) { min ++ }
                }
            }
        }
    }
    return min;
}

Snippet (B)

/*lines*/
/* 1*/function solution(A) {
/* 2*/    var len = A.length;
/* 3*/    if(len > 1){
/* 4*/        let max = Math.max.apply(null, A);
/* 5*/        let range = Array.from(Array(max).keys());
/* 6*/        for(let i = 0; i < range.length; i++){
/* 7*/            if(A.includes(range[i]) === false){
/* 8*/                if(range[i] > 0){
/* 9*/                    return range[i];
/*10*/                }
/*11*/                continue;
/*12*/            }
/*13*/            continue;
/*14*/        }
/*15*/        return max + 1;
/*16*/    }else if(len == 1 && (A[0] < 1 || A[0] > 1)){
/*17*/        return 1;
/*18*/    }else if((len == 1) && (A[0] == 1)){
/*19*/        return 2;
/*20*/    }
/*21*/    return 1;
/*22*/}


Finding the sum of all the segment counts of a 7-segment display in a range

Here are some things that may help you improve your program.  First, I'll mention a few things about the code you've already written, and then I'll describe an idea for a better algorithm.

Be careful with signed versus unsigned

By the problem description, neither start nor end can be less than 1, so they should probably be declared as unsigned rather than int.

Isolate calculation from I/O

The main routine does both the input and output and also is materially involved in the main calculation.  I'd advocate that that function should be isolated like this:

int segcount(unsigned start, unsigned end)
{
  unsigned sum = 0;
  for(auto i = start; i <= end; ++i) {
    std::string current_num = std::to_string(i);
    for(auto c: current_num) {
      sum += get_number_of_segments(c);
    }
  }
  return sum;
}

int main() {
  unsigned start, end;

  std::cin >> start >> end;
  auto sum = segcount(start, end);
  std::cout << sum << '\n';
}

Use const where practical

The segment_count map shouldn't be changed once constructed, and so it should be declared const.

Avoid global variables

The segment_count variable is only used within get_number_of_segments(), so it should go there instead of being a global.  I would also avoid the overhead of the std::unordered_map by using a simple array:

unsigned get_number_of_segments(char num) {
    static constexpr std::array<unsigned, 10> segment_count{
        6, 2, 5, 5, 4, 5, 6, 3, 7, 6
    };
    return segment_count[num-'0'];
}

A better algorithm

Your existing code, while not the fastest possible, does have a significant advantage in that it is obviously correct.  We can use that to verify any alternative approach as well as using it for timing comparisons.   From here to the end of this review, I'll be showing stepwise improvements in the code.

Write a test harness

We might write several versions of the code and want to compare them.  One nice way to do that is using a templated structure and a macro like this:

template <typename F>
struct testfunc {
    F *fn;
    const char *name;
};

#define TEST(x) { x, #x }

Now we can easily make an array of tests and run through all alternative algorithms:

#include "stopwatch.h"
int main()
{
    const testfunc<decltype(segcount)> test[]{
        TEST(segcount),
        TEST(segcount2),
    };

    unsigned start, end, sum;

    std::cin >> start >> end;
    for (const auto t : test) {
        Stopwatch<std::chrono::milliseconds> sw;
        sum = t.fn(start, end);
        std::cout << t.name << ": " << sum << ", " << sw.stop() << "ms\n";
    }
}

Note that this uses my Stopwatch template, but one could use an alternative if desired.

Think carefully about the problem

First, let's consider a range of single digit numbers.  If we go from 1 to 5, for example, we simply add up the segment counts for each of those digits \$= 2+5+5+4+5 = 21\$.  For a range that doesn't start from 1, such as for 3 to 5, we can calculate it one of two ways.  We could calculate just for those numbers \$= 5+4+5 = 14\$ or we could calculate 1 to 5 and subtract 1 to 2.  The motivation for doing it by the latter method is that we can precalculate all possible ranges for a digit and then simply do two lookups and a subtraction.

We can now extend this to look at two-digit numbers.  If we have a range in which the first digit doesn't change, such as 71 to 75 it's simply the single digit range 1 to 5 (which we already calculated above is 21) plus the size of the range (5) times the segments for the first digit (3), so the answer is \$21 + 5(3) = 36\$.

If it's a two-digit number for which the first digit does change, we can break it down into a sum of two-digit ranges for which the leading digit is constant.  For example, if we go from 71 to 88, we can consider it as two subranges: 71 to 79 and 80 to 88 where the algorithm above could be applied.

I think you can probably take it from there and see how to extend the algorithm generically.