Because if you define something like:

def foo(**kwargs):
    pass

  Then to call it, you can't do something like:

options = []
options["one"] = 1
options["two"] = 2
foo(options)

  Right?

The aswer is Yes. But there are ways,

**name is used in two ways.

To define optional keyword argumnets in function definiton.

def f(**kwargs): pass. Here the argument of function f, kwargs is optional. You can legitimately call f like f() i.e without arguments. It's utility is you can pass unlimited number of keyword arguments like one=1,...

To unpack a dict to pass arguments at function invocation.

If a function is defined with some arguments whether it's required or optional, its arguments can be passed by **dict when invoking the function. f.e

def f(a,b=2): pass

This function has two arguments one is required. To call it with one argument, you can do,

arg = dict(a=111)
f(**arg)

With two argumnets,

arg = dict(a=111,b=222)
f(**arg)

Combining the two **name form.

def f(**kwargs): pass

can be called as follows,

f()
f(a=1,b=2,c=3)
arg = dict(foo=1,bar=2)
f(**arg)

The send_email method can be simplified.

def send_email(self, from, to, sub, body, **options):
    '''
        This method sends an email by taking four req. args
        from, to, sub, body and optional 'cc' and 'bcc' keyword args
    '''
    from = from
    to = to
    subject= sub
    text = body
    cc = options.get('cc')
    if cc is not None:
            #use this property
    bcc = options.get('bcc')
    if bcc is not None:
            #use this property

The 'docstring' can be checked by calling,

help('classname or obj'.send_email)
'classname or obj'.send_email.__doc__

and can be called as follows,

obj.send_email('me@example.com', 'you@example.com', 'hi', 'howdy', cc='he@example.com')

or

mail1 = dict(from='she@example.com', to='he@example.com', sub='date', body='free tonight?', bcc='you@example.com')
obj.send_email(**mail1)


Function to find all occurrences of substring

I would turn this function into a generator so that an iteration over its values does not unnecessarily build a list into memory. If the caller trully needs a list, they can still call list(find_substring(...)). I would also rename this function substring_indexes as I feel it better convey what this function is about; also index could be something like last_known_position or last_found. But naming is hard and I might be wrong on this one.

def substring_indexes(substring, string):
    """
    Generate indices of where substring begins in string

    >>> list(find_substring('me', "The cat says meow, meow"))
    [13, 19]
    """
    last_found = -1  # Begin at -1 so the next position to search from is 0
    while True:
        # Find next index of substring, by starting after its last known position
        last_found = string.find(substring, last_found + 1)
        if last_found == -1:
            break  # All occurrences have been found
        yield last_found


First off, as said in the comments, C-style comments matches the first /* with the first */; meaning you can not nest comments:

/* This comment is /* a nested */ comment */

should be interpreted as: comment */

It is also more natural, in Python, to iterate over the elements of a collection rather than their indices. This allows you to write for character in content:. And if you trully need indices, you can use enumerate.

You can also use temporary variables to store characters that may indicate the beginning or the end of a comment without having to look at the character before or after the current one:

def remove_comments(content):
    block_comment = False
    line_comment = False
    probably_a_comment = False
    result = []
    for character in content:
        if not line_comment and not block_comment and character == '/':
            probably_a_comment = True
            continue

        if block_comment and character == '*':
            probably_a_comment = True
            continue

        if line_comment and character == '\n':
            line_comment = False
            result.append('\n')
        elif block_comment and probably_a_comment and character == '/':
            block_comment = False
        elif not line_comment and not block_comment:
            if probably_a_comment:
                if character == '/':
                    line_comment = True
                elif character == '*':
                    block_comment = True
                else:
                    result.append('/')  # Append the / we skipped when flagging that it was probably a comment starting
                    result.append(character)
            else:
                result.append(character)
        probably_a_comment = False

    return ''.join(result)

You can also simplify a bit the memory management by using a generator instead of appending into a list:

def remove_comments(content):
    def gen_content():
        block_comment = False
        line_comment = False
        probably_a_comment = False
        for character in content:
            if not line_comment and not block_comment and character == '/':
                probably_a_comment = True
                continue

            if block_comment and character == '*':
                probably_a_comment = True
                continue

            if line_comment and character == '\n':
                line_comment = False
                yield '\n'
            elif block_comment and probably_a_comment and character == '/':
                block_comment = False
            elif not line_comment and not block_comment:
                if probably_a_comment:
                    if character == '/':
                        line_comment = True
                    elif character == '*':
                        block_comment = True
                    else:
                        yield '/'
                        yield character
                else:
                    yield character
            probably_a_comment = False

    return ''.join(gen_content())

If you want to go crazy, you can also use a state machine approach to simplify the code: no more boolean flags and far less comparisons in average:

def source_code(char):
    if char == '/':
        return comment_begin, ''
    return source_code, char

def comment_begin(char):
    if char == '/':
        return inline_comment, ''
    if char == '*':
        return block_comment, ''
    return source_code, '/'+char

def inline_comment(char):
    if char == '\n':
         return source_code, char
    return inline_comment, ''

def block_comment(char):
    if char == '*':
        return end_block_comment, ''
    return block_comment, ''

def end_block_comment(char):
    if char == '/':
        return source_code, ''
    return block_comment, ''

def remove_comments(content):
    def gen_content():
        parser = source_code
        for character in content:
            parser, text = parser(character)
            yield text

    return ''.join(gen_content())

But, all in all, this is far too complicated for the task at hand. You can get the same job done using a simple regular expression:

import re

COMMENTS = re.compile(r'''
    (//[^\n]*(?:\n|$))    # Everything between // and the end of the line/file
    |                     # or
    (/\*.*?\*/)           # Everything between /* and */
''', re.VERBOSE)

def remove_comments(content):
    return COMMENTS.sub('\n', content)


Searching multiple Excel sheets for the cheapest item

Based on the array video provided by TinMan, I now declared the data as an array, and then populate each tab referencing the array.  The code is now instantaneous for 1000s records.

Thanks TinMan!!

'Set MpnQty array

Dim MpnQty() As Variant
Dim Dimension1 As Long, Dimension2 As Long

Sheet1.Activate

Dimension1 = Range("A2", Range("A2").End(xlDown)).Cells.Count - 1
Dimension2 = 1

ReDim MpnQty(0 To Dimension1, 0 To Dimension2)

For Dimension1 = LBound(MpnQty, 1) To UBound(MpnQty, 1)
    For Dimension2 = LBound(MpnQty, 2) To UBound(MpnQty, 2)
        MpnQty(Dimension1, Dimension2) = Range("A2").Offset(Dimension1,   Dimension2).Value
    Next Dimension2
Next Dimension1

'Add MPN and Qty to Summary page

Sheet22.Visible = True
Sheet22.Activate

For Dimension1 = LBound(MpnQty, 1) To UBound(MpnQty, 1)
    For Dimension2 = LBound(MpnQty, 2) To UBound(MpnQty, 2)
        Range("A2").Offset(Dimension1, Dimension2).Value = MpnQty(Dimension1, Dimension2)
    Next Dimension2
Next Dimension


Problem 1
Consider that register_idle() is equivalent to this slightly rewritten version:
// this function is called by each thread when it is about to sleep
void register_idle(size_t thread_id)
{
    std::atomic_thread_fence(std::memory_order_release);
    uint8_t pos = idle_pos.fetch_add(1, std::memory_order_relaxed);

    // What happens when this thread stops right here?

    idle_ids_stack[pos] = thread_id;
}

If the thread stops after incrementing idle_pos, but before writing the actual thread id to the stack, you will be in trouble when another thread tries to wake up the thread at the top of stack.  It will try to read a thread id from the stack that has not yet been written.
Problem 2
(Credit @MikeMB for correcting me on my previous answer)
You have a problem in wakeup_one() as well.  Suppose idle_pos is 2 and idle_ids_stack[1] is 5.  Now consider the following sequence of events:

Thread 1 runs wakeup_one() and executes id = idle_ids_stack[old_pos-1], so at this point, id is 5.  But now thread 1 sleeps for a little while.
Thread 2 runs wakeup_one(), grabs the same id (5), and returns it, setting idle_pos to 1 in the process.
Thread 3 runs register_idle(), puts its id (3) into idle_ids_stack[1] and increments idle_pos back to 2.
Now thread 1 resumes, and compare-exchanges idle_pos from 2 to 1 successfully.  But it returns id as 5 (a duplicate thread id), instead of 3 (the proper one).


Sorting lists by various measures of goodness

You could try that:

def sort[A, B: Ordering](data: List[A], desc: Boolean)(measure: A => B): List[A] = {
    val baseOrdering = Ordering.by(measure)
    val ordering = if (desc) baseOrdering.reverse else baseOrdering
    data.sorted(ordering)
}

Then you do

sort(listOfFirstClass, desc)(_.good)


A couple of minor style points:

In check_balance() the return can be simplified from:

if len(stack) > 0:
    return False
return True

to:

return len(stack) <= 0

In generate_balance_string() there is a long if/elif string.  But the first
element does not follow the pattern and has an embedded return it does not need.
You can drop the return and make the following if an elif to make your code more uniform:

def generate_balance_string(source, index, prefix, result):
    if index >= len(source):
        result.append(prefix[:])
    elif source[index] == ':' and source[index + 1] == '(':
        ...


Here are some comments to your code, which will be followed by an alternate implementation:

Use functions to do the rotation – If you have learned about functions I would strongly suggest to use functions to do the actual rotation. You call it with the string to rotate and rotation offset, and you'll get the rotated string in return.
Avoid magic numbers – In your code you use magic numbers like 122 and 97, your code looks cleaner if you replace these by what they actually are: ord('z') and ord('a'). Alternatively use constants like ALPHABET_LENGTH = 26, but I'll come back to this one
Don't hide reserved words or modules – decimal is a module in Python, and to use that as a variable name is considered bad practice.
Naming scheme dictates to use snake_case –  Instead of newmessage it is recommended to use new_message and similar. This reads more easy.
Be consistent on indentation – You use a varying amount of spaces to indent your code, please be consistent and use 4 spaces. The previous and this item is related to conforming to the PEP8 guidelines. Please read and follow these guidelines, as that is quite common when using Python.

Algorithm considerations

If keeping to your format of not using functions, there are still some issues related to your algorithmic choices:

What about letters not in the lowercase alphabet? – You don't handle punctuation chracters and non-alpha characters so these would leave somewhat strange behaviour
You don't have a means to exit your code – You are essential having an eternal loop, leaving you to kill the program execution as only means of leaving it
Range checks can be joined in Python – Instead of doing one lower than and one larger than you could do 97 < var < 122 to verify a complete range (This will make better sense in code example below)
range() default to start at 0 – That is range(0, 26) and range(26) is the same, and the latter is preferred for clarity
You don't need to do (expr), unless you want line continuation – It is better to write new_message += chr(decimal) without the extra parentheses. You could use them if you want to spread the expression within over multiple lines, but normally keep the expression without.

Adhering to my style and algorithmic considerations we arrive at this code:

ALPHABET_LENGTH = 26

while(True):
    message = input("What would you like the message to say? ").lower()

    if message == "quit":
        break

    for i in range(ALPHABET_LENGTH):
        new_message = ""
        for letter in message:
            if 'a' <= letter <= 'z':
                char_pos = ord(letter) - ord('a')

                # Rotate by i, and make sure we're within alphabet
                char_pos = (char_pos + i) % ALPHABET_LENGTH

                new_message += chr(char_pos + ord('a'))

                # new_message += chr((ord(letter) - ord('a') + i) % ALPHABET_LENGTH + ord('a'))
            else:
                new_message += letter

        print (new_message)

Within the rotation block there is a commented line which could replace all of the other code, but it is not so easy to read and understand as the uncommented code.

Alternate implementation with functions

In general I would rather use functions to do stuff like this, and I would encapsulate my entire program within a if __name__ == '__main__': block to allow for module execution. That is that the script could be imported as a module, and you could call the different functions to add caesar-cipher rotation to other programs of yours.

One version of this could be like this:

from string import ascii_lowercase

def rotate_lowercase_char(char, offset):
    """Return lowercase <char> rotated by <offset> characters.

    If <char> is a lowercase character rotate it, or else return
    it unchanged allowing for non-alpha characters to be present."""

    if not char in ascii_lowercase:
        return char
    else:
        position = ascii_lowercase.index(char)
        position = (position + offset) % len(ascii_lowercase)
        return ascii_lowercase[position]

def rotate_lowercase_text(text, offset):
    """Return <text> rotated by <offset> characters."""

    return ''.join(rotate_lowercase_char(letter, offset) for letter in text)

def main():

    while(True):
        message = input("What would you like the message to say? ").lower()

        if message == "quit":
            break

        for i in range(len(ascii_lowercase)):
            print("Offset: {}, Rotated: {}".format(i, rotate_lowercase_text(message, i)))

if __name__ == '__main__':
    main()

This uses string.ascii_lowercase for the set of lowercase letters and a positional approach for rotating a letter a given approach. The methods could be extended using default parameters to allow for other characters sets, but that is left as an exercise to the reader.

Furthermore I've presented two functions here one for rotating the entire string, and one for rotating a single character. These could have been combined, but I like the single responsibility principle of letting one function doing exactly one thing.

Lastly I've kept the main logic from the original post, only embedded it into a main(), and added some extra information related to the output to display the various rotation offsets used for presenting the text.

For even more various alternative implementation look at other posts here at Code Review tagged caesar-cipher (in a variety of languages). Both shorter and longer and simpler and more complex variation exists.


Loop + Take for repeatedly taking elements from the same collection

Code optimization

This can be shortened:

while (true)
{
    if (TryMoveNext(enumerator, out enumerator))
    {
        moves++;

        if (startAt > 0 && moves <= startAt)
        {
                continue;
        }

        yield return enumerator.Current;
    }
    else
    {
        yield break;
    }
}

To:

while (TryMoveNext(enumerator, out enumerator))
{
    moves++;

    if (startAt > 0 && moves <= startAt)
    {
        continue;
    }

    yield return enumerator.Current;
}

You added the if for "boolean breaking", but at the same time you've subverted the inherent "boolean breaking" that a while loop provides.

Enumeration needed?

Since you are looking to repeat the same collection multiple times, this collection is cyclic in nature. Whenever I think about cyclic data, the modulo operator always comes to mind. It's by far the most common use case for the modulo operator.

According to this SO answer, though there may be a minor difference, the performance difference between enumeration and indexed arrays is reasonably negligible.
Keeping that in mind, I would advocate using a modulo operator simply because it keeps the code cleaner.

Note: The linked answer does not address re-enumeration, which is relevant for your code. But tbh, I'm not sure if re-enumeration is cached (thus not costing any meaningful overhead) or not. I'm going to continue my assumption that the performance differences are too small to be considered relevant for your current use case.

public static IEnumerable<T> Loop<T>(this IEnumerable<T> values, int startPosition = 0)
{
    if (values == null)
    {
        throw new ArgumentNullException(nameof(values));
    }

    T[] array = values.ToArray();
    int count = values.Count();

    while (true)
    {
        yield return array[startPosition++ % count];
    }
}

I kept the example terse (e.g. by inlining startPosition++), but I hope it highlights the reduced complexity of the code in general.

A slight improvement would be to not let startPosition grow beyond the array's size:

    while (true)
    {
        startPosition = (++startPosition) % count;
        yield return array[startPosition];
    }

Though I think this is only really useful if you expect to enumerate up to a point of integer overflow, which I doubt is the case here.

Footnote

I'm torn about the startPosition variable name. Once we start using it as a counter, its name is no longer correct (it's the current position). However, I do think it fits as a parameter name.
We can assign the value to a variable with a better name; but I'm not sure if it's really that necessary for such a terse piece of code.

I can see arguments for either case. I'm unable to make a conclusive decision on whether it's necessary. I'm open to feedback on this.

If you do want to make the name more appropriate, I would suggest the following:

public static IEnumerable<T> Loop<T>(this IEnumerable<T> values, int? startPosition = null)
{
     //...

     int counter = startPosition ?? 0;

     //...
}


This already seems pretty good considering you just started learning coffeescript.

for k, v of obj
     if v < min_v
       min_v = v
       min_k = k

Personally, I'm a huge fan of comprehensions. I would change the above to the following.

for k, v of obj when v < min_v
    min_v = v
    min_k = k

Your declarations at the top can be refined. No need for brackets/commas.

nodes_dir = {
0 : [1],
1 : [0, 2, 3, 5],
2 : [1, 4],
3 : [1, 4, 5],
4 : [2, 3],
5: [1, 3]
}

Can be simplified to just

nodes_dir =
    0: [1]
    1: [0, 2, 3, 5]
    2: [1, 4]
    3: [1, 4, 5]
    4: [2, 3]
    5: [1, 3]

Regarding the following

links.push link[current_node] if link[current_node] > 0

Don't lookup the value in the array based on the index twice.

linkNode = link[current_node]
links.push linkNode if linkNode > 0

Lastly,

intree = []
distance = []
link = []
parent = []

# set default values for record-keeping arrays
for i in [1..NUM_NODES]
    intree.push -1
    distance.push MAX_WEIGHT
    link.push -1
    parent.push -1

I would suggest creating an object that has these four arrays as properties, as well as putting that initialization code (the for loop) inside it's own method. This would add to clarity/reusability. Also, put all this code inside a coffeescript class declaration, which has a huge host of benefits.


version.ToString(fieldCount) already returns the required amount of numbers. The first character of a variable is usually lower case. Parts contains the numbers in an array, you just need to modify that array and use the String.Join to get your number back. If you pass fieldCount of 0, you don't need to split anything.

<Extension()> Public Function ToString(version As Version, fieldCount As Integer, fieldPadding As Integer) As String

    If fieldCount = 0 Then
        Return String.Empty
    End If

    Dim parts As String() = version.ToString(fieldCount).Split("."c)

    For i As Integer = 0 To parts.Count - 1
        parts(i) = parts(i).PadLeft(fieldPadding, "0"c)
    Next

    Return String.Join(".", parts)
End Function

An alternative would be to look at the code and do your own instead of splitting.


Moving a decision into code that gets executed earlier, with later code merely telling an object to "do whatever it is we decided earlier" is one of the techniques of confident programming.  It's often a good idea, and I think it is well applied here.

Is there a better name for the filter option?

There may be a more descriptive name for the option than "filter."  The trouble is that "filter" might be interpreted as "here are the things I want", instead of "here are the things I don't want."

A less ambiguous name for this option might be "except," "reject", or "exclude".  You get the idea.

Similarly, you might consider renaming the instance method @filter.

Set proc in constructor

Uri is correct that it is better, if you are going to do this, to create the proc just once.  He does so using lazy evaluation.  You might also consider just setting it in #initialize:

def initialize(string, options = {})
  @filter = filter_proc(options[:filter])
  ...
end

# Your filter method, renamed, and made to take an argument
def exclude_proc(filter)
  if filter.is_a?(String)
  ...
end

Use type coercion methods

Rather than testing the option's class, consider testing whether the object responds to a coercion method that converts it to that class.  So, instead of:

if filter.is_a?(String)
  # the code that converts a string to a proc

you would do this:

if filter.respond_to?(:to_str)
  filter = filter.to_str
  # the code that converts a string to a proc

String responds to #to_str, so filters of those types will continue to work fine.  But now the caller can pass in, as well as a String, any object that responds to #to_str.

By the way: We use #to_str instead of #to_s because #to_s will convert pretty much anything to a string.  #to_str only converts to a string objects which wish to be treated like strings.

You can use the same idea for regular expressions, but you cannot do it the same way.  The convention is that an object that responds to #to_regexp can be treated as a Regexp, but for some strange reason Regexp does not respond to #to_regexp.  Instead, you have to use Regexp.try_convert:

elsif Regexp.try_convert(filters)
  filters = Regexp.try_convert(filters)
  Proc.new { |w| w =~ filters }

If given a Regexp, .try_convert will return it.  If given an object that responds to #to_regexp, .try_convert will return the result of that method.  Otherwise, it returns nil.

Consider allowing procs

It's trivial to allow the caller to pass in a callable object, such as a method:

counter = Counter.new("That was magnificent, Trevor.",
                      filter: method(:exclude_word?))

or a lambda:

counter = Counter.new("That was magnificent, Trevor.",
                      filter: ->(word) { foo(word) || bar(word) })

In the code that makes the proc:

...
elsif filter.respond_to?(:to_proc)
  filter.to_proc
...

By allowing this, you give the caller the ability to make decisions that don't fit comfortably in a list of words or a regular expression.

Consider allowing arrays

Once you've made method filter take an argument, you can use a bit of recursion to allow it to take arrays of filters:

def filter_proc(filter)
  if filter.respond_to?(:to_a)
    filter_procs = Array(filter).map(&method(:filter_proc))
    Proc.new do |w|
      filter_procs.any? { |p| p.call(w) }
    end
  ...
end

Interestingly, nil responds to #to_a with an empty array.  That works out fine, because the the result of #any? on an empty array is false.

The caller may now pass in an array of words:

Counter.new("That was magnificent, Trevor.",
            filter: ["That", "was"])

An array of regular expressions sill also work:

Counter.new("That was magnificent, Trevor.",
            filter: [/That/, /was/])

Also, since Enumerable responds to #to_a, the possibilities are endless.  This makes the API flexible enough that the caller can do anything needed, but still rational enough to understand and reason about.  Best of all, it's done pretty simply.

Catch incorrect filter types

If the caller passes in a filter type that the code does not understand, it acts as though there is no filter.  Consider raising an exception instead:

def filter_proc(filter)
  if ...
  ...
  else
    raise ArgumentError, "Incorrect filter type"
  end
end

Use require_relative for spec_helper

In the spec, consider using require_relative to load the spec_helper:

require_relative '../spec_helper'

This will allow the spec to be run no matter what the current directory is.

Consider using lambdas instead of procs

Everything you are doing here with procs can be done with lambdas, and more concisely.  For example, this:

Proc.new { |w| w =~ filter }

could be expressed as:

lambda { |w| w =~ filter }

or, using the "stabby" operator:

->(w) { w =~ filter }


Abstract classes and interfaces in a game inventory system

I think your design introduces a few more dependencies than it should.

Let's have a look at your IUsable interface

public interface IUsable<Player> {
    void Use ( Player player );
}

Do you really need to have a dependency on Player? Why don't you just require it to depend on IUser?

I'd also completely get rid of the Item class. What do you need it for? If you want an abstract class to represent a NamedItem you can create it but you should do it in the following way:

public abstract class NamedItem implements IUsable<IUser>
{
    public string Name {get; private set;} // Better to keep it immutable

    protected NamedItem(string name)
    {
        Name = name;
    }

    public abstract void Use(IUser user);
    /*
     * This way we don't need to provide a
     * default implementation and your subclasses
     * will be forced to provide it.
     */
}

I think you should probably also revise who should be in charge of implementing the Use method. From the names you're using it is quite clear that it is more natural to think at a player that uses an item. That's fine but what your code suggests is that different objects should be used in different ways, hence you need to implement it on the specific Item instance.

Does spreading the logic on how a player uses an item across a lot of different items makes sense in your project? If you don't want to do it you might want to have a look at dobule dispatch as a possible way to retain all the behaviours on player instead than on objects. If you do double dispatch you can have interfaces such as IFood and then have a method in Player with this signature void User(IFood food). IFood should expose a way to determine how many energy is added by the food to the player and the mutation of the state of the player should happen in the specific method you just created.

If you show us how you intend to use those classes we can help you find the best way to design them.


Need help optimizing & improving this php form script

I've tried to address as many things as I could think of, though I'm not sure how relevent a lot of them will be :).

Anyway, on a lot of things I just glossed over the subject for brevity, however, if you have any questions or want me to defend any statements, I gladly will if prompted.

error_reporting

I tend to leave error_reporting and display_errors out of PHP scripts as much as possible.  Those should ideally be server-wide settings more so than application specific.  A development server should always have error_reporting(E_ALL) and display_errors = On and a production server should always have error_reporting(E_ALL) and display_errors = Off.  If error reporting ever has to be lowered to accomdate variable doesn't exist or undefined index type notices, that's a sign of bad code.

Magic Quotes

If magic quotes is on, either turn it off, or if not possible, move servers.  Magic quotes is an ancient, horrible mistake PHP made, and no server admin should ever have it enabled.

get_string

You're doing too much in this function.  The name and the function signature gives the impression that it gets a string if it exists in an array, and otherwise returns the default.

What is actually happening though is much more than this.

Also, the logic in it is a bit misleading.  What if you call it with a default that is not the empty string, but then an empty string is in the array?  Because of the strlen check, the non empty default is going to be picked.  Also, I would not expect this function to be calling trim.

In my opinion, this function needs either better documentation, a better name, or both.  (Or pull the multiple behaviors into multiple functions.)

I would probably implement this function as follows:

function array_get(array $array, $key, $default = null)
{
    return (array_key_exists($key, $array)) ? $array[$key] : $default;
}

I might then build on top of this:

function array_get_string(array $array, $key, $default = '')
{
    $val = array_get($array, $key);
    return (is_string($val)) ? $val : $default;
}

Or, if you wanted to bake in the trim functionality:

function array_get_string(array $array, $key, $default = '', $trim = true)
{
    $val = array_get($array, $key);
    if (is_string($val)) {
        return ($trim) ? trim($val) : $val;
    }
    return $default;
}

Another example of how you could build on it:

function array_get_digits(array $array, $key, $default = 0)
{
    $val = array_get($array, $key);
    if (is_int($val) || ctype_digit($val)) {
        return (int) $val;
    } else {
        return $default;
    }
}

test

Globals are evil.  I'm too lazy to back it up in this post, but the key points:
* ties your code to them (you must always use variables named $errors and $required_errors.  What if you want to call test and have it populate a different set of variables?)
* your code no longer gets along with code you didn't write.  What if a different piece of code happens to use $errors and your code silently clobbers it?
* much harder to maintain -- it's difficult to follow the mutation of a variable when it's done in a far off place with no easily traceable execution flow

What you should do instead is to return an array containing the errors.

Also, test is a bad name.  What are you testing?  Perhaps validateField or testInputField or something along those lines.

When sanitizing should happen

$post = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );

This is done too early.  Your validations should see text as it actually is, not as valid HTML.  SANITIZE is a bit of a misnomer here.  It should actually be something like FILTER_ESCAPE_HTML or something.  HTML escaping only makes sense in the context of HTML.  Your validations are seeing text, not HTML.

This becomes a lot more important if you're storing information in a database.  Once you store text transformed, it becomes harder to search for it, and it becomes harder to predict the length of it.

The length could actually apply to your situation as well.  a & b is 5 characters, however, a &#38; b is 9.  What if you had a field that had a max of 5 characters?  Suddenly the user is very confused as to why his input is failing.  (Also, a &#38; b is meaningless outside of HTML.)  Since your email is plaintext, you would actually see &#38; in your email.

In short, escape at the last possible moment.

Random design input

I might approach your forms a bit more abstractly.  For example, I might take your array idea ($fields) and consider that a "form".  Then a validateForm function could take all of the elements in the form and check them for errors.  This function would return an array of any errors (or perhaps: array('errors' => [errors], 'valid' => [valid field's values]).  This would still use most of the same code you have now, just structed a bit differently.

Also, I would consider making 'validation' be an array.  What if at some point in the future you want to apply multiple validations to a field?  ("If it's wrong in way X, show one message; if it's wrong in way Y, show a different message").

Another design point: I would make 'required' be handled like any other error.  There's not really a reason to only validate until you come across the first empty required field, and this requires complicating the error handling code.

Type strictness

PHP's implicit type system is a bit odd at times.  For example, 0 == '' is true.  That means that in situations like $field['value'] == '' you should likely use $field['value'] === ''.

Or perhaps:

$field['value'] === '' || $field['value'] === null

I highly advise learning the type system and related materials (isset/empty/array_key_exists/etc).  PHP has lots of little quirks that can bite you (and have bitten me many times before I became paranoid :p).

Optimizing

The script looks fine in terms of performance.  The main time-taker in it will be the mail() call, and assuming your mail server is quick to respond, that shouldn't be significant.

mail

I like to use packages like Zend_Mail or PHPMailer.  For a simple email with a simple server setup, though, mail should be fine.  (For example, mail and SSL would be an unpleasant combination.)

I might worry about whether or not mail succedes though.  Might be nice to warn users that mailing failed.

Style

This section is 100% opinion

array_push is pretty rare to see in modern code.  There's borderline cases where it's actually better, but for visual reasons, most people prefer the $array[] syntax.

The following are equivalent:

$arr[] = 5;
array_push($arr, 5);

if (count($errors) or $required_error)

Would usually be written as:

if (count($errors) || $required_error)

(Though or and || are not interchangeable, they are in this situation.  In situations that do not explicitly call for or, || is typically used.)

if ($required_error == true)

Is a bit redundant.  It should just be:

if ($required_error)

The only time to use == for true is when you're strictly checking:

if ($required_error === true) //true iff $required_error is boolean true.  For example, $required_error = 1 would be false because 1 !== true.

I wouldn't mix # and // comments.  Just a being-picky thing, but it looks a bit odd to have both in one file (or really both in one codebase).  // is pretty much the standard in PHP, though both are just as well supported.

I would consider using heredoc style comments.  They can be parsed by IDEs like Netbeans and can be used to generate HTML documentation.  For example:

/**
 * Takes an array, an index for the array and an optional $default and returns $array[$index]
 * if it exists, or otherwise $default.
 *
 * @param array $array The array from which to select the data
 * @param string|int $index The index of the array
 * @param mixed $default The value to return if $index is not in $array
 * @return string $array[$index] if it exists, otherwise, $default
*/
function get_string(array $array, $index, $default = '')

Depending on how clear names are, documentation is often not needed for small code bases, but it's very helpful when you come back a year later and have to figure out what's going on in a function.

Note also that I made it so that $array must be an array.  This is only possible in PHP for certain types (array and classes).


Simple networking layer in Swift using Strategy design pattern

What you have is not a Strategy pattern... The key features of the Strategy pattern is that once the Strategy object is inserted into the Context, it is not referenced from outside the Context. Your view controller is still rooting around inside the Context object for the strategy object.

The simplest way to solve this is to have the view controllers be the context. Then you would have a protocol:

protocol API {
    func insert(user: User)
    func insert(message: Message)
    func insert(imageData: Data, toUserID: String)
    func findUser(withID: String, completion: @escaping (User) -> Void)
    // etc...
}

Then you would have a FirebaseAPI that would implement this protocol and a TestAPI that would implement it. The TestAPI would just return canned data so you can test all the possible permutations.


You should 'spread out' your code more, k==0 kinda looks like a variable,
and if k==0: return n==0 doesn't really look like an if statement at first.

Single letter variable names are bad, amount_bottles is better then n.
You could even use bottles and it would still be better.

T is not an allowed name for a function according to PEP8 Python's style guide.
Capital letters are only used in constants, and classes.

As for your performance concern,
I would recommend using memoization in a wrapper.
memoization remembers output, and so you re-use the output rather then re-find it.
It's really good in recursive functions.

def memoize(fn):
    outputs = {}
    def inner(*args):
        try:
            return outputs[args]
        except KeyError:
            outputs[args] = fn(*args)
            return outputs[args]
    return inner

def permutations(bottles, crates, BOTTLES_CRATE):
    @memoize
    def inner(bottles, crates):
        if crates == 0:
            return bottles == 0
        crates -= 1
        return sum(
            inner(bottles - i, crates)
            for i in xrange(BOTTLES_CRATE[crates] + 1)
        )
    return inner(bottles, crates)

print(permutations(30, 20, range(1, 21)))

This took under a second to get 6209623185136.

Just to note, memoization requires no side effects to happen.
So if you use an outside variable then that can break the memoization.

For example, if we were to memoize addition of a number plus a global variable,
it is prone to breakage.

inc = 4

@memoize
def add(num):
    return num + inc

add(4) # 8
inc = 0
add(4) # 8
add(0) # 0

If you were to want to expand on your above code,
and you make BOTTLES_CRATE a variable,
then you would have to pass BOTTLES_CRATE via the memoizer too.
Just like we should inc in the above.

@memoize
def add(a, b):
    return a + b

add(4, 4) # 8
add(4, 0) # 4

As I use a dictionary to store the arguments,
you will need to cast BOTTLES_CRATE to a hash-able type, e.g. a tuple.
This may lead to a non-transparent solution, where you can just add @memoize.

Another bad use-case is if add 'returns' from it's internals to another variable.

list_ = []

@memoize
def push(num):
    list_.append(num)

push(2) # list_ == [2]
push(2) # list_ == [2]

And so if there are possible side effects, you may want to chose a different method in future.


Snippet to get all local classes from a module

I have already used similar code and it looks rather fine. Some nitpicks:

I’d name the variable cls to mimic the name often used as first parameters of @classmethods; or class_ as it is more common;
I’d store a list of classes intead of a list of names, this feels more directly usable (and names are still stored as cls.__name__ if need be);
sys.modules[__name__].__name__ should be just __name__.

Alternatively, since these classes seems related to each other, you may have an inheritance tree; or maybe a common base class. In this case, you could be even more specific using something such as:

[cls for _, cls in inspect.getmembers(my_module, inspect.isclass) if issubclass(cls, my_module.CommonBase)]

or

my_module.CommonBase.__subclasses__()

if there really is a single level of inheritance, but I wouldn't count much on it as it can break so easily.


The link is dead and the code doesn't compile, but there is still an obvious issue to critique:  Part of the challenge was to not save state with "global variables."  In Go, package variables of the package main are typically considered "global variables".  However, only a single instance of any package ever exists at run time, so package variables of all packages are essentially global variables as well.  The code here uses a package variable fib.Fib, thus the code is failing the exercise from the start, working or not.

Edit:  Thank you Anthony for tracking down the archived course and updating the question.  It helps to have the full context.  It also helps to have code working with a current version of Go, which is pretty easy:

package fib

type BinOp func(uint64, uint64) uint64

var Fib func(op BinOp) uint64

func init() {
    Fib = func(op BinOp) uint64 {
        return fib_intern(0, 1, op)
    }
}

func fib_intern(a, b uint64, op BinOp) uint64 {
    Fib = func(opnew BinOp) uint64 {
        return fib_intern(b, op(a, b), opnew)
    }
    return a
}

Go now has stricter checking of static dependencies and reports "initialization loop" with the old code.  My update of your code works by moving the initial assignment of Fib to an init function, which runs at program startup.

I'll abandon this answer now and add another answer where I try to stick to your request for a review of the 'Go'-iness.


String Calculator kata in JavaScript using TDD

beforeEach(function() {
  calculator = new StringCalculator();
});

I usually recommend not using things like beforeEach (and similarly afterEach). The problem is that your tests are now implicitly dependent on an operation that's not referenced or even called anywhere in the test body. It's not immediately clear that a calculator was defined for each test. It's also not clear if it's a per test instance or a shared instance.

Tests should be independent and self-contained. The general rule I follow  is I should be able to cut and paste a test to any part of the suite and still have it work, or remove it without affecting other tests. You can have shared utility functions that are called explicitly in the test body so that it's clear to the reader what happened, where something was obtained, etc.

function StringCalculator(){...}
StringCalculator.prototype.add = function(string_numbers) {...}

Although the rules mention "a method" which immediately would imply an instance and therefore classes, you don't necessarily need one. You'll only need a function that takes an input and gives an output. Keep it simple.

it("should return the sum of an unknown amount of numbers", function(){
  // creates a random array
  randomArray = (length, max) => [...new Array(length)]
  .map(() => Math.round(Math.random() * max));
  // creates a random number between 1 and 100
  randy = Math.floor((Math.random() * 100) + 1);
  res = randomArray(randy,randy);
  // sums up an array
  sum = res.reduce((pv, cv) => pv+cv, 0);
  // converts the array to a string
  arg = res.join();
  expect(calculator.add(arg)).toEqual(sum);
});

Never forget to use var, let or const if you don't want these variables to be defined in the global space (or at least the top level of the module). I usually recommend const whenever possible to ensure nothing has manipulated the variable since creation and let if you need to mutate it at some point (i.e. counters). Both are also block-scoped, eliminating guesswork and hoisting.

    var total = 0;
    var arrayLength = res.length;
      for (var i = 0; i < res.length; i++) {
        total = total + parseInt(res[i]);
      }
      return total;

You can use array.reduce to accumulate values. It iterates through an array and uses the callback return value as first argument of the next call. An initial value can be supplied, otherwise iteration starts at the second value with first value as initial value.

Also, always check for NaN when converting strings to numbers. NaN passes through calculations, NaNing everything along the way. It's annoying to track the source of NaN and it may be very far from where it's spotted. Guarding near wherever it potentially comes up is a good practice.

Updating your logic:

function add(stringNumbers){
  const numbers = stringNumbers
    .replace(/(\r\n|\n|\r)/gm, ',') // Normalize delimiter
    .split(',')                     // Split values
    .map(n => parseInt(n, 10))      // Convert to integers

  // Check if numbers are ok. There's probably better APIs
  // to check if something in the array is invalid.
  if(numbers.some(n => Number.isNan(n))) throw new Error('Not a number')
  if(numbers.some(n => n < 0)) throw new Error('Negatives not allowed')

  // Add them all up
  return numbers.reduce((s, n) => s + n)

}


Create a generator that returns every permutation (unique arrangement) of positive integers up to n

Style
Readability is impaired because you don't use the space bar enough. Put a space around = for assignments, after ,, around binary operators. Parenthesis are also not required in if statements.
You also use 1-letter variable names which doesn't convey any meaning, which makes it harder to understand the code.
Duplicated work
gen_perm and gen_perm_reverse are basically the same function with some minor tweaks: the range and the "increment" function to call. Increments functions are the same too, only the comparison (< vs > and min vs max) change.
You can merge the two of them and parametrize it with a reverse parameter that default to False.
import operator

def permutations(n, reverse=False):
    numbers = range(1, n+1)
    permutation = tuple(reversed(numbers) if reverse else numbers)

    yield permutation
    while True:
        permutation = next_permutation(permutation, reverse)
        if not permutation:
            return
        yield permutation

def next_permutation(permutation, reverse=False):
    compare = operator.lt if reverse else operator.gt
    top = max if reverse else min

    max_length = len(permutation) - 1
    for i in range(max_length):
        x = max_length - i
        permutable = permutation[x - 1]
        if compare(permutation[x], permutable):
            m = top(i for i in permutation[x:] if compare(i, permutable))
            cl = list(permutation[x:])
            cl[cl.index(m)] = permutable
            return permutation[:x-1] + (m,) + tuple(cl[::-1])

A couple of changes here:

Instead of raising StopIteration, you can just return from a generator. In any case, having a break after a raise is poor practice since it is unreachable code.
I computed len(permutation) (len(l)) less time in next_permutation and assigned l[y] to a variable to reduce the cost of retrieving it.
I removed the call to tuple when creating the object to be returned since it already it a tuple.
The last return was also unnecessary as it is implicit anyway.

The drawback of this approach is that you now perform much more comparisons to reverse to be able to get the right comparison functions. You can get rid of it either by passing the functions as parameters or by combining both functions:
import operator

def permutations(n, reverse=False):
    numbers = range(1, n+1)
    compare = operator.lt if reverse else operator.gt
    top = max if reverse else min
    permutation = tuple(reversed(numbers) if reverse else numbers)
    max_length = n - 1

    yield permutation
    while True:
        for i in range(max_length):
            x = max_length - i
            permutable = permutation[x - 1]
            if compare(permutation[x], permutable):
                m = top(i for i in permutation[x:] if compare(i, permutable))
                cl = list(permutation[x:])
                cl[cl.index(m)] = permutable
                permutation = permutation[:x-1] + (m,) + tuple(cl[::-1])
                break
        else:
            # We didn't break -> no more permutations available
            return
        yield permutation

Here I used the for .. else construct to detect when we couldn't produce an new permutation and stop the generation accordingly.
Building on my comment
As I said in a comment, the most straighforward way to achieve that in python is by using itertools.permutation:
import itertools

def permutations(n):
    return itertools.permutations(range(1, n+1))

the advantage, beside its simplicity of use, is that the reverse version is straighforward too:
def permutations(n, reverse=False):
    numbers = range(1, n+1)
    return itertools.permutations(reversed(numbers) if reverse else numbers)

But being able to use both the forward and reverse iteration had me thinking about defining a class:
import itertools

class Permutations:
    def __init__(self, n):
        self.numbers = range(1, n+1)

    def __iter__(self):
        return itertools.permutations(self.numbers)

    def __reverse__(self):
        return itertools.permutations(reversed(self.numbers))

Usage being:
perm_3 = Permutations(3)
for i in perm_3:
    print(i)
for i in reversed(perm_3):
    print(i)

The advantage here is that, if you really don't wan't to use itertools, you can plug in your custom function easily:
import operator

class Permutations:
    def __init__(self, n):
        self.numbers = range(1, n+1)

    @staticmethod
    def _permutation_helper(permutation, compare, top):
        max_length = len(permutation) - 1

        yield permutation
        while True:
            for i in range(max_length):
                x = max_length - i
                permutable = permutation[x - 1]
                if compare(permutation[x], permutable):
                    m = top(i for i in permutation[x:] if compare(i, permutable))
                    cl = list(permutation[x:])
                    cl[cl.index(m)] = permutable
                    permutation = permutation[:x-1] + (m,) + tuple(cl[::-1])
                    break
            else:
                # We didn't break -> no more permutations available
                return
            yield permutation

    def __iter__(self):
        return self._permutation_helper(tuple(self.numbers), operator.gt, min)

    def __reverse__(self):
        return self._permutation_helper(tuple(reversed(self.numbers)), operator.lt, max)


There are a few things to note here. There is extensive referencing and dereferencing of variable addresses, which makes the code less clear. For example, float *x,y; x = &i; y = 1 + *x;.  This is unnecessary and seems imposed by thinking related to your use of global variables.

There is nothing wrong with passing pointers as arguments to functions, rather than using global variables.

There is also nothing wrong with using functions. The code below is clearer. Additionally, it removes the need for the function "annualRate," as that is simply a division.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

void loanDetails(float * loanAmount, int * years, float* interestRate);
float discount(int years, float i);

int main (void) {
    float loanAmount, interestRate, disc;
    int years;

    loanDetails(&loanAmount, &years, &interestRate);
    disc = discount(years, interestRate/1200);

    printf("\nthe value of discount is : %f",disc);

    printf("\nthe monthly loan payment is %f",loanAmount/disc);
    return EXIT_SUCCESS;
}

void loanDetails(float * loanAmount, int * years, float* interestRate) {
    printf("please enter Total Loan Amount: ");
    scanf("%f",loanAmount);
    printf("please enter the number of years: ");
    scanf("%d",years);
    printf("please enter the annualrate to be applied: ");
    scanf("%f",interestRate);
}
float discount(int years, float i) {
    int months = years*12;
    return (pow((1+i),months)-1)/((i)*pow((1+i),months));
}

If you wanted no functions other than main, you could do the following. Essentially, move the code from the functions to main. This is appropriste, considering that the code is not repeated, runs sequentially, and does not have varied/multiple inputs.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int main (void) {
    float loanAmount, interestRate, disc, i;
    int years, months;

    printf("please enter Total Loan Amount: ");
    scanf("%f",&loanAmount);
    printf("please enter the number of years: ");
    scanf("%d",&years);
    printf("please enter the annualrate to be applied: ");
    scanf("%f",&interestRate);

    months = years*12;
    i = interestRate/1200;

    disc = (pow((1+i),months)-1)/((i)*pow((1+i),months));

    printf("\nthe value of discount is : %f",disc);

    printf("\nthe monthly loan payment is %f",loanAmount/disc);
    return EXIT_SUCCESS;
}


Handling Excel column letter index as struct

Why is that the case?

You need to know what the string + operator does under the covers - it calls String.Concat.

So when you do this:

var someString = aString + anObject;

We get this:

var someString = string.Concat(aString, anObject);

Let's look at the IL for your example:

C#

void Main()
{
    int rowIndex = 1;
    ExcelColumn column = new ExcelColumn(1);
    string cellId = column + rowIndex.ToString();
}

IL

IL_0000:  nop
IL_0001:  ldc.i4.1
IL_0002:  stloc.0     // rowIndex
IL_0003:  ldloca.s    01 // column
IL_0005:  ldc.i4.1
IL_0006:  call        UserQuery+ExcelColumn..ctor
IL_000B:  ldloc.1     // column
IL_000C:  box         UserQuery.ExcelColumn
IL_0011:  ldloca.s    00 // rowIndex
IL_0013:  call        System.Int32.ToString
IL_0018:  call        System.String.Concat
IL_001D:  stloc.2     // cellId
IL_001E:  ret

You can see that your ExcelColumn (column) is being boxed to an object and passed to String.Concat.

So your question is really: why does this work?

string cellId = string.Concat(column, rowIndex.ToString());

Answer: because column.ToString() is being called in string.Concat.

Hmmm... I hope that makes sense.

Time to review your code.

Get rid of the regions. They're almost always pointless and you certainly don't need a region around a single constant.

Constants are named PascalCase in C#. MAX_COLUMN_COUNT should be MaxColumnCount.

I think it would be better to store the string representation at creation rather than computing it each time it's needed.

Structs always have a default constructor which means you have a bug.

new ExcelColumn().ToString() // @


First of all, if statusCode can be null, the code above could possibly throw a null pointer exception.

To directly answer your question though, you could use a Set, such as a HashSet.

HashSet<String> errorOrWarning = new HashSet<String>();
errorOrWarning.add(HAS_ERRORS_HAS_WARNINGS);
errorOrWarning.add(HAS_ERRORS_NO_WARNINGS);
errorOrWarning.add(HAS_ERRORS_HAS_WARNINGS);
errorOrWarning.add(NO_ERRORS_HAS_WARNINGS);

Which you can then use in a single call.

if (errorOrWarning.contains(statusCode) {
    // do something
}

This has the advantage that statusCode can be null and it would produce no exception.


You have abstracted away any concrete dependencies from the controller. I  say that is well done for decoupling the controller and would allow better testability of the controller.

ContextTemplate is assumed to be DbContext derived, which already implements Unit of Work and Repository pattern so there is really no use in re-implementing the pattern.

IMO I see no immediate problems with the above code apart from the non use of the explicitly injected ILogger in the controller, which can be removed if there is no use for it in the controller. Logging can be considered a cross-cutting concern in asp.net-core and handled external to the controller.


Linear regression on points specified by the user in a GUI

from <xx> import *

Prevent a * import. You don't know what it will inject in your module namespace. Instead only import the parts you need:

from graphics import GraphWin, Line, Point, Rectangle, Text

The google style guide as linked by Mircea also says not to import the classes, but only modules and packages, but that is a matter of style and taste.

Magic numbers

There are a lot of magic numbers, scattered in your code. If ever you want to change the location of the button, you will need to adapt that in a few places, and will most likely miss some. To prevent such magic numbers, you can do something like this:

def main():
    coord_max = 40
    win = GraphWin("Regression Line", 10 * coord_max, 10 * coord_max)

    win.setCoords(0, 0, coord_max, coord_max)

    button_x, button_y = 35, 3
    button_width, button_height = 8, 4

    Text(Point(button_x, button_y), "DONE").draw(win)
    button = Rectangle(
        Point(button_x - button_width / 2, button_y - button_height / 2),
        Point(button_x + button_width / 2, button_y + button_height / 2),
    )
    button.draw(win)

split functionality

your dots method does a lot of things now. It:

catches the click
checks whether it it is the button
draws the point
does the summary calculations

Especially the last one should be factored to its own method. The easiest way to do this is let dots just yield the x and y coordinate, and let another method take care of the regression.

Checking whether the click is on the button can also be done simpler. Instead of hardcoding the coordinates, simplest would be to pass in the button object, and ask that one for its bounding coordinates:

def dots(win, button):

    while True:

        click = win.getMouse()
        x = click.getX()
        y = click.getY()
        if button.p1.x <= x <= button.p2.x and button.p1.y <= y <= button.p2.y:
            break # button press
        Point(x, y).draw(win)
        yield x, y

Is to me a lot clearer and easier to understand.

If you don't know that p1 and p2 are bottomleft and topright, you can take that into account by doing:

def dots(win, button):
    while True:
        click = win.getMouse()
        x = click.getX()
        y = click.getY()

        x1, x2 = sorted((button.p1.x, button.p2.x))
        y1, y2 =  sorted((button.p1.y, button.p2.y))
        if x1 <= x <= x2 and y1 <= y <= y2: # button press
            break
        Point(x, y).draw(win)
        yield x, y

summarize:

Instead of each summary metric getting its own variable, you can save them in a dict (or a collections.Counter more specifically)

def summarize(points):
    summary = Counter()
    for x, y in points:
        summary["x"] += x
        summary["y"] += y
        summary["x2"] += x ** 2
        summary["xy"] += x * y
        summary["count"] += 1
    summary["mean_x"] = summary["x"] / summary["count"]
    summary["mean_y"] = summary["y"] / summary["count"]
    return summary

regression:

Then pass this on to a method that calculates the regression line. This needs the maximum x of the screen as an argument:

def regression_line(summary, x_max, x_min=0):
    slope = (
        summary["xy"]
        - summary["count"] * summary["mean_x"] * summary["mean_y"]
    ) / (summary["x2"] - summary["count"] * summary["mean_x"] ** 2)

    y_min = summary["mean_y"] + slope * (x_min - summary["mean_x"])
    y_max = summary["mean_y"] + slope * (x_max - summary["mean_x"])

    return Line(Point(x_min, y_min), Point(x_max, y_max))

rest of main

points = dots(win, button=button)
summary = summarize(points)
try:
    regline = regression_line(summary, x_max=coord_max)
except ZeroDivisionError:
    middle_point = Point(coord_max / 2, coord_max / 2)
    Text(middle_point, "Enter at least 2 points!").draw(win)
else:
    regline.draw(win)
win.getMouse()

main guard

If you put the calling of main() behind if __name__ == "__main__":, you can later import this module from somewhere else, and reuse some of the code

if __name__ == "__main__":
    main()


Here are some things that may help you improve your code.

Eliminate unused variables

Unused variables are a sign of poor quality code, and you don't want to write poor quality code. In this code, a and nbr are unused.  Your compiler is smart enough to tell you about this if you ask it nicely.

Avoid single-line if constructs

The compiler can handle it just fine, but readers of your code are more likely to be able to correctly interpret the code if you avoid single-line if.  So instead of

if (*it % t.back() == 0) {s.erase(it++);}

use this

if (*it % t.back() == 0) {
   s.erase(it++);
}

Be careful when you erase an iterator

The standard, in section 23.2.4 says that for an associative container, when you use erase(it) where it is an iterator:

  erases the element pointed to by q. Returns an iterator pointing to the element immediately following q prior to the element being erased. If no such element exists, returns a.end().

This means that to be safe, your loop should look like this instead:

for (auto it = s.begin() ; it != s.end(); )
{
    cout << "       s  = " << *it << '\n';
    if (*it % t.back() == 0)
        it = s.erase(it);
    else
        ++it;
}

As pointed out by @LokiAstari, this works just fine for associative containers such as std::set but a more generic approach would be to use this for the line containing erase:

        s.erase(it++);

This works with set but also with other non-associative standard containers, including vector.

Think carefully about signed and unsigned

The code currently uses int types for both the vector and the set but are you looking for negative prime numbers?  If not, it could be that unsigned would be a better choice for data type.

Reconsider container choices

A std::set is a sorted associative container.  Since it's usually implemented internally as a tree, it's a relatively computationally expensive container to use consider the fact that all you really need is a list.

Consider using range-for syntax

The code currently prints the resulting vector with this code:

for (vector<int>::iterator it = t.begin() ; it != t.end(); ++it)
{
    cout << "t = " << *it << endl;
}

It can be written much more simply with a range-for:

for (const auto i : t) {
    cout << "t = " << i << '\n';
}

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.


Optimize Scipy Sparse Matrix Factorization code for SGD

There may be other optimizations available, but this one alone should go a long way...

When you do e = self.model - np.dot(self.p,self.q.T), the resulting e is a dense matrix the same size as your model. You later only use e[u, i] in your loop, so you are throwing away what probably are millions of computed values. If you simply replace that line with:

e = self.model[u, i] - np.dot(self.p[u, :], self.q[i, :])

and then replace e[u, i] with e, you will spare yourself a huge amount both of computations and memory accesses, which should boost performance by a lot.


Depleting certain data from a webpage asynchronously

magic numbers

ASCII numbers are pretty obvious, but I would still rather see you express it in this way:

letters = range(ord('a'), ord('z') + 1)
for link in [mainurl.format(chr(page)) for page in letters:

Alternatively, import string and iterate through string.ascii_lowercase.

naming

I'm not fond of these identifiers, as method name is noun, and argument is verb:

async def sub_links(process_links):

Consider making it:

async def process_links(links):

(or process_links(sub_links) if you prefer). Some folks would use "url" for "link", but that's not a substantive criticism. "Process" is a bit vague - I feel download_links() is better.

DRY

Consider breaking out a temp variable:

    anchor = container.cssselect("h2 a")
    name = anchor[0].text if anchor else ""

Better, break that out as a trivial helper function so address and others can concisely use it. I never see such idioms when using BeautifulSoup - perhaps you'd like to try that library in your next project?

Again, I'm not happy with the adding_weblink() identifier, it is much too vague. Your comment suggests the appropriate verb would be download_profile() (or download_profile_page()).
Also, PEP8 asks that you name the parameter profile_link - no biggie.

Settle on tree vs. root, just pick one.

Consider writing a brief helper function that returns html.fromstring(requests.get(link).text).

In this context weblink is on the redundant side, probably enough to just call it a link.

The if weblink: test probably isn't needed, as printing blank + empty_string before newline is pretty harmless.

output format

I can't imagine that name, address, etc. are easy to unambiguously parse from your output. It seems like you want a csv.writer, which would let you writerow(name, address, phone, weblink).

Imagine that 1% of all GET requests, or 10%, yielded temporary fail that you should retry. Would the current code grab 99% (or 90%) of all pages? Could a cleanup module conveniently identify links that should be retried?

Overall the code is nice and clear. I am not left with doubts about whether it would do what it is intended to do. (If Houzz changes details like .proListingLocation there will be some fragility issues, but hey, that's the life of a scraper. Definitely store a sample web page in source control, along with corresponding unit tests, so you can debug things in future when the inevitable website update happens. Have Jenkins run a daily test against the website so you notice bit-rot within 24 hours before it drifts "too" far.)


Hash Map implementation with a function to set all values

The obvious solution, replacing all values, is \$O(n)\$ - the trick is to do it in \$O(1)\$. With that in mind, your approach makes sense - store the new 'all' value, and customize get so it knows whether it should return the actual value for a key or the 'all' value.

I wouldn't use insertion time for that, however - that'll lead to hacks like Thread.sleep. A counter field that is only incremented when you call setAll should work just fine.

I would also wrap V in a custom class that stores both V and the last-modified-counter-value, so get doesn't need to perform two hash-map lookups in the worst case.

With that, get would look something like this:

public V get(K key) {
    VWrapper wrapper = super.get(key);
    if (wrapper.counter < setAllCounter)
        return setAllVal;
    return wrapper.value;
}

In your example, at the end keys 1 and 2 would have a counter value of 0 (they were added before any setAll call), 3 has a counter value of 1 (it was added after the first setAll call) and setAllCounter is 1 (setAll has been called one time).


To answer your question.. it depends on how you want to handle the data. Take a step back and put your self in the users shoes. Lets say the user has those numbers saved as bank account transactions.. He would want those numbers saved somewhere, but not necessarily visible. If that was the case you wouldn't want "delete" that data. You could, however, parse the data into say a table. You could give each cell in that table a class that has a boolean value called visible, and a int value. Then you could set a row or column to not visible as you wish. That would give you the ability to then just loop through the rows and columns and output the data as needed.


It's really worth making your big number be a class.  This will give you the ability to

change the internal representation without altering client code
write operators (+, -, /, *, <, ==, << and more) that work just like they do for other numbers
specialize numeric limits and other traits classes so they can be used as arithmetic types in algorithms. For example, you might like a std::complex<BigNum>.  You can have one, but a std::complex<std::vector<int>> isn't going to work.
add literal operators so that you can write them naturally in your source code.

You don't have to do all the above at once, of course.  But I recommend you read the review of Implementation of a Rational Number class in C++ to see how an arithmetic class can work.
Your main() would then be isolated from the implementation details, and look something like
#include <bignum>

int main () {
    int N = 100;
    auto fac = 1_big;
    do {
        fac *= N;
    } while (--N > 0);

    std::cout << "100! = " << fac << std::endl;
}

Space efficiency
Once you have your class, you'll observe that writing one digit in each int is quite wasteful.  char is defined to include at least 0 to 127 so you could store two digits (0 to 100) in each element of a vector of characters.
If you've made your big number a class, it's then easier to do this in two steps - first store one digit in each character, and then widen to 2 per char.  There are more space-efficient encodings; you'll have to decide where the trade-off between space and time lies for your needs.

Temporary values in multiplication
In your long multiplication, you store all the intermediate results before adding them together.  You can save some of this space by using an accumulator variable to add the results as you go, like this pseudo-code:
accumulator = 0
for i in digits
     tmp = arg1 * i
     accumulator += tmp
return accumulator

Then you no longer need to have a vector of partial products throughout the function.

Working example
Here's what I implemented, following the notes above.  It's the absolute minimum needed to calculate factorials.  Several features are left as an exercise:

Implement a user-defined literal that accepts longer numbers than unsigned long long can represent
Support negative numbers
Implement the other arithmetic and relational operators
Make more of the implementation constexpr so it can be evaluated during compilation

#include <vector>
#include <iosfwd>

class Bignum
{
    static constexpr char max_digit = 100;

    std::vector<char> digits = {};   // smallest centits first

public:
    Bignum(unsigned long long int n)
    {
        while (n) {
            digits.push_back(n % max_digit);
            n /= max_digit;
        }
    }
    // copy constructor and assignment operator can be defaulted

    Bignum& operator+=(const Bignum& other);
    Bignum operator+(const Bignum& other) const;

    Bignum& operator*=(const Bignum& other);

    friend std::ostream& operator<<(std::ostream&, const Bignum&);

private:
    // helper functions
    Bignum& halve();
    Bignum& trim();
};

Bignum operator""_big(unsigned long long n) { return n; }

// IMPLEMENTATION

#include <algorithm>
#include <iostream>
#include <utility>

Bignum& Bignum::operator+=(const Bignum& other)
{
    int sum = 0;
    auto i = digits.begin();
    auto j = other.digits.begin();
    bool in = true;             // until i reaches digits.end()
    bool jn = true;
    while ((in &= i != digits.end()) | (jn &= j != other.digits.end()) || sum) {
        if (jn)
            sum += *j++;
        if (in) {
            sum += *i;
            *i++ = sum % max_digit;
        } else {
            digits.push_back(sum % max_digit);
        }
        sum /= max_digit;       // carry to next digit
    }
    return *this;
}

Bignum Bignum::operator+(const Bignum& other) const
{
    return Bignum{*this} += other;
}

Bignum& Bignum::operator*=(const Bignum& other)
{
    Bignum a = *this, b = other;
    if (a.digits.size() > b.digits.size())
        std::swap(a, b);

    digits.clear();
    while (a.digits.size() > 0) {
        if (a.digits.front() % 2)
            *this += b;
        a.halve();
        b += b;
    }
    return *this;
}

Bignum& Bignum::halve()
{
    int carry = 0;
    for (auto i = digits.rbegin();  i != digits.rend();  ++i) {
        carry *= max_digit;
        carry += *i;
        *i = carry / 2;
        carry = carry % 2;
    }
    return trim();
}

Bignum& Bignum::trim()
{
    while (digits.size() > 0 && !digits.back())
        digits.pop_back();
    return *this;
}

std::ostream& operator<<(std::ostream& out, const Bignum& n)
{
    if (n.digits.size() == 0)
        return out << '0';

    bool z = false;             // track leading zeros
    for (auto i = n.digits.rbegin();  i != n.digits.rend();  ++i) {
        int n = *i;
        if (z |= n/10)
            out << n/10;
        if (z |= n)
            out << n % 10;
    }

    return out;
}

// PROGRAM

int main () {
    const int N = 100;
    auto fac = 1_big;

    for (int i = 1;  i < N;  ++i) {
        fac *= i;
        std::cout << i << "! = " << fac << std::endl;
    };
}


Function to call a list of callables with retry

You are not allowed to remove items from a list while iterating over the list.

>>> a = [“a”, ”b”, ”c”, ”d”]
>>> for b in a:
...   print(a,b)
...   a.remove(b)
...
['a', 'b', 'c', 'd'] a
['b', 'c', 'd'] c
>>>

You should wait to remove the callable_obj from callable_objs until after the for loop completes.  Build a list of callable_obj to remove, and bulk remove them at the end.  Or use list comprehension and filter out the successful calls:

callable_objs = [ obj for obj in callable_objs if not success_tracker[obj] ]


My take, in short:

in programming there is nothing worse than silently swallowing exceptions :) And the fact that you are catching any exception, and not just those related to those specific operations, means than all kinds of errors will go unnoticed.
At the very least, the exceptions should be logged somewhere
be more specific and catch relevant exceptions instead, usually it will be stuff like HTMLParser.HTMLParseError and also requests.exceptions - experiment a bit
Note the difference in behavior between find and find_all since you are using both functions:

If find_all() can’t find anything, it returns an empty list. If find()
can’t find anything, it returns None

Armed with that knowledge you can simply test your expressions for None before you try to fetch the value with find - it's better to avoid an exception than having to handle it.
Likewise, if bs4.find_all('a', {'class': 'question-hyperlink'}) returns an empty list, you don't proceed with the list comprehension but you assign some default value, possibly: payload['hyperlinks'] = None

So the key here is to test the result of every call to find or find_all and act accordingly. Then you can get rid of those try catch blocks. Only one all-purpose exception handler for the whole procedure shall suffice.


Quick estimation for empirical permutation and correlation test in R

Using apply and replicate, you can get a slight speedup (below). Setting a seed, you can check that it gives the same result as your version. In my benchmark test, it's about 10% faster. For further speedup, you could consider using clusterApply and parLapply from the parallel package.

# combining matrices into one to use apply
combinedMat <- cbind(a[rep(1:nrow(a), each=3), ], b[rep(1:nrow(b), times=3), ])
combinedMat <- cbind(combinedMat, obs = as.numeric(t(rcorr.observed)))
# using apply instead of loop
Pval_estim <- t(matrix(apply(combinedMat, 1, function(combined) {
  obs <- combined['obs']
  if (is.na(obs)) return(NA)
  combined <- as.numeric(combined[names(combined) != 'obs'])
  # using replicate instead of loop
  diff.random <- replicate(number_of_permutations,
  {
    shuffled = sample(combined)
    # you only use the correlation, so there is no need to use rcorr.
    diff.random = cor(shuffled[1 : 6],
                      shuffled[7 : length(combined)],
                      method="spearman")
  })
  sum(abs(diff.random) >= abs(obs)) / number_of_permutations
}), nrow = 3, ncol = 3))


More efficient way of removing line indices?

1. Test case

You can't fix what you don't measure. So let's make a test case containing a million lines similar to the example input in your question:

>>> with open('in.txt', 'w') as f:
...     for _ in range(10**6):
...         _ = f.write('511111 12  1.000000  1.000000  1.000000   .750000\n')

How long does your code take?

>>> from timeit import timeit
>>> indices = list(range(3)) + list(range(18, 29))
>>> timeit(lambda:rem_asc_by_pos('in.txt', 'out.txt', indices), number=1)
32.99110442500023

2. Rewrite

Here's a quick rewrite to simplify your code:

Follow the Python style guide (PEP8).
Write a docstring explaining what the code does.
Pick a better name for the function.
Combine the two with clauses into one to keep the indentation sensible.
No need to pass mode 'r' to open: that's the default.

And some changes to speed it up:

Turn the list of removed indices into a set, so that we can look up indices in constant time.
There's no need to split line into a list: you can iterate over a string just as easily.
Drop the checkLine and newList and lineOut intermediate variables.
Cache fout.write in a local variable to avoid having to look it up for every line.

def remove_indices(file_in, file_out, indices):
    """Copy file_in to file_out, removing the given indices."""
    index_set = set(indices)
    with open(file_in) as fin, open(file_out, 'w') as fout:
        write = fout.write
        for line in fin:
            write(''.join(c for i, c in enumerate(line) if i not in index_set))

This is about twice as fast (in my test case):

>>> timeit(lambda:remove_indices('in.txt', 'out.txt', indices), number=1)
17.147783935997722

3. Use slices instead of indices

The next improvement is to represent the parts of the line to be kept (rather than the parts to be removed) in the form of Python slice objects. A slice object represents a range of indices in the same form as an array slice, that is, as start and stop indices together with a step.

So if you are going to remove indices 0–2 and 18–28, then you are going to keep indices 3–17 and 29–. In slice notation that would be:

>>> slices = [slice(3, 18), slice(29, None)]

Note that the stop for the first slice is 18, because ranges of integers in Python are always exclusive at the top.

Here's a version of your function that takes slices to keep instead of indices to remove:

def keep_slices(file_in, file_out, slices):
    """Copy file_in to file_out, keeping the given slices."""
    with open(file_in) as fin, open(file_out, 'w') as fout:
        write = fout.write
        for line in fin:
            for s in slices:
                write(line[s])

This is substantially faster:

>>> timeit(lambda:keep_slices('in.txt', 'out.txt', slices), number=1)
1.877711878001719

That's about an 18 times speedup (on this test case; it might be different on other test cases). Is that good enough for you? It ought to reduce your 20 hour runtime to an hour or so.


Open encrypted PDF file by trying passwords from a word list

Looking at the documentation of PdfFileReader.decrypt It states that it return 0 if the file fails or 1 if it succeeds.

You can also use isEncrypted to check if the file was encrypted in the first place.

So you can turn the loop around. First open the pdf file see if it was encrypted at all and if so try to call decrypt with every password in your dictionary.


Disclaimer: I don't know Go.

Error handling

The sendRequest method may fail,
returning nil,
but the caller in main continues happily as if nothing happened.
In fact, looking at the context of the call in main,
my first impression was that sendRequest magically always succeeds,
which is not the case, and so a bit misleading.

Likewise, parseJson may also fail,
parsing nothing,
but from where you call it,
this is not obvious, which is again a bit misleading.

Naming

It seems [the common convention][1] is to use camelCase or PascalCase for names,
no underscores.
So I suggest to rename the fields of the ChatEvent struct.
I'd go as far as to say use PascalCase for types and camelCase for variables, but this is not so clear in the docs.

The variable parsedJson says nothing about what kind of object it is.
So I'd rename it to chatEvents.

Exceptional users

The list of such users would be better in a global set:

if currentMessage.User_id == -263 || currentMessage.User_id == 125580 {
    // Ignore Captain Obvious & Duga
    continue
}

Too wide lines

The line-end comments in the constant definitions make me scroll to the far right to read them.
Even worse,
while reading the code further down,
when I see lines that seem to end near the right end of the text,
the presence of the horizontal scrollbar makes me wonder if there's something more if I scroll right.
And usually there's nothing, as expected, but this is really annoying.
Please avoid line-end comments if they make the line wider than the longest real line of code.
Or better yet, avoid line-end comments if they will make the line exceed 70 characters.


C++ Class for optionally constructing arbitrary derived classes

Unconstrained templates
The public facing member function templates registerModule never validate any of the types they take. Currently, trying to call registerModule for a type not derived from Module fails due to the instantiation of ModuleCreator::create (and subsequent missing conversion from ModuleClass to Module), this relies on an implementation detail (which might change).
Similarly, the overload of registerModule which takes constructor arguments never validates whether ModuleClass can actually be constructed with them.
Better be explicit about which types are allowed to be passed!
In C++17, one could use a simple if constexpr, but since this question is tagged c++14, using SFINAE is the only option.
Even better, with slightly more work you can give much better error messages than what the compiler generates, so a user of the class doesn't have to parse dozens of lines of template instantiations.
Example using SFINAE (just member function declaration), assuming below fix for ModuleCreatorArgs::args:
template<typename ModuleClass>
static std::enable_if_t<
    std::is_base_of<Module, ModuleClass>::value, void> &&
    std::is_default_constructible<ModuleClass>::value,
void> registerModule(const std::string&);

template<typename ModuleClass, typename... Args>
static std::enable_if_t<
    std::is_base_of<Module, ModuleClass>::value &&
    std::is_constructible<ModuleClass, std::remove_reference_t<Args>...>::value,
void> registerModule(const std::string&, Args&&...);

For error messages, you could add:
template<typename ModuleClass, typename...Args>
static std::enable_if_t<
    !std::is_base_of<Module, ModuleClass>::value ||
    !std::is_constructible<ModuleClass, std::remove_reference_t<Args>...>::value,
void> registerModule(const std::string&, Args&&...)
{
    static_assert(std::is_base_of<Module, ModuleClass>::value, "ModuleClass needs to be derived from Module!");
    static_assert(std::is_constructible<ModuleClass, std::remove_reference_t<Args>...>::value, "ModuleClass is not constructible from the given arguments!");
}

Memory and lifetime management
ModuleManager leaks all created instance of ModuleCreatorBase stored in ModuleManager::registry, as delete is never called. Why not simple use std::unique_ptr<ModuleCreatorBase> instead of ModuleCreatorBase*? (Note: adding calls to delete in the destructor of ModuleManager doesn't fix this problem!)
A bit subtler is the dangling reference issue with ModuleCreatorArgs: Since all the passed arguments are perfectly forwarded to be stored in ModuleCreatorArgs::args, lvalue references (to possibly local values!) will be stored as references, which might dangle when they are actually used for Module construction.
Now, I don't know the requirements for Modules derived classes: Do they need to take references in their constructors (e.g. for non-copyable non-movable objects) that for some reason cannot be passed as pointers?

If no, this gets simple: Change the type of ModuleCreatorArgs::args to std::tuple<std::remove_reference_t<Args>...> so every argument is either moved or copied (as appropriate).
If yes, this will require good documentation and discipline! (Honestly, if you can, try to avoid this mess. This is easy to screw up and hard to get right at the callsite to ModuleManager::registerModule.)

Final notes
I really hopes this class (ModuleManager) gets expanded so it can actually be used to construct objects (all it currently does is creating private state). Maybe add a ModuleManager::create(const std::string&) method?
Also, I don't know your actual use case of Modules, but if you expect them to be shared quite often, you might want to add a create_shared (or similarly named) method that returns a std::shared_ptr<Module> instead.


Bash script for getting geolocation (latitude, longitude and country code)

Bugs:

echo "$my_variable" | my_command can behave unexpectedly if the variable starts with one of the echo options. You can do my_command <<< "$my_variable" instead.
unset $IFS does not unset IFS. For that you need unset IFS.

Simplifications:

You shouldn't need to set IFS - read will save the full input to the variable anyway (see help [r]ead).
A lot of the code is already Python, and Python has much fewer caveats than Bash, so changing to it would very much benefit the maintainability of the code. Strictly speaking it's not a pure Bash script anyway, and you really don't want to be parsing JSON manually in Bash. If you really need a Bash script (which you shouldn't unless it's for a Bash programming exercise, and even then, somebody is wrong on the Internet if they asked you to use pure Bash to parse JSON) you could make it a wrapper script.
Bash's read takes a -p prompt option, so you can avoid the first printf.
Unchanging variables such as URL should be assigned outside of the loop.

Style issues:

Non-exported variables should be lowercase to distinguish them from exported variables.
It is customary to exit with a non-zero exit code when a command fails.


For something so simple, it might be less overkill to use the doctest module.  Write the expected calls and outputs in the docstring, then run python -m doctest -v fizzbuzzmodule.py.  There's no need to write a separate class.

I've written one of the tests to ensure that the function also works when called with decreasing arguments.

As for the function itself, I believe that the code reads better if you write number % 3 == 0 instead of not number % 3.  I would also use a conditional expression, but that's just a matter of personal preference.

def fizzbuzz(number):
    '''
    if number divisible by 3 return 'fizz';
    5, 'buzz'; both, fizzbuzz
    else return number

    >>> fizzbuzz(1)
    1
    >>> fizzbuzz(2)
    2
    >>> fizzbuzz(3)
    'fizz'
    >>> fizzbuzz(4)
    4
    >>> fizzbuzz(5)
    'buzz'
    >>> fizzbuzz(15)
    'fizzbuzz'
    >>> [fizzbuzz(i) for i in range(31, 20, -1)]
    [31, 'fizzbuzz', 29, 28, 'fizz', 26, 'buzz', 'fizz', 23, 22, 'fizz']
    '''
    if number % 3 == 0:
        return 'fizzbuzz' if (number % 5 == 0) else 'fizz'
    if number % 5 == 0:
        return 'buzz'
    return number


Finding first recurring letter in each string of a given set

Better names

The variable names are too short to be meaningful. It's common to use i as an index in for-loops, but r doesn't really tell us its purpose. Names like number_of_strings are self-descriptive, so we should use those.

Unused variables

We never use c in find_first_recurring_letter, therefore we should remove the parameter altogether.

Strictly speaking, we also never use indx[i]. If ch[i] is '\0',indx[i]will be1(see "always use braces" below), and1` otherwise, so we can replace

        printf("'%c' in string %d\n",ch[i],indx[i]+1);

by

        printf("'%c' in string %d\n", ch[i], 2);

without changing the programs logic.

Simpler pointer logic

Instead of ptr = &str[i][0], which is ptr = &(*(str[i])) use ptr = str[i]. Instead of sptr = &ptr[1], just use sptr = ptr.

Again, we could call them current and next or similar.

By the way, all indx[i] are 1  (see "unused variables" above and "always use braces" below). That doesn't sound right. Also keep in mind that variable length arrays are optional from C11 on.

Get rid of additional memory

If we printf the recurring character, we can get rid of ch and indx:

            if(*ptr==*sptr)
                printf("....");
                indx[i]=1;

Always use braces

Note that the code above contains a bug. indx[1] will be set to 1 regardless whether *ptr == *sptr. The indentation is misleading here.

You probably added indx[i] later and forgot the add the braces, so we should always use braces to make sure that bugs like this cannot happen.

If you don't want to use braces, use a code formatter. The indentation on the automatically formatted code will hint possible errors.

Prefer late C99 declarations if possible

That way we can keep the scope of our variables short, e.g.

for(int i = 0; i < number_of_strings; ++i) {
    for(char *current = str[i]; *current != '\0'; current++) {
        for(char *next = current + 1; *next != '\0'; next++) {
            if(*current == *next) {
                printf("'%c' in string %d\n", *current, i);
            }
        }
    }
}

It's now impossible to use next outside of its loop. Also, we should try to initialize our variables whenever possible.

Use const type* for inputs that are not supposed to change

That way we cannot accidentally modify your input values, e.g.

str[i][k] = '\0'

would not compile if str was const char**.

Check malloc's return

We should really check whether malloc returns NULL.

Split functions

find_first_recurring_letter doesn't follow its name completely. We find the first recurring letter on a set of strings on a per-string basis. That sounds perfect for a split:

const char * find_first_recurring_letter(const char * haystack) {
    for(const char * current = haystack; *current != '\0'; current++) {
        for(const char * next = current + 1; *next != '\0'; next++) {
            if(*current == *next) {
                return current;
            }
        }
    }
    return NULL;
}

void find_first_recurring_letters(const char ** strings, int number_of_strings) {
    for(int i = 0; i < number_of_strings; i++) {
        const char * result = find_first_recurring_letter(strings[i]);

        if(result) {
            printf("'%c' in string %d\n", *result, i);
        }
    }
}

We can now use find_first_recurring_letter on any null-terminated string. We're able to reuse functionality. Note that both functions are very easy to check by hand.


You are introducing this requirement of not having a password being the same as a username, but the problem is the way you check for it:

create_password = input("enter a new password (Your password cannot be the same as your username !!!!!!!): ")

if create_password in users:

The problem arises when my password matches someone else's username.

I think you meant to just compare create_username with create_password values.

In general, there is rarely a case when you should try writing your own login system except that for learning purposes. You may though improve your current setup by introducing hashing of the passwords, to avoid storing them in plain text: Salt and hash a password in python; as well as more password strength requirements: Checking the strength of a password.


as far as I could see by googling np.concatenate is the fastest way for concatenate arrays, so I'd keep that.

but talking about code organization, I suggest you to create a function (something like it. it may have syntax errors, so that's just to give you an idea)

def randomChoice(value, select):
    if select:
        return np.random.choice(encoders[value, :], int(c * f * N_E), False);
    else:
        return np.random.choice(non_selec, int(c * (1 - f * p) * N_E), False);

and have a simple and single call instead of a huge block of code into one line with two concatenate calls

ee_i = np.concatenate([ee_i, randomChoice(0, true), randomChoice(1, true), randomChoice(2, true), randomChoice(3, true), randomChoice(4, true), randomChoice(0, false)])

I hope this helps


In an set of integers, find three elements summing to zero (3-sum, leetcode variant)

Multi-part answer: [0) these preliminaries] 1) review of code presented 2) hints for improvement excluding personal, from programming over python and accepting a programming challenge to k-sum and leetcode 3Sum.

One general principle to follow is do as expected, in programming, it has been formulated in many guises, including Principle of Least Surprise. Every other route leaves you under pressure to justify, at risk of being misunderstood.

In coding, document, in the program source code:
What is "everything" there for?

Such rules often have been gathered into guide lines, for Python, follow the Style Guide for Python Code.

Instead of a docstring, your module starts with imports - most of them unused.
If your code mentioned leetcode, the presentation of a class Solution with just one function definition wouldn't beg justification.
the definition of threeSum() shows (a cute addition of target&default and) a curious mix of leetcode's templates for Python 2&3, lacking a proper docstring
comparing "the int" target to the list literal [0, 0, 0] is dangerous given Python's zeal to allow operations: do you know by heart when that evaluates to True?
(Do you expect most every reader of your code to?)
(Belatedly, it occurred to me that you may have intended to compare nums to [0, 0, 0] - bogus if target != 0)
verbosity -
you can denote a tuple containing a single literal list like ([v, v, v],)
2nd early out:
with only one key→value in the dict, there's no need to access it:
every key will equal nums[0]
You need to check for 3*nums[0] != target
naming (Not your fault: Solution and threeSum are substandard.
nums/_1-3 don't feel bad enough to change):
- target, triplets, sub_target: right on!
- given Python's "duck typing", I'd stick with triplets (, never introducing triplets_set)
- lookup is a horrible name → value_to_index (or, in a suitably small context, just index)
(- there's one thing wrong with k: it gets in the way when extending three_sum() to k_sum()…)
pythonic or not (or exploiting library functions, rather?):
value_to_index = { value: index for index, value in enumerate(nums) }
(same for for i, num_1 in enumerate(nums), for j, num_2 in enumerate(nums[i+1:], i+1))
commenting
- you did comment, and I find half of the comments helpful
- I don't get #overwrite from the high (that may just be me)
- #don't reproduce itself: probably use any element/index once, at most rather than don't repeat an element/index
- you did not comment the outer for loop, arguably the most profitable place:
how is what the execution constructs a solution?:
for each value, value_to_index keeps just the last index: how does this not prevent any valid triple to show up in the solution?
checking k: nice!
(I'd go for in (None, i, j))
you don't provide a "tinker harness"

if __name__ == '__main__':
    object_disoriented = Solution()
    print(object_disoriented.threeSum([-1, 0, 1, 2, -1, -4]))
    print(object_disoriented.threeSum([1, 1, 1], 3))

(Something else to follow is make (judicious) use of every help you can: if you use an IDE supporting Python, chances are it can help you with PEP8.)
(Running low on steam, this part will start more frugal than expected.)

Real Programming is the creation of a language that simplifies the solution of the problem at hand.

With Python providing most mechanisms needed in programming challenges, that leaves:

Code readably.
Create elements easy to use correctly.

I bickered you some about having a consistent problem description.
This is another place where Test First shines:
As long as you find yourself not knowing what to test, you are not in a position to implement anything, yet. (Inconsistencies in specification tend to stand out in test design & implementation.)

Programming challenges à la leetcode.com typically build on simpler challenges - you met 2sum, which puts you in a favourable position to tackle 3sum.
The performance part of these challenges is about not doing things over, not discarding knowledge more often than about algebraic insight.

The generic solution to 2sum is to take values and find the complement (1sum?).
The extension to k-sum is to split k into smaller numbers.

Ways to have information about the order of a set or sequence (say, elements) of instances of a type with ordering reusable is to have them ordered (ordered = sorted(elements)) or sorted (histogram = Counter(elements)).
For 2sum, you could search for target/2 and work inside-out.
For 3sum, one value will be no greater, another no smaller than both others. The third one will not "lie outside" the former two.


You forgot to check the result of your recursing calls. Your steps are fine, if you meant the following in step 7

  Step 7: recurse and check result

However, even then, it's not the correct property of a binary search tree. Have a look at the following tree:

    5
   / \
  3   7
 / \
1   6

Does this hold for your steps? Yes. Does this hold for your algorithm, if you check the result of checkBST?

bool checkBST(node *root){
    if(root == NULL){
        return false;
    }

    if(root->left != NULL){
        if(root->data < root->left->data || !checkBST(root->left)){
            return false;
        }
    }

    if(root->right != NULL){
        if(root->data > root->right->data || !checkBST(root->right)){
            return false;
        }
    }

    return true;
}

Yes. But is it a binary search tree? No. You would never find 6. All nodes left of the root must be smaller, and all nodes right of the root must be greater.

Remember, a binary tree has the following property: if you want to find a value, you look at the current value. If the value you're looking for is smaller, you continue in the left tree. If the value is greater, you continue in the right tree. But you always look at one of those subtrees. Never both. In a balanced binary tree, you would only have to look at \$\log_2(N)\$ nodes to find your value.

I would link you to the Wikipedia section on Verification, but it already holds the solution. But here is a hint: carry along what numbers are allowed in your subtree.

So, to go back to your steps, you should do something like this:

check if the node is not null
check if left child exists

check that all elements in the left subtree are smaller than our current value

check if right child exists

check that all elements in the right subtree are greater than our current value

The steps 0 and 1.5 are missing. They handle the current value and the range of valid values. Coming up with them will be the crucial part.

By the way, you usually don't use parent in a binary tree. But that depends on your use-case. Also, you have memory leaks. For small examples, there is no harm not using malloc:

struct node n10, n20, n30, n15, n50, n60;

n10.data = 10;
n10.left = NULL
n10.right = NULL
n10.parent = &n20;

n20.data   = 20;
n20.parent = &root;
n20.left   = &n10;
n20.right  = NULL;

// ....