Quiz component with different but similar data models

Not the Strategy yet

I'd try to not have a super huge ExtraCard component class if possible. The idea is to encapsulate the data in a Card interface/classes:

export interface Card {
  context: Context;
  question: string;
  answers: Answer[];
}

export interface Answer {
  text: string;
  action: () => void;
}

export class Card1 implements Card {
  constructor(public context: Context) { }

  question = "Some card";
  answers = [
    { text: "Answer 1", action: () => { console.info("Q1-A1"); this.context.ga.doSomething(); } },
    { text: "Answer 2", action: () => { console.info("Q1-A2"); } },
    { text: "Answer 3", action: () => { console.info("Q1-A3"); } }
  ];
}

export class Card2 implements Card {
  constructor(public context: Context) { }

  question = "Some card";
  answers = [
    { text: "Answer 1", action: () => { console.info("Q2-A1"); } },
    { text: "Answer 2", action: () => { console.info("Q2-A2"); } }
  ];
}

Please notice two things here:

the Card is now responsible for holding the data related to the specific Question (both, question and the list of answer with corresponding behavior). This is not really the "Strategy Pattern" yet, but it is a first big step towards it. In Strategy pattern you normally do not mix the data and behavior in the same class, but rather separate them.
We declare a context: Context property that will hold the important dependencies (aka Services) that are required for a given Card to do it's work in answers' actions.
This allows the card classes to stay regular TypeScript classes instead of being declared as services. This also means that the Context with the services should be provided from the outside. In TypeScript we can use the constructor (public context: Context) to enforce client pass in the context.

The Context, by the way can look something like this:

export class Context {
  ga: GoogleAnalytics;
  socialSharing: SocialSharing;
  appRateService: AppRateService;
  // Other services/dependencies...
}

Now we need to change the ExtraCard component as well as it consumer.

Why not make the ExctraCard as dumb as we can? Here's what it could look like. Notice that the component now expects the entire Card to be passed in via @Input() card. It will also notify the consumer about receiving an answer (see EventEmitter.

{{card.question}}

{{ answer.text }}

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'extra-card',
  templateUrl: 'extra-card.component.html'
})
export class ExtraCard {

  @Input() isActive: boolean = true;
  @Output() answerReceived = new EventEmitter<void>();

  @Input() card: Card;

  triggerAction(answer: Answer): void {
    answer.action();
    this.answerReceived.emit();
  }
}

The last part is your consumer component. It orchestrates Card objects creation and iteration.

The collection of allCards is created in ngOnInit rather than constructor, and it defines the number, kind, and order of the Cards. Consumer's constructor is used to inject the dependencies and prepare a sharedContext that is than passed to the Cards (remember, they now require it in their constructors).

answerReceived() method is used to react to the corresponding event. In my code I assumed that we only need to iterate through the questions linearly (first to last). If that is not the case (e.g. you may need to jump from Card1 to Card3 if a specific Answer was selected), then ExtraCard would need to emit event with some data. For example, answerReceived = new EventEmitter<number>() and this.answerReceived.emit(answer.id). Then the answerId could be used in Consumer for implementing more complex iteration logic.

  <extra-card
    [isActive]="isActive(card)"
    [question]="card"
    (answerReceived)="answerReceived(cardIndex)"></extra-card>

import { Component } from '@angular/core';
import { Card1, Card2, Context, Card } from './extra-card.component';

@Component({
  selector: 'consumer',
  templateUrl: 'consumer.component.html'
})
export class Consumer {

    private sharedContext: Context;
    allCards: Card[] = [];
    activeCard: Card;

    constructor(ga: GoogleAnalytics, appRateService: AppRateService, socialSharing: SocialSharing) {
        this.sharedContext = {
            appRateService,
            ga,
            socialSharing
        };
    }

    ngOnInit(): void {
        this.allCards = [
            new Card1(this.sharedContext),
            new Card2(this.sharedContext),
            // ...
        ];

        this.activeCard = this.allCards[0];
    }

    isActive(card: Card): boolean {
        return this.activeCard === card;
    }

    answerReceived(cardIndex: number): void {
        const card = this.allCards[cardIndex + 1];
        if (card != null) {
            this.activeCard = card;
        } else {
            // TODO Handle card enumeration complete event.
        }
    }
}

Disclaimer

This is by no means the best approach I recommend to use generally, but I think it's better what you have now. Especially, since you identified a very important problem of Card/Question quantity growth. My solution is much more scalable, but it too has its limits.

If you apply this for now, and see some other issues coming, feel free to post  a follow-up question with a specific ask.

I hope this helps.


This code is not thread safe.  You synchronize (lock) while adding to the queue, but your code which removes from the code does not lock the queue, and will always run on a background thread, which is going to cause potential race conditions.

If you really must write your own logging, I would, at the least, look into using ConcurrentQueue<T> to avoid the need for locking on adding.  BlockingCollection<T> would make this far simpler, as you could just have a thread call GetConsumingEnumerable() to process items as they're added.

That being said, logging is something that's been handled many times, and handled well.  You'd be far better off using something like the new Semantic Logging Application Block (from P&P) or even log4net.


Looks pretty good at first glance! I'd say your main problem is "#define ONE 1" — you've gone out of your way to parameterize things that can't actually be changed in real life without massive changes elsewhere in the game logic. For example, you've set
enum Items { Rock, Paper, Scissors, ItemsCount };

which looks awesome... until someone decides to actually use that flexibility by changing it to
enum Items { Rock, Paper, Scissors, Lizard, Spock, ItemsCount };

and suddenly nothing compiles anymore. (They also have to change the local variables table and data and binding_item inside main, and the text of the cout inside user_choice, and maybe some more stuff too. By the way: variable names are important! data and table are not good names!)
The over-parameterization antipattern tends to travel along with the std::array antipattern — see "The 'array size constant' antipattern" (2020-08-06). Somehow, people who've caught the "named constants > magic numbers" virus also tend to have caught the "std::array > core language" virus as well. Where you write
template<typename T, std::size_t N>
using Matrix = std::array<std::array<T, N>, N>;

const Matrix<Winner, Winner::WinnerCount> table
{
    {  // Rock      Paper      Scissors
        { Tie,      Computer,  Player   }, // Rock
        { Player,   Tie,       Computer }, // Paper
        { Computer, Player,    Tie      }, // Scissors
    }
};

an expert C++ programmer would probably just write
Winner table[3][3] = {
    // Rock      Paper      Scissors
    {  Tie,      Computer,  Player   }, // Rock
    {  Player,   Tie,       Computer }, // Paper
    {  Computer, Player,    Tie      }, // Scissors
};

Incidentally, did you notice your bug above? You dimensioned your table by WinnerCount, but you index into it using values of Item. You're simply getting lucky that WinnerCount (win, lose, tie) happens to be the same as ItemCount (rock, paper, scissors).

Be aware that
std::mt19937 engine{ std::random_device()() };

is a relatively low-entropy way to initialize a Mersenne Twister: it has 19937 bits of state, and you're seeding it with only 32 random bits. But C++ doesn't offer any concise way to seed a PRNG properly, so actually what you've got is the state of the art.

const Items computer = static_cast<Items>(dist(engine));

Throughout, you use plural words where singular would be more appropriate, and relatively abstract nouns (data, table, computer) where more concrete ones would be appropriate. I'd write:
Item computers_choice = static_cast<Item>(dist(engine));

indicating that what we've got now is not a computer but rather the computer player's choice of what to throw; and it is not multiple Items but rather a single Item. (I'd probably rename Item to Gesture, too.)

Your user_choice function returns std::string, which you then have to parse again in main. It should just return the Item it extracted, directly, instead of the string.
Also, the logic around the is_input_valid boolean seems pretty baroque. Think about how the code could be simplified by using a return or break statement inside the loop.
if (std::getline(std::cin, result)) {
    if (map_of_strings_to_gestures.contains(result)) {
        return map_of_strings_to_gestures.at(result);
    }
}
std::cout << "Not valid input.\n";
// and go around again

Also, try hitting Ctrl-D (or Ctrl-Z on Windows) at this prompt. That'll close stdin, which makes cin.fail() true, which means the input isn't valid... and then your code just goes into an infinite loop, doesn't it? I think you actually want to break out of the loop when you see EOF or an error — not stay in the loop!

For configuring the gestures, I think you should investigate X-macros. Here's my take: https://godbolt.org/z/8qhdcPWT5 The entirety of the "configuration" for the game is expressed in a single table at the top of the code:
#define GESTURES \
    X(Rock,     "rock",     BEATS(Scissors)) \
    X(Scissors, "scissors", BEATS(Paper)) \
    X(Paper,    "paper",    BEATS(Rock))

and I've also tested it with this configuration:
#define GESTURES \
    X(Rock,     "rock",     BEATS(Scissors) BEATS(Lizard)) \
    X(Scissors, "scissors", BEATS(Paper) BEATS(Lizard)) \
    X(Paper,    "paper",    BEATS(Rock) BEATS(Spock)) \
    X(Lizard,   "lizard",   BEATS(Spock) BEATS(Paper)) \
    X(Spock,    "spock",    BEATS(Scissors) BEATS(Rock))

(My version also eliminates the dependencies on <map>, <algorithm>, and of course <limits>.)

An obvious "next step" for this program would be to refactor it so that you can print a customized verb for each outcome:
Enter your choice (rock, scissors, paper): rock
You entered: rock
Computer chose: paper
Paper covers rock — you lose!

Enter your choice (rock, scissors, paper): scissors
You entered: scissors
Computer chose: paper
Scissors cuts paper — you win!

and so on.


Genetic algorithm for Clever Algorithms project

First a note on your general design: You use hashmaps to represent members of the population. I'd rather recommend you create a little class to represent them:

class Individual
  include Comparable

  attr_reader :bitstring, :fitness

  def initialize(bitstring)
    @bit_string = bitstring
    @fitness = onemax(bitstring)
  end

  def <=>(other)
    fitness <=> other.fitness
  end
end

You'll now use Individual.new(bitstring) to create a new individual (which will automatically calculate its own fittness) and individual.bitstring and individual.fitness to get an individual's bitstring or fitness respectively.

This has the benefit that now the logic of how to calculate an individuals fitness lives in the Individual class instead of in multiple place in the search method. This is a more natural place for it and makes it easier to find and change should you ever decide to use a different fitness function.

Also note that I included Comparable, implementing <=> based on fitness. This means that you can now compare individuals to each other such that an individual is greater than another if and only if its fitness is greater. This allows you to use > on two individuals as well as methods like max to get the individual with the greatest fitness out of an array of individuals. It also allows you to call sort on array of individuals without passing a block. This will simplify your code in some places.

In a comment you mentioned that you don't want to use classes. However I still think that it would greatly improve your design to have the logic for creating new individuals and calculating their fitness in one single place, so you should at least factor it out into a method like this:

def create_individual(bitstring)
    {:bitstring => bitstring, :fitness => onemax(bitstring)}
end

Now some notes on particular pieces of code:

bitstring.size.times {|i| sum+=1 if bitstring[i].chr=='1'}

As has already been mentioned, this can easily be replaced with a call to count. However as a general note I want to point out that it's good practice to avoid index-based loops wherever possible, so if count did not exist, I'd write the above like this:

bitstring.each_char {|c| sum+=1 if c == '1'}

Or for 1.8.6 compability:

bitstring.each_byte {|b| sum+=1 if b.chr == '1'}

(0...num_bits).inject(""){|s,i| s<<((rand<0.5) ? "1" : "0")}

When dealing with inject, it's usually a good idea to keep the function simple, so it's more easily understandable. Often you can separate the logic of generating the elements from the logic of combining them, by using map before inject. This would make your code look like this:

(0...num_bits).map {|i| (rand<0.5) ? "1" : "0"}.inject("") {|s,i| s<<i}

Now there's two things to notice here:

Whenever you call map on a range from 0 to some size, you might rather want to use Array.new(size) {block} which creates an array of the given size by calling the block size times.
The smaller inject is now much easier to understand, but happens to be equivalent to calling join, so let's just do that.

So your code becomes:

Array.new(num_bits) { (rand<0.5) ? "1" : "0" }.join

This way you create a temporary array, which you didn't before, but on the other hand your code became much more understandable, so that little inefficiency should be worth it.

(pop[i][:fitness] > pop[j][:fitness]) ? pop[i] : pop[j]

Thanks to the Individual class this now looks like this:

(pop[i] > pop[j]) ? pop[i] : pop[j]

This isn't much different, but note that it now has the form (x > y) ? x : y, which incidentally means "the maximum of two objects". In other words we can simplify this code by using the max method:

[ pop[i], pop[j] ].max

bitstring.size.times do |i|
  bit = bitstring[i].chr

Again this should be bitstring.each_char do |bit| or bitstring.each_byte do |b| bit = b.chr.

""+parent1 if rand()>=rate

I'm not sure what the ""+ is supposed to do here. Remove it. Note that ""+x is not a way to turn x into a string in ruby (like it would be in e.g. Java). Calling ""+x when x is not a string (or "duck-string"), will cause a type error.

The fact that you're using ""+ to create a copy is less than obvious (thus the above paragraph). If you use the dup method, whose sole purpose it is to create a copy, instead, it will be much more understandable.

I'd also change the crossover method to return an individual rather than a string, which makes the code a bit simpler.


Calculating Chinese zodiac signs based on birthdays

To start, lets look for something that we can loop through. From your link to relevant dates, we can see that the associated animals loop through 12 animals, in order:

Rat
Ox
Tiger
Rabbit
Dragon
Snake
Horse
Goat
Monkey
Rooster
Dog
Pig

After [Pig], it restarts again with [Rat]. So let's put these into an associative array, with the associated element:

$assocs = array(
    "Rat"     =>  "Yang Wood",
    "Ox"      =>  "Yin Wood",
    "Tiger"   =>  "Yang Fire",
    "Rabbit"  =>  "Yin Fire",
    "Dragon"  =>  "Yang Earth",
    "Snake"   =>  "Yin Earth",
    "Horse"   =>  "Yang Metal",
    "Goat"    =>  "Yin Metal",
    "Monkey"  =>  "Yang Water",
    "Rooster" =>  "Yin Water",
    "Dog"     =>  "Yang Wood",
    "Pig"     =>  "Yin Wood" )
);

Now, to determine the sexagenary cycle of a gregorian year, the algorightm is as follows:

sCycle = (grego - 3) - (60 X ([(grego - 3)] / 60))

So, let's translate that to a PHP function:

function sexagenaryToGregorian($gYear){
    return ($gYear - 3) - (60 * (floor(( $gYear - 3) / 60)));
}

Now, we know that the Sexagenary cycle consists of 60 periods, thus, to determine what animal and element a certain year matches:

$bdayYear = 1989;
$sYear = sexagenaryToGregorian($bdayYear);
// $sYear == 6

For birth year 1989, sYear should be period 6. Now, let's generate a function that will hold the animal-element array above ($assoc) and contain two loops. The outer loop will decrement through the ceiling of the sexagenarian cycle divided by 12, and the inner loop is a foreach() over the animal-element array. This method is accurate all the way back to 4AD.

function generateAnimal($sexaCycle){
    $assocs = array(
        "Rat"     =>  "Yang Wood",
        "Ox"      =>  "Yin Wood",
        "Tiger"   =>  "Yang Fire",
        "Rabbit"  =>  "Yin Fire",
        "Dragon"  =>  "Yang Earth",
        "Snake"   =>  "Yin Earth",
        "Horse"   =>  "Yang Metal",
        "Goat"    =>  "Yin Metal",
        "Monkey"  =>  "Yang Water",
        "Rooster" =>  "Yin Water",
        "Dog"     =>  "Yang Wood",
        "Pig"     =>  "Yin Wood"
    );

    $i = 1;
    while(ceil($sexaCycle / 12) > 0){
        foreach($assocs as $animal => $element){
            if($i == $sexaCycle)
                return array($animal => $element);
            $i++;
        }
    }
}

Let's give it a few runs:

// Let's find the result for the year 2041
$result = generateAnimal(sexagenaryToGregorian(2041));
print_r($result); // Array ( [Rooster] => Yin Water )

// Let's find the result for the year 4
$result = generateAnimal(sexagenaryToGregorian(4));
print_r($result); // Array ( [Rat] => Yang Wood )

// Let's find the result for the year 1989
$result = generateAnimal(sexagenaryToGregorian(1989));
print_r($result); // Array ( [Snake] => Yin Earth )

Looks good to me! Now, if you want to include the dates, that's when you may want to start thinking about just using a database as a static lookup table.


Find Square root of number only with addition or/and subtraction

static void FindSquareRoot(int S)

Why void? The method would be more useful if it returned the value rather than printing it, and throw an exception if the input was invalid rather than printing an error message.

    int i = 1;

    for (; i <= S; i++)

The scope of i is the loop, so why not restrict it to that scope?

        int k = S;
        int j = i;

        while (j>0)
        {
            k = k - i;
            j--;
        }

i and j as loop variables are fairly conventional, but what does k mean? It's not a loop variable. A comment indicating that after the inner loop k = S - i * i would help, and might suggest a name like surplus.

Again, restrict the scope of the loop variable to the loop unless there's good reason not to.

Finally, on scope, by pulling k out of the loop you should be able to figure out a way to update its value without using an inner loop...


Validating user input in C# coming from XAML controls

This is not how it should be done in WPF especially that you are not validating the text but just changing it upper case - you validate only the numeric input.

The right way would be to use the Binding Validation

This method would allow you to write specialized validators without ifs or switches.


Dataframe transformation to numpy ndarray takes ages to complete

Your code appears to be quadratic in the number of groups.  Each call to np.concatenate() allocates enough memory to hold the new array and then copies the data. The first group is copied the first time through the loop. Then the first and second groups on the second time. Then the first to third groups on the third time, etc.
To speed this up, keep a list of the groups and then call np.concatenate() just once on the list of groups.
Another observation is that the code splits a group into chunks only to reassemble them in the loop. The only differences are the group is padded to be a multiple of group_size and the shape of the array has changed. But those can be addressed without splitting and concatenating each group.
The Pandas documentation says to use DataFrame.to_numpy() method rather than .value.
Revised code:
def transform2(dataframe, chunk_size):

    parts_to_concat = []
    labels = []

    for _, id_group in dataframe.groupby('id'):

        group = id_group.loc[:, 'A':'D'].to_numpy()
        labels.append(id_group.loc[:, 'class'].iat[0])

        parts_to_concat.append(group)

        # add a zero-filled part to the list of parts to
        # effectively pad the group to be a multiple of chunk_size
        pad = chunk_size - len(group) % chunk_size
        if pad < chunk_size:
            parts_to_concat.append(np.zeros((pad, 4)))

    # reassemble the data and change it's shape to match
    # the output of the original code
    transformed_data = np.concatenate(parts_to_concat)
    transformed_data = .reshape(-1, 1, chunk_size, 4)

    labels = np.array(labels)

    return transformed_data, labels

On my laptop, the original code takes almost 12 minutes to run the sample dataframe. The new code takes less than one second--about a 700x speedup.


"ACM ICPC Team" challenge on Hackerrank... Easy?

Some improvements:

Combine loops

int maxTopics = 0;
int maxTeams = 0;
for(int i = 0; i < numberOfMembers - 1; i++)
    for (int j = i + 1; j < numberOfMembers; j++)
    {
        int numberOfTeamTopics
            = NumberOfSetBits(new BitArray(numberOfTopics).Or(bitArray[i]).Or(bitArray[j]));

        if (numberOfTeamTopics > maxTopics)
        {
            maxTopics = numberOfTeamTopics;
            maxTeams = 1;
        }
        else if (numberOfTeamTopics == maxTopics)
        {
            maxTeams++;
        }
    }

Use a better algorithm for counting set bits

public static Int32 NumberOfSetBits(BitArray bitArray)
{
    Int32[] ints = new Int32[(bitArray.Count >> 5) + 1];
    bitArray.CopyTo(ints, 0);
    Int32 count = 0;

    // fix for not truncated bits in last integer that may have been set to true with SetAll()
    ints[ints.Length - 1] &= ~(-1 << (bitArray.Count % 32));

    for (Int32 i = 0; i < ints.Length; i++)
    {
        Int32 c = ints[i];

        // magic (http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel)
        unchecked
        {
            c = c - ((c >> 1) & 0x55555555);
            c = (c & 0x33333333) + ((c >> 2) & 0x33333333);
            c = ((c + (c >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
        }
        count += c;
    }
    return count;
}

New execution time: 0.12 seconds.


Using VBA Copying from one ,master sheet to other workbooks based on the file names provided in master book

Your code and problem description is confusing. It seems as if you're halfway debugging the posted code. However, I've set up an example below that you can adapt to your situation. Some notable points:

Always use Option Explicit
Using Activate or Select is almost never necessary
Use clear variables to indicate the source and destination data, it
will help you keep things straight when writing your code and also
later when you have to maintain it.
An internal set of variables can be used to copy the data from one workbook to another. Using the Excel Copy is not necessary.
The "clean up" code at the bottom of my example is not strictly necessary in VBA (the interpreter will detect those objects as out of scope and will destroy them automatically). But for me it's a good habit to keep track of what I'm using.
Saving the previous state of the DisplayAlerts flag is a good idea when your code will change it. You don't necessarily know what the user's current setting will be and, aside from the changes your macro creates, you don't want the user to experience sudden unexpected changes.

Option Explicit

Sub Macro1()
    Dim previousAlertsFlag As Boolean
    Dim masterWB As Workbook
    Dim masterWS As Worksheet
    Dim destWB As Workbook
    Dim destWS As Worksheet
    Dim lastRow As Long
    Dim filepath As String
    Dim fullpath As String
    Dim country As String
    Dim countryData As Variant
    Dim r As Integer

    '--- save the current state of Alerts display, so it can
    '    be restored later
    previousAlertsFlag = Application.DisplayAlerts
    Application.DisplayAlerts = False

    '--- establish connections to the master data
    Set masterWB = ThisWorkbook
    Set masterWS = masterWB.Worksheets("Sheet3")
    lastRow = masterWS.Cells(masterWS.Rows.Count, "A").End(xlUp).Row
    filepath = "C:\Users\abhayl.INDIA\Desktop\For Primary Team\For Primary Team\"

    For r = 2 To lastRow
        country = masterWS.Cells(r, 1).Value
        countryData = masterWS.Cells(r, 2).Value

        fullpath = filepath & country
        Set destWB = Workbooks.Open(fullpath)
        Set destWS = destWB.Sheets("Specific Questions")
        destWS.Cells(1, 2).Value = countryData
        destWB.Close SaveChanges:=True
    Next i

    '--- clean up
    Set destWS = Nothing
    Set destWB = Nothing
    Set masterWB = Nothing
    Set masterWS = Nothing

    '--- restore the previous state of the Alerts flag
    Application.DisplayAlerts = previousAlertsFlag
End Sub


Is this correct usage of the "Decorator" Pattern?

I think you've misunderstood what decorator pattern is.  As described in Wikipedia

"In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class."

What you are doing is simple inheritance.

You can do this with an interface, but you don't have too.  You have to ask yourself the question "Do I need to use the Product class?"  If you do, then leave it as is, if you don't, make it an interface, or mark it abstract.

I'm going to assume you need it.

Your class definition looks the same:

public class Product
{
    public virtual string ProductName { get; set; }
    public virtual Decimal Price { get; set; }
    public virtual string ImageUrl { get; set; }

    public virtual string GetImageUrl()
    {
        return ImageUrl;
    }
}

You would then inherit from this class for any other class you need:

public class FooProduct : Product
{
    //we want to serve the image through a cdn
    public override string GetImageUrl()
    {
        return string.Format("cnd.network.com?url={0}", HttpUtility.HtmlEncode(ImageUrl));
    }
}

You can now use either class as required:

var productInstance = new Product();

var fooProductInstance = new FooProduct();

The nice part is, you can now pass FooProduct in anywhere a Product is expected:

public void DoSomethingWithProduct(Product product)
{
    // Do some processing
}

Can be called:

processor.DoSomethingWithProduct(product);

or

processor.DoSomethingWithProduct(fooProduct);


Filter out date records which don't fall within or span a date range

So, My first answer messed up (Can I blame it on incomplete test data?)

That's a good thing to note, that your should design your tests to cover the situations that are significant to you. Because your tests were incomplete, when I ran and modified your code, and got the 'same' results, I assumed the code was good. I never validated your test cases (my fault).

This re-work made me realize that your data would be better served with a negative test case. What you want to test for is exclusionary ranges. If you can assume your data is valid (it is, right), then you want to just test those cases where there is no intersection.

There is no intersection if the test date ends before the data's date, or the data's date ends before the test date. This simplifies the query to:

select *
from dates_test t0
where not (
      END_DATE < TO_DATE('03-06-2014', 'mm-dd-yyyy')
   or BEGIN_DATE > TO_DATE('04-06-2014', 'mm-dd-yyyy')

As was pointed out to me (very nicely, I may add), the above logic can be simplified further using 'basic' boolean logic to:

select *
from dates_test t0
where END_DATE >= TO_DATE('03-06-2014', 'mm-dd-yyyy')
  and BEGIN_DATE <= TO_DATE('04-06-2014', 'mm-dd-yyyy'))

which is my final answer (thanks @mjolka)

Using your (revised) SQL fiddle, the above query produces (note that your revised data has two records with id 5):

| ID |          HINT |                     BEGIN_DATE |                         END_DATE |
|----|---------------|--------------------------------|----------------------------------|
|  2 |         spans |   March, 05 2014 00:00:00+0000 | September, 08 2014 00:00:00+0000 |
|  3 | Starts within |   March, 07 2014 00:00:00+0000 | September, 07 2014 00:00:00+0000 |
|  4 |   Ends within | January, 01 2014 00:00:00+0000 |     March, 07 2014 00:00:00+0000 |
|  5 |     within OK |   March, 08 2014 00:00:00+0000 |     March, 09 2014 00:00:00+0000 |


IEnumerable Extensions Linq AllOrDefault() Each()

In those places you use new List<T>(), I would recommend using Enumerable.Empty<T>() in its place. It's a little more idiomatic and, as those empty collections are cached by the runtime, repeated calls don't new up more stuff to be GC'd later.

items.Count() > 0 can be replaced with items.Any(), which is more descriptive of what you're trying to test for, and will likely be cheaper computationally. More specifically,

public static bool AnyML<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
    if (items == null) return false;

    items = items.Where(predicate);

    return items.Count() > 0;
}

can be replaced with

public static bool AnyML<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
    if (items == null) return false;

    return items.Any(predicate);
}

** EDITED TO ADD **

public static IEnumerable<T> EachML<T>(this IEnumerable<T> items, Action<T> fn)
{
    var e = items.GetEnumerator();
    while (e.MoveNext())
    {
        fn(e.Current);
    }
    return items;
}

has a small bug - items.GetEnumerator() returns an IEnumerator<T>, which implements IDisposable. This means you should Dispose() of it when you're done using it (see https://stackoverflow.com/a/232616/3312 for good info). Write it like this to do so:

    using (var e = items.GetEnumerator())
    {
        while (e.MoveNext())
        {
            fn(e.Current);
        }
    }
    return items;
}


Hmm. I'm not sure about faster, but you can shorten your code by about 6 lines by doing things a little more efficiently.

First, I'd move your two initializations at the top to be below your if statement. That if statement short-circuits the whole function (which is fine), but since the statement doesn't use those two variables, we shouldn't instantiate them unless it fails to return: that's more efficient. I would also return a.length rather than 1 (to eliminate a 'magic number').

Next, you can eliminate the cur_max_size variable and its usage. Remove the declaration, then take the whole block involving cur_max_size and max_size_so_far and replace with this:

max_size_so_far = Math.max(endInd - startInd + 1, max_size_so_far);

Next, there are two places where you can use i++ inside of another statement, rather than having it stand on its own. i++ means "increment after the original value is used" so this is safe:

Inside of your if conditional (inside the while), delete i++; and change the first statement to be compareInd = i++;
Inside of your else statement, remove i = startInd + 1; and change the startInd=i; line to be startInd = i++;. (Yes, the logic works out.)


int wWidth = 660;
    int wHeigth = 660;

If you never change these, you may as well make them constants.

    const int wWidth = 660;
    const int wHeight = 660;

Then it's clear that they aren't intended to change.

I also fixed the spelling of "height".

    Simple_window sw(centerScreen, 660, 660, "Chapter 12 Exercise 3");

You just created variables for this.   Why not use them?

    Simple_window sw(centerScreen, wWidth, wHeight, "Chapter 12 Exercise 3");

Then you can change one value and have it propagate through.

    int tlx = sw.x_max() - 650;
    int tly = sw.y_max() - 650;

Same thing here.

    const int FRAME_SIZE = 10;
    const int TOP_LEFT_X = sw.x_max() - wWidth + FRAME_SIZE;
    const int TOP_LEFT_Y = sw.y_max() - wHeight + FRAME_SIZE;

This would also save you a comment, as it is much more obvious what this does.

        for(size_t j=0; j < numOfColumns; ++j){

It won't make a functional difference if both are 8, but this should be

        for (size_t j = 0; j < numOfRows; ++j) {

Otherwise if you change one value without changing the other (e.g. if you wanted a 12x8 checkerboard), it won't draw the board as you designate it.

            if ((i+j) % 2 == 0) r->set_fill_color(Color::red);
            else r->set_color(Color::white);

It's more robust in the face of future edits to write this as

            if ((i + j) % 2 == 0) {
                r->set_fill_color(Color::red);
            } else {
                r->set_color(Color::white);
            }

Also consider

            r->set_fill_color(((i + j) % 2 == 0) ? Color::red : Color::white);

Which is more direct.

    for(size_t k=0; k < rects.size(); ++k) sw.attach(*rects[k]);

Why do this separately?  Instead, put it in the j loop, at the end.

            sw.attach(*r);

Note that you can do this even if you put it in rects as well.

For this code, you don't need rects at all.  Perhaps you're planning on using it later, but you don't really need it now.

In C++, when you use the new operator, the memory remains allocated until you explicitly delete it.  You may want to use smart pointers.  Those would work more like you think, with garbage collection when there are no references left.

Also, if you hadn't used new but instead created a local variable that would have been automatically destroyed, putting it in rects wouldn't have worked.  The rects vector would have just contained a bunch of references to memory that no longer represented what it had when it was created.


Alternative to using sleep() to avoid a race condition in PyQt

Use a Queue, python has a threadsafe Queue class.

Push the function you want to run on the background thread onto the queue.

Have the thread wait on the queue executing functions as they are put into it.


After reading through the article linked in Josay's comment, I have translated the code into Python, removed extra fluff and added a bunch of comments to make it more readable then the version in the article. It also ran faster than the solution offered, probably due to Python's highly optimized Lists vs Java's ArrayLists.

This solution is \$O(N)\$ in both space and time, and for more details on why it works, refer to the article.

Here it is for Python 2.7 (the version required for Codility):

import operator

def solution(A):
    # calculate best swap forwards
    result1 = calculate(A)
    # calculate best swap backwards
    A.reverse()
    result2 = calculate(A)

    result = max(result1, result2)

    # If list is negative, choose least negative value
    if result == 0:
        return max(data)

    return result

def calculate(data):
    """Calculates the best partial sum swapping from front of data to back"""
    n = len(data)
    total = sum(data)

    # rolling sum: [0, 1, 2, 3] -> [0, 1, 3, 6]
    partialSum = accumulate(data, operator.add)
    # rolling max: [4, 3, 2, 1] -> [4, 4, 4, 4]
    partialMax = accumulate(data, max)

    differences = [partialSum[i] - partialMax[i] for i in range(n)]
    # rolling minimum of differences
    minDifferences = accumulate(differences, min)

    # Calculate best forward partial sums
    list1 = [min(data[0], 0)]
    for i in range(1, n):
        list1.append(min(minDifferences[i-1] + data[i], list1[i-1]))

    # Calculate best reverse partial sums
    data.reverse()
    reversedPartialSum = accumulate(data, operator.add)
    list2 = accumulate(reversedPartial, min)
    list2.reverse()

    # Calculate best swap result

    best = 0
    for i in range(n-1):
        best = max(best, total - list1[i] - list2[i+1])

    return max(best, total - list1[n-1])

def accumulate(values, function):
    """Accumulates the results of the function into a list"""
    result = [values[0]]
    for i in range(1, len(values)):
        result.append(function(values[i], result[i-1]))
    return result

And just for fun, here's a Python3.x version with the new accumulate() function from itertools:

from itertools import accumulate

def solution(A):
    # calculate best swap forwards
    result1 = calculate(A)
    # calculate best swap backwards
    A.reverse()
    result2 = calculate(A)

    result = max(result1, result2)

    # If list is negative, choose least negative value
    if result == 0:
        return max(data)

    return result

def calculate(data):
    """Calculates the best partial sum swapping from front of data to back"""
    n = len(data)
    total = sum(data)

    # rolling sum: [0, 1, 2, 3] -> [0, 1, 3, 6]
    partialSum = list(accumulate(data))
    # rolling max: [4, 3, 2, 1] -> [4, 4, 4, 4]
    partialMax = list(accumulate(data, max))

    differences = [partialSum[i] - partialMax[i] for i in range(n)]
    # rolling minimum of differences
    minDifferences = list(accumulate(differences, min))

    # Calculate best forward partial sums
    list1 = [min(data[0], 0)]
    for i in range(1, n):
        list1.append(min(minDifferences[i-1] + data[i], list1[i-1]))

    # Calculate best reverse partial sums
    data.reverse()
    reversedPartialSum = list(accumulate(data))
    list2 = list(accumulate(reversedPartial, min))
    list2.reverse()

    # Calculate best swap result

    best = 0
    for i in range(n-1):
        best = max(best, total - list1[i] - list2[i+1])

    return max(best, total - list1[n-1])


Select multiple count queries in single query

I can suggest you use common table expression (Oracle calls it "Subquery Factoring") at the very least you will be doing the filtering by date and name one time only

WITH filter_by_date_name AS (
  SELECT CODE_A, CODE_B, CODE_C FROM table_one WHERE date=myDate AND name=myName
)
SELECT
  (SELECT COUNT(*) FROM filter_by_date_name) AS total,
  (SELECT COUNT(*) FROM filter_by_date_name WHERE CODE_A BETWEEN 100 AND 199) AS code_a_low_count,
  (SELECT COUNT(*) FROM filter_by_date_name WHERE CODE_A BETWEEN 200 AND 299) AS code_a_high_count,
  (SELECT COUNT(*) FROM filter_by_date_name WHERE CODE_B BETWEEN 100 AND 199) AS code_b_low_count,
  (SELECT COUNT(*) FROM filter_by_date_name WHERE CODE_B BETWEEN 200 AND 299) AS code_b_high_count,
  (SELECT COUNT(*) FROM filter_by_date_name WHERE CODE_C BETWEEN 100 AND 199) AS code_c_count
FROM filter_by_date_name
WHERE ROWNUM=1


Getting totals of each primary key by matching it with another worksheet with a many relationship

You've not provided a fully functional set of code with data, so I can only make untested suggestions as an example for you to incorporate into your application.

Without seeing the data that you are working with, it's impossible to know if a Dictionary is the best approach. Using a Dictionary is a good idea, but only if all of the data in the table is unique. In your code fragment, for example, you are relying on the comparison of two specific cells and are not searching for a value within the entire range of data (which is better suited to a Dictionary).

Using the Index or Match is also reasonable, but remember that these functions directly interact with the worksheet cells. With larger data sets in the Range, this results in slower execution because the Range object must be traversed to access the desired Cells.

Memory-based arrays would be my recommendation for the execution speed improvements you're looking for, with a straight up array-to-array comparison. You can learn more information about using arrays here and here.

Again, you didn't include a complete set of your code for review here, but there are a few observations I can make for improvement.

Always use Option Explicit. (You may be doing this, but we can't see it)
Create intermediate objects/variables to make your code more readable. As an example, you are repeating the full reference for a worksheet as ThisWorkbook.Worksheets("Prod. Qty.") everywhere.

While it might seem more tedious at first, trust me when I say it will make your code far more readable and easier to maintain if you set it up like this:

Dim prodQtyWS As Worksheet
Dim dashboardWS As Worksheet
Set prodQtyWS = ThisWorkbook.Worksheets("Prod. Qty.")
Set dashboardWS = ThisWorkbook.Worksheets("Dashboard")

Establish your ranges explicitly so the extent of your data is clear.

Again, it's a few extra lines of code, but it will not slow down the execution time. (My example here may be an incorrect reading of your OP, you'll have to make adjustments.)

Dim prodQtyRange As Range
Set prodQtyRange = prodQtyWS.Range("A2").Resize(Total_rows_Prod, 31)

From here on out it's implementing your business logic to update the dashboard data. Here is my example Sub, which again, you have to adapt to your specific application. You will see a significant speed improvement with this method.

Option Explicit

Sub Example(ByVal Total_rows_Prod As Long, ByVal Total_rows_Dash As Long)
    Dim prodQtyWS As Worksheet
    Dim dashboardWS As Worksheet
    Set prodQtyWS = ThisWorkbook.Worksheets("Prod. Qty.")
    Set dashboardWS = ThisWorkbook.Worksheets("Dashboard")

    '--- establish the ranges and copy the data into a memory array
    Dim prodQtyRange As Range
    Dim prodQtyData As Variant
    Set prodQtyRange = prodQtyWS.Range("A2").Resize(Total_rows_Prod, 31)
    prodQtyData = prodQtyRange.Value

    Dim dashboardRange As Range
    Dim dashboardData As Variant
    Set dashboardRange = dashboardWS.Range("A2").Resize(Total_rows_Dash, 31)
    dashboardData = dashboardRange.Value

    Dim i As Long
    Dim j As Long
    For i = 2 To Total_rows_Prod
        '--- calc this factor once, since we're adding the same value
        '    to all the dashboard rows
        Dim prodQtyFactor As Double
        prodQtyFactor = prodQtyData(i, 31) / prodQtyData(i, 4)
        For j = 2 To Total_rows_Dash
            If prodQtyData(i, 5) = dashboardData(i, 1) Then
                dashboardData(j, 4) = dashboardData(j, 4) + prodQtyFactor
            End If
        Next j
    Next i

    '--- copy the updated data back to the dashboard
    dashboardRange.Value = dashboardData

End Sub


Searching for a specific object in an ArrayList

Your code is very wet (the opposite of DRY). It repeats a lot. Let's start with what you're trying to achieve:

You have an ArrayList of Products.
You want checkAvailability to return true if any Product within the given ArrayList has the same model and type of the given Product.

The way you've implemented this, with instanceof checks, is IMO not ideal. Instead, let's modify the Product class to have a custom equals() method to compare equality of Products; we can store the equality logic inside of the Product class so it's reusable.

The equals() method on an Object, by default, will act similar to == - that is, it will compare referential equality, but it's a common idiom to override this method to compare logical equality instead.

class Product {
    ...

    @Override()
    public boolean equals(Object other) {
        // This is unavoidable, since equals() must accept an Object and not something more derived
        if (other instanceof Product) {
            // Note that I use equals() here too, otherwise, again, we will check for referential equality.
            // Using equals() here allows the Model class to implement it's own version of equality, rather than
            // us always checking for referential equality.
            Product otherProduct = (Product) other;
            return otherProduct.getModel().equals(this.getModel());
        }

        return false;
    }
}

Of course, this does lose the instanceof checking in your checkAvailability method, but you can easily reintroduce something similar by overriding equals() in the subclasses of Product if you wanted to reintroduce this check (Spoiler: You probably don't! Don't compare types unless you have to). At the very least, try to move equality logic to an equals() method on a class rather than comparing equality outside of the class. Encapsulation and reusability is always nice!

With this override, we can simplify checkAvailability to the following:

public static boolean checkAvailability(ArrayList<Product> stock, Product product) {
    for (Product p : stock) {
        if (p.equals(product)) {
            return true;
        }
    }

    return false;
}

Which can be simplified to use Java streams if you'd like.

public static boolean checkAvailability(ArrayList<Product> stock, Product product) {
    return stock.stream()
                .anyMatch(p -> p.equals(product));
}

Or, even better, we can make the required type less specific:

public static boolean checkAvailability(Collection<Product> stock, Product product) {
    return stock.stream()
                .anyMatch(p -> p.equals(product));
}

As an aside: it is generally good practice to reimplement hashCode() if you reimplement equals(). Without having more knowledge of your solution, it's difficult for me to tell you how to do this, but I would recommend you do it if you end up using my suggestions.

Another side note: If you find yourself making lots of comprehensions like this, I would recommend having checkAvailability accept a Stream<Product> instead of Collection<Product> so as to avoid creating multiple streams.


SPOJ is giving TLE for this solution of ROCK

The way you call sellable may amount to a 4-th degree complexity. The very smart compiler may notice that it is a pure function, and optimize it out of the inner loop, but I wouldn't rely on it. So, one obvious optimization is to rephrase it as

if (sellable(a, i, j)) {
    cost = j - i + 1;
} else {
    cost = m[i][j];
    for (k = i; k < j; k++) {
        cost = max(cost, m[i][k] + m[k+1][j]);
}
m[i][j] = max(m[i][j], cost);

Still, sellable contributes to the cubic complexity. With a one-time linear investment you can make it into a constant time. Collect accumulated sums [0, i) of the input array; then sellable becomes just

return (a[j] - a[i]) * 2 > (j - i);

The mandatory CR note on the variable names: one letter identifiers make it really hard to follow the code, even as simple as this. I would recommend to use length, seg_start, seg_end instead of l, i, j respectively. number is just meaningless; size sounds better.

Then, I'd highly recommend to interpret length as length (not length + 1 as your code does).

Finally, please don't be shy on spaces.


Make bytes_to_size() reentrant
Since bytes_to_size returns a pointer to a static buffer, it is not reentrant. This will be a problem if you have multiple threads throwing exceptions at the same time. There are two solutions:

Have bytes_to_sign() take a pointer to a buffer as an argument, and have it write the text into that.
Have it return a std::string.

Avoid mixing C and C++ string formatting
It's very weird to see both snprintf() and std::stringstream used at the same time. Now you will get the worst of both worlds: type unsafety and possible truncation from snprintf(), and the overhead of dynamically growing memory from std::stringstream. Pick one and stick with it.
Consider using std::format
C++20 introduced std::format, which gives you type-safe string formatting. If you want to be compatible with older versions of C++, you can use the {fmt} library.
About units
The SI prefixes are powers of 1000, if you want to make sure people are not confused, use the IEC binary prefixes, so KiB, MiB, GiB and so on. I would also add all the defined prefixes, so up to YiB.
Consider allowing different exception types to be thrown
Your THROW() adds helpful information to the exception message, but the exception type is fixed to std::exception. That means that it is hard for any code that wants to catch exceptions to determine what exactly went wrong has very little information. Maybe you can add the exception type as an argument to the macro?
#define THROW(type, text, ...) \
    error_handler::throw_ex<type>(text, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__);

template <typename Exception, typename... Args>
void throw_ex(const char* text, ...) {
    ...
    throw Exception(stream.str().c_str());
}

Then it can be used like so:
if (value > MAX_VALUE) {
    THROW(std::out_of_range, "value %d larger than maximum %d", value, MAX_VALUE);
}

C++20 will avoid the need for macros
C++20 introduces std::source_location which avoids the need to use macros to get the filename and line number at the place where the exception is thrown.


Basic Color class for both Delphi and Lazarus

Self-review

Randomize missing
Since I use Random to generate pseudo-random color, it is, I lightly remember, a must to call Randomize once program or unit in this case is being created; more information.
// ...

initialization
    Randomize;

end.

Get... Red, Green, Blue, Cyan, Magenta, Yellow
These seem to operate as expected.

constructors
The biggest error I already see I have made is the constructor thing. The problem is I did not write one for direct TColor assignment. It could be re-written for instance like this in the interface:
type
    TBasicColor = class
    // ...
    public
        // default direct TColor assignment constructor
        constructor Create(const AColor: TColor); overload;
        // reintroduce is hiding TObject constructor
        constructor Create; reintroduce; overload;
        // create using RGB values
        constructor CreateRGB(const ARed, AGreen, ABlue: Byte);
        // create using CMY values
        constructor CreateCMY(const ACyan, AMagenta, AYellow: Byte);
        // create pseudo-random color constructor
        constructor CreateRandom;
    // ...

Plus, like this in the implementation:
constructor TBasicColor.Create(const AColor: TColor);
begin
    // in here it is just plain assignment
    inherited Create;
    FColorRef := AColor;
end;

constructor TBasicColor.Create;
begin
    // in case anyone just calls Create() we assign white color
    Create($FFFFFF);
end;

constructor TBasicColor.CreateRGB(const ARed, AGreen, ABlue: Byte);
begin
    Create(ARed or (AGreen shl 8) or (ABlue shl 16));
end;

constructor TBasicColor.CreateCMY(const ACyan, AMagenta, AYellow: Byte);
begin
    CreateRGB(255 - ACyan, 255 - AMagenta, 255 - AYellow);
end;

constructor TBasicColor.CreateRandom;
begin
    Create(Random($FFFFFF + 1));
end;

As you can see, all, in the end, are calling the default constructor, which I see as much better implementation.

overload keyword
Note on overload keyword, I originally did not need it in Lazarus, but Delphi requires it.

Comments
By the way, I should really use more comments, they will prove useful one day, once I read it after years.

Why read-only ColorRef?
On second thought, I see no reason for the ColorRef not being able to change at runtime, I find it hard to see what reason I had before, but no matter, it should stay a private member with properties to safely read and write, also the typecast might be wrong, cannot confirm or disprove at this point, best to typecast when necessary in-place.
For example with private method Assign:
procedure TBasicColor.Assign(const ColorRef: TColor);
begin
    if (ColorRef < 0) or (ColorRef > $FFFFFF)
        then raise ERangeError.Create('ERangeError in TBasicColor class.' + sLineBreak +
                                      'It supports only subset of TColor range.' + sLineBreak +
                                      'Valid range is <0; $FFFFFF>.')
        else FColorRef := ColorRef;
end;

which can in turn be used in the SetColorRef setter:
procedure TBasicColor.SetColorRef(const ColorRef: TColor);
begin
    Assign(ColorRef);
end;

ARed change to Red, etc.
I believe it's a habit or style point, but anyway.
I removed, and am no longer a fan of an A prefixing, changed to this:
constructor TBasicColor.CreateRGB(const Red, Green, Blue: Byte);
constructor TBasicColor.CreateCMY(const Cyan, Magenta, Yellow: Byte);

Modified code
After a few other adjustments, I will name only the use of setters in all color components, this unit could be re-written finally to this state:
unit basic_color;

interface

uses
    Graphics, SysUtils;

type
    TBasicColor = class
    strict private
        FColorRef: TColor;
    private
        // TColor assignment with range check <0; $FFFFFF>
        procedure Assign(const ColorRef: TColor);
        // independent function needed (Delphi/Lazarus; Windows/Linux)
        function RGBToColor(const Red, Green, Blue: Byte): TColor;
    protected
        function GetColorRef: TColor;
        procedure SetColorRef(const ColorRef: TColor);
        function GetRed: Byte;
        procedure SetRed(const NewRed: Byte);
        function GetGreen: Byte;
        procedure SetGreen(const NewGreen: Byte);
        function GetBlue: Byte;
        procedure SetBlue(const NewBlue: Byte);
        function GetCyan: Byte;
        procedure SetCyan(const NewCyan: Byte);
        function GetMagenta: Byte;
        procedure SetMagenta(const NewMagenta: Byte);
        function GetYellow: Byte;
        procedure SetYellow(const NewYellow: Byte);
    public
        // default direct TColor assignment
        constructor Create(const ColorRef: TColor); overload;
        // reintroduce is hiding TObject default constructor
        constructor Create; reintroduce; overload;
        // create color using RGB values
        constructor CreateRGB(const Red, Green, Blue: Byte);
        // create color using CMY values
        constructor CreateCMY(const Cyan, Magenta, Yellow: Byte);
        // create pseudo-random color
        constructor CreateRandom;
        property ColorRef: TColor read GetColorRef write SetColorRef;
        property Red: Byte read GetRed write SetRed;
        property Green: Byte read GetGreen write SetGreen;
        property Blue: Byte read GetBlue write SetBlue;
        property Cyan: Byte read GetCyan write SetCyan;
        property Magenta: Byte read GetMagenta write SetMagenta;
        property Yellow: Byte read GetYellow write SetYellow;
    end;

implementation

procedure TBasicColor.Assign(const ColorRef: TColor);
begin
    if (ColorRef < 0) or (ColorRef > $FFFFFF)
        then raise ERangeError.Create('ERangeError in TBasicColor class.' + sLineBreak +
                                      'It supports only subset of TColor range.' + sLineBreak +
                                      'Valid TBasicColor range is <0; $FFFFFF>.')
        else FColorRef := ColorRef;
end;

function TBasicColor.RGBToColor(const Red, Green, Blue: Byte): TColor;
begin
    Result := Red or (Green shl 8) or (Blue shl 16);
end;

constructor TBasicColor.Create(const ColorRef: TColor);
begin
    // in here it is just plain assignment
    inherited Create;
    Assign(ColorRef);
end;

constructor TBasicColor.Create;
begin
    // in case anyone just calls Create() we assign white color
    Create($FFFFFF);
end;

constructor TBasicColor.CreateRGB(const Red, Green, Blue: Byte);
begin
    Create(RGBToColor(Red, Green, Blue));
end;

constructor TBasicColor.CreateCMY(const Cyan, Magenta, Yellow: Byte);
begin
    CreateRGB(255 - Cyan, 255 - Magenta, 255 - Yellow);
end;

constructor TBasicColor.CreateRandom;
begin
    Create(Random($FFFFFF + 1));
end;

function TBasicColor.GetColorRef: TColor;
begin
    Result := FColorRef;
end;

procedure TBasicColor.SetColorRef(const ColorRef: TColor);
begin
    Assign(ColorRef);
end;

function TBasicColor.GetRed: Byte;
begin
    Result := Byte(FColorRef);
end;

procedure TBasicColor.SetRed(const NewRed: Byte);
begin
    Assign(RGBToColor(NewRed, GetGreen, GetBlue));
end;

function TBasicColor.GetGreen: Byte;
begin
    Result := Byte(FColorRef shr 8);
end;

procedure TBasicColor.SetGreen(const NewGreen: Byte);
begin
    Assign(RGBToColor(GetRed, NewGreen, GetBlue));
end;

function TBasicColor.GetBlue: Byte;
begin
    Result := Byte(FColorRef shr 16);
end;

procedure TBasicColor.SetBlue(const NewBlue: Byte);
begin
    Assign(RGBToColor(GetRed, GetGreen, NewBlue));
end;

function TBasicColor.GetCyan: Byte;
begin
    Result := 255 - GetRed;
end;

procedure TBasicColor.SetCyan(const NewCyan: Byte);
begin
    SetRed(255 - NewCyan);
end;

function TBasicColor.GetMagenta: Byte;
begin
    Result := 255 - GetGreen;
end;

procedure TBasicColor.SetMagenta(const NewMagenta: Byte);
begin
    SetGreen(255 - NewMagenta);
end;

function TBasicColor.GetYellow: Byte;
begin
    Result := 255 - GetBlue;
end;

procedure TBasicColor.SetYellow(const NewYellow: Byte);
begin
    SetBlue(255 - NewYellow);
end;

initialization
    Randomize;

end.


A few quick comments, in no particular order:

Python 3 uses print as a function, not a statement

You’ve tagged the question with [python-3.x], but the code uses print statements, not functions. If I try to run the code with Python 3, I immediately get an error:

  File "tictactoe.py", line 2
    print "The board look like this: \n"
                                       ^
SyntaxError: Missing parentheses in call to 'print'

Henceforth I’ll assume that you’re actually using Python 2.x, and the question was just mistagged.

Don’t catch overly broad exceptions.

In your get_input() function, you have except Exception as e, to catch the case where the user enters something that isn’t an integer. You can improve this in two ways:

Only catch the exception you‘re expecting to throw. If you catch plain Exception, you risk losing information about unexpected errors.

In this case, you might get a ValueError if the user gives a string which can’t be coerced to an integer, so catch ValueError’s instead.
Limit the amount of code in the try block. The only line you expect to throw an exception is user = int(user), but you’ll catch exceptions thrown in any of the surrounding lines. Better to only include that line in the try block – again, you won’t lose information about unexpected errors.

Here’s how you can rewrite the body of the get_input() function accordingly:

user = raw_input("Where would you like to place " + turn + " (1-9)?
try:
    user = int(user)
except ValueError:
    print user + " is not a valid move! Please try again.\n"
    continue
if 1 <= user <= 9:
    return user-1
else:
    print "That is not a valid move! Please try again.\n"
    print_instruction()

That said, I was unable to find any invalid input that caused the script to crash – kudos.

Looking further, I see something worse in check_win():

try:
    if board[each[0]-1] == board[each[1]-1] and board[each[1]-1] == board[each[2]-1]:
        return board[each[0]-1]
except:
    pass

You should never do except: pass. This will (silently) swallow every form of exception – including SystemExit and KeyboardInterrupt, which you almost certainly don’t want to catch. In this case, you probably want to catch KeyError instead.

Get rid of the valid variable in get_input()

Its value is never actually used – it just serves to keep the loop going perpetually until the function returns. Better to use while True than track an unused variable.

Likewise for win in the main function.

Add comments and docstrings

There’s very little in the way of commentary in this code. That makes it hard to follow, and it will make things difficult when you come to maintain it in future.

Comments will help understand why you’ve written the code this way – for example, in get_input(), why do we decrement 1 from the value provided by the user? And docstrings are important if you want your code to be reusable.


You may use a template.

$message = file_get_contents('path/to/your/html/template.html');

Then replace parts of it applying variables

// Defining variables
$variable1 = 'This will be a heading';
$variable2 = 'This will be a paragraph. Look at me, I\'m awesome!';

// Replace placeholders with my variables
$message = str_replace('%variable1%', $variable1, $message);
$message = str_replace('%variable2%', $variable2, $message);

And finally pass it to PHPmailer

$mail->Body = $message;

In your HTML template reference variables as part of your body, nothing more than

%variable1%

%variable2%

You probably already know, but I'd suggest anyway to specify that the message contains HTML

$mail->IsHTML(true);         // specify that it is html
$mail->CharSet = "utf-8";    // avoid encoding issues


DRYing out my Sass, looping through selectors

Well I finally figured out a way to do what I had in my mind:

@each $a, $b, $c, $d in (
    (foo,   (#f69c28,#b75d00,#b75d00), #b85e00, (#FFAC41,#E77500,#E77500)),
    (bar,   (#FFAC41,#E77500,#E77500), #008A0F, (#25CF39,#179F27,#179F27)),
    (baz,   (#67a9e4,#3a7ab2,#3a7ab2), #4477a5, (#72B4EF,#448BCA,#448BCA))
    ) {
    .foo_#{$a} {
        @include linear-gradient(nth($b,1),nth($b,2),nth($b,3)); text-shadow: -1px -1px 0 $c;
        &:hover { @include linear-gradient(nth($d,1),nth($d,2),nth($d,3)); }
    }
}

But really it doesn't look like it's any clearer (likely it's worse) and it only dropped from 493 characters to 420. I guess my intention, though, was just knowing HOW to do it. Perhaps this is one case where I don't need to be DRY if it makes the code harder to understand.


Your code has somewhat inconsistent styling which can inhibit readability and prevent the code from looking crisp and professional. For example, some of your function definitions have braces on the next line others don't. Some of your function definitions and calls put spaces between parenthesis var signal = function ( status ){, and some don't var inject = function (functionToReplace, injectedFunction).

Also, I don't believe that the last line init( constructorOptions ); is executing because you return from the constructor in both the if and else blocks right above it.

That said, using closures to keep private functions private is a great idea.

As for the modularity, while returning a separate object for for testing is a truly fascinating idea, my gut instinct goes against it. I find it somewhat troublesome because it violates cohesion with your constructor really doing two things: creating a dataStatus object and creating a dataStatus test object. This introduces room for bugs if future functions aren't properly assigned to both the real and test object. To catch these bugs, you'd want to write a test case that ensures the test object shares all the same functions as the real object. (i.e. call could have extra functions but it must also have each one that a normal dataStatus would)

I'd recommend eliminating call and if needed to use this instead. Although it might be best to just call the functions directly.

var init = function () {
    jQuery.extend(options, optionsToSet);

    setStatus(options.defaultStatus); // just call setStatus directly
    return this;
}

You can still do your testing by dissecting the methods you want from the real object.

var realObj = new dataStatus (options);
var testObj = {
    setStatus : realObj.setStatus,
    getStatus : function () {},
    signal : function () {}
};

Private functions should be tested through the testing of public functions, but in your case the only private function is for changing functions when testing.

UPDATE:

If you're set on testing your private functions--and I can fully understand how it could be worth it--you ought to to take care of a few things.

First, make sure the test object and the real object have the same functions. You could write a test case that checks that their functions are the same, but it may be best to just write the private functions directly as properties of the call object:

var call = {};

call.init = function () {
    // ...
}
call.inject = function () {
    // ...
}
call.getStatus = function () {
    // ...
}

// ...

if (/* determine if your unit testing each function */) {
    return call;
}
else {
    return {
        init: call.init,
        getStatus: call.getStatus,
        setStatus: call.setStatus,
        signal: call.signal
    };
}

Secondly, you will want to also test the real object. You could have millions of test cases for your test object, but since your real object isn't your test object, the real object might still break.


Calculate and use a linear equation based on sets of x and y values

I'd structure your program in a slightly different way. First, instead of passing around two arrays of float, why don't you introduce a Point data structure and work with it?
It would save you from checking that you get passed two array of the same length, which looks quite neat to me.

I think you could also consider introducing a Coefficients data structure to hold your pair of slope and intercept value. If you do that it will be much clearer what your function does.

Since you eventually want to have a function you can play with, you could create a toFunction :: Coefficients -> Float ->Float. In this way you decouple the computation of the coefficients that best fit with your data and the construction of the corresponding curve. This enables you to play not only with the curves you fit from data but also with curves you can define from their coefficients.

I think that a nicer way to compute the value could be by putting as much math as possible in some temporary variables you define in the where block. That could allow you to separate the high level computation you need to perform with all the other smaller steps required to compute some other intermediate results you need.

If you apply the changes I suggested you should come up with code similar to the following:

type Point = (Float, Float)
type Coefficients = (Float, Float)

toFunction :: Coefficients -> Float -> Float
toFunction (s, i) x = s * x + i

slope :: [Point] -> Float
slope [] = error "Empty list of points"
slope (_ : []) = error "Single point"
slope points = (n*sumCoorProds - (sumX*sumY))/ (n*sumSquares - (sumX*sumX))
  where
    n = fromIntegral $ length points
    (xs, ys) = unzip points
    sumCoorProds = sum $ map ( \(x, y) -> x * y ) points
    sumSquares   = sum $ map ( \(x) -> x * x ) xs
    sumX         = sum xs
    sumY         = sum ys

intercept :: [Point] -> Float
intercept points = (sumY - (s * sumX)) / n
      where
      (xs, ys) = unzip points
      n = fromIntegral $ length points
      s = slope points
      sumX = sum xs
      sumY = sum ys

getCoefficients :: [Point] -> Coefficients
getCoefficients points = (slope points, intercept points)


Project Euler #9: Finding Pythagorean triplets with a given sum

Reorganising the code

In general, it is a good idea to have your logic computing result and your logic handling output/input as independant as possible. This makes things easier to test, easier to understand and thus easier to optimise. In problems based on Project Euler, this is usually a fairly simple task because the problems are described in such a way that they need little or no input and return a number.

In your case, you could write something like:

import java.util.Scanner;

public class SpecialPythagoreanTriplet {

    public static int getProductForPythagoreanTriplerOfPerim(int n)
    {
        int i=0, j=0, a=0, b=0, c=0;
        for(i=1; i<n; i++)
            for(j=(i+1); j<=n; j++) {
                //These two loops run to take a pair of numbers. j=(i+1) to avoid repetitions in the future.
                if(isSquare((i*i) + (j*j))) //check if a number is a square
                    if(((int)Math.sqrt((i*i)+(j*j)) + i + j) == n) {
                        a = i;
                        b = j;
                        c = (int)Math.sqrt((i*i)+(j*j));
                    }
            }
        return (c==0) ? -1 : a*b*c;
    }

    public static void main(String[] args) {
        if (false) // interactive
        {
            Scanner scan = new Scanner(System.in);
            for (int t = scan.nextInt(); t!=0; t--) {
                System.out.println(getProductForPythagoreanTriplerOfPerim(scan.nextInt()));
            }
            scan.close();
        }
        else // hardcoded
        {
            System.out.println(getProductForPythagoreanTriplerOfPerim(25) == -1);
            System.out.println(getProductForPythagoreanTriplerOfPerim(1000) == 31875000);
            System.out.println(getProductForPythagoreanTriplerOfPerim(30000) == 1197129472);
        }
    }

    static boolean isSquare(double t) {
        int a = (int)Math.sqrt(t);
        if(a*a == t)
            return true;
        else
            return false;
    }
}

Improving the code quality

Then, a few things you could do to improve your code quality:
 - remove useless comment
 - put brackets around any block containing more than 1 line of code even if this is not required
 - define variables in the smallest possible scope
 - factorise out expressions written and computed multiple times.

You'd get something like:

public static int getProductForPythagoreanTriplerOfPerim(int n)
{
    int a=0, b=0, c=0;
    for (int i=1; i<n; i++) {
        for (int j=i+1; j<=n; j++) {
            //These two loops run to take a pair of numbers. j=(i+1) to avoid repetitions in the future.
            int squareCand = i*i + j*j;
            if (isSquare(squareCand)) {
                int squareRoot = (int)Math.sqrt(squareCand);
                if (squareRoot + i + j == n) {
                    a = i;
                    b = j;
                    c = squareRoot;
                }
            }
        }
    }
    return (c==0) ? -1 : a*b*c;
}

Optimising the code

Once you've done this. You do not really need the function isSquare anymore. For performance reason, it would even be a good idea to get rid of it in order not to compute square roots multiple times.

public static int getProductForPythagoreanTriplerOfPerim(int n)
{
    int a=0, b=0, c=0;
    for (int i=1; i<n; i++) {
        for (int j=i+1; j<=n; j++) {
            //These two loops run to take a pair of numbers. j=(i+1) to avoid repetitions in the future.
            int squareCand = i*i + j*j;
            int squareRoot = (int)Math.sqrt(squareCand);
            if (squareRoot*squareRoot == squareCand) {
                if (squareRoot + i + j == n) {
                    a = i;
                    b = j;
                    c = squareRoot;
                }
            }
        }
    }
    return (c==0) ? -1 : a*b*c;
}

Then it is clear that the conditions can be rewritten:

           if (squareRoot*squareRoot == squareCand &&
                squareRoot == n - i - j) {
                    a = i;
                    b = j;
                    c = squareRoot;
            }

Then you can use this in order not to compute any squareRoot:

            int squareRootCand = n - i - j;
            int squareCand = i*i + j*j;
            if (squareRootCand*squareRootCand == squareCand) {
                    a = i;
                    b = j;
                    c = squareRootCand;
            }

Also it is even clearer that we want i + j <= n. Because i < j, we also have 2 * i < n.
Thus, the loop boundaries can be rewritten:

    for (int i=1; 2*i < n; i++) {
        for (int j=i+1; i+j<=n; j++) {

I think a more precise analysis of the mathematical property would lead to a smaller search space. In fact, because i corresponds to the smallest side, we could write: 3 * i < nand i + 2j < n.

Warning: from here, it's just me trying to apply random (and simple) math operations with no promise whatsoever that things will get better.

By limiting the number of times sub-expressions are computed, one could write (but I do not find this very beautiful):

    int a=0, b=0, c=0;
    for (int i=1; 3*i < n; i++) {
        int i2 = i*i;
        int rem = n-i;
        for (int j=i+1; 2*j<=rem; j++) {
            int squareRootCand = rem - j;
            int squareCand = i2 + j*j;
            if (squareRootCand*squareRootCand == squareCand) {
                    a = i;
                    b = j;
                    c = squareRootCand;
            }
        }
    }

Then using mathematical property: squareRootCand*squareRootCand = (rem - j)^2 = rem^2 -2*rem*j + j^2 and a few simplifications:

    for (int i=1; 3*i < n; i++) {
        int i2 = i*i;
        int rem = n-i;
        int rem2 = rem*rem;
        for (int j=i+1; 2*j<=rem; j++) {
            if (rem2 - i2 == 2 * rem * j) {
                    a = i;
                    b = j;
                    c = rem - j;
            }
        }
    }

Getting a bit crazy, we can see that we actually want j == (rem2 - i2) / (2*rem) and the division to work fine:

    for (int i=1; 3*i < n; i++) {
        int i2 = i*i;
        int rem = n-i;
        int rem2 = rem*rem;
        int tmp1 = rem2 - i2;
        int tmp2 = 2 * rem;
        if (tmp1 % tmp2 == 0)
        {
            int tmp3 = tmp1 / tmp2;
            for (int j=i+1; 2*j<=rem; j++) {
                if (tmp3 == j) {
                        a = i;
                        b = j;
                        c = rem - j;
                }
            }
        }
    }

and then we do not really need the j loop: the code is now a single loop:

public static int getProductForPythagoreanTriplerOfPerim(int n)
{
    // a + b + c = n
    // 0 < a < b < c < n
    // a^2 + b^2 = c^2
    int a=0, b=0, c=0;
    for (int i=1; 3*i < n; i++) {
        int rem = n-i;
        int tmp1 = rem*rem - i*i;
        int tmp2 = 2 * rem;
        if (tmp1 % tmp2 == 0)
        {
            int j = tmp1 / tmp2;
            if (i+1 <= j && 2*j <= rem) { // not needed ?
                a = i;
                b = j;
                c = rem - j;
            }
        }
    }
    return (c==0) ? -1 : a*b*c;
}

Or, making the math more explicit and adding a check for odd values of n:

public static int getProductForPythagoreanTriplerOfPerim(int n)
{
    // a + b + c = n  =>  c = n - (a + b)
    // a² + b² = c² becomes:
    // a² + b² = (n - (a + b))² = n² + a² + b² + 2ab - 2n(a+b)
    // 2 b (n - a) = n (n - 2a)
    // we must have n = 2m
    // b = n (n-2a) / (2n -2a) = 2m(2m-2a) / (4m - 2a)
    //   = 2m(m-a) / (2m -a )
    //   = n(m-a) / (n-a)
    int a=0, b=0, c=0;
    if (n % 2 == 0) {
        int m = n/2;
        for (int i=1; 3*i < n; i++) {
            int top = n*(m-i);
            int down = n-i;
            if (top % down == 0)
            {
                a = i;
                b = top/down;
                c = down - b;
            }
        }
    }
    return (c==0) ? -1 : a*b*c;
}

Going further

It may not be relevant for this problem (but it may be if you continue on Project Euler problems): a different algorithm can be found using formulas for generating Pythagoran triples.


Student project that calculates the return on an investment

The first thing that is noticeable when looking at this code is that there are too many comments. Let me explain.

Example 1 - stating the obvious

    // set futureValue to tfFutureValue
    tfFutureValue.setText(String.format("$%.2f", futureValue));

This comment does not add any value to your program, it creates mess. The code itself is self-explanatory, and even if I had 2 weeks experience in Java, I would know what it does.

Example 2 - stating the untrue

public class Exercise15_5 extends Application {

    // globals
    private TextField tfInvestmentAmount = new TextField();
    private TextField tfNumYears = new TextField();
    private TextField tfAnnualInterestRate = new TextField();

The comment that says //globals is simply wrong - the TextFields are private fields of Exercise15_5 class. You can create a "global" variable in Java by creating a public static field - then you can use it everywhere, but of course you don't want to do that in your application

Example 3 - extract code to a method instead of commenting

In your start() method, you have 4 big blocks of code that are doing different things and are commented accordingly, like:

    // Set Properties for UI
    gridPane.setAlignment(Pos.CENTER);
    tfInvestmentAmount.setAlignment(Pos.BOTTOM_RIGHT);
    tfNumYears.setAlignment(Pos.BOTTOM_RIGHT);
    tfAnnualInterestRate.setAlignment(Pos.BOTTOM_RIGHT);
    tfFutureValue.setAlignment(Pos.BOTTOM_RIGHT);
    tfFutureValue.setEditable(false);
    gridPane.setHalignment(btCalc, HPos.RIGHT);

We can extract those lines to a new method and give it some meaningful name... Just like we would comment those lines!

private void setPropertiesForUI() {
    gridPane.setAlignment(Pos.CENTER);
    tfInvestmentAmount.setAlignment(Pos.BOTTOM_RIGHT);
    tfNumYears.setAlignment(Pos.BOTTOM_RIGHT);
    tfAnnualInterestRate.setAlignment(Pos.BOTTOM_RIGHT);
    tfFutureValue.setAlignment(Pos.BOTTOM_RIGHT);
    tfFutureValue.setEditable(false);
    gridPane.setHalignment(btCalc, HPos.RIGHT);
}

Then, your start() method becomes much cleaner:

@Override
public void start(Stage primaryStage) {
    createUI();
    setPropertiesForUI();
    calculateFutureValue();
    createSceneAndPlaceItInTheStage();
}

Split logic and UI into separate classes

I also believe that the calculateFutureValue() method should not be in the Exercise15_5 class. It should be extracted to another class, possibly something named like InvestmentCalculator. The method should take doubles and int as input parameters, not Strings (it doesn't know about textfields and UI).

You can make the calculateFutureValue() static in the InvestmentCalculator class since it's just performing some calculations and returning a value - you don't need an instance of it. You can even make InvestmentCalculators constructor private to prevent creating an instance of it - in other words, making the InvestmentCalculator a Util Class.

I don't want to go into the implementation details since this is tagged as homework, but you can always edit your question or post another one after the refactoring.


That is basically the same technique that I would use.

My only suggestion is to consistently use

for (i = 1; i <= n; i++)

for both loops, to match the stated definition.


Peer to Peer GraphQL with Relay over WebSocket

Don't!
After working on this for too long, I'm moving onto something else, and don't suggest you do this. Typical over reach. When building an internet application, you have to ask yourself, are internet servers and the internet itself really the problem? Here are some specifics:

Are Servers Really a Problem? WebRTC requires signaling. Free platforms or WebSocket servers can still be DDoS, requiring something else in front of it. Servers are an easy, often free utility compared to storage and compute on an abstraction of client devices.
Who's Really Offline Today? Mobile and Wifi are ubiquitous. There's web workers. 5G has billions invested in using client devices in conjugation with data providers down to the chips with efficient power consumption.
Peer Discovery A lot of the products that bill themselves as decentralized are surprisingly centralized when it comes to peer discovery.
Authoritative Data Anyone can resolve a query with anything. Requests require complex validation, dropping the peer, and reporting to a signaling server.
Dedicated Coverage No peer instances require a server. Headless browsers may drop WebRTC support.
Private data Servers provide an area of mitigated security, as in, if someone's rooted your server and reads API secrets, you have bigger problems. Peers require specialization, as in adding a Stripe secret in local storage, and announcing checkout support.
HTTP Cookie This was the final deal breaker. Cookies with the secure header prevent JavaScript access to secrets. Server required, non-negotiable.

At best, you have a very complex and insecure infrastructure still running servers.
A better alternative is to find a graphql platform. Then run fail2ban for DDoS protection on a free tier Google Cloud Engine server, and put that in front of the graphql platform.
For more scaling, like expensive compute, setup redis as a queue, and process on a local private network.
Rest here is left as a reference:

I created an npm based on this concept, with github repo.. Feedback and contributions welcomed.
Here's some highlights after about a month's work
Load Balancing

Create a random delay on each peer from 0 to 3s in intervals of 20ms.
During delay, use GraphQL's local state management to save incoming responses.
After delay, check local state for response. Clear state if exists then short circuit exit.

Source Authentication

Use a public key crypto library like nacl.
When sending a response, sign the hash, and provide public key.
When receiving a response, verify the signature.

Validation

Use io-ts to validate the WebSocket message. My hash, query, and signature properties are strings. My variable property is a record of strings and my uri property, is either "request" or "response".
graphql runs the request's query in browser with variables so no injection.
A custom graphql-tools codegen takes the graphql schema, and generates io-ts types. These types runtime decode websocket response data.

Authoritative Data
Even with all this, there is no authoritative data sources. If you build an online store, someone can join and start responding with {price: 0.00}.
Load balancing times them out, authentication tags them, validation makes them do some work, so there's momentum working here. It's not just opening a URL. Still it's possible to open a browser window and send bad data.
My plan is to use brain.js. Train a test set of good and bad source detection. Bundle with the app. Property, value, and source should be enough for consensus and alerting the peer network of bad sources. Other ideas are transparency with good UI and let the user detect bots, and also references. Send a supplier list along with the price, and let the app independently validate. All these are domain specific so I left it out of graphql networking implementation.
Rendering, Suspense API
Work in progress, will report back soon.
Update: 10/21/20
RelayEnvironmentProvider component suspends. Since this at the top level of the app, the entire app suspends as oppose to individual components. The relay issue-tracker demo has a custom react experimental version. I'm creating a npm to see if I can drop this functionality into Relay networking.
Bundle Size
react, react-relay, relay-runtime, and graphql are all 100kb+ each. brain.js is at ~580kb. Working in the browser, and built for the browser are two different things.
To keep bundle size small, I webpack these as external modules loaded from the vendor's CDN, excluded from webpack build.
Other
graphql-tools has limited browser support. file includes do not work. Instead I went with compile time codegen while building io-ts runtime decoding from graphql schema.
jest has limited support too, especially with create-react-app. I wanted to import all files in a folder automatically. browser supports this but jest doesn't. If I want that extensibility, compile time codegen would be the best.
Also jest does not support TextEncoder, which relay uses, and was used but no longer in my nacl implementation. I used StandardLib instead.
I looked into modeling a state machine for this. xState and graphql is redundant. graphql is really nice, the best state management there is. It's best to avoid complex state as most as possible. Straight through pure functions with just input and output, best you can do.


is this a standard/right way to create and use components when using plain JS?

It's not technically wrong, but when you're writing re-usable components it's better to use prototype than to create methods in the constructor itself.

For example,

function listComponent(){}
listComponent.prototype.create = function() { .. };
listComponent.prototype.remove = function(){ ... };
listComponent.prototype.draw = function(){ ... };

When you create the methods inside the constructor then those methods are duplicated in memory for every object created. When you use the prototype those methods only need to be defined once.

If you want to write code that feels like a class then use an actual class. (JS has those now).

Aside from that, don't store you data in the function that creates the list. Pass the data into the constructor or create method.

  if I can create and use objects like this, what is the benefit of
  creating such component using say react.js?

If all you need is to generate a simple list then there is no reason to use react. React has a lot of components that your code doesn't have, like interactive features, etc.

If you take a few minutes to read about exactly what react is and does the answer to this question will be clear.


Handling workflow rules for a job application process

There is really not enough context here to talk to any performance improvements.  On the surface, there doesn't seem to be any way to optimize on this simple O(n) array iteration. I have no idea what is happening in any of the functions being called though.

You have some room for improvement on coding style IMO.

You understand the continue command but you are not using it effectively.  Consider inverting your conditionals in cases like this to get code structured more like this:

if (!someobj.hasOwnProperty(someProp)) continue;

// some logic

if (!someOthetRule) continue;

// some more logic

This eliminates all those nested ifs.

Your code is also extremely densely packed making it hard to read. You should really try to keep your lines under 80 characters, breaking longer lines across lines. And while I am normally a big proponent of meaningful variable and function names, you seem to almost take it to the extreme, using overly verbose variables when sometimes it does not seem necessary. Take for example how in your for loop you store the array length into conversionsLen when something short and simple like len would be just fine since it is clear what is happening here.


I would simplify the findOrQueue function to make sure it stays DRY

public void findOrQueue(Node target, Node top, LLQueue q) {
    int cmp = target.getData().compareTo(top.getData());
    q.enqueue(top);
    if(cmp != 0) {
        Node nextTop = (cmp < 0) ? top.getLeftChild() : top.getRightChild();
        findOrQueue(target, nextTop, q);
    }
}

Since it's used recursively, it might not be a horrible idea to keep the exit condition explicit for readability:

if(cmp == 0) {
    return; // Exit condition
} else {
    // ... as above
}

Edit: The return condition can also be made more direct:

boolean bothEmpty = q1.isEmpty() && q2.isEmpty();
return (!bothEmpty) ? t : null;


For this

full_set = set(xrange(smallest_item, largest_item + 1))

I'd suggest inlining the min and max:

full_set = set(xrange(min(original), max(original) + 1))

You don't need to convert to a list before using sorted so:

sorted(list(full_set - original_set))

Can be written as:

sorted(full_set - original_set)


I will assume that the CreditCard class is set in stone, otherwise I probably would store a DateTime in it and calculate Year, Month and Day properties based on that value. Or at least add a separate method or property that'd return a DateTime.

With that said, first of all, I wouldn't use DateTime.Compare since there're documented operators for comparing DateTimes (see further here). Using them is certainely more readable, because reading DateTime.Compare(d1, d2) > 0 makes one (at least me) lag for a moment to realize what exactly it means. Personally I like the LINQ variant much more than the loop one, but I don't think that the intermediate Select statement is necessary, because it contains such trivial logic. I think that the most readable variant, that I'd probably put into production code, looks like this:

public int NumberOfCreditCards
{
    get
    {
        DateTime now = DateTime.Now;
        return CreditCards
            .Count(card => new DateTime(card.Year, card.Month, card.Day) > now);
    }
}

More things that I'd change:

It's probably debatable, but I feel that making NumberOfCreditCards a method and renaming it into something more transparent like GetNumberOfActiveCreditCards would make the code cleaner. It depends on current time and doesn't seem (at least to me) to be a logical atribute of the User type (official guidelines).
You should consider defining the public CreditCards property as IReadOnlyCollection<CreditCard>. A List should be exposed only when you expect the client code to modify your collection, otherwise it's better to use a restrictive interface. And IReadOnlyCollection is better than IEnumerable because it clearly states that the property returns a collection that won't be enumerated at runtime (e.g. that it's not a method with yield return;). It's quite a common practice and the reasoning is written by the TS here. But again, this topic is debatable.


2D matrix - splitting the matrix in two parts with equal number of elements

Bug
If there are an odd number of M, P, or G, it should be impossible to split the matrix in half.  However, your program may erroneously think it is possible because of this type of comparison:

tmpP == numberP / 2

which can be true for example if tmpP == 2 and numberP == 5, due to the division rounding down.  Here is an example input that demonstrates this:
3 3
M M M
M M S
S P S

An easy way to fix this would be to compare like this instead:
tmpP * 2 == numberP

which doesn't suffer from any roundoff errors.  Or you could immediately return 0 possibilities if any of the three counts is odd.
Repetitive code
Your code in field_split() seems reasonable, and there isn't much that can be improved there.  However, you created a nearly exact duplicate of your code in main().  Perhaps you did this because you needed to print the total count of the answers before printing each individual answer.
A better alternative would be to generate the answers in field_split() and return them to main().  Then you could print the count of answers followed by each individual answer.  You not only reduce your code by half, you also don't have to traverse your matrix twice.
Sample rewrite
Here is how I would rewrite your code.  Some things I did:

Use helper functions to handle repetitive tasks.
Return all the ways the matrix can be split directly from field_split() to avoid having to traverse the matrix twice.
Short circuit the function if any of the counts are odd.
Cleaned up the printing code to add the proper newlines.
Added const keyword to k argument which is not modified by field_split().
Cleaned up spacing which was inconsistent in a few places.

The rewrite:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define MAX_SYMBOLS        3

// Counts GMP and adds to symCount[]
static void countSymbol(char symbol, int *symCount)
{
    switch (symbol) {
        case 'G':
            symCount[0]++;
            break;
        case 'M':
            symCount[1]++;
            break;
        case 'P':
            symCount[2]++;
            break;
    }
}

// Returns true if each count in curCount is half the count in totCount.
static bool isHalf(int *curCount, int *totCount)
{
    int i;

    for (i = 0; i < MAX_SYMBOLS; i++) {
        if (curCount[i] * 2 != totCount[i])
            return false;
    }
    return true;
}

// Returns the number of ways the matrix can be split horizontally or
// vertically, with each side having half of each symbol.
//
// WaysHorizontal must be an array of at least (columns-1) size.
// WaysVertical   must be array of at least (rows-1) size.
static int field_split(const char *k, int rows, int columns,
        int *pNumHorizontal, int *waysHorizontal, int *pNumVertical,
        int *waysVertical)
{
    int i                     = 0;
    int j                     = 0;
    int totSize               = rows * columns;
    int totCount[MAX_SYMBOLS] = {0};
    int curCount[MAX_SYMBOLS] = {0};
    int numHorizontal         = 0;
    int numVertical           = 0;

    // First count all the symbols.
    for (i = 0; i < totSize; i++) {
        countSymbol(k[i], totCount);
    }

    // If any count is odd, there are no answers.
    for (i = 0; i < MAX_SYMBOLS; i++) {
        if (totCount[i] & 1) {
            *pNumHorizontal = 0;
            *pNumVertical   = 0;
            return 0;
        }
    }

    // Find horizontal splits.
    for (i = 0; i < rows - 1; i++) {
        for (j = 0; j < columns; j++) {
            countSymbol(k[i*columns + j], curCount);
        }
        if (isHalf(curCount, totCount)) {
            waysHorizontal[numHorizontal++] = i;
        }
    }

    // Find vertical splits.
    memset(curCount, 0, sizeof(curCount));
    for (j = 0; j < columns - 1; j++) {
        for (i = 0; i < rows; i++) {
            countSymbol(k[i*columns + j], curCount);
        }
        if (isHalf(curCount, totCount)) {
            waysVertical[numVertical++] = j;
        }
    }

    *pNumHorizontal = numHorizontal;
    *pNumVertical   = numVertical;
    return numHorizontal + numVertical;
}

int main(void)
{
    int rows, columns, i, j;
    int splitNumber;

    scanf("%d %d", &rows, &columns);

    char field[rows][columns];
    int waysHorizontal[columns];
    int waysVertical[rows];
    int numHorizontal;
    int numVertical;
    int totalSplits;

    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            scanf(" %c", &field[i][j]);
        }
    }

    totalSplits = field_split(&field[0][0], rows, columns, &numHorizontal,
                    waysHorizontal, &numVertical, waysVertical);

    if (totalSplits > 0) {
        int splitIndex = 1;

        printf("Ways of splitting the field: %d\n", totalSplits);
        for (i = 0; i < numHorizontal; i++) {
            printf("%d. Horizontally, between row %d and %d\n", splitIndex++,
                    waysHorizontal[i]+1, waysHorizontal[i]+2);
        }
        for (i = 0; i < numVertical; i++) {
            printf("%d. Vertically, between column %d and %d\n", splitIndex++,
                    waysVertical[i]+1, waysVertical[i]+2);
        }
    } else {
        printf("Can't be split 50-50.\n");
    }

    return 0;
}


Python simple Class with sqlite and unit testing

This is an interesting question. Thanks for posting it!

IMO, you don't actually have a User class here. A User would be a system object that has a name, maybe an id, a password, some relationships to material, perhaps one or more privilege levels.

What you have here is an object that provides an interface to a database table - specifically, the user table. This is a Table Data Gateway in the parlance of Martin Fowler.

Let's write some sample code:

from private_data import database_path

username = 'yanxun'
user = User(username, database_path)

if user.check_user_exists():
    print("User {} is in the database".format(user.username))

That looks pretty clunky. If you rename your class to UserTable, it starts to make more sense:

from private_data import database_path

username = 'yanxun'
users = UserTable(database_path)

if username in users:      # implemented by .__contains__ method
    print("User {} is in the database.".format(username))
else:
    print("User {} not found. Adding to the database.".format(username))

    users.add(username)

Note that I am treating the table as a collection, specifically, like a set, and presuming you write method names that are inspired by existing Python collection names.

Now, with that out of the way, let me propose that you should be lazy in how you handle creating and deleting database connections. Specifically, make the caller do it!

Making the caller pass you in a connection is the best way to write code that you want to test, as well as the best way to write code that is maximally portable. If the caller mocks a database, you don't know and don't care. If the caller connects you to Oracle instead of sqlite, you don't know and don't care (provided your SQL syntax is valid).

def __init__(self, dbconn):
    self.dbconn = dbconn

Now you don't have to worry about database username/password, database path, or anything else. You can just request a cursor from the connection, and do your thing.

(Note: transaction support, and two-phase-commit support, are connection level operations, rather than cursor operations. That's why I suggest passing in a connection, rather than a cursor. See PEP-249 for details.


Sort and merge list based on another list

Very poor problem statement.  Problem statement is based on your perceived solution so review is difficult.  I could only figure out what you are trying to do by reviewing the code.

Why long Id? If you have that many OnGoingProcess then will probably need a different approach.

Have proper constructors for OnGoingProcess and make Id read only.

Create a proper application and test.  Don't just jam everything in Main.

You are changing selectedDetails.   A calling procedure does not want an input changed.   Output a new List mergedDetails.

Proper problem statement
processDetails and sortedPlans are each List of OnGoingProcess identified by property Id
Need output in this order

processDetails not present in sortedPlans (in the order in    processDetails)
sortedPlans (in the order of sortedPlans)
if present in processDetails then processDetails
else then sorted plan

Putting those thoughts in action

public static void OnGoingProcessMergeTest()
{
    var processDetails = new List<OnGoingProcess>()
    { new OnGoingProcess(120, "Process 29", "T20"), new OnGoingProcess(100, "Process 2", "A20"), new OnGoingProcess(99, "Process 3", "S20"),
      new OnGoingProcess(85, "Process 229", "B20"), new OnGoingProcess(220, "Process 39", "C20"), new OnGoingProcess(15, "Process 20", "D20"),
      new OnGoingProcess(101, "Process 129", "G20")};

    var routePlans = new List<OnGoingProcess>()
    { new OnGoingProcess(100, "Process 2"), new OnGoingProcess(120,"Process 29"), new OnGoingProcess(222, "Process new"),
      new OnGoingProcess(85, "Process 229"), new OnGoingProcess(101, "Process 129")};

    List<OnGoingProcess> mergedDetails = OnGoingProcessMerge2(processDetails, routePlans);
    foreach (var sorted in mergedDetails)
    {
        Debug.WriteLine("Id : " + sorted.Id + " Name : " + sorted.Name + " Code : " + sorted.Code);
    }
    Debug.WriteLine("");
}
public static List<OnGoingProcess> OnGoingProcessMerge2(List<OnGoingProcess> processDetails, List<OnGoingProcess> routePlans)
{
    List<OnGoingProcess> onGoingProcessMerge = processDetails.Where(x => !(routePlans.Any(y => y.Id == x.Id))).ToList();
    foreach(OnGoingProcess routePlan in routePlans)
    {
        OnGoingProcess processDetail = processDetails.FirstOrDefault(x => x.Id == routePlan.Id);
        onGoingProcessMerge.Add(processDetail ?? routePlan);
    }
    return onGoingProcessMerge;
}