Wrapping your methods in a class definition isn't the same thing as making your project OOP. These methods don't care about their receiver, and forcing the programmer to instantiate the PrintJobs class before calling them doesn't accomplish anything useful here. Now, for special-purpose scripts like this, not being OO isn't the worst thing in the world - in fact, going OO can be design overkill for a project this small. However, if you go the functional route, tell it like it is - refactor class PrintJobs to module PrintJobs (because Module is, idiomatically, the correct type for a collection of associated methods) so that you can do your invocation with PrintJobs.scan_for_jobs.

If you want to convert the code to be more OO - to make it easier to incorporate into another project, for example - objects need to be responsible for the data they operate on. That means that the HOST/USERNAME/PASSWORD values need to be instance variables, not class constants. You also want to be sure that your data is typed appropriately. Currently, there's a lot of passing around and manipulation of strings that represent print jobs. If the output format of prt_jobs ever changes, we'll need to update every piece of code that interacts with these objects. Abstracting them into their own type will help prevent this.

Stylistic touches:

Get rid of extraneous definitions - cmd is defined and then only used once, in the immediately following line. Some other variables are defined and then never used.
Avoid abbreviation. I assume res means "results", but I'm not sure.
Exiting with a non-zero status code should only happen if the program encounters some sort of error, which isn't the case with your usage. I'd remove the statement entirely, since there's no real reason for PrintJobs to be responsible for program termination anyway.
Last but not least, the word is "queue".

Here's the class refactored, with additional comments in-line. Since I don't have a print server handy the code has not been tested and probably contains bugs, but it should give you an idea of what a more object-oriented structure looks like.

class PrintManager
  # I've made the PrintJob class belong to PrintManager for now,
  # but you could move it to global scope if it becomes handy elsewhere
  class PrintJob
    attr_reader :printer, :id, :user, :some_other_thing, :date

    def initialize(printer, id, user, some_other_thing, date)
      @printer, @id, @user = printer, id, user
      @some_other_thing, @date = some_other_thing, date
    end

    # If the output of `prt_jobs` ever changes, this is the only code you'll
    # need to update.
    # In real life we'd want to parse the time into a proper Time object.
    def self.parse(job_string)
      job_string =~ /^(\S+)-(\d+)\s+(\S+)\s+(\d+)\s+(.+?)\s*$/
      return self.new($1, $2.to_i, $3, $4.to_i, $5)
    end

    def to_s
      "#{@printer}-#{@id}\t#{@user}\t#{@some_other_thing}\t#{@date}"
    end
  end

  def initialize(host, username, password)
    @host, @username, @password = host, username, password
  end

  def scan_for_jobs
    Net::SSH.start(@host, @username, :password => @password) do |ssh|
      info = ssh.exec!("prt_jobs")
      if info == nil
        puts "No print jobs on server #{@host}"
      else
        # The old "res" object we got here was a big blobby String.
        # Now we have an Array of PrintJobs, which is much easier
        # to interact with.
        print_jobs = info.split("\n").map {|line|
          PrintJob.parse(line)
        }
        print_jobs.reject! {|job| job.date.match(/\s+2016\s+/) }

        # One disadvantage of parsing out the string at object
        # creation is that we lose formatting, and our tab stops
        # may not line up without some extra effort. Oh well!
        puts print_jobs
        print "Kill these jobs (yes/no): "
        input = STDIN.gets.chomp.upcase
        if input == "YES"
          # The kill_queue method only really existed to do string
          # parsing. We accidentally made it unnecessary when we made
          # PrintJob a real class.
          print_jobs.each { |job| kill_job(job, ssh)}
        end
      end
    end
  end

  # Since kill_job is only called from within scan_for_jobs, we'll
  # just reuse its SSH object. Depending on how your program grows, it
  # may be better to have kill_job open its own SSH connection like
  # you had originally, or make it an attribute of PrintManager, or
  # something else.
  def kill_job(job, ssh)
    # Got to remove a bunch more string parsing here
    puts "Cancelling job: #{job.id}"
    ssh.exec!("sudo cancel #{job.id}")
  end
end

killer = PrintManager.new(ARGV[0], Etc.getlogin, nil)
killer.scan_for_jobs


VBA Macro to generate a report of mean values for each date

In my example the iteration needs 2 seconds. How long is your code running?

Note 1:
Reduce the number of iterations. You are iterating 100.000 times

Note 2:
You are accessing the same cell Cells(l, 2).Value very often in the second for loop. But the value does not change. It will change in the first for loop.

You can save the value in a local variable in the first loop:

Dim l2 As Variant
l2 = Cells(l, 2).Value

Note 3:
You are accessing the same 90 cells Cells(1, m).Value very often too (1000 times).

You can save the 90 values in an array before looping:

Dim Arr() As Variant
Arr = Range("K1:CV1")

My complete code looks like this:

' Mean Value
Dim Arr() As Variant
Arr = Range("K1:CV1")
Dim l As Integer, m As Integer
For l = 2 To 1000
    Dim l2 As Variant
    l2 = Cells(l, 2).Value
    For m = 1 To 90
        If l2 = Arr(1, m) Then
            Cells(l, m).Value = Cells(l, 5).Value
        End If
    Next m
Next l


-- for a given y = (y_1,...,y_n) and a bound m, find all vectors
-- x = (x_1,...,x_n) such that |x| = m and x_i <= y_i
boundSequences :: (Num a, Ord a, Enum a) => a -> [a] -> [[a]]
boundSequences m x | m <= sum x = (fByM . sequence . ranges) x
                   | otherwise = [[]]
    where fByM = filter (\x -> sum x == m)
          ranges = map (\x -> [0..x])

Excepting some fortunate cases, you are wasting a lot of work here. sequence . ranges produces (y_1+1) * ... * (y_n+1) lists you have to check. If you write a function to produce only the successful lists, you can gain a lot of performance for larger input (it won't do too much for short lists with small elements, but it will help for those too).
Shouldn't the case sum x < m return [] rather than [[]]?

-- return all the possible arc combinations  to an equivalence
-- class for a given number of arcs
connectionCombinations :: Int -> EquivClass -> [NodeSelection]
connectionCombinations arcs = map groupOcc . prune arcs . sequence . orderRep
    where orderRep (EC o v) = replicate (length v) [0..o]
          prune a = nub . map (reverse . sort) . filter ((== a) . sum)
          groupOcc = filter ((/= 0) . fst) . occurences

Instead of reverse . sort, use sortBy (flip compare). That won't make much difference for short lists, but it's cleaner, IMO. prune arcs . sequence contains another occurrence of the boundSequences problem, creating a lot of lists and filtering out most of them immediately. nub is not good, it is quadratic (worst case, O(total*distinct) in general). The things you're nubbing have an Ord instance, if the order doesn't matter, map head . group . sort is a much faster nub than nub (still better Data.Set.toList . Data.Set.fromList), if order matters, keep a Set of seen elements and for each new, output that and add it to the set of seen.

I've not yet profiled, but it may be that the profile is misleading because it attributes costs to the functions where results are forced rather than where they are calculated, that needs some investigation, check back later.

Okay, the given data doesn't run long enough to produce a meaningful profile, so I changed it to

let cons = connections [EC 4 [1 .. 6], EC 6 [2 .. 9]] 5

That runs long enough to collect a handful of samples. Unfortunately, the profile wasn't very informative:

    total time  =        7.90 secs   (395 ticks @ 20 ms)
    total alloc = 8,098,386,128 bytes  (excludes profiling overheads)
COST CENTRE                    MODULE               %time %alloc
connectionCombinations         Main                 100.0  100.0

So I inserted a couple of {-# SCC #-} pragmas. The biggo in that programme is the sequence . orderRep, unsurprisingly. A rewrite along the lines mentioned above,

boundSequences :: (Num a, Ord a, Enum a) => a -> [a] -> [[a]]
boundSequences m xs
    | sm < m    = []
    | sm == m   = [xs]
    | otherwise = go sm m xs
      where
        sm = sum xs
        go _ r []
            | r == 0 = [[]]
            | otherwise = []
        go _ r [y]
            | y < r     = []
            | otherwise = [[r]]
        go s r (y:ys) = do
            let mny | s < r+y   = r+y-s
                    | otherwise = 0
                mxy = min y r
            c <- [mny .. mxy]
            map (c:) (go (s-y) (r-c) ys)

and using that in connectionCombinations instead of prune arcs . sequence (requires a small change in orderRep),

connectionCombinations :: Int -> EquivClass -> [NodeSelection]
connectionCombinations arcs = map groupOcc . nub . map (sortBy (flip compare)) .
                                     boundSequences arcs . orderRep
    where orderRep (EC o v) = replicate (length v) o
          groupOcc = filter ((/= 0) . fst) . occurences

brought the running time (ghc -O2, no profiling) down significantly:

dafis@schwartz:~/Cairo> time ./orArcs > /dev/null

real    0m5.836s
user    0m5.593s
sys     0m0.231s
dafis@schwartz:~/Cairo> time ./arcs > /dev/null

real    0m0.008s
user    0m0.005s
sys     0m0.003s

Whether any further optimisations (e.g. the abovementioned nub) are necessary, and where most of the time in the actual programme is spent, so that one could identify the most important points, I cannot tell without more realistic data.


Euler problem 3: largest prime factor of the number

When I look at your solution, the first impression I get is that it's too complicated. To solve the problem you don't need any fancy algorithms for prime numbers, or islice and count. It's a simple task of trying to divide by possible factors.

One important thing to note is that we only need to check for prime factors that are smaller than the square root of the number. Once we have reached the square root, there can be only one remaining factor, which can be proved by contradiction.

Another important thing to note is that once we have found a prime factor, we can divide the original number by that factor and reduce our problem size.

Doing both of these things, I end up with something like this:

def get_max_prime_factor(n):
    d = 2
    factors = []
    while d*d <= n:
        while n%d == 0:
            n //= d
            factors.append(d)
        d += 1
    if n != 1:
        factors.append(n)
    return max(factors)

Now, I'll say that even this implementation might be too complicated, since I'm saving all prime factors in a list instead of only keeping track of the largest one. If you want you could change that implementation and make it even more efficient, but to solve the problem above it's not necessary.


Is there something wrong with my solution? I don't think so.
Have I missed any problems?

Omitted Information stream, cf How to process Write-Information pipeline output when using SilentlyContinue
The -Debug parameter  overrides the value of the $DebugPreference variable for the current command, setting the value of $DebugPreference to Inquire. Prompts to continue for every Write-Debug statement which may be considered inconvenient (or even harmful) in batch processing.

Here's my solution (partially commented script):

[CmdletBinding()]
param(
   # [switch]$debug   # alternative to [CmdletBinding()]
)

function Split-Streams {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,ValueFromPipeline)]
        [ValidateNotNull()]   # avoid crashing . property dereference operator
        $InputStream,
        [switch]$revert
    )
    process {
        if ( -not $revert.IsPresent ) {
            # return an object which contains type and value of $InputStream
            [PSCustomObject] @{
                stream = $InputStream.GetType().FullName
                value  = $InputStream
            }
        }
        else {
          # basic input object validity check
          if ( ($InputStream.psobject.Properties.Name -join ',') -match
                    "\bstream\b.*\bvalue\b|\bvalue\b.*\bstream\b" ) {
            # review split streams and handle them individually
            switch($InputStream.stream)
            {
                'System.Management.Automation.DebugRecord' {
                    # Do whatever you want, like formatting an writing to a file.
                    Write-Host ($InputStream.value) -ForegroundColor Gray
                }
                'System.Management.Automation.ErrorRecord' {
                    Write-Host ($InputStream.value) -ForegroundColor Red
                    Write-Host ('Error function: {0}' -f ($InputStream.value).InvocationInfo.MyCommand.Name) -ForegroundColor DarkRed
                }
                'System.Management.Automation.VerboseRecord' {
                    Write-Host ($InputStream.value) -ForegroundColor Cyan
                }
                'System.Management.Automation.WarningRecord' {
                    Write-Host ($InputStream.value) -ForegroundColor Yellow
                }
                'System.Management.Automation.InformationRecord' {
                    Write-Host ($InputStream.value) -ForegroundColor Green
                }
                default {
                    Write-Host "output type: $($InputStream.stream)" -ForegroundColor Blue
                    # keep original output stream unchanged
                    $InputStream.value
                }
            }
          }
        }
    }
}

function Write-Messages
{
    [CmdletBinding()]
    param()
    Write-Debug       "Debug message $DebugPreference"
    Write-Verbose     "Verbose message $VerbosePreference"
    Write-Warning     "Warning message $WarningPreference"
    Write-Error       "Error message $ErrorActionPreference"
    Write-Information "Information message $InformationPreference"

    # Write-Output: it is generally not necessary to use the cmdlet.
                      'Output message'
    #               I'm checking a more complex object than plain string
    Write-Output       $Host
}

$DebugPreferenceSave = $DebugPreference     # backup $DebugPreference
If ($PSBoundParameters['Debug']) {
    # The Debug parameter overrides the value of the $DebugPreference
    #     variable for the current command, setting the value
    #     of $DebugPreference to Inquire.
    # The following setting suppresses asking whether you want to continue
    # even if examined `Write-Messages` is a third-party black box.
    $DebugPreference = 'Continue'
}

Write-Messages -Verbose *>&1 | Split-Streams | Split-Streams -revert

$DebugPreference = $DebugPreferenceSave     # restore $DebugPreference

Alternatively to the (sample) usage in the one pipeline:

Write-Messages -Verbose *>&1 | Split-Streams | Split-Streams -revert

(cf above code) you can call it as follows:

$test3 = Write-Messages -Verbose *>&1 | Split-Streams
# preprocess the $test3 variable here (optional)
$test3 | Split-Streams -revert


There are a few things you could improve. First, the most important if you want to write Python code that scales to more than a script that does just one thing, you should write functions (or classes). They have the nice feature that you can give them a name, which tells you roughly what they do, and you can give them a docstring which can describe what they do in even more detail.

Bug:

While you do iterate over the sheet names, you do not actually change sheets. workbook.active does not automatically switch to another name. Instead, directly iterate over the workbook.

Otherwise here are a few suggestions:

Instead of using os.listdir, you can use pathlib.Path, which has a glob method, to get all excel files in the current directory:

from pathlib import Path

excel_files = Path(".").glob("*.xlsx")

This way you also don't have to deal with different path delimiters in Unix and Windows and manually getting the current directory.

Python can also work with relative paths, so no need to get the current directory at all.
You should use the with keyword to ensure that the files you open are closed, even in the event of an exception.
openpyxl sheets have the attributes rows and columns, which lets you easily iterate over them. You should also learn about list comprehensions. In addition, a csv.writer has the writerows method that can take an iterable of rows to write.
Using regex just to replace a single string with nothing is overkill. You could just use str.replace. But here building the string constructively is probably easier. Learn about f-strings in Python 3.6+.
Instead of moving the file afterwards with shutils, directly save it to the right file.
Use a if __ name__ == "__main__": guard to allow importing from this script from another script.

With these changes your code could become:

import csv
import openpyxl
from pathlib import Path

def convert_all_sheets_to_csv(file_name, target_dir="."):
    """Convert all sheets to csv files saved in the folder `target_dir`."""
    workbook = openpyxl.load_workbook(file_name)
    out_file_name_template = Path(target_dir) / Path(file_name).stem
    for sheet in workbook:
        out_file_name = f"{out_file_name_template}_{sheet.title}.csv"
        convert_sheet_to_csv(sheet, out_file_name)

def convert_sheet_to_csv(sheet, file_name):
    """Convert the content of an excel sheet to a csv file."""
    with open(file_name, "w") as f:
        writer = csv.writer(f)
        writer.writerows([cell.value for cell in row] for row in sheet.rows)

if __name__ == "__main__":
    for excel_file in Path(".").glob("*.xlsx"):
        convert_all_sheets_to_csv(excel_file, target_dir="csv_files")


Getting initial values of non-primitive types from another Javascript file?

So here's what I've ended up doing:

INITIAL_VALUES.js

function GET_FEATURE_TYPES_INITIAL_VALUES() {
  const FEATURE_TYPE_INITIAL_VALUES = {
    SINGLE_CHOICE: '',
    MULTIPLE_CHOICE: [],
    BOOLEAN: false,
    NUMBER: 0,
    STRING: ''
  };
  return FEATURE_TYPE_INITIAL_VALUES;
}

function GET_FILTER_TYPES_INITIAL_VALUES() {
  const FILTER_TYPE_INITIAL_VALUES = {
    NUMBER_RANGE_ALLOW_MULTIPLE: [],
    NUMBER_ACUM_RANGE_ALLOW_SINGLE: [],
    SINGLE_CHOICE_ALLOW_SINGLE: [],
    SINGLE_CHOICE_ALLOW_MULTIPLE: [],
    MULTIPLE_CHOICE_ALLOW_MULTIPLE: [],
    BOOLEAN_ALLOW_MULTIPLE: [],
    STRING_ALLOW_MULTIPLE: []
  };
  return FILTER_TYPE_INITIAL_VALUES;
}

function GET_FIELD_TYPES_INITIAL_VALUES() {
  const FIELD_TYPE_INITIAL_VALUES = {
    STRING_FIELD: '',
    BOOLEAN_FIELD: '',
    NUMBER_FIELD: 0,
    ARRAY_STRINGS_FIELD: [],
    ARRAY_OBJECTS_FIELD: [],
    OBJECT_FIELD: {}
  };
  return FIELD_TYPE_INITIAL_VALUES;
}

export {
  GET_FEATURE_TYPES_INITIAL_VALUES,
  GET_FILTER_TYPES_INITIAL_VALUES,
  GET_FIELD_TYPES_INITIAL_VALUES
};

SomeComponent.js

import { GET_FEATURE_TYPES_INITIAL_VALUES } from '@constants/INITIAL_VALUES';

function SomeComponent() {
  const FEATURE_TYPES_INITIAL_VALUES = GET_FEATURE_TYPES_INITIAL_VALUES();

  // FRESH NEW INITIAL_VALUES AVAILABLE ON EVERY RENDER
}


Ensuring valid origin and destination countries

Representing a country (OOP)

So it seems that your array of countries ($pBCountries) has the following structure:

[
    [
        "id" => "0",
        "name" => "Netherlands"
        "country_code" => "NL"
    ],
    [
        "id" => "1",
        "name" => "United Kingdom"
        "country_code" => "UK"
    ],
]

Now that we have that figured out, lets take a look at how we can improve this. Generally we do not like to work with arrays like this, as it is extremely unclear how they are structured to outside users (as you have seen from the comments to your question).

What we do like working with are objects. Objects are a much better way of representing stuff than arrays are. We can create a simple object that represents a country like so:

class Country {
    private $id;
    private $name;
    private $code;

    /**
     * @param string|int $id
     * @param string $name
     * @param string $code
     */
    public function __construct($id, $name, $code) {
        $this->id = (string) $id;
        $this->name = (string) $name;
        $this->code = (string) $code;
    }

    /**
     * @return string
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getName() {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getCode() {
        return $this->code;
    }
}

Now we have a simple, immutable country object. The private fields cannot be changed from the outside.

Creating the Country objects

Now we still need a function which creates a bunch of these Country objects from your array. For this we are going to create a createMultipleFromArray() function on the Country object:

class Country {
    /* private fields */

    /**
     * @param array countries
     * @return Country[]
     */
    public static function createMultipleFromArray(array $countries) {
        $countries = array();

        foreach ($countries as $country) {
            array_push($countries, self::createFromArray($country));
        }

        return $countries;
    }

    /**
     * @param array $country
     * @return Country
     */
    public static function createFromArray(array $country) {
        return new Country($country["id"], $country["name"], $country["country_code"]);
    }

    /* constructor and getters */
}

I have omitted the private fields, constructor and getters from this snippet and replaced them with a comment, so that you can understand where I would place the methods but without me having to copy them over to this snippet as well.

You have probably noticed that I have annotated most functions with some @return and @param annotations. These annotations are extremely useful as they tell you what type is expected for certain arguments and what type will be returned. If you are using an IDE like PhpStorm this is even more helpful, as PhpStorm will know which methods are available on a Country object and can auto-complete them for you. This is a lot less error prone than fiddling with array indices yourself.

Now we can create an array of Country objects by simple doing:

// p.s. $pBCountries is a pretty bad name for an array of countries
$countries = Country::createMultipleFromArray($pBCountries);

Array Intersection

Now that we have cleaned up that mess of an array, lets get back to the actual function. First of all, your checkCountry() function would be better off taking two explicit $country_from and $country_to parameters, instead of relying on an array to be passed which may or may not contain these indices. This makes the function more clean.

The functionality of your function can actually be extracted to a much more general concept called array intersection. Array intersection is a function that takes two arrays and returns a new array containing only the elements that are in both arrays.

To achieve this, we first need a function which can determine if two Country objects are the same. We do this by creating an equals() method on the Country object:

class Country {
    /* private fields and constructor */

    /**
     * @param Country $other_country
     * @return bool
     */
    public function equals(Country $other_country) {
        return $this->id == $other_country->getId() &&
            $this->name == $other_country->getName() &&
            $this->code == $other_country->getCode();
    }

    /* Getter functions */
}

Now we can create a separate class that can perform an intersection of two arrays of Country objects:

class CountryFilter {
    /**
     * @param Country[] $countries_to_filter
     * @param Country[] $countries
     */
    public static function intersect(array $countries_to_filter, array $countries) {
        $intersected_countries = array();

        foreach ($countries as $country) {
            if (self::contains($countries_to_filter, $country)) {
                array_push($intersected_countries, $country);
            }
        }

        return $intersected_countries;
    }

    /*
     * @param Country[] $country_array
     * @param Country $country
     */
    public static function contains(array $country_array, Country $country) {
        foreach ($country_array as $country_from_array) {
            if ($country->equals($country_from_array)) {
                return true;
            }
        }

        return false;
    }
}

The contains() method I think doesn't really belong on the CountryFilter class, but actually on a class like CountryList, which is a class that holds an array of countries and provides the contains() functionality. But I figured that would probably take it too far, so I kept it at the CountryFilter class.

Assuming that you have changed $row['country_from'] and $row['country_to'] to be actual Country objects and $pBCountries to be an array of Country objects, we can now perform this function call to achieve the same results as the countryChecker() method:

$intersection = CountryFilter::intersect($pBCountries, [$row['country_from'], $row['country_to']]);

This refactor resulted in much more general classes and functionality with a lot of reusability. The intersect() method can be used for any two arrays of countries and is therefore very versatile. Each of these small pieces of code are very readable and easy to understand, which will in turn make other code that utilizes these two classes more easy to understand as well.

Thus code readability and reusability have greatly been improved.


Unit test with Moq callback anonymous function

I think, for what it's worth, you have mostly only succeeded in testing your mocks here.  Even if you moved these mocks out of the test, I think you'd still only be testing your mock implementation and not much production code. So these tests can pass all day long without reflecting the condition of your production implementations.  (If I'm understanding every properly :)

[Test]
public void GetFollowedByUserIdShouldGetTheUsersFollowedOpportunitiesFromOpportunityFollowRepositoryAndThenGetThoseFollowedOpportunities()
{
    const int ExpectedOpportunityId = 9;

    var testOpportunities = new List<Domain.EF.Opportunity>()
    {
        OpportunityBuilder.Default().WithId(1).Build(),
        OpportunityBuilder.Default().WithId(2).Build(),
        OpportunityBuilder.Default().WithId(ExpectedOpportunityId).Build(),
    };

    var actualOpportunities = new List<Opportunity>();

    var expectedOpportunityFollows = new List<OpportunityFollow> { new OpportunityFollow { OpportunityFollowId = 1, OpportunityId = ExpectedOpportunityId, UserId = UserId } };
    mockOpportunityFollowRepository.Setup(x => x.GetByUserId(UserId)).ReturnsAsync(expectedOpportunityFollows);

    mockOpportunityRepository.Setup(
        s =>
            s.GetAsync(
                It.IsAny<Expression<Func<Domain.EF.Opportunity, bool>>>(),
                It.IsAny<Func<IQueryable<Domain.EF.Opportunity>, IOrderedQueryable<Domain.EF.Opportunity>>>(),
                It.IsAny<int?>(),
                It.IsAny<int>()))
        .Callback<
            Expression<Func<Domain.EF.Opportunity, bool>>,
            Func<IQueryable<Domain.EF.Opportunity>,
            IOrderedQueryable<Domain.EF.Opportunity>>,
            int?,
            int>((queryParam, sortParam, takeParam, skipParam) =>
            {
                var func = queryParam.Compile();
                actualOpportunities = testOpportunities.Where(func).ToList();
            });

    // NOTE: not sure which guy your sut variable is here.
    // NOTE: no assertions on the results is suspect.
    var results = sut.GetFollowedByUserId(UserId);

    // NOTE: this is testing the plumbing of a function.  that my thing called another thing.  in general,
    //       i have found this kind of testing to be less valuable and brittle.  if the function
    //       can do the job without calling the other thing in the future, this test will break,
    //       even though the function works properly. ymmv.
    mockOpportunityFollowRepository.Verify(x => x.GetByUserId(UserId), Times.Once);

    // NOTE: unfortunately, all thats tested here is that the mock implementation returns
    //       the right result.  no production code is exercised for these.
    actualOpportunities.Count.Should().Equals(1);
    actualOpportunities[0].OpportunityId.Should().Equals(ExpectedOpportunityId);
}

For all the mocking etc... I believe the above code is functionally equivalent as what I have below (or close to it).  And almost all of it is still mock implementation.  What production code we are testing is hard to know.

[Test]
public void GetFollowedByUserIdShouldGetTheUsersFollowedOpportunitiesFromOpportunityFollowRepositoryAndThenGetThoseFollowedOpportunities()
{
    const int ExpectedOpportunityId = 9;

    var testOpportunities = new List<Domain.EF.Opportunity>()
    {
        OpportunityBuilder.Default().WithId(1).Build(),
        OpportunityBuilder.Default().WithId(2).Build(),
        OpportunityBuilder.Default().WithId(ExpectedOpportunityId).Build(),
    };

    Expression<Func<Domain.EF.Opportunity, bool>> queryParam; // = ???

    var actualOpportunities = new List<Opportunity>();
    var func = queryParam.Compile();

    actualOpportunities = testOpportunities.Where(func).ToList();

    actualOpportunities.Count.Should().Equals(1);
    actualOpportunities[0].OpportunityId.Should().Equals(ExpectedOpportunityId);
}

You could consider this to be more of an integration test.  But then what's being tested?  That entity framework works?  Or SQL?  If so, these fall significantly outside of the boundaries of what a unit test can do well for you.

For my money it's an integration test and needs to exercise production code.  I think you can safely remove this test as a unit test.


Need a better way to create subclass instances from a base class reference

There sure is. You created a redundant way to create a FeatureMap and that is why you are having so much trouble with it. Your createFeatureMapWithMandatoryValues is pretty much useless.
When you do something such as:

FeatureMap featureMap = new FoodFeatureMap("Chinese");

You already have everything that you would ever want. By looking at FoodFeatureMap ctor we can see that you already correctly add the values that are mandatory because you have to create an instance of FoodFeatureMap by calling it.

public FoodFeatureMap(@NonNull String foodTypeValue) {
    addFeature(foodType, foodTypeValue);//this already correctly adds the value to the map
}

And thus the resulting code becomes this.

public abstract class FeatureMap {
    private Map<String, Object> features;
    public FeatureMap() {
        features = new HashMap<>();
    }

    protected void addFeature(@NonNull String name, @NonNull Object value) {
        features.put(name, value);
    }
}

class FoodFeatureMap extends FeatureMap {
    private static final String foodType = "foodType";

    public FoodFeatureMap(@NonNull String foodTypeValue) {
        addFeature(foodType, foodTypeValue);
    }
}

class HumanFeatureMap extends FeatureMap {
    private static final String name = "name";
    private static final String origin = "origin";

    public HumanFeatureMap(@NonNull String nameValue, @NonNull String originValue) {
        addFeature(name, nameValue);
        addFeature(origin, originValue);
    }
}

class Main {
    public static void main(String[] args) {
        FeatureMap featureMap = new FoodFeatureMap("Chinese");
        //do something with FeatureMap
    }
}

Now what comes ahead maybe for example turn your FeatureMap into an Iterable so you can get all the values that are on it


Matching and Merging CPU info between worksheets

Three initial points:

Always use Option Explicit at the top of the module. Always!
Properly indent your code to help with readability and exposure of some of the logic.
Avoid using .Activate and .Select in your code. It is not necessary unless you want to bring something to the user's attention.

You have d, x, y, z but no real understand what they mean. Particularly d, which is not used anywhere except to be incremented!

Taking these points into account, you end up with:

Sub automateCpu()
Dim noofComps As Long
Dim test as Range
Dim testS as Range
Dim test1 as Range
    set test1 = Worksheets("Test1").Range("A1")
    noOfComps = testRange.CurrentRegion.Rows.Count-1
Dim x As Long
    x = 0
Dim d As Integer
    d = 0
    Do While x > noOfComps
        Set test1 = test1.Offset(1,0)
        Dim curComputer As String
        curComputer = testRange.Value
        Dim test1Row As Integer
        d = d + 1
        test1Row = test1.Row
        Dim testS as Range
        Set testS = Sheets("TestS").Range("A1") ' Why "Sheets" instead of "Worksheets" as in the other case? Consistency!
        Dim y As Integer
        y = 0
        Dim z As Integer
        z = 0
        Dim LastRowSummary As integer
        LastRowSummary = testS.CurrentRegion.Rows.Count - 1
        Do While y < LastRowSummary
            Set testS = testSRange.Offset(1, 0)
            If testS.Value = curComputer Then
                z = 1
                Dim SummaryRow As Integer
                SummaryRow = testS.Row
                Set test1 = Sheets("Test1").Range("B" & test1Row)
              Dim curLogValue As Integer
              curLogValue = test1.Value

              Set testS = Sheets("TestS").Range("B" & SummaryRow)
              testS.Value = curLogValue

              Set test1 = Sheets("Test1").Range("A" & test1Row)
              Exit Do
         End If
         y = y + 1
      Loop

      If z = 0 Then
         d = d + 1
         set test1 = test1.Offset(1, 0)
         test1.Value = curComputer
         SummaryRow = test1.Row

         set test1 = Sheets("Test1").Range("B" & test1Row)
         Dim curLogValue As Integer
         curLogValue = test1.Value

         Set testS = Sheets("TestS").Range("B" & SummaryRow)
         testS.Value = curLogValue

         Set test1 = Sheets("Test1").Range("A" & test1Row)
      End If
      z = 0
      d = d + 1
      x = x + 1
   Loop
   End Sub

But, looking at the code, you can see that there is a lot of shuffling of data into temporary variables. We can also clean this up with direct assignments.

Sub automateCpu()
Dim noofComps As Long
Dim test as Range
Dim testSA as Range
Dim test1A as Range
Dim testSB as Range
Dim test1B as Range
    set test1A = Worksheets("Test1").Range("A1")
    noOfComps = testRange.CurrentRegion.Rows.Count-1
Dim x As Long
    x = 0
    Do While x > noOfComps
        Set test1A = test1A.Offset(1,0)
        Dim curComputer As String
        curComputer = testRange.Value
        Dim test1Row As Integer
        test1Row = test1A.Row
        Set testSA = Sheets("TestS").Range("A1") ' Why "Sheets" instead of "Worksheets" as in the other case? Consistency!
        Dim y As Integer
        y = 0
        Dim z As Integer
        z = 0
        Dim LastRowSummary As integer
        LastRowSummary = testS.CurrentRegion.Rows.Count - 1
        Do While y < LastRowSummary
            Set testSA = testSRange.Offset(1, 0)
            If testSA.Value = curComputer Then
                z = 1
                Dim SummaryRow As Integer
                SummaryRow = testSA.Row
                Set test1B = Sheets("Test1").Range("B" & test1Row)
                Set testSB = Sheets("TestS").Range("B" & SummaryRow)
                testSB.Value = test1B.Value

                Set test1A = Sheets("Test1").Range("A" & test1Row)
                Exit Do
            End If
            y = y + 1
         Loop

         If z = 0 Then
             set test1A = test1A.Offset(1, 0)
             test1.Value = curComputer
             SummaryRow = test1A.Row

             set test1B = Sheets("Test1").Range("B" & test1Row)
             Set testSB = Sheets("TestS").Range("B" & SummaryRow)
             testSB.Value = test1B.Value

             Set test1A = Sheets("Test1").Range("A" & test1Row)
         End If
         z = 0
         x = x + 1
     Loop
End Sub

Probably still some tidying up to do - but this gives the idea.


In my testing, constructing one Perl script and running it repeatedly is much faster (0.5s versus 3.6s) then running a new Perl instance for each replacement:

while read f; do
    echo "s/$f/$f/gi;"
done < files.txt > s.pl

while read fn; do
    perl -pi s.pl "$fn"
    echo "$fn | $count/$lines finished..."
    count=$((count+1))
done < filenames.txt

rm s.pl

But it seems even faster (0.05s) to rewrite the whole thing to Perl:

#! /usr/bin/perl
use warnings;
use strict;

use File::Find;

my $dir = 'theradoc2';

my %change;

find(sub {
    return unless -f;
    undef $change{$_};
    rename $_, lc $_;
}, $dir);

my $regex = join '|',
            map quotemeta,
            sort { length $b <=> length $a }
            keys %change;
find(sub {
    return unless -f;
    my $file = $_;
    open my $IN, '<', $file or die $!;
    open my $OUT, '>', "$file.new" or die $!;
    while (<$IN>) {
        s/($regex)/\L$1/g;
        print {$OUT} $_;
    }
    close $OUT or die $!;
    unlink $file or die $!;
    rename "$file.new", $file or die $!;
}, $dir);


Return character frequency in the order of occurrence

Problems like this tend to be annoying: so close to a simple solution, except for the need to be adjusting state during the loop. In this case, itertools.groupby() offers a shortcut, because its grouping function defaults to an identity, which is exactly what you need.
from itertools import groupby

def seq_count(word):
    return [
        (char, len(tuple(g)))
        for char, g in groupby(word)
    ]

If you don't want to use another library, you can reduce the bookkeeping a bit by yielding rather than returning and by iterating directly over the characters rather than messing around with indexes. But even with such simplifications, tedious annoyances remain. Anyway, here's one way to reduce the pain a little. The small code comments are intended to draw attention to the general features of this pattern, which occurs in many types of problems.
def seq_count(word):
    if word:
        # Initialize.
        prev, n = (word[0], 0)
        # Iterate.
        for char in word:
            if char == prev:
                # Adjust state.
                n += 1
            else:
                # Yield and reset.
                yield (prev, n)
                prev, n = (char, 1)
        # Don't forget the last one.
        if n:
            yield (prev, n)

exp = [('a', 3), ('b', 2), ('c', 3), ('a', 2), ('d', 1)]
got = list(seq_count("aaabbcccaad"))
print(got == exp)    # True


Assign values to answers from a questionnaire, input into a formula and calculate score

Since everything in this code is defined statically rather than as a function input (and your comments indicate that there is no way to vary any part of how this code functions), there is no possibility allowed within the parameters of this question for the score to ever vary.  You can therefore make this code significantly more concise and efficient by simply computing the score statically:

score = -15

This will produce the same score result as your original code with a significantly smaller footprint.

If this doesn't seem right, the question to ask yourself (and then answer for the benefit of your code reviewers) is: which constants in this code can vary, and what types/values are permissible for them?


Is my main method too large? Should I break it into smaller methods? How would you suggest splitting it up?

Your main method isn't too large; it is doing too many different things.

It is more typical in a java program to use the main method to set up an instance of a class that is going to do the work, and then hand off control of the program to that object.

In this case, main is initializing your seat map, running your input/output loop, providing your business behavior.

  Is the 'switch' statement the most efficient/logical way to write this class

Probably not -- there are two problems here.  First is that you are switching on an int, where the int is code for something else.  There's no particular reason that "1" should be first class and "2" should be economy -- that's just an arbitrary encoding required by this assignment.  A better choice would be to use an enum to represent the different seating classes.

public enum SeatingClass {
    FIRST_CLASS, ECONOMY
}

The second problem here is that you are using the switch to drive changes in behavior.  That usually means that there is a class hiding in the code, waiting for you to notice it.  In this case, there are two: first is the fact that what you are really doing is converting the inputs to Commands.

Also, notice that case 1 and case 2 are doing exactly the same behavior, but with different data.  That indicates that there should be a class that knows how to provide that behavior, and two different instances of it with different data values.  So here, you should have some sort of SeatSectionAssigner; each has a number of seats and an offset into the seat map that determines which seats get assigned.

  Any improvement/feedback is greatly appreciated, just keep in mind I am a little more than a month into learning java

Look for ways to decompose programs into classes that do one thing.

  I found the exact same assignment (Airline Reservations System) but it was really difficult for me to follow the program. Maybe that comes with programming experience? Reading other's code with ease, that is. But there isn't a "main" method there.

Yes, that code doesn't do anything on its own.  The implied assumption is that somewhere else is some code that looks like

Airline airline = new Airline();
airline.start();


I think if you continue this path you violate the "interface seggregation principle". Try to separate the interfaces. Going with your semantics I expect interfaces like ParameterAware or Storable. Then you won't get into such a semantical trouble.

As you have less semantical problems with your interfaces  you will face other challenges that have to do with the implementing classes and your algorithms using and working with these seggregated interfaces. But you cannot escape it and the effort and it is justified.


First, some positive notes. I got no warnings when compiled with gcc using -Wall -Wextra -pedantic. The code seems to work correctly, although the user has to signal EOF from the keyboard, or use file redirection (some warning about this in the question would have been nice.) It is good to see you using size_t for array indices, good that you are checking the results of your functions (i.e., malloc() and realloc()), and good that you are remembering to free() allocated memory.

I like that you do not cast the result of malloc(), though there are those that would disagree on that point.

Concerning realloc(), you are directly assigning the result of realloc() to the pointer to the memory which is being reallocated. This is bad, since realloc() can return a NULL pointer in the event of an error. This would cause a memory leak because you would no longer have a pointer to the previous allocation. You should instead store the result of realloc() in a temporary variable, and test that before reassigning:

char *temp;
...
temp = realloc(word, buff_size);
check_malloc_result(temp);
word = temp;

I don't really understand the need for dynamic allocation here. You only allocate storage for one word; this is not a lot of memory. The method of allocating a reasonable space, and then growing it as needed is sound, but note that if the first word is 17 characters, then you will have to allocate for 32 characters. This is a lot of waste, if you are concerned about space at this scale. You could allocate for one extra character at a time, as needed. I would recommend allocating for a larger initial value (say, 100 chars); if you want to handle possible very large first words, then you can grow this allocation dynamically. Then, if you really want to trim the memory, you can realloc() to the actual length of the word after you have read it.

It would be more idiomatic to use getchar() instead of read() to read from stdin. And, since the specification says that the only separators are spaces and the three punctuation characters, I would consider using '\n' as a way to terminate input to make keyboard entry more friendly:

while((stdin_ch = getchar()) != '\n' && stdin_ch != EOF) {
...
while(word_len && (stdin_ch = getchar()) != '\n' && stdin_ch != EOF) {

Without the test for newlines, this looks much simpler than the read() version of the same code:

while((stdin_ch = getchar()) != EOF) {
...
while(word_len && (stdin_ch = getchar()) != EOF) {

When you calculate result, you don't need to use two casts; the first will do:

result = (double)matched_count / sen_count;

Or, you can do away with the cast altogether by multiplying by 1.0; Note that a floating constant without a suffix is of type double:

result = (1.0 * matched_count) / sen_count;

I personally lean towards the second approach as I prefer to avoid casts whenever possible.

I also added a newline to the format string of your final printf statement, since this is nicer for the user; you might have a reason not to do this, though.

Finally, a note on the indirection operator: opinions vary, but it seems most common to use "right-leaning" asterisks. This is purely a matter of style, but I prefer:

int *var;

to the "left-leaning" version:

int* var;

The only place that I make an exception is in function declarations:

int * func(int *ptr);

There are good reasons for both styles; consistency trumps all in this case.


Multilingual command handler using inheritance

Static registration should be avoided. Not only because it is global code, burdening start-up and the class must be loaded (!), but also for unit-testing and diversification (proposing Tamil+English and Sinhala+Tamil as two configurable choices).

This is almost something for declarative extensions, say in XML with class loading with Class.forName.

You also might opt for loading by convention or configuration: instead of 1, 2, 3 use "si", "ti", "en" checked by a config properties "translators=si,ti,en" or "si=mypackage.SiTranslator".

Or a discovery system: java SPI (Service Provider Interface): in META-INF/services/ a text file mypackage.Command containing the class name(s). You can have several jars.

A map held in a singleton object is not bad, with a small, not very dynamic domain, like languages.

Map<String, Command> commandsMap = new HashMap<>();

But you might consider the overhead of 3 or more languages, when only 2 are used on average. Say if they load a dictionary. In that case: register first
producers of those classes, which you then place in the map with a java 8 Supplier<Command>:

register("si", SiTranslator::new);
register("ta", TaTranslator::new);
register("en", EnTransleightour::new);

A special factory class as your Handlers does not seem needed, or can in java 8 be defined as interface annotated with @FunctionalInterface and written as anonymous lambda.

Open/Close would imply using the java SPI, where you plug-in a new language, possibly in a separate jar. You still better use "si" (best the Locale key) instead of a number "1". One interface method would be String getKey().

However I would not say that a declarative or map registry at one place would be a sin. A specified orchestrated system behavior (at one point) is just as worthwile as independent extendibility. Only if you want to plug-in new languages, say separate jars, then it matters.

The Open/Close Principle is important for multitudes, maybe fine grained business rules. Open domains of a large magnitude.


Function to get top k words in a given String

Initialize Set with values

Your method of initializing the hashset with values takes quite a bit of space. I would create a static field:

public static final String[] SEPARATORS = new String[] { " ", ",", ".", ";" };

And then use it like this:

public static final Set<String> separatorsSet = new HashSet<String>(Arrays.asList(SEPARATORS));

Extract code to methods

Your getTopStrings method currently does three things: extract words from string, count amount of duplicate words, sort the result of that by frequency. I would at least create separate methods for the first two and the third functionality.

Simplify Sorting

Your sorting mechanism using a queue seems overly complicated. If you are using Java 8, it could be reduced to three lines (or one really long one):

    // sort by value, reversed
    Stream<Entry<String, Integer>> sorted = wordMap.entrySet().stream().sorted(Map.Entry.comparingByValue((x,y) -> (y < x) ? -1 : ((x == y) ? 0 : 1))); // alternatively: use reversed and cast
    // flatten map to list:
    List<String> collected = sorted.map(entry -> entry.getKey()).collect(Collectors.toCollection(ArrayList::new));
    // top k:
    List<String> topK = collected.subList(0, k);

Misc

in Java, it is customary to place curly brackets on the same line as the opening statements.
use curly brackets even for one line statements for improved readability and to avoid future bugs.
use more spaces, eg around ==, <, +, after ;, etc for increased readability.
declare variables in as small a scope as possible to increase readability.


Finding the objects with the cheapest seats

Following the little big O.
You ask

"...if there is a better way following big o notation..." (?)

Big O notation is a formalized mathematical convention used to express how a function (mathematical function) behaves as it approaches infinity.
It is used in computer science to classify an algorithms complexity in regard to a definable input metric, usually the size of the input array when dealing with arrays.
You can not "follow" big O notation as it provides no insight into how to reduce an algorithms complexity apart from a comparison.
Find the big O
To classify your function using Big O, first we need to make it at least readable, and convert it to a function. See snippet.
Now count the number of times the function loops over each item in the input array data. Experience lets you do this in your head, but to demonstrate we modify the function to count every time you handle an item in the input array.
Because we need to fit a curve we need at least 3 different input sizes which I do with some random data.

function bestSeats(data) {
     var c = 0; // the counter
     const seats = data.filter( seat =>
         (c++,  // count the filter iterations
         seat.price.replace(/[^0-9.-]+/g, "") == Math.min(
                 ...data.map(function ( seat ) {
                     c += 2;  // this counts as two
                              // once each to map to the arguments of Math.min
                              // once each to find the min
                     return Number(seat.price.replace(/[^0-9.-]+/g, ""))
                 }
             )
         ))).map(seat => (
             c++,  // count each result
             seat.seat
         ));
     return "O(n) = O(" + data.length + ") = " + c;
}

function randomData(size) {
    const data = [];
    while (size--) { data.push({seat:size, price: "$"+(Math.random() * 100 | 0)})}
    return data;
}
console.log("Eval complexity A:" + bestSeats(randomData(10)));
console.log("Eval complexity B:" + bestSeats(randomData(100)));
console.log("Eval complexity C:" + bestSeats(randomData(500)));

The 3 points we can use to find the curve that best fits
 O(10) ~= 211
 O(100) ~= 20,102
 O(500) ~= 500,005

Experience tells me it's a polynomial of some (not too high) order. Using a graphing calculator I found a reasonable fits at 2.15 making your functions big O complexity
\$O(n^{2.15})\$
Which is insanely inefficient. OMDG!!!!
So keeping

"...in es6 format" (?)

in mind a cleaner more readable, less CO2 producing sea level rising approach is to do a two pass scan of the seats. The first pass finds the min price, the second extracts the min price seat numbers.
This example uses for of loops rather than the Array methods like filter and map, because these array methods have a nasty way of blinding people to the insane level of  complexity of what they do, and for of is a little quicker and often allows better optimizations than the array methods, so it's win win for for of
Examples in \$O(n)\$ linear time.
 function bestSeats(seats) {
     var min = Infinity, minVal;
     const result = [];
     for (const seat of seats) {
         const price = Number(seat.price.slice(1));
         if (price < min) {
             min = price;
             minVal = seat.price;
         }
     }
     for (const seat of seats) {
         if (seat.price === minVal) { result.push(seat.seatNumber) }
     }
     return result;
 }

And if you must use the array methods.
 function bestSeats(seats) {
     const price2Num = seat => Number(seat.price.slice(1));
     const min = (min, seat) => price2Num(seat) < min ? price2Num(seat) : min;
     const minPrice = "$" + seats.reduce(min, Infinity);
     return seats.filter(seat => seat.price === minPrice).map(seat => seat.seatNumber);
 }


So I'll preface this with it's a little difficult without the actual context of the code, and that all suggestions need to be checked to ensure they don't break the existing flow of control.

A few options:

Breaking out repetitive operations into reusable methods
Wrapper methods (within reason) to apply some common operations and call some other method

With the assumption that these are inside of a loop, and you're not relying on an exception from the Convert.ToDouble() call to break out then you might consider some approaches like follows.

Simplified from provided example. Assuming additional trailing '}' is not significant.

if (currentElement != null
    && !RowHasEmptyCells(firstGridRow, "Low", "High", "Mean", "StdDev")
    && newRow.Lenth != 0)

{
    AddColourListWithSourceValue(firstGridRow, newRow, "Low", currentElement, opid, listCollectionLow);
    AddColourListWithSourceValue(firstGridRow, newRow, "High", currentElement, opid, listCollectionHigh);
    AddColourListWithSourceValue(firstGridRow, newRow, "Mean", currentElement, opid, listCollectionMean);
    AddColourListWithSourceValue(firstGridRow, newRow, "StdDev", currentElement, opid, listCollectionStdDev);
}

Functions attempting to contain some of the previously duplicated logic:

//return true if any of the named cells in the row are 'empty'
bool RowHasEmptyCells(RowType row, params string[] cellNames)
{
    return cellNames.Any(cellName => row[cellName].ToString() == string.Empty);
}

//RowType is the type of your row object (DataGridRow?)
void AddColourListWithSourceValue(RowType sourceRow, RowType newRow, string cellName, object currentElement, object opid, object listCollection)
{
    double currentValue = Convert.ToDouble(sourceRow[cellName]);
    AddColourList(currentElement, opid, currentValue, cellName, newRow, listCollection);
}

For the above double.Parse or .TryParse might be the way to go for a string > double conversion. If using Parse you could remove the empty cells check and just catch a FormatException/ArgumentNullException

This can likely be improved upon, but I've tried to make the flow of the main part a bit easier to follow whilst keeping roughly the same logic.

Edit 1: Sorry - fixed typo. Also AddColourListWithSourceValue() is just a guess at what's going on :)

Edit 2:  Quick edit with @svick's correction on logic and suggestion for LINQ to check for empty. Inverted to allow for the positive method prefix 'Has' instead of a 'CellsNotEmpty'. Would welcome thoughts on !IsSomething() vs IsNotSomething()...

Edit 3: != to == in RowHasEmptyCells() as pointed out by @svick


One thing that would help simplify your implementation is to fall back to already implemented code. For example, you could implement subtraction as addition using the negative of the second fraction. Likewise you could implement division as multiplication with the reciprocal of the second fraction.
Another point about readability: because you are implementing a mathematical notion which fits well with the standard arithmetic operations, consider adding +, *, etc as operators. As above, these operators could simply call the add, multiply, etc functions you already have. E.g. Fraction operator+(const Fraction& other) {return add(other);}
Consider adding helper methods for negation and reciprocal. These could be private, and used only by the simplified subtract and divide as above, or they could be exposed as potentially useful to the class consumer.
Another simplification would be to avoid coding special cases when the general case works just as well. For example, when adding, you don't need to first check whether the denominators match.
To help avoid the numbers getting out of hand, you could call simplify as a matter of course when doing these operations.
Consider moving some of your functions into the private section of the class definition. Generally, things that are intended to be used by the class and are not intended to be used from outside should be private. findGCD looks like a good candidate for moving. (One advantage of doing this to readability is that someone who wants to use your class knows they're only meant to look at the public methods, so they don't get drowned in irrelevant options.)
Consider getting rid of the set function completely. According to everything else, Fraction objects are immutable and cannot be changed. Instead, each operation returns a new Fraction object. Having set breaks this convention, and actually isn't that helpful a feature.
Consider marking all your member functions const if they don't change the current Fraction object. For example, Fraction simplify() const;
Consider marking all your functions (and your constructors) constexpr if you are using c++14 or greater. This tells the compiler that it's allowed to do some calculations at compile time if it knows the inputs, saving you having to do them at runtime.
As a point of efficiency, int numeratorTemp(m_Numerator); is unnecessarily setting a variable that will then be immediately overwritten. Hopefully an optimising compiler would simply pretend that never happened, but you might as well jump straight to const int numeratorTemp = m_Numerator * other.m_Denominator; or as appropriate.
You could do with some checks against illegal numbers. In particular, any fraction with zero as a denominator including 0/0 as given in your default constructor is undefined, and you should probably throw an exception. (For the same reason, I'd make the default constructor return 0/1.)
Nitpicks.
Although you should make your classes fit with the convention of your broader codebase, all things being equal it's probably better to have toString in a generic class produce a standard string rather than a <QString>.
You have a typo in multiply as multiphy. You also want numerator instead of numberator and subtract instead of substract.
When calling a constructor, don't qualify it. E.g Fraction(n, d); rather than Fraction::Fraction(n, d);


Naming
sequence_function is not a very good name for this function. For one, we already know it's a function, no need to name as such (you don't name your variables foo_variable right?). Likewise, result_array can just be results.
Second, what does "sequence" mean in context? When you look at the code that uses this function again in 6 months, will you be able to understand what this sequence_function is for without having to go back and read the code of the function? Good naming is one of the most important aspects of maintainable code.
Let's name it multipleOf4Or7 for now. Note that camelCase naming is usually used for JS, rather than snake_case.

Conditionals
Your conditionals would read better using plain if/else if/else in my opinion. If you're using something like switch(true) it's probably a sign that it's not the best structure. Using regular conditionals, you can also reduce one conditional branch, and the code is a lot shorter.
So far...
function multipleOf4Or7() {
    var results = [],
        start = 1,
        limit = 10;

    for(i = start; i <= limit; i ++) {
        if (i % 4 === 0) {
            if (i % 7 === 0) {
                results.push('xy');
            } else {
                results.push('x');
            }
        } else if (i % 7 === 0) {
            results.push('y');
        } else {
            results.push(i);
        }
    }
    console.log(results.join(','));
};

Return from function
You ought to return the results array from the function, instead of making the function print it. The advantage of that is if you need to do something else with the result, you can just let the caller handle it and not have to modify the function. Just replace console.log(results.join(',')); with return results, then just call like this:
console.log(multipleOf4Or7().join(','));

Hard-coded values vs. Default values
Right now your function is not very flexible, because all the values are hard-coded into the function.

What if you wanted to run it for 30 instead of 10?

What if you wanted to use 3 and 5, instead of 4 and 7?

What if you wanted to use values other than x and y?

Right now, you can't do any of that without changing or copying the function. JavaScript functions can have default parameters which would make it to where regular function calls with no arguments will return the exact same results, but you do have the option to call it with different arguments.
To do that, let's move all the hard-coded values into named parameters in the function signature of a new function, and replace the hard coded values:
function multipleOfOneOrBoth(num1 = 4, num2 = 7,
                             val1 = 'x', val2 = 'y',
                             start = 1, limit = 10) {
    var results = [];
    for(i = start; i <= limit; i ++) {
        if (i % num1 === 0) {
            if (i % num2 === 0) {
                results.push(val2);
            } else {
                results.push(val1);
            }
        } else if (i % num2 === 0) {
            results.push(val2);
        } else {
            results.push(i);
        }
    }
    return results;
}

Then simply replace the existing function's body like this:
function multipleOf4Or7() {
    return multipleOfOneOrBoth();
}

You could also, instead of using default arguments, just write
function multipleOf4Or7(start = 1, limit = 10) {
    return multipleOfOneOrBoth(4, 7, 'x', 'y', start, limit);
}

With this you can easily use it for other things, for example a FizzBuzz :
console.log(multipleOfOneOrBoth(3,5,"Fizz","Buzz",1,30).join("\n"));


Using TryXXX pattern to avoid exceptions

I was going to edit my first answer, but as I wrote the example code I wanted to show, and refactored, and refactored again, ...the result went so far away from the original code that I thought it warranted a separate answer.

So I copied your code into Visual Studio, and started by implementing the changes I suggested in my other answer. Quickly though, I felt the need to extract a FractionInfo type, a Structure that would hold the Whole, Numerator and Denominator parts of a fraction, so that I could write the regex part into a separate function that would return an instance of this FractionInfo type.

Being a Structure, I wanted to make that type immutable, so I implemented an Empty property that returned a Shared default instance... and then I tried doing If result = FractionInfo.Empty and noticed the = operator needed to be implemented - I'm lazy, so instead I just implemented Equals, and since when you override Equals you also need to override GetHashCode, I implemented GetHashCode as well.

So the ConvertFractionToDecimal function started like this:

Dim info As FractionInfo = GetFractionInfo(value)
If info.Equals(FractionInfo.Empty) Then Throw BuildBadFractionException(value)

And then I thought "great, now I can get rid of pretty much the whole rest of the code!" ...and then it struck me: you're not showing where your Convert.../TryConvert... methods are written, but I'm assuming they're not written in a Structure called Fraction.

And to follow the single responsibility principle, the only logical place to put such conversion methods would be in a value type called Fraction.

I suggest you take a look at this question and answers (disclaimer: it's one of my questions on this site) - it's C#, but the basic idea is essentially the same.

After much refactoring, this is what I ended up with - I'm not fully satisfied with it because it will throw a FormatException whenever parsing fails, even when one would expect an OverflowException. It does throw an ArgumentNullException when you give it Nothing, but the produced stack trace might be a little surprising.

Private Shared Function TryParseMatchGroups(ByVal groups As Match, ByRef result As Fraction) As Boolean

    Dim success As Boolean
    Dim wholePart As String = groups.Groups("whole").Value
    Dim numeratorPart As String = groups.Groups("numerator").Value
    Dim denominatorPart As String = groups.Groups("denominator").Value

    Dim whole As Integer
    Dim numerator As Integer
    Dim denominator As Integer

    success = Integer.TryParse(IIf(String.IsNullOrEmpty(wholePart), "0", wholePart), whole) _
        And Integer.TryParse(IIf(String.IsNullOrEmpty(numeratorPart), "0", numeratorPart), numerator) _
        And Integer.TryParse(IIf(String.IsNullOrEmpty(denominatorPart), "0", denominatorPart), denominator)

    If success Then
        result = New Fraction(whole, numerator, denominator)
    Else
        result = Fraction.Empty
    End If

    Return success

End Function

Public Shared Function Parse(ByVal value As String) As Fraction

    Dim result As Fraction
    Dim match As Match = regexp.Match(value)

    If match.Success And TryParseMatchGroups(match, result) Then
        Return result
    Else
        Throw New FormatException()
    End If

End Function

Public Shared Function TryParse(ByVal value As String, ByRef result As Fraction) As Boolean

    If value Is Nothing Then Return False

    Dim match As Match = regexp.Match(value)
    Return match.Success And TryParseMatchGroups(match, result)

End Function

These functions are Shared, exactly like Decimal.Parse and Decimal.TryParse are. Here's the rest of the type:

Public Structure Fraction

    Private Const pattern As String = "^((?<whole>[0-9]+)?\s+?)?(?<numerator>[0-9]+)\s?/\s?(?<denominator>[0-9]+)\s*?$"
    Private Shared ReadOnly regexp As Regex = New Regex(pattern)
    Private Shared ReadOnly emptyValue As Fraction = New Fraction()

    Private ReadOnly WholePart As Integer
    Private ReadOnly NumeratorPart As Integer
    Private ReadOnly DenominatorPart As Integer

    Public Sub New(ByVal whole As Integer, ByVal numerator As Integer, ByVal denominator As Integer)
        WholePart = whole
        NumeratorPart = numerator
        DenominatorPart = denominator
    End Sub

    Public ReadOnly Property Whole() As Integer
        Get
            Return WholePart
        End Get
    End Property

    Public ReadOnly Property Numerator As Integer
        Get
            Return NumeratorPart
        End Get
    End Property

    Public ReadOnly Property Denominator As Integer
        Get
            Return DenominatorPart
        End Get
    End Property

    Public Shared ReadOnly Property Empty As Fraction
        Get
            Return emptyValue
        End Get
    End Property

    Public Function ToDecimal() As Decimal
        Return Whole + CDec(Numerator) / CDec(Denominator)
    End Function

    Public Overrides Function Equals(obj As Object) As Boolean
        Dim other As Fraction = DirectCast(obj, Fraction) 'let it blow up on InvalidCastException
        Return other.Whole = Me.Whole _
            And other.Denominator = Me.Denominator _
            And other.Numerator = Me.Numerator
    End Function

    Public Overrides Function GetHashCode() As Integer
        'ok this is a bit like cheating.. but so much easier than implementing the real thing
        Return Tuple.Create(Me.Whole, Me.Numerator, Me.Denominator).GetHashCode()
    End Function

    Public Overrides Function ToString() As String
        If Me.Whole <> 0 Then
            Return String.Format("{0} {1}/{2}", Me.Whole, Me.Numerator, Me.Denominator)
        Else
            Return String.Format("{0}/{1}", Me.Numerator, Me.Denominator)
        End If
    End Function

You'll notice this implementation doesn't support negative fractions either - I'll leave that for you to explore and implement yourself. Note that vb.net isn't my primary language, so there might be stylistic errors in here.

If you looked at my A fraction of the code post, you've noticed there's many, many members missing here, mostly operators; you'll probably want a Fraction to at least support the = and <> operators, but the Equals implementation might be good enough as well. To make the type more usable you'll want to add MinValue and MaxValue, and perhaps a Zero value (0/1) and a Simplify() method. And of course you'll want to support negative fractions.

Basically, what this answer is suggesting that no answer has suggested yet, is to implement a [full-blown?] Fraction type, and to encapsulate your parsing logic in there: putting it anywhere else will break SRP.


Creating some Loaded Dice to make our board game fairer

Performance
If you intend on using this for (e.g.) large-scale Monte-Carlo simulation, consider moving to vectorized Numpy rather than base Python.
Direct generators
There's no need for yield here:
    for v in self.history.values():
        yield 1 / v

Instead,
return (1/v for v in self.history.values())

Counter initialization
roll_history can be reduced, I think, to
return Counter(
    (
        sum(self.roll_value_from_index(roll_index)),
        count,
    )
    for roll_index, count in self.history.items()
)

In other words, Counter accepts an iterable of key-count tuples. If the above generator expression seems unwieldy to you, write a separate method to yield roll-count pairs:
    for roll_index, count in self.history.items():
        roll_1, roll_2 = self.roll_value_from_index(roll_index)
        yield roll_1 + roll_2, count


If you are dealing with number lists, then array.array has a compact memory representation and implements the buffer protocol which allows memoryview’s to be created, which directly support views like you are creating.

For lists which can hold other things (tuples, dictionaries, lambdas, ...), Python has no built in support, and your view class can be appropriate.

PEP8 guidelines

Your class name should begin with a capital letter.  I’d suggest ListView as an option.  I don’t know what the ‘y’ is intended to mean.

There should be one space after every comma.  There shouldn’t be any spaces between a variable name and the [ character (b = a[1:3]).

Private members (self.begin, etc) should begin with an underscore (self._begin, etc).

Use a pylint, pyflakes, ... to ensure PEP8 compliance.

You could implement __repr__ in terms of __str__:

    def __repr__(self):
        return str(self)

Extension: Your list view could support a view slice with a step size other than 1.

You don’t protect against indexing beyond the length of your view. i >= self.len.


Process List asynchronously with SemaphoreSlim for throttling extension method

The only thing I can see is that you should dispose the semaphore:

using (var semaphore = new SemaphoreSlim(maxConcurrency))
{
  var tasks ....
}

And you could generalize to IEnumerable<T> instead of IList<T>

A simple solution using Parallel.ForEach() could be:

public static void ProcessWithParallelAsync<T>(this IEnumerable<T> list, Action<T> action, int maxConcurrency)
{
  ParallelOptions options = new ParallelOptions();
  options.MaxDegreeOfParallelism = maxConcurrency;
  Parallel.ForEach(list, options, action);
}

Or you could wrap it in a Task if you like:

public static Task ProcessWithParallelAsync<T>(this IEnumerable<T> list, Action<T> action, int maxConcurrency)
{
  return Task.Run(() =>
  {
    ParallelOptions options = new ParallelOptions();
    options.MaxDegreeOfParallelism = maxConcurrency;

    Parallel.ForEach(list, options, action);
  });
}


You are not supposed to replace all matches but only the first one. And then repeat the process.

Here is some javascript code that implements the markov algorithm exactly the way it is described on the wikipedia page.
Now all you have to do is translate that to C#.

function binaryToUnary(value) {
  var matchFound = false,
      rules = [["|0", "0||"],
               ["1",  "0|" ],
               ["0",  ""   ]];
  do {
    matchFound = false;
    for(var i = 0; i < rules.length; i++) {
      var rule = rules[i],
          pattern = rule[0], replacement = rule[1],
          index = value.indexOf(pattern);
      if(index >= 0) {
        value = value.substring(0, index) +
                replacement +
                value.substring(index + pattern.length);
        matchFound = true;
        break; //break because only the first pattern that matches should be replaced
      }
    }
  } while(matchFound);
  return value;
}


I'm going to skip reviewing the OP's code, which has already been reviewed quite nicely by others.  Instead I'm just going to show a much faster version and explain it.
What is the algorithm?
Basically the way the algorithm works is that a buffer is created that holds alphaLen^2 patterns, where alphaLen is the length of the alphabet.  A pattern is one combination, such as "aaaaa\n".  The reason that alphaLen^2 patterns are used is because the buffer is prepopulated with the last 2 letters already set to all possible combinations.  So for example, the buffer initially looks like (for length 5 patterns):
"aaaaa\naaaab\naaaac\n ... aaa99\n" (62*62 patterns, 23064 bytes in length)

On every iteration, the function uses write() to output the buffer, and then increments the third to last letter.  This involves writing that letter alphaLen^2 times (once per pattern).  So the first iteration goes like:
"aabaa\naabab\naabac\n ... aab99\n"
   ^      ^      ^           ^
   |      |      |           |
   +------+------+-----------+----- Characters written to buffer (62*62 changes)

Whenever the third to last character wraps around, then we also need to update the fourth to last letter.  If that wraps around, the fifth to last letter is also updated, etc.  This continues until the first letter wraps around, at which point we are done.
How fast is it?
For all testing, I outputted to /dev/null so that my hard drive speed would not be the limiting factor.  I tried the OP's program for 5 letter patterns but for me it took way too long (203 seconds).  So I'll use Edward's estimate of 18 seconds for the OP's program instead.  I also tested Edward's program on my machine, as well as a second program I wrote where I extended the algorithm to hardcode the last 3 characters instead of 2.  I am using Cygwin gcc (32-bit) with -O4 on a Windows desktop.  Here are the results:
Time (secs)  Length   Program
-----------  ------   -------
    18.0       5      syb0rg
     9.6       5      Edward
     0.4       5      JS1 (2 characters)
     0.4       5      JS1 (3 characters)

   665.0       6      Edward
    26.0       6      JS1 (2 characters)
    24.2       6      JS1 (3 characters)

  1513.7       7      JS1 (3 characters)

As you can see, this algorithm is very fast.
The code
Both programs are available here on GitHub.  I'll show the 2 character variation below:
static void generate(int maxlen)
{
    int   alphaLen = strlen(alphabet);
    int   len      = 0;
    char *buffer   = malloc((maxlen + 1) * alphaLen * alphaLen);
    int  *letters  = malloc(maxlen * sizeof(int));

    if (buffer == NULL || letters == NULL) {
        fprintf(stderr, "Not enough memory.\n");
        exit(1);
    }

    // This for loop generates all 1 letter patterns, then 2 letters, etc,
    // up to the given maxlen.
    for (len=1;len<=maxlen;len++) {
        // The stride is one larger than len because each line has a '\n'.
        int i;
        int stride = len+1;
        int bufLen = stride * alphaLen * alphaLen;

        if (len == 1) {
            // Special case.  The main algorithm hardcodes the last two
            // letters, so this case needs to be handled separately.
            int j = 0;
            bufLen = (len + 1) * alphaLen;
            for (i=0;i<alphaLen;i++) {
                buffer[j++] = alphabet[i];
                buffer[j++] = '\n';
            }
            write(STDOUT_FILENO, buffer, bufLen);
            continue;
        }

        // Initialize buffer to contain all first letters.
        memset(buffer, alphabet[0], bufLen);

        // Now in buffer, write all the last 2 letters and newlines, which
        // will after this not change during the main algorithm.
        {
            // Let0 is the 2nd to last letter.  Let1 is the last letter.
            int let0 = 0;
            int let1 = 0;
            for (i=len-2;i<bufLen;i+=stride) {
                buffer[i]   = alphabet[let0];
                buffer[i+1] = alphabet[let1++];
                buffer[i+2] = '\n';
                if (let1 == alphaLen) {
                    let1 = 0;
                    let0++;
                    if (let0 == alphaLen)
                        let0 = 0;
                }
            }
        }

        // Write the first sequence out.
        write(STDOUT_FILENO, buffer, bufLen);

        // Special case for length 2, we're already done.
        if (len == 2)
            continue;

        // Set all the letters to 0.
        for (i=0;i<len;i++)
            letters[i] = 0;

        // Now on each iteration, increment the the third to last letter.
        i = len-3;
        do {
            char c;
            int  j;

            // Increment this letter.
            letters[i]++;

            // Handle wraparound.
            if (letters[i] >= alphaLen)
                letters[i] = 0;

            // Set this letter in the proper places in the buffer.
            c = alphabet[letters[i]];
            for (j=i;j<bufLen;j+=stride)
                buffer[j] = c;

            if (letters[i] != 0) {
                // No wraparound, so we finally finished incrementing.
                // Write out this set.  Reset i back to third to last letter.
                write(STDOUT_FILENO, buffer, bufLen);
                i = len - 3;
                continue;
            }

            // The letter wrapped around ("carried").  Set up to increment
            // the next letter on the left.
            i--;
            // If we carried past last letter, we're done with this
            // whole length.
            if (i < 0)
                break;
        } while(1);
    }

    // Clean up.
    free(letters);
    free(buffer);
}


If you're still looking for a way how to find out the dimensions of a StorageFile image, there is an easy way to do that. I am using it in uwp as well.

I guess it would be less expensive than creation of a new BitmapImage.

        StorageFile image;
        ImageProperties properties = await image.Properties.GetImagePropertiesAsync();
        int height = (int)properties.Height;
        int width = (int)properties.Width;

As well I have this one method which I am using couple of places:

        private async Task<WriteableBitmap> StorageFileToWbmp(StorageFile file)
              {
        ImageProperties props = await file.Properties.GetImagePropertiesAsync();
        WriteableBitmap bitmap = new WriteableBitmap((int) props.Width, (int) props.Height);
        await bitmap.SetSourceAsync(await file.OpenReadAsync());
        return bitmap;
              }


Asynchronous task and close sql connection

Will this CommitAsync method execute synchronously in the Commit method?

I wouldn't phrase it that way, CommitAsync always executes asynchronously, but Commit wait for it to complete synchronously.

  Is it best practive to pass new CancellationToken() in the Commit method?

It's better to use CancellationToken.None, to make the meaning clearer. Though functionally, the two are equivalent.

  Will the base.SaveChangesAsync() call in CommitAsync() close the connection if it was opened beforehand?

I don't think it will, a single connection can be used for multiple commands.

In general, you should create a new connection for each separate operation (which may comprise more than one command) you do and then dispose the connection, which closes it. This won't hurt efficiency, because connections are actually pooled, so closing the connection object means that the actual connection can be reused by another operation.

var status = new ContextStatus();

var task = Task.Run(async () => { status = await CommitAsync(userName, new CancellationToken()); });
task.Wait();

return status;

This is unnecessarily verbose and complicated. Instead, I would write it like this:

return Task.Run(() => CommitAsync(userName, new CancellationToken())).Result;

CommitAsync returns Task<ContextStatus>, so Task.Run() will also return that type. The Task's Result will give you the ContextStatus, synchronously waiting for the Task to complete before returning.

SqlParameter param = new SqlParameter()

Why not use var here too? The type of the variable is clear, so specifying the type just makes the code more verbose.


Visibility modifiers and names

enum types are by default public static. You can choose to remove them.

Type is a very broad name for your enum, so you can consider just calling it EffectType.

switch and return

Instead of assigning the result to effect, you should return directly from each case, i.e.:

switch(type) {
case ATTACKBUFF:
    return new AttackBuff(monster, duration);
case ATTACKBREAK:
    return new AttackBreak(monster, duration);
case DEFENSEBUFF:
    return new DefenseBuff(monster, duration);
case DEFENSEBREAK:
    return new DefenseBreak(monster, duration);
// shifted default case as the last, it's more 'conventional'
default:
// case NIL:
    return new NilEffect();
}

You can also choose to place this as method for EffectType instead, but from an OOP approach, this depends if an EffectType is supposed to 'know' an Effect (and Monster) or not. Your approach is still fine.

Adding and updating effects

Since you are on Java 8, you can consider return-ing null from Map.computeIfPresent() to expire the type and remove the entry in one go:

public void addEffect(Effect.Type type, int duration) {
    effects.computeIfPresent(type, (k, effect) -> { effect.expire(); return null; });
    Effect effect = Effect.newEffect(type, this, duration);
    effect.apply();
    effects.put(effect.getType(), effect);
}

Do you really need to invoke parallelStream() when updating effects? Since the maximum number of elements you can have in your Map is bounded by the number of EffectType values (BTW, you may want to switch to an EnumMap), I think the overhead of doing a concurrent access on your Map is not required. Also the forEach() operation can be done using a method reference as well, in this case:

public void updateEffects() {
    effects.values().stream().forEach(Effect::update);
}


The reason PHP dislikes the use of Regex is because some people don't know how to use it.
You, for example, don't.
Regex is for matching input, not for validation.
And so you'd use it to change say your date format to ISO 8601:

> $date = '19700101000000';
> preg_replace('/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', '$1-$2-$3T$4:$5:$6Z', $date);
=> "1970-01-01T00:00:00Z"

The regex is simple as we know the data should be there. Not that it's correct.

Your code is also long-winded, rather than manually checking if the code is alright make PHP do it for you with strptime.
You know the format the date is in, %Y%m%d%H%M%S, and so you can use it:

> strptime($date, '%Y%m%d%H%M%S');
=> {"tm_sec":0,"tm_min":0,"tm_hour":0,"tm_mday":1,"tm_mon":0,"tm_year":70,"tm_wday":4,"tm_yday":0,"unparsed":""}

And so you could change the function to just use:

/**
  * Function that checks the format, date, and time of a given timestamp.
  * @author : somar
  * @param string $date timestamp ex: 20161230154523
  * @return boolean resultat de check
  */
public function validateDate($date)
{
    return (bool)strptime($date, '%Y%m%d%H%M%S');
}

To note, strptime seems to have a bug with %S:

> strptime('19700101000070', '%Y%m%d%H%M%S');
=> {"tm_sec":7,"tm_min":0,"tm_hour":0,"tm_mday":1,"tm_mon":0,"tm_year":70,"tm_wday":4,"tm_yday":0,"unparsed":"0"}

To fix this you could change the function to take ISO 8601 dates, and have a function that converts to this format.

/**
  * Function that checks the format, date, and time of a given ISO 8601 timestamp.
  * @author : somar
  * @param string $date timestamp ex: 2016-12-30T15:45:23Z
  * @return boolean resultat de check
  */
public function validateDate($date)
{
    return (bool)strptime($date, '%Y-%m-%dT%H:%M:%SZ');
}

public function compactDateToISO($date)
{
    return preg_replace('/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', '$1-$2-$3T$4:$5:$6Z', $date);
}


TLE on SPOJ for Prime Generator (PRIME1)

Avoid magic numbers

        boolean[] isPrime =new boolean[31623];

This should have a constant defined.  Perhaps

    final long MAXIMUM_CANDIDATE = 1000000000;
    final int MAXIMUM_SMALLEST_FACTOR = (int)Math.sqrt(MAXIMUM_CANDIDATE);

I suppose that the really correct name would be MAXIMUM_SMALLEST_FACTOR_OF_ANY_NONPRIME_NUMBER_LESS_THAN_MAXIMUM_CANDIDATE, but hopefully this is clear enough.

And you may want to pass it into the method, e.g.

    static boolean[] composites = primesUpto(MAXIMUM_SMALLEST_FACTOR);

and

    static boolean[] primesUpto(int maximumSmallestFactor) {
        boolean[] composites = new boolean[maximumSmallestFactor + 1];

This makes the method more general.

I also changed the name from the verb isPrime to a noun name, as is consistent with object-oriented naming conventions.  I also changed the direction.  This allows us to eliminate the step of setting everything to true.  Now the natural default of false will be correct.  We only need to set the true values.

Don't do unnecessary math

            for(int j=i;j*i<isPrime.length;j++){
                isPrime[j*i]=false;
            }

This does more work than is necessary.  Consider

            for (int j = i*i; j < composites.length; j += i) {
                composites[j] = true;
            }

This saves a multiplication every iteration (two if the compiler is dumb enough) but only replaces an increment by one with an increment by i.  Two operations that will normally take the same time.

You can save even more time by adding another check.

            if (!composites[i]) {
                for (int j = i*i; j < composites.length; j += i) {
                    composites[j] = true;
                }
            }

Now we only sieve out multiples of primes.  So one comparison per outer loop iteration saves running the inner loop more than half the time.

        for(long i=m; i<n+1; i++){

Similarly, this could be written

        for (long i = m; i <= n; i++) {

Don't do in a loop what you can do outside

            for(int j=2; j<isPrime.length;j++){
                if(isPrime[j] && i%j==0) break;
                if(j==31622) System.out.println(i);
            }

You check on every iteration if it is the last iteration.  Consider

            int j = 2;
            for (; j < composites.length; j++) {
                if (!composites[j] && i%j == 0) {
                    break;
                }
            }

            if (j == composites.length) {
                System.out.println(i);
            }

This does the same thing in effect, but it only checks once to see if the loop reached the end.

It also gets rid of the magic number.

And I added more {} and whitespace, because I find it easier to follow.

An alternative

If these changes aren't enough, you might consider changing the algorithm.  You iterate over the entire array to find just the primes.  Why not store just the primes in the first place?  Still use the sieve to mask out the non-primes, but when you find a prime, save it.

            if (!composites[i]) {
                primes.add(i);
                for (int j = i*i; j < composites.length; j += i) {
                    composites[j] = true;
                }
            }

Also, rather than trial division, consider using a sieve again on the range from m to n.

If you want to see an example of how this could work, try here.  I already wrote out a solution for this.  The other answer to the same question has additional explanation of the algorithm and links to a C++ solution.


if (typeof n !== "number") {
    throw new TypeError("factorial() expects a number.");
}
if (Math.floor(n) !== n) {
    throw new TypeError("factorial() expects an integer.");
}
if (n < 0) {
    throw new RangeError("factorial() expects a non-negative number.");
}

First, I discourage manual type and value checks on runtime. They're redundant since the JS engine will emit an error if you operate on the wrong data anyways. It's also runtime overhead as well as unnecessary code.

Often times, developers forward this task to the IDE when writing code. With the right plugins and annotations, the IDE can warn you of incompatible data types and operations. This only prevents writing the API incorrectly though. There's still risk of using the function incorrectly, but that's the consumer's fault, not the API.

var accumulator = 1;

JS has let, the block-scoped version of var. It's a good habit to use let since in most cases, you'll want block-scoped vars. It also prevents ambiguity of where the variable exists in the code, which usually causes problems (like var in for or if). If I remember correctly, it's because of hoisting that developers started defining vars explicitly on the top of the function body to signal that a variable of that name exists in the function.

if (n > 170) {
    return Infinity;
}

var accumulator = 1;

for (var i = 2; i <= n; i++) {
    accumulator *= i;
}

return accumulator;

In the end, the factorial code is just the one above. A shorter version factorials can be done using recursion.

function factorial(n) {
  return n > 170 ? Infinity    // Bail out on 170
    : n == 0 || n == 1 ? 1  // When the answer is just 1
    : n * factorial(n - 1)  // Multiply current with next smallest
}

console.log(factorial(1))
console.log(factorial(2))
console.log(factorial(3))
console.log(factorial(4))
console.log(factorial(5))


Code snippet for a method dealing with IDs from multiple threads

Here are my thoughts on the code that you provided:

You should mark your lockObj and runningIds as readonly
You are using the presence of the queue in the dictionary as a signal that another thread is currently working on specific ID which is not quite obvious
You mix non-blocking (await) approach along with blocking (ManualResetEvent.WaitOne). It would be better to stick to one of them (preferably non-blocking).
If you change the approach from "notify the guy after me that he can start working" to "I'm done", then you would be able to capture only the last "guy" against specific ID. "I'm done" is easily modelled by Task.

As a result, my first refactoring of your code looks like this:

private static readonly object _lockObj = new object();
private static readonly Dictionary<int, Task> _runningIds = new Dictionary<int, Task>();

public async Task TheMethod(int id, string val)
{
    //Will be used to signal others that the work has finished
    var completionSource = new TaskCompletionSource<bool>();

    Task currentTask;

    lock (_lockObj)
    {
        _runningIds.TryGetValue(id, out currentTask);
        _runningIds[id] = completionSource.Task;
    }

    if (currentTask != null)
        await currentTask;

    // DO LONG RUNNING TASK
    await Task.Delay(3000);
    Console.WriteLine(id + " " + val + " at time " + DateTime.Now.ToString("m:ss"));

    completionSource.SetResult(true);

    //cleanup
    lock (_lockObj)
    {
        if (_runningIds.TryGetValue(id, out currentTask) && currentTask == completionSource.Task)
            _runningIds.Remove(id);
    }
}

Second take was mostly as an exercise to get rid of lock at all by using the ConcurrentDictionary.

private static readonly ConcurrentDictionary<int, Task> _runningIds = new ConcurrentDictionary<int, Task>();

private static Task RegisterAsLastScheduledTask(int id, Task task)
{
    Task previousTask = null;

    //Either adding a new task to the dictionary, or capturing and replacing previous task
    while (!_runningIds.TryAdd(id, task) &&
        !(_runningIds.TryGetValue(id, out previousTask) && _runningIds.TryUpdate(id, task, previousTask)))
    {
        previousTask = null;
    }

    return previousTask;
}

public async Task TheMethod(int id, string val)
{
    //Will be used to signal others that the work has finished
    var completionSource = new TaskCompletionSource<bool>();
    Task previousTask = RegisterAsLastScheduledTask(id, completionSource.Task);

    if (previousTask != null)
        await previousTask;

    // DO LONG RUNNING TASK
    await Task.Delay(3000);
    Console.WriteLine(id + " " + val + " at time " + DateTime.Now.ToString("m:ss"));

    completionSource.SetResult(true);

    //"hack" to atomically remove the element only if both key and value match, see http://blogs.msdn.com/b/pfxteam/archive/2011/04/02/10149222.aspx
    ((ICollection<KeyValuePair<int, Task>>)_runningIds).Remove(new KeyValuePair<int, Task>(id, completionSource.Task));
}


Simple jQuery validation script works but it uses a ton of if/else statements

I would recommend that you use the JQuery validation plugin (http://docs.jquery.com/Plugins/Validation) then your validation declaration would be as follows (fields which do not exist are ignored):

$("#footer_newsletter").validate(
    rules: {
            email: {
                    required: true,
                    email: true
                   },
            country: "required",
            gender: "required"
    },
    messages: {
             email: {
                     required: "Please enter an email",
                     email: "Please enter a valid email address"
                    },
             country: "Please select a country",
             gender: "Please select your gender"
    }
);


Scraping PubMed query results: follow-up

The first thing I might do is get rid of the email regex matching.  PHP has this awesome functionality called filter_var that will take care of a lot of cool things for you, like validating a string as an email address.  This is a better solution because you're less likely to get back false positives where the email is valid, but doesn't match the regex.

Next, I'm not sure I like the search/fetch parameters being set at various places throughout the code.  This feels like something that should be done in the constructor; setup all the data you need to complete the responsibility of the class in the constructor.  If you ever add a new method or make some changes you always have to keep in the back of your mind "Have I set $x yet?".  Well, do it in __construct() and you'll know you have.

Finally, I noticed you were calling some get* functions but not assigning the return value to any variable.  If you don't use the return value you don't need to use the get* function and if you don't use the get* function you don't need it in the class.

Overall I like the API, the method names are fairly self explanatory.  I'm not sure that they should all be public as your use case only has one method actually being used from calling code.  In addition, I might change the properties from private to protected for extensibility but that is certainly not mandatory and is as much a preference as anything else.  I would also prefer to see some kind of documentation, even if it is just the responsibility of the class and your though processes behind why you solved the problem this way.


Is this a typical way to write something like

If that’s all the information that is required – yes, why not? I see no problem at all with this approach.

On the other hand, if code lik this is prolific this is a sure sign that the original class design is broken. But from your code it looks like this is outside of your control anyway, since UserModel is a framework class.

In general, if a class is used in such a fashion then it is over-engineered: a static method could have been used just as well (on the other hand, this may make unit testing harder because it prevents mocking).


Image cache for lots of images using WeakReference on C#

It looks like weak reference would serve the purpose of what you are trying to achieve [IF] those images will go out of scope (not being directly referenced in any execution path) after handing them back to the caller of that method then they will be collected by GC at some point.
This MSDN article explains weak references in .net, I'll quote it here:

The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object.
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object.
A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist. When you use a weak reference, the application can still obtain a strong reference to the object, which prevents it from being collected. However, there is always the risk that the garbage collector will get to the object first before a strong reference is reestablished.
Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.

While your code should work fine, I would consider using an in-memory Cache instead with (either or both) capping the TTL (time to live) or count of objects that can occupy that cache (adding new items to the cache would invalidate and remove older items to maintain the capacity).
Check out MemoryCache class in .net framework.