Calculating the speed of a bicycle given the gear size and cadence

Your question here is again an improvement over your previous version, but, I was hoping you would take some of the abstraction suggestions and apply them.

As it stands, your program is not a general purpose program, rather it is a complex constant value...

Let's look at the things that are actual constants:

PI - 3.14 (though, for more accuracy, use Math.PI constant).
12 inches in a foot
5280 feet in a mile
60 minutes per hour

Those are your constants, and should be declared as private static final.

The things which are variables, are the cadence, and the 'gear size'.

A general purpose program would have a method that takes those two variables, and returns a speed....:

public static double calculateSpeed(double gearSize, double cadence) {...}

That method would be reusable, and general, and it exposes the right amount of functionality without exposing the inner workings of the class.

In your main method, if you would call:

System.out.println(calculateSpeed(100, 90) + "mph");

or rather, you would get the 100 and the 90 from somewhere else, perhaps a constant for the purpose of this exercise.

Now, how do you implement the calculateSpeed function? That is where the smarts of your program should be, and it should perhaps call other private methods, or do some basic calculations.

There are some style issues I see, but the most significant is that I always recommend using decimal-style typed values when you are using a double literal in your code. You have code like:

private static double feetPerInches() {
    return 1.0 / 12;
}

That produces the right results, but I recommend expressing the 12 as 12.0 to make the implicit conversions absolutely clear. I have seen too many times when bugs were introduced by integer arithmetic when floating-point was expected.

Bottom line, I would expect your program to look like:

private static final double PI = 3.14;
private static final double MINS_PER_HOUR = 60.0;
private static final double FEET_PER_MILE = 5280.0;
private static final double INCHES_PER_FOOT = 12.0;
private static final double INCHES_PER_MILE = FEET_PER_MILE * INCHES_PER_FOOT;

public static final double getSpeed(double gearSize, double cadence) {
    ....
}

public static void main(String[] args) {
    System.out.printf("%.3fmph%n", getSpeed(100.0, 90.0));
}

Note, I have used a printf at the end to simplify the logic of the output. Well, it is simpler for me, but, I thought you should see how printfs are used in Java. What that printf says, is print a floating-point value with 3 decimal places (%.3f), followed by 'mph', followed by a newline %n. The floating value to print is the speed.


What I would take away from this is how the standard library does this.

It disassociates sorting algorithms from specific container types (by using iterators). Then you can write the sorting algorithm in a way that is independent of the actual container type.

What I dislike about your code is that when you move elements you basically re-order the list (you actually move the nodes). This is a complex operation taking many checks. Personally I would leave the actual nodes where they are and move the values between nodes. std::swap() can be used for this.

This:

               current->next = tempNode->next;
                tempNode->next = current;
                if (prev != 0)
                    prev->next = tempNode;
                prev = tempNode;
                if (head == current)
                    head = tempNode;
                if (current->next == 0)
                    end = current;

Can be replaced with:

                swap(current->value, tempNode->value);

With C++ new move semantics this is now very efficient.

  EDIT: I was told that it is preferred to use a bool type for the changeFlag instead of using an int as it makes it more readable?? Thoughts?

Yes. Use the correct type. bool is a truth value it imparts meaning to the person reading the code. Humans need that extra meaning to help them understand the code better.


Minimal stack from unsigned int to track boolean values wtih bits

Reading this:

enum { LEFT, RIGHT, STKMAX = 4 };

I expect to see use LEFT and STKMAX interchangeably however they're different things you packed together for convenience. Split it and readers won't need to browse all your code to understand that they can't use STKMAX where FALSE or TRUE are expected. Is stack_push (&s, STKMAX); valid and meaningful?

You already know you may use uint32_t instead of unsigned int but, at least, you should really use unsigned, the extra int in the declaration adds nothing to your code (but that's just an opinion then take it or leave it).

unsigned int kp[STKMAX], idx;

I prefer, for clarity, to have one single variable declaration for each line. I'd also change names to something more meaningful. For example, why idx can't be indexOfNextAvailableBit? We don't need to obfuscate our code and I do not neet to read stack_push() to understand how it's used to determine what it is.

stack_clear() can be simplified to use memset(), any decent compiler will (probably) recognize it and use the best algorithm to perform the task (loop, unrolled loop, plain memset(), something more esoteric/fancy).

memset(s->kp, 0, sizeof(unsigned)*STKMAX);

As noted by chux you better use memset(s->kp, 0, sizeof s->kp[0] *STKMAX) "as it reduces a dependency on matching a variable with a type - which may evolve".

In stack_push() you should again declare one variable each time, no need to save few keystrokes and it makes declaration easier to read. Also here you should use more meaningful names, ideally I would like to read the variable name and go to the next line, there should be no need to read and understand the expression to determine what it is going on. I'm stressing on this but it's a very important concept when after 1 year you go back to  your 500k/1M LOC codebase to fix a bug.

It's not a big compile-time protection but you have an enum, give it a name and use it for the parameter v (which may be value). Callers are still able to push 41 instead of TRUE and FALSE but you're documenting your function interface (and see next paragraph).

You may want to validate inputs.

Do not print error messages to stdout. For two reasons: first because stdout is for program output and errors should go to stderr, second because it's not your code responsibility to inform the user, you're just handling a stack of booleans and an appropriate return code is enough.

/* set bit at index */

If you feel you need a comment for this then you're missing the opportunity to introduce a separate self-explicative setBitAtIndex() method.

Do you really need to return the index of the next available bit? It's never a parameter for your functions then caller is probably not interested in it (and it's available in selstack). You may want to use return value as error code (eventually, from C11, consider to use errno_t).

Above applies to stack_pop() and stack_last() as well.


C++ algorithm that rearranges linked list based on pivot

Those -> are really a standard.

You could change them to the * dereference operator but the parenthesis apocalypse it requires to make it works in larger expressions will bother you more than everything.
In a small implementation like this one it's do-able though.

Or, you may want to write your stuff in an immutable fashion. Meaning you don't use pointers and just use return values and arguments to functions to pass values.
Without modifying them (as variables) so you never have to use pointers.


I still can't quite figure out the way to this algorithm =/. But, from the Java point of view, you can gain 9-10% by changing your loop to:

for (int i = 1; i <= c; i ++) {
    BigInteger temp = s.pow(2);
    s = temp.pow(2).subtract(BigInteger.valueOf(4).multiply(temp)).add(BigInteger.valueOf(2)).mod(F);
}

...because the cached value can be used twice there.

Otherwise, the code is hard to read. It's not self explanatory nor commented and could be written in a better way - for a human to read, at least. But none of those changes would affect performance in any way.

EDIT: Additional 17% thanks to @Landei in comments.

for (int i = 1; i <= c; i ++) {
    BigInteger temp = s.modPow(BigInteger.valueOf(2), F);
    s = temp.pow(2).subtract(BigInteger.valueOf(4).multiply(temp)).add(BigInteger.valueOf(2));
}
s = s.mod(F);

That takes advantage of modPow() method which can do pow().mod() in one step without much additional overhead. Since the mod is not necessary to have every time, it is enough to do it in temp (that actually propagates twice into the resulting expression) and enjoy the substantial speedup. You need to add one proper mod after the loop is done, though.


From a once over:

You are a bit overdoing the blank lines in your definition of A
I like the namespace idea, given how you implement getObj and setObj, it would be nice if the caller could set the namespace.
setType -> I get that remember probably means you want to remember info across sessions, hence you choose localStorage and not sessionStorage, still something like persist or persistAcrossSessions could be more informative.
setObj -> does totally not what I would expect it to do, I would expect your code to JSON.stringify() and assign that to a key, however you store each property individually which can make for a very messy retrieval
getObj -> does exactly what I thought i would, give all properties in 1 object, this is very limited functionality. You should consider really consider JSON in your class.
clear -> I would make var key part of the for loop : for (var key in this.A.storage) {
Commenting is uneven, the 2 functions which are most surprising to me have no comments.


Two things:

First, you notice that if I entered "1" as an input, I will get "2," instead of "2".

Second, you check the divisibility of a number n against all numbers from 2 to sqrt(n). This is good, but you can improve it by keeping track of all prime numbers you produce. Whenever you find that p is a prime number, you add it to a list of prime numbers, call it primeList. Now whenever you want to check if n is prime, you can test n against all primes in primeList whose sqrt is less than or equal to n. This way to save on the number of primes to test.

There is a lot of advance theory on finding a prime, but for simple one this is sufficient.


Best way to identify a computer in LAN C#

You've got some duplication in there;

Perhaps you can create a function with a string argument that will handle response writing?

protected void CreateResponse(string response){
    Response.Clear();
    Response.ClearHeaders();
    Response.AddHeader("Content-Type", "text/plain");
    Response.Write(response);
    Response.Flush();
    Response.End();
}

To me that seems far more concerning than the way in which you retrieve the hostname.


Welcome to CodeReview. Great first question!

Stringly-typed dates

Rather than holding onto dates as strings, you should be holding onto them as actual datetime objects. So this:

# When to start monitoring
start_time = datetime.now().strftime("%H:%M:%S")
# End Time - When to end monitoring
end_time = "08:55:00"

should instead be

# When to start monitoring
start_time = datetime.now()
# End Time - When to end monitoring
# This assumes that we are running early in the morning of the same
# day as the end_time
end_time = datetime.now().replace(hour=8, minute=55)

and

p_start_time <= datetime.now().strftime("%H:%M:%S") <= p_end_time:

should be

p_start_time <= datetime.now() <= p_end_time:

Parametric paths

# Directory - Where to store activity log
directory = r"C:\Users\username\Documents"

should not be hard-coded. Instead, accept it as a command-line argument, or an environmental variable, or store it in a config file.

Path management

# File path / File name
log_path = dir_t + "\\Log.csv"

is much easier with pathlib:

from pathlib import Path
# ...
dir_t = Path(...)
log_path = dir_t / 'Log.csv'

Logging

Strongly consider using the actual logging module instead of rolling your own. This will lend you more flexibility, and access to a more feature-rich logging framework. You can do everything you're doing now - have a file handler; have a custom formatter with your own chosen fields; etc.

In-place addition

        num = num + 1

can be

        num += 1


Convert flat object keys to hierarchical one

The main complexity of this function arises from using a plain for-in loop to loop over object keys - this adds two extra indentation levels instead of just one level if one were to use a higher-level looping construct. So I would use some library function or create something like:

function eachKeyValue(obj, fun) {
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            fun(i, obj[i]);
        }
    }
}

Within this loop, there's another low-level for-loop, which I would again replace, say... with an Array.forEach method.

Now, in your code the loop goes over all the parts of the key, checking each time whether it's the last part. Instead of this, I would first remove the last part, loop over all the other parts to ensure all these are initialized, and then simply assign the value to the last position.

With some additional improvements to variable names, I would write it as such:

function convert(obj) {
    var result = {};
    eachKeyValue(obj, function(namespace, value) {
        var parts = namespace.split(".");
        var last = parts.pop();
        var node = result;
        parts.forEach(function(key) {
            node = node[key] = node[key] || {};
        });
        node[last] = value;
    });
    return result;
}

This code has just 2 levels of nesting compared to the original 4.


Is there any other short way to make calculator

Without trying to be facetious, of course there are many different ways to try and do the same thing.

I assume this is a beginner exercise; so I'll review it with that in mind, giving you some tips on what to tackle next as well.

The coding style

The variables are acceptably named, but I'd refrain from using shorthand such as op, instead favoring operation. This makes no technical difference but it enhances readability. The current program is simple enough that it's not an issue, but more complex applications will suffer more from these unclear abbreviations.
Well structured paragraphs (although I personally would have put the last line on a separate paragraph, but I'm nitpicking).
You should really separate some of this logic into separate methods(/classes), but I do concede that the current code is short enough that's it's not a big issue right now.

The code itself

On a technical level, everything is as it should be.
You have not accounted for nonsensical input. Ask yourself what happens if the user enters "batman" as a number value.
Similarly, you have not accounted for non-existing operators. If I enter "batman" as the operator; your application will tell me that the result is 0.

As a user, I'm unable to differentiate whether this is correct (e.g. if I entered 5 - 5) or incorrect (if I use an unknown operator). That's not good. Suppose I get 0. That would make me paranoid and require me to backtrack what I gave as input to confirm whether this is a real answer or not.
Instead, your application should clearly tell the user that they used an unknown operator, e.g. Error - "batman" is not a known mathematical operation!

You've avoided the int division problem.
You've abstracted your result into a result variable instead of creating a different Console.WriteLine() for every operation. That is a good application of reusability.
You have not avoided division by zero. This is a fairly important fringe case to account for in a calculator application.

Improvements and future challenges

Implement a failsafe to prevent division by zero.
Implement clear user feedback in case the user enters nonsensical data.
The current application performs a single calculation and then exits. What if the user wants to calculate a few different things? A better approach would be to loop the application code until the user enters "exit", at which point the application closes.
Although the current code is simple enough that it's not necessary yet, I would suggest you abstract the number entry into a method, so your code looks like this: float num1 = AskForNumber(); float num2 = AskForNumber(); (feel free to use a different method name).
String comparison is not as type safe as enum comparison. It would be a good exercise to create an enum Operation { Add, Subtract, Multiply, Divide } and then use that in your switch case instead of directly checking string values. Note: The current code is simple enough that the enum adds more code than it's currently worth, but it is a good exercise and preparation for the future.
Since you're learning C#, I would suggest you try an OOP approach, e.g. a Calculator class which implements the calculations, so that your Program class doesn't contain any of the math logic. Again, the current example is simple enough that it's not quite necessary, but it's a good exercise. If you only start using OOP when the code is already complicated; that's not going to help you understand the core principles.
Currently, the user is asked for a number, another number, and then an operation. This is not intuitive from the perspective of a user. Notice how every real world calculator asks for the operation before it asks for the second number.

It would also be nice if the user could enter the entire calculation in a single go (1 + 2), and your code extract the needed num1, num2 and operation values.
Try allowing for multiple operations in a single statement (1 + 2 - 3).
Don't forget to apply the correct order of operations! (e.g. 1 + 2 * 3 is equal to 7, not 9).
Add functionality for () parentheses to influence the order of operations.
More operators: ^ for powers (e.g. 2 ^ 3 = 2³ = 8)

Small remark

  Is there any other short way

Shortness is not a measure of good code. If anything, excessively short code is often bad due to inlining several operations and generally lowering code readability.

I know that you meant "simple", i.e. you didn't want a counterexample that is massively more complicated than your exercise.

But I just want to call your attention to the distinction between short code and simple code. These are not freely interchangeable; and more often end up being opposites of each other.


If non-array property exists convert it to one and push new value

Basically after reading over the code, I interpret that the conditional (i.e. !obj[key].push) checks if the value at the given key is not an array. A more robust way to do that is to use (the negated value of) Array.isArray() instead. That may not be any shorter, but perhaps a better way to determine if the property at key is an array.

var obj={a:1,b:[1,2]}

function add(key,value){
  if(!Array.isArray(obj[key])){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
add('a',3);
console.log(obj);

It would be difficult to prevent the re-assignment of the property .push (see example below). .push could be assigned to something other than a function, like an integer, string or object, or a function that does something other than push the supplied argument on the array.

var obj={a:1,b:[1,2]}

function add(key,value){
  if(!obj[key].push){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
obj.b.push = undefined;
add('b',3);
console.log(obj);

Edit
insertusernamehere made a good point in a comment: Perhaps it would be wise to guard against the case where the obj[key] is undefined. The current code would add that to the array, which is likely not preferable.
There are multiple ways to achieve this, including calling obj.hasOwnProperty(), checking the array returned by Object.keys(obj) does include key, etc.

var obj={a:1,b:[1,2]}

function add(key,value){
  if (!Object.hasOwnProperty(key)) {
      obj[key]=[];
  }
  if(!Array.isArray(obj[key])){
    obj[key]=[obj[key]]
  }
  obj[key].push(value)
}
add('a',3);
add('c',4);
console.log(obj);


I love seeing functionality like this packed so concisely. Really nice job.

UX

When I ran your code, it ran fine, but a usability problem is that the text entry box does not have focus, you have to click on it to make it have the active focus/cursor. You should add this to your script:

typing_ground.focus_set()

I ran it with python and python3, both worked fine.

Another thing that came up is that it occasionally happens that the next word is the same as the previous word. You should add a re-selection of a new word until it is different, otherwise the experience is "odd" (the word stays the same but your entry widget clears... and when you're typing you are not really looking at the entry box, just the target word.... and since it does not change, you think you've made a mistake.

Variables

Your code uses text entry and display components as variables. This code makes me cringe:

points['text'] = "Score: " + str(int(points['text'].split(': ')[-1]) + 1)

Instead of having a score variable, you store the score in the partial text value of the score displaying widget. Really? You do the same thing with the text to copy. Currently your code is:

def if_equal_delete_and_take_other_phrase(ev):
    if text_to_copy.cget("text") == typing_ground.get():
        typing_ground.delete(0, 'end')
        text_to_copy['text'] = new_word()
        points['text'] = "Score: " + str(int(points['text'].split(': ')[-1]) + 1)

Would it really be so hard to do:

target = "start"
score = 0
def if_equal_delete_and_take_other_phrase(ev):
    global target
    global score
    if target == typing_ground.get():
        score = score + 1
        target = new_word()
        typing_ground.delete(0, 'end')
        text_to_copy['text'] = target
        points['text'] = "Score: " + str(score)

Lambda

The lambda here is simply gratuitous:

new_word = lambda: random.choice(random.choice((WORDS[0:len(WORDS)//10], WORDS)))

It is never used in an anonymous way, and really there's no use for this format at all. It makes the reader expect something "funny", and there's confusion when the only funny thing is the declaration above.

Talk about confusing.... why is the first 10% of the WORDS list more important than the next 10%? The first 10% of the words appear with significantly more frequency because you not only choose the random word from the array, but you choose to use either the first 10% only, or the whole thing. In other words, half of the choices only ever come from the first 10% of the words.

I cannot think of any reason for that, and it makes the code complicated, and it is a head scratcher, and as a consequence, the code maintainer (me) would be cursing your name and hexing your bytestrings. For all things sweet and dainty, at least leave a comment, please. As for me, I'll just rewrite that crap as:

def new_word():
    return random.choice(WORDS)

Hmmm.... let me add in the non-repeating word function too:

def new_word():
    while True:
        nword = random.choice(WORDS)
        if nword != target:
            return nword

Conclusion

I added a #!/usr/bin/python3 line too. It's nice to not have to type these things in linux at least.

The code I ended up with is:

#!/usr/bin/python3
try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk
import random

FONT = (None, 50)
WORDS = ['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have',
         'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you',
         'do', 'at', 'this', 'but', 'his', 'by', 'from', 'they',
         'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one',
         'all', 'would', 'there', 'their', 'what', 'so', 'up', 'out',
         'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when',
         'make', 'can', 'like', 'time', 'no', 'just', 'him', 'know',
         'take', 'people', 'into', 'year', 'your', 'good', 'some',
         'could', 'them', 'see', 'other', 'than', 'then', 'now',
         'look', 'only', 'come', 'its', 'over', 'think', 'also',
         'back', 'after', 'use', 'two', 'how', 'our', 'work',
         'first', 'well', 'way', 'even', 'new', 'want', 'because',
         'any', 'these', 'give', 'day', 'most', 'us']

target = "start"
score = 0

root = tk.Tk()
root.title("Typing trainer")

text_to_copy = tk.Label(root, text = target, font=FONT)
text_to_copy.pack()

typing_ground = tk.Entry(root, font=FONT)
typing_ground.pack()

points = tk.Label(root, text = "Score: " + str(score), font=FONT)
points.pack()

def new_word():
    while True:
        nword = random.choice(WORDS)
        if nword != target:
            return nword

def if_equal_delete_and_take_other_phrase(ev):
    global target
    global score
    if target == typing_ground.get():
        score = score + 1
        target = new_word()
        typing_ground.delete(0, 'end')
        text_to_copy['text'] = target
        points['text'] = "Score: " + str(score)

root.bind('<Key>', if_equal_delete_and_take_other_phrase)

typing_ground.focus_set()

root.mainloop()


Good job overall. You're developing good habits: you're testing your code, you've used the type annotations, you're using f-strings.
If I were to be nit-picky, here's what I'd still suggest:

some of your lines are too long and I have to horizontally scroll to see everything. try to shorten them as specified in PEP8
add a docstrings to your function
function names are usually describing an action so you should be calling yours something like: def count_teams() - I'm really bad at naming things but you got my point

The final code would look like this:
from typing import Tuple

def count_teams(players: int, teams: int) -> Tuple[int, int]:
    """
    Calculate the number of teams with 1 or 2 players
    in call of Duty WarZone (Duos mode)
    """

    if players <= 0 or teams <= 0:
        raise ValueError(f"{players=}, {teams=} - Players and "
                         f"teams must be a positive value")

    if teams > players or teams < players / 2:
        raise ValueError(f"{players=}, {teams=} - Teams must be "
                         f"less than players and greater than or"
                         f" equal to half of players")

    twos = players - teams
    ones = teams - twos

    return ones, twos

As far as your tests go, the only thing you could improve is to parametrize the tests that are the same but use different values. You have on the pytest's official docs some examples.
And another small nit-pick would be to first import the 3rd party libraries and then the local ones, with a blank line between each group:
import pytest

from teams_of_two import team_counts

# tests ...

LE: edited the chain comparison advice which wasn’t applicable in this case.


Constructing a query string using StringBuilder

Although there's nothing wrong with your code, it is generally easier to fall back on framework classes for this kind of thing. Namely UriBuilder and HttpValueCollection.

public static Uri BuildUri(string root, NameValueCollection query)
{
    // omitted argument checking

    // sneaky way to get a HttpValueCollection (which is internal)
    var collection = HttpUtility.ParseQueryString(string.Empty);

    foreach (var key in query.Cast<string>().Where(key => !string.IsNullOrEmpty(query[key])))
    {
       collection[key] = query[key];
    }

    var builder = new UriBuilder(root) { Query = collection.ToString() };
    return builder.Uri;
}

Then you can simply use with a name value collection:

var values = new NameValueCollection
{
    {"i", "item" },
    { "f", "found" },
    { "wt", "what%" },
    { "wr", "where" }
};
BuildUri("http://example.com/search.aspx", values);
// http://example.com/search.aspx?i=item&f=found&wt=what%25&wr=where

The HttpValueCollection handles all of the encoding for you so you don't need to worry about doing it the right way. You just create the name value collection and any null/empty values will just be skipped in the BuildUri method.

Update

As svick has pointed out in the comments it might not be ideal to use an internal class in this way. I think the risk of the implementation changing is quite low but it is a risk and should be thought about.


Run a command for all files in a directory

Looping over glob.glob to build files is unneeded.
You shouldn't need to chdir if you change the glob to xml/*.xml
filearchiver_cmdline can be changed to use str.join and a comprehension.

Note: untested

import glob
import os

dir_name = "../pack"

if not os.path.exists(dir_name):
    os.mkdir(dir_name)

os.system(" ".join(
    ["archiver.exe"]
    + ["xml\\" + f for f in glob.glob("xml/*.xml")]
))


Console Commands with dependency injection (C#)

If you're not using C# 8's nullable references, you should be checking for null whenever you're supplied with input.

In the ConsoleCommandHandler constructor, throw ArgumentNullException if logger or commands is null.
In ConsoleCommandHandler.TryHandleCommandAsync, throw ArgumentNullException if input is null. Even though you're only ever passing non-empty strings from your entry point, this method is publicly visible which sends a signal that anybody could potentially use it differently in the future.

In ConsoleCommandHandler, you create a Dictionary that maps command names to ICommands. You would do this if you wanted constant-time lookup of commands from command names. But then you wrote commands.Any(command => command.Key == header) which will instead do a linear search over every key-value pair in the dictionary until it finds a matching key. This defeats the purpose of using a dictionary. Use TryGetValue to check-and-retrieve a value from a dictionary in one shot:

    if (commands.TryGetValue(header, out var command)
    {
        await command.RunAsync(input.Substring(spacePosition + 1).Split(' '));
    }
    else
    {
        logger.LogWarning("'{0}' is not recognized as an internal command", header);
    }

TryHandleCommandAsync really does two things -- it parses user input into a command + arguments, and then it finds/runs the associated command. It may be worth separating those concerns into methods. Then, if the format of those command strings ever changes then you'll know exactly where and what to change in the code.

Depending on how sophisticated your command line interface needs to be, consider a third-party library that does all the gross string parsing stuff for you. For example, do you need to support commands or arguments that contain spaces? Your implementation currently doesn't.


Repetitive code for a projected field in a lambda

You can extract out that repeat call to a variable inside your Select.

var result = employments.Select(x =>
{
    var empRelationship = x.EmpRelationship.OrderByDescending(y => y.EndTime).FirstOrDefault();

    return new EmpListItem
    {
        EndDate = empRelationship.CancelledBeforeTime ?
                      empRelationship.CancelEndTime :
                      empRelationship.EndTime,
        JobType = x.JobType
    };
});

This will also speed up execution.

The trick behind this is remembering you can execute more than just one statement inside a lambda by using { and }


When the performance of your program in the face of large inputs is not even in the right ballpark, it's time to look for a new algorithm, even if your code is correct.  Factoring numbers is considered a "hard" problem — most public-key cryptography relies on the fact that factoring numbers takes a long time.

The Sieve of Eratosthenes would be perfect for this problem.  It should be possible in about 10 lines of code, and run in about one second.

Implementation hint:

# Build a big list
prime_list = range(limit + 1)

# Strike non-prime numbers 0 and 1 from the list
prime_list[0] = prime_list[1] = None

# TODO: Strike all multiples of prime numbers from the list
for k in xrange(len(prime_list)):
    ...

# Sum the numbers that have not been stricken out
return sum(filter(None, prime_list))

Alternatively, strike out numbers by setting them to 0 instead of None.  That removes the need to call filter(), but I think the clarity would suffer a tiny bit.


Performing batch insertion for a single row

Short answer to your question: No it's the same performance wise.

Full review:

My first concern with your code is the double for loop that uses the same looping variable i. This makes it harder to understand when you see an i inside the inner for loop.

My other major concern is that the only difference between the code before the inner for loop and the code inside the inner loop is setting the variable max which I had no idea what it should be at first sight. Let's start by renaming that to transactionNumber. And since this is independent of the loop itself let's initialise that from the manager right above the loops instead:

int transactionNumber = manager.getTransNo();
for (int i = 0; i < 1; i++) {
    String itemName = (String) jTable.getValueAt(i, 0);
    int itemQty = (int) jTable.getValueAt(i, 1);
    Double itemPrice = (Double) jTable.getValueAt(i, 2);
    Items items = new Items();
    items.setName(itemName);
    items.setPrice(itemPrice);
    items.setQty(itemQty);
    items.setTransactionNumber(transactionNumber);
    manager.saveItems(items);

    for (i = 1; i < rows; i++) {
        String itemsName = (String) jTable.getValueAt(i, 0);
        int itemsQty = (int) jTable.getValueAt(i, 1);
        Double itemsPrice = (Double) jTable.getValueAt(i, 2);

        items.setName(itemsName);
        items.setPrice(itemsPrice);
        items.setQty(itemsQty);
        items.setTransactionNumber(transactionNumber);
        manager.saveItems(items);
    }
}

Now with a closer look there's a second difference. You only instantiate items once and overwrite that with the setters. I don't think this is a good idea. You should probably create a new items object each time with it's own name, price, quantity and save that independent of any previous values. This means we can just combine the 2 for loops into 1 like so:

int transactionNumber = manager.getTransNo();
for (int i = 0; i < rows; i++) {
    String itemName = (String) jTable.getValueAt(i, 0);
    int itemQty = (int) jTable.getValueAt(i, 1);
    Double itemPrice = (Double) jTable.getValueAt(i, 2);
    Items items = new Items();
    items.setName(itemName);
    items.setPrice(itemPrice);
    items.setQty(itemQty);
    items.setTransactionNumber(transactionNumber);
    manager.saveItems(items);
}

If you now take a close look at what would happen if you only had 1 row you can see that the code inside the loop gets executed exactly 1 time with the i replaced by a 0. This is exactly the same code you have inside your if(rows == 1) block so you can remove that check and only keep the for loop.

Depending on how the Items are used in the rest of your code I also strongly suggest to remove the setters and pass any needed parameters with the constructor instead. This results in the following implementation of the entire method:

private void jButton1ActionPerformed (java.awt.event.ActionEvent evt){
    int transactionNumber = manager.getTransNo();
    for (int i = 0; i < rows; i++) {
        String itemName = (String) jTable.getValueAt(i, 0);
        int itemQty = (int) jTable.getValueAt(i, 1);
        Double itemPrice = (Double) jTable.getValueAt(i, 2);
        Items items = new Items(transactionNumber, itemName, itemPrice, itemQty);
        manager.saveItems(items);
    }
}

The only improvement you should consider is to rename jTable to something more meaningful.


Converting std::string to int without Boost

There's a few things that jump out at me both in your implementation and standard options you missed. A few (scattered) thoughts follow.

Returning a default if you care about error checking doesn't make sense. How would you determine if conversion failed if there's not an integer available for use as a sentinel? You are basically doing the same thing atoi does except your default is flexible instead of 0.

Have you considered [strtol][1]? It's basically atoi with error checking capabilities. It's the fastest string to int converter you're likely going to get:

long string_to_long(const std::string& str, long default_value, int base = 10) {
    char* parse_end = NULL; //nullptr if C++11, though really you don't have to initialize this
                            //since strol is guaranteed to initialize it. I just like to avoid
                            //unitialized variables.
    long val = strtol(str.c_str(), &parse_end, base);
    if (parse_end == str.c_str() + str.size()) {
        return val;
    } else {
        return default_value;
    }
}

Note: strtol ignores leading whitespace. The function I've written above errors for trailing whitespace (or trailing anything). In other words, " 3" is fine, but "3 " would error.

The idiomatic way to do this in C++ would be to use a string stream:

int string_to_int(const std::string& str, int def)
{
    std::istringstream ss(str);
    int i;
    if (!(ss >> std::noskipws >> i)) {
        //Extracting an int failed
        return def;
    }
    char c;
    if (ss >> c) {
        //There was something after the int
        return def;
    }
    return i;
}

In terms of performance, strtol will likely be faster than this. This does have a useful advantage though that it can be made highly generic with simple templating (this is the essential idea behind boost::lexical_cast actually, but this doesn't use exceptions):

template<typename ResultType>
ResultType lexical_cast(const std::string& str, const ResultType& default_value = ResultType()) {
    std::istringstream ss(str);
    ResultType result;
    if (!(ss >> std::noskipws >> result)) {
        return default_value;
    }
    char c;
    if (ss >> c) {
        return default_value;
    }
    return result;
}

If you don't want to use exceptions, but you want to be able to detect errors, you're going to have to use a flag. You basically have two options of how to handle that. You can use a boolean flag and return the value, or you can use a boolean reference parameter and return the value. Which route you take really depends on how you want to use the code, but I would probably return the value. That lets you ignore errors if you want to, but it still doesn't force you to. I might do something like this:

template<typename ResultType>
ResultType lexical_cast(const std::string& str, bool& success) {
    std::istringstream ss(str);
    ResultType result;
    success = true;
    if (!(ss >> std::noskipws >> result)) {
        success = false;
    }
    char c;
    if (ss >> c) {
        success = false;
    }
    return result;
}

template<typename ResultType>
ResultType lexical_cast(const std::string& str) {
    bool ignore;
    return lexical_cast<ResultType>(str, ignore);
}

This gives you both options of detecting an error or ignoring one. You could even build more on top of this to have one that returns a default value:

template<typename ResultType>
ResultType lexical_cast(const std::string& str, const ResultType& default_value = ResultType()) {
    bool success;
    ResultType val(lexical_cast<ResultType>(str, ignore));
    if (success) {
        return val;
    } else {
        return default_value;
    }
}

Don't check for classes of characters manually. Just use the cctype header's functions (isspace, isdigit, etc).

You loop is way over complicated:

bool all_digit = true;
for (std::string::size_type i = 0, l = str.size(); i < l; ++i) {
    if (!std::isdigit(str[i])) {
       all_digit = false;
        break;
    }
}

if (all_digit) { ... }

Or, allowing leading/trailing whitespace:

std::string::size_t i = 0;
const std::string::size_t len = str.size();
for (; i < len && std::isspace(str[i]); ++i) { /* empty */ }
for (; i < len && std::isdigit(str[i]); ++i) { /* empty */ }
for (; i < len && std::isspace(str[i]); ++i) { /* empty */ }
const bool all_digits = (i == len);


Issue tokens concurrently with synchronization per client

The pattern looks correct. One disadvantage here is you're blocking threads waiting for the lock. You could instead use a SemaphoreSlim and its WaitAsync method for a nonblocking lock.

Even better, have a look at LazyCache. (Scott Hanselman blogged about this recently.) It basically does all of this for you - caching, asynchronous double-check locking, and guaranteeing refresh only happens once. You could replace most of what you've done here with a GetTokenAsync implementation that looks something like this:

return await _tokenCache.GetOrAddAsync(
    $"tokens-{client.ClientId}",
    () => client.BaseAddress
        .AppendPathSegment("/login")
        .WithBasicAuth(client.Username, client.Password)
        .GetJsonAsync<TokenDetails>(),
    TimeSpan.FromHours(1));

One little caveat here is you need to know ahead of time how long to cache the token, i.e. you can't use the Expires value returned from the server. But in your case it sounds like you know it's an hour, so hopefully that's a non-issue.


Remove and Add items from array in nested javascript object

For the remove function, how about using a map and filter instead:

removeItem (groupId, itemId){
    let {groups} = this.state;
    groups = groups.map((group) => {
        if(group.id === groupId){
           group.item = group.item.filter(item => item.id !== itemId);
        }
        return group;
    });
    this.setState({groups});
}


The short answer here is: don't do this. It does not make boost::condition_variable easier to use. You're actually just limiting what you can do with it. You're not even exposing the entire interface...

But if you insist on doing such a thing, your wrapper is close. You're not handling spurious wakeup in timed_wait() - that can return true even without being signaled. You should just take advantage of the fact that the various wait() overloads also take a predicate:

void wait()
{
    boost::mutex::unique_lock lock(mutex);
    cond.wait(lock, [this]{ return work_to_do; });
    work_to_do = false;
}

bool timed_wait(unsigned int timeout)
{
    boost::mutex::unique_lock lock(mutex);
    if (cond.timed_wait(lock, boost::chrono::milliseconds(timeout),
                        [this]{ return work_to_do; })
    {
        work_to_do = false;
        return true;
    }
    else
    {
        return false;
    }
}

Really adding predicates is the way to handle calling wait() after the notify was called. The wrapper is not a good solution to this in my opinion.


Advice 1

urlName = "https://en.wikipedia.org/wiki/";

I suggest you make that magic string a static constant:

private static final String WIKIPEDIA_MAIN_URL =
        "https://en.wikipedia.org/wiki/";

Advice 2

for(int i = 0; i < urlComponents.length; i++) {
    ...

According to (common) Java coding conventions there must be a single space between for and the opening brace:

for (int i ...
   ^

Advice 3

for (int i = 0; i < urlComponents.length; i++) {

may be written as

for (String urlComponent : urlComponents) {

Advice 4

for(int i = 0; i < urlComponents.length; i++) {
    urlName += urlComponents[i];
    urlName += "_";

    nameOfArticle += urlComponents[i];
    nameOfArticle += " ";
}
urlName = urlName.substring(0, urlName.length() - 1);
nameOfArticle = nameOfArticle.substring(0, nameOfArticle.length() - 1);

You are essentially repeating yourself; I would do this instead:

StringBuilder stringBuilder = new StringBuilder();
String separator = "";

for (String urlComponent : urlComponents) {
    stringBuilder.append(separator).append(urlComponent);
    separator = "_";
}

this.articleName = stringBuilder.toString();
String urlName = WIKIPEDIA_MAIN_URL + stringBuilder.toString();

Advice 5

public void getArticle() {
    try(InputStream inputStream = url.openStream(); Scanner scanner = new Scanner(inputStream)) {
        while(scanner.hasNext()) {
            article += scanner.next() + "\n";
        }
    } catch(IOException e) {
        System.out.println(e);
    }
}

Why read one "word" at a time when you can read an entire line. Also, whenever building such strings, StringBuilder will be much more efficient:

public void getArticle() {
    StringBuilder stringBuilder = new StringBuilder();

    try (Scanner scanner = new Scanner(url.openStream())) {
        while (scanner.hasNextLine()) {
            stringBuilder.append(scanner.nextLine()); // <-- note the builder
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    this.article = stringBuilder.toString();
}

Alternative implementation

Gathering all the advices, I had this in mind:

import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;

public class ArticleSupplier {

    private static final String WIKIPEDIA_MAIN_URL =
            "https://en.wikipedia.org/wiki/";

    private String articleName;
    private URL url;
    private String article;

    public ArticleSupplier(String[] urlComponents) {
        StringBuilder stringBuilder = new StringBuilder();
        String separator = "";

        for (String urlComponent : urlComponents) {
            stringBuilder.append(separator).append(urlComponent);
            separator = "_";
        }

        this.articleName = stringBuilder.toString();
        String urlName = WIKIPEDIA_MAIN_URL + stringBuilder.toString();

        try {
            this.url = new URL(urlName);
        } catch(MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

    public void getArticle() {
        StringBuilder stringBuilder = new StringBuilder();

        try (Scanner scanner = new Scanner(url.openStream())) {
            while (scanner.hasNextLine()) {
                stringBuilder.append(scanner.nextLine());
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        this.article = stringBuilder.toString();
    }

    public void saveAsHTML() {
        String filename = articleName + ".html";

        try (BufferedWriter writer =
                new BufferedWriter(new FileWriter(filename))) {
            writer.write(article);
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ArticleSupplier as = new ArticleSupplier(args);
        as.getArticle();
        as.saveAsHTML();
    }
}


In order of appearance:

list_init

While destroy is definitely a property of the list, cmp is not; it is a property of a particular searc. Only find really cares of how to compare elements. It is better to pass a comparator to find directly.
list_desroy

may and should take advantage of knowing the list size. If perchance the list is corrupted, it is possible that the (el=list_head(list)) != NULL condition is never satisfied, and the loop becomes infinite. Counting iterations gives you an ability to fail gracefully.
Insertions

Naming is questionable. list_ins_next should be list_insert_after; list_ins_off should be list_insert_at. In any case, do not abbreviate insert.
Removals

The purpose of list_drem_next is quite unclear. Why to destroy data of the next element? It is much more straightforward to destroy data of this element. In any case, you must nullify the data pointer once data are destroyed.

The name itself is also questionable. list_destroy_data sounds better.
Missing functionality

There is no way to remove the head element.


Algorithm

Looks like you are doing too much. The recurrence can be greatly simplified:

\$a_{n} = a_{n-1} + a_{n-2} + \cdot\cdot\cdot + a_{n-k+1} + a_{n-k}\$, and

\$a_{n+1} = a_{n} + a_{n-1} + \cdot\cdot\cdot + a_{n-k+1}\$, so

\$a_{n+1} = a_{n} + (a_{n-1} + \cdot\cdot\cdot + a_{n-k+1}) = a_{n} + (a_{n} - a_{n-k})\$

meaning that the next k-bonacchi number is just

  sequence[n+1] = 2*sequence[n] + sequence[n-k]

Naming

Honestly, names like sqnceItratr and crrntVlue are more than unreadable. Don't abbreviate so aggressively. In this particular case I'd say that n fits much better than sqnceItratr.
Separation of concerns

calculateSequence initialize the sequence and produces the rest of it in a single call. It doesn't look right. I recommend to split the solution in initialize, and compute_next calls, along the lines of

sequence = initialize(N)
for n in range(N, limit):
    value = compute_next(sequence, N)
    sequence.append(value)


Codility: MaxZeroProduct challenge and solution

You must consider domain boundaries: A can contain integers in the range [1..1,000,000,000] so the largest possible product would be 1,000,000,000^3 which is way beyond int.MaxValue (and even ulong.MaxValue). One way to overcome this problem while keeping you algorithm as is, is to use System.Numerics.BigInteger instead of int.

This conditional expression while (!(n <= 0 || n % 10 != 0)) has its equivalent in while (n > 0 && n % 10 == 0) which I find more straight forward readable.

These nested loops can be optimized a little bit:

    for (var i = 0; i < A.Length; i++) {
        for (var j = i + 1; j < A.Length; j++) {
            for (var k = j + 1; k < A.Length; k++) {

    for (var i = 0; i < A.Length - 2; i++) {
        for (var j = i + 1; j < A.Length - 1; j++) {
            for (var k = j + 1; k < A.Length; k++) {


Rewriting domain only if not on local dev enviroment and forcing www with Mod Rewrite

Yes! That is indeed correct. From the docs for RewriteCond:

  'ornext|OR' (or next condition)

  Use this to combine rule conditions with a local OR instead of the
  implicit AND.

The [AND] flag is the default behaviour of combining multiple conditions expressions together.

As for the rule itself, I'd suggest using %{REQUEST_URI} instead of $1 in rewrites:

RewriteCond %{HTTP_HOST} !\.local$
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


Very little code prompts a very small review. Here are a few things that came to my mind:

Includes

One issue is definitely that you are missing #include <utility> for std::pair, as well as #include <cstddef> (or similar) for std::size_t.

Another thing that might turn out to make some people angry at you is the fact that you #include <iostream>. The reason for this is that this header injects some static initializers into the current compilation unit which initialize the special streams it provides, which in turn leads to binary bloat and a possible performance reduction (take a look at the assembly that your header generates).

On almost all occasions, #include <iostream> can be avoided by including one of several other headers, in you case #include <ios>, which provides std::ios_base.

Ugh, std::type_info

Usually, seeing std::type_info around is setting off some alarm bells for me. The cause for this is not that there is anything inherently wrong with std::type_info, but that most things it could be used for are better expressed through polymorphism or compile time template switching.

From the single file you provide, I cannot possibly tell whether that is the case with your code or not. However, passing a pointer to some std::type_info around together with an int does hint at somewhat dubious practices. Please reevaluate whether the use of std::type_info is really appropriate.

Comments

// Enum representing the Length, specifier and type information provided by the format string

seems borderline unnecessary to me. What the enums represent is already made sufficiently clear by their name, only the information bit linking them to the whole format string functionality is not given in the code (however, since the header is named FormatInfo.h, I would say this information is implied).

// printf doc http://www.cplusplus.com/reference/cstdio/printf/
// Use the same values as in printf documentation so it is easy to lookup
// Use the same values as in printf documentation so it is easy to lookup
// The type we are expecting
// If width and/or precision are specified by parameter

That first comment is bad, because linking to external resources is subject to link rotting. Only do so when the information that is provided there is not easily available anywhere else. In the case of printf parameters this is not the case; most POSIX-compliant systems even have a manpage explaining them thoroughly. Furthermore, the use of printf is so ubiquitous that I'd say it is acceptable to assume users are able to find documentation on their own.

The next two comments are exactly the same and should be coerced into a single commit above the two applying enums.

Both of the last comments do not at a whole lot of valuable information to the code, so I'd say you should omit them.

Structure

FormatInfo seems to contain three separate "blocks" of information/settings. Since these blocks each mark a certain category of information, I would have made nested structs for them. My suggestion would look something akin to this:

struct FormatInfo {
    struct Flags {
        bool leftJustify;
        bool forceSignWidth;
        bool prefixType;
        bool leftPad;
    };

    struct Dimension {
        std::size_t width;
        std::size_t precision;
        Length length;
        Specifier specifier;
    };

    struct FormatSettings {
        Type type;
        Dynamic useDynamicSize;
        AllowedType expectedType;
        std::ios_base::fmtflags format;
    };

    Flags flags;
    Dimension dimension;
    FormatSettings formatSettings;
};

which encapsulates the different setting groups better.

Depending on your use case, there is also a point in making the four enums from the top of your file part of FormatInfo if this makes sense from a structural point of view (again, I don't have an overview of your whole project structure).

Apart from the mentioned points, some points of my answer to Part 1 also apply here, for example the point about indentation.


Filtering a data structure using regex predicates

First up, notice that you're creating 3 leted names by using exactly the same expression but replacing one key lookup function. This is a prime candidate for deduplication by making a local function.

(defn my-filter [str-input]
  (let [seek (fn [k](filter #(re-find (->> (str str-input)
                                         (upper-case)
                                         (re-pattern))
                                    (upper-case (k %)))
                     @data))
         firstname (seek :first-name)
        lastname (seek :last-name)
        age (seek :age)]
    (if-not (empty? firstname)
      firstname
      (if-not (empty? lastname)
        lastname
        (if-not (empty? age)
          age)))))

Next we can notice that the remainder is just doing the same "return this if it's not empty" logic with each of the three keys in sequence. some returns the first non-falsy result of a function on a sequence so by adding a seq to the seek function we can turn empty filter sequences into nils we can combine the two and get the logic we want. I used letfn this time because we're only leting fns, might as well.

(defn my-filter [str-input]
  (letfn[(seek [k]
               (seq (filter #(re-find (->> (str str-input)
                                         (upper-case)
                                         (re-pattern))
                                    (upper-case (k %)))
                     @data)))]
    (some seek [:first-name :last-name :age])))


Bug? In each of your 4 inner for loops, your code is referencing the following:

newClientTripTypeContract.ClientTripTypeContractChargeValueLists[i]

Shouldn't it be this, instead?

newClientTripTypeContracts[i]

EDIT: I missed the OP's restriction in the question that indicated that property names couldn't be changed.  I've added another section at the bottom to attempt to modify my original answer to accomodate this restriction.

Making some assumptions about your data structures, I'd try consolidating the code with the following approach:

Since it seems like your ChargeBITValues, ChargeDECIMALValues, ChargeENUMValues, and ChargeTierMONEYValues lists contain similar-but-different objects, I would first ensure that they are related by deriving from a common base class.  I would define the heirarchy as follows:

abstract class ChargeValue
{
    public abstract int ChargeValueFKID { get; set; }
}

class ChargeBITValue : ChargeValue
{
    // TODO: implement the ChargetValueFKID property
}

class ChargeDECIMALValue : ChargeValue
{
    // TODO: implement the ChargetValueFKID property
}

class ChargeENUMValue : ChargeValue
{
    // TODO: implement the ChargetValueFKID property
}

class ChargeTierMONEYValue : ChargeValue
{
    // TODO: implement the ChargetValueFKID property
}

Notice that the base class has an abstract ChargeValueFKID property.  This property can be overridden in each derived class, and is intended to replace or work with the ChargeBITValueFKID, ChargeDECIMALValueFKID, ChargeENUMValueFKID, and ChargeTierMONEYFKID properties that are in your original code.

Next, I would create an "ApplyCharges" method to perform the same task as in each of your 4 inner for loops.  You could define it as something like the following. Alternatively, you could make this a public instance method of the ClientTripTypeContract class:

static bool ApplyCharges(ClientTripTypeContract contract, IList<ChargeValue> charges, int fkid)
{
    if (charges == null || charges.Count == 0)
        return false;

    foreach (var charge in charges)
    {
        charge.ChargeValueFKID = fkid;
    }

    return true;
}

Finally, I'd update your original code to the following:

    var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0).ToList();

    int counter = -1;
    foreach(var contract in newClientTripTypeContracts)
    {
        contract.ClientTripTypeContractChargeValueListID = counter;

        bool chargesApplied = false;

        if (!chargesApplied)
            chargesApplied = ApplyCharges(contract, contract.ChargeBITValues, counter);
        if (!chargesApplied)
            chargesApplied = ApplyCharges(contract, contract.ChargeDECIMALValues, counter);
        if (!chargesApplied)
            chargesApplied = ApplyCharges(contract, contract.ChargeENUMValues, counter);
        if (!chargesApplied)
            chargesApplied = ApplyCharges(contract, contract.ChargeTierMONEYValues, counter);

        counter -= 1;
    }

Hopefully this will at least get you started and maybe give you a few ideas.  You could probably come up with a cleaner or more specific approach that makes more sense, since you have the knowledge around what these data structures mean.

EDIT:
You could, perhaps simplify your data structures with the following changes:

Add a ChargeType property to the ChargeValue base class.  Create a ChargeType enum with the following values:  Bit, Decimal, Enum, and TierMoney.

enum ChargeType
{
    Bit,
    Decimal,
    Enum,
    TierMoney,
}

abstract class ChargeValue
{
    public abstract ChargeType ChargeType { get; }

    public abstract int ChargeValueFKID { get; set; }
}

Then, Instead of having the 4 properties ChargeBITValues, ChargeDECIMALValues, ChargeENUMValues, and ChargeTierMONEYValues, you could simply have 1 property called ChargeValues, which contains all of the charge values from all of those properties.  You could even keep those 4 original properties, but I would make them read-only and have them return an IEnumerable<ChargeValue> object; adding/removing charge values should be done to the ChargeValues property.  An example is shown below:

class ClientTripTypeContract
{
    // ChargeValues replaces the original ChargeBITValues, ChargeDECIMALValues, ChargeENUMValues, and ChargeTierMONEYValues properties
    public IList<ChargeValue> ChargeValues { get; private set; }

    public IEnumerable<ChargeBITValue> ChargeBITValues
    {
        get { return this.ChargeValues.Where(charge => charge.ChargeType == ChargeType.Bit).Cast<ChargeBITValue>(); }
    }

    public IEnumerable<ChargeDECIMALValue> ChargeDECIMALValues
    {
        get { return this.ChargeValues.Where(charge => charge.ChargeType == ChargeType.Decimal).Cast<ChargeDECIMALValue>(); }
    }

    public IEnumerable<ChargeENUMValue> ChargeENUMValues
    {
        get { return this.ChargeValues.Where(charge => charge.ChargeType == ChargeType.Enum).Cast<ChargeENUMValue>(); }
    }

    public IEnumerable<ChargeTierMONEYValue> ChargeTierMONEYValues
    {
        get { return this.ChargeValues.Where(charge => charge.ChargeType == ChargeType.TierMoney).Cast<ChargeTierMONEYValue>(); }
    }
}

According to the OP's question, the properties of the data structure classes can't be changed/renamed, so below is my attempt to take the suggestions mentioned above and still work with that restriction:

Below, I've removed the ChargeValue base class and replaced it with an IChargeValue interface.  You can have each Charge*Value class implement this interface.  In the example code below, I've implemented that interface explicitly so that the properties of that interface do not show up as public properties; I don't know if that matters...perhaps an OR mapper tool that you are using looks at the public properties.  Alternatively, there ought to be some mechanism that your OR mapper uses that allows you to ignore these properties.

    enum ChargeType
    {
        Bit,
        Decimal,
        Enum,
        TierMoney,
    }

    interface IChargeValue
    {
        ChargeType ChargeType { get; }

        int ChargeValueFKID { get; set; }
    }

    class ChargeBITValue : IChargeValue
    {
        int ChargeBITValueFKID { get; set; }

        ChargeType IChargeValue.ChargeType
        {
            get { return ChargeType.Bit; }
        }

        int IChargeValue.ChargeValueFKID
        {
            get { return this.ChargeBITValueFKID; }
            set { this.ChargeBITValueFKID = value; }
        }
    }

    class ChargeDECIMALValue : IChargeValue
    {
        int ChargeDECIMALValueFKID { get; set; }

        ChargeType IChargeValue.ChargeType
        {
            get { return ChargeType.Decimal; }
        }

        int IChargeValue.ChargeValueFKID
        {
            get { return this.ChargeDECIMALValueFKID; }
            set { this.ChargeDECIMALValueFKID = value; }
        }
    }

    class ChargeENUMValue : IChargeValue
    {
        int ChargeENUMValueFKID { get; set; }

        ChargeType IChargeValue.ChargeType
        {
            get { return ChargeType.Enum; }
        }

        int IChargeValue.ChargeValueFKID
        {
            get { return this.ChargeENUMValueFKID; }
            set { this.ChargeENUMValueFKID = value; }
        }
    }

    class ChargeTierMONEYValue : IChargeValue
    {
        int ChargeTierMONEYValueFKID { get; set; }

        ChargeType IChargeValue.ChargeType
        {
            get { return ChargeType.TierMoney; }
        }

        int IChargeValue.ChargeValueFKID
        {
            get { return this.ChargeTierMONEYValueFKID; }
            set { this.ChargeTierMONEYValueFKID = value; }
        }
    }

Using this approach, you could modify the "ApplyCharges" method mentioned above to the following:

    static bool ApplyCharges(IEnumerable<IChargeValue> charges, int fkid)
    {
        if (charges != null && charges.Any())
        {
            foreach (var charge in charges)
            {
                charge.ChargeValueFKID = fkid;
            }

            return true;
        }
        else
        {
            return false;
        }
    }

And you can call this method using the following:

        // NOTE: the .ToList() call on this line is not required, because the code below uses a foreach loop instead of a for loop.
        var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0).ToList();

        int counter = -1;
        foreach (var contract in newClientTripTypeContracts)
        {
            contract.ClientTripTypeContractChargeValueListID = counter;

            bool chargesApplied = false;

            if (!chargesApplied)
                chargesApplied = ApplyCharges(contract.ChargeBITValues.Cast<IChargeValue>(), counter);
            if (!chargesApplied)
                chargesApplied = ApplyCharges(contract.ChargeDECIMALValues.Cast<IChargeValue>(), counter);
            if (!chargesApplied)
                chargesApplied = ApplyCharges(contract.ChargeENUMValues.Cast<IChargeValue>(), counter);
            if (!chargesApplied)
                chargesApplied = ApplyCharges(contract.ChargeTierMONEYValues.Cast<IChargeValue>(), counter);

            counter -= 1;
        }

Although not used in the example above, you could also add a ChargeValues property to the ClientTripTypeContract class, as shown below:

    class ClientTripTypeContract
    {
        public IList<ChargeBITValue> ChargeBITValues { get; private set; }
        public IList<ChargeDECIMALValue> ChargeDECIMALValues { get; private set; }
        public IList<ChargeENUMValue> ChargeENUMValues { get; private set; }
        public IList<ChargeTierMONEYValue> ChargeTierMONEYValues { get; private set; }

        public IEnumerable<IChargeValue> ChargeValues
        {
            get { return this.ChargeBITValues.Cast<IChargeValue>().Concat(this.ChargeDECIMALValues).Concat(this.ChargeENUMValues).Concat(this.ChargeTierMONEYValues); }
        }
    }

The ChargeValues property just consolidates all of the charges contained in the other properties into a single IEnumerable<IChargeValue> object, so that you can more easily iterate over all of the charges without duplicating code.

The bottom line is that if you want to simplify your code and reduce redundancy, then you will need to somehow add some semantics to your data structures to indicate that the different types of charges are in some ways the same.  In my examples, I tried to add those semantics by either inheriting from a common base class or implementing a common interface.  If you simply cannot change the code for those classes at all, then another option that would require more work and more refactoring would be to create a layer of abstraction by defining your own wrapper classes.  These wrapper classes would encapsulate your existing classes and would expose public properties and methods to allow your application code to manipulate the underlying data.

Update: below is a more simple approach to condensing the original code.

This approach doesn't rely on any data structure changes.  This is a bare-bones approach to simplifying the original code.

First, define a ForEach extension method.  This is just a utility method, so it is not at all specific to this problem:

public static class EnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        foreach (var item in source)
        {
            action(item);
        }
    }
}

Next, update the original code to the following:

    var newClientTripTypeContracts = newClientTripTypeContract.ClientTripTypeContractChargeValueLists.Where(u => u.ClientTripTypeContractChargeValueListID == 0).ToList();

    int counter = -1;
    foreach (var contract in newClientTripTypeContracts)
    {
        contract.ClientTripTypeContractChargeValueListID = counter;

        if (contract.ChargeBITValues.Any())
            contract.ChargeBITValues.ForEach(charge => charge.ChargeBITValueFKID = counter);
        else if (contract.ChargeDECIMALValues.Any())
            contract.ChargeDECIMALValues.ForEach(charge => charge.ChargeDECIMALValueFKID = counter);
        else if (contract.ChargeENUMValues.Any())
            contract.ChargeENUMValues.ForEach(charge => charge.ChargeENUMValueFKID = counter);
        else if (contract.ChargeTierMONEYValues.Any())
            contract.ChargeTierMONEYValues.ForEach(charge => charge.ChargeTierMONEYValueFKID = counter);

        counter -= 1;
    }

I don't think this code can be condensed much/any further without modifying the data structures.


You surely can shorten it by also improving readability

For example:

if Class == "1":
    with open ("class1.csv" , "w", newline='') as file:
        writer = csv.writer(file)
        for row in ScoresList:
            writer.writerow(row)

if Class == "2":
    with open ("class2.csv" , "w", newline='') as file:
        writer = csv.writer(file)
        for row in ScoresList:
            writer.writerow(row)

if Class == "3":
    with open ("class3.csv" , "w", newline='') as file:
        writer = csv.writer(file)
        for row in ScoresList:
            writer.writerow(row) `

Becomes:

if Class in ("1", "2", "3"):
    with open ("class{}.csv".format(Class) , "w", newline='') as file:
        writer = csv.writer(file)
        for row in ScoresList:
            writer.writerow(row) `

And, as you do that twice, you can extract it into a function to further avoid duplication.

You can also extract common code out of conditional branches

        if answer==realanswer:
            print("That's the correct answer")
            correctquestions = correctquestions + 1
        else:
            print("Unlucky not the corret")

is repeated in all of the ifs so you can write it just once at the bottom.


Comparing the size of tumors over time using PANDAS

There are a few quick improvements you can make. First, always remove as many things as possible from for loops. In this case, the date formatting and the open file lines can be removed.

Dates. Format the dates in your dataframe before the first for loop with something like

df['Date'] = pd.to_datetime(df['Date']).dt.date

Notice I’m converting the datetime into a date only since I don’t think you need to know the time.

This way you can write

compare_df = df.loc[df.Date < date].copy()

and

for row in df.loc[df.Date == date].itertuples():

It's faster to use Pandas series functions rather than calculate/convert something like pd.Timestamp(date).to_pydatetime() while looping through rows. I really liked this article which explains the fastest way to do things in Python.

Saving to file. Inside of the second for loop you have

with open('final_csv.csv',"a", newline="") as f:
    writer = csv.writer(f, dialect="excel-tab")

which is opening and closing the file every time through the for loop. So for a million records, the file is being opened and closed a million times. Opening it once at the beginning by moving those two lines to the beginning of the script should save a significant amount of time. When I time it for the four rows you gave in your example, it looks like the time is cut in half just by moving the with two lines above outside of the for loops.

Also, ‘final_csv’ has no extension, so the file is being saved as type ‘file’. If you want to save as a csv, then write

with open('final_csv.csv', "a", newline="") as f:
    writer = csv.writer(f)

I removed dialect="excel-tab" from the second line above so that columns are separated by commas and appear in separate columns when opened up in Excel.

If you run your script more than once the final_csv file that you already created will be added onto, and so you might end up with duplicate entries. To avoid this, write

with open('final_csv.csv', "w", newline="") as f

where “a” has been replaced with “w”, so that a new file will be created each time your script is run.

The pairs and diffs lists that you create are never used, so remove them.
As your code is right now, when there is no prior date, the last most_similar_to and similarity are being written to the file a second time rather than ‘nan’. To fix this, remove

cell = row.cell
Date = row.Date

from the conditional statement and instead put these two lines right after the second for statement.
Then replace

pairs.append(float('nan'))
diffs.appen(float('nan'))

after the if statement with

most_similar_to = float('nan')
similarity = float('nan')

Algorithm. Your use of map and lambda function is clever.

Another method to consider all together is using NumPy and calculating distances with matrix operations. Here is how I rewrote your code using NumPy (including all changes I mentioned above):

import pandas as pd
import numpy as np
import csv

df['Date'] = pd.to_datetime(df['Date']).dt.date

with open('final_csv.csv',"w", newline="") as f:
    writer = csv.writer(f)
    for row in df.itertuples():
        cell = row.cell
        Date = row.Date
        compare_df = df.loc[df.Date < row.Date].copy()
        if compare_df.empty:
            most_similar_to = float('nan')
            similarity = float('nan')
        else:
            sizes = np.array(list(compare_df['tumor_size']))
            diff = sizes - np.array(row.tumor_size).transpose()
            square = np.multiply(diff,diff)
            sums = np.sum(square, axis=1)
            distances = np.sqrt(sums).round(decimals=2)
            similarity = min(distances)
            ind = np.where(distances == similarity)[0][0]
            most_similar_to = list(compare_df['cell'])[ind]
        writer.writerow([cell, Date, most_similar_to, similarity])

For a small number of tumor sizes, I see an additional 2x increase in speed using NumPy. However, Python can only seem to easily handle a 10,000 by 10,000 square matrix. Anything much larger will drastically slow down a laptop with 8 GB RAM and core i7 processor. Below is the graph of the processing times as the size of the matrix increases.

It’s not clear to me if every cell size should be compared to all cell sizes from every previous date going back indefinitely. If you're able to limit the number of cells that each row has to be compared to (like maybe only going back a certain number of days, for example), you will save on time. If you do need to compare all cell sizes to all previous cell sizes, it may be possible to chunk the matrices and store in hdf5 files using PyTables.

Good luck!


Looks like you are trying to re-invent std::bind.

#include <functional>
#include <iostream>

void test(int x, int y, int z) {
    std::cout << "my first number is " << x << std::endl;
    std::cout << "my second number is " << y << std::endl;
    std::cout << "my favorite number is " << z << std::endl;
}

int main() {
    // Add placeholders for non bound values.
    using namespace std::placeholders;

    // Note the last argument is a place holder.
    auto f = std::bind(test, 5, 3, _1);

    // Now you can call and pass a placeholder argument.
    f(7);
}

As a side note: This is the kind of reason why underscore is reserved for the implementation to allow for little shortcuts like this without having to re-invent the language.

Rather than using recursive templates. I would have used an iterative aproach. With constexpr you can do quite a lot that is evaluated at compile time.

struct all_true
{
    template<typename... T>
    static bool constexpr isTrue(T... b)
    {
        bool result = true;
        for(auto const& a: {b...})
        {
            result = result && a;
        }
        return result;
    }
};

// Then your code looks like this:
b = all_true::isTrue(std::is_nothrow_constructible<Args, Args&&>::value...),


how to write generic extensions for standard collection types in java?

Parts this question have already been answered on StackOverflow - https://stackoverflow.com/a/13529644/139985  So I'm going to treat this as a simple request for a code review.

The method name is opaque ... addOnCompare does not clearly imply a particular action ... and there is no javadoc for the method.  This immediately makes code-review hard ... because I have to try and figure out what the code is trying to do before I can comment on whether it is doing that well.
The parameter name collection is poor.  It is a list, not a collection.
The local variable diff_near should be diffNear.
This is convoluted:

        switch(diff) {
        case 1: i++; break;
        default: break;
        }

Write it as:

        if (diff == 1) { i = 1; }

I don't know what these lines are trying to do, but they are definitely wrong:

        int near = i + diff;
        if (near < 0) { i = 0; break; }
        if (near > range) { i = range + 1; break; }
        int diff_near = comparator.compare(item, collection.get(near));

The value returned by a comparator has no meaning beyond being -ve, zero, or +ve.  So adding it to the index i is going to have an unpredictable effect. Indeed, since range never changes, this code makes the behaviour of the entire algorithm too difficult to understand.
I'm going to hazard a guess that the method is intended to insert item at the correct position in a previously sorted list.  But given the above, I have grave doubts that it will actually work for all possible (valid) comparators and all possible (sorted) input lists.
Even if this code did work, the performance for a linked list would be poor.  The List.get(int) method for a linked list is O(N), so even an optimal binary search pattern would result in O(Nlog(N)) operations to insert one element into the linked list.  A simple traversal of the list followed by an insert would be O(N).


If I were to call this function with an element created on the stack (example below), would it continue to work for the entirety of the program's lifetime?

No, it wouldn't:

i is created on the stack
pointer to i is saved in the list
i disappears and stack is reused when caller goes out of scope (now list is pointing to garbage)

Your List can be used to store:

Objects created on the heap (using malloc)
Global/static objects
Local stack objects, but only if they are removed again before they go out of scope.

For example:

List l;
List_Init(&l);
int i = 1;
int* ptr_i = (int*)malloc(sizof(int));
*ptr_i = i;
List_Add(&l, ptr_i);
// *ptr_i will remain until someone calls free(ptr_i)


Ensure that a Sinatra hash always has a valid value

I'd write this in multiple lines, so that you don't have to write out the complex conversion multiple times:

v = (params[:v] || :list).downcase.to_sym
params[:v] = if %i[icons list].include?(v) then v else :list end


Count number of registers in interval & location

Consider not expanding a dataframe inside the for loop but build a list or dictionary and then concatenate all dataframe elements outside loop.

Expanding objects within a loop causes substantial memory resources to allocate before and after blocks with lots of copying of objects to do so. Running one call on outside should substantially run faster as virtually no copying is done.

Specifically change:

output = pd.DataFrame()

To a list:

output = []

And then append to list inside loop and then pd.concat(list) outside loop.

def time_features(df, time_key, T, location_key, output_key):
    """
    Create features based on time such as: how many BDs are open in the same GRA at this moment (hour)?
    """
    from datetime import date
    assert np.issubdtype(df[time_key], np.datetime64)
    output = []

    grouped = df.groupby(location_key)
    for name, group in grouped:
        # initialize times registers open as 1, close as -1
        start_times = group.copy()
        start_times[time_key] = group[time_key]-pd.Timedelta(hours=T)
        start_times[output_key] =  1

        aux = group.copy()
        all_times = start_times.copy()
        aux[output_key] = -1
        all_times = all_times.append(aux, ignore_index=True)

        # sort by time and perform a cumulative sum to get opened registers
        # (subtract 1 since you don't want to include the current time as opened)
        all_times = all_times.sort_values(by=time_key)
        all_times[output_key] = all_times[output_key].cumsum() - 1

        # revert the index back to original order, and truncate closed times
        all_times = all_times.sort_index().iloc[:len(all_times)//2]
        # APPEND TO LIST
        output.append(all_times)

    # CONCATENATE ALL DF ELEMENTS
    final_df = pd.concat(output, ignore_index=True)

    return final_df


You fail to address the first sentence of your homework: you do not have an application class named LetterDemo.

I'm a strong believer in always specifying the access modifier.  Therefore both your Letter and CertifiedLetter classes should be decorated with public.

The name of your properties should be Pascal-cased.  Specifically they should begin with a capital letter, as in Name and Date.  I would suggest that Date is too generic a name, and that you should rename it to SentDate.  Why?  One day you may modify CertifiedLetter to record a ReceivedDateand having clearly named variables adds clarity to your code.

The Name property should only record the actual name, and ditch the preface.  You should omit forcing the user of your class to include "\nSender: ".

Likewise SentDate should omit "\nDate: " and only record the actual date.  Furthermore, the type for this property should be Date and not String.


Getting last or return a default value in a Seq[Either[A, B]]

Instead of map() - fold() - getOrElse(), you could just use two fold() calls.

val response = Response(y.lastOption
                         .fold("Not Found")(_.fold(_=>"Not Found", _=>"Found")))

Or you could turn it into a single Option with just one fold().

val response = Response(y.lastOption
                         .flatMap(_.toOption)
                         .fold("Not Found")(_ => "Found"))


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

Use the required #includes

The code uses std::vector which means that it should #include <vector>.  It was not difficult to infer, but it helps reviewers if the code is complete.  The full set of required includes appears to be this:

#include <iostream>
#include <fstream>
#include <vector>

Think of the user

The provided example input requires 21 numbers so that the computer can create a matrix containing just 16.  There is a lot of redundancy there!  It seems to me that simply having your example output be the input format would make a lot more sense and require less space, less typing and less interpretation.

Sanitize user input better

If I change the last line of the sample input to 1 9 9 it is asking the code to initialize a location that is outside the bounds of the vector and on my machine the computer segfaults and the program dies.  Some bounds checking would be prudent.

Pass a stream rather than a filename

The current design is rather inflexible in that it can only use an actual file as input.  I'd recommend making it more generic and accepting a std::istream & as a parameter rather than a file name.

Use a better data structure

The choice of a vector of vectors for a matrix is not a very good one because unlike a matrix, there is nothing to assure that all of the vectors are the same size.  I'd recommend creating your own custom object which hides the messy details of the actual storage (it might be a std::array or a single std::vector) but could do bounds checking and retrieval using the same coordinate system.  An example is shown below.

Use a friend extractor instead of a standalone function

Rather than having a separate function, it would be nicer to be able to write code something like this:

SokobanBoard board;
std::cin >> board;

Alternatively,

SokobanBoard board;
ifstream in(fileName);
in >> board;

To do this, we could write an extractor.  Here's a sketch of an example:

class SokobanBoard {
public:
    SokobanBoard(std::size_t rows, std::size_t cols);
    int at(std::size_t x, std::size_t y) const;

    friend std::ostream& operator<<(std::ostream& out, const SokobanBoard &sb);
    friend std::istream& operator>>(std::istream& in, SokobanBoard &sb);
private:
    std::size_t m_height;
    std::size_t m_width;
    std::vector<int> m_board;
};

A word about addressing individual squares

A question in the comments was whether doing the mathematics (multiplication) might be longer than the addressing of a vector of vectors.  On my 64-bit Linux machine using gcc 6.2.1 with -O3 optimization, I coded two different versions.

First, here is the test source code:

#include <vector>
#include <iostream>

class Test1 {
public:
    Test1(int rows, int cols) :
        vec(rows)
    {
        for (auto &row: vec) {
            row.reserve(cols);
        }
    }
    int fetch(int x, int y) const;
private:
    std::vector<std::vector<int>> vec;
};

class Test2 {
public:
    Test2(int rows, int cols) :
        height{rows},
        width{cols},
        vec(height * width)
    {}
    int fetch(int x, int y) const;
private:
    const size_t height;
    const size_t width;
    std::vector<int> vec;
};

int Test1::fetch(int x, int y) const { return vec[x][y]; }
int Test2::fetch(int x, int y) const { return vec[x+y*height]; }

int main() {
    std::size_t rows, cols;
    std::cin >> rows >> cols;
    Test1 test1(rows, cols);
    Test2 test2(rows, cols);
    std::size_t x, y;
    std::cin >> x >> y;
    int m = test1.fetch(x, y);
    int n = test2.fetch(x, y);
    std::cout << "m = " << m << ", and n = " << n << "\n";
}

Note that this is a poor program lacking all error checking, but the purpose was only to extract the assembly language for the two versions of fetch.  First, this version

int Test1::fetch(int x, int y) const { return vec[x][y]; }

produced this assembly code

0000000000000000 <Test1::fetch(int, int) const>:
Test1::fetch(int, int) const():
   0:   48 63 f6                movslq %esi,%rsi
   3:   48 8b 0f                mov    (%rdi),%rcx
   6:   48 63 d2                movslq %edx,%rdx
   9:   48 8d 04 76             lea    (%rsi,%rsi,2),%rax
   d:   48 8d 04 c1             lea    (%rcx,%rax,8),%rax
  11:   48 8b 00                mov    (%rax),%rax
  14:   8b 04 90                mov    (%rax,%rdx,4),%eax
  17:   c3                      retq

This version

int Test2::fetch(int x, int y) const { return vec[x+y*height]; }

produced this assembly code

0000000000000020 <Test2::fetch(int, int) const>:
Test2::fetch(int, int) const():
  20:   48 63 d2                movslq %edx,%rdx
  23:   48 8b 47 10             mov    0x10(%rdi),%rax
  27:   48 63 f6                movslq %esi,%rsi
  2a:   48 0f af 17             imul   (%rdi),%rdx
  2e:   48 01 d6                add    %rdx,%rsi
  31:   8b 04 b0                mov    (%rax,%rsi,4),%eax
  34:   c3                      retq

I was not able to detect any timing differences with the testing I did, but we can see that the difference is that there are 5 memory fetches for the vector of vectors version, versus three for the multiplying version.  If the structure happens to be in the cache (likely the case in my testing where I was using small dimensions), they are both about the same duration.  If there is a cache miss, the multiplying version will likely be faster.

I'd always encourage you to measure it on your own machine with your own data to determine which is better for your purposes.


Unit tests for a single JavaScript function

You can use array.map to create errs instead of creating an array and pushing to it.

const errs = response.data.map(entry => `options. ${entry.dataField}`)

With that out of the way, there's only two things that can happen with this code:

No errors emitted, app goes to top, processing is false.
Error emitted, app goes to top, processing is false.

Suggesting you create 2 tests, one for each branch and testing all 3 things. The function is small enough, there's no need to get too complicated.


Bug

There is a case that requires NFA instead of simple DFA to recognize string (of course it is possible to convert NFA to DFA):

eval("aaab", "a*ab");

Gives false, even though the string matches the regex. Disallowing same character after * fixes the problem too.

Style

why-is-using-namespace-std-considered-bad-practice.

Pass by const reference for read-only access. In the case of eval and availability of C++17, one could use std::string_view. I would advise taking the input range as input iterator, that would allow matching files, input from console, etc.

(int)p[i+1] == 42

I do not see why that is preferred to

p[i + 1] == '*'

more readable version makes comment obsolete.

if(j < s.length()) return false;
    else return true;

Could be rewritten as

return j == s.length();

Note that for this a bug about running over the string should be fixed, the bug is described below. >= will work too.

There are also no checks if string is already fully traversed in conditions with *. Although all implementations that I know of store null terminator at the end, this will not work on arbitrary ranges of characters.

I agree with KonradRudolph that comments do not contribute anything useful.

// is next character is wildcard

This comment is misleading. * is called Kleene star. Without looking at ASCII table one would assume there is a bug.

Runtime complexity

I believe runtime is \$\mathcal{O}(n)\$ in the worst case, where \$n\$ is length of input string. Think about it: the code does a single pass over a string, and doesn't reroll.

Theory

I would advise learning method of transforming NFA to DFA. It's great to learn parsing techniques, but there tools for that like flex, bison, etc exist, if you just want to hammer the nail into it's place.

I would assume .* means match any sequence of characters, as by logic in the question even doing | for all characters in the alphabet will make it impossible to describe just any combination of letters in the alphabet. Note that such a language is in the set of regular languages, as it is possible to construct DFA for it. May be I am wrong though, as my assumption stems from javascript regex.


There are clear guidelines for Enum Design where one of them says:

  X DO NOT use an enum for open sets (such as the operating system version, names of your friends, etc.).

and this

public enum MobiusBillingLocation { None, UK, US, SGSingapore }

looks like an open set. const values might be a better solution in this case. You won't have to convert anything and you can use any names for the values.

public static class MobiusBillingLocation
{
    public const string None = null;
    public const string GreatBritan = "UK";
    public const string UnitedStates = "US";
    public const string SomethingSingapure = "SGSingapore";
}


The problem I see there is that when a new view controller subscribes, the previous one stops receiving notifications. There reason is because delegation is a one to one relationship.

"View controllers can subscribe to its delegate" That is wrong, it should be something like: "A view controller can subscribe to its delegate"

If that is what you want, then it is OK.

On the other hand, if you want to have several view controllers listening for those events, you need a 1 to many relationship. You can use NoticationCenter, KVO, Observables (RxSwift or Combine), or create your own solution, like:

addObserver removeObserver an array to save these observers (that conform to a protocol) and when triggering the event, just use observers.forEach { $0.sendEvent... }


Seems like there's one major point of redundancy, in that you're performing the same logic on the two different pages you're scraping (requesting site, parsing results, storing in dataframe).
You could eliminate the redundancy with a function that takes in the site URL and performs the logic... something like def get_matches_data(url)...


Implementing linked list from scratch - Follow up

Specification and Unit Tests

You are lacking a clear specification for your methods. We have to guess what these methods do exactly, specially for edge cases.
You should provide unit tests when providing an API class. You would have found some bugs if you did.

Review

 @head.setter
    def head(self, node):
        if node is not None:
            self.__head = node

There is no link from the new head to the previous one. Also, what would you do if node.next is already filled?

 @head.setter
    def head(self, node):
        if node is not None:
            node.next = self.__head
            self.__head = node

@tail.setter
    def tail(self, node):
        if node is not None:
            try:
                if node.next is None:
                    self.__tail.next = node
                    self.__tail = self.__tail.next
            except AttributeError:
                self.__tail = node

Why would you expect an AttributeError here? You are only setting next. And why would you ignore a tail that has a next node? Why not include the tail chain?

''' generator for nodes '''
''' iterating, search etc. '''
def node_generator(self, target=None):
    node = self.head
    yield node
    while node.next is not None and node.next.key != target:
        node = node.next
        yield node

The spec is unclear here. You always include the head, and then continue as long as a next node's key does not match the specified target. Why not check head for the same condition?

def delete(self, target):
    for node in self.node_generator(target):
        pass
    node.next = node.next.next
    self.length -= 1

What if the node you want to delete is the tail? This edge case is not foreseen.


Advent of Code 2018 Day 4 - Pythonic Sleepy Guards

Replacing chained if with dictionary lookup

This function:

def event_type(line):
    if "begins shift" in line:
        return EventType.STARTS_SHIFT
    if "falls asleep" in line:
        return EventType.FALLS_ASLEEP
    if "wakes up" in line:
        return EventType.WAKES_UP
    raise Exception("Unknown line: " + line)

isn't bad, but chained if like this smell. It may be better represented as a dictionary, where the key is the string above, the value is the enum value, and you do a simple key lookup based on the last two words of every line. Whereas chained if is worst-case O(n), dictionary lookup is O(1). Then - no ifs needed, and you get the exception for free if key lookup fails.

Use raw strings

re.search("Guard #(\\d+)", line)

should be

re.search(r"Guard #(\d+)", line)

Settle down with the one-liners

This:

events = sorted(list(Event(datetime.strptime(line[1:17], "%Y-%m-%d %H:%M"), get_guard(line), event_type(line)) for line in read_file(4)), key=operator.attrgetter("time"))

is effectively illegible. Break this up into multiple lines - including a temporary variable for the strptime, as well as linebreaks in the list comprehension itself.

Don't use lists if you can use tuples

This:

MostSleepy = namedtuple('MostCommon', ['id', 'minute', 'amount'])

should be

MostSleepy = namedtuple('MostCommon', ('id', 'minute', 'amount'))

for various reasons - tuples are immutable, so use them for immutable data; and under certain narrow contexts (certainly not this one) they're faster.

Use a sum instead of a list constructor

This:

amount = len(list((m for m in current_guard.sleeps if m == most_common_minute)))

should be

amount = sum(1 for m in current_guard.sleeps if m == most_common_minute)

(Also, even if you kept using len, you should use a tuple constructor instead of a list constructor.)

Another footnote - don't put inner parens in expressions like list((...generator...)). Constructors can accept generator expressions directly.


Encapsulate stuff that shouldn't be public
I'd rather make the callback functions private static functions of the c++ class This helps to encapsulate the nasty void*casts:
#ifdef __cplusplus
class Foo {
public:
    Foo();
    int getValue() const;
    void setValue(int value);

    void register_callbacks();

private:
    int value_;

    static int  cb_getValue(void *arg1);
    static void cb_wrapper_setValue(int value, void *arg1);
};
#endif

Implementation:
void Foo::register_callbacks() {
    register_handler(Foo::cb_getValue, Foo::cb_setValue, static_cast<void *>(this));
}

void Foo::cb_setValue(int value, void *arg1) {
    Foo* foo_instance = static_cast<Foo*>(arg1);
    foo_instance->setValue(value);
}

int Foo::cb_getValue(void *arg1) {
    Foo* foo_instance = static_cast<Foo*>(arg1);
    return foo_instance->getValue();
}

Usage:
Foo foo_object;
foo_object.register_callbacks();
call_cpp_get_function();
call_cpp_set_function(35);


Hackerrank Submission Optimisation for Melodious Password

Keeping the way that you're doing this at the moment, you can:

Change consonants to a string. This allows for easier readability, and may give better performance than a list.
Name constants in UPPER_SNAKE_CASE.
Using itertools.pairwise, you can remove all bar one if. This is as you can categorise each letter, l in consonants. And then compare if they are the same.
You should use a function, as it can be faster
You should use a if __name__ == '__main__' guard.
You should use print ''.join(letters), rather than for j in letters: sys.stdout.write(j).
You can yield from the function instead, so that if it's not fast enough, you can group prints. Or use it in other ways.

This can lead to:

import itertools

CONSONANTS = 'bcdfghjklmnpqrstvwxz'
VOWELS = 'aeiou'

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return izip(a, b)

def generate_answers(n):
    consonants = CONSONANTS
    for answer in itertools.product(consonants + VOWELS, repeat=n):
        letter_categories = (l in consonants for l in answer)
        if all(a != b for a, b in pairwise(letter_categories)):
            yield ''.join(answer)

if __name__ == '__main__':
    for answer in generate_answers(int(raw_input().strip())):
        print(answer)

However, this is based around an inefficient usage of itertools.product.
You instead want to pass it the arguments so that it'll create them efficiently.
This is easy to do when n is even:

def generate_answers(n):
    return chain(product(CONSONANTS, VOWELS, repeat=n//2),
                 product(VOWELS, CONSONANTS, repeat=n//2))

To, do this efficiently when n is odd, is also quite easy.
You want to do roughly the same thing, but if the first item of the products is not the same as the first character of the first argument, then stop looping.
And so you can use:

import itertools

CONSONANTS = 'bcdfghjklmnpqrstvwxz'
VOWELS = 'aeiou'

def product(a, b, repeat):
    if repeat % 2 == 0:
        for ret in itertools.product(a, b, repeat=repeat//2):
            yield ret
    else:
        for ret in itertools.product(b, a, repeat=repeat//2+1):
            if ret[0] != b[0]:
                break
            yield ret[1:]

def generate_answers(n):
    return itertools.chain(product(CONSONANTS, VOWELS, repeat=n),
                           product(VOWELS, CONSONANTS, repeat=n))

if __name__ == '__main__':
    for answer in generate_answers(int(raw_input().strip())):
        print(''.join(answer))