Building tree structure based on flat objects - second follow up This is a follow up on this question which is a follow up on this question
This follow up is created, because the class in question contained something, which didn't do what it should do.

Based on the suggestion for the RemoveRootArchiveDefinitions() method of the first follow up I have renamed the name of the return variable to remainingEntries and renamed the method to GetNonRootArchiveDefinitions().

Please review the class in question, if you find anything, which should be changed.

public class ArchiveBuilder
{
    public static IEnumerable<ArchiveTreeEntry> Build(IEnumerable<ArchiveDefinition> archiveDefinitions)
    {
        IEnumerable<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

        if (archiveDefinitions != null && archiveDefinitions.Count() > 0)
        {
            IEnumerable<ArchiveDefinition> localEntries = new List<ArchiveDefinition>(archiveDefinitions);

            rootArchiveTreeEntries = CreateRootEntries(localEntries);
            localEntries = GetNonRootArchiveDefinitions(localEntries);

            foreach (ArchiveTreeEntry rootEntry in rootArchiveTreeEntries)
            {
                HandleEntriesForParent(localEntries, rootEntry);
            }
        }

        return rootArchiveTreeEntries;
    }

    private static IEnumerable<ArchiveTreeEntry> CreateRootEntries(
        IEnumerable<ArchiveDefinition> archiveDefinitions)
    {
        List<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

        rootArchiveTreeEntries.AddRange(
            archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive)
                .Select(d => new ArchiveTreeEntry(d)));

        return rootArchiveTreeEntries;
    }

    private static IEnumerable<ArchiveDefinition> GetNonRootArchiveDefinitions(
        IEnumerable<ArchiveDefinition> archiveDefinitions)
    {
        IEnumerable<ArchiveDefinition> remainingEntries =
                archiveDefinitions.Except(
                archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive));

        return remainingEntries;
    }

    private static void HandleEntriesForParent(
        IEnumerable<ArchiveDefinition> archiveDefinitions,
        ArchiveTreeEntry parent)
    {
        if (archiveDefinitions.Count() > 0)
        {
            IEnumerable<ArchiveDefinition> children = GetChildren(archiveDefinitions, parent.Id);

            AddChildrenToParent(parent, children);

            archiveDefinitions = GetParentlessEntries(archiveDefinitions, parent.Id);

            foreach (ArchiveTreeEntry nextParent in parent.Children)
            {
                HandleEntriesForParent(archiveDefinitions, nextParent);
            }
        }
    }

    private static IEnumerable<ArchiveDefinition> GetChildren(
        IEnumerable<ArchiveDefinition> archiveDefinitions, string parentId)
    {
        return archiveDefinitions.Where(e => e.ParentId == parentId);
    }

    private static void AddChildrenToParent(ArchiveTreeEntry parent,
        IEnumerable<ArchiveDefinition> children)
    {
        parent.AddChildRange(children.Select(x => new ArchiveTreeEntry(x)));
    }

    private static IEnumerable<ArchiveDefinition> GetParentlessEntries(
        IEnumerable<ArchiveDefinition> archiveDefinitions,
        string parentId)
    {
        return archiveDefinitions.Where(e => e.ParentId != parentId);
    }

}

Regarding Any() and Count() as pointed out in the last follow up:

As long as the underlying object is a ICollection or ICollection<T> the Count() method returns the Count property of the underlying object. Which in turn just returns an internal counter of the items contained in the collection.

See: this question and this question

As long as the underlying object is a ICollection or ICollection<T> the Count() method returns the Count property of the underlying object.

That's correct, but since your parameter has type IEnumerable<T>, and the method is public, you have no guarantee that the underlying collection is an ICollection<T>. Even in non-public methods, if you assume the underlying collection is an ICollection<T>, your method signature should reflect that; if you decide to accept the more generic IEnumerable<T>, then you should use Any(). Otherwise you have hidden assumptions throughout your code that the type system cannot help with.

Use of the var keyword would clean things up considerably.

In this code

private static IEnumerable<ArchiveTreeEntry> CreateRootEntries(
    IEnumerable<ArchiveDefinition> archiveDefinitions)
{
    List<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

    rootArchiveTreeEntries.AddRange(
        archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive)
            .Select(d => new ArchiveTreeEntry(d)));

    return rootArchiveTreeEntries;
}

there's no point creating a List<T>, you can just write

private static IEnumerable<ArchiveTreeEntry> CreateRootEntries(
    IEnumerable<ArchiveDefinition> archiveDefinitions)
{
    return archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive)
        .Select(d => new ArchiveTreeEntry(d));
}

Similarly, you can write

private static IEnumerable<ArchiveDefinition> GetNonRootArchiveDefinitions(
    IEnumerable<ArchiveDefinition> archiveDefinitions)
{
    IEnumerable<ArchiveDefinition> remainingEntries =
            archiveDefinitions.Except(
            archiveDefinitions.Where(e => e.TypeOfArchive == ArchiveType.Archive));

    return remainingEntries;
}

as

private static IEnumerable<ArchiveDefinition> GetNonRootArchiveDefinitions(
    IEnumerable<ArchiveDefinition> archiveDefinitions)
{
    return archiveDefinitions.Where(e => e.TypeOfArchive != ArchiveType.Archive);
}


The efficiency and options of my PNG sequence JS class I have built a JavaScript PNG sequence engine that allows for playing, pausing and stopping and a time change event. I am asking for genuine opinions if the code is actually good. Its ONLY for the iDevice range (not for desktop browsers or anything) and here is the code and a link to the gist if you wanted to edit it for examples.

Hope its as good as I think it is!

/**
 * @param slides ~ Array (ARRAY) of image locations
 * @param duration ~ Number - in milliseconds how long to run for
 * @param element ~ jQuery object - The <img> tag to change the src of.
 * @returns void
 *
 * @example
 *  <img src="#" id="sequence" data-loop="true" data-autoplay="true" />
 *  <script>var vid = new PNGSequence(tiffanyCrystal, 4, $('#sequence'));</script>
 */
var PNGSequence = function (slides, duration, element) {
    this.slides = slides;
    this.NSlides = slides.length;
    this.duration = duration;
    this.interval = (this.duration * 1000) / this.NSlides;
    this.element = element;
    this.index = 0;
    this.loop = this.element.data('loop') == true;
    this.autoplay = this.element.data('autoplay') == true;

    var inter;

    this.interGo = function () {
        var self = this;
        return setTimeout(function () {
            // Update the image
            element.attr({
                "src": slides[self.index]
            });

            // Increase the index
            self.index++;

            // Call the onTimeChange event
            if (self.hasOwnProperty('onTimeChange')) {
                if (self.onTimeChange) {
                    self.onTimeChange.call(self, self.index, self.NSlides);
                }
            }

            // Check if its the end of the animation
            if (self.index > self.NSlides) {
                // If we're not looping, clear the interval
                if (!self.loop) {
                    clearTimout(inter);
                } else {
                    // If we're looping then start the loop from the beginning
                    self.index = 0;
                    self.play();
                }
                return;
            }

            //Fire the timeout again
            self.interGo();
        }, this.interval);
    };

    /**
     * Pauses the sequence
     */
    this.pause = function () {
        clearTimout(inter);
        return this.index;
    };

    /**
     * Plays the sequence from last known point
     */
    this.play = function () {
        return inter = this.interGo();
    };

    /**
     * Stops the sequence and sets the pointer
     * at the beginning again
     */
    this.stop = function () {
        clearTimout(inter);
        this.index = 0;
        return 0;
    };

    this.onTimeChange = function () {
        return this;
    };

    if (this.autoplay) {
        inter = this.interGo();
    }

    return this;
};

And here is the link to the gist https://gist.github.com/3360011

I would suggest a few minor changes:

Use setTimeout instead of setInterval to ensure that callbacks don't stack up if they can't be serviced on time.  This implies re-invoking this.interGo at the end of the callback to re-trigger the timer.
Only declare and use self in the functions that need it, to avoid traversing the scope chain unnecessarily.
Remove over-reliance on the Number constructor.


Compute adjacent days from date string I'm trying to do some datetime processing. The input is a string of the form 20141005 ('%Y%m%d') and I want to return a data structure that stores the day before the input date, the day from the input, and the day after along with the day after that in a %y%m%d format (141005)

This is my function right now, and I'm wondering if there's a better way of doing it, whether it's too compact, if I should use different data structures, if my comments are too verbose, if my style is alright - basically any kind of tips and advice are very welcome.

from datetime import datetime, timedelta

def process_dates(date):
    """
    Process adjacent days to account for flights that
    have a different departure day than the day they were
    archived (which is the date contained in the filenames)
    """

    """
    Convert to datetime objects before processing
    This is done so the conversion is less error-prone by
    avoiding edge cases like 1st of Jan, 29th of Feb, y3k, etc
    """
    datetimes = []
    today = datetime.strptime(date, '%Y%m%d')

    """
    Compute the adjacent days, but keeping the order of the elements
    the following: today, yesterday, tomorrow, and the day after tomorrow.
    This is done because the looking up later on is done sequentially
    and the order reflects the probability of being the needed date
    (i.e. it's most probable the needed day is today, so it will stop before
    processing the other days)
    """
    [datetimes.append(today + timedelta(days=i)) for i in [0, -1, 1, 2]]
    return [datetime.strftime(j, '%y%m%d') for j in datetimes]

Yes, the comments are too much. You don't need to explain why you're doing it all; you might not always be using this function for its current purpose. And I wouldn't put general explanatory comments like that inline; put them in the function docstring.

Also, it's not at all Pythonic to do something like:

[datetimes.append(today + timedelta(days=i)) for i in [0, -1, 1, 2]]

filling a list with None then discarding it; either use a list comprehension:

datetimes = [today + timedelta(days=i) for i in [0, -1, 1, 2]]

or append:

 for i in [0, -1, 1, 2]:
     datetimes.append(today + timedelta(days=i))

I would also encapsulate more of the variables in default parameters, to make the function more flexible:

from datetime import datetime, timedelta

def adjacent_dates(date, deltas=[0, -1, 1, 2], format="%Y%m%d"):
    """Generate date strings adjacent to the argument date.

    Note:
      The default order of deltas is to ensure that the most
      likely date is first in the output.

    Args:
      date (str): The date to process.
      deltas (iter of int): The offsets to apply, in days, to the input
        date (defaults to [0, -1, 1, 2]).
      format (str, optional): The format to use for input and output
        (defaults to "%Y%m%d").

    """
    start = datetime.strptime(date, format)
    days = [start + timedelta(days=i) for i in deltas]
    return [d.strftime(format) for d in days]

Now you can use your defaults:

>>> adjacent_dates("20141030")
['20141030', '20141029', '20141031', '20141101']

or easily switch to something else:

>>> adjacent_dates("30-10-2014", range(-2, 3), "%d-%m-%Y")
['28-10-2014', '29-10-2014', '30-10-2014', '31-10-2014', '01-11-2014']

Note that strftime is a datetime instance method, so you can call it on the instances rather than the class - d.strftime(format) is neater than datetime.strftime(d, format).


Finding longest common prefix I have been trying to solve a modification of the Longest Common Prefix problem. It is defined below.

  Defining substring

  For a string P with characters P1, P2,…, Pq, let us denote by P[i, j]
  the substring Pi, Pi+1,…, Pj.

  Defining longest common prefix

  LCP(S1, S2,…, Sk), is defined as largest possible integer j such that
  S1[1, j] = S2[1, j] = … = Sk[1, j].

  You are given an array of N strings, A1, A2 ,…, AN and an integer K.
  Count how many indices (i, j) exist such that 1 ≤ i ≤ j ≤ N and
  LCP(Ai, Ai+1,…, Aj) ≥ K. Print required answer modulo 109+7.

  Note that K does not exceed the length of any of the N strings. K <= min(len(Ai)) for all i

  For example,

  A = ["ab", "ac", "bc"] and K=1.

LCP(A[1, 1]) = LCP(A[2, 2]) = LCP(A[3, 3]) = 2
LCP(A[1, 2]) = LCP("ab", "ac") = 1
LCP(A[1, 3]) = LCP("ab", "ac", "bc") = 0
LCP(A[2, 3]) = LCP("ac", "bc") = 0

  So, the answer is 4. Return your answer % MOD = 1000000007

  Constraints

  1 ≤ Sum of length of all strings ≤ 5*105. Strings consist of small alphabets only.

Here is my approach:

class Solution:
    # @param A : list of strings
    # @param B : integer
    # @return an integer
    def LCPrefix(self, A, B):
        res = 0
        for i in xrange(len(A)):
            prev = A[i]
            prevLCP = len(A[i])
            for j in xrange(i, len(A)):
                prevLCP = self.getLCP(prev, A[j], prevLCP)
                prev = A[j]

                if prevLCP >= B:
                    res += 1

        return res % 1000000007

    def getLCP(self, A, B, upto):
        i = 0
        lim = min(upto, len(B))
        while i < lim:
            if A[i] != B[i]:
                break

            i += 1

        return i

The time complexity of this algorithm is O(n^2*m), where n is the length of the list and m is the maximum length of the string.

The online judge (InterviewBit) does not accept this solution in terms of time complexity. Can anyone think of a way to improve it?

Note: although I hinted in a comment that there's a O(n * K) solution, I'm deliberately not going to give it to you (and I hope that by bumping the question to the front page I don't cause someone else to) because in my opinion the point of challenge websites is for you to learn by doing, and you will learn more effectively by figuring it out yourself with hints than by getting the solution on a plate. However, I do have some comments on your code.

class Solution:
    # @param A : list of strings
    # @param B : integer
    # @return an integer

It's useful to document the expected type, but it's more useful to document the meaning. Here B is the K of the problem specification, but I shouldn't have to work that out myself. The parameters would benefit from descriptive names, and the @return should outline what the integer returned means.

    def LCPrefix(self, A, B):
        res = 0
        for i in xrange(len(A)):
            prev = A[i]
            prevLCP = len(A[i])
            for j in xrange(i, len(A)):
                prevLCP = self.getLCP(prev, A[j], prevLCP)
                prev = A[j]

There's a possible minor optimisation here: when j == i you already know the LCP, but you calculate it again. In my opinion it would be worth duplicating the simple test if prevLCP >= B: res += 1 before the loop, and only considering j > i. As a bonus, you would no longer need to track prev because you would always be testing the common prefix of A[j-1] and A[j]. (Hint: does that give you any ideas for optimisation?)

Why the update to prevLCP? I can figure it out, but a comment (and a better name - because the value of prevLCP isn't the previous LCP) would be useful.

                if prevLCP >= B:
                    res += 1

An else: break clause here would not change the asymptotic complexity of your solution, but it would surely make it much faster in many test cases.

        return res % 1000000007

I'll give you one more hint about improving the complexity: the fact that they want the answer modulo 109 is a really big clue that you shouldn't compute it solely via res += 1.

    def getLCP(self, A, B, upto):

Document the parameters, and think about the names. getLCP implies to me that the return value should be the longest common prefix: i.e. a string. But it's actually an integer, and it might not even be the length of the LCP because of upto.

        i = 0
        lim = min(upto, len(B))
        while i < lim:
            if A[i] != B[i]:
                break

            i += 1

        return i

In the other method you used xrange: why not here?

        lim = min(upto, len(B))
        for i in xrange(lim):
            if A[i] != B[i]:
                return i
        return lim


Circular linked list Please review this:

#include <iostream>
using namespace std;

template <class T>
struct Node
{
  T data;
  Node * next;
  Node(T data) : data(data), next(NULL) {}
};

template <class T>
class CircularLinkedList
{
public:
  CircularLinkedList() : head(NULL) {}
  ~CircularLinkedList();
  void addNode(T data);
  void deleteNode(T data);
  template <class U>
  friend std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll);
private:
  Node<T> * head;
};

template <class T>
CircularLinkedList<T>::~CircularLinkedList()
{
  if (head)
    {
      Node<T> * tmp = head;
      while (tmp->next != head)
        {
          Node<T> * t = tmp;
          tmp = tmp->next;
          delete(t);
        }
      delete tmp;
      head = NULL;
    }
}

template <class T>
void CircularLinkedList<T>::addNode(T data)
{
  Node<T> * t = new Node<T>(data);

  if (head == NULL)
    {
      t->next = t;
      head = t;
      return;
    }

  Node<T> * tmp = head;
  while (tmp->next !=  head)
    {
      tmp = tmp->next;
    }

  tmp->next = t;
  t->next = head;
}

template <class T>
void CircularLinkedList<T>::deleteNode(T data)
{
  Node<T> * tmp = head;
  Node<T> * prev = NULL;
  while (tmp->next !=  head)
    {
      if (tmp->data == data) break;
      prev = tmp;
      tmp = tmp->next;
    }

  if (tmp == head)
    {
      while (tmp->next != head)
        {
          tmp = tmp->next;
        }
      tmp->next = head->next;
      delete head;
      head = tmp->next;
    }
  else
    {
      prev->next = tmp->next;
      delete tmp;
    }
}

template <class U>
std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll)
{
  Node<U> * head = cll.head;
  if (head)
    {
      Node<U> * tmp = head;
      while (tmp->next != head)
        {
          os << tmp->data << " ";
          tmp = tmp->next;
        }
      os << tmp->data;
    }
  return os;
}

int main()
{
  CircularLinkedList<int> cll;

  cll.addNode(1);
  cll.addNode(2);
  cll.addNode(3);
  cll.addNode(4);
  cll.addNode(5);

  cout << cll << endl;

  cll.deleteNode(3);
  cll.deleteNode(1);
  cll.deleteNode(5);

  cout << cll << endl;

  return 0;
}

)

My first comment is you should start looking at smart pointers.
They will definitely simplify your code.

The second comment: look at the STL containers.
Containers in C++ follow a specific pattern. The idea is that we want to use algorithms on containers interchangeably and thus containers follow these conventions to make them easy to use with the standard algorithms.

Third comment: you fail to follow the rule of three.
Basically. If you define one of 'Destructor'/'Copy-Constructor'/'Assignment-Operator' (rather than using the compiler generated defaults) then you probably need to define all three. In this case your code is going to crash if you make a copy of the list. The problem arises from having an owned pointer in your code.

Fourth comment: Prefer to be pass parameters by const reference. For simple objects like integers it will not make any difference. But you have templatised the code and T can be any type. Thus passing by value is going to cause a copy (which may be expensive).

Reviewing the above code:
The complexity of adding a node is O(n). By maintaining a head and a tail pointer you can change this to have a complexity of O(1). ie. this loop becomes unnecessary.

Node<T> * tmp = head;
while (tmp->next !=  head)
{
  tmp = tmp->next;
}

You have an output operator std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll) It would be nice if you had a symmetric input operator. In this situation you need to worry about the size of the list (or adding a special terminating character). So the creation of the input operator will affect your design of the output operator.


Java Console Guess The Number Game I was given a homework assignment to code a console Guess the Number Game, where the user should guess a random number. Also, I had to code a simple menu with switch where I can change a random number origin/bound and attempts amount.

Please, give me some tips how could I improve the code and where I'm wrong.

P.S. I must not use classes / methods etc. Only Control Flow Statements.

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static void main(String[] args) {
        var scanner = new Scanner(System.in);
        var origin = 0;
        var bound = 100;
        var attempts = 10;

        System.out.println("Guess the Number Game!");

        while (true) {
            System.out.println();
            System.out.println("1. Start new game.");
            System.out.println("2. Change origin (" + origin + ").");
            System.out.println("3. Change bound (" + bound + ").");
            System.out.println("4. Change attempts amount (" + attempts + ").");
            System.out.println("5. Quit.");
            System.out.println();

            switch (Integer.parseInt(scanner.nextLine())) {
                case 1:
                    var number = ThreadLocalRandom.current().nextInt(origin, bound);
                    var currentAttempts = attempts;
                    System.out.println("Guess the number between " + origin + " and " + bound + "!");
                    while (currentAttempts > 0) {
                        System.out.println(currentAttempts-- + " attempts left:");
                        var input = Integer.parseInt(scanner.nextLine());
                        if (input == number)
                            break;
                        else
                            System.out.println("The number is " + (input < number ? "greater" : "less") + " than yours.");
                    }
                    if (currentAttempts > 0)
                        System.out.println("You win! Congratulations!");
                    else {
                        System.out.println("You loose! Better luck next time!");
                        System.out.println("The number was " + number);
                    }
                    break;
                case 2:
                    while (true) {
                        System.out.println("Enter new origin:");
                        int newOrigin = Integer.parseInt(scanner.nextLine());
                        if (newOrigin < bound) {
                            origin = newOrigin;
                            break;
                        } else
                            System.out.println("Origin should be less than bound. Try again.");
                    }
                    break;
                case 3:
                    while (true) {
                        System.out.println("Enter new bound:");
                        int newBound = Integer.parseInt(scanner.nextLine());
                        if (newBound > origin) {
                            bound = newBound;
                            break;
                        } else
                            System.out.println("Bound should be greater than origin. Try again.");
                    }
                    break;
                case 4:
                    while (true) {
                        System.out.println("Enter new attempts amount:");
                        int newAttempts = Integer.parseInt(scanner.nextLine());
                        if (newAttempts > 0) {
                            attempts = newAttempts;
                            break;
                        } else
                            System.out.println("Attempts amount should be greater than 0. Try again.");
                    }
                    break;
                case 5:
                    System.out.println("Bye!");
                    return;
            }
        }
    }
}

Because of the 'I must not use classes / methods etc. Only Control Flow Statements' I will try to not give comments to that direction.
Here are some advices

Input checking

Integer.parseInt(scanner.nextLine())

This will crash when someone enters anything but a digit (eg. 'a'). You should add exception handling for this

way to keep things going

while (true)

I would personally go for while(isRunning), as it will allow you to end the loop without the need for the "return" statement in the switch.

usage of var

var number = ThreadLocalRandom.current().nextInt(origin, bound);
int newOrigin = Integer.parseInt(scanner.nextLine());

You are mixing the usage of var and int when reading from the command line (which is technically ok) but I think consistency is also important in code.

default case

There is no default case in the switch. That would for example allow you to handle people entering number 6

changing variables in printing output

System.out.println(currentAttempts-- + " attempts left:")

This gets really tricky when you would use a logging framework and suddenly the user decides to switch of the level of logging.
I would go for System.out.println is to print current values, and to change values before/after (whatever is appropriate)

coding style

if (input == number)
    break;
else
   System.out.println ...

I would advice to always put {}, even if the next line is a simple instruction. This will avoid any human  reading mistakes.

eg.

if (<somecondition>)
    dosomething();
    break;
else
   System.out.println ...


Merging website info into an array I'm scraping a title and a link from a website and placing them in a single array.
The $i variable seems a bit wrong to me, or is it perfectly fine?

$linkQuery = $xpath->query("//div[@class='news-archive']//a/@href");
$titleQuery = $xpath->query("//div[@class='news-archive']//a");

$data = [];

foreach ($linkQuery as $link) {
    $data[] = array('link' => $link->value);
}

$i = 0;
foreach ($titleQuery as $title) {
    $data[$i]['title'] = $title->nodeValue;
    $i++;
}

I do like the structure of the Array:

Array (
    [0] => Array
        (
            [link] => http://www.gpupdate.net/nl/f1-nieuws/321783/force-india-vreest-voor-deelname-aan-laatste-test/
            [title] => Force India vreest voor deelname aan laatste test
        )

I think that one of the collections you iterate already has all the data you need. Try this:

$linkQuery = $xpath->query("//div[@class='news-archive']//a");
foreach ($linkQuery as $link) {
    $data[] = array('link' => $link->getAttribute('href'), 'title' => $link->nodeValue);
}

Btw. array_map() is another way for traversing two (or more) arrays simultaneously:

$group_elements = function($link, $title) {
    return array('link' => $link->value, 'title' => $title->nodeValue);
};
$data = array_map($group_elements, $linkQuery, $titleQuery);


Improvment of and looping in a regular expression pattern My implemented regex pattern contains two repeating symbols: \d{2}\. and
(.*)
. I want to get rid of this repetition and asked myself if there is a way to loop in Python's regular expression implementation.

Note: I do not ask for help to parse a XML file. There are many great tutorials, howtos and libraries. I am looking for means to implement repetition in regex patterns.

My code:

import re

pattern = '''
<menu>
<day>\w{2} (\d{2}\.\d{2})\.</day>
<description>

(.*)

(.*)

(.*)

</description>
'''

my_example_string = '''
<menu>
<day>Mi 03.04.</day>
<description>

Knoblauchcremesuppe

Rindsbraten "Esterhazy" (Gem&uuml;serahmsauce)

mit H&ouml;rnchen und Salat

</description>
</menu>
'''

re.findall(pattern, my_example_string, re.MULTILINE)

Firstly, just for anyone who might read this: DO NOT take this as an excuse to parse your XML with regular expressions. It generally a really really bad idea! In this case the XML is malformed, so its the best we can do.

The regular expressions looping constructs are * and {4} which you already using. But this is python, so you can construct your regular expression using python:

expression = """
<menu>
<day>\w{2} (\d{2}\.\d{2})\.</day>
<description>
"""

for x in xrange(3):
    expression += "<p>(.*)</p>"

expression += """
</description>
</menu>
"""


Python script that does a git diff I have created a small script that aims on comparing two versions of a file by doing a git diff. Is there a better way to code it?

import subprocess

def diff_versions(file_to_be_compared, directory):
    try:
        out = subprocess.check_output(["git", "diff", "origin/master^", "origin/master", file_to_be_compared],
            cwd = directory)
    except subprocess.CalledProcessError as ex:
        return ex.output

    return out is None

def main():
    result = diff_versions('file.txt', "some/directory")
    if result is False:
        raise Exception('diff found between the files')
    else:
        return 'files are identical'

if __name__ == "__main__":
    main()

if result is False:
    raise Exception('diff found between the files')
else:
    return 'files are identical'

Why would a difference be considered Exceptional? Given that nothing else happens in the program, there isn't much difference at this point between raising an error and just printing the message, but it seems like an odd way to do things.

Also, you shouldn't test for False by identity, if not result is the usual method.

Have you considered allowing the user to select branches to compare? You could use the current value as a default, e.g.

 def diff_versions(file_to_be_compared, directory, branch="origin/master"):


Order line reversing (reversing line order) I'm a student learning to code in C. I had to make a program for class to reverse lines of input from the keyboard (not character wise, but reverse the order of the lines input).
The program is working to the requirements of the assignment already, but feel free to have a look at my code and help me understand where I can make improvements to it. I am looking to learn as much as possible about the language.

Assignment:
Program will allow user to type in several lines of a poem. User signals the end of their input with a single dot on a newline (and enter). After input, the lines will be printed out from last entered to first. No line can be greater than 1000 characters in length. No max number of lines. Lines cannot contain a single '.' dot/period as the only character on the line. No use of global variables.

   1 #include <stdio.h>
   2 #include <stdlib.h>
   3 #include <string.h>
   4
   5 int main(){
   6
   7   /* array variables */
   8   int MAXSIZE = 1000;
   9   char **array;
  10   char *string;
  11   char inputStr[MAXSIZE+1];
  12
  13   /* declare for my while loop parameter*/
  14   inputStr[0] = 0;
  15
  16   /* logic variables */
  17   int i = 0;
  18   int j = 0;
  19
  20   /* allocate inital space for a line */
  21   array = malloc(sizeof(char*) * 1);
  22
  23   printf("Enter the poem:\n");
  24
  25   /* if the line is only a period, end loop */
  26   while(*inputStr != '.'){
  27
  28     /* get input from user, max 1000 chars per line */
  29     fgets(inputStr,MAXSIZE,stdin);
  30     inputStr[strlen(inputStr)-1] = '\0';
  31
  32     if(*inputStr != '.'){
  33
  34       /* allocate space to store the string and copy from input */
  35       string = malloc ( sizeof(char) * (strlen(inputStr)+1) );
  36       strncpy ( string, inputStr, strlen(inputStr)+1 );
  37
  38       /* allocate space in the array for the string and copy it in */
  39       array[i] = malloc((sizeof(char*))*(strlen(string))+1);
  40       strncpy(array[i],string,strlen(string)+1);
  41
  42       /* free the string, add to line count, reallocate with new line count */
  43       free (string);
  44       i++;
  45       array = realloc(array, (i + 1) * sizeof(char*));
  46     }
  47   }
  48
  49   /* print the array in reverse order using line count*/
  50   for( j = i-1 ; j >= 0; j-- ){
  51     printf("%s\n", array[j]);
  52   }
  53
  54   /* free the array strings and then the array */
  55   while(i--){
  56     free(array[i]);
  57   }
  58   free(array);
  59
  60   return(0);
  61
  62 }

First I need to mention that I have been learning C coding for some time but would call myself an intermediate beginner at best. So take what I say with the right amount of scepticism.

int MAXSIZE

To define constants like buffer sizes it is better to use const int which make your intention clearer.

Also you should be more consistent with the spaces around your arithmetic operations:

For example, strlen(inputStr) - 1 is clearer than strlen(inputStr)-1.

You should be constant with the way you use functions and how you intend their arguments:

f(arg1, arg2) instead of sometimes f (arg1,arg2) and sometimes f ( arg1, arg2 ).

In addition to these points, which will only improve the readability of your code, I am pretty sure that you could copy directly from input into the array
like this:

/* allocate space in the array for the string and copy it in */
array[i] = malloc((sizeof(char*)) *(strlen(inputStr)) + 1);
strncpy(array[i], inputStr, strlen(inputStr) + 1);

This way you can delete the intermediate step where you save the input into a separate string and allocate (and free!) memory for it.


Pixelate image with average cell color I wrote a function that will pixelate an image using the average color of each 4x4 cell.

The function will "split" the image into 4x4 cells, and find the average color of each pixel in the 4x4 cell, and set the 4x4 cell to the average color.

I'd like some help optimizing my function so it can pixelate an image as fast as possible. In its current state the pixelation process is quite slow.

private static Image PixelateImage(Image image)
{
    var bitmap = new Bitmap(image.Width, image.Height);
    using (var graphics = Graphics.FromImage(bitmap))
    {
        graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
            new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
    }

    // Loop through the image in 4x4 cells.
    for (var yy = 0; yy < image.Height && yy < image.Height; yy += 4)
    {
        for (var xx = 0; xx < image.Width && xx < image.Width; xx += 4)
        {
            var cellColors = new List<Color>();

            // Store each color from the 4x4 cell into cellColors.
            for (var y = yy; y < yy + 4 && y < image.Height; y++)
            {
                for (var x = xx; x < xx + 4 && x < image.Width; x++)
                {
                    cellColors.Add(bitmap.GetPixel(x, y));
                }
            }

            // Get the average red, green, and blue values.
            var averageRed = cellColors.Aggregate(0, (current, color) => current + color.R) / cellColors.Count;
            var averageGreen = cellColors.Aggregate(0, (current, color) => current + color.G) / cellColors.Count;
            var averageBlue = cellColors.Aggregate(0, (current, color) => current + color.B) / cellColors.Count;

            var averageColor = Color.FromArgb(averageRed, averageGreen, averageBlue);

            // Go BACK over the 4x4 cell and set each pixel to the average color.
            for (var y = yy; y < yy + 4 && y < image.Height; y++)
            {
                for (var x = xx; x < xx + 4 && x < image.Width; x++)
                {
                    bitmap.SetPixel(x, y, averageColor);
                }
            }
        }
    }
    return bitmap;
}

Jerry Coffin suggested that I should simply scale the image down to a smaller size, and then back up to the original size. (Thanks!)

Using Emgu CV, I was able to shorten my function to a single return statement.

private Image<Bgr, byte> PixelateImage(Image<Bgr, byte> image)
{
    return image.Resize((int)(image.Width * .25), (int)(image.Height * .25), Inter.Area)
        .Resize(image.Width, image.Height, Inter.Nearest);
}


increase the efficiency of a matching algorithm I'm trying to create an algorithm that will match one set of objects with another.  Each of the objects from one group can be matched with some of the objects from another group. Once an item has been matched, it cannot be matched to another item.  My current implementation iterates over each of the objects and attempts to find a solution where each object has a match. I've done this recursively, but this method quickly becomes unusable as the processing time increases exponentially.  Here is a trivial example of what I've written:

def demo_match():
    possible_matches = {
        "x": {1, 2},
        "y": {2, 3},
        "z": {1, 2}
    }

    used_numbers = set()

    matched = {}

    def match_items(remaining_items_to_match):

        for letter in remaining_items_to_match:
            possible_numbers = possible_matches[letter]
            available_numbers = possible_numbers.difference(used_numbers)
            print(f"can match '{letter}' with {available_numbers}")
            if not available_numbers:
                raise ValueError(f"there are no possible matches for {letter}")
            for possible_match in available_numbers:
                try:
                    used_numbers.add(possible_match)
                    matched[letter] = possible_match
                    print(f"'{letter}' has been matched with {possible_match}")
                    if len(remaining_items_to_match) is 1:
                        return matched
                    # remove this item and process the remaining
                    next_remaining_items = remaining_items_to_match[1:]
                    return match_items(next_remaining_items)
                except ValueError:
                    print(f"***** found a dead end, unmatching '{letter}' and {possible_match} *****")
                    used_numbers.remove(possible_match)
                    del matched[letter]
            raise ValueError("ran out of available numbers to match")

    print(f"\nMatch Solution: {match_items(list(possible_matches.keys()))}")

The actual implementation assigns weights to the possible matches, meaning that matching 1 item would be preferred, but if it results in a dead end it tries the next match.  I feel like there is a better implementation of this out there, maybe involving sets to find where items overlap and determining the critical path. I just haven't been able to come up with a decent alternative other than this exhaustive search.

------- Update ------

After researching the algorithms suggested in the answers I decided to go with the munkres algorithm. It allows weighting of items in the vertex.

It accepts a matrix of items, where the rows represent 1 item, the columns another, and where they intersect is the cost when those items are paired. The common example uses people and jobs as the items. This algorithm will find the pair of items with the least cost. To prevent an item from being paired, set the cost in the matrix to float('inf')
eg:

         Janitor     Teacher     Doctor
Bob       9           5          1
Dick      1           4          6
Sally     5           3          7

would be represented by:

[
[9,5,1],
[1,4,6],
[5,3,7]
]

and would return [0,1,2], [2,0,1] where the first list represents the row indices and the second list represents the index of columns that would be matched with the rows
I ended up converting the two lists into a dictionary of people to their corresponding job via

>>> def match():
    from munkres import Munkres
    people = ["bob", "dick", "sally"]
    jobs = ["janitor", "teacher", "doctor"]
    matrix = [
               [9,5,1],
               [1,4,6],
               [5,3,7]
              ]

    m = Munkres()
    indexes = m.compute(matrix)

    matches = {}
    for p, j in indexes:
        person = people[p]
        job = jobs[j]
        matches[person] = job
    return matches

>>> match()
{'bob': 'doctor', 'dick': 'janitor', 'sally': 'teacher'}

matches will be a dictionary of people to their matched job

1. The Hopcroft–Karp algorithm

The problem you're trying to solve here is to find a maximum matching in an unweighted bipartite graph. This can be solved in \$O(\sqrt V E)\$ by the Hopcroft–Karp algorithm.

Here's a sketch of how the Hopcroft–Karp algorithm works. Suppose that we have a bipartite unweighted graph, like the one you use as an example in the post:

Because it's bipartite, there are two sets of vertices which we'll call \$U\$ and \$V\$:

The Hopcroft–Karp algorithm works by repeatedly augmenting the matching, increasing the number of edges in the matching by one. Suppose that we have added one edge to the matching so far, between \$y\$ and \$2\$, drawn as a red edge:

The algorithm now searches for an augmenting path. This is a path that starts at an unmatched vertex in \$U\$, crosses to \$V\$ on an unmatched (black) edge, crosses back to \$U\$ on a matched (red) edge, and so on, finally ending in \$V\$. Here's an augmenting path, starting at \$x\$, following an unmatched edge to \$2\$, following a matched edge to \$y\$, and following an unmatched edge to \$3\$:

An augmenting path has an odd number of edges (because it starts in \$U\$ and finishes in \$V\$) and the edges along the path alternate between unmatched and matched. This means that if we swap all the edges along the augmenting path (matched becoming unmatched and vice versa), we get a new matching with one more edge, like this:

Now carrying on with the algorithm, there is another augmenting path, \$z\$–\$2\$–\$x\$–\$1\$:

Swapping the edges along this path, we increase the matching again:

Now there are no more augmenting paths (because there are no unmatched vertices in \$U\$) and we are done.

How do we find the augmenting paths? Well, we use a combination of breadth-first search and depth-first search. At each stage we do a breadth-first search to divide the vertices into layers according to their shortest distance from an unmatched vertex along an augmenting path. Suppose we are at this stage of the algorithm, where \$y\$ has been matched with \$2\$:

Now the breadth-first search divides the vertices into the following layers:

Using this structure, an augmenting path can be found efficiently (linear time) by a depth-first search that only follows edges from lower-numbered layers to higher-numbered layers.

2. Implementation

This is a direct translation of the pseudocode from Wikipedia into Python. To help with book-keeping, this implementation introduces a distinguished node nil, with all vertices being artificially matched with nil to start with. When there are no more augmenting paths ending at nil then we know the matching is maximal.

from collections import deque

def maximum_matching(graph):
    """Find a maximum unweighted matching in a bipartite graph. The input
    must be a dictionary mapping vertices in one partition to sets of
    vertices in the other partition. Return a dictionary mapping
    vertices in one partition to their matched vertex in the other.

    """
    # The two partitions of the graph.
    U = set(graph.keys())
    V = set.union(*graph.values())

    # A distinguished vertex not belonging to the graph.
    nil = object()

    # Current pairing for vertices in each partition.
    pair_u = dict.fromkeys(U, nil)
    pair_v = dict.fromkeys(V, nil)

    # Distance to each vertex along augmenting paths.
    dist = {}
    inf = float('inf')

    def bfs():
        # Breadth-first search of the graph starting with unmatched
        # vertices in U and following "augmenting paths" alternating
        # between edges from U->V not in the matching and edges from
        # V->U in the matching. This partitions the vertexes into
        # layers according to their distance along augmenting paths.
        queue = deque()
        for u in U:
            if pair_u[u] is nil:
                dist[u] = 0
                queue.append(u)
            else:
                dist[u] = inf
        dist[nil] = inf
        while queue:
            u = queue.pop()
            if dist[u] < dist[nil]:
                # Follow edges from U->V not in the matching.
                for v in graph[u]:
                    # Follow edge from V->U in the matching, if any.
                    uu = pair_v[v]
                    if dist[uu] == inf:
                        dist[uu] = dist[u] + 1
                        queue.append(uu)
        return dist[nil] is not inf

    def dfs(u):
        # Depth-first search along "augmenting paths" starting at
        # u. If we can find such a path that goes all the way from
        # u to nil, then we can swap matched/unmatched edges all
        # along the path, getting one additional matched edge
        # (since the path must have an odd number of edges).
        if u is not nil:
            for v in graph[u]:
                uu = pair_v[v]
                if dist[uu] == dist[u] + 1: # uu in next layer
                    if dfs(uu):
                        # Found augmenting path all the way to nil. In
                        # this path v was matched with uu, so after
                        # swapping v must now be matched with u.
                        pair_v[v] = u
                        pair_u[u] = v
                        return True
            dist[u] = inf
            return False
        return True

    while bfs():
        for u in U:
            if pair_u[u] is nil:
                dfs(u)
    return {u: v for u, v in pair_u.items() if v is not nil}


Subclassing pandas DataFrame for an ETL I'm writing a small ETL, which loads data from CSVs, cleans each table a bit, and then loads everything into a PostgreSQL database. I was planning to use pandas for its built-in capabilities, but am wondering whether to subclass DataFrame or whether to just do everything functionally.

The subclassed DataFrame code is pasted below. For maintainability by non-developers, I have a small YAML file with information about each table and column type.

import pandas
import numpy
import yaml
from os import path

CFG = yaml.load(open('config.yaml', 'r'))

class ETLDataTable(pandas.DataFrame):
    _metadata = ['table_name', 'file_name', 'columns', 'notes']

    @property
    def _constructor(self):
        return ETLDataTable

    def __init__(self, table_name):
        # Name of the database table
        self.table_name = CFG[table_name]['table']
        # Name of the CSV file
        self.file_name = CFG[table_name]['file']
        # Whether file has note fields
        self.notes = CFG[table_name]['notes']

        #Data Types to feed into read_csv
        try:
            self.columns = CFG[table_name]['columns']
        except:
            pass

        _ = path.join(path.abspath(path.pardir), self.file_name)
        super().__init__(pandas.read_csv(_))

    def load_df(self, root_path, **kwargs):
    """Read the csv associated with the table name,
    then import as a pandas DataFrame
    """
        _ = path.join(path.abspath(path.pardir), self.file_name)
        pandas.read_csv(csv_path,
                        na_values = ['00000000', ' ', ''],
                        encoding="latin1",
                        dtype="object",
                        **kwargs)

Going forward I was planning to add in some methods that are needed by every table: fixing bad dates, stripping empty strings, etc. Is this approach going to be more trouble than it's worth?

For the parsing and analysis of my tests, I did something like this:

import pandas as pd
from pathlib import Path

class MyTest:

    def __init__(self, settings: dict, root_dir: Path):
        self.table_name = settings['table']
        self.file_name = settings['file']
        ...
        self.columns = settings.get('columns', None)

        filename = root_dir / self.file_name
        data = read_data(filename, columns=self.columns)
        self._data = fix_data(data)

    def summary_x(self):
        ...
        return None

    def get_data_between(self, date1, date2):
        # optionally parsing the dates
        return self._data[self._data['data'].between(date1, date2)]

    ...

def read_data(filename, **kwargs) -> pd.DataFrame:
    return pd.read_csv(
        filename,
        na_values=['00000000', ' ', ''],
        encoding="latin1",
        dtype="object",
        **kwargs,
    )

def fix_data(data: pd.DataFrame, date_cols=None) -> pd.DataFrame:
    if date_cols:
        date_cols = (date_cols,) if isinstance(date_cols, str) else date_cols
        data[date_cols] = [fix_dates(data[col]) for col in date_cols]
    ...
    return data

def fix_dates(data: pd.Series) -> pd.Series:
    #optionally a column
    pass

def remove_empty_strings(data):
    pass

Once I was at the stage where I had multiple types of tests, I made a generic type, and subclassed this. But I see little value in subclassing pandas.Dataframe, because then you also have to take care not to accidentally overwrite any of it's methods and attributes


C inner product function without using array subscripting As part of a question designed to help us understand the relationship between pointers and arrays in C, I've been asked to write an inner product function that doesn't use any array subscripting. Here's what I came up with, but it looks like the kind of complicated 'clever' coding that we've traditionally been told NOT to write.
Any feedback on it, or how it could be done better / more efficiently would be much appreciated.

int inner_product(const int *a, const int *b, int n) {

    const int *p, *q;
    int result = 0;
    for(p = a, q = b; p < a + n, q < b + n; p++, q++) {
            result += *p * *q;
    }
    return result;
}

Edit - Inner product is simply summing the product of the indexes, so a[1,2,3] b[2,3,4] would be 1*2 + 2*3 + 3*4

I have a few comments on style.  (By which I really mean, 100% opinion... :D)

One declaration per line

A lot of people strongly disagree with this, but I find it much easier to read code that has one declaration per line.

const int *p;
const int *q;

Is a lot clearer to me than:

const int *p, *q;

Though really, the only time I've vehemently opposed to it is if both variables are not the same in terms of a pointer or value:

const int *p, q;

Is a harder to read and more prone to errors than:

const int *p;
const int q;

n

I would name the n paramter something more meaningful.  I would consider calling it size or num.

It's fairly apparent that n is meant to be the number of elements, but two or three extra keystrokes seems worth the extra clarity.

Possible implementation

I would probably write the function something like this:

int inner_product(const int *a, const int *b, int num)
{

    const int* end = a + num;

    int sum = 0;

    while (a != end) {
            sum += (*a) * (*b);
            ++a;
            ++b;
    }

    return sum;

}

Since the two pointers are incremented at the same time, there's no reason to check both.

This should be a tiny bit more efficient (well... probably not once the compiler does it's magic optimisations on the original), and I think it's a bit clearer.


Simple math library in Rust So, I've tried to make a simple math library in Rust. What do you think about it?

const PRECISION: f64=512.; //Balance between speed and precision here.

fn ln(x:f64) -> f64 {
    let mut sum=0.;
    let epsilon=(x-1.)/(5.*PRECISION);
    let mut i=1.;
    while (epsilon>0. && i<x) || (epsilon<0. && i>x) {
        sum+=epsilon/i;
        i+=epsilon;
    }
    sum
}

fn exp(x:f64) -> f64 {
    let mut i=0.;
    let mut y=1.;
    let epsilon=x/PRECISION;
    while (epsilon>0. && i<x) || (epsilon<0. && i>x) {
        y+=epsilon*y;
        i+=epsilon;
    }
    y
}

fn arctan(x:f64) -> f64 {
    let mut sum=0.;
    let epsilon=x/PRECISION;
    let mut i=0.;
    while i<x {
        sum+=epsilon/(1.+i*i);
        i+=epsilon;
    }
    sum*(180./pi())
}

fn tan(degrees:f64) -> f64 {
    sin(degrees)/cos(degrees)
}

fn sin(degrees:f64) -> f64 {
    if degrees<0. {
        return -sin(-degrees);
    }
    if degrees>90. {
        return cos(degrees-90.);
    }
    let radians=degrees/(180./pi());
    let mut tmpsin=0.;
    let mut tmpcos=1.;
    let epsilon=radians/PRECISION;
    let mut i=0.;
    while (epsilon>0. && i<radians) || (epsilon<0. && i>radians) {
        tmpsin+=epsilon*tmpcos;
        tmpcos-=epsilon*tmpsin;
        i+=epsilon;
    }
    tmpsin
}

fn arcsin(x:f64) -> f64 {
    arctan(x/sqrt(1.-x*x))
}

fn arccos(x:f64) -> f64 {
    90.-arcsin(x)
}

fn cos(degrees:f64) -> f64 {
    sin(90.-degrees)
}

fn sqrt(x:f64) -> f64 {
    let mut max=1000.;
    let mut min=0.;
    let mut i=(min+max)/2.;
    while (max-min)>1./PRECISION {
        if i*i>x {
            max=i;
        }
        else {
            min=i;
        }
        i=(max+min)/2.;
    }
    i
}

fn pi() -> f64 {
    let mut sum=0.;
    let mut i=-1.;
    let epsilon=1./PRECISION;
    while i<1. {
        sum+=epsilon/(1.+i*i);
        i+=epsilon;
    }
    2.*sum
}

fn main() {
    println!("x\tsin(x)\tcos(x)\ttan(x)\tln(x)\tsqrt(x)\tasin\tacos\tatan");
    for i in 0..101 {
        print!("{:.4}\t",i);
        print!("{:.4}\t",sin(i as f64));
        print!("{:.4}\t",cos(i as f64));
        if tan(i as f64)<100. && tan(i as f64)> -10. {
            print!("{:.4}\t",tan(i as f64));
        }
        else if tan(i as f64)< -10. {
            print!("{:.3}\t",tan(i as f64));
        }
        else {
            print!("inf\t");
        }
        if ln(i as f64)> -100. {
            print!("{:.4}\t",ln(i as f64));
        }
        else {
            print!("-inf\t");
        }
        print!("{:.4}\t",sqrt(i as f64));
        if arcsin((i as f64)/100.)<90. {
            print!("{:.4}\t",arcsin((i as f64)/100.));
        }
        else {
            print!("90\t");
        }
        if arccos((i as f64)/100.)<90. && arccos((i as f64)/100.)>0. {
            print!("{:.4}\t",arccos((i as f64)/100.));
        }
        else if arccos((i as f64)/100.)>0. {
            print!("90\t");
        }
        else {
            print!("0\t");
        }
        print!("{:.4}\n",arctan((i as f64)/100.));
    }
    println!("pi={:.4}",pi());
    println!("rad={:.4}",180./pi());
    println!("ln(1/pi)={:.4}",ln(1./pi()));
    println!("e={:.4}",exp(1 as f64));
    println!("1/e={:.4}",exp(-1 as f64));
}

I'm not too familiar with the math side of this, so I'll just focus on the Rust part.

Run rustfmt

Running cargo fmt will autoformat your code to the Rust best practices. For example, it will convert

fn arctan(x:f64) -> f64 {
    let mut sum=0.;
    let epsilon=x/PRECISION;
    let mut i=0.;
    while i<x {
        sum+=epsilon/(1.+i*i);
        i+=epsilon;
    }
    sum*(180./pi())
}

to

fn arctan(x: f64) -> f64 {
    let mut sum = 0.;
    let epsilon = x / PRECISION;
    let mut i = 0.;
    while i < x {
        sum += epsilon / (1. + i * i);
        i += epsilon;
    }
    sum * (180. / pi())
}

Notice the spacing added.

Run clippy

Running cargo clippy will point out a few common mistakes. Let's take a look at them here.

warning: using `print!()` with a format string that ends in a single newline
   --> src/main.rs:136:9
    |
136 |         print!("{:.4}\n",arctan((i as f64)/100.));
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: `#[warn(clippy::print_with_newline)]` on by default
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#print_with_newline
help: use `println!` instead
    |
136 |         println!("{:.4}",arctan((i as f64)/100.));
    |         ^^^^^^^

As it suggests, you should replace that line with println!.

warning: casting integer literal to `f64` is unnecessary
   --> src/main.rs:141:28
    |
141 |     println!("e={:.4}",exp(1 as f64));
    |                            ^^^^^^^^ help: try: `1_f64`
    |
    = note: `#[warn(clippy::unnecessary_cast)]` on by default
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast

That, and the line that follows it, can be used as a float like you do everywhere else in your code. You can do 1_f64, 1f64, 1.0, or like elsewhere in your code, 1..

Extract repeated operations

When you print things out, you repeat the calculation a lot, and it actually appears to have a difference in assembly (although not when #[inline(never)] is used on ln?). So instead of

if arccos((i as f64) / 100.) < 90. && arccos((i as f64) / 100.) > 0. {
    print!("{:.4}\t", arccos((i as f64) / 100.));
} else if arccos((i as f64) / 100.) > 0. {
    print!("90\t");
} else {
    print!("0\t");
}

Prefer

let inv_cos = arccos((i as f64) / 100.);
if inv_cos < 90. && inv_cos > 0. {
    print!("{:.4}\t", inv_cos);
} else if inv_cos > 0. {
    print!("90\t");
} else {
    print!("0\t");
}


Such code, Much wow, very FizzBuzz So, I've written FizzBuzz for a dialect of JavaScript called Dogescript.

It has the same functionality as JavaScript, it simply changes some of the syntax points:

  [A few from the language spec]

shh [comment] - // [comment]
very [var] is [value] - var [var] = [value]
[var] is [value] - [var] = [value]
such [name] much [variables] - function [name] ([variables])
wow - }
rly [params] - if ([params])
but rly [params] - else if ([params])
but - else

I have a feeling I'm misusing the language syntax in relation to adding strings to result.

I also have a feeling my underlying structure of:

Create result variable
Append "Fizz" and "Buzz" based on rules
Print result variable if it has content, otherwise the iterator value.

such fizzbuzz much max
    much very i is 0 next i smaller max next i more 1
        very result
        rly i % 3 is 0
            result += "Fizz"
        wow
        rly i % 5 is 0
            result += "Buzz";
        wow
        console.loge(result || i);
    wow
wow

You can run this with:

plz fizzbuzz with 30

First, use the doge version for everything possible:

    such fizzbuzz much max
        much very i is 0 next i smaller max next i more 1
            very result
            rly i % 3 is 0
                result more "Fizz" next
            wow
            rly i % 5 is 0
                result more "Buzz" next
            wow
            console dose with result or i next
        wow
    wow

As it's a fun fun language, making use of but rly is more important than optimizations:

    very result
    rly i % 3 is 0
        result is "Fizz" next
    but rly i % 5 is 0
        result is "Buzz" next
    but rly i % 15 is 0
        result is i

Making another function for printing instead keeping the result variable looks even better:

    such print much result
        console dose loge with result
    wow

    such fizzbuzz much max
        very i is 1
        much next i smaller max next i more 1
          rly i % 15 is 0
              plz print with "FizzBuzz"
          but rly i % 3 is 0
              plz print with "Fizz"
          but rly i % 5 is 0
              plz print with "Buzz"
          but
              plz print with i
          wow
        wow
    wow


atoi implementation in C I'm looking for feedback on my atoi implementation here in C. Any feedback would great. I made my own atoi for fun and to learn about it.

I'm not trying to replace the standard library version. Reinventing the wheel is fun to me.

#include <limits.h> /* for LONG_MAX, INT_MAX */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#define IS_ASCII_DIGIT(c) ((c >= 48) && (c <= 57))

long __my_atoi(char* buffer)
{
    long ret = 0;
    bool neg = false;

    if (*buffer == '-') {
        neg = true;
        buffer++; /* advance to next position to pass ascii check */
    }

    while (*buffer) {
        if (IS_ASCII_DIGIT(*buffer)) {
            ret = ret * 10 + (*buffer - '0');
        } else {
            fprintf(stderr, "Fatal Error: unexpected '%c' passed to %s\n", *buffer, __func__);
            exit(EXIT_FAILURE);
        }
        buffer++;
    }

    return neg ? -ret : ret;
}

int main(void)
{
    printf("%ld\n", __my_atoi("-10004"));
    return EXIT_SUCCESS;
}

If implementing your own version of a standard routine such as atoi(), some form of explanation (comment) is needed.  For example, is this supposed to be a drop in replacement for atoi()?  Are some aspects deliberately not implemented?  Do you have space restrictions that prevent you from using the standard?  Do you know that certain string combinations will not exist?  This type of information is helpful to anyone reading your code so that they can put things into context.

For the remainder of this review, I shall be assuming that it is meant as an exact replacement for atoi().

The header file limits.h is included, but I do not see any current reason for it to be there.
IS_ASCII_DIGIT() should not be using the magic numbers of 48 and 57.  Values such as '0' and '9' are preferred.
It is customary to surround the macro arguments with parentheses.  This helps to ensure that the argument is evaluated as a whole to cover the case where the argument is a complex expression.
Instead of using IS_ASCII_DIGIT(), I would recommend using isdigit().  This would require including the header file ctype.h.
atoi() is supposed to return an int.  Your routine returns a long.  This indicates either a misnamed routine or an incorrect return value.
The contents of buffer parameter do not change.  It would be better to declare it as a 'const char *'.
There is nothing preventing the dereferencing a NULL pointer.
There is no accounting for white space at the beginning of the string.
There is no accounting for the '+' character at the start of the integer sequence.
There is no accounting for values that are too large or too small to represent.
The standard atoi() routine does not exit or print any message upon a detected error; neither should yours.

For additional information on atoi(), please refer to the following pages:

http://pubs.opengroup.org/onlinepubs/009695399/functions/atoi.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/strtol.html

Hope this helps.


Using a single for loop to load multiple images in a canvas Is there a better way to do this? If I ever have to worry about earlier images not being loaded before the later images, i.e. image[3] being loaded after image[21]. I have to load about 100 images at the start.

for (var i = 0; i < 22; i++) {
   images[i] = new Image();
   images[i].src = whatever[i] + ".png";
    if (i == 21) {
        images[21].onload = function() {
            for (var j = 0; j < 22; j++) {
            context.drawImage( images[j], (test * 60), (240 + ((Math.floor(j * 0.25)) * 70)) );
            }
            test ++;
            if(test > 4) {
                test = 1;
            }
        }
    }
}

Sprite!

I suggest you place the images in a single image, like a "sprite sheet". This means that you need to pre-assemble the images into one image, load that single image and draw it on the canvas.

That way:

You only load one image, thus reducing your http requests to the server to one only.
You draw to the canvas only once. No more loops, no more multiple drawImage.

Order in the court!

Loading images are async, thus the need for the event handler. This also means that the images will arrive in any order, and not necessarily in the order you called them down. In your case, the image at index 21 might come earlier than you'd expect, even before all others have loaded.

I suggest you add an onload to each image and have it check if all images have been loaded before doing anything with them. A simple way to do this is to increment a counter and check if the counter value matches the expected number.

When the count is equal to the expected length, run the code you want to run.

No aftershocks?

If the entire operation was just to load into the canvas the images, it's fine.

However, you aren't loading them for no reason now are you? You are loading them for something. I suggest you wrap this operation in a function, have it accept your url array, and a callback that runs when it finishes loading and rendering all your images on the canvas.

Something like:

loadImagesToCanvas([
  //urls
],function(renderedCanvas){
  //run when done
});

Math.floor() is slow and long

In some browsers, Math.floor() is a slow way to trim off the decimal places of a number. Try bitwise OR (|) instead:

var wholeNumber = decimalNumber | 0;

Unnecessary math

If some consecutive operations use some value resulting from some math operation, cache that value in a variable rather than doing the math again.


Class to represent playing card I admit I'm sort of stuck on this. I couldn't think of a better way of representing the card value that will be used in a playing card game. How well thought out is the casting an enum value to an int? I might be wrong but it does not seem very OOP. Is there a different way I should be doing it instead?

void Main()
{
    Card testCard = new Card(CardSuit.Diamonds, (int)CardValue.Ace);
}

public enum CardSuit
{
    Spades,
    Hearts,
    Diamonds,
    Clubs
}

public enum CardValue
{
    Ace = 1,
    Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10,
    Jack = 11,
    Queen = 12,
    King = 13
}

public class Card
{
    public CardSuit CardSuit { get; private set; }
    public int CardValue { get; private set; }

    public Card(CardSuit cardSuit, int cardValue)
    {
        CardSuit = cardSuit;
        CardValue = cardValue;
    }
}

Use the types you have

Why are you storing the card value as an int? You have already created a CardValue enum, so use it. Change the Card.CardValue property and the cardValue parameter in the Card constructor to be of type CardValue. That way, you don't need to cast to an int when creating a card, and you can always get the numeric card value by casting ((int)cardValue) when you need it.

Argument Validation

What happens if you use new Card((CardSuit)100, (CardValue)100). Your card will have an invalid suit and value. In order to validate the arguments, you can use Enum.IsDefined, which will cause a performance penalty since it uses reflection, or you can hardcode a valid range of values.

Type Naming

The name CardValue seems too general for such a specific type (thanks to @RickDavin). "Value" implies it may refer to any value from the card, such as its suit or rank. A better name might be CardRank.

Property Naming

As noted by @Heslacher, type names shouldn't be used as property names. For instance, in the Card class, the property CardSuit and has a redundant name. Consider a variable Card card = new Card(). Using card.Suit is much clearer and more concise than using card.CardSuit. In addition, you should change the property CardValue to Rank, since the type CardValue was renamed.

Readonly Properties

It seems Rank and Suit are supposed to be readonly. Prior to C#6, your approach was an acceptable one, so long as you remembered not to change those properties outside of the constructor. However, if you're using C#6, a better alternative is to declare them without setters. Like readonly fields, properties that have only getters can only be set inside the constructor, but not outside of it.

With that, the Card class should look like:

public class Card
{
    public CardSuit Suit { get; }
    public CardRank Rank { get; }

    public Card(CardSuit suit, CardRank rank)
    {
        if (suit < CardSuit.Spades || suit > CardSuit.Clubs) // or if (!Enum.IsDefined(typeof(CardSuit), suit))
        {
            // handle error (possibly with ArgumentException)
        }
        if (rank < CardRank.Ace || rank > CardRank.King) // or if (!Enum.IsDefined(typeof(CardValue), rank))
        {
            // handle error
        }
        Suit = suit;
        Rank = rank;
    }
}


Command-Line tool to find large files on a Linux system Is the code pythonic and easy to read and understand? Is there a better way to exclude directories? Did I miss any bugs?

'''Find large files on a linux system.

:Example:
excludes = ['/proc', '/sys', '/dev', '/swapfile']
find_larg_files('/', n_results=20, excludes=excludes)
'''

import os
import operator
from itertools import islice
import fnmatch
import re
import argparse

def take(number, iterable):
    """Return first n items of the iterable as a list.

    :param number: `int` How many do you want to take.
    :param iterable: `iterable`
    :rtype: `list`
    """
    return list(islice(iterable, number))

def walk(fpath, **kwargs):
    ''' Traverse thru a directory tree.

    :param fpath: `int` The root file path
    :param excludes: `list` optional directories to exclude
    :rtype: `generator`
    '''
    kwargs.setdefault('excludes', [])
    excludes = kwargs.get('excludes')
    # transform glob patterns to regular expressions
    excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'
    for root, dirs, files in os.walk(fpath, topdown=1):
        # exclude dirs
        if excludes:
            dirs[:] = [os.path.join(root, d) for d in dirs]
            dirs[:] = [d for d in dirs if not re.match(excludes, d)]
        for name in files:
            yield os.path.join(root, name)

def getsize(fpath):
    ''' Return the size of a file.
    Will return 0 if an OSError is raised.
    :param fpath: `str`
    '''
    try:
        return os.path.getsize(fpath)
    except OSError:
        return 0

def find_larg_files(fpath, n_results=10, **kwargs):
    ''' Recursively find the largest files in a directory.

    return n largest files in a directory tree.
    :param fpath: `str` where to start.
    :param n_results: `int` how many results to retrun.
    :param kwargs: This will be passed to walk.
    :rtype: `None` it prints the paths and sizes to the screen.
    '''
    results = {}
    for name in walk(fpath, **kwargs):
        results[name] = getsize(name)

    results = reversed(sorted(results.items(), key=operator.itemgetter(1)))
    for name, size in take(n_results, results):
        print name, size

def main():

    parser = argparse.ArgumentParser(description='Find large files')
    parser.add_argument('path', metavar='-p', type=str, help='The path to start crawling')
    parser.add_argument(
        '--results', metavar='-n', type=int,
        help='How many results to return the default is 10.',
        default=10
        )
    parser.add_argument(
        '--exclude', metavar='-e', type=list,
        help='Directoris to exclude in the search.',
        nargs='+', default=[]
        )

    args = parser.parse_args()
    find_larg_files(args.path, n_results=args.results, excludes=args.exclude)

if __name__ == '__main__':
    main()

Some observations:

Use a main function and the argparse module pull out an argument parsing method to make this scriptable.
"larg" should be "large"; getsize should be get_size, fpath should be file_path. Saving characters costs a lot of money in maintainability.
As @Edward wrote, don't keep the entire list of files in memory. As a counter-point I would have liked for the results limit to not exist - the default behaviour would then be simpler to implement, and would return every file in order of size.
In addition to excluding directories you should make sure that you don't follow symbolic links, or you could end up with an infinite loop.
The OSError in this case should be fatal - it indicates that your program is faulty since it doesn't properly filter files which you can't get the size of. I believe it could also happen if a file is not accessible, which means any result you get from this script might be inaccurate.
Replace **kwargs with excludes=None, followed by a simple excludes = [] if excludes is None else excludes. That way the parameter list is unambiguous. Even easier, make excludes mandatory (you are always using it anyway). YAGNI & KISS apply :)
It looks like your handling of exclusions doesn't anchor the regex at the start of the filename, so you'll end up excluding for example /home/user/dev.
excludes in walk is always truthy. You should either remove the or r'$.' bit (best option IMO) or get rid of if excludes:.
You reuse excludes in walk to create a completely different list. This is a bad practice because it makes the use and content of a variable really hard to follow. Use separate variables for these.


Parsing values from string into struct using match in Julia My goal
I am parsing from a string which contains token:value pairs into a type.
Example:
mutable struct Foo
    bar
    baz
    qux
end

function parse(str::AbstractString)::Foo
    f = Foo()

    bar_pattern = r"bar:(\w*)"
    baz_pattern = r"baz:(\d*)"
    qux_pattern = r"qux:(\w*)"

    f.bar = match(bar_pattern, s)[1]
    f.baz = match(baz_pattern, s)[1]
    f.qux = match(qux_pattern, s)[1]

    return d
end

Problem
This works but only if the patterns are actually present. When match can't find the pattern, it returns nothing, which of course can't be indexed [1] or accessed with captures. The result is an error.
I want the fields of the returned struct to either get the matched result (the "capture") directly, or remain empty or set to nothing, should the match be unable to find the pattern.
I could do something like this:
function safeparse(str::AbstractString)::Foo
    f = Foo()

    bar_pattern = r"bar:(\w*)"
    baz_pattern = r"baz:(\d*)"
    qux_pattern = r"qux:(\w*)"

    if !isnothing(match(bar_pattern, s))
        f.bar = match(bar_pattern, s)[1]
    end

    if !isnothing(match(baz_pattern, s))
        f.baz = match(baz_pattern, s)[1]
    end

    if !isnothing(match(qux_pattern, s))
        f.qux = match(qux_pattern, s)[1]
    end

    return f
end

But that approach seems ugly and becomes verbose very quick if more/new patterns are introduced.
Question
Is there a nicer but readable way to achieve this?
Preferably without combining/changing the regex patterns or too much regex magic, however I am
open to that route too if it is the only nice (less verbose) way. I am of course also open to general tips.
To keep things simple, just assume that the patterns my example is looking for only appear 0 or 1 times. However if the only way to make this nicer involves writing another function like safematch which does the check for nothing and returns the captured value or nothing, I would want that to also work with multiple matches somehow and stay a bit more general.

The easiest thing I can think of is to use eachmatch -- when there is no match at all, it returns an empty iterator:
julia> collect(eachmatch(r"(bar:(\w*))", "bla bar:werfsd 1223 bar:skdf"))
2-element Array{RegexMatch,1}:
 RegexMatch("bar:werfsd", 1="bar:werfsd", 2="werfsd")
 RegexMatch("bar:skdf", 1="bar:skdf", 2="skdf")

julia> collect(eachmatch(r"(bar:(\w*))", "bla "))
RegexMatch[]

Then you can simply combine those into a dictionary, for example:
julia> Dict(re => [m[1] for m in eachmatch(re, s)] for re in patterns)
Dict{Regex,Array{T,1} where T} with 3 entries:
  r"qux:(\w*)" => Union{Nothing, SubString{String}}[]
  r"baz:(\d*)" => SubString{String}["33"]
  r"bar:(\w*)" => SubString{String}["werfsd", "skdf"]

Without further information about how you want to organize your data structure when more then one value occurs, I can't really say more.  Perhaps you can make use of merge.
Give types to struct fields, and don't use mutable structs unless necessary.  Without knowing more, I suggest
struct Foo
    bar::Union{String, Nothing}
    baz::Union{String, Nothing}
    qux::Union{String, Nothing}
end
function Foo(;bar=nothing, baz=nothing, qux=nothing)
    return Foo(convert(Union{String, Nothing}, bar),
               convert(Union{String, Nothing}, baz),
               convert(Union{String, Nothing}, qux))
end

which also takes care of converting the SubString from the regex match, in case this is relevant.


AI bot Java dungeon game I have written a script that allows a user to walk around a dungeon pick up gold and once they have picked it all up they can exit the game through an exit.

What I am doing now is writing a bot to do the same. So far I have come up with a 'stupid' bot that is based mainly on randomness. The bot has has actions to the following functions;

look() - Can see around the ASCII map in a radius of 2. The function prints it out so the bot cant actually store it in memory(I am allowed to store it memory).

move <direction>() - move in the direction these include N E S W.

pickUp() - If the bot is standing on gold this picks it up.

exitGame() - If the bot is standing on an exit, has all the gold and this command is ran he will exit the game.

Here is my bot code so far.

import java.io.IOException;
import java.util.Random;

public class Bot{
    public GameLogic bot;

    public static void main(String[] args) throws IOException{
        // TODO Auto-generated method stub
        GameLogic bot = new GameLogic("map2.txt");
        bot.startGame();
        int gold = bot.gold();
        System.out.println(gold);
        int turn = 0;
        char[][] myWorld = bot.getMap();
        while(true){
            int posX = bot.getPosX();
            int posY = bot.getPosY();
            Random rn = new Random();
            int min = 0;
            int max = 3;
            int n = max - min + 1;
            int i = rn.nextInt(n);
            if(myWorld[posX][posY] == 'G'){
                bot.pickUp();
            }
            if(myWorld[posX][posY] == 'E'){
                boolean y = bot.exitGame();
                if(y){break;}
            }
            turn++;
            if(i == 0){
                bot.moveN();
            }else if(i == 1){
                bot.moveE();
            }else if(i == 2){
                bot.moveS();
            }else if(i == 3){
                bot.moveW();

            }else{
                System.out.println("SOMETHING WENT WRONG!!!");
            }

        }
        System.out.println(turn);

    }
}

What I am asking is what would be a better way to do this. How can I improve my bot so it takes less turns to complete? How can I make my bot 'smarter'?

Overall
I think you have too much code in the main method. You should split that into more digestible segments. Perhaps some more methods in your GameLogic class (which probably should be split into one Game class and one GameBot / Player class). (At least) one method for determining the next move, one method for choosing the proper action based on the current tile, etc..
Improving your bot
Assuming the gold never moves once it is placed, you could use a Set of all the tiles you have visited. You could then try to not move to a tile you have already visited.
The tiles themselves could be represented as a Point class that contains x and y, or it could be represented as an int if you do a little mathematics to represent a column and row by one single int (I do recommend the Point class though). Or you could make a Tile class, since each tile also has some content (wall, exit, gold, empty space...)
Random
Random rn = new Random();
int min = 0;
int max = 3;
int n = max - min + 1;
int i = rn.nextInt(n);

Since min is zero, there's no need to do - min.
As max is a constant, it'd be easier to declare max as 4 from the start rather than using + 1
As n only is used once, you could just use int i = rn.nextInt(4);
Random objects are meant to be re-used. Initialize your Random object outside the loop. This is because randomization will be different when creating the object over and over again.

Moving
You can move in four directions, this is telling me that you should use a Direction enum and replace your four methods with one move(Direction4 dir); By using this enum, you could also simplify your random process:
Direction4 chosenDirection = Direction4.values()[rn.nextInt(Direction4.values().length)];

This line grabs all the possible directions and randomizes an int from 0 (inclusive) to length (exclusive) and grabs the direction with that index.
When something goes wrong
System.out.println("SOMETHING WENT WRONG!!!");

I can assure you, this will never happen. And even if it would, Exceptions are meant to be for... well, exceptions. throw new AssertionError("Something went wrong."); is what I would have done here. Or rather... I would have removed the entire line, as it will never happen. Especially when you use the Direction4 approach.
Spacing
This is one of the things I mention most often in my reviews probably, but please:
}else if(i == 1){

change to
} else if (i == 1) {

It makes the code more readable with proper spacing.


Project Euler 27 - Quadratic Primes Project Euler problem 27

I decided to try simple brute force, and it worked surprisingly quickly.  How can this be optimized?

"""Considering quadratics of the form:
n^2 + an + b, where |a| < 1000 and |b| < 1000
Find the product of the coefficients, a and b,
for the quadratic expression that produces
the maximum number of primes for
consecutive values of n,
starting with n = 0."""

from timeit import default_timer as timer
import math
start = timer()

def longestPrimeQuadratic(alim, blim):

    def isPrime(k): # checks if a number is prime
        if k < 2: return False
        elif k == 2: return True
        elif k % 2 == 0: return False
        else:
            for x in range(3, int(math.sqrt(k)+1), 2):
                if k % x == 0: return False

        return True

    longest = [0, 0, 0] # length, a, b
    for a in range((alim * -1) + 1, alim):
        for b in range(2, blim):
            if isPrime(b):
                count = 0
                n = 0
                while isPrime((n**2) + (a*n) + b):
                    count += 1
                    n += 1

                if count > longest[0]:
                    longest = [count, a, b]

    return longest

ans = longestPrimeQuadratic(1000, 1000)

elapsed_time = (timer() - start) * 100 # s --> ms

print "Found %d and %d in %r ms." % (ans[1], ans[2], elapsed_time)

This is mostly quite good, but has some issues.

The required answer to the Project Euler problem is not the values of \$a\$ and \$b\$, but their product. You could output that value rather than requiring another computation.
Your prime test could be speeded up by first calculating a table of primes, then only checking for divisibility against that.

primes = [2, 3]

def extend_primes(upto):
    """Pre-extend the table of known primes"""
    for candidate in range(primes[-1], upto + 1, 2):
        if is_prime(candidate):
            primes.append(candidate)

def is_prime(x):
    """Check whether "x" is a prime number"""
    # Check for too small numbers
    if x < primes[0]:
        return False
    # Calculate the largest possible divisor
    max = int(math.sqrt(x))
    # First, check against known primes
    for prime in primes:
        if prime > max:
            return True
        if x % prime == 0:
            return False
    # Then, lazily extend the table of primes as far as necessary
    for candidate in range(prime[-1], max + 1, 2):
        if is_prime(candidate):
            primes.append(candidate)
            if x % candidate == 0:
                return False
    return True

Whether this actually improves performance would have to be properly benchmarked.
Your longest is an list. Instead, you probably wanted to use a tuple:

longest = (0, 0, 0)
...
if count > longest[0]:
    longest = (count, a, b)
...
_, a, b = longestQuadraticPrime(...)

What is the difference? A list is a variable-length data structure where all entries should have the same type. In C, the rough equivalent would be an array. A tuple is a fixed-size data structure where each entry can have a different type. The C equivalent would be a struct.

However, I think it would be actually better to use named variables instead of indices:

longest_count = 0
longest_a = None
longest_b = None
...
if count > longest_count
    longest_count = count
    longest_a = a
    longest_b = b
...
return longest_a, longest_b
...
a, b = longestQuadraticPrime(...)

This is longer, but more readable.
Your code takes some nice shortcuts but fails to explain why you can take these shortcuts.

For example, you only test a \$b\$ if it's a prime. This follows from the \$n = 0\$ case where the expression can be reduced to \$b\$, which therefore has to be prime. This also allowed you to narrow the search space from \$(-1000, 1000)\$ to \$[2, 1000)\$. Just mention this in a comment instead of implying it.

If we pre-calculate a prime table, we could also iterate through those known primes instead of testing each number again and again:

extend_primes(blim)
for b in primes:
    if b >= blim:
        break
    ...

Your n and count variables are absolutely equivalent. Keep n, discard count.
Stylistic issues:

Variables and functions etc. should use snake_case, not camelCase or some quiteunreadablemess. If possible, they should consist of proper words rather than abbreviations, except for very common abbreviations like maximum as max.

alim → a_lim or a_max
isPrime → is_prime
longestPrimeQuadratic → longest_prime_quadratic (although this name doesn't convey very well what this function is doing)
ans → answer, but returning a tuple and destructuring this is probably cleaner.

Don't use one-line conditionals like if k < 2: return False. Instead, use all the space you need to make it as readable as possible:

if k < 2:
    return True

Put spaces around binary operators. math.sqrt(k)+1 becomes math.sqrt(k) + 1
alim * -1 would usually be written with an unary minus: -alim.


Creating a family hierarchy Requirement:

For the input list of tuples to create single line output showing father of the family|spouse|child1,child2....

Input:

input_list = [("David","Polly","Spouse"),
          ("Roger","Patty","Spouse"),
          ("David","Lily","Child"),
          ("Roger","Max","Child"),
          ("David","Sam","Child")]

Expected output:

David|Polly|Lily,Sam
Roger|Patty|Max

I have written the code but it is very clunky. Any improvement and shorter/efficient version is much appreciated.

input_list = [("David","Polly","Spouse"),
          ("Roger","Patty","Spouse"),
          ("David","Lily","Child"),
          ("Roger","Max","Child"),
          ("David","Sam","Child")]
# Expected output
'''
David|Polly|Lily,Sam
Roger|Patty|Max
'''
priority = {"Spouse" :1,"Child" :2}
intermediate_list = []
final_list =[]
return_name = ''
input_list_w_priority = [tuple(x) + (priority[x[2]],) for x in input_list ] #  spouse has priority 1, children have 'lower' priority
sorted_input_list = sorted(input_list_w_priority)
get_father = sorted(list(set([ x[0] for  x in sorted_input_list]))) # getting 'unique' father
for x in range(len(get_father)):
    i =0
    intermediate_list =[]
    spouse_name =''
    final_name = ''
    for y in range(len(sorted_input_list)):  # traversing the input list for a single father

        i+=1

        if(get_father[x] == sorted_input_list[y][0]):
            intermediate_list.append((sorted_input_list[y][1],sorted_input_list[y][3])) # assigning spouse/child name and priority

    if(i == len(sorted_input_list)):
    final_tuple = sorted(intermediate_list,key=lambda x : x[1]) #sorting on priority

    for z in range(len(final_tuple)):
        if(final_tuple[z][1] == 1): # if spouse then pipe separated
            spouse_name = '|'+ final_tuple[z][0] + '|'
        else:
            final_name = final_name + ','+ final_tuple[z][0]
    return_name = return_name + get_father[x] + spouse_name +final_name[1:] + '\n'
print(return_name)

Using a dictionary to group your data is arguably a better alternative to sorting, and building the actual output strings is a perfect fit for the .join() method of strings:

data = {}
for head, tail, kind in input_list:
    tails = data.setdefault(head, [None, []])
    kind = kind.lower()
    if kind == 'spouse' and tails[0] is None:
        # Duplicate spouse entries raise, should we do differently?
        tails[0] = tail
    elif kind == 'child':
        tails[1].append(tail)
    else:
        # Should wrong inputs be ignored, rather than raise?
        raise ValueError('Wrong input')
for head, (spouse, children) in data.items():
    print('|'.join((head, spouse, ','.join(children))))

This will print the families in some arbitrary order, but you could get them sorted by sorting the last for loop, i.e.

for head, (spouse, children) in sorted(data.items()):


Quoting strings passed to an output stream This class allows me to quote strings being sent to an output stream:

class Quote{
public:
    friend std::ostream& operator<<(std::ostream& os, const Quote& obj){
        obj.write(os);
      return os;
    }
    Quote() = delete;
    Quote(const string & text): text(text){}

    void write(ostream & os) const{
        os << default_quote_token << text << default_quote_token;
    }
private:
    const string & text;
};

Like this:

os << Quote(name);

It feels like a lot of work to avoid:

os << "\"" << name << "\"";

Is there a better solution?

In C++14, there's std::quoted. Some advantages it has over your approach:

It works with both output and input streams
You can specify the delimiter and escape character
It's a stream manipulator, allowing it to be used seamlessly with operations while yours is a one-off class with zero interoperability
It supports wide strings


Device-dependent image descriptor fields In a Java class that belongs in a library, I have a field size that indicates size of image. It must be int, but some values are depending to devices, so other developers can set  various types for it:

thumbnail (value depends on device)
real size (value depends on device)
custom (arbitrary integer)

I want to restrict other developers (that use this library) to set value of size with one option from set of specific and meaningful options.My purpose is to show list of legal options to developer and also type safety, like Enum. But I think it is impossible to do that only by enum, so I create an interface and some classes:

public interface SizeMode {
}

public enum DevicePreDefinedImageSizeMode implements SizeMode {
    THUMBNAIL, REAL_SIZE
}

public enum CustomImageSizeMode implements SizeMode {
    CUSTOM_SIZE
}

public abstract class Size {

    private final SizeMode mode;

    public SizeMode getMode() {
        return mode;
    }

    public abstract int getDownSampleFactor();

    protected Size(SizeMode mode) {
        this.mode = mode;
    }
}

public class DevicePreDefinedImageSize extends Size {

    public DevicePreDefinedImageSize(DevicePreDefinedImageSizeMode mode) {
        super(mode);
    }

    @Override
    public int getDownSampleFactor() {
        throw new UnknownError("????");
    }

}

public class CustomImageSize extends Size {
    private final int downSampleFactor;

    private CustomImageSize(CustomImageSizeMode mode, int downSampleFactor) {
        super(mode);
        this.downSampleFactor = downSampleFactor;
    }

    @Override
    public int getDownSampleFactor() {
        return downSampleFactor;
    }

}

Now I can declare field size of type Size class and other developers are restricted to use one of sub classes of Size and initialize them with THUMBNAIL, REAL_SIZE or CUSTOM_SIZE.

But is there a better approach to achieve my purpose?

I'm afraid, it's hard to use. To create a size, I need to do something like

new DevicePreDefinedImageSize(
    DevicePreDefinedImageSizeMode.REAL_SIZE,
    number)

I don't think I could ever remember this. What about:

Size.newRealSize(number)

This can be done easily, all you need are three static methods. You can otherwise keep you classes as they are.

@Override
public int getDownSampleFactor() {
    throw new UnknownError("????");
}

This is a real pain. I can see that there's no downSampleFactor, but throwing four question marks isn't really helpful. I'd return 0. Though it may hide errors, it can make it easier to use.

Or, when you're defining so many classes, what about making them so that the unwanted method doesn't really exist? Declare it only where it makes sense.

Personally I wouldn't do six classes for this.


Reverse multiple strings separated by comma Recently I did a lot of practice problems in brainfuck to learn better about how to use it (and to get more competent in general). Today I write a program to manipulate the input such that every word (separated by comma ,) is printed in reverse, while the commas are kept in place, which I'm quite proud of. Example provided in the statement: Input: Hello,world\0 Output: olleH,dlrow

Feel free to rip my code (and comments as well) apart and give some pointers on how my code could be improved!

>, 1:read
[ ~a:varchar a:in
[>+>+<<-] a:0 b:c:in
>>>>++++[<+++++ +++++ +>-]<[<->-] a:0 b:in [c:in-44]
<[[-]<[<+>-]>>] if c then a:in else
<[<<[.<]>[>]>.>]< print reverse then comma
, redo a':read ]
<[.<] print reverse

Upon learning more brainfuck, I've learned that my loop that subtracts 44 could be improved:

Before

>> tmp2=0 ++++[< tmp1=0 +++++ +++++ + >-] tmp1 is 44
<[<->-] subtract tmp1 from ptr

After

>  tmp1=0 ++++[< ptr    ----- ----- - >-]

This prevents actually creating the value 44 and performing an additional ~44 operations.