Instead of assigning your properties null or empty values from the start, just define them with no values. If they aren't initialized, then they will resolve to null. Although, from what I can tell, you aren't doing much checking of these properties anyways, so I don't understand why you had default values anyways. You really should be verifying these properties before you use them.

private
    $conn,
    $stmt,
    $arr,
    $eof=true,
    $error
;

You should always specify the access level of your methods and properties (public, private, protected). You did fairly well with your properties, but then you ignore your methods. Sure, right now PHP defaults to making each of these methods public by default, but this will be deprecated before too much longer. Plan for the future and define them properly. Besides, this is just good coding practice.

Always, always, always use braces on your statement. In languages such as Python, where braces don't exist, this is fine, but in PHP this is wrong. Even though PHP allows this syntax, even they say it is wrong, because it CAN cause issues with the code. Not to mention problems with reading the code. Its two characters,  and doesn't hurt anything to add them, but it could cause all kinds of problems by not adding them. You do this quite a bit, so I wont point out each case.

if(mysqli_connect_errno()) { $this->error = mysqli_connect_error(); }

When you have a lot to say in the comments, don't use single line comments, use block comments. Or better yet, since you seem to be documenting the behavior of a method here, you should be using PHPDoc comments.

/* returns false on error, true on successful select, number of affected rows otherwise
at minimum, query is the sql statement to execute
if there are query parameters, the second argument is is the types list, followed by the parameters
e.g. query('SELECT * FROM table WHERE id = ?', 'i', 5)*/
//OR PHPDoc Comments
/** Queries database
  *
  * The second argument is is the types list, followed by the parameters
  *
  * e.g. query('SELECT * FROM table WHERE id = ?', 'i', 5)
  *
  * @param string $query At minimum, query is the sql statement to execute if there are query parameters
  *
  * @return mixed false on error, true on successful select, number of affected rows otherwise
  */

You lied to us in the documentation and promised us a third and, at the very least, fourth parameter in your query() method. But they are no where in sight. I do see that you have decided to use func_get_args() in there, but that's a big no-no (at least for something so simple). If you want to pass an unspecified number of parameters, do so as an array. That's all you are really getting  with func_get_args() anyways. Either way, your documentation should properly reflect your code, otherwise it is useless. Besides the parameter issue, there is something fundamentally wrong with your query() method. It is entirely too busy. Two very common principles that are always associated with OOP are the "Single Responsibility" (SR) Principle and the "Don't Repeat Yourself" (DRY) Principle, the first isn't normally shortened to that acronym, but I will do so in this answer to avoid repeating myself. These two principles go hand in hand, and you have potentially violated both of them.

SR tells me that this method should only be focused with querying the database and returning the results, after all, that's what you called it query(). However, you are doing so much more. Such as binding the parameters and executing the statement. I wont explain each deviation to you, because you need to be able to separate your code properly, but those two should help get you started. I'm also not entirely certain, but is it necessary for that array to be assigned values by reference? I didn't feel like following it all the way through to make sure.

You have potentially violated the DRY principle because each of the tasks I listed above, and each of the others I didn't, could potentially be reused in this class. Instead they are hardcoded into the one method and therefore their potential is being wasted.

Here's another DRY violator. If you have two methods performing the same task, either A) get rid of one of them, or B) have one of them point to the other. This way if you ever decided to change which array you were fetching from, you would only have to do so once. This is one of the key benefits of DRY.

function result($field) { return $this->arr[$field]; }
function __get($field) { return $this->result($field); }

Ternary functions, unless nested (which they should never be), don't require parenthesis. So, this could be a stylistic point, but figured I'd let you know.

function count() { return $this->stmt ? $this->stmt->num_rows : 0; }


How to make my save/load to/from file function more canonical?

Converting a list of Ints to a comma separated string

map.forEach {
    out.println("${it.key}:${it.value.toString().replace("[", "").replace("]", "").replace(" ", "")}")
}

This could be refactored as:

map.map { (key, value) ->
    key + ":" + value.joinToString(",") { it.toString() }
}.forEach(out::println)

Loading data into the map

val map = mutableMapOf<String, List<Int>>()
map.put("first", listOf(1, 2, 3))
map.put("second", listOf(4, 5, 6))

This can be rewitten to use mapOf, which increases readability

val map = mutableMapOf(
        "first" to listOf(1, 2, 3),
        "second" to listOf(4, 5, 6)
)

Destructuring declaration for splitting string

val parts = it.split(":")
map.put(parts[0], parts[1].split(",").map { it.toInt() })

Using a destructuring declaration may make the purpose of this code clearer.

val (key, values) = "a".split(":")
map.put(key, values.split(",").map { it.toInt() })


You're off to a great start!  This is reasonably readable, and I'm sure you'll get better with practice.

lenght

Typo.  I make tons of typos myself.  I highly recommend getting an IDE with a spell checker.

string input = ...

This confused me at first.  It has to be a typedef, but what kind of typedef makes sense?  Turns out in <cs50.h>, they typedef char *string;.  This is a little weird to me because char* is a very familiar type -- I instantly know a few things to look for/what operations you can do with that.  string is an unknown entity.  I think char* input = ... is clearer.

float gradeLevel = (0.0588 * (100 * (float) length(input, 'l') / (float) length(input, 'w')) - 0.296 * (100 * (float) length(input, 's') / (float) length(input, 'w'))) - 15.8;

This line is so long!  Breaking it down and simplifying a bit:

float l_over_w = (float) length(input, 'l') / (float) length(input, 'w');
float s_over_w = (float) length(input, 's') / (float) length(input, 'w');
float gradeLevel = (5.88 * l_over_w - 29.6 * s_over_w) - 15.8;

I have no idea where the numbers 5.88, 29.6, and 15.8 came from.
Maybe the div function would help you instead of casting to float?  floats are slow and have a lot of idiosyncrasies... IMO they are best to avoid unless you absolutely MUST use them.
I find the general idea here non-obvious.  How about some comments?
This could be a function float gradeLevel(char* input);

int length(string str, char check)

You've used check to determine what this function should do.  That's generally a bad idea, but if you cannot avoid it, at least assert(false) if check is invalid.  That way you get a runtime error if check is wrong.  As you've written it, you'll silently get the wrong answer if check is wrong.

In this case, it is trivial to do better.  You could have several functions: int letterCount(char* str);, int wordCount(char* str);, and int sentenceCount(char* str);.  This way you get a compiler error if you write the wrong function name (and you can't get check wrong since check doesn't exist).

int letterCount = 0;
int n = strlen(str);
for (int i = 0; i < n; i++) {
    if (isalpha(str[i])) {
        letterCount++;
    }
}
return letterCount;

This is OK, but you go over the string once to compute strlen and once to compute letterCount.  You can do them at the same time:

int letterCount = 0;
for (int i = 0; str[i]; i++) {
    if (isalpha(str[i])) {
        letterCount++;
    }
}
return letterCount;

I think this is also nicer since you don't have an n to worry about.  You could further simplify this to get rid of the index and just have the pointer:

while (str) {
    letterCount += isalpha(*str++);
}

but maybe that's overkill.

N.B. at least you didn't write for (int i = 0; i < strlen(str); i++) which goes over the string once per character!

(str[i] == ' ' || str[i] == '\n' || str[i] == '\t')

How about isspace(str[i])?

(str[i] == '.' || str[i] == '!' || str[i] == '?')

How about ispunct(str[i])?  Not an exact match so be careful.

Here's a list of similar functions available https://linux.die.net/man/3/ispunct.

//print lengths for testing
/* ...

This is totally fine for a personal project, but there are lots of testing frameworks that will always compile your test code but only run it under certain conditions.  Might be worth researching.  Here's a list to get you started https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C.

Do you need to deallocate the string returned by get_string?

Is the number of words equal to the number of spaces?  What about this string with         lots of white-spaces.....  How many sentences are in that string?  I don't know the answer to these questions (maybe the exercise tells you what to compute?), but I think it's interesting to think about.


Performing several hundred raster multiplications

Rasters

Rasters are highly memory intensive in R's already fragile memory space. However, one does not necessarily need to read a raster into memory each time. In fact, it is highly frowned upon to read in a raster in that way as it just eats up so much memory and is computationally intensive.

stack()'s beauty

It's much better to make a stack of rasters as it does not load them into memory, but opens their file location.

library(raster)

A_Files <- list.files(pattern="A.tif") # files A
All_A <- stack(unique(A_Files))

B_Files <- list.files(pattern="B") # files B
All_B <- stack(unique(B_Files))

Notice, all of the elements are now in a "vectorized" form.

overlay() to calculate

From here, we can use overlay() to perform a calculation. Note, since the number of layers is equivalent between (ALL_A) and (ALL_B) we do not need to worry about an element being repeated.

x <- overlay(All_A, All_B, fun=function(x,y) x*y )

Export

The only downside to this approach is you will have to go through a loop to export the answers:

out <- unstack(x)
outputnames <- paste0(seq_along(out), "_result.tif")
for(i in seq_along(out)){ writeRaster(out[[i]], file=outputnames[i]) }

References

For multiplying stacks see:

overlay
calc

For more information on stacks (see bricks as well)

stack
brick


Compare lines in 2 text files with different numbers of fields

Less repetition

You have a lot of repeated code (and unnecessary code).  For example, you manually increment your second reader when you could zip them together.  You perform the same list comprehension on each of them.  You map multiple things onto them after a list comprehension.  You perform a pointless filter that is essentially a copy.  Removing all of this gives us this:

from itertools import izip
import csv
import sys

file1 = sys.argv[1]
file2 = sys.argv[2]

def get_clean_line(line):
    return [entry.strip().lower() for entry in line if entry]

with open(file1) as first_file, open(file2) as second_file:
    first_reader = csv.reader(first_file)
    second_reader = csv.reader(second_file)

    for first_line, second_line in izip(first_reader, second_reader):
        first_list, second_list = get_clean_line(first_line), get_clean_line(second_line)

        if (len(first_list) != len(second_list) or
                sorted(first_list) != sorted(second_list)):
            print('Line {}: different fields: A: {} B: {}'.format(
                first_reader.line_num, first_list, second_list))

You could easily move the sorted call into get_clean_line if you want to, but if you think the lengths will be different more often it might make sense to leave it there so short circuiting avoids too many expensive sorts.

Names

You could use better names - bytes are cheap

file1 and file2 vs f1 and f2, first/second_reader vs a and b, etc.  There are probably even better names, but that would probably depend on your specific domain.


I would follow semantics.

Persons are not Accounts. A person may have multiple accounts. Either you rename Person to Account or you have a separate class "Account" so you have following semantic: Amy  transfers 500 from her Account 638423331 to an Account 747266783 that belongs to John.

Transactions are not bound to Accounts. They are on the level of the system which tries to ensure consistency. Sure you can have a list of transactions in each account the account was participant. But that is semantically redundant (denormalized) and has to be synchronized. So I suggest to introduce a class "Accountingsystem" that holds all transactions that keeps the whole consistent.

So my preferred model:

Accountingsystem knows all Persons, all Accounts and all transactions

An account knows its balance and its owner that must be one of the known Persons.

A Transaction knows the accounts participated and the debit/credit amount.

You can have convinience methods to filter transactions or which accounts belong to a person within the accountingsystem.


Hmm, I think there's two things I'd do:

Put the 'neighbors' loops into their own method.
Potentially, separating the neighbor collection from the actual printing.

(Please note that I've attempted to format this slightly better for SO's display width)

public final class PrintCircumference {

    private PrintCircumference() {
    }

    public static void printCircumference(int[][] matrix) {

        if (matrix == null) {
            throw new NullPointerException("The input matrix cannot be null");
        }

        for (int currentRow = 0,
                 rowCount = matrix.length,
                 columnCount = matrix[0].length; currentRow < rowCount; currentRow++) {
            for (int currentColumn = 0; currentColumn < columnCount; currentColumn++) {
                System.out.println(matrix[currentRow][currentColumn]
                                   + " --> "
                                   + collectNeighbors(matrix, rowCount, columnCount, currentRow, currentColumn));
            }
        }
    }

    private static String collectNeighbors(int[][] matrix, int rowCount, int columnCount, int originCellRow, int originCellColumn) {
        StringBuilder neighbors = new StringBuilder();
        for (int neighborRow = Math.max(0, originCellRow - 1),
                 neighborRowLimit = Math.min(rowCount, originCellRow + 2),
                 neighborColumnLimit = Math.min(columnCount, originCellColumn + 2); neighborRow < neighborRowLimit; neighborRow++) {
            for (int neighborColumn = Math.max(0, originCellColumn - 1); neighborColumn < neighborColumnLimit; neighborColumn++) {
                if (neighborRow != originCellRow || neighborColumn != originCellColumn) {
                    neighbors.append(matrix[neighborRow][neighborColumn]);
                }
            }
        }
        return neighbors.toString();
    }

    public static void main(String[] args) {

        int[][] m = { { 1, 2, 3 },
                      { 4, 5, 6 },
                      { 7, 8, 9 }, };

        printCircumference(m);
    }
}

I've scoped the variables about as tightly as is possible.
Also, the original row and column variables are slightly misnamed - they're the count/limit, whereas most developers are probably expecting them to be the 'current' value.  In addition, while i is fine for a single loop, when you're explicitly looping over columns/rows, please name your variables as such.  Use new methods to let you 'rename variables in context' (something like what I've done with the currentRow -> originCellRow, etc, here).  It's also usually a good idea to put brackets on every loop/condition, in case something more needs to be added at some point in the future.

One word of warning - you're not doing enough error-checking here; fixing that is left as an exercise for the reader (for instance, I was unsure if anything should be printed if the matrix wasn't completely square).


toRoman.h

Is there any reason to expose DecimalToRoman to callers?

char * toRoman(int n)

Nit: it might be preferable to take unsigned rather than int as you cannot really handle negative numbers.

if (n < 1) return NULL;

Seems reasonable.  If you took unsigned, then you would only have to handle 0.  In that case, it might make sense to return "" so you always return a valid string.

On second thought, there's sort of an upper-bound on what you can reasonably write as a roman numeral.  Does it make sense to write two billion in terms of thousands?  If you choose an upper bound, you can make assumptions about the length of your buffer.

const DecimalToRoman numbers[] = {
....

I love that this is written out so clearly.  Nice.

size_t resultLen = 1;

Help a reader out by saying why you init to 1.  IMO it's not obvious until you get to malloc.

int tmp = n;
for (size_t i = 0; i < sizeof numbers / sizeof(DecimalToRoman) && tmp; i++) {
    while(tmp >= numbers[i].decimal) {
        tmp -= numbers[i].decimal;
        resultLen += strlen(numbers[i].roman);
    }
}

How about making this a function?  There's a common pattern:

Type thing = init;
...actually figure out what thing is often with a loop...

// don't change thing anymore!
... use thing ...

This is almost always more clearly written as:

Type const thing = createThing(init);
... use thing ...

But anyway back to this code.

sizeof numbers / sizeof(DecimalToRoman)

How about making this a variable named lenNumbers or something like that?  Super nit: I like that you used parens for the type and not for the expression, but IMO it looks weird with the operator/.  More clear: (sizeof numbers) / sizeof(DecimalToRoman).

if (result == NULL) {
    perror("allocate");
    return NULL;
}

Good.  I admit I usually assert in situations like this since there's not much you can do when you're out of memory (and it rarely happens in the things I do), but this is the party line.

memset(result, '\0', resultLen);

Isn't this overkill?  You're about to overwrite the memory anyway.  Could just set the last character to '\0` (and you might as well do that after you write the answer for cache locality).

        int j = 0;
        while (numbers[r].roman[j])
            result[i++] = numbers[r].roman[j++];

Better option: a for loop.  Best option: strcpy.

You could remove the calls to strlen by storing the length in DecimalToRoman.  The lengths are tiny so this is more a question of simplicity than optimization.

There's a common pattern in C APIs for returning buffers. The idea is you let the user pass in the buffer and you return an error code.  Something like:

int getRomanNumerals(int nInput, char* strOut, int* nLen);

The return value is either success, failure, or "insufficient buffer" (you probably want an enum or a preprocessor #define for this).  In any case, the user passes in a buffer and the buffer's length.  You always set nLen to the number of bytes needed, and you set strOut if you have enough space (maybe you start setting strOut assuming the buffer is long enough, but stop writing if you run out of space and only need to set nLen).

This way the user can do crazy stuff like store the result in a weird place or maybe the user knows they don't have enough memory to store the whole thing etc.


Well, it starts with the name. double_list looks like a list of doubles, not a doubly-linked-list, which would be better named list. Anyway, your code doesn't work as a doubly-linked list, and anyway you have one member too few for that.
But your list isn't a generic list of T, but a specific list of int, so that should be reflected in the name too, leading to list_int. Better to bite the bullet and templatize it.
Use one style for class-names, and use it consistently: Either snake_case like the standard, or UpperCamelCase, but please not a mix.
While you can declare a member and a type at the same time, please desist. It's non-obvious, and mimics the pattern of declaring a tag and a typedef-name at the same time in C and C/C++-combi-headers.
Use C++11 nullptr instead of the obsolete NULL-macro. The latter can result in surprising behavior as it can be a zero constant.
Use consistent indentation. Always indent the same amount, and don't forget to indent / dedent as neccessary.
You can signal an error with the return-value or an exception, depending on whether it is expected. But don't ever try interacting with the user directly from generic library code. It seriously restricts usability.
list_search must return a value on every execution-path. If your compiler didn't complain loudly, you should fix your invocation.
Try to use a for-loop directly instead of simulating it with a while-loop.
I wonder why many of your member-functions drag around the prefix list_ as if they were free C-functions.
list_delete and display leak memory.
You are violating the rule-of-three: Your class manages a resource, except is misses a custom copy-ctor and dtor.
Consider allowing output to a different std::ostream than std::cout. While you are at it, implement the stream-output-operator to conform to the standard stream interface.


There is something wrong with this Method that makes it a bit confusing.

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        if(httpContext.User.Identity.IsAuthenticated) {
            if(string.IsNullOrEmpty(Roles)) {
                return true;
            } else {
                var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);
                var authorizedRoles = Roles.Split(RolesSeparator);

                var common = rolesOfUser.Intersect(authenticatedRoles);

                if(common.Count() == 0) {
                    httpContext.Response.Redirect(
                        string.Format("{0}?{1}={2}", ActiveUnAuthorizedUrl, "requestUrl", httpContext.Request.Url.AbsoluteUri));
                    return false;
                }

                return true;
            }
        } else {
            return false;
        }
    }

first thing that I noticed is that the authorizedRoles variable isn't being used, then I saw that you use a variable that isn't declared or initialized anywhere in your code, authenticatedRoles, I am assuming that these are supposed to be the same variable when I removed the common variable like this

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        if(httpContext.User.Identity.IsAuthenticated) {
            if(string.IsNullOrEmpty(Roles)) {
                return true;
            } else {
                var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);
                var authorizedRoles = Roles.Split(RolesSeparator);

                if((rolesOfUser.Intersect(authorizedRoles)).Count == 0) {
                    httpContext.Response.Redirect(
                        string.Format("{0}?{1}={2}", ActiveUnAuthorizedUrl, "requestUrl", httpContext.Request.Url.AbsoluteUri));
                    return false;
                }
                return true;
            }
        } else {
            return false;
        }
    }

I removed some of the else statements that were making this code a little cluttered as well, I was tempted to remove some of these return statements and replace it with a single bool and then just return at the end of the method, but I think that would have made this code messier and harder to read, so this is what I came up with, and it should do the same thing as your code assuming that those two variables I mentioned earlier are the same variable.

protected override bool AuthorizeCore(HttpContextBase httpContext) {
    if(httpContext.User.Identity.IsAuthenticated) {
        if(string.IsNullOrEmpty(Roles)) {
            return true;
        }
        var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);
        var authorizedRoles = Roles.Split(RolesSeparator);

        if((rolesOfUser.Intersect(authorizedRoles)).Count == 0) {
            httpContext.Response.Redirect(
                string.Format("{0}?{1}={2}", ActiveUnAuthorizedUrl, "requestUrl", httpContext.Request.Url.AbsoluteUri));
            return false;
        }
        return true;
    }
    return false;
}


Recursion to map phone number to strings

Here are some comments from my side:

The end parameter is unnecessary. You can just test for start >= letters.length instead. Also, you might want to rename start.
It might make sense to wrap your algorithm in a callable method such as private void printSequences(String[] letters), which just kicks off the recursion by calling printSequences(letters, 0, "").
As to your bug, it depends on how exactly you are calling the method above (what is start and end).
Your test for letters[start] == null does not seems necessary if the letters array is well-behaved (i.e., does not contain null).
Recursion is a decent way to solve this problem.
Your bug comes from the fact that when you process "-" as a digit, you generate null in letters. When processing letters, you don't call your function recursively but just return. That way, nothing is ever printed, which explains the behavior you describe. The proper way to handle that case would be to call the method recursively without appending anything to the prefix (or to make sure there are no null entries in letters, which I believe is the better way, see point 7).
I would use a List<String> for letters. That way you don't end up with null entries.
Your IllegalArgumentException should describe the problem. For instance, it could say "Got illegal phoneNumber".
Your digits map should map characters to strings, not strings to strings. That way you don't have to coerce the character into string with phoneNumber.charAt(i) + "".


Your code has a few different responsibilities, most of which are currently in the search function:

Setting up the GUI
Retrieving the weather report
Parsing the relevant data out of that report
Displaying the result

Each of these deserves their own function. I would also abstract the format itself away into a constant of the class. This allows looping over the different keys to build the objects instead of having to do it manually. I used a collections.OrderedDict to preserve the order of them.

These template strings are:

class WeatherInfo(tk.Tk):
    templates = OrderedDict([
        ('temp', 'Temperature: {temp:.1f} C'),
        ('humid', 'Humidity: {humid}%'),
        ('status', 'Status: {status}'),
        ('sunrise', 'Sunrise at {sunrise:%H:%M:%S}'),
        ('sunset', 'Sunset at {sunset:%H:%M:%S}'),
        ('day_length', 'Day length: {day_length:.1f} h'),
        ('night_length', 'Night length: {night_length:.1f} h')])

Note that you can already define the format for the date in there and also the rounding for floats.

This allows doing this in __init__:

def __init__(self):
    ...
    self.tk_info = {key: tk.StringVar(
        self, value='') for key in WeatherInfo.templates}
    ...
    self.labels = []
    for key in WeatherInfo.templates:
        self.labels.append(
            tk.Label(self.output, textvariable=self.tk_info[key]).pack())
    ...

search should just be concerned with getting the result from the web, catching an error if needed. Here you should notice that you should never have a bare except. It will also catch e.g. the user pressing CTRL-C to abort the program. Always use at least except Exception which will catch almost everything (and not some special exceptions like CTRL-C). Here you can be more specific, because the code will throw a AttributeError if unsuccessful:

def search(self):
    obs = self.owm.weather_at_place(self.kw.get())
    try:
        return json.loads(obs.get_weather().to_JSON())
    except AttributeError:
        self.tk_info['temp'].set('Pick a city to display weather.')

Note that I am using the json format here, just because I think it is more intuitive to work with. But you can also use the get_* functions in parse.

Speaking of which: I would add a parse function that takes the result of obs.get_weather and does all the conversions/calculations. It returns a dictionary with the raw values we want to put in the template:

def parse(self, w):
    parsed_weather = {'temp': round(w['temperature']['temp'] - 273.15, 0),
                      'humid': w['humidity'],
                      'status': w['status'],
                      'sunrise': datetime.fromtimestamp(w['sunrise_time']),
                      'sunset': datetime.fromtimestamp(w['sunset_time']),
                      'day_length': round((w['sunset_time'] - w['sunrise_time']) / 3600, 1),
                      'night_length': round(24 - (w['sunset_time'] - w['sunrise_time']) / 3600, 1)}
    return parsed_weather

I also used from datetime import datetime in the header to get rid of one level of redundant naming.

Then I would define a update function, which updates all the labels to the correct wording. Here it comes in handy that we already have the template strings defined and have a dictionary of the values we want to put in there!

def update(self, report):
    for key, template in WeatherInfo.templates.items():
        self.tk_info[key].set(template.format(**report))

The whole thing comes together in the main function (for lack of a better word):

def main(self):
    report = self.search()
    if report:
        self.update(self.parse(report))

Of course, this main function has to be linked to the Go button instead of search now.

Finally, I would guard the execution of the app with a if __name__ == "__main__" clause to allow importing of your module without executing it.

Final code:

import tkinter as tk
import pyowm
import time
import json
from datetime import datetime
from collections import OrderedDict

class WeatherInfo(tk.Tk):
    templates = OrderedDict([
        ('temp', 'Temperature: {temp:.1f} C'),
        ('humid', 'Humidity: {humid}%'),
        ('status', 'Status: {status}'),
        ('sunrise', 'Sunrise at {sunrise:%H:%M:%S}'),
        ('sunset', 'Sunset at {sunset:%H:%M:%S}'),
        ('day_length', 'Day length: {day_length:.1f} h'),
        ('night_length', 'Night length: {night_length:.1f} h')])

    def __init__(self):
        tk.Tk.__init__(self)
        self.wm_title('Weather')
        self.tk_info = {key: tk.StringVar(
            self, value='') for key in WeatherInfo.templates}

        self.ask = tk.LabelFrame(self, text='Location')
        self.ask.pack(fill='both', expand='yes')
        self.kw_label = tk.Label(self.ask, text='City:')
        self.kw_label.pack(side=tk.LEFT)
        self.kw = tk.Entry(self.ask)
        self.kw.pack(side=tk.LEFT)
        self.rb = tk.Button(self.ask, text='Go', command=self.main)
        self.rb.pack(side=tk.RIGHT)
        self.owm = pyowm.OWM('*CENSORED*')

        self.output = tk.LabelFrame(self, text='Information')
        self.output.pack(fill='both', expand='yes')
        self.labels = []
        for key in WeatherInfo.templates:
            self.labels.append(
                tk.Label(self.output, textvariable=self.tk_info[key]).pack())
        button = tk.Button(master=self, text='Quit', command=self._quit)
        button.pack(side=tk.BOTTOM)

    def search(self):
        obs = self.owm.weather_at_place(self.kw.get())
        try:
            return json.loads(obs.get_weather().to_JSON())
        except AttributeError:
            self.tk_info['temp'].set('Pick a city to display weather.')

    def parse(self, w):
        parsed_weather = {'temp': w['temperature']['temp'] - 273.15,
                          'humid': w['humidity'],
                          'status': w['status'],
                          'sunrise': datetime.fromtimestamp(w['sunrise_time']),
                          'sunset': datetime.fromtimestamp(w['sunset_time']),
                          'day_length': (w['sunset_time'] - w['sunrise_time']) / 3600,
                          'night_length': 24 - (w['sunset_time'] - w['sunrise_time']) / 3600}
        return parsed_weather

    def update(self, report):
        for key, template in WeatherInfo.templates.items():
            self.tk_info[key].set(template.format(**report))

    def main(self):
        report = self.search()
        if report:
            self.update(self.parse(report))

    def _quit(self):
        self.quit()
        self.destroy()

if __name__ == "__main__":
    app = WeatherInfo()
    app.mainloop()


As for your actual algorithm, you need to change it. Filtering down python's generating makes things relatively simple. However, in this case you are going throw away way more items then you keep. As a result, this isn't going to be an efficient method.

What I'd try is iterating over all possible starting positions. For each starting position I'd take the next windowWidth+maximumIntervalSize items. Then I'd use itertools.combinations to grab each possible set of maximumIntervalSize items to remove from the list.

EDIT

Review of new code:

def combinationsWithMaximumCombinedIntervals2(data, combinationWidth, maximumCombinedIntervals):

The python style guide recommends lowercase_with_underscores for function and parameter names. The name are also just a bit on the longish side. (Which is way better then being too short or cryptic)

    windowWidth = combinationWidth + maximumCombinedIntervals

    combinations = []

    for startingIndex in range(len(data)-windowWidth+1):
        for indices in itertools.combinations(range(startingIndex, startingIndex+windowWidth), combinationWidth):

If possible, try to avoid looping over indexes. Code is cleaner if it loops over the data elements.

            if not indices in combinations:

You use if indices not in combinations for a slightly cleaner expression

                yield(tuple(data[j] for j in indices))

You don't need the parenthesis for yield, it is a statement not a function.

                combinations.append(indices)

Combinations would be faster to check if it were a set rather then a list.

But the real question here is how to avoid the duplicates being generated in the first place. We simple restrict the combinations generated to include the startingIndex. This prevents duplicates because no later window can produce the same combinations. (They don't have the startingIndex in them). But it still produces all values because all combinations without the startingIndex will still be contained in the next window. (The next window is the current window except without startingIndex and with an additional value) The only tricky part is the end, when there are no more windows. This is most easily handled by continuing to generate just with a smaller window size for as long as possible.

My solution (tested to make sure it produces the same results as yours, so I don't make any more silly mistakes):

def combinationsWithMaximumCombinedIntervals3(data, combinationWidth, maximumCombinedIntervals):
    windowWidth = combinationWidth + maximumCombinedIntervals

    for startingIndex in range(len(data)-combinationWidth+1):
        window = data[startingIndex + 1: startingIndex + windowWidth]
        for indices in itertools.combinations(window, combinationWidth - 1):
            yield (data[startingIndex],) + indices


Scanning your code I have a few recommendations to make. If you update your question with a demo I'll make a few more.

As I mentioned in comments you have a few obvious issues with globals

var native_btn = element;
native_type = native_btn.attr('type');
//should be
var native_btn = element,
    native_type = native_btn.attr('type');

And similarly for group. I don't understand why you're doing this

function replace_default_action(element) {
        var input = element;
        group = input.attr('name');

Why not:

function replace_default_action(input) {
    var group = input.attr('name'); //on another note I'd prefer groupName over group

Throughout your code you make pretty good use of chaining in places it is clear and concise however there are a few spots I would adapt

Obvious one:

$('body').on('change', '.styled-input', function() {
            replace_default_action($this);
        })
        .on('click', '.label-replacement', function() {
            label_action($this);
        });

You can write this code with toggleClass to remove some lines

    var input_select = $(this);
    if (input_select.is(':checked')) {
        input_select.siblings('.input-replacement').addClass('selected');
    } else {
        input_select.siblings('.input-replacement').removeClass('selected');
    }

    //With toggle class
    var input_select = $(this);
    input_select.siblings('.input-replacement').toggleClass('selected', input_select.is(':checked'));

Also I'm pretty sure you have a logic error here:

.append('
')

Finally in javascript, especially with jQuery code (per their style guide), we prefer camelcasing over underscores for names. I'll point you to this discussion from SO.

Update Here's how I would probably write your code and here's your updated fiddle up and running. As you'll notice I removed all your helper functions that were only called once as there was no need for them and I found them confusing to be honest. I added guiding comments to replace them. I corrected the things mentioned in this review, including function names and condensed ways of writing the original. In the future I think you would benefit from trying to write your functions as straightforward and simple as possible (it took me a while to understand your original code cause of all the helper abstractions)!

$.fn.replaceme = function() {
    'use strict';

    return this.each(function() {

        var $this = $(this);
        var native_type = $this.attr('type');

        //setup button for plugin
        $this.each(function() {
            var $btn = $(this);
            $btn.next('label').addClass('label-replacement');
            $btn.wrap('
');
            $btn.parent('.input-container').append('');
        });

        //check if is live
        $('.styled-input:checked').each(function() {
            $(this).siblings('.input-replacement').addClass('selected');
        });

        //handlers
        $('body').on('change', '.styled-input', function() {//set default action, override if already one exists
            var group = $this.attr('name');
            var $cur = $(this);
            $('input[name="' + group + '"]').each(function() {
                $cur.siblings('.input-replacement').toggleClass('selected', $cur.is(':checked'));
            });
        })
        .on('click', '.label-replacement', function() {
            $this.prevAll('.input-container').children('.styled-input').prop('checked', 'checked').trigger('change');
        });
    });
};


I agree, the temporary tuples are a code smell. They carry a performance overhead, but worse, they obscure the purpose of the code. Here is a way of achieving the goal by working directly on the enumerators.

private static void TripleForEach<TFirst, TSecond, TThird>(
        IEnumerable<TFirst> first,
        IEnumerable<TSecond> second,
        IEnumerable<TThird> third,
        Action<TFirst, TSecond, TThird> action)
{
    using (IEnumerator<TFirst> e1 = first.GetEnumerator())
    using (IEnumerator<TSecond> e2 = second.GetEnumerator())
    using (IEnumerator<TThird> e3 = third.GetEnumerator())
    {
        while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())
        {
            action(e1.Current, e2.Current, e3.Current);
        }
    }
}


Redefine count-leaves as an accumulation

The code doesn't handle the case of only a single leaf, i.e.

 (count-leaves 'leaf)

but I guess that's a side-effect of the original problem formulation. A cleaner solution would be

(define (count-leaves t)
  (if (pair? t)
      (accumulate + 0 (map count-leaves t))
      1)))

also because it's shorter but this doesn't fit the pattern of the original exercise.

Incidentally, in this case the standard Scheme procedure apply would be enough because the Scheme + routine takes in an arbitrary number of arguments, and you could write just:

(define (count-leaves t)
  (if (pair? t)
      (apply + (map count-leaves t))
      1)))


Python methods to reduce running times KTNS algorithm

1. Bug

The code in the post does not compute the correct sequence of tool insertions for the Keep Tool Needed Soonest (KTNS) algorithm.

This is easiest to see if we print out the tools in the machine at each stage, by adding a line like

print(numpy.nonzero(J)[0] + 1)

near the end of the main loop. The first three lines of output are:

[ 1  2  4 10]
[1 4 5 8]
[1 5 6 9]

The third job in the schedule is job 4, which requires tools number 1, 5, and 9. So why did the code insert tool number 6? This is not needed by job 4, and so according to the KTNS algorithm it should not be inserted into the machine. Something has gone wrong.

This bug causes KTNS to return the wrong result for the example: it returns a cost of 17, but the KTNS algorithm only requires 16 tool insertions for this schedule.

2. Argument

I started to write a review of the code in the post, but the major problem is that the wrong data structures have been selected, so I think it will be more helpful to explain how to approach this kind of problem from first principles.

Tang and Denardo (1986) give a mathematical description of KTNS procedure in section 3 of their paper. Mathematical notation is used in scientific papers because of its compactness and lack of ambiguity. But that doesn't mean that it is a good idea to translate the notation directly into source code. Before writing code, you need to solve two problems:

Choosing good names for variables. In the context of a paper, if you don't know what \$L(i, n)\$ is supposed to mean, then you can refer to its formal definition

  \$L(i, n) = \min\left\{m:m∈T(i, n)\right\}\$

or to its informal description:

  the integer \$L(i, n)\$ is the first instant at or after instant \$n\$ at which tool \$i\$ is needed.

But in the context of source code it is not so easy to refer to these definitions, and so naming a variable Lin is only helpful to the reader who is following along with a copy of the paper. It is better to choose variable names that directly communicate the meaning, and to add comments (if necessary) to make that meaning unambiguous, for example:

# Mapping from tool to the next instant at which it will be needed.
next_needed = { ... }

Choosing data structures. The mathematical notation \$L(i, n)\$ doesn't give any clues as to how this should be implemented. Should you precompute a table of values for all tools \$i\$ and instants \$n\$? Or should you store for each tool the instants where that tool is needed in a sorted list and use bisection to find the first instant at or after \$n\$? Or should you store for each tool the instants where that tool is needed in a sorted queue, and pop its queue when a tool is used, so that the first element of queue is always the next instant when the tool will be needed? Or what? The choice of data structure is vital both in getting the most efficient implementation and in making the code simple and clear to the reader.

3. Decode

The key to finding the best data structures is to have a high level understanding of the algorithm, so that you are not trapped by the notation. The idea is to read the mathematics and decode it into concepts that you can work with. So when the paper says "Set \$J_i = 1\$" you figure out that this means "Insert tool \$i\$ into the machine".

This is the procedure:

  Step 1. Set \$J_i = 1\$ for \$C\$ values of \$i\$ having minimal values of \$L(i, 0)\$. Break the ties arbitrarily. Set \$J_i = 0\$ for the remaining \$M - C\$ values of \$i\$. Set \$n = 1\$.

  Step 2. Set \$W_n = J\$. Stop if \$n = N\$.

  Step 3. If each \$i\$ having \$L(i, n) = n\$ also has \$J_i = 1\$, set \$n = n + 1\$ and go to Step 2.

  Step 4. Pick \$i\$ having \$L(i, n) = n\$ and \$J_i = 0\$. Set \$J_i = 1\$.

  Step 5. Set \$J_k = 0\$ for a \$k\$ that maximizes \$L(p, n)\$ over \$\{p: J_p = 1\}\$. Go to Step 3.

Here are my thoughts as I read the procedure:

Steps 2 to step 5 are a loop over \$n\$.
\$n\$ represents the current instant (job) in the schedule.
\$n\$ starts at 1 (the first job) and goes up to \$N\$ (the last job). When implementing this in code, we will need to change this so that instants run from 0 up to (but not including) \$N\$, to avoid having to subtract 1 all the time.
Step 1 is initialization: we fill the machine with the tools that will needed the soonest.
In step 2, \$W_n = J\$ is just recording the set of tools that are now in the machine, which we don't care about since we are only going to be computing the cost.
Step 3 is asking "does the machine contain every tool that is needed by the current job?" If so, it can go on to the next job.
Step 4 only gets run if the machine lacks some tools that are needed. So we pick one of them, tool \$i\$, and insert it into the machine.
Step 5 picks a tool in the machine that is not currently needed and removes it from the machine. The tool is the one that won't be needed for the longest.

4. Pseudo-code

Now that you have a good high-level understanding of the algorithm, the next step is to describe it in pseudo-code. Something like this:

While the machine is under capacity:

Insert the tool that is needed soonest.

For each job in the schedule:

For each tool needed by the job:

Insert the tool into the machine.

While the machine is over capacity:

Remove the tool that won't be needed for the longest.

5. Data structures

Now examine the pseudo-code and figure out the data structures that are needed.

During initialization (but not afterwards), we need to be able to find the tool that is needed soonest.
We need to store the collection of tools that are currently in the machine.
We need to be able to find the size of this collection, so that we can determine whether the machine is over or under capacity.
This collection needs to support efficient insertion and deletion.
We need to be able to efficiently find the tool in the machine that won't be needed for the longest.

Point 1 is easy enough: for each tool, we can find the jobs that require that tool, and so find the first job for each tool, and use heapq.nsmallest to pick the tools we want.

But points 2 to 5 are hard to satisfy. Here are three alternative implementation strategies:

The requirement to repeatedly and efficiently extract the minimum or maximum element (point 5) suggests some kind of priority queue. In the Python standard library the closest thing we have to a priority queue is a heap and heaps don't support efficient deletion. However, there is a workaround for deleting items from heaps, namely to leave the item in the heap but mark it as deleted, and ignore deleted items when they are extracted. But in order to satisfy point 3 we would need to ignore the deleted items so we would need to maintain a separate count.
Use a data structure from a third-party library. It looks as if a SortedSet from the sortedcontainers library would meet our requirements.
Use an ordinary data structure like a set, and accept some inefficiency in point 5 by calling max (taking time proportional to the capacity of the machine). When the capacity is small, this is acceptable.

I'm going to use strategy 3 because it's the simplest and because in your example the capacity is 4, which is small enough for the inefficiency not to matter.

6. Implementation

from collections import defaultdict, deque
from heapq import nsmallest

def schedule_cost(schedule, requirements, capacity):
    """Return the cost of the schedule, that is, the number of tool insertions.

    Parameters:
    schedule -- Sequence of jobs.
    requirements -- Mapping from job to iterable of required tools.
    capacity -- Number of tools that the machine can hold at once.

    Jobs and tools may be any hashable objects.

    """
    # Mapping from tool to deque of instants when the tool will be needed.
    tool_instants = defaultdict(deque)
    for i, job in enumerate(schedule):
        assert len(requirements[job]) <= capacity
        for tool in requirements[job]:
            tool_instants[tool].append(i)
    for instants in tool_instants.values():
        instants.append(len(schedule))

    # Point in schedule when tool will next be needed.
    def next_needed(tool):
        return tool_instants[tool][0]

    # Set of tools in the machine.
    machine = set(nsmallest(capacity, tool_instants, key=next_needed))

    cost = len(machine)
    for job in schedule:
        # Set of tools that need to be inserted.
        new_tools = {tool for tool in requirements[job] if tool not in machine}
        if new_tools:
            cost += len(new_tools)
            # Remove tools if necessary to avoid going over capacity.
            for _ in range(len(machine) + len(new_tools) - capacity):
                machine.remove(max(machine, key=next_needed))
            machine.update(new_tools)
        for tool in requirements[job]:
            tool_instants[tool].popleft()

    return cost

7. Performance

The revised code in §6 is about 20 times faster than the code in the post:

>>> test = lambda:schedule_cost([10, 9, 4, 1, 6, 3, 7, 5, 2, 8], J, 4)
>>> from timeit import timeit
>>> KTNS()[1] / timeit(test, number=1)
20.335097001763668

8. Tool decisions

If you also want to return the decisions about which tools to insert (in addition to the cost), then that's easy. The newly inserted tools at each instant are in the new_tools set, and the tools in the machine at each instant are in the machine set. Take a copy of whichever one of these you need to keep.

For example, if you want to keep copies of machine then you would start with something like:

machine_record = []

and then at the end of each loop, append a copy of machine to the record:

machine_record.append(set(machine))

and findally return the record along with the cost:

return cost, machine_record


I don't have time to do a thorough review, but here are some comments based on a casual reading.

In read_file_contents, the function returns None if the file doesn’t exist. I’d suggest modifying this to print or return an explicit message to that effect, to make debugging easier later. For example, something like:

def read_file_contents(path):
    try:
        with open(path) as infile:
            return infile.read().strip()
    except FileNotFoundError:
        print "Couldn't find the token file!"
        return None

will make your life easier later.

Also, is this meant to be open(path, 'r')?
New-style classes should inherit from object: that is, use

class ApiClient(object):

instead of

class ApiClient():

Don't copy and paste the API URL throughout your code. Make it a variable, and then pass api_url as an input to ApiClient(). That way, you can reuse this code for other APIs, or make changes to the URL in a single place. (If, for example, the API changes.)
Don't hard code username, email and password in the login function. It makes it harder to change them later, and it's a security risk. Consider using something like the keyring module for storing sensitive information. (Should the token be stored securely as well?)
The __init__ function uses the token, and also retrieves it from the file. This can cause problems if you later get the token from somewhere else. (For example, if you used keyring.) Instead, consider passing token as an argument to __init__, and having the code to obtain the token somewhere else. Something like:

def __init__(self, api_url, token=None):
    self.api_url = api_url
    self.token = token

    if self.token is not None:
        # if you get a token
    else:
        # if you don't

and then later:

if __name__ == '__main__':
    api_token = read_file_contents('token')
    api_url = 'http://10.0.1.194:1234'
    api = ApiClient(api_token, api_url)
    print api.test_auth()


Without really understanding what you're attempting to do (and sorry, not enough time to dig into the subject matter), I've rewritten you code a little and profiled it.
The biggest bottleneck I see have to do with the panda/numpy definitions, there is a lot of code querying what your data structure is to determine how to handle it. Perhaps review all your cells in the data frame and ensure they're defined correctly?

Full image (but I'm pretty sure it's not helpful): https://i.imgur.com/nSiOrqu.png

A lot of those hints come from the exceptions which are raised - something you could have found easily if you didn't disable them with continue. More on that later.

Onto the code. Firstly was the imports, make sure you have them defined - when I loaded up your code I had a missing import, and that could have been either your paste (missing) or settings on your computer.

import pandas as pd
import statsmodels.api as sm
import itertools

Next is you're missing the entry point for your python code, always have this as it performs several things. First, it lets people reading your code understand where it begins and ends, secondly if you use tools like an auto-documentor, they load your code to perform reflection on all the objects.
Currently your code would just execute immediately on loading (that's loading, not executing), and that's not good - think of it like your car taking off in gear as soon as you turn the engine on.

if __name__ == "__main__":

Is your standard entry point for python code. Next, we have data initialisations at the top of the code - again, they should be after the entry point, or better yet, external (like an .ini file) and imported at runtime. The code comes out to:

if __name__ == "__main__":
    data = [['01-01-2018', 150, 661, 396, 286, 786], ['01-02-2018', 231, 341, 57, 768, 941],
            ['01-03-2018', 486, 526, 442, 628, 621],
            ['01-04-2018', 279, 336, 140, 705, 184], ['01-05-2018', 304, 137, 800, 94, 369],
            ['01-06-2018', 919, 340, 372, 494, 117],
            ['01-07-2018', 947, 920, 848, 716, 719], ['01-08-2018', 423, 20, 313, 368, 909],
            ['01-09-2018', 422, 678, 656, 604, 674],
            ['01-10-2018', 422, 678, 656, 604, 674], ['01-11-2018', 337, 501, 743, 606, 991],
            ['01-12-2018', 408, 536, 669, 903, 463]]
    df = pd.DataFrame(data, columns=['date', 'A', 'B', 'C', 'D', 'E'])
    result = param(df)
    print(result)

When looking at the function def param(data_param):, the first thing that my IDE highlighted was mod_score_param was used inside a loop on a conditional path - but never initialised outside the loop.
When you write code, you need to be aware of what scope your variables have. Usually variables used inside loops are discarded at the end of the loop. This changes the start of def param(data_param): slightly to:

    seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(
        itertools.product(p, d, q))]  # Generate all different combinations of seasonal p, q and q triplets

    mod_score_param = pd.DataFrame({
        'id': w,
        'param': x,
        'param_seasonal': y,
        'results_aic': z,
    })

    for i in data_param:

The next modification I did was to extract the call to the stats package into it's own function, this is because we try to adhere to the Single Responsibility Principle (from S.O.L.I.D) where each function should only perform a single action - it makes it much easier to track down bugs, and we usually only change a single line of code when fixing problems (great when our single change doesn't work - we don't need to debug 10 new lines of code to find out what went wrong on top of the original bug).
Much easier in the long-run (and the code looks very clean). Here is the function:

def model_params(data_param, i, param, param_seasonal):
    results = sm.tsa.statespace.SARIMAX(data_param[i],
                                        order=param,
                                        seasonal_order=param_seasonal,
                                        enforce_stationarity=False,
                                        enforce_invertibility=False).fit()
    return results.aic

So the caller becomes:

            try:
                results = model_params(data_param, i, param, param_seasonal)
                w.append(i)
                x.append(param)
                y.append(param_seasonal)
                z.append(results)

The exception was modified slightly too:

            except Exception as e:
                print("Exception reached: ", e)
                continue

So we can see immediately what is broken and needs fixing. It's important with any coding - you should never let your exceptions be silenced, because it will lead to bigger problems in the future.
If they are known, catch them with the appropriate exception handler, such as ZeroDivisionError or TypeError, and handle them at the time of the exception.
If they don't match any existing error type, create a custom error handler and handle that particular error before continuing on.

That wraps up my code review and attempt to help you find the slow down in your code. Please apply these changes and see if the modifications to your data frame definitions (such as defining the frequency of the date strings - that's one of the warnings I saw) make the intended improvements.
Good Luck!


Changing all comments' size in range to autosize

as I research more and tried different ways, I have found that I can use the application.screenupdating way to make my whole program run faster and since this question have been unanswered for quite awhile, I will mark this as my answer once a week has past since I asked this question. however I will still be checking to see if there is any better answers posted here till then. Thank you all!

Sub AutoSizeComments()
    Dim c as range, ws as worksheet

    Application.ScreenUpdating = False
    Set ws = ActiveSheet
    'Loop through each comment on worksheet
    For Each c In ws.Cells.SpecialCells(xlCellTypeComments)
        c.Comment.Shape.TextFrame.AutoSize = True
    Next c
    Application.ScreenUpdating = True
End Sub


I won't cover any bugs in your implementation, I'll only have a look at your coding style. It looks like you were writing plain c but tagged it as c++. I think I didn't even found a single c++-only feature you made usage of.

Don't use a string as data storage unless it's necessary

And of course, don't use plain c-style strings, because you'll do it wrong.

char address[][32] = { { "192.168.14.101" },{ "192.168.14.102" },
                 {"192.168.14.103" },{ "192.168.14.106 "} };

You reserve 32 chars for your ip-address storage, but that isn't ever necessary. If you really want to store them as a string, do it as std::string, or if it's a constant string, as std::string_view(C++17). An ip-address has a upper maximum of 4 * 3 signs + 3 dot signs and additionally the zero at the end (that accumulates to a max of 16 signs). So, that means you reserved twice as much memory as you really ever need.

Use better data type

Why don't you simply store the ip-address as an 32bit uint; or as an std::array<std::unit8_t, 4>. You could easily create a typedef for that:
using ipv4 = std::array<std::unit8_t, 4>
With that typedef you'll be able to use that type everywhere you need the ipv4 address. That makes the code more readable and less error prone.

rethink your return statements

That looks really horrible.

bool get_name(unsigned char* name, char dest[32])
{
  // ...
  if (info != NULL)
  {
    // ...
  }
  else
  {
    return false;
  }
  return true;
}

You could write that in an easier way:

bool get_name(unsigned char* name, char dest[32])
{
  // ...
  if (info != NULL)
  {
    // ...
    return true;
  }
  return false;
}

use std::optional if you expect your function return a invalid return value

In C++17 we got a new helper template class called std::optional. It's very helpfull in returning values with an invalid state. You could adjust your get_name function like this:

std::optional<std::string> get_name(ipv4 ip)
{
  // ...
  if (info != NULL)
  {
    return info.name; // pseudo-code; don't know the real interface of this info object, but hopefully you get what I try to explain
  }
  return std::nullopt;
}

That will make your code more reable and self-descriptive. All of the above is also true for your get_mac function.

c-style cast are bad

You used them alot; don't do that. In c++ there are plenty of cast you should use instead. For example (int)mac_address_len should be written as static_cast<int>(mac_address_len)


Extract your preferences code into extra class or create extension functions to get those objects. Ex. sharedPreferences.loadObject(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName,Objective::class.java) should have it's own method. Ex. loadUserByName.
You are using kotlin, use it's strengths like non-nullables by default. Does repository.updateUserName() really accept nullables? That seems wrong. I'd use it for example with elvis operator loadUserByName(user.username) ?: error("username not found")


Fast regex to extract strings before and after a time

Regex 2 is faster, but probably not for the reason that you expect.

You can easily answer questions like these by writing a benchmark.  Here is an example:

public static long splitTime(String regex, String text) {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000; i++) {
        String[] split = text.split(regex);
    }
    long end = System.currentTimeMillis();
    return end - start;
}

public static void main(String[] args) {
    String regex1 = "([0-9]{2}):([0-9]{2}):([0-9]{2})";
    String regex2 = "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]";
    String s="Text1 10:24:02 Text2";

    // Warm up the loops
    for (int i = 0; i < 2000; i++) {
        splitTime(regex1, s);
        splitTime(regex2, s);
    }

    long time0 = 0, time1 = 0, time2 = 0;
    for (int i = 0; i < 2000; i++) {
        time1 += splitTime(regex1, s);
        time2 += splitTime(regex2, s);
        time2 += splitTime(regex2, s);
        time1 += splitTime(regex1, s);
    }

    System.out.println("Regex 1: " + time1);
    System.out.println("Regex 2: " + time2);
}

The JIT compiler tends to do funny tricks.  For fairness, I've warmed up the loop by executing both of them without timing.  I've also interleaved the calls to splitTime in case the order somehow makes a difference.

I found that Regex 1 is slower than Regex 2 by about 5%.

However, Regex 1 has some capturing parentheses.  If you remove them,

    String regex0 = "[0-9]{2}:[0-9]{2}:[0-9]{2}";

then you get a result that is 16% faster than Regex 2.


Not sure what you are trying to achieve, but you can use numerical values for enum_of_collapsible_numbers and you can generate them like this
$enum_of_collapsible_numbers = range(1, 20);


Classifying image by file extension within a PDF creator

Naturally, you can use a dictionary to map extensions to file types:

"jpg" -> ImageFileType.Jpeg
"jpeg" -> ImageFileType.Jpeg
"bmp" -> ImageFileType.Bmp
"gif" -> ImageFileType.Gif
... and so on

If the key fileExtension exists in the dictionary, you set sourceImage.ImageInfo.ImageFileType to the mapped file type, otherwise simply do nothing.
That will get rid of all the if-else.


I'm not exactly sure of your environment (I'm going to assume you're using Node), and with this assumption, I want to address a few things starting with specific things, then more general:

Specific

You shouldn't be keeping inputText in the global store. This creates lots of store dispatches and updates which are completely unnecessary and costly. Instead, pass the input value once you want to add a todo. This would entail the use of state in TodoApp to control the input so you'd have to change to an ES6 class, but that's favorable to the unnecessary updating of the Redux store.
There's no need to do the two lines:

const numbers = range(todos.length);
const zipped  = zip(numbers, todos);

You can shorten your Array#map callback to this without those two lines:

{
  todos.map(({ text }, index) =>

      {text}
      <button onClick={() => onDelete(index)}>delete</button>

  )
}

General

Organization - Separate your Redux reducers, actions, etc. into different files for organization. I'm not sure if your project is currently in one file or not, but this is general advice. This app may be a minor one, but it's good practice for larger apps to keep things organized. For example, a directory structure I would use in this case looks like this:

src/
├── actions/
│   ├── actions.js
│   └── actionCreators.js
├── reducers/
│   └── todos.js
├── components/
│   └── Todos.js
└── index.js

Where action.js contains all your actions, exported using ES6 modules (which I name accordingly for uniformity):

export const DELETE_TODO = 'DELETE_TODO';
export const ADD_TODO = 'ADD_TODO';

And actionCreators.js contains all the action creators, in other words, returns an action to be dispatched. Right now, you're using object literals left and right, which isn't very consistent. It also doesn't convey a message at a glance. I would use action creators instead, for example, if you're adding a todo:

export const addTodo = text => ({
  type: ADD_TODO,
  text
});

Then you can dispatch the action like so:

dispatch(addTodo('foo'));

Instead of like this everytime:

dispatch({ type: ADD_TODO, text: 'foo' });

This can be applied also to another action creator named deleteTodo. And in this new structure, todos.js would be a separate file for your reducer. This is good practice in preparation for larger apps, where you may have more than one reducer. Finally Todos.js is your actual React component and index.js is where you create the store and call ReactDOM.render.
react-redux - Don't subscribe to state like that -- sure, it works but there's a more canonical pattern to use. That's where the react-redux comes in. Redux doesn't have anything to with React itself, but integrates well with React with the react-redux package. This is because Redux emits updates (via store.subscribe) when you dispatch and action and generate new state, which react-redux can take advantage to readably connect your components to state without having to recall ReactDOM.render every time the store changes. This allows for scaling to larger applications with more components.

So in react-redux there's the connect higher-order component that provides state to a certain child, connecting it to the Redux store. You provide it two arguments: mapStateToProps and mapDispatchToProps. What each does can be found in more detail at the GitHub page, but they essentially take values and the dispatch function from the Redux store and pass them as props to a certain component, the same as what you're doing now, except all in a neat package. But connect has to get the store from somewhere, so react-redux also provides a <Provider> component to pass down the Redux store to ancestors while not having to physically do store.getState(). This will get you this in index.js:

import { Provider } from 'react-redux';
import Todos from './components/Todos.js';
import todos from './reducers/todos.js';

const store = createStore(todos);

ReactDOM.render(
  <Provider store={store}>
    <Todos />
  </Provider>,
  …
);

Then in Todos.js:

class Todos extends React.Component {
  constructor() {
    this.state = {
      inputText: ''
    };
  }

  handleChange(e) {
    this.setState({
      inputText: e.target.value
    });
  }

  render() {
    const { todos, onAdd, onDelete } = this.props;

    return (

TODO!

          {
            todos.map(({ text }, index) => (

                {text}
                <button onClick={() => onDelete(index)}>delete</button>

            )
          }

            <input type="text" value={this.state.inputText} onChange={e => this.handleChange(e)}/>
            <button onClick={() => onAdd(this.state.inputText)}>add</button>

    );
  }
}

const mapStateToProps = ({ todos }) => ({ todos }); //provides this.props.todos
const mapDispatchToProps = dispatch => ({
  onAdd(text) {
    dispatch(addTodo(text)); //import this from ../actions/actionCreators.js
  },
  onDelete(index) {
    dispatch(deleteTodo(index));
  }
});

export default connect(mapStateToProps, mapDispatchToProps)(Todos); //connects component to Redux store

Finally, this will clean up the reducer in todos.js for you:

export default function todos(state = { todos: [] }, action) {
  switch(action.type) {
    case ADD_TODO: //import from ../actions/actions.js
      return {
        todos: state.todos.concat({
          text: action.text
        })
      };
    case DELETE_TODO:
      const filtered = state.todos.filter((e, index) => index !== action.index);
      return {
        todos: filtered
      };
    default:
      return state;
  }
}


Optimizing iteration through linked lists

I haven't tested this solution, but I believe that your code could be simplified by using a reverse_iterator.

upperReferenceSet_.clear();
lowerReferenceSet_.clear();
for (int objective = 0; objective < nObjectives_; ++objective)
{
    const  Real referenceValue = reference_->value(objective);
    const  Real  inserteeValue =  insertee_->value(objective);
    const bool lower = referenceValue >= inserteeValue;
    Iterator it = referencePositions_[objective];
    if (!lower)
    {
        it = std::reverse_iterator<Iterator>(it);
    }
    ReferenceSet& referenceSet = lower ? lowerReferenceSet_:
                                         upperReferenceSet_;

    do
    {
        referenceSet.insert(it->individual());
    } while (it++->value() != inserteeValue);

    lists_[objective].insert(--it, Node(insertee_, inserteeValue));
}


int[] is too strong a requirement. The code does not do any random access. Consider changing an argument from array to stream (this way you may process data not fitting in memory).
The method does two (technically) unrelated jobs: finding the maybe dominant element, and verification that the element is indeed dominant. I recommend splitting it into two methods, for the following reasons:

Each loop does an important job and deserves a name.
If it is guaranteed that the dominant element exists, verification is a waste of time.
If it is guaranteed that the dominant element exists, the requirements can be relaxed even more to an input iterator.

Do not print anything from the algorithm. Let main handle results.


Removing an object which is wrapped in another object from a collection

All you need is a (hash) map for mapping a Clip to its ClipHolder. That way you can remove Clips in constant time. I have added a couple of comments directly in the code snippet:

Line.java:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

class Line {

    private static class Bounds {
        //...
    }

    // Clip is immutable. It is a good idea to override 'hashCode' and 'equals'
    // in order to make sure that we can safely use 'Clip's as keys in a hash
    // map.
    private static class Clip {
        private final String name;

        Clip(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public int hashCode() {
            return name.hashCode();
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Clip)) {
                return false;
            }

            return ((Clip) o).getName().equals(this.getName());
        }

        @Override
        public String toString() {
            return "[Clip: " + name + "]";
        }
    }

    // Keyword 'static' removes an implicit reference to Line from each
    // 'ClipHolder', thus saving some space. Declare your ClipHolder a
    // 'Comparable'.
    private static class ClipHolder implements Comparable<ClipHolder> {
        private final Clip clip;
        private final Bounds bounds;

        ClipHolder(Clip clip, Bounds bounds) {
            this.clip = clip;
            this.bounds = bounds;
        }

        @Override
        public int compareTo(ClipHolder o) {
            return this.getClip().getName().compareTo(o.getClip().getName());
        }

        public Clip getClip() {
            return clip;
        }

        public Bounds getBounds() {
            return bounds;
        }
    }

    // 1: Program to interface, not implementation.
    // 2: Since Java 7, you can use diamond inference "<>".
    private final Set<ClipHolder> associatedClips = new TreeSet<>();
    private final Map<Clip, ClipHolder> map = new HashMap<>();

    public void addClip(Clip clip) {
        Bounds bounds = null; // Compute your bounds.
        ClipHolder holder = new ClipHolder(clip, bounds);
        associatedClips.add(holder);
        // Map a clip to its holder.
        map.put(clip, holder);
    }

    public void removeClip(Clip c) {
        associatedClips.remove(map.get(c));
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[Line: ");

        int i = 0;

        for (ClipHolder ch : associatedClips) {
            sb.append(ch.getClip().toString());

            if (i < associatedClips.size() - 1) {
                sb.append(", ");
                ++i;
            }
        }

        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        Line line = new Line();
        line.addClip(new Clip("A"));
        line.addClip(new Clip("B"));
        line.addClip(new Clip("C"));
        line.addClip(new Clip("D"));
        System.out.println(line);

        line.removeClip(new Clip("B"));
        System.out.println(line);
    }
}


Why not do something like this:

$(document).ready(function() {
     $('.containerClass-filter-expression-that-selects-all-your-chks').click(function() {
       recalculate();
     });
});

function recalculate(){
   $('.some-expression-that-selects-all-your-checkboxes').each(function() {
       if($(this).is('checked')) {
           //add

       } else {
           //substract from total
       }

   });
};


Better way to create objects from strings

In .Net laguages you can easily instatiate any object given only the full name of the class (=namespace+class name).

Here is a runnable example:

using System;
using System.Reflection;

namespace Test
{

    class MsgPrinter
    {
        public MsgPrinter()
        {
            System.Console.WriteLine("Hello!");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            MsgPrinter printer = assembly.CreateInstance("Test.MsgPrinter") as MsgPrinter;
            Console.Read();
        }
    }
}

So in your case it would break down to something like (of course, the names in your parameter file would need to exactly match the class names in your application):

...
string[] parts = currentLine.Split(delimiter);
Vehicle vehicle = Assembly.GetExecutingAssembly().CreateInstance(namespace_name+"."+parts[0]) as Vehicle;
...


Regarding code style, it's better to respect the PEP8 and use Flake8 to check your code.

For instance, replace:

from itertools import product
from enum import Enum
class Direction(Enum): forwards = 1; backwards = 0

by

from itertools import product
from enum import Enum

class Direction(Enum):
    forwards = 1
    backwards = 0

Regarding implementation:

When you raise an exception, always give the reason:

raise ValueError("Invalid conversion direction {0!r}! Only backwards or forwards.".format(direction))

In fact, convert() function could be “protected" because it is not used outside the class. And there is no need to check that the direction value is something else than backwards and forwards.

By convention, you could rename the alive function to is_alive because it is a predicate (it returns a Boolean). This function should be a method of State class because it use state variable.

For the same reason, the game function should also be a method. I don't like its name because we cannot understand that it's a generator. Something like next_state could be better.

At the end you calculate the sum of alive() values which are booleans. I consider this to be a bad practice: it's better to use 0 and 1.


Confirm regex for validating password policy

I find the problem with regular expressions is how hard they are to read, and how quickly they become very complicated.

Instead of using a single regex to check for all your conditions I would define a class for a the password that you can then set a series of simple rules for.

This does use static methods, which is not to everyone's taste.

interface Rule
{

    public function check(string $value): bool;
}

class LengthRule implements Rule
{
    protected $length;

    /**
     * LengthRule constructor.
     *
     * @param $length
     */
    public function __construct($length)
    {
        $this->length = $length;
    }

    public function check(string $value): bool
    {
        return mb_strlen($value) >= 8;
    }
}

class DigitRule implements Rule
{
    public function check(string $value): bool
    {
        return preg_match('/\d/', $value) === 1;
    }
}

class SpecialCharacterRule implements Rule
{
    public function check(string $value): bool
    {
        return preg_match('/[^a-zA-Z\d ]/', $value) === 1;
    }
}

class Password
{
    /** @var Rules[] */
    protected static $rules = [];

    protected $value;

    /**
     * @param string $value
     */
    public function __construct(string $value)
    {
        foreach (static::$rules as $rule) {
            if (false === $rule->check($value)) {
                throw new InvalidArgumentException("The value doesn't" .
                    " match all rules.");
            }
        }

        $this->value = $value;
    }

    /**
     * @param Rule $rule
     */
    public static function registerRule(Rule $rule)
    {
        self::$rules[] = $rule;
    }

}

Password::registerRule(new LengthRule(8));
Password::registerRule(new DigitRule());
Password::registerRule(new SpecialCharacterRule());

new Password('12343.4654j');


Creating a RegExp in JavaScript from user input

The else if block was pretty hard to follow.  I would say that your function has rather weird behaviour (treating the text as flags) if the input has a leading slash but no trailing slash.

Anyway, even if you are not very familiar with JavaScript, surely you are familiar with regular expressions?  Why not just use a regular expression to parse your regular expression?

function regGen(uInput) {
    var regExpParser = new RegExp("^/(.*)/(.*)|(.*)");
    var match = uInput.match(regExpParser);
    return new RegExp(match[1] || match[3], match[2]);
}

Strictly speaking, we should both be more careful about interpreting possible backslashes in the input, but that is rather tricky to do correctly.

I've taken out the alert(); a malformed expression would probably be better handled by the caller.


Just a few thoughts:

Your method (IIUC) is conceptually correct, but has computation complexity O(n!) where n is the dimension of a given matrix. If you need better complexity (polynomial in n), you have to use another solution, such as using PLU decomposition described here.
Be aware that since Haskell lists are essentially linked lists, getting i-th element using (!!) takes O(i). So your code

[r !! j | j <- [0..n-1], j /= i]

has O(n2) complexity. You could express it in O(n) for example using splitAs as

let (left, right) = splitAt i r
 in left ++ (tail right)

The same applies for i <- [0..n-1], let x = (head mat) !! i. You could do something like

(i, x) <- zip [0..] (head mat)

instead.


How do I remove nested if else conditions?

I'm assuming that computer and brand are meant to be function parameters, otherwise any kind of branching would be unnecessary.
Here's something that pretty much does what you want, assuming you just want messages that describe in clear english the quantity and brand of computers, and not necessarily have the exact messages used in your examples:
public static void Message(int quantity, string brand)
{
    Console.WriteLine("You own " + quantity + " " + brand + (quantity !== 1 ? 's' : '');
}

The actual brand and quantities are variables that are inserted into the general message. If you want the message to be longer and use more variables, then you would probably want to create substrings to later be combined, for the sake of readability:
public static void Message(int quantity, string brand)
{
    string brandPlural = brand + (quantity !== 1 ? 's' : '');

    Console.WriteLine("You own " + quantity + " " + brandPlural;
}
```


Functional interface hierarchy in Java 8

Honestly, skiwi, you make things more complicated than they need to be.

Please rename View to Listener to avoid confusion. Because that's really what they are, it's a Listener, not a View. It doesn't by itself provide any UI functionality.

Prefixing your interfaces with On is, although understandable why you are doing it, not something I recommend or have seen been done in other places. You're already suffixing Listener to the name (which is what I would recommend, and what I have seen in lots of other code), no need to prefix the interface with On. The method names can be prefixed with on, as they have been already.

Why are you bringing IntConsumer and Consumer<Card> into your code? In what way does that help you? In my opinion, it doesn't help you at all. It creates more confusion than brings something good. If you want to "transform" an IntConsumer into a CardPlayedListener, use Java 8's method reference style by using something like IntConsumer::accept.

Now, let's see if we can write more or less the same thing of your interface heirarchy but with fewer lines.

public interface HandListener {
    default void onCardAdded(final Card card) {}

    default void onCardPlayed(final int cardIndex) {}

    default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {}

    public static HandListener merge(final HandListener... handViews) {
        return new HandListener() {
            @Override
            public void onCardAdded(final Card card) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardAdded(card));
            }

            @Override
            public void onCardPlayed(final int cardIndex) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardPlayed(cardIndex));
            }

            @Override
            public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardsSwapped(cardIndexOne, cardIndexTwo));
            }
        };
    }

    @FunctionalInterface
    public static interface CardAddedListener extends HandListener {
        @Override
        void onCardAdded(final Card card);
    }

    @FunctionalInterface
    public static interface CardPlayedListener extends HandListener {
        @Override
        void onCardPlayed(final int cardIndex);
    }

    @FunctionalInterface
    public static interface CardsSwappedListener extends HandListener {
        @Override
        void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);
    }
}

This way, you can keep having only HandListeners as listeners in your Hand, no need to split it up into three separate listeners. And if you want to easily create a listener that listens only to cards being swapped, you can easily do so. The trick here is that I'm overriding a default method and removing the implementation, thus making it abstract again. While letting the original HandListener interface have default implementations for all the methods.

Original lines of code: 72
New lines of code: 43
Lines of code reduced by: 40%


Dreza has outlined the correct approach (the same used in IComparable<T>). You can make your class generic, with a type constraint:

public abstract class TraktQuery<TResponse> where TResponse : TraktResponse

And change every occurence of TraktResponse to TResponse:

protected abstract TResponse ParseResponse(string response);

and

public TResponse PerformQuery()
{
    //...
}

Then, your deriving class can be defined as

public class TraktQueryEpisodeSummary : TraktQuery<TraktResponseEpisodeSummary>
{
    //...
    protected override TraktResponseEpisodeSummary ParseResponse(string response)
    {
        //...
    }
    //...
}

Voila, no cast necessary:

TraktResponseEpisodeSummary summary = query.PerformQuery();

Further suggestions:

Use collection and object initializers, for instance in the overridden QueryParameters:

 return new List<string> {_showName, _season.ToString(), _episodeNumber.ToString()};

Or turn them into an IEnumerable<string> and use an iterator block:

protected override IEnumerable<string> QueryParameters
{
    get
    {
        yield return _showName;
        yield return _season.ToString();
        yield return _episodeNumber.ToString();
    }
}

Be careful when concatenating strings to form a URL like this:

string url = baseUrl + QueryUrl + "/" + apiKey + "/" + string.Join("/",QueryParameters);

It might be better to

Use the Uri and/or UriBuilder class
Put the first three parts into an sequence, then call IEnumerable<T>.Concat and finally string.Join
There's probably some even better options.


Javascript: Profile Lookup from freecodecamp

You have very repetitive code. This can be optimized. I'm not sure whether your function name lookUpProfile is the correct one, as you actually look up a property of a Contact and not its whole profile. But if the task is to look up a certain property of a Contact you can simplify the code to this:

function lookUpProfile(firstName, prop) {
    for (let contact of contacts) {
        if (contact.firstName === firstName) {
            return contact[prop];
        }
    }
    return false;
}

How it works

It loops through all contacts:

for (let contact of contacts) {

It tests whether the firstName matches:

if (contact.firstName === firstName) {

In case a match is found it returns the requested property or undefined:

return contact[prop];

In case no match is found it returns false:

return false;

What it returns

This function will have a mixed return value. The code that is calling the function can now deal with the result. It will return one of the following:

false if no Contact with the requested firstName exists
undefined if a Contact matches but the requested property doesn't exists
string|array if a match was found and the property exists

So all those calls will work:

console.log(
    lookUpProfile(),
    lookUpProfile('A'),
    lookUpProfile('Sherlock'),
    lookUpProfile('Sherlock', 'number'),
    lookUpProfile('Kristian', 'likes')
);

The return values are:

false false undefined 0487345643 Array [ "Javascript", "Gaming", "Foxes" ]

What the code doesn't do:

It doesn't check whether there's a choice for Contacts, i.e. if more than one Contact with that name exists. It will always exit at the first match.

jsFiddle Demo

Try before buy

Update "No such property"

Regarding the OP's comment about a different return value, I would suggest keeping the code as is and let other parts worry about a concrete message:

var value = lookUpProfile('Sherlock', 'random');

if ('undefined' === typeof value) {
    console.log('No such property');
};

If your task is to include that text into the function you can replace this line:

return contact[prop];

with:

return 'undefined' === typeof contact[prop] ? 'No such property' : contact[prop];

This is a lot harder to handle, as the string "No such property" could be an actual value of a property.


About your HTML

DOCTYPE

You are missing a DOCTYPE. You probably want to use

<!DOCTYPE html>

title element

The title element is a required element (in the very most cases). It has to be added to the head:

  <title>Register …</title>

alt attribute

The alt attribute is required for img elements.

If you account-logo.png is just decoration, the alt value should be empty:

label elements and placeholder attributes

You shouldn’t use the placeholder attribute to "label" input elements. Add label elements instead.

If you want to use the placeholder attribute, it should show an example of what should be entered, or a description of the expected format. See placeholder definition in HTML 5.1.

Email
<input type="email" maxlength="100" name="email" id="email" placeholder="alice@example.com" class="sign-in-box" required />

Usability: maxlength

Do you really want a max length here?

Because there are certainly names longer than 30/60 chars, and email addresses longer than 100 chars. Those users would have to abbreviate their names or use a different email address.

strong for warnings

You could make use of the strong element for the warnings/errors.

A heading

Your page has no headings. You’ll probably add site-wide stuff (like a header, navigation etc.) that contains headings, but even your form (i.e., this page’s main content) should get a heading.

meta-charset

Not required if you provide it via HTTP headers, but it’s typically a good idea to provide a meta-charset element in the head (as first element), e.g. if you use UTF-8:

  <meta charset="utf-8" />


This LINQ Model Query seems extremely inefficient

As this is EF code, assuming you have all the associations set up correctly, you should be able to write it something like this:

public IEnumerable<Collection> GetCollectionByUid(long uid) {
    var result =
       (from collection in db.UserCollections
        where collection.uid == uid
        orderby collection.CreateDate descending
        select new Collection {
            Name = collection.CollectionName,
            Type = collection.CollectionType.CollectionTypeName,
            Created = collection.CreateDate,
            Count = collection.Figures.Count(),
        }).ToList();
    return result;
}

My only real criticism is the variable names.

Local variables or parameters should not be prefixed with an underscore.  IMHO, it should only be allowed for private instance fields.  So rather than using _collection, it would be better off as collection (though I used result for the name here instead).

Parameter names are very much part of the documentation as well (especially so in C# and .NET in general).  The method is called GetCollectionByUid which suggests you provide a uid.  The parameter name should reflect that.  Call it uid since that's what it is.

Personal preference but I also prefer to write out the full/reasonable-length variable names in queries.  I reserve significantly shortened variable names (i.e., one character variable names) in lambda expressions.


I have notes on style and redundancies, but you should read the Python Style Guide: PEP0008. It has a lot of good info on how to format your code to be clear and readable for yourself and others. I'll miss pointing out some of it's recommendations so do read it too.

You have a lot of unnecessary inline comments. from package import Class makes it pretty clear that you're importing Class from package. Python is designed to be readable so that you don't need to explicitly tell people these things. I'd remove most of them. In particular, with your long if and elif chains it's be better to cut down on repetition. Both by having only one comment at the top, and by putting n=n+1 at the end. Though, you can rewrite that as n+=1, and you should put spaces around operators, makes them easier to read:

for row in data["H2S"]:
    #Assign response based on H2S concentration and do indexing
    if row < 120:
        data['response'].iloc[n] = s[0]
    elif row >= 120 and row < 500:
        data['response'].iloc[n] = s[1]
    elif row >= 500 and row < 1000:
        data['response'].iloc[n] = s[2]
    elif row >= 1000 and row < 1300:
        data['response'].iloc[n] = s[3]
    else:
        data['response'].iloc[n] = s[4]
    n += 1

But actually you could just use enumerate for your for loop instead. It allows you to do the same as what you're using n for, it contains the number iteration you're on. So you can save a line and just do this:

for n, row in enumerate(data["H2S"]):
    #Assign response based on H2S concentration and do indexing
    if row < 120:
        data['response'].iloc[n] = s[0]

    ...

    else:
        data['response'].iloc[n] = s[4]

No need for the n += 1 any more.

You never use len_column except to assign to len_iteration, so just assign directly to len_iteration:

len_iteration = len(new_data.columns) - 1

You shouldn't use the semicolon line separator, it's rarely a good idea and often just looks unPythonic. Anyway, Python lets you assign multiple values at once by comma separating them:

j, i, k = 3000, 0, 0

Having them out of alphabetical order is a bit confusing though. You'd be better giving these meaningful names since their usage isn't simple.

In you're while loop you increment i and j in both conditions, so you should just do that at the end and just run the middle block if your condition is False:

while i < len_iteration:
    if int(colnames[i]) != j:
        for k in range(0, b):
            new_col.iloc[k] = (new_data.iloc[k,i-1]+new_data.iloc[k,i+1])/2
        new_data.insert(i,str(j),new_col)
        colnames = list(new_data)
        len_iteration += 1;
    j += 5
    i += 1

That block could really do with some comments though. Especially this line:

new_col.iloc[k] = (new_data.iloc[k, i - 1] + new_data.iloc[k, i + 1]) / 2

I have no idea what that's doing.

You also use m, n and p for indexing. If you're not going to give them more meaningful names, you can at least re-use i, j and k which are more commonly used for looping over indices.


Overloading operators in PhoneCall class

using namespace std;

This is generally frowned upon, especially at the "global" level like this. Since you don't know what names might be defined inside namespace std, this has the potential to create conflicts with your code.

class PhoneCall {
private:

Although it's harmless, the private: here is redundant--members of a class are private by default.

    string phonenumber;
    double perminuterate;
    double calldurationminutes;

I think I'd rename these to something like:

string phone_number;
double per_minute_rate;
double call_duration_minutes;

If at all possible, I'd use an std::vector instead of a "raw" array, so this:

 PhoneCall a[10];

...would turn into something like:

std::vector<PhoneCall> a(10);

std::endl is drastically overused. I'd generally just use '\n';. endl also flushes the file's buffer, which you rarely want. When you read/write cin and cout, flushes are done automatically between writing and reading anyway.

 cout << "Enter 10 phone numbers, duration in minutes, and the per-minute rates." <<
     endl << "Separate each with a space and then hit enter to complete it." << endl;
 for ( int i= 0; i < 10; ) {
     cin >> a[i];
     int j;
     for ( j= 0; j < i; ++j )
         if ( a[i] == a[j] ) {
             cout << "Duplicate number information ignored. Try again." << endl;
             break;
         }
     if ( j == i ) ++i;
 }

You might want to use std::find to find whether the array already contains an instance of a particular phone number. This could simplify your logic quite a bit.

When you print out your phone call objects:

 for ( int i= 0; i < 10; ++i )
     cout << a[i];

...you traditionally want to only print out the data itself in your operator<<, and leave any final new-line to separate one object from the next to be printed somewhere else (like right here).

 system("pause");

I'd avoid this, and use something like:

std::cout << "Press return to quit."
char ch;
std::cin.get(ch);