OK, there's a couple of comments I can make WRT code style looking at what you have now. Things that really stand out, for example, are lines like this:

return "", "", fmt.Errorf(fmt.Sprintf("String '%s' cannot be read as property.", str))

The function in the fmt package is called Errorf, where the f at the end stands for format. Why, then bother with the fmt.Sprintf call, just to get a string? fmt.Errorf does the same job as fmt.Sprintf, only it returns an error:

return "", "", fmt.Errorf("string '%s' can't be read as property", str)

Golang coding standards also states that error strings should start with a lower-case character (see here)

Other, general comments - as I usually do, I'll go through your code pretty much line by line, commenting on things as I see them

var DefaultConfig = Config{"2006-01-02"}

Now this is a perfectly valid statement. However, it makes code less readable (especially if the declaration of Config sits in a different file, or contains a ton of fields. Imagine you need ~10 config values, some of them have defaults, some of them are not. To this end, I'd recommend you explicitly mention which field you're assigning, rather than relying on the order of the fields never changing:

var DefaultConfig = Config{
    dateFormat: "2006-01-02",
}

I also don't get why DefaultConfig (a variable) is exposed, even though the field it contains isn't. The default variable clearly is an internal thing, and should as such not be exported.
The same logic applies to the Config type: if it's exported, then surely there should be some fields or methods that are exported, too. Your snippet shows no such thing.

// FromFile returns the configuration to use for did
func FromFile(path string) (c Config, e error) {

I'd opt to return a pointer, here. It forces people to check for errors. Currently, you're returning a valid Config value, which can be safely used. I can call conf, _ := FromFile("/tmp/does_not_exist"), and assume everything went fine. I'm guaranteed to receive a valid value after all. Not so if I were to change the function to:

func FromFile(path string) (*Config, error) {}

If there's an error, I'll get a nil value, accessing that will result in a runtime panic, so I'm forced to defend against that, and check errors. I'll rewrite some of the code to use a pointer return value

// c = DefaultConfig <-- this is now gone
if lines, err := File2lines(path); err == nil {

Yes, again there's a comment I can make. because your if clause is true on success, the rest of your code is essentially wrapped in a big if. Golang programmers prefer to return early, especially if something goes wrong. Rewrite this to:

// don't know why this function is exposed, don't know what this func looks like, but I prefer CamelCasing (or camelCasing) the name - also recommended style
lines, err := FileToLines(path); err != nil {
    return nil, err
}
// one less level of indentation here

Now a bigger one. Your propertyOf function has a triple return value, again this is perfectly valid. However, it's clear that you're returning a key-value pair, and an error. Why not create a type kv struct{ key, value string} or something so it's clear that the first 2 strings belong together. This is safer because it doesn't allow for people being silly and ignoring one of the return values. The key means nothing without the value and vice-versa after all. The data looks better when grouped. Anyway, let's rewrite the body of your FromFile func now:

// not in a func
type kv struct {
    key, value string
}

conf := DefaultConfig
// in func FromFile
for _, ln := range lines {
    kv, err := propertyOf(ln) // we will look at propertyOf later
    if err != nil {
        return nil, err // again, return early
    }

    // valid
    switch kv.key {
    case "dateformat":
        // maybe check for empty strings and return errors here
        // you could even try parsing a known date, to see if the format is valid
        conf.dateFormat = kv.value
    case "some-other-key":
        // implement other values
    default:
        // optional, unknown config could just as well be skipped
        return nil, fmt.Errorf("unknown config %s (value %s)", kv.key, kv.value)
    }
}
return &conf, nil // all good

Now let's look at the propertyOf function. I must say, the name is confusing to say the least. I'd call it something like lineToKVPair or something. Then again, naming things isn't my speciality. However, when I see propertyOf, I'm expecting either a pointer to a field to be returned (through reflection), a boolean (whether or not an argument of type interface{} is a struct, and has a given property, or simply a bool given a value, telling me whether or not that value is a property of a given object.

// again: return pointer to ensure the error is checked
func toKVPair(ln string) (*kv, error) {
    parts := strings.Split(
        strings.Trim(ln, " \t\n"), // removes all spaces, tabs, and new-line characters from string in one call
        "=",
    )
    if len(parts) != 2 {
        return nil, fmt.Errorf("string %s could not be parsed to a key-value pair", ln)
    }
    return &kv{
        key: parts[0],
        value: parts[1],
    }, nil
}

Now putting all of this together, the code looks something like this:

type Config struct {
    dateFormat string
}

type kv struct {
    key, value string
}

var DefaultConfig = Config{
    dateFormat: "2006-02-01",
}

func FromFile(path string) (*Config, error) {
    lines, err := FileToLines(path)
    if err != nil {
        return nil, err
    }

    conf := DefaultConfig

    for _, ln := range lines {
        kv, err := propertyOf(ln)
        if err != nil {
            return nil, err
        }

        switch kv.key {
        case "dateformat":
            conf.dateFormat = kv.value
        case "some-other-key":
            // implement other values
        default:
            return nil, fmt.Errorf("unknown config %s (value %s)", kv.key, kv.value)
        }
    }
    return &conf, nil // all good
}

func toKVPair(ln string) (*kv, error) {
    parts := strings.Split(
        strings.Trim(ln, " \t\n"), // removes all spaces, tabs, and new-line characters from string in one call
        "=",
    )
    if len(parts) != 2 {
        return nil, fmt.Errorf("string %s could not be parsed to a key-value pair", ln)
    }
    return &kv{
        key: parts[0],
        value: parts[1],
    }, nil
}

This, to my eye, looks a lot tidier, and simpler. But it's still not what I'd actually do. My preferred approach is even simpler, still.

Use environment/config packages.

Golang projects are more often than not either CLI tools, or containerised binaries. In case of the latter, they usually get their config from environment variables. There's a lot of packages out there that handle this really nicely.

Now for some shameless self-promotion: I usually use this package, and it served me well. So much so that I've contributed a bit to it. To do what you're trying to do is dead-easy:

import(
    "github.com/caarlos0/env"
)

type Config struct {
    DateFormat string `env:"DATE_FORMAT" envDefault:"2006-01-02"`
}

func GetConfig() (*Config, error) {
    var c Config
    if err := env.Parse(&c); err != nil {
        return nil, err
    }
    return &c, nil
}

That's it! if you want some validation to be added, you can have a look at the custom parsers, or just add them on to the Config type:

// do validation here, and call that in the GetConfig func before you return
func (c Config) validate() error {}

When you are working on a CLI tool, there's other packages you can use that handle both flags and environment variables. The most commonly used one (in my experience) is viper. It's quite nicely documented, although I find using it can lead to quite verbose code in the end.

What you can quite easily do, however, is use the standard flags package, and use os.Setenv to populate the environment variables accordingly, and then use the code above:

import(
    "flags"
    "fmt"
    "os"
)

func main() {
    // create the flag
    flagSet := map[string]string{
        "DATE_FORMAT": "2006-01-02",
    }
    flags.StringVar(&flagSet["DATE_FORMAT"], "date-format", flagSet["DATE_FORMAT"], "set different date format string")
    // parse the flags:
    if err := flags.Parse(); err != nil {
        fmt.Printf("error: %+v", err)
        os.Exit(1)
    }
    // populate env
    for k, v := range flagSet {
        if err := os.Setenv(k, v); err != nil {
            fmt.Printf("error: %+v", err)
            os.Exit(1)
        }
    }
    // load config struct from the env vars we just set
    conf, err := GetConfig()
    // etc...
}

Note: All the code I wrote, I just typed here on the site, I've not tested anything, so there might be some typo's and such, but the basic ideas are all there. I think the code is close to complete enough to be used as a basis to write your own solution.

Have fun


Break a full name into a dictionary of its parts

You have some unnecessary try blocks.  Watch this:

>>> 'this'.split(', ')
['this']
>>> ''.split(', ')
['']

Look, Ma!  No empty lists!  Since a split will always have at least one item in the result, you don't need to try to get the first item.  It will always be there for you.  Watch this:

>>> [][1:]
[]
>>> ' '.join([])
''

Look, Ma!  No errors!  A slice never throws errors, and a ' '.join() will return '' when the argument is empty.  That means that you need only one try block for first and middle.

An except block should specify what it is expecting.  A bare except is dangerous. I have found myself caught when I have done that because I can't even interrupt the script with Ctrl+C.  If it isn't an IndexError that trips the except, we want to know about it.  We don't want to hide it under an except.

Your naming does not comply with PEP 8 (the Python style guide).  It says to use lowercase_with_underscores for function and variable names.  Besides that, csSplit is a little hard to understand.  Sure, one can recognize cs as being short for comma-separated if one thinks about it,  but I prefer something a little bit easier to understand.  Keeping the same spirit, why not comma_split?  I don't really like that name, but it seems a little easier to understand that csSplit.

It doesn't make much difference with short strings, but first and middle both perform the same split operation.  To speed things up, make the split only once by assigning a variable to it.

Why the intermediate variable partsDict?  We know that the function returns a dictionary of parts by its name and doc string.  Therefore, the variable cannot be for clarity.  It is longer to use than a simple return, so it isn't for line length.  Why then?  Just return directly.

The code ends up looking like this:

def get_name_parts(name):
    """Return a dictionary of a name's parts.
    name: e.g. 'JOHNSON, John Roberts, Jr. (Jack)'
    Ignores nicknames.
    """
    comma_split = name.split(', ')
    last = comma_split[0]

    try:
        first_mid = comma_split[1].split(' ')
    except IndexError:
        first_mid = ['']

    first = first_mid[0]
    middle = ' '.join(first_mid[1:])

    try:
        suffix = comma_split[2].split(' ')[0]
    except IndexError:
        suffix = ''

    return {'first': first,
            'last': last,
            'middle': middle,
            'suffix': suffix}

Is it shorter?  Not really.  It is only two or three lines shorter, but it is clearer, less repetitive, and safer.  Happy coding!


How can I make this function that checks whether a number is a palindrome better?

It looks fine - note that for a function this small there will almost always be no real impact on runtime, nor on readability. The only thing I would change is avoiding converting num into a string twice.
It is also possible to check for a palindrome without explicitly reversing the string, which I have done below.
export function is_palindrome(num: number): boolean {
    const str = num.toString();
    const len = str.length;
    for (let i = 0; i < Math.floor(len / 2); i++) {
        if (str[i] !== str[len - i - 1]) {
            return false;
        }
    }
    return true;
}


Code duplication where impliment extension method for IEnumerable and IQueryable on entity set

Given that the logic is exactly the same (i did not do a line by line comparision), one of the possible solutions whould be:

private static TCollection WhereCreateWithin<T, TCollection>(TCollection query,
             DateManager.TimeRange timeRange,
             DateTime? beginDayParam,
             Func<TCollection, Func<T, bool>, TCollection> selector)
    where T : IHasCreateDate
    where TCollection : IEnumerable<T>
{
    //insert your logic here
    //replace query.Where(x => ... ) call with selector(query, x => ... ) call
}

public static public static IQueryable<T> WhereCreateWithin<T>(this IQueryable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate
{
    return WhereCreateWithin<T, IQueryable<T>>(query, timeRange, beginDayParam, (q, f) => q.Where(x => f(x)))
}

public static public static IEnumerable<T> WhereCreateWithin<T>(this IEnumerable<T> query, DateManager.TimeRange timeRange, DateTime? beginDayParam = null) where T : IHasCreateDate
{
    return WhereCreateWithin<T, IEnumerable<T>>(query, timeRange, beginDayParam, (q, f) => q.Where(f))
}


To combine the second and third column into only 1 helper column I deviced the following formula's:

In the first cell of the second column I put the following formula: =IF(ISNUMBER(SEARCH($B$3,E3,1))=FALSE,"",--ISNUMBER(SEARCH($B$3,E3,1))

In the second cell and down I wrote the following formula: =IF(--ISNUMBER(IFERROR(SEARCH($B$3,E4,1),""))=0,"",COUNT($E$3:$E3)+1)


Stack with "getMiddle" and "deleteMiddle" operation

Implementing "correctly":

Your Classname says, you have implemented a Stack with additional operations. Why do I not see implements or extends in your code then?

public class FindMiddleStack<T> {

should have been:

public class FindMiddleStack<T> extends Stack<T> {

scratch that, Stack<T> has been deprecated for so long, that there should be some annotation @Antique. Even the official oracle documentation recommends the use of Deque<T>!
Mind that Deque can also be used as a FIFO Queue

That said, your class could start with the following:

public class FindMiddleDeque<T> implements Deque<T> {

Design:

Your node class design is "flawed". You make it way to complicated, if you only want a LIFO (last in first out) behavior. Usually a Node in a stack knows about it's value and has a reference to the next Node.

private static class Node<T> {
    Node<T> next;
    T value;

    Node(T value, Node<T> next) {
        this.value = value;
        this.next = next;
    }
}

This also simplifies your pop and push methods:

@Override
public T pop() {
    if(size == 0 || top == null){
       throw new EmptyStackException();
    }

    size--;
    Node<T> destroy = top;
    top = destroy.next;

    return destroy.value;
    //destroy should be destroyed by falling out of scope
}

@Override
public void push(T value) {
    top = new Node(value, top);
    size++;
}

@Override
public T peek() {
    if(size == 0 || top == null){
       throw new EmptyStackException();
    }

    return top.value;
}

Finding the middle.

Your code is a little complicated concerning finding the middle of the stack. In fact we can assume, that the middle element is that at "index" size / 2.

How can we use that to our advantage?

public void deleteMiddle() {
    if(size == 0 || top == null){
        throw new EmptyStackException();
    }
    int middleIndex = size / 2;

    Node<T> current = top;
    Node<T> previous = null;
    for (int i = 0; i < middleIndex; i++){
        previous = current;
        current = current.next;
    }
    // we can assume we are in the middle now.
    previous.next = current.next; //current is lost
    size--;
}

We can also get the middle element in a similar fashion:

public T getMiddle() {
    if(size == 0 || top == null){
        throw new EmptyStackException();
    }

    int middleIndex = size / 2;

    Node<T> current = top;
    for (int i = 0; i < middleIndex; i++){
        current = current.next;
    }
    return current.value;
}


CLI to bump package.json version and add git tags

(Disclaimer: I'm not a JavaScript expert and I don't have much experience with async/await either, so take my advices with a grain of salt. I hope you will find it helpful anyway.)

Running async calls in parallel

If you assume these will run in parallel, they won't:

// both of these may run together
await git.push();
await git.pushTags();

To make them run in parallel, you could use Promise.all:

await Promise.all([git.push(), git.pushTags()]);

Or save the result of the calls without await, and await on the results:

const pushResult = git.push();
const pushTagsResult = git.pushTags();
await pushResult;
await pushTagsResult;

Not too much async and spinners?

Most of the operations are fast,
such as updating the file, git add, and git commit,
and I don't see a good reason to make them run in parallel and with a progress indicator.

The only operation that may be slow and where the progress indicator makes sense is the git push.

Since the main logic is not packaged as reusable code that can be imported and called from another module,
wrapping it in async (in the IIFE at the end) seems unnecessary too.
If the updating of the package was separated from the command line parsing,
then it could make sense to make it possible to run async,
if you had a use case for that.
Without a use case, I think it's over-engineering.

Addressing your questions

  A lot of my code is wrapped in try-catch blocks which I understand is not supposed to be the case with async/await or Promises. I'm not sure how to fix this.

I don't see anything wrong with your try-catch blocks (but see the disclaimer at the top).

  There's a lot of duplication with the spinner initialisation code. I am aware the ora has an ora.promise method as well. I couldn't get this to work.

As mentioned earlier, I think the spinners are overkill.
However, even if you remove them from most places,
much duplication will still remain.

I don't think you need the granularity of catching exception at every step.
You could wrap those steps in a single try-catch block,
and that will reduce the duplication and boilerplate code.

  I haven't added much error checking yet. For example, later, I'd like to check if a package.json exists, and if it doesn't, get the current version from git tags. How can I structure my code in such a way that I can easily add such functionality in the future?

The way you did so far seems fine to me.
If later you want to get tags from Git,
you can add a function for that,
and call it from nextVersion as needed.


This

let filePath = Bundle.main.path(forResource: "test", ofType: "dat")
guard filePath != nil else { return }
let fileURL = URL(fileURLWithPath: filePath!)

is an anti-pattern in Swift, see also When should I compare an optional value to nil? on Stack Overflow. Instead of testing a value against nil and then force-unwrapping it, you should use optional binding:

guard let filePath = Bundle.main.path(forResource: "test", ofType: "dat") else { return }
let fileURL = URL(fileURLWithPath: filePath)

This can be further simplified by retrieving an URL in the first place, instead of getting a file path and converting that to an URL:

guard let fileURL = Bundle.main.url(forResource: "test", withExtension: "dat")
    else { return }

But actually this is a situation where I would prefer force-unwrapping: A missing resource file in the application bundle is a programming error and there is no way of recovering from that situation in a sensible way. It should be detected early during development:

let fileURL = Bundle.main.url(forResource: "test", withExtension: "dat")!

The same reasoning applies to reading and decoding the file:

let file = try! String(contentsOf: fileURL, encoding: .utf8)

Using split() here

let arrayOfLines = file.split { $0.isNewline }

is good: It creates an array, but the array elements are substrings, i.e. they contain references into the character storage of the original file string. The same method can be applied to split each line to avoid data duplication:

for line in arrayOfLines {
    let arrayOfItems = line.split(separator: ",")
    // ...
}

This

let tempPerson = Person(id: Int(arrayOfItems[0])!,
                        first: arrayOfItems[1].replacingOccurrences(of: "\"", with: ""),
                        last: arrayOfItems[2].replacingOccurrences(of: "\"", with: "")

would crash if a line has less than 3 comma-separated items, or if the first item is not an integer. However, as mentioned above, this is acceptable if the data is read from your own resource file (and not from some external resource): We can rely on the data to be well-formed.

It is a bit difficult to read though, and I would split the single statement into parts:

let id = Int(arrayOfItems[0])!
let firstName = arrayOfItems[1].replacingOccurrences(of: "\"", with: "")
let lastName = arrayOfItems[2].replacingOccurrences(of: "\"", with: "")
let tempPerson = Person(id: id, first: firstName, last: lastName)

With respect to removing the delimiters: What you do is fine if the data file has exactly the format from your example, and there are no embedded quotation marks or commas in the fields. An alternative is

let firstName = String(arrayOfItems[1].dropFirst().dropLast())
let lastName = String(arrayOfItems[2].dropFirst().dropLast())

which might be slightly more efficient because it does not need bridging to NSString. (But I did not measure it.)

Finally note that your code does not parse all valid CSV files. Problems are for example

embedded commas: 4,"Sammy","Davis, Jr."
embedded quotation  marks: 5,"John","Foo""Bar"
or embedded newlines.

Before you try to implement all those features yourself I would suggest to have a look at some existing Swift CSV parsing libraries.


Plotting text from a dictionary with Matplotlib

Your code might be a bit clearer without level & start, preferring to manipulate just x & y.

You might write a sorting helper function, and change the emoj loop to this:

    for x, emoj in enumerate(emoj_by_score(dictionary)):

You have some hard coded values that you could derive by inspecting the top input argument. On the whole, it doesn't seem so terrible. It is reasonably clear.


Scala Direction enum with Enumeration and collection usage

Use an Algebraic Data Type (ADT):

abstract class Direction(val opposite: Direction)
case object Up extends Direction(Down)
case object Down extends Direction(Up)
case object Left extends Direction(Right)
case object Right extends Direction(Left)

or:

abstract class Direction {
  def isOpposite(d: Direction): Boolean
}
case object Up extends Direction {
  def isOpposite(d: Direction) = d == Down
}
case object Down extends Direction {
  def isOpposite(d: Direction) = d == Up
}
case object Left extends Direction {
  def isOpposite(d: Direction) = d == Right
}
case object Right extends Direction {
  def isOpposite(d: Direction) = d == Left
}


Swift extension: Dictionary to JSON string for URL parameter

Your dictionary to JSON converter has some serious issues:

The special characters " and \in strings are not properly escaped:

[ "a\"b" : "c\\d"].toJSONString()

produces "{"a"b":"c\d"}", correct would be {"a\"b":"c\\d"}
(see for example http://json.org).
Only arrays of strings are implemented, but not arrays of numbers
or arrays of arrays or dictionaries.
Value types which are not covered by your code just print as an
empty string instead of causing an error.
Boolean values are simply treated as numbers:

[ "key" : true].toJSONString()

gives {"key":1}, correct would be {"key":true}

While this could all be fixed, it probably isn't worth the effort
because there is a Foundation class NSJSONSerialization which already
does exactly this:

var dict : [String: AnyObject] = [:]
dict["a\"b"] = "c\\d"
dict["strings"] = ["string", "another"]
dict["keywdict"] = [ "anotherKey": 100, "Key2": "Val2"]
dict["numbers"] = [ 1, 2, 3]
dict["bools"] = [ true, false]

var error : NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dict, options: nil, error: &error) {
    let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
    println(jsonString)
} else {
    println("Error in JSON conversion: \(error!.localizedDescription)")
}

Output:

{"keywdict":{"anotherKey":100,"Key2":"Val2"},"bools":[true,false],"a\"b":"c\\d","strings":["string","another"],"numbers":[1,2,3]}


Here is a simplified version, thanks to this answer.

public interface IMainPaymentProvider : IPaymentProvider
{
}

public interface IPaymentProvider : IPaymentService
{
    string Name { get; }
}

public interface IPaymentGateway : IPaymentService
{
}

public interface IPaymentService
{
    Task<BillingId> RegisterAsync(CreditCard card);
    Task ChargeAsync(BillingId id, decimal amount);
}

Where:

[TypeConverter(typeof(BillingIdTypeConverter))]
[JsonConverter(typeof(BillingIdJsonConverter))]
public class BillingId
{
    public static BillingId Parse(string text) =>
        IsNullOrWhiteSpace(text) ? null :
        text.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries) is string[] p && p.Length == 2
            ? new BillingId(p[0], p[1])
            : throw new FormatException();

    public BillingId(string provider, string value) =>
        (Provider, Value) = (provider, value);

    public string Provider { get; }
    public string Value { get; }

    public override string ToString() =>
        $"{Provider}:{Value}";
}

So payment gateway looks like:

[Service]
public class PaymentGateway : IPaymentGateway
{
    public PaymentGateway(IMainPaymentProvider mainProvider, params IPaymentProvider[] providers) =>
        (MainProvider, Providers) =
        (mainProvider, providers.ToDictionary(p => p.Name));

    IPaymentProvider MainProvider { get; }
    IReadOnlyDictionary<string, IPaymentProvider> Providers { get; }

    public async Task<BillingId> RegisterAsync(CreditCard card) =>
        await MainProvider.RegisterAsync(card);

    public async Task ChargeAsync(BillingId id, decimal amount) =>
        await Providers[id.Provider].ChargeAsync(id, amount);
}

And a sample provider could be:

public interface IStripeProvider : IMainPaymentProvider
{
}

[Service]
public class StripeProvider : IStripeProvider
{
    StripeClient Client { get; } = new StripeClient();

    public string Name => "Stripe";

    public async Task<BillingId> RegisterAsync(CreditCard card) =>
        new BillingId(Name, await Client.RegisterAsync(card));

    public async Task ChargeAsync(BillingId id, decimal amount) =>
        await Client.Charge(id.Value, amount);
}


De Casteljau's algorithm to draw Bezier Curves in OOP and C++ (iterative version)

I am repeating much of what is already in the comments but felt it should be spelled out more explicitly.

Avoid using #define statements

Per Scott Meyers's Effective C++ you should always prefer const to #define statements because #define statements are a preprocessor step, which means when you are debugging, you will see a number and not a variable name. This can make your life very difficult, so you should avoid #defines whenever possible.

Descriptive Naming

You should only use a name like temp when it's really important to emphasize that you are using a temporary variable (say to draw your reader/client's attention to the fact that a function creates a temp object and so should be used sparingly when certain memory concerns are present). Quite literally any other name would be better than temp possibly even var. Why not use pointCollection or something similarly descriptive?

Comments where helpful

I don't see any comments in your code. I am also not familiar with the libraries you are using. If you want a reader like me to understand your code, you should put in some clarification, succinct one line statements should be enough. Even for yourself, you should put in a note about what you hoped to accomplish in a function.


Alternately taking elements from an array

This one-liner should be what you're looking for:

def alternate_take(xs, ys)
  raise ArgumentError, "Unequal length" if xs.length != ys.length
  xs.zip(ys).map.with_index{|(x,y),i| i.even? ? x : y}
end

Follow Up

Tokland's answer to OP's followup about a solution without indexes is really clever.  Here's another variation, which I don't like as much as the index version, but it answers the question:

def alternate_take(xs, ys)
  raise ArgumentError, "Unequal length" if xs.length != ys.length
  xs.zip(ys).reduce([]){|m,(x,y)| m + (m.size.even? ? [x] : [y])}
end


I think the query is optimal enough. The truth is query can retrieve a result only by accessing 2 years data, so given WHERE condition is must. And the query access rows only once. At performance aspect, table access method (through index or by full scan) is critical, but Oracle Optimizer will choose it by referring statistics information.


Print largest two integers from a stream

Your logic is actually correct.  Perhaps you just don't know what to type in your terminal window to terminate the input stream.  After typing in your numbers, you need to send an end-of-file ("EOF") character.  On Unix, you do that by hitting ControlD.  On Windows, it's ControlZ.

Note that System.in is the program's "standard input" stream, which doesn't have to come straight from the keyboard.  You can also do

echo 3 1 4 1 5 9 | java Homework.Question1

or

java Homework.Question1 < numbers.txt

Therefore, kbd is a misnomer.  Try naming your Scanner more generically, like scanner or input.

You don't want to print your two numbers with no space in between.  It will look like one long number!

The placement of your braces is inconsistent, with the ones for the main function and the else if being closest to conventions.  The brace opening the while loop should be on the same line as the while keyword.  The brace closing the if block should be pulled further left, aligned with the if keyword, and else can come immediately after.

public class Question1 {
    public static void main(String[] args) {
        ...
        while (...) {
            ...
            if (...) {
                ...
            } else if (...) {
                ...
            }
        }
        System.out.println(...);
        System.out.println(...);
    }
}

You have interpreted the exercise such that duplicate entries in the input are ignored.  That's the easier way.  If the exercise requires you to print the same number twice when there is a tie for the maximum, then the program is trickier to implement.


I noticed with dx and dy, you're assigning them to self.dx and self.dy regardless of what they are. Those assignments can be moved up with x1 and x2 which thins out the checks a bit.

Unless you really want all four combinations to happen using the same function though, I'd probably break this down into some "pseudo-constructors" that defer to the main constructor. Instead of allowing all possible combinations of data then error checking after, I'd just try to limit up front what options are available. There are four possible input combinations: dx, dy, dx, y2, x2, y2, and x2, dy. You could have four static methods that explicitly request a certain combination, and construct a line accordingly.

In the below code, I also decided to use a NamedTuple here. They're basically a shortcut way of creating an immutable class, complete with a generated constructor, a __repr__ implementation and some other nice features. See the comments doc page and the comments.

Now, I'll admit that this code that I ended up with isn't quite as nice as what I originally saw in my head. I think it is still quite an improvement though in terms of readability:

from typing import NamedTuple, Optional

# NamedTuple automatically creates a constructor that handles all the annoying self._x2 = x2 lines
# It also makes Line immutable. This gets rid of the need for the getters you have
class Line(NamedTuple):
    x1: int  # "Declare" the fields that the tuple will have
    y1: int

    x2: int
    y2: int

    dx: Optional[int] = None  # With defaults of None for some
    dy: Optional[int] = None

    # staticmethod essentially gets rid of the `self` parameter and makes the method
    #  intended to be called on the class itself instead of on an instance.
    @staticmethod
    def from_dx_dy(x1, y1, dx, dy):
        return Line(x1, y1, dx=dx, dy=dy, x2=x1 + dx, y2=y1 + dy)

    @staticmethod
    def from_dx_y2(x1, y1, dx, y2):
        return Line(x1, y1, dx=dx, y2=y2, x2=x1 + dx)

    @staticmethod
    def from_x2_dy(x1, y1, x2, dy):
        return Line(x1, y1, x2=x2, dy=dy, y2=y1 + dy)

    @staticmethod
    def from_x2_y2(x1, y1, x2, y2):
        return Line(x1, y1, x2=x2, y2=y2)

Then, as an example:

>>> Line.from_dx_dy(1, 2, 3, 4)
Line(x1=1, y1=2, x2=4, y2=6, dx=3, dy=4)

>>> Line.from_x2_dy(1, 2, 3, 4)
Line(x1=1, y1=2, x2=3, y2=6, dx=None, dy=4)

It still has an unfortunate amount of duplication, but I think it's easier to make sense of.

As mentioned in the comments, since I'm referring to the class itself in the static methods, they should arguably be classmethods instead:

@classmethod
def from_dx_dy(cls, x1, y1, dx, dy):
    return cls(x1, y1, dx=dx, dy=dy, x2=x1 + dx, y2=y1 + dy)

@classmethod
def from_dx_y2(cls, x1, y1, dx, y2):
    return cls(x1, y1, dx=dx, y2=y2, x2=x1 + dx)

@classmethod
def from_x2_dy(cls, x1, y1, x2, dy):
    return cls(x1, y1, x2=x2, dy=dy, y2=y1 + dy)

@classmethod
def from_x2_y2(cls, x1, y1, x2, y2):
    return cls(x1, y1, x2=x2, y2=y2)

Where cls is referring to the current class (Line). I don't like the look of this as much, but it is the intent of class methods.


JavaScript Armstrong Number Validator (ES6)

Being called isArmstrong, it should just return a boolean value, and not have side effects of setting any sort of DOM. That can be done in a separate function by the caller.
expandedInputValue can probably have a better name. Maybe digitTotal or digitCubeTotal. But the current name isn't helpful.
I think this is a no-op: .map(digit => digit)


Generic property with AOP-functionality in Java

My first thought is: Interesting.

The Property<T> class as it is right now

First, some feature-requests or changes you can consider:

You could combine beforeSet and onSet into a BiFunction<T, T, T> (which is the same as BinaryOperator<T>).
It could potentially be useful to use the afterSet as a BiConsumer, to also let it know about what the previous value was.
What if a previous function has been set for afterSet/beforeSet/etc.? I think you should do a null-check there and either throw an exception if it has already been set, or auto-add it (using the default methods that exists on the interfaces), such as this.afterSet = this.afterSet.andThen(afterSet);
I'm not a big fan of the onGet feature. In my experience, getters should do what they do best: Get the actual value. Having the possibility to modify the value that should be returned seems risky. Doing conversion like String.toLowerCase() for example should lie where it is being used, or the property should be set to lower case right from the start IMO.
Actually, thinking about it... I'm not sure about any of the get-features... I just don't see a specific real use case for them.

The system itself

I'm going to list a couple of good things and a couple of bad things with this approach:

Good things:

Allows you to manipulate the "behavior" of a property in quite some detail.
Allows you to manipulate the "behavior" of a property in quite some detail.
Allows you to manipulate the "behavior" of a property in quite some detail.

(One time for the beforeSet feature, once for the onSet and once for afterSet. Three-in-one)

Bad things:

Primitive types needs to be wrapped into it's non-primitive type, like int -> Integer. This leads to slower code as there will be some auto-boxing, and it will allow the value null where you might not want that value, or you have to handle the null with a beforeSet or similar. Although you could potentially separate classes for  IntProperty, BooleanProperty, etc. I don't think you'd want to do all those classes.
When should I make my Java classes use this approach or not? Should I introduce them when I feel like I need them or should I play safe and use this approach on all my properties, even though when I will probably never need them? I can imagine there will be some headache going on no matter what option I would choose.
It's breaking the Java beans style, which isn't a bad thing by itself. It can cause a bit of a problem when using libraries that depends a lot on reflection, but there are normally ways to work around that. (I.e. telling the library to ignore the private property and use the getters and setters provided).

A different approach that's capable of doing the same thing

Consider Google's EventBus code. With the right event classes, this can accomplish the same things. Example code following: (not tested, but something similar would work)

public class Foo {

    private int bar;
    private EventBus events = new EventBus();

    public Foo() {
        bar = 42;
        events.registerListener(this);
    }

    @Subscribe
    private void onSetChanged(BarChangeEvent event) {
        System.out.printf("bar will be set from %d to %d.%n", event.getOldValue(), event.getNewValue()));
    }

    public int getBar() {
        return bar.get();
    }

    public void setBar(int bar) {
        events.post(new BarChangeEvent(this.bar, bar));
        this.bar = bar;
    }
}

Of course, there's bad things to say about this approach as well. One example is that it always creates a new object whenever bar is set. For most projects of course, the @Subscribe method is probably not inside the Foo class. Instead the class will have to expose the EventBus somehow (or the EventBus can be injected into the Foo class).

Still another approach

This is the fastest approach, but unfortunately it is the least flexible approach as well.

The simple "do-it-in-the-setter approach"

public class Foo {

    private int bar;

    public Foo() {
        bar = 42;
    }

    public int getBar() {
        return bar;
    }

    public void setBar(int bar) {
        System.out.printf("bar will be set from %d to %d.%n", this.bar, bar);
        this.bar = bar;
    }
}

Summary

You might have use for your Property<T> code, if so then great. I personally would probably not use it. (I tend to use the Event-driven approach when I need to, not for each and every property of course. Sometimes I might even use the "put-it-in-the-setter-approach")

  Does this put too much logic into properties?

Personally, I think it does yes. But that's just my two three cents.


That is not the Sieve of Eratosthenes

The Sieve of Eratosthenes computes multiples
of each found prime to mark subsequent composite numbers in the sieve.
Your algorithm computes the remainder of all subsequent numbers instead.
That makes a huge difference. I'll come back to that later, let's start
with a

Review of your current code

There is a inconsistency here:

func generatePrimes(to n: Int) -> [Int] {
    // ...
    var arr : [Int] = Array<Int>(stride(from: 3, to: n, by: 2))
    // ...
}

The function – as I understand the to parameter –
computes all primes up to and including n. On the other hand,
stride(from: 3, to: n, by: 2) does not include the upper bound,
and that is easily verified with

print(generatePrimes(to: 11)) // [2, 3, 5, 7]

So either rename the function to func generatePrimes(below n: Int)
or use stride(from: 3, through: n, by: 2) to include the upper bound.
I'll do the latter for this review.

It would also be a good idea to add a documentation comment which
unambiguously documents the function parameters.

The explicit type annotation is not needed, and the array creation
can be simplified to

var arr = Array(stride(from: 3, through: n, by: 2))

Why is the limit number expected to be greater than 5? That is an
unnecessary restriction and would be unexpected for a caller of your function. It may be that your implementation  does not work if
\$ n \le 5 \$, but it would be easy to handle that case separately:

if n <= 5 {
    return [2, 3, 5].filter { $0 <= n }
}

In

    let num : Int = arr.remove(at: index)

the type annotation on the left is again not needed.

(Remark: This

    arr = arr.filter { $0 % num != 0 }

can be replaced by the more efficient

    arr.removeAll(where: { $0 % num == 0 })

in a future version of Swift, when SE-0197 Adding in-place removeAll(where:) to the Standard Library is implemented in Swift 4.2.)

Here

    if arr[index + 1] >= Int(floor(sqrtf(Float(n)))) { break }

is a hidden bug: As

print(generatePrimes(to: 26)) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 25]

demonstrates, you are leaving the loop to early.
I would also compute the square root only once, and use double-precision
arithmetic: The 24 bit significand of a Float cannot represent large
integers correctly (compare Computing the integer square root of large numbers).

Finally, the function should compute the result, but not print it, i.e. this

//Print Statements
print("Prime numbers under \(n):")
_ = arr.enumerated().map { (index, element) in print("\t\(index + 1). \(element)") }

should be removed. It is generally a good habit to separate computation from I/O.
In addition, this distorts the benchmark results, because you measure also the
time for converting the numbers to strings, and the time to print these strings
(which depends on the output device, printing to a file is faster than printing
to the Terminal or the Xcode console).

With all changes suggested so far, your function would look like this:

/// Compute list of primes
///
/// - Parameter n: The upper bound
/// - Returns: An array with all primes <= `n`
func generatePrimes(to n: Int) -> [Int] {

    if n <= 5 {
        return [2, 3, 5].filter { $0 <= n }
    }

    var arr = Array(stride(from: 3, through: n, by: 2))

    let squareRootN = Int(Double(n).squareRoot())
    for index in 0... {
        if arr[index] > squareRootN { break }
        let num = arr.remove(at: index)
        arr = arr.filter { $0 % num != 0 }
        arr.insert(num, at: index)
    }

    arr.insert(2, at: 0)
    return arr
}

Using the Sieve of Eratosthenes

As I said above, your algorithm is different from the Eratosthenes sieve.
Each time a prime number \$ p \$ is found, your code does trial divisions for
all remaining numbers to remove multiples of \$ p \$.
The Eratosthenes sieve computes multiples of \$ p \$ instead:

p*p, p*p + p, p*p + 2*p, p*p + 3*p, ...

and marks these as composite. Note that there are far less values to compute.

Also your algorithm removes and inserts array elements frequently.
That is slow because the remaining elements must be shifted to the left
or to the right.

The Eratosthenes sieve works with a fixed-sized boolean array instead.

Here is a very simple straight-forward implementation in Swift:

func eratosthenesSieve(to n: Int) -> [Int] {
    var composite = Array(repeating: false, count: n + 1) // The sieve
    var primes: [Int] = []

    if n >= 150 {
        // Upper bound for the number of primes up to and including `n`,
        // from https://en.wikipedia.org/wiki/Prime_number_theorem#Non-asymptotic_bounds_on_the_prime-counting_function :
        let d = Double(n)
        let upperBound = Int(d / (log(d) - 4))
        primes.reserveCapacity(upperBound)
    } else {
        primes.reserveCapacity(n)
    }

    let squareRootN = Int(Double(n).squareRoot())
    var p = 2
    while p <= squareRootN {
        if !composite[p] {
            primes.append(p)
            for q in stride(from: p * p, through: n, by: p) {
                composite[q] = true
            }
        }
        p += 1
    }
    while p <= n {
        if !composite[p] {
            primes.append(p)
        }
        p += 1
    }
    return primes
}

The only optimization I did was to reserve capacity for the result
array in order to avoid reallocations.

This is already considerably faster than your original code.
Here is my benchmarking code:

func benchmark(_ ident: String, _ function: (Int) -> [Int], to n: Int) {
    let start = Date()
    let primes = function(n)
    let elapsed = Date().timeIntervalSince(start)
    print(ident, primes.count, "primes up to", n, String(format: "time: %.3f", elapsed))
}

benchmark("original", generatePrimes, to:     100_000)
benchmark("original", generatePrimes, to:   1_000_000)
benchmark("original", generatePrimes, to:  10_000_000)

print()

benchmark("eratosthenes", eratosthenesSieve, to:       100_000)
benchmark("eratosthenes", eratosthenesSieve, to:     1_000_000)
benchmark("eratosthenes", eratosthenesSieve, to:    10_000_000)
benchmark("eratosthenes", eratosthenesSieve, to:   100_000_000)
benchmark("eratosthenes", eratosthenesSieve, to: 1_000_000_000)

On a 1.2 GHz Intel Core m5 MacBook (Retina, 12-inch, Early 2016)
with 8GM RAM I get the following results (slightly reformatted to
increase the legibility):

original   9592 primes up to   100000 time: 0.038
original  78498 primes up to  1000000 time: 0.418
original 664579 primes up to 10000000 time: 9.739

eratosthenes     9592 primes up to     100000 time:  0.001
eratosthenes    78498 primes up to    1000000 time:  0.007
eratosthenes   664579 primes up to   10000000 time:  0.096
eratosthenes  5761455 primes up to  100000000 time:  1.223
eratosthenes 50847534 primes up to 1000000000 time: 15.034

This can surely be further improved, a first step would be to handle the case p=2
separately and to use the sieve only for odd numbers (which however complicates the
index calculations a bit).

But, as you see, computing the primes up to 1 billion is feasible with the sieve
of Eratosthenes (and the numbers are correct, you can compare them with
https://primes.utm.edu/howmany.html).

Going for the trillion

You were also thinking of computing all primes up to one trillion. That might be
a problem, no matter which algorithm you choose. According to
https://primes.utm.edu/howmany.html, there are 37,607,912,018 prime numbers
below 1 trillion. Even if we use 32-bit bit integers to save space, that would
still require approx 140 GB memory, which makes returning an array with all that
numbers difficult.

So that would require a different approach which allows to compute prime numbers in
some given range, instead of all prime numbers up to a limit.


Resizing and recoloring a logo using PHP GD Library

If you have ImageMagick available, I would strongly consider moving towards that library - not necessarily for any performance/quality gains (I think this can vary between libraries based on use case) - but because it presents an object oriented interface.  Right now, your code is very much procedural in nature and you might find it harder to maintain and reuse over time.

From a performance standpoint, your best best is to actually load test your application to see if it is going to meet your needs.  I am guessing when you say 5000 users, you don't mean 500 concurrent users.  How many users do you truly expect executing this script concurrently? How much memory does this take on typical execution?  How does that compare against your server hardware?  Is the user experience on your hardware (i.e. the time that this takes to execute) appropriate?  Does that time to complete change under concurrent load?

Really your performance is going to have more to do with the questions I just asked than your code.

You need to DRY (Don't Repeat Yourself) up your code.  You can do this through some configuration and use of variables:

For example:

$background_colors = [
    'plum' => ['red' => 93, 'green' => 62, 'blue' => 93],
    ...
];
$text_colors = [
    'black' => ['red' => 0, 'green' => 0, 'blue' => 0],
    ...
];

$fill_color = imagecolorallocate(
    $base_image,
    $background_colors[$theme]['red'],
    $background_colors[$theme]['green'],
    $background_colors[$theme]['blue'],
);

$text_color = imagecolorallocate(
    $base_image,
    $background_colors[$textC]['red'],
    $background_colors[$textC]['green'],
    $background_colors[$textC]['blue'],
);

This rids you of all those if-else conditionals.  And also gives you the ability to lookup a provided background/text color string to determine if it exists in configuration.  This could be useful in setting defaults.  For example:

if(!empty($background_colors[$theme])) {
    $theme = $default_theme;
}

You have a lot of hard-coded "configuration" values (the colors as noted before, image size thresholds, font size, file name string length, etc.) that are simply hard-coded into your script. Personally, I would look to do all of this in a class context, so you have means to store default /overridden configuration as well as to get your main logic out of the main script path and provide you greater re-use down the line (like when you want to do this same thing on another site).

By the way, your $font_size variable only seems to be defined on one half of a conditional which could be problematic (though perhaps it is doe that is not shown).

You should actively try to design away else constructs.  When you get in the habit of doing this, you will find that in most cases these are not really necessary.

Why should you do this?  Because the more code paths you have, the more fragile and harder to maintain/debug your code will tend to be (the term cyclomatic complexity is used to describe this).

So when you see yourself with a conditional like this:

if(($width>=601)&&($width<=1080)) {
    $percent = $width/$logo_width;
} elseif($width>=1081) {
    $percent = 1.2;
    $font_size = 28;
}

Consider changing it to something like:

$percent = 1.2;
$font_size = 28;
if(($width>=601)&&($width<=1080)) {
    $percent = $width/$logo_width;
}

This is easier to read and reduces your potential code paths by one.  This is also at the heart of my early comment to get rid of all those if-else conditions.  They simply are not needed in this case and can be designed away.

Similarly,

if($height==768) {
    $y = (($height/2)+($logo_new_height/2));
} else {
    $y = (($height/2)+($logo_new_height));
}

Could become:

  $y = (($height/2)+($logo_new_height));
  if($height==768) {
    $y = (($height/2)+($logo_new_height/2));
  }

if($height==768) {

Do you really have a use case for this specific height?  Should this be > or < comparison?

You should consider using exact comparisons (=== and !==) as your default means for comparison as opposed to the loose comparisons you are doing.  Loose comparisons tend to introduce bugs into code around unexpected truthy/falsey conditions.  I find myself using them in only very specific cases where a truly loose comparison is warranted.

Some stylistic thoughts:

Use space around your comparison operators for better readability.
Be consistent in using curly braces around flow-control structures (conditionals, loops, etc.).
Try to limit the length of your lines to less than 80 characters to make the code easier to read. Your imagecopyresampled() call is pretty long and could easily be broken across multiple lines for better readability.


Tabbed user interface with a panel that expands downward

There are a few things you can do to reduce the code, for example:

you can use add to add jquery selections:

$('.product-filter').add('.sortby').css('display', 'none');

rather then have lots of nested if's you can use a ternary op and seperate them to seperate functions:

var action =  $(this).hasClass('active') ? handleActive : handleInactive;
action.call(this);

function handleActive () {
    if ($(this).hasClass('filter-header'))  {

        $('.clickable-header').removeClass('active');
        $(this).addClass('active');
        $('.sortby').slideUp(speed);
        $(this).parent().find('.dropable-section').slideDown(speed);
        $('#category-products').animate({ 'marginTop': filterHeight}, speed);
    }

    if ($(this).hasClass('sort-by-header'))  {

        $('.clickable-header').removeClass('active');
        $(this).addClass('active');
        $('.product-filter').slideUp(speed);
        $(this).parent().find('.dropable-section').slideDown(speed);
        $('#category-products').animate({ 'marginTop': sortbyHeight}, speed);
    }
}

function handleInactive () {
     if ($(this).hasClass('filter-header'))  {

         $(this).parent().find('.dropable-section').slideUp(speed);
         $('#category-products').animate({ 'marginTop': 0}, speed);
     }

     if ($(this).hasClass('sort-by-header'))  {

         $(this).parent().find('.dropable-section').slideUp(speed);
         $('#category-products').animate({ 'marginTop': 0}, speed);
     }
}

you can also remove the duplication where the same outcome is reached regardless of the if, such as:

if ($(this).hasClass('filter-header'))  {

            $('.clickable-header').removeClass('active');
            $(this).addClass('active');
            $('.sortby').slideUp(speed);
            $(this).parent().find('.dropable-section').slideDown(speed);
            $('#category-products').animate({ 'marginTop': filterHeight}, speed);
        }

        if ($(this).hasClass('sort-by-header'))  {

            $('.clickable-header').removeClass('active');
            $(this).addClass('active');
            $('.product-filter').slideUp(speed);
            $(this).parent().find('.dropable-section').slideDown(speed);
            $('#category-products').animate({ 'marginTop': sortbyHeight}, speed);
        }

could be reduced to:

$('.clickable-header').removeClass('active');
$(this).addClass('active');
$(this).parent().find('.dropable-section').slideDown(speed);

if ($(this).hasClass('filter-header'))  {
  $('.sortby').slideUp(speed);
  $('#category-products').animate({ 'marginTop': filterHeight}, speed);
}

if ($(this).hasClass('sort-by-header'))  {
  $('.product-filter').slideUp(speed);
  $('#category-products').animate({ 'marginTop': sortbyHeight}, speed);
}


opening a text file and building a dictionary

There are more efficient ways to implement this:

1) If you only need a dictionary to keep your data together without semantics, you could split as follows:

>> line = "ajones Alice Jones 44 F alice@alicejones.net"
>> identifier, *userdata=line.split()

results in:

>> identifier
'ajones'
>> userdata
['Alice', 'Jones', '44', 'F', 'alice@alicejones.net']

That's a simple point to start, but as mentinoed, the resulting array is very dumb, i.e. you have no semantics about what is what. You end up with a simple array.

2) Another way is using named tuples

from collections import namedtuple

[...]
Userdata = namedtuple("Userdata", "first_name last_name age gender email")
[...]
key, firstname, lastname, age, gender, email = a.split()
user=Userdata(firstname, lastname, age, gender, email)

Now your user contains the data in a meaningful way:

>> user.last_name
'Jones'

Besides:
Your code looks a little bit messy. It's really hard, to get ones head around what you wrote. If you come again in 3 months i doubt, you understand anything you did above.

Your naming of variables is not only poor (list,value,newdict) but terribly misleading:

for line in file_name:

You are not iterating over lines in file_name you are iterating over lines, which are perhaps from a file; in the function (and for python) it doesn't matter what the source is, but you should choose an apropriate name.

You make your and your peers life easier, if you try to write better, i.e. cleaner code.


Personally I never mutate the cell inside the cellForRowAt func but I send it a bunch of things that it needs to (re)build itself through a configure function. So:

cell.configure(with: isForHeaderCell, whenA: { /* someblock */ }, whenB: { /* another block */ }) /* etcetera */

You seem to be forwarding a lot of calls that are doing nothing except forwarding. So the only thing you really need to do is to forward the function you want to call in the end. What you need to understand is that functions can be parameters where blocks are asked and vice versa. A block is an anonymous function and if the in/out matches you can use it.

So technically you only need to pass the function that is going to do the required work all the way up and you're good. For example I have a class that fetches some data:

DataFetcher.fetch(for: id, whenDone: { result in /* etc */ })

This could be wrapped in a block:

{ (id: Int) in
    DataFetcher.fetch(for: id, whenDone: { result in /* etc */ })
}

And this block could be passed all the way up the chain, so you call down once.

func configure(with fetchStuff: (Int) -> ())

I also don't understand why you pass the Cell itself as a parameter. Perhaps because the way the @IBAction functions are structured by default but it's better to ignore it unless you have some really pressing reason to got back to exactly that cell.

Last but not least, providing defaults is not that bad when dealing with blocks that almost surely will be set during runtime:

public var btnReplyTappedClousre:((CommentCell) -> (Void))?

Could be:

private var replyAction: (Int) -> () = { _ in
    assertionFailure("This block should always be replaced by the configure function before the cell is shown")
}

Let me explain the changes in detail:

It can be private because it's set through your configure function and will only ever be called from within the cell. Better encapsulation.
It does not relate to the button but to what actually happens when you tap the button. So the @IBAction func replyButtonTapped() will call replyAction(chatId)
It only passes the required data (in this case the chat id). Nobody outside of CommentCell needs to know anything about CommentCell
The empty block containing only the assertionFailure will warn any boneheaded colleague that did not call configure during testing but will not crash when released (if it managed to escape during testing)
The block will always be set so you're not dealing with optionals anymore


Project Euler #47: find four consecutive integers, each with four distinct prime factors

Since you already have a nice implementation of a prime sieve, you should make use of it when checking for prime factors. Note that prime factors are needed, not all factors. I definitely would not use a recursive algorithm for this. It can fail with a stack limit and you need a lot of unreadable code just to set up the data structures.

I would use something simple like this:

from math import sqrt

def prime_factors(n, primes=None):
    """(int) -> iterable of ints

    Yields the prime factors of a number, excluding 1.
    Optionally takes an iterable of pre-computed prime numbers.
    """
    max_p = int(sqrt(n)) + 1
    if primes is None:
        primes = primes2(max_p)
    for p in primes:
        while n > 1 and n % p == 0:
            n //= p
            yield p
        if n == 1 or p >= max_p:
            break
    if n > 1:
        yield n

The second part of the task can be done in multiple ways. You have chosen to just define a maximum value up to which to search, filter all numbers with the right number of prime factors and then search for an increasing sequence. This will take quite a bit of memory, potentially, depending on where the answer is.

An easier way is to only remember the last four numbers with the right number of prime factors using a collections.deque with a maxlen=4, and check if they are an increasing sequence:

from itertools import count
from collections import deque

def diff(it):
    it = iter(it)
    x = next(it)
    for y in it:
        yield y - x
        x = y

def is_increasing_sequence(it):
    return all(d == 1 for d in diff(it))

if __name__ == "__main__":
    d = deque([], maxlen=4)
    for n in count(1):
        if len(set(prime_factors(n))) == 4:
            d.append(n)
            if len(d) == 4 and is_increasing_sequence(d):
                print(d[0])
                break

This can be sped up by re-introducing a maximum number to check and pre-computing the prime numbers for the prime number factorization:

if __name__ == "__main__":
    max_n = 200000
    primes = primes2(max_n)
    d = deque([], maxlen=4)
    for n in range(1, max_n):
        if len(set(prime_factors(n, primes=primes))) == 4:
            d.append(n)
            if len(d) == 4 and is_increasing_sequence(d):
                print(d[0])
                break

This solves the problem in less than a second on my machine, which is similar to your code.

Note that I followed Python's official style-guide, PEP8, which recommends lower_case for functions and variables and surrounded my code with an if __name__ == "__main__": guard to allow importing from this script without running the code. This is especially important for Project Euler, as you will need e.g. the prime sieve and the prime number factorization again in other problems.


Arranging numbers in a circle such that the sums of neighbors and sums of diametric opposites are prime

First, Vector shouldn't be used here. It's essentially a synchronized ArrayList, and you don't need any synchronization in this case. Just change it to an ArrayList.

This has the potential to be a little faster.

Second, you're using a raw ArrayList which isn't typesafe:

list.add("Some nonsense"); // Doesn't cause an error

and is necessitating your (int) type-casts later on. Specify that the list is holding integers using generics, and it will be typesafe. Read the < > as "of" here:

// Note how we specify what the list can hold
// An ArrayList of Integers
ArrayList<Integer> list = new ArrayList<>();

list.add("Some nonsense") // This causes an error now at compile time

You're also doing odd stuff with the Integer constructor. You don't need to manually cast unboxed integers like Integer(2). 2 will be "auto-boxed" into its object wrapper as necessary implicitly.

You're calling Integer/parseInt outside of a try; which is risky. If the user enters bad input, your whole program with crash. Wrap it up and handle failure (yes, users will enter bad input):

try {
    int ene = Integer.parseInt(n);
    // Code using "ene"

} catch (NumberFormatException e) {
    // Just an example. You'll need to do something more involved, like re-asking for input
    System.out.println("Parse failed");
}

Just as an example of what I mentioned earlier:

static void exchange(ArrayList arr, int k){
    ...
    int one = (int) arr.get(j);
    int two = (int) arr.get(j + half);
    Integer number_test = new Integer(one + two);

Make the parameter generic, and do away with the casts and boxing. Just write:

static void exchange(ArrayList<Integer> arr, int k){
    ...
    int one = arr.get(j);
    int two = arr.get(j + half);
    int number_test = one + two;

And then similarly below that.

Also, Java prefers camelCase, not snake_case. It's best to stick to the conventions of the language you're using.

import java.sql.Date;

is a little worrying. You shouldn't really be raiding a SQL library just to make use of some date object. Java has a java.time package for this purpose.

Just as a tip,

int two;
if (j + 1 == arr.size()) {
    two = arr.get(0);

} else {
    two = arr.get(j + 1);
}

Can also be written as:

int two = j + 1 == arr.size() ? arr.get(0) : arr.get(j + 1);

or, alternatively:

int two = arr.get(j + 1 == arr.size() ? 0 : j + 1);

Depending on how much duplication you can tolerate. The ? : part is known as the "ternary operator"/a "conditional expression".

if (!primes.contains(number_test)) {

This is quite expensive when done on a List like an ArrayList. If you need to use contains, you should probably be using a Set like a HashSet. Membership lookups are much faster using sets. The time difference will become increasingly noticeable as primes grows.


Distinct List of attribute values from XML, using a pre-defined set of attribute names

As long as you don't face noticable performance issues I would chose whatever method seems to be better for you. The XPath works so you may stick to it.

I would however build the path in a more generic way by specifying an array of attribute names first:

var attributeNames = new[]
{
    "billingLocation",
    "adminOffice",
    "homeCity",
    "origin",
    "destination",
    "location",
    "station"
}

and the combining them into a query:

var xPath = string.Join("|", attributeNames.Select(n => $"//@{n}"));
...xd.SelectNodes(xPath);

In this cas however it is a little bit easier to do the same with linq:

Parse the xml first (which is btw invalid in your example - some elements are not closed):

var xElement = XElement.Parse(text);

Then use the same array for the linq query:

var cities =
    (from attr in xElement.Descendants().Attributes()
     where attributeNames.Contains(attr.Name.LocalName)
     select attr.Value).Distinct();


Join two collections by date with no duplicate

You've got a pretty big bug here. You don't actually end up with unique items in your final list. In fact, with the sample data you gave, 1/15/14 ends up in the final output twice. You should be entering that Else block, but you're not. This is because you're not comparing what's already stored in datesTot to that value in dates2, you're comparing it to what is at the current index of dates1. (By the way, don't shorten your variable names like that. datesTotal or dateTotals would be a much better name).

I think this stems from the fact that you don't loop all the way through the first collection, before you shift the index on the second. Your attempt at optimizing the performance of the code has led to a bug. A wise dev once told me:

  Make it work.
  Make it right.
  Then make it fast.

The second problem I see is your data structure. You're keeping related data in two separate, but parallel collections. That's a recipe for disaster. Why? Because you can't overwrite an item in a collection. You have to add the replacement to the collection and then remove the original. That leaves a ton of room to make a mistake.

A correct algorithm requires three loops.

For Each outerItem in outerCollecton

    For Each innerItem in innerCollection

        If outerItem = innerItem Then

            For Each resultItem In results
                If innerItem = resultItem then
                    resultItem.Count = resultItem.Count + innerItem.Count
                    Exit For
                Else
                    results.Add innerItem
                End If
            Next resultItem

        End If

    Next innerItem

Next outerItem

Implementing that in a clean way would be easier said than done though, because you can't overwrite a value in a collection. That means you will need to keep single collection of objects that represent your data structure. For simplicity's sake, you could create a class module as simple as this.

Option Explicit

Public DateValue As Date
Public Count As Long

Alternatively, assuming your original data that you want to merge has only one instance of each date, then a Scripting.Dictionary could be a great data structure to use. See my example below.

Public Sub test()

    Dim dates1 As New Scripting.Dictionary
    dates1.Add #1/14/2013#, 1
    dates1.Add #1/15/2014#, 3
    dates1.Add #1/17/2016#, 4

    Dim dates2 As New Scripting.Dictionary
    dates2.Add #12/1/2014#, 4
    dates2.Add #1/15/2014#, 7
    dates2.Add #1/17/2018#, 12

    ' first copy the first dict to a new one to return
    Dim results As New Dictionary

    Dim currentKey

    For Each currentKey In dates1.Keys
        results.Add currentKey, dates1(currentKey)
    Next

    ' second dict
    For Each currentKey In dates2.Keys

        If results.Exists(currentKey) Then
            results(currentKey) = results(currentKey) + dates2(currentKey)
        Else
            results.Add currentKey, dates2(currentKey)
        End If

    Next

    ' print the results
    For Each currentKey In results.Keys
        Debug.Print "Date: " & currentKey & vbTab & "Count: " & results(currentKey)
    Next

End Sub

Output:

Date: 1/14/2013 Count: 1
Date: 1/15/2014 Count: 10
Date: 1/17/2016 Count: 4
Date: 12/1/2014 Count: 4
Date: 1/17/2018 Count: 12


The only criticism with the code is that your business rules are implemented in the third-party class UserRuleManager. This is OK if you are developing a a "rule system", but otherwise you should encapsulate the rules within the user class if they are about a user; the user factory if they are about how to create users; and the user repository (or data access class) if they are about how to persist and retrieve user objects.

Also, be wary if your class ends with "Manager"; it signals that the class will be responsible of too many things -- a God class.


In Haskell you can always use ;, see The Haskell Report.

So your original code could be written as an one-liner as follows:

import Data.List ; c 0 _ = [[]] ; c n xs = [ y:ys | y:xs' <- tails xs, ys <- c (n-1) xs'] ; main = mapM_ putStrLn . c 3 $ ['a' .. 'b'] ++ ['0' .. '1']

A small improvement - sequence_ . map f is mapM_ f.

Of course you'll lose the nice indentation.

IF you don't mind repeating elements (which is what you have in the original shell script), you can use replicateM:

import Control.Monad
main = mapM_ putStrLn . replicateM 3 $ ['a' .. 'b'] ++ ['0' .. '1']


Finding the most frequent words in Pandas dataframe

Note: The data you're going through is 370k+ lines. Because I tend to run different versions of code a lot during review, I've limited my version to 1000 lines.

Your code goes all over the place. Imports, downloads, another import, a variable being loaded, a function definition, the function being called and oh, another import. In that order. Would you agree it's helpful to sort those, so we can easily find what we're looking for?
The revised head of the file would look like this:
import re
import string
import nltk

import pandas as pd

from collections import Counter
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

nltk.download('punkt')
nltk.download('stopwords')

After that, we'd ordinarily put the function definition. However, there's part of the program that doesn't have to be in the function itself. It only has to be executed once, even if multiple files are handled.
# removing the emojies
# https://www.kaggle.com/alankritamishra/covid-19-tweet-sentiment-analysis#Sentiment-analysis
EMOJI_PATTERN = re.compile("["
                           u"\U0001F600-\U0001F64F"  # emoticons
                           u"\U0001F300-\U0001F5FF"  # symbols & pictographs
                           u"\U0001F680-\U0001F6FF"  # transport & map symbols
                           u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           u"\U00002702-\U000027B0"
                           u"\U000024C2-\U0001F251"
                           "]+", flags=re.UNICODE)

The variable is in UPPER_CASE now, because it's a pseudo-constant (Python doesn't really have constants, but it's a reminder to you and other developers that the variable should be set once and only once). It's customary to put the pseudo-constants between the imports and function definitions so you know where to look for them.
Now, the rest of the program is mostly fine already. You could use more functions, but with a program this size that would mostly be an exercise. I'd rename some of the variables, cut up the lines, use a proper docstring (you had a great start already with the comment at the start of the cleaning function) and prepare the program for re-use. After all, it would be nice to simply import from this file instead of having to copy code to the next few projects using this, wouldn't it? And we don't want to run the specifics of this program every time it's imported, so we explicitly only run it if it's not imported.
import re
import string
import nltk

import pandas as pd

from collections import Counter
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

nltk.download('punkt')
nltk.download('stopwords')

STOP_WORDS = stopwords.words()

# removing the emojies
# https://www.kaggle.com/alankritamishra/covid-19-tweet-sentiment-analysis#Sentiment-analysis
EMOJI_PATTERN = re.compile("["
                           u"\U0001F600-\U0001F64F"  # emoticons
                           u"\U0001F300-\U0001F5FF"  # symbols & pictographs
                           u"\U0001F680-\U0001F6FF"  # transport & map symbols
                           u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           u"\U00002702-\U000027B0"
                           u"\U000024C2-\U0001F251"
                           "]+", flags=re.UNICODE)

def cleaning(text):
    """
    Convert to lowercase.
    Rremove URL links, special characters and punctuation.
    Tokenize and remove stop words.
    """
    text = text.lower()
    text = re.sub('https?://\S+|www\.\S+', '', text)
    text = re.sub('<.*?>+', '', text)
    text = re.sub('[%s]' % re.escape(string.punctuation), '', text)
    text = re.sub('\n', '', text)
    text = re.sub('[’“”…]', '', text)

    text = EMOJI_PATTERN.sub(r'', text)

    # removing the stop-words
    text_tokens = word_tokenize(text)
    tokens_without_sw = [
        word for word in text_tokens if not word in STOP_WORDS]
    filtered_sentence = (" ").join(tokens_without_sw)
    text = filtered_sentence

    return text

if __name__ == "__main__":
    max_rows = 1000  # 'None' to read whole file
    input_file = 'covid19_tweets.csv'
    df = pd.read_csv(input_file,
                     delimiter = ',',
                     nrows = max_rows,
                     engine = "python")

    dt = df['text'].apply(cleaning)

    word_count = Counter(" ".join(dt).split()).most_common(10)
    word_frequency = pd.DataFrame(word_count, columns = ['Word', 'Frequency'])
    print(word_frequency)

Naturally, if you'd want a more memory-efficient version, you could cut-out all intermediate variables in those last few lines. That would make it a little harder to read though. As long as you're not reading multiple large files into memory in the same program, it should be fine.
Some of the advice I've provided comes from the PEP8, the official Python style guide. I can highly recommend taking a look at it.


Tokenize a mathematical statement string

Possible errors/suspicious statements
In def get_char_type(char), you have repeated the statement
if char.isdigit():
    char_type = 'number'

twice. This is probably unintentional.
Note: The OP has removed this error in an edit before this answer was posted.
Suggestions
Instead of explicitly checking for whitespace in your generator expression and using a continue to skip whitespace, you can filter the input string by a regex (regular expression) to remove all whitespace before you run the loop over the characters of the string. Kind of like this:
whitespace_pattern = re.compile(r"\s")
for char in whitespace_pattern.sub("",string):
    new_type = get_char_type(char)
    ...

instead of
for char in string:
    if char == ' ':
        continue  # Spaces are not included
    ...

This looks a bit better, although it might not be as performant as your original code. You will also need an import re somewhere at the top of your code.
Also, instead of that if-elif-else in get_token_type(), what about this?
def get_char_type(char):
"""
Returns a string denoting the type of char.

>>> get_char_type('x')
'letter'
"""
operators = {'*', '/', '+', '-', '=', '%', '~', '/', '&', '|', '>', '<'}
characteristics_of_token_types = {
    (lambda char: char.isdigit()): 'number',
    (lambda char: char.isalpha()): 'letter',
    (lambda char: char in operators): 'operator',
    (lambda char: len(char) == 1): 'other' #default case, if extending functionality, put any new case before this
}
for characteristic in characteristics_of_token_types.keys():
    if(characteristic(char)):
        return characteristics_of_token_types[characteristic]

Why is this better? If you want to add more types, it just becomes a matter of specifying a characteristic of a token type (via a lambda dictionary key), and a name for the type (as the lambda key's value). It makes a bit more sense to me logically, however, opinions vary.
Also, note that what I did above is somewhat along the canonical path of emulating a switch-case in Python, which is, in fact, a better fit for this problem than if-else. I was looking for something like guards in Haskell, as I've recently become a functional programming guy, but I've got to make do with Python, so this is what I could think up.
Finally, I did not bother making your token-parsing code more "functional" as I think the result would be more complicated than what you already have.
Style
You have docstrings. That's a definite plus. You also follow the proper naming conventions for methods and variables, and there is adequate commenting, so no issues there.
However, a minor peeve - do you really need that line continuation when declaring the operators list? It doesn't look like you do, the whole thing fits in a line in below 40 characters all right.


Review

You make a special branch to distinguish odd from even array lengths. if (subject.Length % 2 != 0) This is not required because getting the mid of an array can just be retrieved as (end - start) / 2. In case of an even array, you get the left index of the mid index pair. This is not a bad thing, we are not calculating a median here.
You write alot of comments // if the array count is odd. Because you are a beginner, this is ok. But try writing code in a way these obvious comments are not required. Pick good method and variable names.
You have taken the chopping part a bit literally. Array.Copy(subject, chopped, mid); is an expensive operation. Perhaps you could have worked on the source array, but played around with the start and end index instead.

Alternative

Use an algorithm that keeps refining start and end index until a match is found. This way, you don't need to make new array segments. This works for both odd and even arrays.

public static int Chop(int value, int[] subject)
{
    subject = subject ?? throw new ArgumentNullException(nameof(subject));
    if (subject.Length == 0) return -1;
    var start = 0;
    var end = subject.Length - 1;
    return Chop(value, subject, start, end);
}

private static int Chop(int value, int[] subject, int start, int end)
{
    var span = end - start;
    var mid = start + span / 2

    if (subject[mid] == value) return mid;
    if (span == 0)  return -1;

    if (subject[mid] > value)
    {
        return Chop(value, subject, start, mid);
    }

    return Chop(value, subject, mid + 1, end);
}

Test

static void Main(string[] args)
{
    Console.WriteLine(Chop(3, new[] { 2 }));
    Console.WriteLine(Chop(3, new[] { 3 }));
    Console.WriteLine(Chop(3, new[] { 3, 4 }));
    Console.WriteLine(Chop(3, new[] { -1, 3, 4 }));
    Console.WriteLine(Chop(3, new[] { 1, 2, 3, 4 }));
    Console.WriteLine(Chop(3, new int[0]));
    Console.ReadKey();
}


Your function fails if n is 0 or greater than the list size.

Also, I prefer to see one variable defined per-line:

ListNode *pre = head;
ListNode *cur = head;

And the opening brace belongs in column 0 (I guess you don't agree, but there are - or were anyway - tools that rely on this).

An alternative implementation might use a function to find the number of entries in the list and another to return a specified entry (size - n - 1, in this case). Then once you've checked that 0 < n <= size, the main function is simple - but no better than yours :-)

BTW, delete is C++, not C


It's not mandatory but it's a widely accepted guideline. Break it only if you have a good reason to do so.
No, they don't. Class should be internal (default) and static (because it has not instance methods). Main() method should be private to make clear that it won't be called outside this class but it's not mandatory (someone prefers public because it's logically called from outside).

For the other points things are more complex that a paragraph...

You can create a generator to read from standard input (see very last paragraph for a discussion about this):

private static IEnumerable<string> ReadAllInputs()
{
    while (true)
    {
        string line = Console.ReadLine();
        if (line == null)
            break;

        yield return line;
    }
}

You do not need ToLower() on input, I do not even start to mention all the problems of case insensitive comparison if not done properly: a lower case string may be different from an upper case string (even in number of characters) but they may be compared equal. Don't put yourself in trouble and let the framework do the work for you:

var counts = new SortedDictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);

Note that you do not need a SortedDictionary here, ordering may be done (in this case) when printing output. If performance matters then you should profile by yourself.

When you increment word count you also increment local variable count, not a big performance hit (and compiler may be smart enough to elide local variable) but it's about code clarity. You can do:

counts[word] = count + 1;

Or simply:

++counts[word];

Note that this innocent code ++counts[word] (as well as original counts[word] = ++count) when word doesn't exist in dictionary (TryGetValue returns false) will perform another lookup vanishing part of the benefit of TryGetValue for the first insertion! You have to explicitly call Add().

If you want you can refactor foreach loop to print results with LINQ, not a big gain (IMO), let's see how:

Console.WriteLine(String.Join(Environment.NewLine,
    counts.Select(x => $"{x.Key} {x.Value}")));

If we put everything together with then have something like this:

namespace Test {
    static class TraditionalWordCountApp {
        static void Main(string[] args) {
            var counts = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
            var wordRegex = new Regex(@"(?i)[\p{L}']+");

            foreach (var match in ReadAllInputs().SelectMany(x => wordRegex.Match(x))) {
                if (counts.TryGetValue(match.Value, out count))
                    counts[word] = count + 1;
                else
                    counts.Add(match.Value, 1);
            }

            Console.WriteLine(String.Join(Environment.NewLine,
                counts.OrderBy(x => x.Key).Select(x => $"{x.Key} {x.Value}")));
        }

        static IEnumerable<string> ReadAllInputs() {
            while (true) { // Yes, in C# this is "safe"
                string line = Console.ReadLine();
                if (line == null)
                    break;

                // No need to match any regex against an empty line
                if (line.Length == 0)
                    continue;

                yield return line;
            }
        }
    }
}

All these done you may think that...there should be another way to do it. You can use GroupBy(). Profile both versions to see which one has better performance (and the one you feel more easy to understand):

var counts = ReadAllInputs()
    .SelectMany(x => regex.Match(x))
    .GroupBy(x => x.Value, StringComparer.CurrentCultureIgnoreCase)
    .Select(x => new { Word = x.Key, Count = x.Count() })
    .OrderBy(x => x.Word);

Then you print it with:

Console.WriteLine(String.Join(Environment.NewLine,
    counts.Select(x => $"{x.Word} {x.Count}")));

One final note about word counting. It may apply or not to your case but don't forget that word is a concept with different meanings in different languages. Topic is vast but try to paste a - for example - Japanese text in Microsoft Word and check what the word count is: number of characters (another vague concept). If you have to deal with international text you may need to write specific code for different cultures.

Comments. Few notes collected from comments.

Sometimes you see this kind of code:

while (Console.In.Peek() != -1)
   yield return Console.ReadLine();

It works only if console input is redirected, when input is line buffered then it'll end immediately after first line. Nice and short but simply it doesn't work. If you really really love LINQ and you can't live without one-line functions then you may do this:

static IEnumerable<string> ReadAllInputs() {
    return Enumerable.Range(0, Int32.MaxValue)
        .Select(_ => Console.ReadLine())
        .TakeWhile(x => x != null);
}

Can we make our reader more "generic"? The obvious idea is to use it with files. Maybe yes, maybe not. First of all a console application can have piped input (from file or from another application) then we may not need this feature. If we do then we should introduce a separate class InputReader, implementation will be different for ConsoleInputReader, FileInputReader and HttpInputReader (for example); one function with a TextReader parameter will probably be the worst compromise for all our use-cases. What I'm suggesting is just to don't introduce complexity until you need it...


Perhaps you're looking for the .zfill method on strings. From the docs:

Help on built-in function zfill:

zfill(...)
    S.zfill(width) -> string

    Pad a numeric string S with zeros on the left, to fill a field
    of the specified width.  The string S is never truncated.

Your code can be written as:

def padhexa(s):
    return '0x' + s[2:].zfill(8)

assert '0x00000123' == padhexa('0x123')
assert '0x00ABCD12' == padhexa('0xABCD12')
assert '0x12345678' == padhexa('0x12345678')


Rotate a string of integers to match index

Variable name

If you were to give t a different name, you wouldn't need to comment number of tests. I suggest nb_tests.

Looping - the pythonic way

There are better ways to write :

nb_tests = int(raw_input())
while nb_tests:
    ...
    nb_tests -= 1

You could use a simple for loop.

nb_tests = int(raw_input())
for _ in range(nb_tests):

(I've used _ as a variable name because this is the convention for unused variables in Python).

Split the logic into smaller functions

At the moment, the logic related to input/output is mixed with the logic related to the actual algorithm. It would make things clearer to write proper functions to handle this properly.

def get_rotate_sequence_with_best_match(sequence):
    max_score, answer_sequence = 0, []
    n = len(sequence)
    for i in range(n):
        sequence = rotate_left(sequence)
        sequence_score = is_in_position(sequence)
        if max_score < sequence_score:
            max_score = sequence_score
            answer_sequence = sequence
        if max_score >= 0.5 * len(sequence):
            break
    return answer_sequence

nb_tests = int(raw_input())
for _ in range(nb_tests):
    n = int(raw_input())
    sequence = str(raw_input()).split()
    assert len(sequence) == n
    print(' '.join(get_rotate_sequence_with_best_match(sequence)))

See also : separation of concerns.

if __name__ == "__main__":

It is a good habit to use a if __name__ == "__main__": guard to separate your function definitions to what you actually run when you call your script. It is useful when you want to re-use your code via module import.

Tests

Now that you've re-organised a bit your code, it is much easier to write and run unit tests to ensure everything is working properly.

Based on the provided example, I have :

def run_test_on_stdin():
    nb_tests = int(raw_input())
    for _ in range(nb_tests):
        n = int(raw_input())
        sequence = str(raw_input()).split()
        assert len(sequence) == n
        print(' '.join(get_rotate_sequence_with_best_match(sequence)))

def run_unit_tests():
    seq = [3, 6, 1, 2, 4, 5]
    assert get_rotate_sequence_with_best_match(seq) == [1, 2, 4, 5, 3, 6]

if __name__ == "__main__":
    run_unit_tests()

Counting - the pythonic way

You could use sum(iterable[, start]) in is_in_position. Indeed, you could write :

def is_in_position(seq):
    return sum(int(val) == idx for idx, val in enumerate(seq, start=1))

Micro-optimisations

You don't need to always check if max_score >= 0.5 * len(sequence): : you just need to check it after updating max_score. Also, you could reuse n instead of calling len every time.

def get_rotate_sequence_with_best_match(sequence):
    max_score, answer_sequence = 0, []
    n = len(sequence)
    for i in range(n):
        sequence = rotate_left(sequence)
        sequence_score = is_in_position(sequence)
        if max_score < sequence_score:
            max_score, answer_sequence = sequence_score, sequence
            if max_score >= 0.5 * n:
                break
    return answer_sequence

Different algorithm

Generating n sequences and counting how many of the n elements are in the right position gives you an 0(n²) algorithm (at best).

A different strategy could be to look at the shift required for each number to be in the correct position. Because all numbers are in 1...n, you can compute the shift with a simple substraction and a modulus operation. Doing this for all numbers can be easily done :

print([(i - val) % n for i, val in enumerate(sequence, start=1)])

Then, you just need to see which elements occurs more often which can be done with collection.Counter.most_common.

from collections import Counter

def rotate_left(seq, shift=1):
    return seq[shift:] + seq[:shift]

def get_rotate_sequence_with_best_match(sequence):
    n = len(sequence)
    shifts = Counter([(i - val) % n for i, val in enumerate(sequence, start=1)])
    best_shift, nb_occur = shifts.most_common(1)[0]
    return rotate_left(sequence, best_shift)


Use the var keyword to declare titleElement and linkElement in this scope, otherwise they will always be global variables and you'll have no choice about it.

Using var will still put them in the global scope until you wrap this logic in a closure:

(function() {
    // var titleLink...
})();

You should still take the advice of @NebulaFox - don't use document.write.


Implementation of a new kind of smart pointer in C++

To answer my own question, in light of the disadvantages that were gathered, I guess that the usage of the proposed smart pointer would be severely limited. Hence, I would rather rely on the flexibility of the standard smart pointers, especially through the use of std::make_shared.


SQL Stored Procedure Get Distinct and Update

Consistency

You have this:

    with cnt as (
       SELECT
         1 as cntAll
         , case WHEN CurrentAlertStatus = '0' then 1 else 0  end as cnt1
         , case WHEN CurrentAlertStatus = '1' then 1 else 0  end as cnt2
         , case WHEN CurrentAlertStatus = '2' then 1 else 0  end as cnt3
         , case WHEN CurrentAlertStatus = '3' then 1 else 0  end as cnt4
       from [TblTableCountFrom] where EmployeeID = @EmployeeID

And this:

    SELECT @StatusTotal = sum(cntAll),
      @Status0  = sum(cnt1),
      @Status1  = sum(cnt2),
      @Status2  = sum(cnt3),
      @Status3  = sum(cnt4)
      FROM cnt;

While both styles of formatting are perfectly acceptable, it's better to sick with the same throughout your code for readability.

Same for this:

    DECLARE @StatusTotal AS Int

And this:

    DECLARE @EmployeeID  AS NvarChar(10);

It works with or without a semicolon in this case, try to stick to one method.

The elephant in the room

Cursors are very slow. Especially using a bunch of variables with it. I understand you were experimenting with a function of SQL you are new to, and that's great. We all do that, play with our shiny new toy.

However, for something that's production and that will get called regularly, efficiency is key. Your clients won't care how cool your code looks, especially if it takes longer to run.

It is very rare that you actually need a cursor. Think about it this way. If you have 100 employees in your table, then it is running the query 100 times instead of once. Imagine 5000 or 50000 employees how long this would take.

I commented out all sections I think you could safely dispense with for better efficiency:

    USE [database]
    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    Alter PROCEDURE [dbo].[spSummary]
        -- Add the parameters for the stored procedure here
    AS
    BEGIN

    DECLARE @StatusTotal AS Int
    DECLARE @Status0 AS Int
    DECLARE @Status1 AS Int
    DECLARE @Status2 AS Int
    DECLARE @Status3 AS Int

    --Cursor to loop through
    DECLARE @EmployeeID  AS NvarChar(10);

    /* DECLARE propCurs CURSOR FOR
    SELECT  EmployeeID FROM [TblTableList]

    --Open Loop Code
    OPEN propCurs;
    FETCH NEXT FROM propCurs INTO @EmployeeID
    WHILE @@FETCH_STATUS = 0
    --Now do repeated code

      BEGIN */

     -- SELECT @StatusTotal = COUNT(ID) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID
     -- SELECT @Status0 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '0'
     -- SELECT @Status1 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '1'
     -- SELECT @Status2 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '2'
     -- SELECT @Status3 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '3'

    with cnt as (
       SELECT
         1 as cntAll
         , case WHEN CurrentAlertStatus = '0' then 1 else 0  end as cnt1
         , case WHEN CurrentAlertStatus = '1' then 1 else 0  end as cnt2
         , case WHEN CurrentAlertStatus = '2' then 1 else 0  end as cnt3
         , case WHEN CurrentAlertStatus = '3' then 1 else 0  end as cnt4
       from [TblTableCountFrom] where EmployeeID = @EmployeeID
    )
    SELECT @StatusTotal = sum(cntAll),
      @Status0  = sum(cnt1),
      @Status1  = sum(cnt2),
      @Status2  = sum(cnt3),
      @Status3  = sum(cnt4)
      FROM cnt;
        -- Check if ID Exists

        --HERE NEED TO CHECK IF EXISTS OR SHOULD I WIPE THE TABLE AT THE START?
        IF EXISTS (SELECT EmployeeID FROM [TblTableCount] WHERE @EmployeeID = EmployeeID)

            UPDATE [TblTableCountFrom]Count
            SET StatusTotalCount = @StatusTotal, Status0 = @Status0, Status1 = @Status1, Status2 = @Status2, Status3 = @Status3
            WHERE EmployeeID = @EmployeeID
          Else
            INSERT INTO [TblTableCount]
            (EmployeeID, StatusTotalCount, Status0, Status1 , Status2, Status3) VALUES (@EmployeeID, @StatusTotal,@Status0, @Status1, @Status2,@Status3 )

        /* END

        -- Now we bookend the loop code

        FETCH NEXT FROM propCurs INTO @EmployeeID */

    END

    --Tidy up and close loop code
    /* CLOSE propCurs;
    DEALLOCATE propCurs; */

Also!

Do what @ckuhn203 said about a view.


Taking text from a file and formatting it

You are doing a lot of unnecessary work. Why split each row only to join it with single spaces and then split it again by those single spaces?

Instead, here is a list comprehension that should do the same thing:

def get_workload(file_name="workload.txt"):
    with open(file_name) as f:
        return [[float(x) for x in row.split()] for row in f]

This uses the fact that files are iterable and when iterating over them you get each row on its own.

If this is still too slow (or e.g. too large to fit into memory), then you need to process each row separately. For this you would make this a generator of processed lines:

def get_workload(file_name="workload.txt"):
    with open(file_name) as f:
        for row in f:
            yield [float(x) for x in row.split()]


I am going to suggest a few improvements.

Most of the principles for code quality apply just as well to test code as it does to production code:
Your tests should follow Single Responsibility Principle. A test should ascertain one feature; such that any change or discovery or addition of a feature does not cause you to fix many unrelated tests. Ideally any bug introduced will cause one test to fail and that test failure will direct the programmer to the cause of the bug.

You should use Intention Revealing Names. The names of your tests should tell the reader of the tests what is being tested.

For example Implementing a Role Provider says: "CreateRole method;
Takes as input the name of a role and adds the specified role to the data source for the configured ApplicationName." One test case for that spec could be:

 public void WhenICreateARoleItExists() {
        roleProv.CreateRole(A_VALID_ROLE_NAME);

        Assert.IsTrue(roleProv.RoleExists(A_VALID_ROLE_NAME));
 }

This code is derived from your first assertion. Notice removal of code related to other assertions made the test more readable.

You can initialize your System Under Test in a [SetUp] method and assign it to a field, here roleProv, so that common initialization code does not clutter the reader's view. You should also extract repeated constant values, here A_VALID_ROLE_NAME,  to const members, and name them as descriptive as you can.

You should also test that what your system should not do. For example, the document says : "You should throw a ProviderException if the specified role name already exists for the configured ApplicationName."

  public void MultipleRolesCannotBeCreatedWithSameName() {
        var sameName = A_VALID_ROLE_NAME;
        roleProv.CreateRole(sameName);

        Assert.Throws<ProviderException>(delegate {roleProv.CreateRole(sameName);});
  }

Any unexpected exception should not be caught and indicates a broken test. Your test runner should , and most probably does, log its message and stack trace. Any expected exception should not cause the test to fail. You can remove your try/catch above.

I noticed that you write the values to the Trace if a collection is  returned from a tested method. That is totally useless. If a test does not Assert, it is not a test. A test should fail when the functionality it is testing is not working.

 // Names are just to give you an idea
 public void WhenIAddSomeUsersToSomeRolesTheirRolesIncludeAllOfThoseRoles() {
        // Given some users
        var userNames = new string[] { A_VALID_USER_NAME,  ANOTHER_VALID_USER_NAME};
        foreach(var userName in userNames) {
             createUserWithName(userName);
        }

        // And some roles
        var roleNames = new string[] { A_VALID_ROLE_NAME,  ANOTHER_VALID_ROLE_NAME};
        foreach(var roleName in roleNames) {
             createRoleWithName(roleName);
        }

        // When I add those users to those roles
        roleProv.AddUsersToRoles(userNames, roleNames);

        // Each users roles contain all of those roles
        // This could be done more idiomatically by someone more familiar with C#
        foreach(var userName in userNames) {
             Assert.That(roleNames, Is.SubsetOf(roleProv.GetRolesForUser(sUsername)));
        }
 }