A few suggestions for general code quality:

If your class only does one thing and it doesn't store any values, it should be a function. Redpy only downloads images from reddit and stores values to achieve exactly this, which you could do in a function. Using a class can have unforeseen consequences.
Choose descriptive names for variables and functions. _getImages does not actually get the images, it returns a list of links of images. In this method, you have images = [] #contains links of images. The comment could have been avoided if you would have chosen image_links as name.
If you split your code up into methods or functions, everything belonging to one task should be inside it. The removal of 'amp;' in every image_link does not belong in _DownloadFiles, it should be in _getImages. download gets unnecessarily separated into _DownloadFiles and _DownloadFiles doesn't generally download files, but it could if some of its functionality got relocated elsewhere.
Clean up your code: there are unnecessary line breaks after _DownloadFiles and a redundant return True in createFolder.
Don't catch general Exceptions, be more specific. In _getImages, you should just look out for KeyErrors. Exceptions in request.get on the other hand are not handled although they possibly should be.
The pattern of looping over a list with a counter (index in your code) in _DownloadFiles can be simplified with enumerate.
When working with files, it is more elegant to use a context manager.

Possible bugs:

subreddit.strip('/') just returns a new string that you would have to assign to a new variable. In your code, the value of subreddit remains unchanged.
self.user gets updated every time download is called. If this happens multiple  times, self.user becomes a dict encapsulating a dict encapsulated a dict...
If something goes wrong when extracting links in _getImages, less links than expected get returned.
If your folder already contains images, they will be overwritten.

Concerning PEP8:

A few of your lines are longer than 80 characters. Try to split them up, either by implementing the same logic over multiple lines or by breaking the line up.
In PEP8, functions and methods are in snake_case.

Nit-picky stuff:

You could just use an empty string as default argument for sort_option. Strings are immutable, so you don't have the problem of mutable default arguments.
I don't see why you would import requests as _requests and os as _os
There is no need to construct an absolute file path. f'{_os.getcwd()}/red_media/{index}.jpg' could become f'red_media/{index}.jpg'

Here is my attempt at solving this problem:

import requests
import os

def get_image_links(json, N):
    '''returs a list of the first <N> links to reddit images found in <json>'''
    try:
        children = json['data']['children']
    except KeyError:
        return []

    # append links from children until N are found
    image_links = []
    for child in children:
        try:
            image_link = child['data']['preview']['images'][0]['source']['url']
        except KeyError:
            continue

        image_link = image_link.replace('amp;', '')
        image_links.append(image_link)

        if len(image_links)==N:
            break

    return image_links

def download_files(file_links, folder_name='data', file_extension='jpeg'):
    '''downloads files from <file_links> into subfolder ./<folder_name>/'''

    # create subfolder if it does not exist
    if not os.path.exists(folder_name):
        os.mkdir(folder_name)

    # download files
    for i, file_link in enumerate(file_links):
        try:
            res = requests.get(file_link)
        except requests.exceptions.RequestException:
            print(f"Unable to download {file_link}")
            continue
        if not res.ok:
            print(f"Error {res.status_code} when requesting {file_link}")
            continue

        file_path = os.path.join(folder_name, f'{i}.{file_extension}')
        with open(file_path, 'wb') as file:
            for chunk in res.iter_content(100000):
                file.write(chunk)

def download_reddit_images(user, subreddit, N=5, sort_by='',
                           folder_name='red_media'):
    '''
    downloads the first <N> images of <subreddit> sorted by <sort_by>
    (''/'new'/'hot'/'top') into subfolder ./<folder_name>/
    '''

    json_url = ('https://www.reddit.com/r/' + subreddit.strip('/') + '/'
                + sort_by + '.json')

    try:
        res = requests.get(json_url, headers={'user-agent':user})
    except requests.exceptions.RequestException:
        print(f"Unable to get {json_url}")
        return

    if not res.ok:
        print(f"Error {res.status_code} when requesting {json_url}")
        return

    image_links = get_image_links(res.json(), N)
    if not len(image_links):
        print("Unable to find any images")
        return

    download_files(image_links, folder_name=folder_name, file_extension='jpeg')

if __name__=='__main__':
    download_reddit_images('', 'all')

The problem of overwriting existing images persists. A solution would be to use the original filename from reddit that is included in the url.


While I don't entirely agree with not using path, I will try to keep my answer unbiased. This is because using a path is much more developer-friendly, and opens up more options to do what you ask.

Keep your code styled, with--that's right--tabs

Using tabs in your code to indent it makes it a lot more readable and allows you to see the structure much more easily. You can see the difference in the following two code examples:

Before:

<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<mask id="a">
<circle cx="50" cy="50" r="50" fill="#fff"/>
<rect x="50" width="5" height="100%"/>
</mask>
<rect width="100" height="100" fill="gray" mask="url(#a)" />
</svg>

After:

<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
    <mask id="a">
        <circle cx="50" cy="50" r="50" fill="#fff"/>
        <rect x="50" width="5" height="100%"/>
    </mask>
    <rect width="100" height="100" fill="gray" mask="url(#a)" />
</svg>

XMLNS isn't needed

Unless you're using XHTML, XML, or any other kind of page that requires an XML parser, then XMLNS is not needed. Since inline SVG is a recent development in HTML5, this is never really needed. I'm also going to add that you added the tags HTML and CSS to this, so I'll assume you don't want XMLNS.

Your final code should look something like this:

<svg width="100" height="100">
    <mask id="a">
        <circle cx="50" cy="50" r="50" fill="#fff" />
        <rect x="50" width="5" height="100%" />
    </mask>
    <rect width="100" height="100" fill="gray" mask="url(#a)" />
</svg>

There isn't much more you could optimize without using path. Using path would allow you to use things like fill-rule="evenodd", and many other options.

EDIT:

@somethinghere asked me to expound a bit on how to use the extra features available with path that would allow you to do shape cutouts much more easily.

fill-rule="evenodd"

This can be used on a <path> element and have the <path> element have multiple shapes, if the shape number is even in the path call, it will define an outside point. If it's odd, it'll define an inside point. This allows you to define two path segments, your circle and your rectangle, and have the rect mark the inside point. This is an implementation using fill-rule="evenodd" in your scenario:

<svg width="100" height="100">
    <path d="M50 0 h 5 v 100 h -5 z M0 50 a 50 50 0 1 1 0 0.0001 z" fill-rule="evenodd" fill="gray" />
</svg>

Use a <clipPath>. This works similar to the <mask> tag you used and doesn't need a <path> element either:

<svg width="100" height="100">
    <clipPath id="myClip">
        <rect x="0" y="0" width="50" height="100%" />
        <rect x="55" y="0" width="50" height="100%" />
    </clipPath>
    <circle cx="50" cy="50" r="50" fill="gray" clip-path="url(#myClip)" />
</svg>

You could use a <path> element and define the entire shape if needed, but that seems a bit counter intuitive unless you're using a tool to make the SVG instead of drawing it by hand.


new byte[0x1f80]

I think using decimal would be more readable here. And I don't understand why is your buffer 8096 bytes, usual sizes are powers of two, like 8192.

IpAddress = "192.168.1.65"

This looks like a perfect example of something that should be configurable, not set in stone. You should accept the IP address in the constructor, like you already do with port number.

public abstract void Receive(byte[] buffer);
public abstract void Error(Exception e);

I'm not sure I like the use of inheritance here. I think using events, or something like that would make more sense here.

_socket.BeginConnect(…)

I don't like that you're using the old Asynchronous Programming Model when you could (and do in other parts of your code) use async-await. Unfortunately, Socket doesn't expose awaitable methods, but there are ways around that.

private async void Authenticate(IAsyncResult ar)

I think Authenticate is not a very good name for this method, it does much more than just authentication.

throw new Exception("not^authenticated")

You shouldn't throw Exception, you should instead create a custom class that derives from Exception and use that. And the exception message should be human-readable, not some error code like it seems in your case. If you need to differentiate different errors, either have different exception types for them, or add a property for that to your custom exception.

if (size == 0) throw new Exception("invalid^size");

When ReadAsync() returns 0, it's not invalid size, it means the end of the stream was reached, so you should act accordingly.

Native.MemoryCopy(Buffer, buffer, (uint)buffer.Length);

Why are using some custom memory copying method here? Do you have some reason for not using Buffer.BlockCopy()? Also, why are you even doing the copying here? It seems you class is intended only for limited use (since you have a constant IP address), so couldn't you make sure the buffer isn't used after Receive() returns, so you didn't have to copy at all?

return true;

I'm no expert on security, but I think you should perform at least some checks of the certificate here. Otherwise, your class isn't really a “secure stream”.

MessageBox.Show(…);

You shouldn't mix code like this with GUI code, they should be separated.


Is there a better way of making an NSString with many argument values?

You could use NSMutableString. It has appendString method which you could use to create string by appending other strings.
For example:

NSMutableString *mutableString = [NSMutableString stringWithFormat:@"%@", someString];
[mutableString appendString:otherString];
// and so on...

NSMutableString also has the stringByAppendingString method, but appendString method is more memory friendly.

You can also do this:

NSString *exampleString = @"Multiple " @"string " @"example";

NSString can even be built using NSArray:

NSArray *stringArray = [NSArray arrayWithObjects:@"Another", @"string", @"example", nil];
NSLog(@"%@",[pathArray componentsJoinedByString:@"\n"]);
// Log wold look like
// Another
// string
// example


C# and unity. Moving an object to a target and destroy target once we're close

Welcome to Code Review!
I'm not too familiar with Unity, so I can't really comment or offer advice on Unity-specific things.
There are still a few places where I feel like your code could be improved however.
Whitespace
While I generally prefer to keep my code not too dense, I recommend never having more than one blank line in a row (except maybe if you want to separate a block of imports or usings from the rest of the code); some editors will even automatically remove any consecutive blank lines when you format your document.
Similarly, that blank line at the end of your Distance() method doesn't serve any purpose, so I would just remove it, or maybe move it right below your aPos and bPos declarations.
AreClose() method
Your AreClose() method could be rewritten in a much shorter and cleaner way, like so :
private static bool AreClose(GameObject a, GameObject b)
{
    double result = Distance(a, b);
    return (result < 2.5); // random magic number for now
}

That's because the expression result < 2.5 itself evaluates to a boolean, so there's no need to check whether its value true or false, you can simply return it.
You could further shorten it to...
private static bool AreClose(GameObject a, GameObject b)
{
    return Distance(a, b) < 2.5; // random magic number for now
}

...since, in my opinion, the variable result doesn't add anything to the readability or the clarity of the code. Seeing Distance(a, b) < someMagicNumber is clear enough on its own.
You could go even further and take advantage of C#'s expression body definitions, like so
private static bool AreClose(GameObject a, GameObject b) => Distance(a, b) < 2.5; // random magic number for now

...which doesn't look too great here because of that comment. I would recommend you put that magic number into a const variable, either declared inside AreClose() or as a class variable. This will make your code easier to modify in the future, and also allows you to give it a meaningful name like MIN_DISTANCE.
private static bool AreClose(GameObject a, GameObject b) => Distance(a, b) < MIN_DISTANCE;

Distance() method
Like I said earlier, I'm not too familiar with Unity, but I'm pretty sure it has a built-in method for computing the distance between two vectors, like so Vector3.Distance(aPos, bPos).
There's nothing inherently wrong with doing it yourself if you're just trying to learn and get familiar with a new language or concept, but if you're looking for optimal performance or accuracy, I would recommend making sure there isn't already a function that does what you need before trying to reinvent the wheel -although in this specific case it's probably not too important.
Additionally, I would avoid using Math.Pow() when you only want to square a number, as it's quite an expensive operation compared to simply doing (aPos.x - bPos.x) * (aPos.x - bPos.x). This is because Math.Pow() needs to be able to handle non-integer exponents and (probably) uses Taylor series (https://en.wikipedia.org/wiki/Taylor_series) to compute powers for arbitrary exponents, even if your exponent happens to be 2. So you can just compute the square yourself, which should significantly improve performance.
You could also create a DistanceSquared() method, and compare it with MIN_DISTANCE * MIN_DISTANCE, which is equivalent to comparing Distance() and MIN_DISTANCE. This allows you to avoid using Math.Sqrt(), which is, again, a rather slow operation. Then you can rewrite Distance() like this, if you still want it :
public static double Distance(GameObject a, GameObject b) => Math.Sqrt(DistanceSquared(a, b));


Potentially superfluous iOS interface system

There is one performance issue that can be addressed quite easily, and that is when we're even bothering to respond to the notification.

This if statement can be completely eliminated:

if ([notification.name isEqualToString:State] && [self.stateDictionary count]!=0)

The left half of the && can be eliminated by registering only for a specific notification.  The right half of the && can be eliminated by registering/unregistering for the notification based on this property we're checking.

First, let's take care of registering/unregistering at appropriate times.

We only care about this notification if there's something in our stateDictionary, right?  So, let's unregister when it's empty, register when it's not.

- (void)setStateDictionary:(NSDictionary *)stateDictionary {
    _stateDictionary = stateDictionary;
    if ([stateDictionary count] > 0) {
        // register for notification
    } else {
        // unregister for notification
    }
}

Now our code is already better because our object is only getting a message from the notification center if our object is in a state where it would care about the notification.

Now, as for registering only for this specific notification.  That'd look something like this:

NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
[notifCenter addObserver:self
                selector:@selector(receiveNotification:)
                    name:State
                  object:nil];

We can make this better still if we have a reference to the specific object that might post the notification (if there's only one) and only listen to notifications of that type.

The important bit here is that now we're only listening to notifications that have the notification name we care about and we're only listening when our object is in a state that we would care about the notification.  The if statement itself isn't a particularly expensive bit of code, however isEqualToString: isn't a particularly cheap method either, and there's no reason to run this (effectively twice, because NSNotificationCenter is already going to look at the notification names when determining who to send it to).

We can now refactor our method which responds to the notification into simply this:

- (void)receiveNotification:(NSNotification *)notification {
    NSDictionary *dictionary = notification.userInfo;
    NSString *stateId = dictionary[StateId];
    NSString *sender = dictionary[Sender];

    [self syncStateWithId:stateId andSender:sender];
}

And we'll get the same result.

So this code will run faster when it does receive the notification (because it skips the if check), and in general you'll be running faster overall because all the times that this method ran and the if check failed in the past, now the method will simply never be called and we'll never run through the if check.


Since there is already a function called elem, I wouldn't call the element the same. There's no way that those two can get mistaken though, since their types differ. So you're safe at that point. However, you will still get a warning on -Wall.

Next, you call your list h. Lists are usually called xs (one x, may xses), which makes it a little bit harder to catch than it needs to be. We can also split the list into the three parts at the same time:

search :: (Ord a) => a -> [a] -> Maybe Int
search _ [] = Nothing
search n xs
  | elem == n = Just index
  | elem < n  = (+index) . (+1) <$> search n bs
  | otherwise = search n as
  where index = length xs `quot` 2
        (as,elem:bs) = splitAt index xs

This removes the need to traverse the list again just to get the correct init/tail, however it's harder to read, so it's up to you. Also, I really like to have the compiler yell at me if I forgot a case in my guards. For example, GHC will happily accept

search :: (Ord a) => a -> [a] -> Maybe Int
search _ [] = Nothing
search n xs
  | elem == n = Just index
  | elem < n  = (+index) . (+1) <$> search n bs
  where ...

even with warnings. With compare elem n, we get warnings:

search n xs = case elem `compare` n of
    EQ -> Just index
    LT -> (+index) . (+1) <$> search n bs
    -- third missing, GHC warns us
  where ...

But that's more or less a personal preference. A major nitpick though is that you take the length of the list in every iteration. You can get rid of that if you write another function:

search :: (Ord a) => a -> [a] -> Maybe Int
search n ys = go (length ys) ys
  where
    go _ [] = Nothing
    go l xs = ...


Getting the first selected item from a list of Backbone models

I assume you want to return the first model from an array of models. Since you're using Backbone, you'll be able to use Underscore. So, if first model has length, return it:

    function getItems() {
        var model1 = new Backbone.Model({
            firstName: "Wassily",
            lastName: "Kandinsky"
        });

        var model2 = new Backbone.Model({
            firstName: "Jhon",
            lastName: "Doe"
        });

        var model3 = new Backbone.Model({
            firstName: "Jane",
            lastName: "Doe"
        });
        return [model1, model2, model3]

    }

    function getSelectedItem() {
        var isFilled =  _.map(getItems(), function (s) {
            return s.toJSON();
        });
        return isFilled.length ? isFilled[0] : null;
    }

    console.log(getSelectedItem().firstName);

I do not use Util since I don't know what that is but it shoudn't be neccesary. You can test it here: http://jsfiddle.net/jgauna/Lnmsp6jf/


I would recommend something closer to a Knuth shuffle, where you swap items in place in the array, rather then allocating a new one.

This is untested and is based on the Fisher-Yates shuffle:

func (deck *Deck) Shuffle() {
    rand.Seed(time.Now().UnixNano())

    for i := len(deck.Cards)-1; i > 0; i-- {
        j := rand.Intn(i+1) // i+1 rather than i; the upper bound is not inclusive
        deck.Cards[i], deck.Cards[j] = deck.Cards[j], deck.Cards[i]
    }
}

Unrelated to shuffling, you should also check out bucketed flashcards.  Consider the Leitner system.


You re-calculate string length every iteration of every loop:

    for(i =0;i<strlen(strMain);i++){
        for(j =0;j+i<strlen(strMain);j++){

It does not look like the string changes length. So calculate it once.

    size_t  size = strlen(strMain);
    for(i =0; i < size; i++){
        for(j =0; j+i < size; j++){

Or don't even calculate it at all. The string is terminated when you reach the '\0' character so just look for that

    for(i =0; strMain[i]; i++){
        for(j =0; strMain[j+i]; j++){

The other thing I noticed is that you are checking the string against itself. Which is not similar to the description you give above (where you are comparing two different strings).


Your code is easy to understand and very performant.

Some improvements:

String for start / end tag could be stored as constant. That has the advantage that it can be changed on one central location and the length of the string can be accessed like i += START_TAG.Length
When using a StringBuilder instead of of the char array newText, the running variable 'j' can be dropped.
The 2 code parts

            if (text.IndexOf("<upcase>", k) < 0)            // check if there is
            any <upcase> tag
            {                                               // if no, copy everyting
                while (i < text.Length)
                {
                    textNew[j++] = text[i++];
                }
            }
            else
            {
                while (i < text.IndexOf("<upcase>", k))     // if there is an <upcase> tag, copy letters until the tag
                {
                    textNew[j++] = text[i++];
                }

                i += 8;                                     // move index i to the position right next to the <upcase> tag
                k = i;
            }

and

            if (text.IndexOf("</upcase>", k) < 0)           // check if there is any </upcase> tag
            {                                               // if no, copy everyting in CAPITAL letters
                while (i < text.Length)
                {
                    textNew[j++] = Char.ToUpper(text[i++]);
                }
            }
            else
            {
                while (i < text.IndexOf("</upcase>", k))    // if there is an </upcase> tag, copy letters in CAP letters until the tag
                {
                    textNew[j++] = Char.ToUpper(text[i++]);
                }

                i += 9;                                     // move index i to the position right next to the </upcase> tag
            }

are very simlar. Probably it is possible to create one more generic code fragment that coveres both cases.

Since your solution is still understandable for such a simple use case, it will fast become unmaintainable if the use case becomes more complex. Therefore, it makes sense to think about a more abstract OOP concepts to model the solution.

One alternative impl. (that is probably over engineered for the given problem) gives an idea how a more object oriented design could look like:

        public class Tag
        {
            private readonly Func<char, char> map;
            public Tag(string start, string end, Func<char, char> map)
            {
                this.Start = start;
                this.End = end;
                this.map = map;
            }

            public string Start { get; }
            public string End { get; }
            public char Map(char input) => this.map(input);
        }

        public class TagProcessor
        {
            private readonly Tag tag;
            private readonly StringBuilder output = new StringBuilder();

            private string input;
            private bool isTagOpen;
            private int index;

            public TagProcessor(Tag tag)
            {
                this.tag = tag;
            }

            public string Process(string input)
            {
                this.input = input;
                this.index = 0;
                this.isTagOpen = false;
                this.output.Clear();

                do
                {
                    var tagProcessed = this.TryOpenTag() || this.TryCloseTag();
                    if (!tagProcessed)
                    {
                        this.ApplyCurrentChar();
                    }
                }
                while (this.MoveNext());

                return output.ToString();
            }

            private bool IsEndTag() => input.IndexOf(tag.End, this.index) == this.index;

            private bool IsStartTag() => input.IndexOf(tag.Start, this.index) == this.index;

            private bool MoveNext()
            {
                index++;
                return index < this.input.Length;
            }

            private void ApplyCurrentChar()
            {
                var inputChar = this.input[this.index];
                var transfomed = this.isTagOpen ? tag.Map(inputChar) : inputChar;
                this.output.Append(transfomed);
            }

            private bool TryOpenTag()
            {
                if (!isTagOpen && IsStartTag())
                {
                    this.index += this.tag.Start.Length - 1;
                    this.isTagOpen = true;
                    return true;
                }

                return false;
            }

            private bool TryCloseTag()
            {
                if (isTagOpen && IsEndTag())
                {
                    this.index += this.tag.End.Length - 1;
                    this.isTagOpen = false;
                    return true;
                }

                return false;
            }
        }

        public static void Main(string[] args)
        {
            var processor = new TagProcessor(new Tag("<upcase>", "</upcase>", char.ToUpper));

            var test = new[]
            {
                "abc<upcase>test</upcase>",
                "abc<upcase>test",
                "abc<upcase></upcase>test",
                "abc<upcase>test</upcase>test",
                "abc<upcase>te<upcase>st</upcase>test",
                "a</upcase>bc<upcase>te<upcase>st</upcase>te</upcase>st",
            };

            foreach (var t in test)
                Console.WriteLine(t + ": " + processor.Process(t));
            Console.ReadLine();
        }

The advantages are, that this solution remains readable if the complexity grows (e.g. more tags were added) and it allows to change / extend the logic without understanding the whole parsing logic. Further more, each method has a single pupose which increases comprehensibleness.


To format the data nicely for printing you can use the ljust method:

print "Country".ljust(15),"Population"
for country in countries:
    print country["Name"].ljust(15), country["Population"]


This is how you end up with projects with forms with 25,000 lines of code.  It's also how you end up with duplicated code.

Your (poorly named) Form1 class should only be responsible for stuff directly related to the form it's displaying.  Otherwise, complicated forms end up with even more complicated code.

And what happens if you have another form that wants to do some of the same FizzBuzz things?  Well, now you have to copy & paste all of your code.  As soon as you start to copy & paste anything while programming, that should be a massive red flag that you're absolutely doing something wrong.  You need to take a step back and figure out how to do it without copy & pasting.

In this case, we need a separate class to hold all of our FizzBuzzing logic.  Now, any form or anything else, that wants to use our FizzBuzz code instantiates our FizzBuzz class and uses its method (although perhaps, we've implemented as a static class and we just call its methods without instantiation).


def game(word):
    guesses = 0
    while True:
        user_string = prompt("What do you think the word is? ",
                            lambda s: len(s) == len(word),
                            "Please guess a {}-letter word.".format(len(word)))

        if user_string == word:
            print("You WIN!")
            break

        print([handle_letter(user_string, word, i) for i in user_string])

        guesses += 1
        print ("You have guessed {} times.".format(guesses))

def handle_letter(user_string, word, i):
    if user_string[i] == word[i]:
        return "[" + user_string[i] + "]"
    elif user_string[i] in word:
        return "(" + user_string[i] + ")"
    else:
        return user_string[i]

def prompt(statement, condition, warning):
    user_string = input(statement)
    while not condition(user_string):
        print(warning)
        user_string = input(statement)
    return user_string

def main():
    game("tiger")

if __name__ == '__main__':
    main()

Assuming you are familiar with functions, there should be only two things here that stand out as "weird": the lambda and the list comprehension (this line: print([handle_letter(user_string, word, i) for i in user_string])).

lambdas are just anonymous functions, meaning they are functions that don't have name. I could have easily instead written:

def is_correct_length(user_string):
    return len(user_string) == len(word)

and replaced the lambda line with is_correct_length. It's just shorter this way.*

The list comprehension is a huge code-lines win, but I'd rather you just read http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions than me explain it to you.

*Actually this approach would not work because word is not in scope for the sub-function unless you define it inside of game. lambda has the advantage here of having access to all the variables that in the scope of game, including word, which makes life easier.

If you reeeealy wanted to avoid the lambda you could put the definition of is_correct_length indented and inside of the definition of game, but this is probably not a good move stylistically.

It just occurred to me that this is actually MORE lines of code than you originally had, but I'd say it's better code because it's much more modular. The prompt function, for instance, seems ridiculously useful for games like this one and you can use it everywhere.

If you remove the main() and ifmain wrappers and put thing on one line that I have put on two, you could probably make it shorter, though this is usually not a good idea because readability it far more important than lines of code.

(If you really want to make it shorter - no holds barred - you could do this:

print(["[" + user_string[i] + "]" if user_string[i] == word[i] else "(" + user_string[i] + ")" if user_string[i] in word else user_string[i] for i in range(len(user_string))])

Instead of the current line in game and completely remove handle_letter. However, this is much harder to read so I would advise against it.)


Finding the postion of a substring in a string

Small improvement here:

Your IsFound method is making an assumption that stringTwo is longer than stringOne. Might I suggest:

Math.Abs(stringOne.Length - stringTwo.Length)

This way length will never be negative and the for loop will always execute.


Correct Implementation of Custom UIView into ViewController Programatically

A couple of thoughts:

It is curious to do some of the configuration of the subview's within your custom class (e.g. the frames) and other portions (e.g. numberOfLines and sizeToFit) in the view controller. If I were going to have this UIView subclass, then I'd encapsulate all the presentation details within that class. As it is, if the UI isn't quite right, you'll never quite know which class you have to take a look at.
It is curious to use numberOfLines of zero, but then to use hard-coded frame sizes. (Sure, you sizeToFit, but don't adjust the origin.) If one label changes size, wouldn't you want to move the other controls accordingly? You might contemplate specifying preferredMaxLayoutWidth, too.
In this day and age of differing device dimensions, it is curious to see hard-coded frame sizes at all. I'd probably implement auto layout unless you had some compelling reason not to. And even if I didn't use auto layout, I'd still specify the autosizing masks.
I generally give my subviews weak references because the process of doing addSubview already maintains a strong reference, and it's not clear your really need two strong references. (Clearly, you have to temporarily use a local variable when instantiating the label, if you go this route.)

Clearly you're not contemplating it at this point, but let's say you ever wanted to do [self.tagLabel removeFromParentView]. Would you also want to have to remember to do self.tagLabel = nil as well?

It's not a big deal, but I tend to follow the NIB/storyboard model that I don't generally maintain strong references to subviews: The only strong reference I'd maintain would be to the root view.
You're never setting the frame for your ratingView. I might confirm the clipping and content mode, too.
If you're going to have this UIView subclass, it doesn't feel like the view controller should be playing around with which image to show in the rating view. The view controller should probably just tell the UIView subclass what the rating is, and that subclass should take care of the presentation of the appropriate rating image.
Rather than using fixed fonts, if this was an iOS 7+ target, I'd consider using Dynamic Type.
If [NSURL URLWithString:self.movie.fanArt] is in the local file system, you can get away with doing that main thread, but if it's a remote URL, then definite retrieve that image asynchronously.
In terms of having custom UIView subclass at all, I'm not sure there's enough utility in this subview to warrant a subclass. Perhaps, once you start incorporating the above points, there might be enough substance to make this worth while, but I'm not sure your existing code sample justifies it.


Seems OK to me.

However, it might be nice to add a "macro" to let you skip the I18n. and just use t like you do in views.

And you can add some extra checks while you're at it, since you'll i18n want it to make noise when testing.

For instance, you could add a file like spec/support/macros/i18n_macros.rb with the following:

module I18nMacros
  def t(*args)
    I18n.translate!(*args)
  end
end

Using translate! will cause i18n to raise an exception if the translation you're looking for doesn't exist.

Then include it in spec_helper.rb

config.include I18nMacros

or alternatively include it for type: :feature specs only.

And if you haven't already (it's default for newer versions of Rails), set i18n to raise exceptions in your views (the above will only raise on the stuff in your tests). Put something like this in config/environments/test.rb

# Raises error for missing translations
config.action_view.raise_on_missing_translations = true


as I mentioned in my comment I was playing with a LayoutManager. Based off of what you are hoping to achieve I would suggest going down this path as you are trying to control how the components are laid out which is what the LayoutManager does. Here is a version that works, but could stand to be cleaned up a bit more, and adapted a tad more to cover more scenario's (padding, margins, isVisible...etc)

public class VerticalLayout implements LayoutManager {
    private final Dimension minimumSize = new Dimension();

    @Override
    public void addLayoutComponent(String name, Component comp) {
    }

    @Override
    public void removeLayoutComponent(Component comp) {
    }

    @Override
    public Dimension preferredLayoutSize(Container parent) {
        Dimension dimension = new Dimension(getTotalPaddingWidth(parent), getTotalPaddingHeight(parent));
        minimumSize.height = dimension.height;
        for(Component c :parent.getComponents()){
            if(!c.isVisible()){
                continue;
            }

            Dimension preferredSize = c.getPreferredSize();
            dimension.height += preferredSize.getHeight();
            if(preferredSize.width > dimension.width){
                dimension.width = preferredSize.width;
            }
        }
        minimumSize.width = dimension.width;
        return dimension;
    }

    private int getTotalPaddingWidth(Container container) {
        Insets padding = container.getInsets();
        return padding.left + padding.right;
    }
    private int getTotalPaddingHeight(Container container){
        Insets padding = container.getInsets();
        return padding.top + padding.bottom;
    }
    @Override
    public Dimension minimumLayoutSize(Container parent) {
        return minimumSize;
    }

    @Override
    public void layoutContainer(Container parent) {
        Insets padding = parent.getInsets();
        int y = padding.top;
        for(Component c : parent.getComponents()){
            if(c.isVisible()) {
                c.setBounds(padding.left, y, parent.getWidth(), c.getPreferredSize().height);
                y += c.getHeight();
           }
        }
    }
}


Search table without repetitive for loops

I am not proficient with NumPy and I am sure there is a better way, but, as a step to following the DRY principle and making the code a bit more scalable, you can dynamically determine and "and" all the filtering conditions:

import datetime

from astropy.table import Table
import numpy as np

def search(test_tab, **params):
    def vectorize_callable(item):
        return all(getattr(item, param_name) == param_value
                   for param_name, param_value in params.items()
                   if param_value is not None)

    return test_tab[np.where(np.vectorize(vectorize_callable)(test_tab['date']))[0]]

data = [1, 2, 3, 4, 5, 6]
dates = [datetime.datetime(2010, 6, 25, 0, 15),
         datetime.datetime(2011, 5, 25, 0, 45),
         datetime.datetime(2011, 6, 25, 1, 15),
         datetime.datetime(2012, 7, 12, 3, 45),
         datetime.datetime(2013, 9, 15, 2, 15),
         datetime.datetime(2014, 2, 25, 2, 45)]

test_tab = Table(data=[dates, data], names=['date', 'data'])
print(search(test_tab, year=2011, day=25))

Prints:

        date        data
------------------- ----
2011-05-25 00:45:00    2
2011-06-25 01:15:00    3

Note how all() in combination with getattr() are used to "join" the logical conditions applied to different attributes.


Positioning a tooltip relative to various kinds of elements

Create an array which contains :

the id of element
the offset x
the offset y

then, loop on each element of this array and do a single if.

Something like that (not tested)

var items = [
    {name: '#te_classbuilder', x: -120, y: -0},
    {name: '#lesson-details-extend-button', x: 0, y: 120},
    {name: 'label', x: 100, y: -120}
];

for (var i = 0; i < items.length; i++) {

  var item = items[i];

  if ($element.is(items[i].name) {
    tooltipXPos = xPos + item.x;
    tooltipYPos = yPos + item.y;
  }
}

If you know the key, use a map and don't use a loop in the array, simply get the item of the map using the key.


Use final properties

private List<String> list = null;
private ArrayList<String> arrayList;

Both properties are set in the constructor, so they should both be final.

private final List<String> list = new ArrayList<>();
private final ArrayList<String> arrayList = new ArrayList<>();

public AlternateRowArrayAdapter(@NonNull Context context, @LayoutRes int layout,
                                @IdRes int textViewResourceId, @NonNull List<String> objects)
{
   // ...
    this.list.addAll(objects); // same solution for both lists!
    this.arrayList.addAll(this.list);
}

Choose better names

Naming is the hardest part in programming. Always take your time to think about the names of your identifiers, if they express their purpose.

E.G.: Your lists should have better names like allItems and filteredItems

Work in constructors

In general constructors should not access any method on a dependency or and non private or non final method inside its own class (except super() and this()).

Therefore I'd rather pass in the colors array as constructor parameter. But I don't know much about android programming to say if that is even possible...

  Regarding using colors in constructors - it's possible to pass them as an arguement, but we already pass a context as an argument which contains these colors – Marek Czaplicki

Because you passed the context instead of the color array you class has two more dependencies: the context itself and the ResourcesCompat class. You class should have as less dependencies as possible.


Nice use of """docstrings""".

This code is useless:

else:
    "Value out of bounds"

If the else clause is reached, the string statement is executed, with no effect.  Just like executing a docstring statement has no effect.

You want:

else:
    raise ValueError("Value of out bounds")

The function convert_to_word() returns strange values like "sevenhundredandtwentyfive", which is only useful for counting letters, and nothing else.  A more flexible return might be ["seven", "hundred", "and", "twenty", "five"], allowing the caller to count words, or letters ... or ... join the words with spaces.

Several recursive calls are unnecessary.

convert_to_word(x//100) could simply be num_word_map[x // 100], and convert_to_word(x % 10) could be num_word_map[x % 10].

Comparison of a floating point value and an integer for equality is dangerous x / 1000 == 1.  Simply use x == 1000.

For this problem, instead of storing the words in num_word_map, you could simply store the lengths of the words.

Your """docstring""" usage is good.  You describe what the function does, what the parameters are, and what the return value is.  Someone wishing to use your functions would only need to type help(convert_to_word) and they should have all the information required to use the function.

There is no formal "right way" to format the docstrings, but there are some tools which expect things a certain way.

For instance

"""
... omitted ...

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains
23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing
out numbers is in compliance with British usage.
Answer = 21124
"""

This docstring contains 2 examples with answers, and one answer to a large question.  You can embed examples in a """docstring""", and it can become a built-in test for your module.

"""
... omitted ...

Answer = 21124

NOTE: Do not count spaces or hyphens.  The use of "and" when writing
out numbers is in compliance with British usage.  For example:

>>> len(convert_to_word(342))     # three hundred and forty-two
23

>>> len(convert_to_word(115))     # one hundred and fifteen
20
"""

Starting at the >>>, the text look like lines straight out of what you might see if you typed commands in a Python REPL.  The lines beginning with >>> are the commands, and the lines below that are the command output.  The doctest module can read the docstrings in a module, find lines formatted this way, execute the commands, and verify the output matches the expected output.  You might run this as:

python3 -m doctest numbers-letters.py

The output of the above command should be nothing, because the tests would pass.  Let's add one more test in the doc string:

"""
... omitted ...

>>> len(convert_to_word(342))     # three hundred and forty-two
23

>>> len(convert_to_word(115))     # one hundred and fifteen
20

>>> convert_to_word(115)
'one hundred and fifteen'
"""

Now running the doctest will produce output due to the failing test:

python3.8 -m doctest number-letters.py
**********************************************************************
File "/Users/aneufeld/Documents/Stack Overflow/number-letters.py", line 23, in number-letters
Failed example:
    convert_to_word(115)
Expected:
    'one hundred and fifteen'
Got:
    'onehundredandfifteen'
**********************************************************************
1 items had failures:
   1 of   3 in number-letters
***Test Failed*** 1 failures.

The output doesn't match because the test output contains spaces, which the function doesn't actually produce.

Other tools exist which read the docstrings, such as the Sphinx documentation generator.  It has formatting requirements; read the docs for details.


Send multiple individualised emails via a limited number of SMTP clients

Don't use SmptClient.Send(), use SmptClient.SendMailAsync() instead. It returns a Task..

Actually, I don't think you need this class at all.

(I'm typing in a notepad, so this is untested and just to illustrate the concept.)

var mailTasks = new List<Task>();
var client = new SmtpClient();

foreach(var participant in courseParticipants)
{
    var mail = new MailMessage
    {
        From = new MailAddress("from@example.com"),
        To = participant.email,
        Subject = "come and attend course",
        BodyFormat = MailFormat.Html
    }

    string token = await GetRegistrationTokenAsync(cp);
    mail.Body = $"
let me come
";

    mailTasks.Add(client.SendMailAsync(mail));
}

try
{
    await Task.WhenAll(mailTasks);
}
catch(AggregateException ex)
{
    //handle failures
}

This code is much simpler to understand, and therefore maintain.

One last thing before I go: Are you absolutely certain that GetRegistrationTokenAsync() will always return a url safe string?

string token = await GetRegistrationTokenAsync(cp);
mail.Body = $"
let me come
";

You should probably be Url encoding the token.


Your indentation is off: there should be a level also after class, not only in methods:

class CyclicIterator {
    // Class members here
}

Always try to instantiate to an interface, not an implementation:
This:

LinkedList<Integer> list = new LinkedList();

Should be:

List<Integer> list = new LinkedList<>();

Note there the diamond operator <> to actually get a genericized list. Without it, you should have got a compiler warning about using raw lists. The diamond operator is shorthand for giving the generic type to the implementation: List<Integer> list = new ArrayList<Integer>();

I would also prefer using System.out.format to just smashing strings together in a println call: System.out.format("For members %s:%n");


Overall, it looks pretty good. Not very much code, so not very much that could be bad. I'll give you some tips, from my perspective:

This first note isn't exactly about C++, but more common than that: It's a good idea to put "public" things first in your class, and more protected things further down. This is because when people look at the class, they are more likely looking for public things, rather than protected/private things. So if you put those at the top, they don't have to scroll through to find them.

Consider making get_surface(); an inlined function, by defining it directly in the header. It's a shame if such a quick and simple function would incur the cost of a function call, and the cost of inlining such a tiny thing is near to nothing.
As I see it, all direct/simple getters and setters should be inlined.

There is no need to write this->, since that is always implied. They only clutter the code.

It is good practice to point out which variables are actually protected members, in the name of the member. I personally put a small "m" in front of all protected members, such as "mSurface". Some people write "m_Surface", or just a "_" in front, with no "m", and so on.

The part that says (this->surface == NULL), you should use nullptr instead of NULL. It's a keyword from C++11, assuming you're using at least C++11. nullptr is a pointer-type, while NULL is simply an int. Writing NULLis exactly the same as writing 0. In some cases, this causes ambiguity, so it's good practice to always use this keyword for null-pointers, since it sometimes actually matters, even if not always.

And as for const-correctness, there is only one function to consider, here. And since it returns a pointer, which could be used to change internal data, it shouldn't really be considered a const member function. (Or "method", to you Java people.)


In general, you should use one, and only one synchronization strategy in any class. You have synchronization, and are contemplating volatiles too.

The best-practice mechanism for now in Java is using the classes from java.util.concurrent.* to manage locking, and memory synchronization. The benefit from there that will help you most, is the Condition concept, as well as the fine-grained management of locks.

Your locking at the moment relies on a 'global' lock that all events use, thus if you have many collections of events running, each collection uses the same lock. Thus, if some other Events are happening in some other code block somewhere, we will still be notified or each of those 'remote' event completions, and our completions will notify their awaits....

Additionally, I did not like the way you manage the await-any concept. You literally scan the Events for changes, and check for one to complete.

In essence, I dislike:

using a static lock
using synchronization
using messy awaitAny logic

Finally, I did not like the method you chose as the core await container... Instead of the awaitAll(Event[]) I prefer the awaitAll(List<Event>...). I cannot defend that preference right now though. Not sure why I prefer it.

Still, having thrown all that criticism at you, here's how I would probably do it. Note, the logic change for the await....

You have a single static lock. What I suggest is to create a 'completion listener'. In the case of awaitAll, each Event has it's own listener. In the case of awaitAny, they all share a single listener, so there's just one notification.

The system below makes each await*(...) an independent operation. The only signals are what's happening that's relevant to the completion service.

This is untested, so go through and understand it well ;-)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Event {

    private static final class EventCompletion {
        private final Lock plock = new ReentrantLock();
        private final Condition pcond = plock.newCondition();
        private boolean complete = false;

        void completed() {
            plock.lock();
            try {
                if (!complete) {
                    complete = true;
                    pcond.signalAll();
                }
            } finally {
                plock.unlock();
            }
        }

        void awaitCompletion() throws InterruptedException {
            plock.lock();
            try {
                while (!complete) {
                    pcond.await();
                }
            } finally {
                plock.unlock();
            }
        }

    }

    private final Lock lock = new ReentrantLock();
    private boolean complete = false;

    private final List<EventCompletion> listeners = new ArrayList<>();

    private void addListener(EventCompletion ec) {
        boolean notifyNow = false;
        lock.lock();
        try {
            if (!complete) {
                listeners.add(ec);
            } else {
                notifyNow = true;
            }
        } finally {
            lock.unlock();
        }
        if (notifyNow) {
            // immediate notification of completion...
            ec.completed();
        }
    }

    /**
     * Return the signaled state of this Event.
     */
    public boolean isSignaled() {
        lock.lock();
        try {
           return complete;
        } finally {
            lock.unlock();
        }
    }

    /**
     * Return the signaled state of this Event.
     */
    public void signal() {
        EventCompletion[] toNotify = null;
        lock.lock();
        try {
            if (complete) {
                return;
            }
            toNotify = listeners.toArray(new EventCompletion[listeners.size()]);
            listeners.clear(); // no need to remember previous notifications....
        } finally {
            lock.unlock();
        }
        for (EventCompletion ec : toNotify) {
            ec.completed();
        }
    }

    public static void awaitAll(Event ev0, Event... events) throws InterruptedException {
        List<Event> toWait = new ArrayList<>(1 + events.length);
        toWait.add(ev0);
        for (Event e : events) {
            toWait.add(e);
        }
        awaitAll(toWait);
    }

    public static void awaitAll(Event[] events) throws InterruptedException {
        awaitAll(Arrays.asList(events));
    }

    public static void awaitAll(List<Event> events) throws InterruptedException {
        EventCompletion[] toComplete = new EventCompletion[events.size()];
        int pos = 0;
        for (Event e : events) {
            EventCompletion ec = new EventCompletion();
            e.addListener(ec);
            toComplete[pos++] = ec;
        }

        for (EventCompletion ec : toComplete) {
            ec.awaitCompletion();
        }

    }

    public static int awaitAny(Event ev0, Event... events) throws InterruptedException {
        List<Event> toWait = new ArrayList<>(1 + events.length);
        toWait.add(ev0);
        for (Event e : events) {
            toWait.add(e);
        }
        return awaitAny(toWait);
    }

    public static int awaitAny(Event[] events) throws InterruptedException {
        return awaitAny(Arrays.asList(events));
    }

    public static int awaitAny(List<Event> events) throws InterruptedException {
        // all events notify the same completion service.
        EventCompletion ec = new EventCompletion();
        for (Event e : events) {
            e.addListener(ec);
        }
        ec.awaitCompletion();
        int pos = 0;
        for (Event e : events) {
            if (e.isSignaled()) {
                // first completed event is returned.
                return pos;
            }
            pos++;
        }
        throw new IllegalStateException("One of the events must have been signalled... This Exception should never happen!");

    }

}

Update: As per your comment, the use of ReentrantLock and Condition is not necessary. I prefer to use consistent locking mechanisms in my code, and I have 'standardized' on Locks. Locks can do anything synchronization can do, and then more too. Unless you have many thousands of events all happening at once, the memory cost of the locks would be negligible.

Still, I agree with the sentiment you expressed. The same can be done with synchronization:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Event {

    /* Private class can be used as a synchronization lock too */
    private static final class EventCompletion {
        private boolean complete = false;

        synchronized void completed() {
            if (!complete) {
                complete = true;
                this.notifyAll();
            }
        }

        synchronized void awaitCompletion() throws InterruptedException {
            while (!complete) {
                this.wait();
            }
        }

    }

    private boolean complete = false;

    // use private-final listeners class as private lock on public class.
    private final List<EventCompletion> listeners = new ArrayList<>();

    private void addListener(EventCompletion ec) {
        boolean notifyNow = false;
        synchronized (listeners) {
            if (!complete) {
                listeners.add(ec);
            } else {
                notifyNow = true;
            }
        }
        if (notifyNow) {
            // immediate notification of completion...
            ec.completed();
        }
    }

    /**
     * Return the signaled state of this Event.
     */
    public boolean isSignaled() {
        synchronized(listeners) {
           return complete;
        }
    }

    /**
     * Return the signaled state of this Event.
     */
    public void signal() {
        EventCompletion[] toNotify = null;
        synchronized(listeners) {
            if (complete) {
                return;
            }
            toNotify = listeners.toArray(new EventCompletion[listeners.size()]);
            listeners.clear(); // no need to remember previous notifications....
        }
        for (EventCompletion ec : toNotify) {
            ec.completed();
        }
    }

    public static void awaitAll(Event ev0, Event... events) throws InterruptedException {
        List<Event> toWait = new ArrayList<>(1 + events.length);
        toWait.add(ev0);
        for (Event e : events) {
            toWait.add(e);
        }
        awaitAll(toWait);
    }

    public static void awaitAll(Event[] events) throws InterruptedException {
        awaitAll(Arrays.asList(events));
    }

    public static void awaitAll(List<Event> events) throws InterruptedException {
        EventCompletion[] toComplete = new EventCompletion[events.size()];
        int pos = 0;
        for (Event e : events) {
            EventCompletion ec = new EventCompletion();
            e.addListener(ec);
            toComplete[pos++] = ec;
        }

        for (EventCompletion ec : toComplete) {
            ec.awaitCompletion();
        }

    }

    public static int awaitAny(Event ev0, Event... events) throws InterruptedException {
        List<Event> toWait = new ArrayList<>(1 + events.length);
        toWait.add(ev0);
        for (Event e : events) {
            toWait.add(e);
        }
        return awaitAny(toWait);
    }

    public static int awaitAny(Event[] events) throws InterruptedException {
        return awaitAny(Arrays.asList(events));
    }

    public static int awaitAny(List<Event> events) throws InterruptedException {
        // all events notify the same completion service.
        EventCompletion ec = new EventCompletion();
        for (Event e : events) {
            e.addListener(ec);
        }
        ec.awaitCompletion();
        int pos = 0;
        for (Event e : events) {
            if (e.isSignaled()) {
                // first completed event is returned.
                return pos;
            }
            pos++;
        }
        throw new IllegalStateException("One of the events must have been signalled... This Exception should never happen!");

    }

}


Counting consecutive streaks in random numbers

If your program is going to be run via cli only, then I'd suggest that you look into argparse library.
Split the code snippet into different functions. Though your current use-case is limited, but suppose you later want to check successive outcomes in a 6 face die? A 10 face die? A 20 face die? I'd suggest asking for number of faces as an argparse param, and default it to 2.
Use the logging library's RotatingFileHandler to control logging to the files.
In the logic, you do not need to store the value of random_number_before. Just checking against a constant value of 1 would suffice in your case:

if random_number == 1:
    actual_succession += 1
else:
    if actual_succession > longest_succession:
        longest_succession = actual_succession
    actual_succession = 0

as the logic is executed for each iteration of the counter, everytime you encounter a number other than 1, your succession counter would be reset to 0.


PreserveIds using inheritance id db auto incrementing

I would change implementation if Id property in both your models into:

public class StatesModel
{
    private int id;

    public int Id
    {
        get
        {
            return id;
        }
        set
        {
            id = value;

            if (OriginalId == 0)
                OriginalId = value;
        }
    }

    public int OriginalId { get; private set; }

    // (...)
}

// The same for CityModel

and remove your PreserveIds method all together. You can also add private setter to OriginalId just to make sure that nobody would override this value.


Javascript speed of an animated object (planet orbiting sun)

Review
Orbit
You are incorrectly calculating the position of the planet.
The eccentric anomaly which you attempt to calculate with a linear, integrated 2nd derivative, in the function this.updateTheta will never work as the solution in non linear. That said the example below uses a linear approximation.
There is no easy way to change your code such that time steps can be scaled while maintaining the same orbit. It is best to use the standard orbital solution.
Animation
Never use 'setInterval' for animation
For the best result when animating via JS in the browser use the animation callback requestAnimationFrame (rAF)
It will call the main render loop function at 60FPS (If your render function takes no more than ~80% of 1/60th second (12 - 13ms)) Please read the documentation for rAF as there are many caveats.
Example of basic animation loop
    requestAnimationFrame(renderLoop);     // request first frame

    function renderLoop() {
        ctx.clearRect(0, 0, W, H);         // clear canvas ready for next frame render

        ... // call render function

        requestAnimationFrame(renderLoop); // Request Next frame
    }

Readable
Your calculations are very hard to read and you are using some outdated calls.

Use the ** operator rather than Math.pow or Math.sqrt. Eg 2 ** 2 is two squared and 2 ** 0.5 is the square root of two.

The main reason that your calcs are hard to read is because you don't space out the operators. Always use spaces between operators.
The line...

var R = Math.pow(((Math.pow(T,2))/((4*Math.pow(Math.PI, 2))/(G*M))),(1/3)) ;

is far easier to read as...
 const R = (T ** 2 / (4 * Math.PI ** 2 / (G * M))) ** (1 / 3);

Note that variables that do not change should be constants.

Orbits and controlling their animation periods.
Note I use radians
Kepler's laws modify a circular orbit into an ellipse such that the line from the planet (Earth) to the parent (Sun) sweeps equal areas in equal time.
We define the ellipse by the semi-major axis, the eccentricity, and either the closest (periapsis) or furthermost (apoapsis) points in the orbit. Both points are on the semi-major axis
We want to crate a function that gives the planets position at a given time. We can then scale that time to control the rate that the animation plays out.

For a circular orbit the object must travel 2 * MATH.PI.

Using ms we can define the period of the orbit. eg 1 second is 1000ms

We can then scale the orbit position as a function of time.
Example

The orbit position scale is scale = (period) => 2 * MATH.PI / period
With an orbit of 1 second the position is  pos = (ms) => scale(1000) * ms where ms is the current time. The pos returned is the mean anomaly M

Kepler's law

The orbital position is called the mean anomaly M in radian (range -PI to PI)

When traveling on a non circular orbit the mean anomaly M is advanced or retarded depending on the orbital distance. That value is the eccentric anomaly E in radians

The ellipse is defined by eccentricity e range  0 <= e < 1

Kepler states that M = E - e * Math.sin(E)

We know M and e, but not E so we must solve the above equation in terms of M. This is non trivial so we must approximate.
To do this we use Newtons method to solve M = E - e * Math.sin(E) for M with a linear approximation of the non linear part e * sin(E) see function eccentricAnomaly in Demo

With E we can then calculate the 2D position of the body using e and the distance to apoapsis r
  const x = r * (Math.cos(E) - e);
  const y = r * Math.sin(E) * (1 - e ** 2) ** 0.5;

This 2D position can then easily be aligned to the semi-major axis, and if needed rotated into 3D to match the inclination, position of ascending node and argument of periapsis to fully define any 2 body orbit (Newtonian).

DEMO
All that above was clear as mud I am sure, thus a Demo.
The code below animates 3 objects (two 2 body solutions) at a specified orbital period of 1 and 2 seconds. The time is given by rAF as first argument given to the callback renderLoop.
Time 0 is set to apoapsis which is defined by the start positions of the planet relative to the parent body. The orbit is rotated in 2D to align to the apoapsis.
The eccentricity of planets e is 0.5

requestAnimationFrame(renderLoop);
const ctx = canvas.getContext("2d");
ctx.lineCap = "round";
var frameCount = 0, startTime, prevTimeScale = timeScale.value, lastTime;
const W = canvas.width, H = canvas.height, CX = W * 0.25, CY = H * 0.5;

const SUN_RADIUS = 20, SR = SUN_RADIUS;               // in pixels
const PLANET_SCALE = 0.4, PS = PLANET_SCALE;          // in sun radi
const FIRST_PLANET_DIST = 4, FPD = FIRST_PLANET_DIST; // in sun radi
const ECCENTRICITY = 0.5, E = ECCENTRICITY;           // 0 circlular
const KEPLER_PERIOD = 1000, KP = KEPLER_PERIOD;       // ms per orbit

const MBLUR_LINE_GRAD = 8; // Steps to grade blur line
const FRAME_RATE = 60; // Max 60 Frames per second. Only use valid values
                       // Valid vals 60, 30, 20, 15, 12, 10, 6, 5, 4, 3, 2, 1
const FRAME_SKIP = 60 / FRAME_RATE;
Math.TAU = Math.PI * 2;
Math.R90 = Math.PI * 0.5;

const calcVectors = (A, B) => {
    const dx = B.x - A.x;
    const dy = B.y - A.y;
    const rSqr = dx * dx + dy * dy, r = rSqr ** 0.5;
    const nx = dx / r;
    const ny = dy / r;
    return {nx, ny, rSqr, r, axis: Math.atan2(ny, nx)};
}
const eccentricAnomaly = (M, e) => {  // newtons method to solve M = E-e sin(E) for E
    var d, E = M; // guess E
    do {
        d = (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));
        E -= d;
    } while (d > 1e-6);
    return E;
}

const Planet = {
    x:  0, y:  0, vx: 0, vy: 0, ox: 0, oy: 0,
    init() { return this },
    update() { },
    draw(ctx, lastSubFrame) {
        const A = this;
        const dx = A.ox - A.x;
        const dy = A.oy - A.y;
        const dist = (dx * dx + dy * dy) ** 0.5;
        ctx.setTransform(1, 0, 0, 1, CX + A.x, CY + A.y);
        ctx.fillStyle = ctx.strokeStyle = A.col;
        if (dist > 0.1 && MBLUR_LINE_GRAD > 0) {
            ctx.globalAlpha = (1 / (dist - 0.1)) ** 1.4;
            ctx.beginPath();
            ctx.strokeStyle = A.col;
            const r = A.radius * 2;
            ctx.moveTo(dx, dy);
            ctx.lineTo(0, 0);
            const MBLG = MBLUR_LINE_GRAD;
            let i = MBLG;
            while (i--) {
                ctx.lineWidth = Math.cos(((i - 1) / MBLG) * Math.R90) * r;
                ctx.stroke();
            }
        } else if (lastSubFrame) {
            ctx.beginPath();
            ctx.arc(dx / 2, dy / 2, A.radius, 0, Math.TAU);
            ctx.fill();
        }
        ctx.globalAlpha = 1;
        A.ox = A.x;
        A.oy = A.y;
    },
};
const KeplerPlanet = {
    period: 1,
    init(e, B) {  // B at relative position at time 0. A is at apoapsis
        const A = this;
        A.period =  Math.TAU / A.period;
        A.e = e;
        Object.assign(A, calcVectors(A, B));
        A.px = Math.cos(A.axis); // Transform to Rotate semi major axis
        A.py = Math.sin(A.axis);
        return A;
    },
    update(time) {
        const A = this;
        const E = eccentricAnomaly(A.period * time, A.e);
        const x = A.r * (Math.cos(E) - A.e);
        const y = A.r * Math.sin(E) * (1 - A.e ** 2) ** 0.5;
        A.x = x * A.px - y * A.py;
        A.y = x * A.py + y * A.px;
    },
};
const FixedPlanet = {
    radius: 0,
    col: "#EC8",
};

function createOrbitObj(type, x, y, radius, col, period, e, orbits) {
    return  ({...Planet, ...type, x, y, ox: x, oy: y, period, radius, col }).init(e, orbits);
}
const sun = createOrbitObj(FixedPlanet , 0, 0, SR, "#FF8");
const p1 = createOrbitObj(KeplerPlanet,  FPD * SR, 0, SR * PS, "#6C1", KP, E, sun);
const p9 = createOrbitObj(KeplerPlanet,  FPD * SR * 2, 0, SR * PS, "#C61", KP * 2, E, sun);
const system = Object.assign([sun ,p1, p9], {
    update(time) {
        var i = this.length - 1;
        while (i) { this[i--].update(time) }
    },
    draw(ctx, lastSubFrame) {
        for (const A of this) { A.draw(ctx, lastSubFrame) }
    },
});

function renderLoop(time) {
    var tT, i, pTS = prevTimeScale; // tT is totalTime
    if (frameCount++ % FRAME_SKIP === 0) {
        startTime = startTime ?? time;
        tT = time - startTime;

        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.clearRect(0, 0, W, H);

        const inputTimeScale = timeScale.value;
        if (inputTimeScale !== pTS) {
            startTime = time - tT * pTS / inputTimeScale;
            pTS = prevTimeScale = inputTimeScale;
            tT = time - startTime;
        }
        const dT = tT * pTS - lastTime; // delta time
        i = 0;
        while (i < MBLUR_LINE_GRAD && lastTime) {
             const current = lastTime + dT * (i++ / MBLUR_LINE_GRAD);
             system.update(current);
             system.draw(ctx, false);
        }

        system.update(tT * pTS);
        system.draw(ctx, true);
        lastTime = tT * pTS;
    }
    requestAnimationFrame(renderLoop);
}
canvas { background: black; }
input { position: fixed; top: 10px; left: 10px; color: white; width: 340px }
<canvas id="canvas" width="350" height="300"></canvas>
<input type="range" id="timeScale" min="0.01" max="4" step ="0.01" value="1">

Why retro? The view is up from under the ecliptic (to matche canvas coords), orbits are thus retrograde to the solar system's direct (prograde)
Extras
I have added some additional features to demo.

Time Scale. The range bar changes the time scale that lets you change the rate of time. Time is a value based on a start time. When scaling time that start time must be change so that the planet does not skip time.

Frame Rate. There is a value called FRAME_RATE which sets the frame rate. Max 60. This rate is a requested rate, the actual rate will vary depending on device and CPU/GPU load, but over time it will average the requested rate.

Motion Blur. To improve the look when the time scale is large there is a simple motion blur applied to the moving planets.
The blur is just a linear interpolation between sub time steps and thus only works when movement per sub step is less than about 0.5 radians.
MBLUR_LINE_GRAD controls how the blur is drawn and the number of sub time steps are used. A value of 0 will turn off motion blur. Values 1 or greater will increase the persistence. Current value is 8 and is tuned for the current frame rate of 60FPS.


A class for animating messages as feedback to the user

It looks really good! The only bit I don't like is the nested ifs, but I'm really nit-picking.

       if (hide) {
            if (obj.input_element) {
                obj.input_element.removeEventListener("keypress", obj.enter);
            }
            obj.cover_element.style.display = 'inline';
        } else {
            if (obj.input_element) {
                obj.input_element.addEventListener("keypress", obj.enter);
            }
            obj.cover_element.style.display = 'none';
        }

Maybe....

obj.cover_element.style.display = hide ? 'inline' : 'none';
if (!obj.input_element) return;

if (hide) {
   obj.input_element.removeEventListener("keypress", obj.enter);
}
else {
   obj.input_element.addEventListener("keypress", obj.enter);
}

Putting the return value at the start, instead of protecting both blocks from it being null, makes it slightly more understandable. But I still don't like that section much.


As per common naming convention, the class names should start with a capital letter.
It may be more readable to put the template line above the class line:

template < typename _Ty >
class data : public dummy
{
}

Your bool functions should be const.  Any member function that doesn't modify data members should be const.  Such functions also include accessors ("getters") and the bool operators (operator==, operator!=, operator<, and operator>).

For instance, with empty():

bool empty() const
{
    // ...
}

and operator==:

bool operator==(object &_Rhs) const
{
    // ...
}

Also, the above parameter should be const& since _Rhs is not being modified.
If you're not defining your own constructor and/or destructor, you don't need to make them yourself.  The compiler will make them for you.

However, if you're using C++11, you can have an explicitly defaulted constructor and destructor:

data() = default;
~data() = default;


your code is not bad. You write comments that don't state the obvious, so thats good. You don't make stupid rookie mistakes like I used to make, so thats good. But... (such a lovely word)
Naming
You define an interface: InterfaceController. The name tells me that every class that implements this interface, is some kind of Controller of interfaces. It sounds fancy, I must give you that.
Maybe it's personal, but I just don't like writing implements RandomInterface. Ofcourse it's an interface, thats why I implement it. And if you have a problem where the interface and the class implementing it have the same name, one of the two should not exist.

AbstractPageController implements Controller: So we have a Controller for an AbstractPage ? What is an Abstract page? This might be nitpicking, but these kind of namings lead to confusion. Either use class AbstractController or interface PageController.

Every Controller class we create needs to have 2 methods, setup and compile. However, I'm not so sure these are good names, they even smell.
setup: Whats wrong with using __construct()? This was basically created for setup.
compile: It's PhP, why should I compile, is there some kind of .Net integration? Compiling a view, I understand, but a Controller? You lost me. maube run is better.
Especially given the fact that your comment reads:
// run the controller, let it prepare a view and return the rendered code

wouldn't it make more sense to have the following code?
return (new $controllerName())->run()->renderView();

Also note that the word 'run' does not really tell us anything about what is being returned. Making us guess. What are we calling renderView() on? Try to avoid chaining unless they really make sense (Again, mabe it's me, but I just hate 'unknown method on undefined' errors). Use the __construct instead of run()/setup() and we get the following code:
return (new $controllerName())->render()

This doesn't even need comments, saves you a few key strokes #lazyDev

I also see no way of passing arguments to a Controller. Planning on using $_GET there? IF so, here is my sad face :(

Minor remarks
Your Controller has some magic strings:
'\\App\\Controllers\\'

and
'Controller'

maybe you should replace it by some constant or similar. Simply because CONTROLLER_NAMESPACE makes more sense than '\App\Controllers\'. Also make sure that the namespace is only hardcoded in one place. I just don't like hard coded strings.


It looks like extractLedesText() is trying to do three things:

Strip away any BOM from fileData.
If this is a MIME message, extract only the TextBody part and pass that recursively into this method again.
Else just do a split("\\[]") to get our desired String[] array.

So...

Data massaging

You can use a helper method to achieve this:

private static byte[] filterBOM(byte[] fileData) {
    if (fileData.length < 3) {
        return fileData;
    }
    final byte[] array = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
    final byte[] data =  { fileData[0], fileData[1], fileData[2] };
    return fileData.length > 3 && Arrays.equals(data, array) ?
        Arrays.copyRangeOf(fileData, 3, fileData.length) : fileData;
}

I think it may be better to do a fileData.length < 3 check before you construct your data array. Also, I am using the Arrays utility class instead of ArrayUtils to copy part of the array.

Extracting the TextBody from a MIME message

You can make use of try-with-resources for both your ByteArrayInputStream and ByteArrayOutputStream instances, and I suppose this is where we can employ a bit of Stream trickery...

private static byte[] getTextBody(final String ledes) {
    final TextBody tb;
    try (final InputStream input = new ByteArrayInputStream(ledes.getBytes(StandardCharsets.UTF_8))) {
        tb = ((Multipart) new Message(input).getBody()).getBodyParts().stream()
                .filter(part -> part.getMimeType().equalsIgnoreCase("text/plain"))
                .findFirst().orElseThrow(() -> new BaseApplicationException(
                    "No MIME part found with MIME type of 'text/plain' while parsing submitted invoice file."))
                .getBody();
    } catch (IOException e) {
        throw new BaseApplicationException(e);
    }
    try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        tb.writeTo(output);
        return output.toByteArray();
    } catch (IOException e) {
        throw new BaseApplicationException(e);
    }
}

We stream on the List from getBodyParts(), filtering those where their MIME type is "text/plain" and then look for the first matching BodyPart. If there isn't any, we call orElseThrow() with a new BaseApplicationException(...), otherwise we will getBody() and writeTo() your ByteArrayOutputStream. The output of this method is a byte[] array if there are no thrown Exceptions.

Putting it all together

protected String[] extractLedesText(byte[] fileData) {
    final String ledes = new String(filterBOM(fileData));
    return ledes.startsWith("MIME") ? extractLedesText(getTextBody(ledes)) : ledes.split("\\[]");
}


Populating a list of all .wtv files across 4 hard drives

Your macro/procedure is implicitly working off the ActiveSheet: everywhere you use an unqualified Cells or Range, what VBA is seeing is ActiveSheet.Cells or ActiveSheet.Range: if you're supposed to work off Sheet1 or, if you gave it a code name, some DestinationSheet worksheet, use that instead, so that VBA doesn't need to resolve what the active sheet is every time you refer to it.

You should also avoid using .Select and .Activate and working off the Selection whenever possible.

The procedure is doing way too many things; break it down! You need a procedure whose role is to clear the contents of the DestinationSheet. Then you need a function that takes some rootPath and recursively returns all .wtv files under it and its subdirectories: you want to flatten that tree and work off a straight list of filenames to process (simply tweak that code to make it a Function and fill up and return some Collection instead of Debug.Printing as it goes). Seems your code will process any file, not just .wtv ones.

This is a missed opportunity:

Dim vArray As Variant
vArray = Array(0, 21, 27, 1, 260, 15, 253, 261, 16, 259, 177, 19) 'removed
'0=Name, 21=Title, 27=length, 01=size, 260=recordingtime, 15=year, 253=channelno,
'261=stationcallsign, 16=genre, 259=progdesc, 177=path, 19=rating

Consider declaring an Enum type here:

Private Enum FileInfoField
    Name = 0
    Size = 1
    Year = 15
    Genre = 16
    Rating = 19
    Title = 21
    Length = 27
    Path = 177
    Channel = 253
    ProgDesc = 259
    RecordingTime = 260
    StationCallsign = 261
End Enum

And now you can do away with these comments and mental mappings:

Dim infoFields As Variant
infoFields = Array(Name, Size, Year, Genre, Rating, Title, Length, Path, Channel, ProgDesc, RecordingTime, StationCallsign)

Note the identifier infoFields is much more descriptive than vArray which says essentially nothing other than "well it's a variant array", assuming the v is a Hungarian Notation prefix for "variant".

Because we've recursively found all files under a given root folder already, I don't think we need that queue overhead anymore.

Remember we're collecting the data at this point, so there won't be any Cells(lRow, iCol + 1) = assignment here. Instead we'll .GetDetailsOf each file and perhaps populate a data type - I'd add a class module here, to represent some "file info" data; the class doesn't need to be very complicated, it's just a "dumb data container", so a bunch of public fields can do:

Option Explicit

Public Name As String
Public Genre As String
Public Title As String
Public Size As String
'...

Or we can make it a little more than that, and embed some of the functionality in that class - in that case I'd opt for get-only properties instead, move the FileInfoField definition to that class module, and rename its members to avoid  clashing identifiers - I'd call that class MovieFileInfo:

Option Explicit
Private Enum FileInfoField
    NameField = 0
    SizeField = 1
    YearField = 15
    GenreField = 16
    RatingField = 19
    TitleField = 21
    LengthField = 27
    PathField = 177
    ChannelField = 253
    ProgDescField = 259
    RecordingTimeField = 260
    StationCallsignField = 261
End Enum

Private Type TMovieFileInfo
    Name As String
    Genre As String
    Title As String
    Size As String
    '...
End Type

Private this As TMovieFileInfo

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Get Genre() As String
     Genre = this.Genre
End Property

Public Property Get Title() As String
    Title = this.Title
End Property

Public Property Get Size() As String
    Size = this.Size
End Property

'...

Public Sub LoadFrom(ByVal parentFolder As Shell32.Folder, ByVal info As Shell32.FolderItem)
    With parentFolder
        this.Name = .GetDetailsOf(info, NameField)
        this.Title = .GetDetailsOf(info, TitleField)
        this.Size = .GetDetailsOf(info, SizeField)
        this.Genre = .GetDetailsOf(info, GenreField)
        '...
    End With
End Sub

Back to your loops. oShell doesn't need to be re-created at every single iteration of the inner-inner loop; it can very well be declared and assigned before any looping is done, and destroyed after all loops complete. The oFldr reference could be held by the With block itself - instead of this:

Set oFldr = oShell.Namespace(CStr(oSubfolder))
With oFldr

You could have this:

With oShell.Namespace(subfolder.Path)

And then the object reference is gone at End With.

Notice Path is teh default property of a Scripting.Folder, so by doing CStr(oSubfolder) you're really just fetching its Path property.... quite indirectly.

I'd suggest you add an actual reference to the Microsoft Scripting Runtime and Microsoft Shell Controls and Automation libraries, and early-bind all those, and work with strongly-typed objects instead of Variant and Object, which are costing you lots of overhead here.

So, something like this (I think I'm getting confused with the actual involved types here though):

Dim item As MovieFileInfo
Dim info As Shell32.FolderItem
Dim allFiles As Collection

With oShell.Namespace(subfolder.Path)
    For Each info In subfolder.Items
        Set item = New MovieFileInfo
        item.LoadFrom subfolder, info
        allFiles.Add item
    Next
End With

Anyway, so you traverse your flat list of files and populate a collection of MovieFileInfo items.

Once you have that, you dimension an array large enough to fit all rows and all columns, and then you populate it by iterating your collection.

Once you have that 2D array, you just dump it onto the target worksheet in one, single, instant worksheet write.

Alternatively you could skip the MovieFileInfo part and write directly to the array, but the constant resizing to accomodate each new record might not be worth it.

So, to recap:

Reduce nesting by extracting loop body into specialized procedures/functions
Avoid writing to cells as much as possible
Early-bind references as much as possible, avoid Variant and Object types
Avoid implicitly working off the active sheet; use explicit worksheet references whenever possible


You don't need a temporary variable $tempEntries
You don't need to check if the array is empty, if the array is empty shuffle will just do nothing

The code you need may look like:

$entries = $contest->getEntries();
shuffle($entries);


Clear out a textbox after submitting its content

Since you're already keeping track of the <input>'s value in your model, it would be cleaner to use that as the value in your view, too.

view : Model -> Html Msg
view model =
    div []
        [ div [] (List.map viewMessage model.messages)
        , input [ onInput Input, value model.value ] []
        , button [ onClick Send ] [ text "Send" ]
        ]

This way, your view is a pure representation of your model, and your model is kept in sync with user input.

I took the liberty of doing a quick pass over your code, additionally introducing record update syntax in your update function, as opposed to constructing a fresh record from scratch.

Adding or removing a field from a record needn't result in refactoring every single place you happen to modify the values of that record.


Just a few comments on the code as it stands so far:

You're using pretty old-school file dependency management (which isn't the same as dependency management) by explicitly including things.  I'd strongly suggest you look into the SPL autoload system, write an autoloader that can find where your classes are located in the filesystem and rely on the autoloader to handle the file dependency management instead.  It means that only code that's actually going to be used will be included and you won't get into a situation where you have loads of included classes but only a few get used, or where you're not sure what's been included.
You're using static methods.  Generally, statics are frowned upon because they're not considered to be good OO practice.  Sometimes they're necessary, but as a rule you should avoid them.  Any other class that makes use of the static call becomes tightly coupled to the class that implements it, reducing re-usability and testability (it becomes very difficult to test the dependant modules in isolation because you can't easily replace the static with a mock implementation).  I'd advise refactoring your factory to work in a non-static way.
Your Database class seems like it might not be necessary.  It's merely a wrapper around PDO, and actually hides most of the PDO class functionality.  I'd suggest you might be better off using PDO directly, as it's got a well-documented interface and you'll have full access to all the PDO functionality in the consuming classes instead of the small subset your Database class provides.

I would say that on the whole you're on basically the right track though.  It's certainly better than my own early efforts with OOP.  Don't worry, thinking in an "objecty" way is something that comes with practice and experience.


The output of your script is lovely, but it strikes me as a work in progress.  There's nothing wrong with what is there, but it seems a few major pieces are missing.

error checking

What happens if one of the steps fails?  As it stands the script will diligently proceed to the next step.  If you actually checked the return codes from your apt commands you would also get a chance to use the RED color that seemed wasted in the comments above.

logging

You mention logging, but there is no such thing in the script.  Adding this would not be hard.  If you want your messages to go to the screen and a log you could add functions that log and write to the screen.  logger is handy way to add to the system logs, but you could write to your own $LOGFILE too with something like

echo "step $STEP: $MSG" >> $LOGFILE

docs

Shouldn't there be docs somewhere?  A link to a wiki page or something in the script would help folks figure out what is up.  Providing help from within the script if a -h is provided is a good habit to get into.

rewrite based on above

#!/bin/bash

RED="\033[1;31m"
GREEN="\033[1;32m"
NOCOLOR="\033[0m"

mylog() {
        STEP=$1
        MSG=$2

        echo -e "step $STEP: ${GREEN}${MSG}${NOCOLOR}"
        logger "step $STEP: $MSG"
}

myfail() {
        STEP=$1
        MSG=$2

        echo -e "step $STEP ERROR: ${RED}${MSG}${NOCOLOR}"
        logger "step $STEP ERROR: $MSG"
}

# handle command line options
if [[ $1 == "-h" ]]; then
        echo "usage: $0"
        echo " -h prints help"

        exit 1
fi

# step 1
mylog 1 "the start"
echo foo

# step 2
mylog 2 "a middle"
echo bar

# step 3
mylog 3 "the end"
echo baz
if [[ $? == 0 ]]; then
        myfail 3 "nothing really"
fi

finally

It is a good habit to run your scripts through shellcheck.net.  Even my short rewritten example has one thing that could be improved.


This looks quite good code.  You've avoided many of the common mistakes.

Here are the things I spotted as I walked through.  Most of them are quite minor; the only serious issue is the handling of invalid user input.

srand(time(0));

Don't do this every time you want a random number - a random number generator is intended to be seeded just once.  So move the srand() call to the beginning of `main().

(Yes, I know this program calls generate_random_number() only once.  But we shouldn't need to have that knowledge, and we might want to change that behaviour, or to re-use this function in another program.)

// this function stops the program until useless input is entered

What's the point?  That just annoys the user, who would naturally expect to be returned to their shell after executing a program.  This just makes it look like the program is not responding.  Also, the useless variable is unnecessary - add the * modifier to the %i conversion to inhibit assignment.

int main()

This says that main() can be called with an unspecified number of arguments.  Instead, prefer to explicitly declare that it takes no arguments:

int main(void)

printf("You have to guess a number between 1 and 99.\n");

When the output is a fixed string ending in newline, we can use puts() instead of printf().

    int guess;
    scanf("%i", &guess);

If something that's not a number is entered, then scanf() will fail and guess will be uninitialized (that's Undefined Behaviour, which is Not A Good Thing).  We really, really need to check that scanf() successfully converts 1 input, and take some recovery action if not:

int status;
while ((status == scanf("%i", &guess)) != 1) {
    if (status == EOF) {
        fprintf(stderr, "Read error!\n");
        exit 1;
    }
    scanf("%*[^\n]");  // discard input
    printf("? >");
}

Correctly handling input (and, in particular, unexpected input) is difficult in C!

    else if (guess == random_number)

The if is redundant here, as we've eliminated all other possibilities.  So that can be simply else.


Programming Puzzle - N Teams K Wins each

Style

You are lacking consistency in the spacing in assignments.

Organisation

It might be worth extracting the algorithm in a function. It makes code easier to read and to test.

<?php
function guessChronology($n, $k)
{
    if ($n * $k > ($n * ($n - 1)) / 2) {
        return "-1\n";
    }
    $output = $n*$k."\n";
    $winMap = array();
    for ($i = 1; $i <= $n; $i++) {
        $winMap[$i] = 0;
    }
    for ($i = 1; $i <= $n; $i++) {
        for ($j = $i + 1; $j <= $n; $j++) {
            if ($winMap[$i] < $k) {
                $output .= "$i $j\n";
                $winMap[$i] += 1;
            } else if ($winMap[$j] < $k) {
                $winMap[$j] += 1;
                $output .=  "$j $i\n";
            }
        }
    }
    return $output;
}

$s = fopen("php://stdin", 'r');
$n = stream_get_contents($s);
$dum = explode(" ",trim($n));
$n = $dum[0];
$k = $dum[1];
echo guessChronology($n, $k);
?>

Re-using functions

You can use array_fill to write $winMap = array_fill(1, $n, 0);


Avoiding shell injection when calling Git in Python

Your defense strategy is known as "enumerating badness".  As a rule, any strategy based on enumerating badness is doomed to fail.  For example, you prohibit rm -rf /, but have you considered find / -delete, which basically does the same thing?  How about some use of the dd if=/dev/zero?  What if a user legitimately wants to perform an operation on a file named normal.py or even rm.c?  Why are you silently altering the command to do something else?

If you ever need to execute an external program with user-supplied parameters, sensible practices would be to use subprocess.run() or subprocess.Popen()

with the command line as a list already split into words,
with the shell=False parameter (the best way to avoid shell injection is to avoid using the shell at all!),
with the command given using an absolute path (which is essential with shell=False),
with -- preceding the user-supplied filenames, so that filenames that start with - are treated literally.

Do not attempt to prohibit any "bad" words; you want your code to work for any legitimate filenames.  Do check that the filenames are legitimate, though — for example, not containing too many ../../../...

Better yet, use a Python module that takes care of interacting with Git so that you don't have to deal with the problem yourself.


Sum of multiples of 3 or 5 using functional programming

This is one of those programming problems where there’s a special trick that can give you a better algorithm, in this case constant-time instead of linear.

If you add the multiples of 3 and the multiples of 5, you’ll count the multiples of 15 twice. So subtract those out. The answer becomes (3+6+9+...+999) + (5+10+15+...+995) - (15+30+45+...+990).

Then, to get all the multiples of m from 1 to N, factor the series m+2·m+... to m· (1 + 2 + ... + ⌊N/m⌋). There’s a simple formula for the series from 1 up to some number, called the Gaussian formula after its discoverer, Carl Friedrich Gauss.  The story goes that he found it as a child, and when his math teacher ordered the whole class to add the numbers from 1 to 100, just to keep them busy so he could take a nap, young Carl shocked him by finding the answer in seconds.  It works on computers, too!  So, substitute this formula into the previous equation to get a constant-time formula for the sum of all multiples of m up to N.  Then substitute that formula into the paragraph above this one, with m = 3, 5 and 15.

Maybe you know all that.  The point of the exercise might have been to practice the specific idioms you used here, like list comprehension and reduction.  Now that you have, you might want to compare an optimal algorithm in functional style.  The last time I posted a better algorithm for a Project Euler problem, someone informed me that the point of Code Review is not to write a better answer myself, so I’ll leave that to you if you feel like it.


Non-string input can lead to surprising results:

p (5/2).to_r #=> (2/1), integer division performed first
p (1.1).to_r #=> (2476979795053773/2251799813685248),  float can not be represented in binary

The last case is prevented by:

p 1.1.to_s.to_r #=> (11/10)

So I'd change rational = fraction.to_r to rational = fraction.to_s.to_r.  But the first case is only handled correctly if it is a string to begin with:

p "5/2".to_r #=> (5/2)

I don't think there is a remedy for that, except accepting string or float input input only.


Disclaimer: I only have a TI-85, whose commands are slightly different from the TI-83 and TI-84.

User Experience

At first, I was puzzled by the numbering of the squares.  Then I realized that squares 1 to 9 corresponded nicely to the way the calculator number pad is laid out.  Nice!
You could probably do without the lines at ±9, as a tic-tac-toe board is conventionally drawn as #, with no borders.
There's not much point in asking who goes first, in my opinion.
As you noted, you fail to check whether a square is already occupied.  A nine-element list could easily be used to perform that check.

Code

Variables X and O are defined but never used.
I don't know why you chose to name your variables F and M.  I would have picked P for "player" and S for "square".
The two-argument form of the Input command can also display the prompt.
fPart(M/3)3-2→H didn't work for me.  Due to the way precedence of operations works on the TI-85, it is evaluated at fPart((M/3)3)-2→H.  Rewriting it as 3fPart(M/3)-2→H fixes it.
The code to map M to H and V is excessively complicated.  Each assignment should be done in one line:

6(mod(M-1,3)-1)→H
6 int((M-4)/3)→V

The TI-84 has remainder() instead of mod().
The TI-83 has neither remainder() nor mod(), and must use 6(3fPart((M-1)/3)-1)→H.
I believe the latter is works for all three models.
Your use of Goto is unjustified.  I should be initialized, tested, and incremented using a For( loop.
To toggle F between 0 and 1, just do 1-F→F.  You don't need an abs function.
I'm not sure that ClrDraw adequately resets the drawing context.  On the TI-85, I need ClDrw, ZStd (to set the bounds to the standard zoom), and AxesOff (to hide the axes).

Rewrite for the TI-85 dialect

I've noted what I believe the equivalent TI-83 / TI-84 commands are, based on reading the Guidebooks.

:ClLCD                       Equivalent to ClrHome?
:ClDrw                       Equivalent to ClrDraw?
:ZStd                        Equivalent to ZStandard?
:AxesOff
:DrawF -3                    Equivalent to Horizontal?
:DrawF 3
:Vert -3                     Equivalent to Vertical?
:Vert 3
:1→P
:For(I,1,9)
:Input "Square (1-9)? ",S
:6(mod(S-1,3)-1)→H           See portability note above.
:6 int((S-4)/3)→V
:If P
:Then
:Line(H-2,V-2,H+2,V+2)
:Line(H-2,V+2,H+2,V-2)
:Else
:Circl(H,V,2)                Equivalent to Circle?
:End
:Pause
:1-P→P
:End