Python class hierarchy, extend ancestor data

Is this a good design?

No IMO it's quite horrible, please reconsider it.

  Could the update() blocks be implicit maybe?

Yeah, use metaclasses.

  I have more than one document in real code, so that would be nice.

Yeah, don't request us to write code for you. However, with a metaclass this is easy.

To make a cross Python 2 and Python 3 metaclass you need to use something like Class = Class('name', (object,), {}).
You want to also build these dictionaries in the metaclasses __new__, and for the values to be taken from another attribute.
To do this I defaulted to the uppercase of the value. I.e. A.DOC.

This works kinda like Python's default multiple inheritance, but I make no guarantees. Also doc is now a static value, so you may need to clone it at object instantiation.

def update(values=[]):
    if isinstance(values, str):
        values = values.split()
    class Meta(type):
        def __new__(meta, classname, bases, class_dict):
            for value in values:
                val = {}
                for base in reversed(bases):
                    val.update(getattr(base, value, {}))
                val.update(class_dict.get(value.upper(), {}))
                class_dict[value] = val
            return super(Meta, meta).__new__(meta, classname, bases, class_dict)
    return Meta('Meta', (object,), {})

class A(update('doc')):
    DOC = {'v': 0}

class B(A):
    DOC = {'v': 1}

class C(A):
    DOC = {'c': 0}

class D(B, C):
    pass

class E(C, B):
    pass

print(D.doc)
print(E.doc)


Note: Regarding the OP's comment on the "nature of IE7 mobile", I suspect it has more to do with jQuery's implementation of focusin and focusout. This may not be the case, but I have written my review with that assumption in mind.

There are a few things about your code that are, to put it bluntly, pointless.

First, checking whether Utils exists is a good thing, but you then immediately clobber it with the return of your function:

var Utils = Utils || {};

Utils = (function(window, $) {
    /* ... */
    return _public;
})(window, jQuery);

Something like the following would most likely be better:

var Utils = Utils || (function(window, $) {
    /* ... */
    return _public;
})(window, jQuery);

Second, why pass window to the function at all? Browsers will not allow overwriting of the window object, and your parameter name is window anyway, so it doesn't save you anything.

Third, _private is unnecessary. Any variables (including functions) that you don't include in whatever object you return will be hidden by the local scope of your self-executing function.

var handleFocusIn = function(e) { /*...*/ },
    handleFocusOut = function(e) { /*...*/ };

_public is also unnecessary, though not as much as _private. If it were me, I would simply return the object literal, rather than bothering with the _public variable.

Lastly, given that your elements will always be input elements, there is no need to use focusin and focusout; Simply use focus and blur - this will avoid any possible bubbling issues, and then, most importantly, allow you to dispense with the unbinding/rebinding that happens in your handlers.

@Raynos also makes some good points on your implementation of supportsPlaceHolderAttr, regarding variables and conditionals.

//if placeholder is supported, no reason to continue on
if ('placeholder' in document.createElement("input")) {
    // useless variable, just return true
    return placeHolderSupported = true;
}

// useless placeHoldSupported check, always false. Useless enableFallback conversion always a bool
if (!placeHolderSupported && !!enableFallback) {

It's a good attempt at writing unobtrusive code, but it falls short of good modularity and namespacing. Still, like I said, a good start.


Some obvious problems

It leaks memory (every newly allocated Node) when the Hashmap leaves the scope.
A delete/remove function is missing.
It doesn't replace the value within the existing Node on repeated puts with the same key but instead adds an additional Node every time.
The size is fixed and therefore the hashmap get quickly degenerates into linked list search.
Key and value types aren't generic.

Some positive things

It implements a hashmap
uses hash-lookup for search
returns correct results


How to parse a collection of objects in Backbone?

Based on the way your parse function works you're worried about mutability. Your code can be much shorter. Also, your use of _.clone is wasted since it's only a shallow copy. I've rewritten parse code and now it looks like this:

// response is array of object
// [{id:1, prop: null },{id:2, prop: "bar" }]

// the output parsed_response can be
//[{id:1, prop: null, isProp: true },
// {id:2, prop: "bar", isProp: false }]

parse: function(response)
{
    return _.map(response, function(obj) {
        obj = _.clone(obj);
        obj.isProp = obj.prop !== "" && obj.prop !== null;
        return obj;
    });
}

If you want further explanation let me know :)

The only thing I'm concerned with is how your prop works? Can you just check for a falsey value here (i.e. !obj.prop) or do you really need to explicitly check for an empty string or null?

In term of re-usability, you're covered here. parse() doesn't reference this so it can more or less be called statically from anywhere in your code. But be careful where you use it from, if you start calling this all over the place, it would make more sense to refactor this parse() function to a more generic object.


Your implementation of the sieve, using a dictionary, throws away many of the benefits of the approach; dictionaries are unordered. Even a naive list-based implementation ends up processing fewer than half as many numbers (146 vs. 382 with a limit of 100):

def sieve(limit):
    nums = range(limit+1)
    nums[1] = 0
    for n in nums:
        if n:
            for x in range(2*n, limit+1, n):
                nums[x] = 0 # counting this vs. pop
    return set(filter(None, primes))

Your approach processes multiples of numbers that will subsequently turn out to be non-prime themselves, e.g. you might pop all multiples of 9, then go back over them when you later process 3.

Note that I have used a set, which is effectively a dictionary with no values, rather than have some dummy value.

Also, there was no need to copy the whole dictionary; for n in numbers.keys() would have worked fine.

There are numerous other implementations, in Python and other languages, on this site and elsewhere; I suggest you look at a few to see what other alterations could be made.


Is there a shorter way to write the following if statements?

Add all items to a list and do a foreach instead.

var buttons = new List<Button>
{
    tx_cmb_Circuits1,
    tx_cmb_Circuits2,
    ...
};

foreach ( var button in buttons )
{
    if ( !String.IsNullOrEmpty( button.Text.Trim() ) )
    {
        emp.CircuitEmail_Group_Rels.Add(
            new Circuit_Email_Group_Rel
            {
                Circuits = (Circuits) button.SelectedItem,
                Group = emp
            } );
    }
}

P.S.: Consider giving your variables better names. No real need for abbreviations like tx_cmb nowadays.


Averaging a list of intersecting rectangles

To improve performance, wait for another review with some clever numpy trick.

To make it more Pythonic, it would be better to represent a rectangle with a Rectangle class instead of a simple tuple, for example:

class Rectangle(object):
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height

    def intersect(self, other):
        hoverlaps = (self.x <= other.x + other.width) and (self.x + self.width >= other.x)
        voverlaps = (self.y <= other.y + other.height) and (self.y + self.height >= other.y)

        return hoverlaps and voverlaps

The intersect method fits naturally into it, and now the code is easier to read.

The averaging method becomes:

def average_rects(rects):
    x = np.average([rect.x for rect in rects])
    y = np.average([rect.y for rect in rects])
    w = np.average([rect.width for rect in rects])
    h = np.average([rect.height for rect in rects])

    return x, y, w, h, len(rects)

The main part of ordered_average_intersecting_rects becomes:

while rects:
    r1 = rects[0]

    rect_cluster = [r1]

    for r2 in rects[1:]:
        if r1.intersect(r2):
            rect_cluster.append(r2)
            rects.remove(r2)

And in your testing method you can create rects with:

rects = [Rectangle(150, 55, 40, 20),
         Rectangle(160, 40, 20, 20),
         Rectangle(100, 120, 20, 20),
         Rectangle(45, 10, 15, 30),
         Rectangle(50, 25, 25, 20),
         Rectangle(35, 35, 20, 30)]

And of course you can (and should) go further:

average_rects could return a tuple: Rectangle(x, y, w, h), len(rects)
The assertions could use cluster1.x, .y, .width, instead of cryptic [0], [1], ...

You can replace while len(rects) > 0: with simply while rects:, because in Python empty sequences are false. This is recommended on PEP8 too.


My little bit of input:

inline is a C++ keyword, and it's only a hint to the compiler. The only reason to explicitly use inline is when you define function's body inside a header file, which is included in more than one source file.
Avoid basic data types like int, use types from stdint.h instead
Use comments to explain why are you doing something, and what are function arguments for
No reason to break a line after declaring a type.
No reason to give nameList[32] a size - the compiler will guess it on its own. Just do it as

static char* nameList[]  = {
    "Ross",
    "Litt",
    "Hellyeah"
};

Use sizeof(nameList) - 1 instead of a magic number to indicate last array index - there will be less changes if you ever add more names.

Regarding your union questions:

union is kinda like a struct; the only difference is how it's handled in memory.
Since your union has two fields (PersonItem and CompanyItem), you must say which one is to be used. Every object created with your struct will contain both fields. What you're trying to do is called polymorphism, and you have it with classes in C++. Original C does not have such option.


There is no "proper" dictionary, there are just different trade-offs. In this case, we have that HashMap gives us better asymptotic random access whereas BTreeMap gives us sortedness.

Sorting the a HashMap after-the-fact is well and good, but BTreeMap is already sorted so it seems like the better choice.

Rust very heavily gives tasks out to crates. This is guided by RFC 1242, and you might notice regex is in rust-lang-nursery. This means it is official and it is "standard rust"; it's just not in the standard library.

Plus, it's as easy as adding regex = "0.1" to your Cargo.toml, so that's no reason to avoid it.

Ignoring that, that

let words = line.to_lowercase().split(...)

doesn't work is just a fact of life right now, although that will eventually get fixed with non-lexical lifetimes.

These imports

use std::io;
use std::io::BufRead;

are nicer as

use std::io::{self, BufRead};

The large match

match line_result {
    Ok(line) => {
        ...
    },
    Err(e) => {
        panic!("Error parsing stdin: {:?}", e);
    }
}

would be nicer as

let line = match line_result {
    Ok(line) => line,
    Err(e) => panic!("Error parsing stdin: {:?}", e),
};

...

or even

let line = line_result.unwrap_or_else(
    |e| panic!("Error parsing stdin: {:?}", e)
);

But in this case the error handling doesn't add anything, so I'd just unwrap. All of these examples panic; a method that doesn't would involve error handling by printing and then returning from the function. Printing is normally worse to debug (no tracebacks) but nicer for end-users.

Instead of

*(counts.entry(word.to_string()).or_insert(0)) += 1;

which always allocates a new String, one can index with a borrowed &str. Sadly this isn't supported by the entry API right now, but you can hack around it:

if let Some(count) = counts.get_mut(word) {
    *count += 1;
    continue;
}
counts.insert(word.into(), 1);

Note the use of if let/continue instead of match is because of lexical lifetimes.

Since this is currently pretty ugly and the speedup probably doesn't matter, I'll leave this as a hypothetical. You say you "don't like the asterisk", but that's kind'a how it's meant to be done. I guess you could go the Julia route (get + unwrap_or + insert), but that's not really better.

After a few miscellaneous changes, the code for me looks like

extern crate regex;

use std::collections::BTreeMap;
use std::io::{self, BufRead};

use regex::Regex;

fn main() {
    let word_re = Regex::new(r"[a-z']+").unwrap();

    let mut counts: BTreeMap<String, isize> = BTreeMap::new();

    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let line = line.unwrap().to_lowercase();
        let matches = word_re.find_iter(&line);
        let words = matches.map(|(x, y)| &line[x..y]);

        for word in words {
            *counts.entry(word.into()).or_insert(0) += 1;
        }
    }
    for (key, value) in counts.iter() {
        println!("{} {}", key, value);
    }
}

This isn't as nice as the Julia code, but it's giving you a lot of opportunities to be a lot more efficient, and it's catching a lot more errors. It's true that locking stdin feels like a chore on 50-line examples, but it fits Rust's macro-goals of faster, safer APIs.


Using Array to store calculations in VBA

Most of your variables aren't defined and your indenting isn't great.

When you don't define your variable, VBA will declare it as a Variant, which are objects:

  Performance. A variable you declare with the Object type is flexible
  enough to contain a reference to any object. However, when you invoke
  a method or property on such a variable, you always incur late binding
  (at run time). To force early binding (at compile time) and better
  performance, declare the variable with a specific class name, or cast
  it to the specific data type.

By not declaring variables, you could possibly be paying a penalty.

It's good practice to indent all of your code that way Labels will stick out as obvious.

Here's the first thing I would do -

Option Explicit
Sub mort()
    Dim age As Integer
    Dim month As Integer
    Dim i As Long
    Dim j As Long
    Dim gender As String
    Dim mortable As String
    Dim a As Long
    Dim b As Long
    Dim a1 As Long
    Dim b1 As Long
    Dim q As Long

    For i = 0 To ActiveSheet.Range("F5", Range("F5").End(xlDown)).Count
        For j = 0 To ActiveSheet.Range("G3", Range("G3").End(xlToRight)).Count

        gender = Range("C5").Offset(i, 0)

        If gender = "F" Then
            mortable = Worksheets("Female Tabs").Range("A3:C122")
        Else: mortable = Worksheets("Male Tabs").Range("A3:C122")
        End If

        month = Range("G3").Offset(0, j)
        age = WorksheetFunction.RoundDown(Range("F5").Offset(i, 0) + (month - 3) / 12, 0)

        If age < 119 Then
            a = (12 - ((month - 3) Mod 12)) / 12
            a1 = Application.VLookup(age, mortable, 3, False)
            b = ((month - 3) Mod 12) / 12
            b1 = Application.VLookup(age + 1, mortable, 3, False)
        Else
            a1 = 0
            b1 = 0
        End If

        q = (1 / 12) * (a * a1 + b * b1)
        Worksheets("Policy Mortality Qx").Range("G5").Offset(i, j).Value = q

        Next j
    Next i
End Sub

Next, I'd deal with the Variable names - give your variables meaningful names. As well as your procedure

Also if mortable is a Range then mortable = Worksheets("Female Tabs").Range("A3:C122") needs to be Set mortable = Worksheets("Female Tabs").Range("A3:C122")

Private Sub mortable()
    Dim age As Long
    Dim month As Long
    Dim gender As String
    Dim mortable
    Dim i As Long
    Dim j As Long
    Dim ageMonths As Long
    Dim ageMonthsLookup As Long
    Dim ageMonthsIncrease As Long
    Dim ageMonthsIncreaseLookup As Long
    Dim calculation As Long
End Sub

This If block can be simplified

   If age < 119 Then
        a = (12 - ((month - 3) Mod 12)) / 12
        a1 = Application.VLookup(age, mortable, 3, False)
        b = ((month - 3) Mod 12) / 12
        b1 = Application.VLookup(age + 1, mortable, 3, False)
    Else
        a1 = 0
        b1 = 0
    End If

Into

        If age < 119 Then
            ageMonths = (12 - ((month - 3) Mod 12)) / 12
            ageMonthsLookup = Application.VLookup(age, mortable, 3, False)
            ageMonthsIncrease = ((month - 3) Mod 12) / 12
            ageMonthsIncreaseLookup = Application.VLookup(age + 1, mortable, 3, False)
            calculation = (1 / 12) * (a * a1 + b * b1)
        Else: calculation = 0
        End If

This piece

ActiveSheet.Range("F5", Range("F5").End(xlDown)).Count

Is not the best way to find the bottom of a range

Dim lastRow As Long
Dim lastColumn As Long
lastRow = Cells(Rows.Count, "F").End(xlUp).Row
lastColumn = Cells(3, Columns.Count).End(xlToLeft).Column
For i = 0 To lastRow
    For j = 0 To lastColumn

Eh, that's it for now from me.


For the simplicity I'm not using a "model class" for this [...]

Then it's not Model-View-Presenter you have here.

var Presenter = new AttendancePointPresenter(AttendancePointView, ds);

I love it. What you've done here, is called Dependency Injection - more specifically, constructor injection. It's a technique that, when applied consistently, greatly contributes to making your code more cohesive and less coupled.

I think AttendancePointView being a local variable, should be named attendancePointView, or simply view - same for Presenter, it's a local variable, should be presenter; and ds could simply be called service, so the presenter code would read:

var presenter = new AttendancePointPresenter(view, service);
presenter.Show();

Which is awesome! Well done!

The only thing is that in Program.cs it doesn't matter that the view and the service are injected as interfaces, since Program is coupled with frmAttendancePoints and DataService anyway. I'd write it like this:

var view = new frmAttendancePoints();
var service = new DataService();

var presenter = new AttendancePointPresenter(view, service);
presenter.Show();

The presenter still receives its dependencies as abstractions, per its constructor.

  View

You're declaring an event that looks more like a method:

public event EventHandler ShowAttendancePoints;

Seeing that it's raised when the form gets loaded...

private void frmEnterAttendance_Load(object sender, EventArgs e)
{
    ShowAttendancePoints(sender, e);
}

That event does nothing that Load doesn't do. I think you should have an IView interface that exposes that Load event, and everything a presenter needs to know about any view:

public interface IView
{
    event EventHandler Load;
    void ShowDialog();
    void BindModel(IModel model);
}

Now the form's code can look like this*:

public partial class frmAttendancePoints : Form, IView
{
    public frmAttendancePoints()
    {
        InitializeComponents();
    }

    public void BindModel(IModel model)
    {
        dgAttendancePoints.DataSource = model;
    }
}

  DataService

This class should spit out your model, not a boilerplate-level DataTable.

One thing though, is that you can stack the using blocks for fewer levels of indentation:

using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
using (SqlDataAdapter da = new SqlDataAdapter(sqlCommand))
using (DataSet ds = new DataSet())
using (DataTable dt = new DataTable())
{
    ds.Tables.Add(dt);
    sqlConnection.Open();
    da.Fill(dt);
    return dt;
}

*This might need a bit of work, I'm not sure a WinForms DataGridView.DataSource can be assigned just like that, but you get the idea ;)


EDIT: FIXED

This specific instance can be rewritten as

public bool IsDirty(bool checkChildrenInd) {
  return ! (  Parent.NewId ||
              backup == null ||
              String.Equals(MissingDataValue, backup.MissingDataValue) ||
              String.Equals(PreviewDataValue, backup.PreviewDataValue) ||
              FieldOption == backup.FieldOption );
}

if this pattern is always the same, but there may be other conditions as you note in the comments, I note that CheckChildren

Takes a parameter which is also the function parameter
returns on all code paths
result is never assigned to before the goto statement

If this is always true, you can factor it out. replace the CheckChildren label with a function:

private bool CheckChildren(bool checkChildrenInd){
    bool result = false;
    if (!checkChildrenInd)
    {
        return result;
    }
    return result;
}

and the goto CheckChildren; with return CheckChildren(checkChildrenInd);

if result is possibly set to true before the goto statement, you will need to pass result as a variable to the funcion too (and include it in the signature).


Bash script to generate and change Java keystore passwords

It is a good practice to have the script tested on shellcheck.net so that you have a convention.

In the initialise section, you are cleaning up the keystore file (if it exists). Use the shell-builtin echo and redirect to achieve this:

echo "" > $config_file

The password_length can become a global value instead of being local to set_key_passphrase.

You can avoid the double echo in the set_keystore_password by using tee:

echo "$password" | tee -a "$config_file"


Is this the right way to write OOP PDO classes?

If a User object represents a single User, you would want one User instance per actual user you are working with in the application. For example, say your user might have friends:

class User {
    private $friends;

    public function addFriend(User $friend) {
        if (!in_array($friend, $this->friends)) {
            $this->friends[] = $friend;
        }
    }
}

Now, your User object can hold an array of other User objects, who he's friends with! You can do all sorts of cool stuff with that, like listing mutual friends (since those Users have their $friends array too!), displaying a list of friends on the page, or just figuring out who has more friends.

The User object is commonly known as a Domain object, it's an object which is part of the Domain Logic or Business Logic, i.e. the actual application, the actual purpose of the application, the part that does the actual work.

Review:

Most naming conventions in PHP dictate that $variableNames should be camelCased and not lowercase_underscores, however, stick with that works for you, and don't break existing convention if you're working in a collaborative project.
It's often preferable to separate the part where the User's details are kept and actual computation and processing takes place, and the part which is responsible for fetching and saving the User's details from permanent storage of some sort.

Consider this:

class User {
    private $id;
    private $name;

    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

This User object is different, it doesn't know where the details come from, they are injected from that magical place outside of the object where it doesn't know anything about. This User could have come from a database, he could have come from session, a file, a REST api, or I could have just made it up for testing purposes.

So how do you get the details from the database? You use the Data Mapper pattern.

class UserMapper {

    public function __construct(PDO $db_connection) {
        $this->db = $db_connection;
    }

    /**
      * Fetch user details from the database based on ID.
      * If $user exists, fill it. If not, create a new one.
      */
    public function fetch($id, User $user = null) { ... }
    /**
      * Save $user back into the database
      */
    public function save(User $user) { ... }

    ....
}

You can have more methods like "fetch the N top user with most comments", or "Fetch all the friends of this $user"

The point is, the Mapper is responsible for getting/saving all necessary data from the database or whatever other permanent storage you might need, and fill the actual Domain Object, which is then used by the application to do processing.


Memoizing a generator is a good idea to save having to rerun it. There are a few ways to do it - one is to handle it the way you're handling it, by returning the cached result if it exists, otherwise returning and caching the new result.

The first way, is to the the tee() method from itertools. Such as follows:

from itertools import tee

def run():
    for i in range(1000):
        yield i

sequence, memoized_sequence = tee(run())

This returns a 32 byte object:

<itertools.tee object at 0x23a564>
<itertools.tee object at 0x23a58c>

which you can then iterate over as you normally would:

for x in memoized_sequence:
    print x

Another way to do it, if the generator consistently returns small sets of data, is to just use list(). This is especially true if, like aforementioned, the generator returns small sets of data and that data is not dependent on an action (ie, data is static) and that data is not kept in memory for a long time (such as in a child that is killed (and its memory freed) once its served its purpose). The way to do so, is:

def run():
    for i in range(1000):
        yield i

memoized_sequence = list(run())

However, this set of 1000 integers while have a size of 4.2KB in memory. So its not ideal, nor memory efficient, but its an option.

Now, the way that you did it, as follows:

_results = []

def run():
    for i in range(1000):
        yield i

def results():
    def caching_iterator(it, r):
        for t in it:
            yield t
            r.append(t)

    if _results:  # _results is [] initially
        return _results
    return caching_iterator(run(), _results)

Would result in a 36 byte object:

<generator object caching_iterator at 0x23f97c>

I would suggest using the system provided tee function over the custom memoization technique, so your code would look like

from itertools import tee

def results():
    _, memoized_sequence = tee(self.run())
    return memoized_sequence

Doing so shaves you 4 bytes from the returned iterator object, as well as all the variable assignments and the added function and compacts your code.

EDIT

Seems that tee() does not memoize as I thought - it just returns an iterator. However, list() does so, though statically:

import random
from itertools import tee

def run():
    for i in range(5):
        x = random.randint(0, 100) * i
        print "calculating"
        yield x

_, memoized = tee(run())

for x in memoized:
    print x

l = list(run())
print l
print l

Results in:

calculating
0
calculating
92
calculating
94
calculating
165
calculating
100
calculating
calculating
calculating
calculating
calculating
[0, 43, 106, 222, 8]
[0, 43, 106, 222, 8]


Main Question

Is there better logic?

Repeated code
The first thing that I see with this code, which perhaps you see also, is that it is quite repetitive - select a list of checkboxes to see if any are checked - if none are checked then show an error message and return, otherwise hide any affiliated error message. This violates the Don't Repeat Yourself principle. It can be remedied by abstracting the common logic - e.g. putting the  the selectors into a mapping:
var SELECTOR_ERROR_MAPPING = {
    "#sources input[type=checkbox]:checked": "#lblSourcesError",
    "#academicFormatsRow input[type=checkbox]:checked": "lblacademicFormatError",
    //...more entries
};

Then use a loop to iterate over the mapping, checking each selector - e.g. using Array.every():
return Object.keys(SELECTOR_ERROR_MAPPING).every(function(selector) {
    var errorSelector = SELECTOR_ERROR_MAPPING[selector];

    var showError = !$(selector).length;
    $(errorSelector).toggle(showError, errorSelector);
    return !showError;
});

Those last three lines of the inner function could be placed into a separate function if desired, which would allow for better modularization/atomization and testing.
demo

var SELECTOR_ERROR_MAPPING = {
  "#sources input[type=checkbox]:checked": "#lblSourcesError",
  "#academicFormatsRow input[type=checkbox]:checked": "#lblacademicFormatError",
  "#academicMediaFormatRow input[type=checkbox]:checked": "#lblacademicmediaFormatError",
  //...more entries
};
$("#requestForm").submit(function(e) {
  e.stopPropagation();
  e.preventDefault();

  var allValid = Object.keys(SELECTOR_ERROR_MAPPING).every(function(selector) {
    var errorSelector = SELECTOR_ERROR_MAPPING[selector];

    var showError = !$(selector).length;
    $(errorSelector).toggle(showError, errorSelector);
    return !showError;
  });
  console.log('result', allValid);
  return allValid;
})
.error {
  color: red;
}

<form id="requestForm">

 Source

    Audi
      <input type="checkbox" name="source" value="Audi" />

    BMW
      <input type="checkbox" name="source" value="BMW" />

Please select a source

 Formats

    College
      <input type="checkbox" name="source" value="college" />

    University
      <input type="checkbox" name="source" value="university" />

Please select a format

 Media Formats

    DVD
      <input type="checkbox" name="source" value="DVD" />

    Blue-ray
      <input type="checkbox" name="source" value="blueray" />

Please select a media format

  <button>Submit</button>
</form>

Modern browsers support client-side validation using the required attribute on input elements1 and it is supported for checkbox inputs2 but apparently setting a custom message for checkboxes still involves writing some JavaScript3.
HTML layout
As one comment suggested, the dependence on the id attribute could be decreased - For example, if the location of the error message element was consistent within each section -e.g. a sibling of the list of checkbox inputs. Another solution might be to have each section of checkboxes and error message contained by a parent element with a consistent class name- then the JavaScript could loop over those container elements looking to see if the checkbox elements have any checked- if not, then display the error message.
Other review points
ES6
With modern JavaScript, consider using newer EcmaScript-2015 (AKA ES6) features, like for...of loops, the keywords let and const instead of var, etc.
jQuery
Also consider whether you really need jQuery because it may be the case it can be replaced with “vanilla JS” features. For example, to select elements with a CSS selector use document.querySelectorAll() and to add an event listener for the form submission, use the addEventListener() method after selecting that form element - e.g. with document.getElementById('requestForm'), document.forms[0] unless it isn't the first form, etc..
Loose comparisons
In the original code the length property of the jQuery objects was compared with 0 using loose equality - i.e. ==. A good habit and recommendation of many style guides is to use strict equality operators (i.e. ===, !==) whenever possible. The problem with loose comparisons is that it has so many weird rules one would need to memorize in order to be confident in its proper usage.
The suggested code above and below simplified this by using !$(checkboxSelector).length;
demo

const SELECTOR_ERROR_MAPPING = {
  "#sources input[type=checkbox]:checked": "#lblSourcesError",
  "#academicFormatsRow input[type=checkbox]:checked": "#lblacademicFormatError",
  "#academicMediaFormatRow input[type=checkbox]:checked": "#lblacademicmediaFormatError",
  //...more entries
};
document.forms[0].addEventListener('submit', e => {
  e.stopPropagation();
  e.preventDefault();

  for (const [selector, errorSelector] of Object.entries(SELECTOR_ERROR_MAPPING)) {
    const showError = !document.querySelectorAll(selector).length;
    document.querySelector(errorSelector).classList.toggle('hidden', !showError);
    if (showError) {
      return false;
    }
  }
});
.error {
  color: red;
}
.hidden {
  display: none;
}

<form id="requestForm">

 Source

    Audi
      <input type="checkbox" name="source" value="Audi" />

    BMW
      <input type="checkbox" name="source" value="BMW" />

Please select a source

 Formats

    College
      <input type="checkbox" name="source" value="college" />

    University
      <input type="checkbox" name="source" value="university" />

Please select a format

 Media Formats

    DVD
      <input type="checkbox" name="source" value="DVD" />

    Blue-ray
      <input type="checkbox" name="source" value="blueray" />

Please select a media format

  <button>Submit</button>
</form>


Try this minor variation over your script, that will probably have a dramatic effect on performance:

names = set()
edges = []

for idx, user in enumerate(all_users):
    if idx and not idx % 1000:
        print('Processing {} batch',format(idx))
    user_id = str(user['id_str'])
    names.add(user_id)
    for friend_id in user['friends_ids']:
        friend_id = str(friend_id)
        edges.append((user_id, friend_id))
        names.add(friend_id)

The main modification is making names a set, not a list, Your script is checking membership of every friend_id in names, an operation that takes time linear in the size of names. In contrast, membership in a set is done in constant time.

If you need names to be a list, simply do:

names = list(names)

after the processing is completed.


First of all, your code has a bug: You did not follow the rule of three.
Code such as myStack1 = myStack2; will cause the pointer to be deleted twice - which is undefined behavior.

int storedElements;

This seems kind of misleading. This variable doesn't hold the stored elements. It holds the number of stored elements. Perhaps storedElementsCount or something like that would be better?

myStaticIntStack( int aNumber );

Why did you call the variable aNumber here? aNumber is a terrible name. It tells me essentially nothing. Later you used stackSize which is a FAR better name. Why didn't you use it here too?

And, by the way, consider using size_t to store sizes and capacities instead of ints. This would apply to stackSize and storedElements.

myStaticIntStack::myStaticIntStack()
{
    this->stackSize = 1;
    this->elements = new int(0);
    this->storedElements = 0;
}

Seriously? The default behavior for the stack is to create a stack with maximum size 1? That is kind of... worthless. It's OK to allow this in the myStaticIntStack(int) constructor, but as a default it just seems odd.

Consider not even allowing a default constructor.

myStaticIntStack::myStaticIntStack( int stackSize )
{
    this->stackSize = stackSize;
    this->elements = new int[ stackSize ];
    this->storedElements = 0;
}

Can the stackSize be zero? Can it be negative? Consider adding an assertion.
By the way, if you make stackSize be a size_t, the negative case becomes impossible, since size_t is unsigned. But you'll still need to handle the "stackSize == 0" case.

A size of 0 might be acceptable. If that is the case, add a comment stating that and why it is so.

Consider declaring this constructor explicit.

myStaticIntStack::~myStaticIntStack()
{
    if( this->elements != NULL )
    {
        if( stackSize > 1 )
            delete[] this->elements;
        else
            delete this->elements;
    }

}

Why do you need a NULL check? Are you expecting the destructor to be called with elements == NULL? If this merely defensive programming and this case is never supposed to happen, then leave it as an assertion.

Also, that whole delete vs delete[] is weird. What if I use the constructor myStaticIntStack(1)? Then you'll be deleteing something created with new[].

I'd change the code (from the constructors) so that new[] - not new - is always used and, therefore, delete[] is always the right thing to do in the destructor.

void myStaticIntStack::push( int newElement )
{
    if( this->storedElements == this->stackSize )
        cout << "Stack is full, you must POP an element before PUSHing a new one!" << endl;
    else
    {
        this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
        this->storedElements++;
    }
}

This is improper error handling that violates the single responsibility principle.
Your function should either throw an exception, merely assert the condition or return an error code. Printing to the command line should be done elsewhere - probably outside this class.

this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;

I'm pretty sure you could simplify this. For a stackSize=16, the first position is at index 15. Why 15? Why not 0? That'd simplify the code to just elements[storedElements] = newElement;. Just remember to also fix the pop/peek code.

Just because the stack is Last-in-first-out doesn't mean you have to fill the last indexes in the internal array first. That's an implementation detail.

  it's confusing that pop() returns a value even if Stack is empty.

Then don't  return a value if the Stack is empty. Throw an exception or abort with an assertion. Problem solved. Next.
As I stated before, your couts are in the wrong place. If you fix that the "Pop return" problem might just naturally go away.

If you decide to keep it like that (return -1), then consider making -1 a named constant since magic numbers are bad.

return ERROR_STACK_IS_EMPTY;

int myStaticIntStack::peek()

Same thing about cout.
Also, peek() doesn't change anything, does it? Then consider making it const.

int myStaticIntStack::peek() const

Consider splitting your myStaticIntStack in two files: myStaticIntStack.hpp and myStaticIntStack.cpp.
Your main function would be in a third file.

Some extra thoughts:

I suspect the "better way" might be to just use a vector internally. This would painlessly solve your "rule of three" problem. Bonus points since it'd make it easier to "resize" the stack after being created if you ever wanted to add that feature.
Personally, I'd uppercase the first letter of the class name, but that's just personal preference. Nothing wrong with your particular style.
Consider adding a bool empty() function, that checks if the stack is empty.
Consider adding a bool full() function, that checks if the stack is full.
Those two functions above could make your error detection code easier to understand. If your assignment forbids adding extra functions, consider adding them as private functions.
Consider adding a int size() function, that returns storedElements.
Consider adding a int capacity() function, that returns stackSize
Normally, a class like this would be implemented as a template since it's useful to have stacks for more than just integers. Not sure if you've learned about templates yet.

If you follow QuentinUK's suggestion of removing the this->, beware. There is one case that might cause you trouble.
In the constructor, this->stackSize = stackSize; is correct, but stackSize = stackSize; would not be.
To work around this issue, you could use something like this:

/*optionally add "explicit" here*/ myStaticIntStack::myStaticIntStack( int stackSize ) :
    stackSize(stackSize)
{
    elements = new int[ stackSize ];
    storedElements = 0;
}

This is all I can think of right now. Hope this helps.


Reverse an array without affecting special characters

Class fields

    static HashSet<Character> invalidChars = new HashSet<Character>(Arrays.asList(',', '?', ':','!','$'));

You might as well go ahead and make this final as well.

    public static final Set<Character> invalidChars = new HashSet<>(Arrays.asList(',', '?', ':', '!', '$'));

As a final variable, it's clear that it won't change.

We should probably specify a visibility.  Unless it's a secret, we should go ahead and make it public.  Since it's final, no one can change it.

It is better to type to the interface than the implementation.  This allows us to change the implementation without changing the type.  And it forces us to limit ourselves to the operations available in the interface.

In newer versions of Java, you don't need to say Character twice.  The compiler will figure out the type on the second one.

Eliminate unnecessary variables

        int l = 0;
        int r = charArray.length - 1;
        for (int i = 0; i < charArray.length; i++) {

            if (r <= l) {
                break;
            }

You can write this either

        for (int l = 0, r = charArray.length - 1; l < r; ) {

or

        int l = 0;
        int r = charArray.length - 1;
        while (l < r) {

You don't need the extra i variable.  Nor do you need to do the l < r check separately.

It's up to you if you use a for or a while.  Either will work.  The for is a bit more compact, but you have to leave the update section blank.  Either will be shorter.

Not really invalid

            if (!isInvalidChar(charArray[l]) && !isInvalidChar(charArray[r])) {
                charArray = swapChars(charArray, l, r);
                l++;
                r--;
            } else if (isInvalidChar(charArray[l])) {
                l++;
            } else if (isInvalidChar(charArray[r])) {
                r--;
            }

It's not that the characters are invalid.  They are expected and you want to preserve them.  It's that the character are special and treated different.  Consider

            if (isSpecialChar(charArray[l])) {
                l++;
            } else if (isSpecialChar(charArray[r])) {
                r--;
            } else {
                // neither is a special character
                swapChars(charArray, l, r);
                l++;
                r--;
            }

You use the terminology special elsewhere, so why not here?

I also like that this emphasizes the positive.

Since we already know that neither character is a special character, we don't have to check again.

The swapChars method modifies the charArray in place.  We don't have to return it and assign.

Generating a character array

        char[] charArray = new char[]{'a', 'b', 'c', 'd', '?', 'f', 's', ':', 'w'};

If you want to type less, consider

        char[] charArray = {'a', 'b', 'c', 'd', '?', 'f', 's', ':', 'w'};

or

        char[] charArray = "abcd?fs:w".toCharArray();

No big deal, but why type more than necessary?


Isolate a Database Change Within Django Transaction.Atomic

Let's start off with what's probably the most important note here: if you are running into issues with atomic transactions, pushing the database work off to Celery (or another worker thread) inherently makes your transactions non-atomic. It sounds like this has been working for you currently, but this will not always work and may have unintended consequences.

So I'm going to review this from two different angles:

Handling atomic transactions within APIs when you only need part of it to be atomic
Chaining Celery tasks that need to execute conditionally

If only part of your handling needs to be atomic, don't make everything atomic

In your hypothetical example, you make it clear that db_operation needs to be atomic and that's why you are wrapping the entire handle in transaction.atomic. I'm assuming that db_operation is actually a series of calls, or something more complex than just a single call, which is why you couldn't just decorate that call with transaction.atomic. But you only appear to care about these calls being atomic, which is why the call to refresh_token still needs to be committed to the database even if there are issues within db_operation.

My suggestion would be to use transaction.atomic as a context manager instead of as a decorator. This would result in your hypothetical view looking something like:

def post(request):
    response = api_call()
    with @transaction.atomic():
        db_operation(response['result']) #  Could potentially have an exception

This still allows db_operation to remain atomic while ensuring that api_call is always committed to the database.

Celery has advanced method chaining, use it to your advantage

You correctly identified that calling one Celery task and waiting for a response can easily cause a deadlock or starvation, which is why Celery explicitly recommends that you don't do it.

Getting an error when making an API call because your access token has expired is generally considered to be an exceptional case. Celery provides functionality for handling exceptions, so don't be afraid to use it. You found Celery's chaining functionality, but what is also useful is the linking functionality between tasks that works very similarly.

def post(request):
    api_call_task.apply_async(
        link=[db_operation_task.s()],
        link_error=[refresh_token_task.s(), api_call_task.s(), db_operation_task.s()]
    )

You'll see in this case that if the original call to api_call_task returns an error, we are instructing Celery to call refresh_token_task, then api_call_task again (it should have a valid token) and then eventually db_operation_task like we originally planned. This allows for api_call_task to error out twice, such as if there was an error not relating to the token refresh, without risking calling db_operation_task with potentially invalid data.

Because Celery provides a clear callback format and allows you to define a chain of methods to be called during the callbacks, you can design your tasks to only focus on what they really care about: calling those other methods.

@task
def api_call_task():
    response = requests.post(url, params)

    if response.status_code == 401:
        raise Exception('Access token needs to be refreshed')

    return response

@task
def refresh_token_task():
    refresh_token()

@task
@transaction.atomic()
def db_operation_task(response):
    db_operation(response['result'])

This has the benefit of allowing you to handle errors naturally within the flow, without forcing every step in the chain to perform the error handling for you.

Bonus: Celery tasks can also be run synchronously, use that to your advantage

In your hypothetical example, you defined api_call and api_call_task when talking about the Celery task and the actual API call itself. If you have control over api_call (it's not a third-party call), you can actually just condense this down to a single method. If you call a method wrapped with @task() without calling .delay() or .apply_async(), the method is called synchronously and Celery is never contacted. This allows you to design methods which can be called either asynchronously using Celery, or synchronously in the course of your own application, without having to duplicate a lot of code or add in additional special cases.

Because Celery allows you to execute the code synchronously that would otherwise be executed asynchronously, this also makes testing of these tasks much easier. In tests you can call them synchronously and ensure the functionality works as expected, while knowing that in the real world there may be a time delay that you need to account for.


Organizing a long string into a list of lists


Can this promise be chained more cleanly?

I have never used RSVP, I am more familiar with Q, but I believe following should do what you need:
var evaluate = function (xmlDoc) {
    TokenData = xmlDoc.evaluate(
        '/root/theToken',
    xmlDoc.documentElement,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null).singleNodeValue.textContent;
    return TokenData;
}

RSVP.resolve(TokenData || LoadURIPromise(TokenURL).then(evaluate))
    .then(function (token) {
    //Use Token here
    console.info(token);
});

Here is working jsFiddle
BTW, do you really need TokenData to be global?


Using VBA to "apply names" to named range references

'No error handling should be needed

Except, you never really know what assumptions you're making without realizing. Better safe than sorry.

For example, here's where your procedure might blow up:

Set srchRng = ActiveSheet.UsedRange

You're assuming that the ActiveSheet will be a Worksheet object, but ActiveSheet can also be a Chart object, which doesn't have a UsedRange method, so that line raises error 438 "Object doesn't support this property or method".

You could verify that ActiveSheet is indeed a Worksheet object before accessing its UsedRange, but that wouldn't be all.

For n = 1 To ClctNames.Count

You're also assuming ClctNames.Count will be equal to or greater than 1. However in a new workbook, ActiveWorkbook.Names.Count returns 0, so that For loop goes from 1 to 0... lucky for you, VBA won't enter that loop - but it's not obvious behavior and would be better off explicitly handled at the start of the procedure:

If ClctNames.Count = 0 Then Exit Sub

When evaluating a Boolean value in an If condition:

If c.HasFormula = True Then

You never need to make a Boolean expression out of the Boolean value. This is equivalent, and reads better:

If c.HasFormula Then

As for the forced-absolute references, you can pass parameters to Range.Address:

rngNameLoc = ClctNames(n).RefersToRange.Address(RowAbsolute:=False, ColumnAbsolute:=False)

This removes the dollar signs from the RefersToRange address, but then this:

strFrmla = Replace(c.Formula, rngNameLoc, rngName)

Needs to actually look for the 4 variants of the range address:

$A$1
$A1
A$1
A1

Things get more "fun" when the address refers to a range of cells:

$A$1:$A$10
$A1:$A$10
A$1:$A$10
A1:$A$10

Wait, did you notice?

Replacing $A$1 with Foobar in =SUM($A$10:$A$25) will break something - it won't raise a VBA runtime error, but I'm pretty sure =SUM(Foobar0:$A$25) won't evaluate properly.

This definitely looks like a job for a regex replace, more than a simple string comparison and replacement.


I'm going to say no, because this is an array. It works, but you are hammering a screw at this point. Simply use an array.


I know you wanted to avoid if / else, but I think i would probably write it like this:

def create
  @stud = Student.new params[:student]

  if @stud.save
    redirect_to @stud
  else
    render :action => :new
  end
end

Which is the same amount of code but has two advantages:

it is more readable by a human.  Rescue is not a human concept in logic, whereas if / else is clearly understood.
when you rescue here, you rescue from anything.  if @stud.save is specific, if that fails it won't throw an exception, but will return false.  So you are responding to the appropriate condition.

One other note: if you want to stick with the rescue pattern, you could shorten the function by a single line by writing

@stud = Student.create! params[:student]

which is the same as writing:

@stud = Student.new params[:student]
@stud.save!

ian.


As mentioned in the comments by @elclanrs, you should not use for...in to loop through arrays.
As mentioned by @megawac, lexical comparison will not produce the results you expect. So you'll need to parse those strings.
Use more descriptive names. data should probably be tickets, arr could be dates. Nothing should be just o or d. It makes the code much, much harder to read.
Remember to remove all console.log calls in production code (or do a check to make sure that console exists, and has a function called log before you try calling it - otherwise things break)

Since you seem to be using underscore.js, you should look at the groupBy function

var grouped = _.groupBy(tickets, function (ticket) { return ticket.date });

The above will create an object with the date strings as keys, and arrays of tickets as values. Pretty much the same as the first half of your current function.

But we can do more with underscore. All of it actually:

function sortMyTicketsByDate(tickets) {
  return _.chain(tickets)
    .groupBy(function (ticket) { return ticket.sort })
    .sortBy(function (group, date) {
      var parts = date.split(/\/0?/);
      return new Date(parts[3], parts[1] - 1, parts[2]);
    })
    .map(function (group, date) { return { date: date, tickets: group }; })
    .value();
}

Caveat emptor: The major difference between the above function and your original one, this one returns the same objects it was given, whereas yours return copies. So any change made to the tickets afterward are being made to the originals.

That also means that the sort property remains (whereas you just don't copy it)

To avoid these points (if you really need to, which I very much doubt you do), you can do this:

function sortMyTicketsByDate(tickets) {
  return _.chain(tickets)
    .map(_.clone) // copy objects
    .groupBy(function (ticket) { return ticket.sort })
    .sortBy(function (group, date) {
      var parts = date.split(/\/0?/);
      return new Date(parts[3], parts[1] - 1, parts[2]);
    })
    .map(function (group, date) { return { date: date, tickets: group }; })
    .each(function (group) { // remove sort property
      _.each(group.tickets, function (ticket) { delete ticket["sort"] });
    })
    .value();
}


Find and select image files from webpage

There is no point in hard-coding proxy_addr and proxy_port separately, then concatenating them using interpolation.  On the other hand, it would be useful to make the proxy configurable.  One way is to use a default parameter:

def self.images(url, proxy='http://localhost:8080')
  doc = …
end

(Personally, I'd choose to have proxy default to nil, but the formulation above preserves compatibility with your existing code.)

You appear to be using the open function that is provided by OpenURI.  You have a bug: the proxy needs to be specified as an option to open rather than to Nokogiri#HTML.  Furthermore, opening the stream like that makes it impossible to close it properly.  I suggest using a block instead:

def self.images(url, proxy=nil)
  open(url, proxy: proxy) do |io|
    doc = Nokogiri::HTML(io)
    …
  end
end

Your regular expression should be case-insensitive when it looks for http:, as recommended by RFC 3986 Sec 3.1:

  An implementation should accept uppercase letters as equivalent to lowercase in scheme names (e.g., allow "HTTP" as well as "http") for the sake of robustness but should only produce lowercase scheme names for consistency.

Furthermore, hostnames are case-insensitive, as stated in RFC 1035 Sec 2.3.3 (though clarified by RFC 4343 Sec 2):

  For all parts of the DNS that are part of the official protocol, all
  comparisons between character strings (e.g., labels, domain names, etc.)
  are done in a case-insensitive manner.

Also consider allowing URLs that start with https:.

The parameter to your two blocks should not be named uri, but rather img, after the <img> tags that your CSS-style selector requested.

The way you sequence select, map, and reject is awkward.  I suggest

doc.css('img[src$="jpg"], img[src$="png"]').map do |img|
  img['src']
end.select do |uri|
  uri =~ %r{^https?://(\d+|media)}i and uri !~ /avatar/
end


Operator-free version (answer to...your answer):

public static class Analysis
{
    public static readonly Lazy<double> n10 = new Lazy<double>(() => F(10));

    private double static F(int n)
    {
        return n <= 1 ? 1 : n * F(n - 1);
    }
}

Do not look at marginal style differences (I cannot get used/appreciate expression bodied functions but it's just my own problem), point I'd like to highlight is:

You do not need Once class, Framework already has a class for lazy creation of values: Lazy<T>. It even nicely handle thread-safety issues (safe creation and/or publication) if field is not static (in that case C# itself helps us.)

Few minor notes about current code:

Analysis class has no need to be instantiable and all methods can be static.
Class itself can then be static.
IMO you do not need a dictionary, first of all because of the performance impact (even if it's a concurrent collection without locks) but also because it limits its usage to static methods (you use MethodInfo as key).

I understand your point of view (C# syntax isn't so clean to be used for business logic) but instead of forcing syntax and change operators semantic I'd prefer to use another language. Boo was first that came to my mind (especially because to change and extend the language to have a DSL is incredibly easy). I used it few years ago then I'm not up-to-date with its evolution. There are also other tools (second thought if for Microsoft Modeling SDK if you like visual editors instead of plain text code)


Word break problem with dynamic programming

The first thing an algorithm needs to be is correct, and yours isn't, at least the recursive version (I didn't look at the second one).

For example, ContainsWordRecursive("ihate", dictionary) returns { "i" }, which I don't think is the right result. Instead, your method should somehow indicate that it failed, for example by returning null.


ISTR that type(x) is relatively slow.  Try saving it in a local variable:

typev = type(v)
if typev is list and len(v) == 1:
        isSingleElementList = True

if typev is not list or isSingleElementOfList:   # if v is a single element
    v0 = v[0] if isSingleElementOfList else v

    type_v0 = type(v0)
    if type_v0 is bytearray or v0.__class__.__name__ == 'bytes':
        return hash(v0)
    if type_v0 is int:
       return hash(ToByteArray(v0))
    if type_v0 is str:
        return hash(v0.encode('utf-8'))
else:                               # if v is a list
    res = bytearray()
    for vi in v:
        res +=  RecHash(vi)     # recursion
    return hash(res)            # hash the concatenated hashes

Also, btw, your code will choke on nested single element lists. Consider [[[1]]]


Python script using Minneapolis / St. Paul Metro Transit's API to tell you how long till next bus

As Ludisposed said in his answer, yours is a very top-down approach. The minimum you should do is put this into a function, so you can re-use it. Here I rewrote your code quite significantly. Instead of returning -1, use the fact that a Python function returns None by default, which is a better safe value than -1.

I also completely re-wrote your getData function. Honestly, I have no idea what half of that was trying to do. All you need to do is iterate over the data. No need for a try: sys.exit(...) except: (which will always call what is inside the except, so why bother?). Also no need for a while True loop, if you are only ever going to go through it once.

I added the simple argparse parser and added the calling code under a if __name__ == "__main__": guard.

import argparse
import time
import sys
import requests

URL = "http://svc.metrotransit.org/NexTrip/{}?format=json"

def get(path, key, value, arg):
    resp = requests.get(URL.format(path))
    data = resp.json()
    for item in data:
        if arg in item[key].lower():
            return item[value]

def next_bus(route, stop, direction):
    route_id = get("Routes", "Description", "Route", route)
    if route_id is None:
        raise RuntimeError("{} is not a valid route.".format(route))

    direction_id = get("Directions/{}".format(route_id),
                           "Text", "Value", direction)
    if direction_id is None:
        raise RuntimeError("{} does not go {}.".format(route, direction))

    stop_id = get("Stops/{}/{}".format(route_id, direction_id), "Text", "Value", stop)
    if stop_id is None:
        raise RuntimeError("{} is not along {} going {}.".format(
            stop, route, direction))

    time_ = get("{}/{}/{}".format(route_id, direction_id, stop_id),
                    "RouteDirection", "DepartureTime", direction)
    if time_ is None:
        raise RuntimeError("Could not get next connection.")
    return int((float(time_[6:16]) - time.time()) // 60)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("route")
    parser.add_argument("stop")
    parser.add_argument("direction")
    args = parser.parse_args()
    time = next_bus(**vars(args))
    if time > 1:
        print "{} minutes".format(time)
    else:
        print "1 minute or less"

Alternatively, you could make this a class and use property for the different ids. This would allow you to have an object like trip_home = Connection(route, direction, stop), on which you could call trip_home.next to get the latest connection.

The different ids are looked up upon the initialization of the class. Calls to trip_home.next will only need to get the next connection. This assumes that the ids do not change during the runtime of the program, of course.

import argparse
import time
import sys
import requests

class Connection:
    url = "http://svc.metrotransit.org/NexTrip/{}?format=json"

    def __init__(self, route, stop, direction):
        self.route = route
        self.stop = stop
        self.direction = direction
        self.route_id = self.get_route_id()
        self.direction_id = self.get_direction_id()
        self.stop_id = self.get_stop_id()

    def __str__(self):
        return "{self.route} from {self.stop} due {self.direction}. Next connection in {self.next} minutes.".format(self=self)

    def get(self, path, key, value, arg):
        resp = requests.get(self.url.format(path))
        data = resp.json()
        for item in data:
            if arg in item[key].lower():
                return item[value]

    def get_route_id(self):
        id_ = self.get("Routes", "Description", "Route", self.route)
        if id_ is None:
            raise RuntimeError(
                "{self.route} is not a valid route.".format(self=self))
        return id_

    def get_direction_id(self):
        id_ = self.get(
            "Directions/{self.route_id}".format(self=self), "Text", "Value", self.direction)
        if id_ is None:
            raise RuntimeError("{self.route} does not go {self.direction}.".format(
                self=self))
        return id_

    def get_stop_id(self):
        id_ = self.get(
            "Stops/{self.route_id}/{self.direction_id}".format(self=self), "Text", "Value", self.stop)
        if id_ is None:
            raise RuntimeError(
                "{self.stop} is not along {self.route} going {self.direction}.".format(self=self))
        return id_

    @property
    def next(self):
        time_ = self.get("{self.route_id}/{self.direction_id}/{self.stop_id}".format(self=self),
                         "RouteDirection", "DepartureTime", self.direction)
        if time_ is None:
            raise RuntimeError(
                "Could not find next connection on route {self.route} from {self.stop} due {self.direction}".format(self=self))
        return int((float(time_[6:16]) - time.time()) // 60)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("route")
    parser.add_argument("stop")
    parser.add_argument("direction")
    args = parser.parse_args()
    trip_home = Connection(args.route, args.stop, args.direction)
    print trip_home


Select comparison function for sorting based on type information

Bug
I don't know anything about the python interpreter, but this if statement:

if (keys_are_in_tuples &&
    (lo.keys[i]->ob_type != &PyTuple_Type || Py_SIZE(lo.keys[0]) == 0)){

should be:
if (keys_are_in_tuples &&
    (lo.keys[i]->ob_type != &PyTuple_Type || Py_SIZE(lo.keys[i]) == 0)){

where keys[0] was changed to keys[i] in the size check.  Otherwise the size check will always be false, since Py_SIZE(lo.keys[0]) was already determined to be nonzero if keys_are_in_tuples is true.
Suggestion for simplification
If you created static inline functions like these:
static inline bool key_is_in_tuple(PyObject *obj)
{
    return obj->ob_type == &PyTuple_Type && Py_SIZE(obj) > 0;
}

static inline PyTypeObject *get_key_type(PyObject *obj)
{
    return key_is_in_tuple(obj) ?
               PyTuple_GET_ITEM(obj,0)->ob_type :
               obj->ob_type);
}

Then your code would read easier:
/* Turn off type checking if all keys are same type,
 * by replacing PyObject_RichCompare with lo.keys[0]->ob_type->tp_richcompare,
 * and possibly also use optimized comparison functions if keys are strings or ints.
 */
/* Get information about the first element of the list */
int keys_are_in_tuples = key_is_in_tuple(lo.keys[0]);

PyTypeObject* key_type = get_key_type(lo.keys[0]);

int keys_are_all_same_type = 1;
int strings_are_latin = 1;
int ints_are_bounded = 1;

/* Test that the above bools hold for the entire list */
for (i=0; i< saved_ob_size; i++) {

  if (keys_are_in_tuples && !key_is_in_tuple(lo.keys[i]) {
    keys_are_in_tuples = 0;
    keys_are_all_same_type = 0;
    break;
  }

  if (get_key_type(lo.keys[i]) != key_type) {
      keys_are_all_same_type = 0;
      break;
  }
  // ...


OK, after some digging I realized I was actually familiar with the notation below after all:

$$\sum_{j=0}^{\infty} \sum_{k=0}^{\infty} \binom{-1}{j}\binom{-2}{k}$$

However I've only seen it in use for combinations where negative numbers are not allowed.  I initially thought it must represent some other mathematical function, but I found a generalized version that easily allows for negative numbers.  For those interested, it's covered under the Wikipedia article on "Binomial Coefficient" in the section on "Generalization and connection to the binomial series."

Below is the C++ function I came up with.  It essentially starts the CDF off with zero and then adds to the CDF by increasing j and k from zero toward infinity until the change falls below the threshold given in the precision constant.  Here the precision is set to 0.00000001, giving probably at least six decimal places of accuracy, possibly seven, which is good enough for my purposes.  Decreasing the precision further would return even more accurate results at the cost of speed, but that might be necessary for a different application.

Some quick notes:

-- The net result of this function:
$$\sum_{j=0}^{\infty}\binom{-1}{j}$$
is to simply return 1 if j is even and -1 if j is odd.  I've substituted it with a much simpler jMult = ((j % 2) != 1) ? 1 : -1;

-- The net result of this function:
$$\sum_{k=0}^{\infty}\binom{-2}{k}$$
is to simply return k + 1 if k is even and -(k + 1) if k is odd.  I've substituted it with a much simpler kMult = -((k % 2) * 2 - 1)*(k + 1);

-- Although Nadarajah shows two different formulas in his paper, one for value greater than zero and one for value less than zero, I've written this function so that it can accept a positive or negative value and return the correct number with only one formula.

-- Also, Nadarajah doesn't mention this but I realized that when the shape is negative, there are j and k combinations that end up dividing by zero.  However, the correct result is given by finding x using the negative of the shape and value and returning 1 - x as the result.

-- I accomplished both of the above by introducing the distance, distanceMultiplier, shapeTerm, and extraShapeTerm variables and adjusting Nadarajah's formula to use those.

-- I also use kLastSignificant and kPrevious variables to track how far out on k the previous iteration of j went before it fell below the precision threshold.  I found that for larger values of j, the initial k would be below the precision threshold but later values of k would be above the threshold.  Here I wanted to ensure the function captured those later values by going out at least as far on k as the previous iteration of j did.

[EDIT]
-- I've updated the function to use Nadarajah's correct formula for the case of when the value is exactly zero.  The psi function comes from http://people.sc.fsu.edu/~jburkardt/cpp_src/cdflib/cdflib.cpp

There are still two areas of improvement I can identify:

-- The function is extremely fast except when the value is close or equal to zero.  For example, if the value is 0.0001, the j and k tend to stretch out for extremely long periods before they fall below the precision threshold.

-- For very large values, the j and k initially start below the precision threshold and the function results in a one or a zero, which are not possible in the logistic distribution.  To fix this, I've added a portion at the end of the function to simply return either the precision or (1 - precision) in those cases.

In the end, the skew logistic CDF really needs an approximation formula that would easily address each of those issues and provide an even faster function at the cost of a little accuracy.  It's how most other functions like this (i.e., the Normal CDF) are calculated and it would make the inverse much easier to calculate (and more practical to program).

// Skew Logistic CDF
double SkewLogisticCDF(double value, double location, double scale, double shape)
{
const double precision = 0.00000001;

double x = 0;

if (shape == 0)
{
    x = 1 / (1 + exp(-(value - location) / scale));
}
else
{

    // Evaluate the distance and the shape
    // If the shape is negative, then distance *= -1 and shape *= -1
    double shapeTerm = (shape > 0) ? shape : -shape;
    double distance = (shape > 0) ? (value - location) : (location - value);

    double distanceTermMultuplier = (distance < 0) ? 1 : -1;
    double extraShapeTerm = (distance < 0) ? shapeTerm : 0;

    int j = 0;
    int k = 0;

    double result;
    int kPrevious = 0;
    int kLastSignificant = 0;

    // distance != 0
    if (distance != 0)
    {
        // j
        do
        {

            // Returns 1 if j is even, -1 if j is odd
            // This is the ( -1 )
            //             (  j ) of the formula
            // Can also achieve using (j % 2)*-2 + 1;
            // Went with conditional operator to make quicker
            int jMult = ((j % 2) != 1) ? 1 : -1;

            k = 0;
            kLastSignificant = 0;
            // k
            do
            {

                // Returns (k + 1) if k is even, -(k + 1) if k is odd
                // This is the ( -2 )
                //             (  k ) of the formula
                // Can also achieve using -((k % 2) * 2 - 1)*(k + 1);
                // Went with conditional operator to make quicker
                int kMult = -((k % 2) * 2 - 1)*(k + 1);

                result = jMult * kMult * 1 / (1 + extraShapeTerm + shapeTerm * j + k) * exp((1 + extraShapeTerm + shapeTerm * j + k) * distanceTermMultuplier * distance / scale);

                x += result;

                kLastSignificant = (abs(result) >= precision) ? k : kLastSignificant;
                ++k;

            } while (abs(result) >= precision || k <= kPrevious);

            kPrevious = kLastSignificant;

            ++j;

        } while (kLastSignificant > 0);

        x *= 2;
        x = (distance < 0) ? x : 1 - x;

    }

    // distance == 0
    else
    {
        // j
        do
        {

            // Returns 1 if j is even, -1 if j is odd
            // This is the ( -1 )
            //             (  j ) of the formula
            // Can also achieve using (j % 2)*-2 + 1;
            // Went with conditional operator to make quicker
            int jMult = ((j % 2) != 1) ? 1 : -1;

            double psiAlpha = 1 + shapeTerm + shapeTerm * j;
            double psiOne = (1 + psiAlpha) / 2;
            double psiTwo = psiAlpha / 2;

            psiOne = psi(psiOne);
            psiTwo = psi(psiTwo);

            result = jMult * (0.5 - shapeTerm * (1 + j) * 0.5 * (psiOne - psiTwo));

            x += result;

            ++j;

        } while (abs(result) >= precision);

        x *= 2;

    }
}

// Reverse result if shape is negative
x = (shape > 0) ? x : 1 - x;

x = (x == 0) ? precision : x;
x = (x == 1) ? (1 - precision) : x;

return x;

}


No sense send slice of numbers into the summation function. Would be better pass the string and work with it. This will avoid necessary  enumeration of the elements of the slice and return result.
No need to create a slice with 0 capacity,because it will increase costly. In your case, it was possible to write so:

floatsSlice := make([]float64, len(textSlice))
 ...
 for index, elem := range textSlice {
     ...
    floatsSlice[index] = i
 }

No need to create extra variable

fmt.Println("Here is the result:", AddAll(ReadInput()))

Putting it all together and the result is:

func getline() (string, error) {
    return bufio.NewReader(os.Stdin).ReadString('\n')
}

func sumNumbers(str string) float64 {
    var sum float64
    for _, v := range strings.Fields(str) {
        i, err := strconv.ParseFloat(v, 64)
        if err != nil {
            fmt.Println(err)
        } else {
            sum += i
        }
    }
    return sum
}

Call:

str, err := getline()
if err == nil {
    fmt.Println("Here is the result:", sumNumbers(str))
}


My $0.02. Your solution is quite good as it stands. Just putting my thing down too.

I'm a fan of interface-based development with factory methods, so I extracted out an interface for the Person class called IPerson:

public interface IPerson
{
    string Name { get; }

    DateTime BirthDate { get; }
}

and then implemented Person as a sealed immutable class (using readonly and a parametrized private constructor) which has a factory method:

public sealed class Person : IPerson
{
    private readonly string name;

    private readonly DateTime birthDate;

    private Person(string name, DateTime birthDate)
    {
        this.name = name;
        this.birthDate = birthDate;
    }

    public string Name { get { return this.name; } }

    public DateTime BirthDate { get { return this.birthDate; } }

    public static IPerson Create(string name, DateTime birthDate)
    {
        return new Person(name, birthDate);
    }
}

I did similarly with the class you called Pair, but I called it PersonBirthdayDifference (I'll freely admit I can't think up a useful name at all). Also note the static Empty property which I put to use in the Finder algorithm rather than just newing up one with no properties set.

public interface IPersonBirthdayDifference
{
    IPerson YoungerPerson { get; }

    IPerson ElderPerson { get; }

    TimeSpan AgeDifference { get; }
}

and

public sealed class PersonBirthdayDifference : IPersonBirthdayDifference
{
    private static readonly IPersonBirthdayDifference empty = Create(null, null);

    private readonly IPerson youngerPerson;

    private readonly IPerson elderPerson;

    private readonly TimeSpan ageDifference;

    private PersonBirthdayDifference(IPerson youngerPerson, IPerson elderPerson)
    {
        this.youngerPerson = youngerPerson;
        this.elderPerson = elderPerson;
        this.ageDifference = (youngerPerson == null) || (elderPerson == null)
            ? default(TimeSpan)
            : elderPerson.BirthDate - youngerPerson.BirthDate;
    }

    public static IPersonBirthdayDifference Empty { get { return empty; } }

    public IPerson YoungerPerson { get { return this.youngerPerson; } }

    public IPerson ElderPerson { get { return this.elderPerson; } }

    public TimeSpan AgeDifference { get { return this.ageDifference; } }

    public static IPersonBirthdayDifference Create(IPerson p1, IPerson p2)
    {
        return new PersonBirthdayDifference(p1, p2);
    }
}

Finally, I update the Finder class by some of the same methods as above, plus introduce a couple more helper classes called GreaterThanComparer and LessThanComparer (not posting that code, it's rather trivial) to keep the switch from executing every iteration of the loop. There's also a healthy dose of LINQ to help declare intent where I can:

public sealed class Finder : IFinder
{
    private readonly IList<IPerson> people;

    private Finder(IEnumerable<IPerson> people)
    {
        this.people = people.ToList();
    }

    public static IFinder Create(IEnumerable<IPerson> people)
    {
        return new Finder(people);
    }

    public IPersonBirthdayDifference Find(FinderType finderType)
    {
        var peopleInOrder = this.PopulateListInOrder();

        return peopleInOrder.Any() ? GetAnswer(peopleInOrder, finderType) : PersonBirthdayDifference.Empty;
    }

    private static IPersonBirthdayDifference GetAnswer(
        IEnumerable<IPersonBirthdayDifference> peopleInOrder,
        FinderType finderType)
    {
        IPersonDifferenceComparer comparer;

        switch (finderType)
        {
            case FinderType.LessThan:
                comparer = LessThanComparer.Create();
                break;
            case FinderType.GreaterThan:
                comparer = GreaterThanComparer.Create();
                break;
            default:
                return PersonBirthdayDifference.Empty;
        }

        var answer = peopleInOrder.First();

        foreach (var person in peopleInOrder)
        {
            if (comparer.Compare(person.AgeDifference, answer.AgeDifference))
            {
                answer = person;
            }
        }

        return answer;
    }

    private IEnumerable<IPersonBirthdayDifference> PopulateListInOrder()
    {
        IList<IPersonBirthdayDifference> peopleInOrder = new List<IPersonBirthdayDifference>();

        for (var i = 0; i < this.people.Count - 1; i++)
        {
            for (var j = i + 1; j < this.people.Count; j++)
            {
                var isYounger = this.people[i].BirthDate < this.people[j].BirthDate;
                var youngerPerson = isYounger ? this.people[i] : this.people[j];
                var elderPerson = isYounger ? this.people[j] : this.people[i];

                peopleInOrder.Add(PersonBirthdayDifference.Create(youngerPerson, elderPerson));
            }
        }

        return peopleInOrder;
    }
}


The class could be better named. PlayerSet is not just a set of players: it also knows how to play the game. I would consider calling it PassThePigs since it implements the logic for the game.
Most of your comments are unnecessary. Now, I understand that you're learning to program so you probably find it helpful at this stage to explain each line of code you write. But as you get more experienced, you'll realise that it's not necessary to write comments that merely say the same thing as the code. In cases like this:

return self.currentPlayer.get_name() # return the name of the player

you should find that you can easily read the code:

return self.currentPlayer.get_name()

as meaning "return the name of the current player".

Comments like return the name of the player eventually become a burden rather than a help, because you have to remember to update the comment every time you update the code. For example, it would be all too easy to end up with code like this:

return self.currentPlayer.get_score() # return the name of the player

where the code has been changed and the comment is now wrong.

The best comments explain things that can't easily be figured out by reading the code, for example why you wrote the code in a particular way. Here are a couple of my comments for comparison:

From here:

assert(limit == 10 ** max_digits) # algorithm works for powers of 10 only

And from here:

dt = self.clock.tick(FPS) / 1000.0 # convert to seconds

The Python style guide (PEP 8) suggests that you

  Limit all lines to a maximum of 79 characters [... This] makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.

Also, shorter lines wouldn't disappear off the right hand side of code blocks here on Code Review.

You're not obliged to follow PEP 8, but it makes it easier for you to collaborate with other Python programmers.
There's no need to store the number of players in self.playersCount because you can always get the number of players as len(self.playersList). Storing a fact in two places leads to a risk of inconsistency.
Instead of:

'Player ' + str(i) + ', please enter your name:'

consider:

'Player {}, please enter your name:'.format(i)

Building a string by repeatedly appending to it is an anti-pattern in Python: it takes time that's quadratic in the number of append operations, because each += operation creates a new string. It's nearly always better to use the str.join method. So this code:

string=''
for player in self.playersList:
    string+= player.get_name() + ' has ' + str(player.get_score()) + ' points \n'
return string

is better written:

return ''.join('{} has {} points\n'.format(player.get_name(), player.get_score())
               for player in self.playersList)

Python does not generally need accessor methods like the get_name and get_score in your Player class. Instead of player.get_name(), consider using just player.name. That allows you to write:

return ''.join('{0.name} has {0.score} points\n'.format(player)
               for player in self.playersList)

If the player has exactly 1 point, then this is going to produce ungrammatical output:

Parminder has 1 points

You need something like:

'{0.name} has {0.score} point{1}\n'.format(player, '' if player.score == 1 else 's')

The purpose of the __str__ method is "to compute the “informal” or nicely printable string representation of an object". But you are using it here to format the players' current scores. It would be better to use a method name like format_scores.
The go_to_next_player method seems very complicated. First, you have a loop where you try to find the index of the current player in the list:

index = 0
for i in range(len(self.playersList)):
    if self.playersList[i] == self.currentPlayer:
        index = i

Whenever you find yourself iterating over the indexes of a list, consider using the enumerate function:

index = 0
for i, player in enumerate(self.playersList):
    if player == self.currentPlayer:
        index = i

Second, when you find the player in the list, you set index but you carry on looping. It would be better to break out of the loop as soon as you find what you are looking for:

index = 0
for i, player in enumerate(self.playersList):
    if player == self.currentPlayer:
        index = i
        break

I've shown you how to rewrite the loop, but in fact no loop is needed. Python comes with a built-in method list.index for this operation:

index = self.playersList.index(self.currentPlayer)

Finally, why go to this effect of looking up the current player in the list of players, when you could just remember the index instead of the player? In __init__ you could write:

self.current_player_index = 0

combined with a property:

@property
def currentPlayer(self):
    return self.playersList[self.current_player_index]

and then the go_to_next_player method would be very simple:

self.current_player_index = (self.current_player_index + 1) % len(self.playersList)

A more "advanced" approach would be to use itertools.cycle. In __init__ you'd write:

self.player_cycle = itertools.cycle(self.playersList)
self.currentPlayer = next(self.player_cycle)

and then the go_to_next_player method would become:

self.currentPlayer = next(self.player_cycle)

This code:

if self.currentPlayer.get_score() >= 100:
    return True
else:
    return False

can be simplified to:

return self.currentPlayer.get_score() >= 100

since Boolean expressions like a >= b evaluate to True or False.
Instead of:

while self.is_curr_winner() == False:

you could write:

while not self.is_curr_winner():

but actually this should be

while True:

since the winner detection has already been done (after the player took their turn).
The play_game method returns a string but this is not mentioned in the documentation for the method. (In fact, it's probably a mistake.)
Consider giving a name to the value 100 so that it's clear what it means and so that it's easy to find and change if you need to.
When you have a method that's called from only one place, and is only one line long, consider whether it's worth having a method at all. Adding methods is good because it improves the clarity of the code (you can give the method a name that explains its purpose, and provide documentation), but on the other hand each method increases the length of the code and makes it harder to read.
Once you do this inlining process, it will become clear that there isn't really any persistent state in the game: everything important happens inside PlayerSet.play_game. So is it really worth having a class at all? Compare your implementation with this one:

from itertools import cycle

def pass_the_pigs(self, n, winning_score=100):
    """Play a game of Pass the Pigs with n players."""
    players = [Player(input('Player {}, please enter your name:'.format(i)))
               for i in range(1, n + 1)]
    for player in cycle(players):
        for p in players:
            print('{0.name} has {0.score} point{1}'
                  .format(p, '' if p.score == 1 else 's'))
        for p in players:
            if p.score >= winning_score:
                print('{0.name} has won!'.format(p))
                return
        print("{0.name}, it's your turn".format(player))
        player.play_turn()

(Note that there's almost nothing here that's specific to Pass the Pigs — the same code would work as the main loop for any turn-based game where the players do not interact with each other, and where there's a winning score.)


Transforming a byte array into an array of byte arrays with F#

You should consider whether byte[][] is really the best type to represent a bitmap in F#.

On one hand, arrays are inherently mutable and don't work well with pattern matching, so you might want to consider using list<list<byte>>, especially if performance is not critical.

On the other hand, a rectangular array of bytes is more accurately modeled as byte[,] (2D array), not byte[][] (array of arrays, a.k.a. jagged array). Though again, this is going to be slower than the original option.

for tRowIndex in [ 0 .. tHeight ] do

This has to be tHeight - 1, otherwise your code will fail with an exception.

let mutable tStart = 0
let mutable tFinish = tStart + pArrayWidth - 1        // 0 indexed array

for tRowIndex in [ 0 .. tHeight ] do
    tImageArray.[tRowIndex] <- pArray.[tStart .. tFinish]
    tStart <- tStart + pArrayWidth
    tFinish <- tFinish + pArrayWidth

tImageArray

You can use sequence expressions to create arrays in a functional way. Here, that would look something like:

[|
    for tRowIndex in [ 0 .. tHeight - 1 ] do
        let tStart = tRowIndex * pArrayWidth
        let tFinish = tStart + pArrayWidth - 1
        yield pArray.[tStart .. tFinish]
|]

In both cases, a very similar syntax (for .. in) is used, but my version doesn't use any mutable variables and is very similar to list comprehensions in other functional languages.


Docstring

Is nums really of type List[int]?  Perhaps the first time it is, but after the first step, it is going to turn into a List[float].

Efficiency

Assuming nums is a list of numbers (int or float), you never need to call float() on any of the values.  If you expect a list of 4 strings ("1", through "9") from the contest input, turn them into numbers using int(_) and then pass the List[int] to your judge function.

The test nums[0] == 24 or abs(nums[0] - 24.0) <= 0.1 could be simplified to just abs(nums[0] - 24.0) <= 0.1.

Your doing a lot more work than you think you are.  This code is looping through your list, finding pairs of values:

    for i in range(len(nums)):
        for j in range(len(nums)):
            if i == j:
                continue

For each pair, i & j, you compute all possible combinations of those values, including reverse subtraction and reverse division.

And later, you'll encounter the same pair only as j & i!  And you'll compute all possible combinations of those values a second time.

If your inner loop started at one index after the current outer loop index, then you'd never generate a pair of indices with i > j ... or even i == j, so you can omit that test as well.  Finally, since the inner loop starts at 1 index above the outer loop, the outer loop should end one index early:

    for i in range(len(nums)-1):
        for j in range(i+1, len(nums)):

You could also use enumerate( ) to loop over the values along with their indices at the same time.

    for i, a in enumerate(nums[:-1]):
        for j, b in enumerate(nums[i+1:], i+1):

And then you can refer to a instead of nums[i], and b instead of nums[j], which will prevent repeated indexing into the nums[] array, which will result in decreased performance.

Management of remaining values:

            indexes = set([x for x in range(len(nums))])
            indexes.remove(i)
            indexes.remove(j)
            next_items = [nums[index] for index in indexes]

First set([x for x in range(len(nums))]) could simply be set(range(len(nums))).  There is no need for the list comprehension.

But this is still a lot of extra work.  Simply copy the numbers to a new list, and then delete the i-th & j-th entries.  Since i < j is guaranteed, deleting the j-th element first won't change the location of the i'th element:

            next_items = nums[:]
            del next_items[j]
            del next_items[i]

Or, build up the new list with just the elements you want by omitting the i-th and j-th elements:

            next_items = nums[:i] + nums[i+1:j] + nums[j+1:]

2+2 == 2*2 and 1*1 == 1/1 == reverse_div(1,1).  It is a small optimization, but instead of making a list of all possible operations values, you could make a set() of the values, which would eliminate some redundant recursive steps.

If you don't need this to be a class as a requirement of the leetcode automated judging, you can gain some efficiency by not passing an extra self argument all the time.  This can simply be a function.

Reworked Code

def judge_point_24(nums):

    for i, a in enumerate(nums[:-1]):
        for j, b in enumerate(nums[i+1:], i+1):
            operations = {a+b, a*b, a-b, b-a}
            if a:
                operations.add(b/a)
            if b:
                operations.add(a/b)

            if len(nums) > 2:
                next_items = nums[:i] + nums[i+1:j] + nums[j+1:]
                for x in operations:
                    if judge_point_24(next_items + [x]) == True:
                        return True
            else:
                return any(abs(x-24) < 0.1 for x in operations)

    return False

if __name__ == '__main__':

    def test(expected, nums):
        print(nums, judge_point_24(nums))
        assert judge_point_24(nums) == expected

    test(True, [4, 1, 8, 7])
    test(False, [1, 2, 1, 2])


Docstrings

You should include a docstring at the beginning of every method, class, and module you write. This will allow documentation to identify what your code is supposed to do. It also helps external text editors, such as VSCode, to display what types of parameters your functions accept, and a short description of your method.

Error or Error

This line

except UnicodeDecodeError or ValueError as e:

should be this

except (UnicodeDecodeError, ValueError) as e:

Your current line of code raises this warning from pylint:

  Exception to catch is the result of a binary "or" operation

If you need to handle multiple errors, you should group them into a tuple.

Method Names

According to PEP-8 Function Name Conventions, your method names sendpacket and recivepacket should really be send_packet and receive_packet.

Unnecessary else

This section of code

if rawdata.endswith(sep):
    return rawdata[:-1]
else:
    raise ValueError("Could not find Packet end!")

should be this

if rawdata.endswith(sep):
    return rawdata[:-1]
raise ValueError("Could not find Packet end!")

Since you are returning a value if the condition is satisfied, the ValueError line will not run. And if the condition is not satisfied, it will simply move to the next line. Therefore, the else is unnecessary and should be removed.

Updated Code

"""
Description of this module goes here
"""

import socket

sep: bytes = b'\0'

minpacketsize: int = 10

def send_packet(sock: socket.socket, data: bytes) -> None:
    """

    Description of this method goes here

    :param sock -> socket.socket: Socket to send the data over\n
    :param data -> bytes: Data to send over the socket

    :return: None
    """
    send: bytes = str(len(data) + 1).encode('utf-8') + sep + data + sep

    if len(send) < minpacketsize:
        raise ValueError("Packet too small!")

    sock.sendall(send)

def receive_packet(sock: socket.socket) -> bytes:
    """

    Description of this method goes here

    :param sock -> socket.socket: Socket to receive the data over

    :return: bytes
    """
    datalen = 0
    header: bytearray = bytearray()
    while not datalen:
        header += sock.recv(1)
        if header.endswith(sep):
            try:
                datalen = int(header[:-1].decode('utf-8'))
            except (UnicodeDecodeError, ValueError) as e:
                raise ValueError("Error while decoding header!") from e

        if len(header) == 10:
            raise ValueError("Could not find Header!")

    rawdata: bytes = sock.recv(datalen)

    if rawdata.endswith(sep):
        return rawdata[:-1]
    raise ValueError("Could not find Packet end!")


Here's my take. I removed the $self structure, as it gives you no advantage, and fixed the problem with missing lines.

#! /usr/bin/perl
use warnings;
use strict;

use Data::Dumper;

sub read_in_chunks {
    my %args = @_;
    my $fh = $args{fh} or die "No filehandle given.\n";
    my $size = $args{chunk_size} || 10;
    my @chunk;
    while (@chunk < $size && defined(my $line = <$fh>)) {
        chomp $line;
        push @chunk, $line;
    }
    return @chunk
}

open my $fh, shift or die $!;

my %opts = (
    fh         => $fh,
    chunk_size => 4
);

while (my @chunk = read_in_chunks(%opts)) {
    print Dumper(\@chunk);
    # ...
}


I have a few suggestions. Some high-level and then I'll go through your code.

My first suggestion would be to focus on readability. That means:

good use of spacing
descriptive names for modules, classes, methods, variables, everything
think about the different concepts involved
extract into simple modules, classes and methods
start small
read the documentation (here), particularly string, hash, array

For example, look at a subsection of your code with a little spacing:

class Person
  def input(count)
    puts "Hi, let\'s create three new Person. Start with number #{count}"

    puts "What\'s your name?"
    @name = gets
    @name = @name.delete("\n")

    puts "How old are you?"
    @age = gets
    @age = @age.delete("\n")

    puts "Where are you from?"
    @origin = gets
    @origin = @origin.delete("\n")
  end
end

I would argue you can clearly see the structure of the 3 questions, and all it took was 3 blank lines in the right place.

Next up is proper naming. You look good for the most part. You have @name, @age, @origin.. you have @antwort. From what I understand that is German for answer. Up to you if you want to mix German and English, but be aware of the native language of other people who will be reading your code. I would do the safe thing and use @answer instead.

Avoid redundancy in naming. For example, you have return person_return. Instead, just use return person. Instead of var_person_one just use person_one (note: this is still not descriptive enough, but better).

Now let's have a look at the different concepts involved, turn them into classes.

You have a Person.. but the question and answer format doesn't really suit the person itself. Think about what you could do if you introduced a Question class and an Answer class.

You have name, age and origin as answers to your questions about person, then you build up an array of those instance variables and call that array a person, but those are attributes of the Person class, so add them to it:

class Person
  attr_accessor :age, :name, :origin
end

You also have this concept of a QA session being interacted with through the console. So, you could create a QuestionAnswerSession.

To not complicate things too much you could get quite far by using just a Person and QuestionAnswerSession and forget the separate Question and Answer classes.

The qa session is responsible for outputting questions to the console and listening for answers, then using those answers to create Person objects.

My next suggestion would be to start small. Just introduce a couple of attributes and questions at first and forget about the multiple persons. Try to figure out the overall structure. It will be fewer lines and will be easier to take in and allow to focus on the design.

Let's say we have a Person with a name and age attribute, and we have corresponding questions. From that we want to assign name and age to a Person and, finally, output the Person to the console.

Let's create the person:

class Person
  attr_accessor :name, :age
end

# usage
# Person.new(name: 'Dave', age: 20)
# or
# person = Person.new
# person.name = 'Dave'
# person.age = 20

Now let's build the QA session.

class QuestionAnswerSession
  def start
    puts "Hi, let's create a new Person"

    person = Person.new

    puts "What's your name?"
    person.name = gets.strip

    puts "What's your age?"
    person.age = gets.strip

    puts person
  end
end

qa = QuestionAnswerSession.new
qa.start

Few minor things first. Notice I've removed What\'s which is now simply What's. This is an escape character and is only required if the enclosing quote is the same. Since you are using double quotes you do not need to escape it.

Also note I have replaced @age.delete("\n") with String#strip (docs here). This will remove the newline character for you.

The qa session itself is fairly simple. You instantiate it first, then you call the start method which outputs a question and starts listening for input. It then builds up attributes for a person object and outputs the final result.

I would add one small aspect to this to give you an idea on how to expand the behaviour. Let us say we wanted the person to be able to speak for itself. When we do puts person this is what we get:

#<Person:0x0000000002572518 @name="Dave", @age="20">

Not very nice. If you wanted to output something cleaner, you could add it to the qa session class (puts "Hi, my name is #{person.name}"), but you could also add a simple method to the Person class such as:

class Person
  def introduce_self
    "Hi, my name is #{name} and I'm #{age}"
  end
end

Then in the qa session, instead of puts person you could do puts person.introduce_self.

Extracting different responsibilities into simple, descriptive methods is a great way to keep things manageable, rather than dumping everything into the same method.

Though there are other ways you could improve your code and it could be designed with numerous approaches, I'd urge you to focus on these important aspects first as outlined above, then tackle multiple Person objects later.

Hope that helps! If you have any questions leave a comment.