Numerical Python code to generate artificial data from a time series process I'm writing code to generate artificial data from a bivariate time series process, i.e. a vector autoregression. This is my first foray into numerical Python, and it seemed like a good place to start.

The specification is of this form:

\begin{align}
\begin{bmatrix}
y_{1,t} \\
y_{2,t}
\end{bmatrix}
&=
\begin{bmatrix}
0.02 \\
0.03
\end{bmatrix}
+
\begin{bmatrix}
0.5 & 0.1 \\
0.4 & 0.5
\end{bmatrix}
\begin{bmatrix}
y_{1,t-1} \\
y_{2,t-1}
\end{bmatrix}
+
\begin{bmatrix}
0 & 0 \\
0.25 & 0
\end{bmatrix}
\begin{bmatrix}
y_{1,t-2} \\
y_{2,t-2}
\end{bmatrix}
+
\begin{bmatrix}
u_{1,t} \\
u_{2,t}
\end{bmatrix}
\end{align}

where \$u\$ has a multivariate normal distribution, i.e.
\begin{align}
\begin{bmatrix}
u_{1,t} \\
u_{2,t}
\end{bmatrix}
\sim N \left( \begin{bmatrix} \mu_1 \\ \mu_2 \end{bmatrix}, \Sigma \right)
\end{align}

My basic algorithm generates enough observations to get past the effects of the (arbitrary) initial conditions, and only returns the number of observations asked for. In this case, it generates ten times the number of observations asked for and discards the first 90%.

import scipy

def generate_data(y0, A0, A1, A2, mu, sigma, T):
    """ Generate sample data from VAR(2) process with multivariate
        normal errors

    :param y0: Vector of initial conditions
    :param A0: Vector of constant terms
    :param A1: Array of coefficients on first lags
    :param A2: Array of coefficients on second lags
    :param mu: Vector of means for error terms
    :param sigma: Covariance matrix for error terms
    :param T: Number of observations to generate
    """

    if y0.ndim != 1:
        raise ValueError("Vector of initial conditions must be 1 dimensional")

    K = y0.size

    if A0.ndim != 1 or A0.shape != (K,):
        raise ValueError("Vector of constant coefficients must be 1 dimensional and comformable")

    if A1.shape != (K, K) or A2.shape != (K, K):
        raise ValueError("Coefficient matrices must be conformable")

    if mu.shape != (K,):
        raise ValueError("Means of error distribution must be conformable")

    if sigma.shape != (K, K):
        raise ValueError("Covariance matrix of error distribution must be conformable")

    if T < 3:
        raise ValueError("Cannot generate less than 3 observations")

    N = 10*T

    errors = scipy.random.multivariate_normal(mu, sigma, size = N-1)
    data = scipy.zeros((N, 2))
    data[0, :] = y0
    data[1, :] = y0
    for i in range(2, N):
        data[i, :] = A0 + scipy.dot(A1, data[i-1, :]) + scipy.dot(A2, data[i-1, :]) + errors[i-1,:]
    return(data[-T:, :])

def main():
    y0 = scipy.array([0, 0])
    A0 = scipy.array([0.2, 0.3])
    A1 = scipy.array([[0.5, 0.1], [0.4, 0.5]])
    A2 = scipy.array([[0, 0], [0.25, 0]])
    mu = scipy.array([0, 0])
    sigma = scipy.array([[0.09, 0], [0, 0.04]])
    T = 30

    data = generate_data(y0, A0, A1, A2, mu, sigma, T)
    print(data)

if __name__ == "__main__":
    main()

As I said, this code is very simple, but since it's my first attempt at a numerical Python project, I'm looking for any feedback before I slowly start building a larger code project that incorporates this. Does any of my code (base Python, SciPy, etc.) need improvement?

This specific model comes from:

  Brüggemann, Ralf, and Helmut Lütkepohl. "Lag Selection in Subset VAR Models with an Application to a US Monetary System." (2000).

Is

scipy.dot(A1, data[i-1, :]) + scipy.dot(A2, data[i-1, :])

a bug or a copy-paste error? According to the spec, the second term should have i - 2.
A 90% lead-in seems arbitrary. In fact, any lead-in would be arbitrary, as long as you didn't quantify how much the initial condition should fade. In any case, I recommend to pass it as a parameter (either percentage to discard, or - preferably - the desired decay of the initial condition).


JavaScript and jQuery check for image file and assign CSS This is my first attempt at JavaScript, so I am looking to learn.

I have a website that has jQuery built in and I wanted to leverage that in the following way:

I want to get a number variable that precedes a certain text string (*n*/portal.css)
Get the name of the current webpage
Use this number and pageName to help build a URL to a specifically named image file  The image will have the same name as the webpage with an "_hd.jpg" appended to it
Check if the image file exists and if it does add this image to a CSS div background otherwise do nothing

<script>

    $(function () {
        $(document).foundation();
        //get webpage name
        var loc = window.location.href
        var fileNameIndex = loc.lastIndexOf("/") + 1;
        var dotIndex = loc.lastIndexOf('.');
        var pageName = loc.substring(fileNameIndex, dotIndex < fileNameIndex ? loc.length : dotIndex);

        //get number variable
        var head = document.head
        var portalCss = head.innerHTML.match(/\/[0-9]+\/portal.css/);

        var portalNum = portalCss[0].replace("/", "")
        portalNum = portalNum.replace("portal.css", "")

        //build url for image
        var HeaderImgUrl = '/Portals/' + portalNum + '/Images/' + pageName + '_hd.jpg'

        //check if image exists and assign css values to css class RowPageHeader
        $.ajax({
            url: HeaderImgUrl, //or your url
            success: function (data) {
                $(".RowPageHeader").css("background-image", "url(" + HeaderImgUrl + ")");
                $(".RowPageHeader").css("background-position", "center top");
                $(".RowPageHeader").css("background-size", "100% auto");
                $(".RowPageHeader").css("background-repeat", "no-repeat");
                $(".RowPageHeader").css("overflow", "hidden");
            },
        })

        var FooterImgUrl = '/Portals/' + portalNum + '/Images/footer_bg.jpg'

        $.ajax({
            url: FooterImgUrl, //or your url
            success: function (data) {
                $(".RowFooter").css("background-image", "url(" + FooterImgUrl + ")");
                $(".RowFooter").css("background-position", "center top");
                $(".RowFooter").css("background-size", "2000px auto");
                $(".RowFooter").css("background-repeat", "no-repeat");
                $(".RowFooter").css("overflow", "hidden");
            },
        })

    })

</script>

Two questions:

How can I improve this code?
I want to move the CSS rules into a CSS class in the pages skin.css file.  How can I add a CSS class to the existing one that I am adding the CSS rules to?

Basically every duplicated object can be made one object. And maybe use a function so you can call it when required.

If you use an IIFE like below, you can put this code in an external *.js file. It will then run asap without stalling other http requests while loading the page. Also pass in the jQuery object as a parameter so you can safely use $ instead.

The configuration separation allows you to easily change things when needed. They're also grouped and give you a better overview. Compared to the other objects the cfg variable is the "local global" so you can use cfg throughout your whole script.
The window object groups your functionality or component in one object. Basically one DOM object for a project is ideal imho. Allows you to access window.ComponentName in other files as well.
The activation is under your control. For the moment it uses the common DOM ready event and basically just runs the init() function.

// @param ($): jquery version x?
(function ($) {
    // 1. CONFIGURATION
    var cfg = {
        rowpageheader: '.RowPageHeader',
        rowfooter: '.RowFooter',
        options: {
            header: {
                'background-position': 'center top',
                'background-size': '100% auto',
                'background-repeat': 'no-repeat',
                'overflow': 'hidden'
            },
            footer: {
                'background-position': 'center top',
                'background-size': '2000px auto',
                'background-repeat': 'no-repeat',
                'overflow': 'hidden'
            }
        },
        path: {
            portal: 'Portals',
            images: 'Images'
        },
        misc: {
            portalcss: 'portal.css',
            imagequality: '_hd.jpg',
            footerbg: 'footer_bg.jpg'
        }
    };

    // 2. DOM OBJECT
    window.Images = {
        init: function () {
            this.cacheItems();
            this.activate();
        },

        cacheItems: function () {
            this.rowPageHeader = $(cfg.rowpageheader);
            this.rowFooter = $(cfg.rowfooter);
        },

        activate: function () {
            var cfgOptions = cfg.options,
                portalNum = this.getPortalNum(),
                pageName = this.getPageName();

            this.updateHeader(portalNum, pageName, cfgOptions.header);
            this.updateFooter(portalNum, cfgOptions.footer);
        },

        getPageName: function () {
            var loc = window.location.href,
                fileNameIndex = loc.lastIndexOf('/') + 1,
                dotIndex = loc.lastIndexOf('.');

            return loc.substring(fileNameIndex, dotIndex < fileNameIndex ? loc.length : dotIndex);
        },

        getPortalNum: function () {
            var head = document.head,
                portalcss = cfg.misc.portalcss,
                regexp = '/\/[0-9]+\/' + portalcss + '/',
                portalCss = head.innerHTML.match(regexp),
                portalNum = portalCss[0].replace('/', '');

            return portalNum.replace(portalcss, '');
        },

        updateHeader: function (portalNum, pageName, options) {
            var proj = this,
                cfgPath = cfg.path,
                headerUrl = [cfgPath.portal, portalNum, cfgPath.images, pageName, cfg.misc.imagequality];

            $.ajax({
                url: headerUrl.join('/')
            }).done(function () {
                var opt = $.extend(options, { backgroundImage: 'url(' + headerUrl + ')' });
                proj.rowPageHeader.css(opt);
            });
        },

        updateFooter: function (portalNum, options) {
            var proj = this,
                cfgPath = cfg.path,
                footerUrl = [cfgPath.portal, portalNum, cfgPath.images, cfg.misc.footerbg];

            $.ajax({
                url: footerUrl.join('/')
            }).done(function () {
                var opt = $.extend(options, { backgroundImage: 'url(' + footerUrl + ')' });
                proj.rowFooter.css(opt);
            });
        }
    };

    // 3. DOM READY
    $(function () {
        $(document).foundation();
        Images.init();
    });
} (jQuery));

Haven't checked if this works, but it should ^^


Creating Menubar using Angularjs 1.5 I've a sample code to create a simple menubar here which works, but I'm not sure if that's the best way to code it. Can somebody please validate if there is a better way to do the same?

In short

I've create a sample page with a directive called <menu-bar>

<menu-bar></menu-bar>

The directive merely points to a template code and a controller

app.directive("menuBar", function () {
  return {
    restrict: 'E',
    templateUrl: 'main-nav.html',
    controller: 'navController',
    controllerAs: 'nc'
  }
});

The controller loads the menubar (which will eventually fetch the items from the DB

app.controller('navController', ['$scope', '$location', function ($scope, $location) {
  $scope.navigationTabs = [
    new NAV("file","/file","File","fa fa-file-o", "active"),
    new NAV("edit","/edit","Edit","fa fa-edit", "inactive"),
    new NAV("view","/view","View","fa fa-search", "inactive"),
    new NAV("hist","/history","History","fa fa-history", "inactive"),
    new NAV("bmark","/bookmarks","Bookmarks","fa fa-bookmark-o", "inactive"),
    new NAV("hlp","/help","Help","fa fa-life-buoy", "inactive")
  ];
  ...
}]);

The controller defines a 'selectTab()' method which changes the url of the application when the user selects a menu-item. It also clears the active class on all the other items and sets the 'active' class on the one selected

    ...
    $scope.selectTab = function (nav) {
    $scope.navigationTabs.forEach(function (nav) {
        nav.active="";
    });
    console.log("navigating to url: " + nav.key);
    $location.path(nav.key);
    nav.active = "active";
}

The NAV item is defined in the app.js as follows:

var NAV = function (id, key, value, icon, active) {
    this.id = id;
    this.key = key;
    this.value = value;
    this.icon = icon;
    this.active = active;
};

$scope.navigationTabs = [
  new NAV("file","/file","File","fa fa-file-o", "active"),
  ...
]

All this piece of code does is define an instance of a NAV with the specified properties. It's not sharing methods, no inheritance, making the use of a constructor overkill. This is no different from doing:

$scope.navigationTabs = [
{ id: "file", key: "/file", value: "File", icon: "fa fa-file-o", active: "active" }

The above method throws away the need for a constructor, names your properties verbosely, and order of appearance doesn't matter. If you want defaults, a factory function that merges your object with a default one does the same thing. It may just be replacing your constructor, but you still keep the perks of using an object.

function createNav(settings){
  return Object.assign({
    // defaults here
  }, settings);
}

Taking this further, you can just store the objects in an array, and run map through it to create the tabs. This way, you avoid always calling the function and concentrate on just the data.

var navItems = [
  { id: "file", key: "/file", value: "File", icon: "fa fa-file-o", active: "active" },
  ....
];

$scope.navigationTabs = navItems.map(createNav);

console.log("navigating to url: " + nav.key);

Consider avoiding console.log when debugging. Use the browser's developer tools instead. Should you really want to log, use Angular's $log service as it safely detects the presence of console.

I would recommend that the directive be like a standalone component and written like:

<menu-bar menu-items="someVarWithMenuItems"></menu-bar>

In this manner, you make the directive portable, letting the enclosing controller decide what the menu items are. Another idea would be to have another directive and let the consumer write it this way:

<menu-bar>
  <menu-item ...props...>tab text</menu-item>
  <menu-item ...props...>tab text</menu-item>
  <menu-item ...props...>tab text</menu-item>
</menu-bar>

This way, you can just let the consumer drop in the scripts and not have to worry about them. They can just declare the tabs in the markup.


Script for Python Hanoi Tower OOP Is my Python Script to play Hanoi Tower respectful of OOP spirit?

I have difficulties to create meaningful classes so I started an easy project. Here is one class at the plateau level and then a class to handle towers.

How can it be improved (on the OOP level and on script level)?

I want then a GUI with TKinter, a third class GUI would be suited ?

Thank you

import numpy as np
NB_DISKS = 3

class Plateau:
    """Class for the whole plateau"""
    def __init__(self):
        self.init_plateau()

    def init_plateau(self):
        """List of towers,first tower full"""
        self.nb_disks = NB_DISKS
        self.towers = [Tower(self.nb_disks), Tower(0), Tower(0)]

    def motion(self, tower_from, tower_to):
        """Motion from one tower to another one with checking"""
        from_tower = self.towers[tower_from-1]
        to_tower = self.towers[tower_to-1]

        if from_tower.get_last_disk()>to_tower.get_last_disk():  #Receive 0 if to_tower is empty
            disk = from_tower.get_last_disk()
            from_tower.delete_disk()
            to_tower.add_disk(disk)

            self.check_victory()
            self.print_towers()
        else:
            print('Last disk number from origin has to be bigger than reception one')

    def check_victory(self):
        """Check if last tower has an ordered list or not"""
        last_tower = self.towers[2].get_whole_tower()
        if len(last_tower) == self.nb_disks:
            diff_last_tower = np.diff(last_tower)
            if np.unique(diff_last_tower) == 1:
                print('victory:')
                self.print_towers()
                print('new plateau:')
                self.init_plateau()

    def print_towers(self):
        """Print the towers"""
        for elt in self.towers:
            elt.print_tower()
        print('\n')

class Tower:
    """Class for a tower"""
    def __init__(self,nb_disks):
        """Creation of a tower"""
        if nb_disks !=0:
            self.tower = list(range(1, nb_disks+1))
        else:
            self.tower = []

    def get_last_disk(self):
        """Return last element of the tower"""
        if self.tower == []:
            return 0
        else:
            return self.tower[-1]

    def delete_disk(self):
        """Delete last disk of the tower"""
        self.tower.pop()

    def add_disk(self,disk):
        """Add a disk to the top of the tower"""
        self.tower.append(disk)

    def get_whole_tower(self):
        """Return the complete tower"""
        return(self.tower)

    def print_tower(self):
        """Print the element of the tower"""
        print(self.tower)

if __name__ == '__main__':
    game = Plateau()
    game.motion(1,3)
    game.motion(1,3)   # Try to move a big disk on a small one
    game.motion(1,2)
    game.motion(3,2)
    game.motion(1,3)
    game.motion(2,1)
    game.motion(2,3)
    game.motion(1,3)

From the OOP/typing level, you might want to consider having Disk be a type.  If it doesn't need any methods, you could just make it a subtype of int:

from typing import NewType

Disk = NewType('Disk', int)

Some notes on your interfaces:

Since you always use get_last_disk and delete_disk together, why not combine them?  The thing you really want is a pop_top_disk operation that removes and returns the last disk (that's already how you're implementing delete_disk anyway).
add_disk could implement the "no larger disk on a smaller one" rule.
get_whole_tower seems bad because it's exposing the internal data structure of the tower; this violates your entire OOP abstraction.  Note also that in general you should distinguish between "private" and "public" members of your classes.
Rather than making NB_DISKS a global and having Plateau initialize itself from that, Plateau's initializer should take the number of disks as a parameter.
The Pythonic way of making a "print" function is to implement the magic function __repr__ to return a string.
The int values of your disks should be reversed so that bigger numbers represent bigger disks.
This is more an English thing than a Python thing, but the verb form of "motion" is "move" so it would be better to name your method move.  :)

Here's the final code I came up with after implementing the above suggestions:

from typing import NewType

Disk = NewType('Disk', int)

class WrongOrder(Exception):
    def __init__(self, top: int, bottom: int) -> None:
        super().__init__("Can't put a disk of size %d on a disk of size %d" % (top, bottom))

class Plateau:
    """Class for the whole plateau"""
    def __init__(self, nb_disks: int) -> None:
        self._init_plateau(nb_disks)

    def _init_plateau(self, nb_disks: int) -> None:
        self._towers = [Tower(nb_disks), Tower(0), Tower(0)]

    def move(self, from_tower: int, to_tower: int) -> None:
        """Move from one tower to another (towers specified as an int from 1-3).
        Prints an error if the move is invalid."""
        # Convert from 1-index to 0-index.
        from_tower -= 1
        to_tower -= 1
        # Make the move, print exception if it fails.
        try:
            disk = self._towers[from_tower].pop_top_disk()
            try:
                self._towers[to_tower].add_disk(disk)
            except WrongOrder:
                # don't drop the disk!  Put it back where we got it and reraise.
                self._towers[from_tower].add_disk(disk)
                raise
        except Exception as e:
            print('Move failed: ', str(e))
        else:
            self._check_victory()
            print(self)

    def _check_victory(self) -> None:
        """Check if all disks have moved to the last tower (victory condition).
        If the player has achieved victory, reset the game.
        """
        if sum(tower.height for tower in self._towers) == self._towers[2].height:
            print('victory:')
            print(self)
            print('new plateau:')
            self._init_plateau(self._towers[2].height)

    def __repr__(self) -> str:
        """Print the towers"""
        return "\n".join([repr(tower) for tower in self._towers]) + "\n"

class Tower:
    """Class for a tower"""
    def __init__(self, nb_disks: int) -> None:
        """Creation of a tower"""
        self._tower = [Disk(size) for size in range(1, nb_disks + 1)]
        self._tower.reverse()  # order the stack from largest to smallest

    def pop_top_disk(self) -> Disk:
        """Remove and return the top disk on this tower."""
        return self._tower.pop()

    def add_disk(self, disk: Disk) -> None:
        """Add a disk to the top of the tower.
        Raises WrongOrder if the disk being added is too big.
        """
        if len(self._tower) and self._tower[-1] < disk:
            raise WrongOrder(disk, self._tower[-1])
        self._tower.append(disk)

    @property
    def height(self) -> int:
        """Number of disks in the tower."""
        return len(self._tower)

    def __repr__(self) -> str:
        """Print the elements of the tower"""
        return repr(self._tower)

if __name__ == '__main__':
    game = Plateau(3)
    game.move(1,3)
    game.move(1,3)   # Try to move a big disk on a small one
    game.move(1,2)
    game.move(3,2)
    game.move(1,3)
    game.move(2,1)
    game.move(2,3)
    game.move(1,3)


Method to convert String to int array I was working on a suggestion for this question, but the method, I would've suggested the OP do something similar to, seems a bit convoluted.

It's supposed to take a String input and return an array of only the integers deliminated by spaces. It does this correctly, but It feels like I may be doing some unnecessary things or there's a more succinct way to do this, such as with regex.

public static int[] getIntegers(String s) {
    int[] result;
    ArrayList<Integer> helper = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == ' ' ^ i == s.length() - 1) {
            if (i == s.length() - 1) { sb.append(s.charAt(i)); }
            if (sb.toString().length() > 0) {
                try { helper.add(Integer.parseInt(sb.toString()));
                } catch(NumberFormatException nfe) {
                        // Ignore non-integers
                }
                sb.setLength(0);
                continue;
            }
        }
        sb.append(s.charAt(i));
    }

    result = new int[helper.size()];
    int i = 0;

    for (Integer n : helper) {
        result[i++] = n;
    }
    return result;
}

Ohhhh.... XOR logic on booleans in Java ..... how esoteric:

if (s.charAt(i) == ' ' ^ i == s.length() - 1) {

That should be removed "just because". It's hard to understand, the logic is inverted, and it is not short-circuit, so it tests the i == s.length() - 1 even when s.charAt(i) == ' '

I think what you have is an inverted logic problem. You are looking for all the digits in the input, when, instead, you should be looking for not-digits....

The supporting logic, using StringBuilders, etc. is not a bad idea.... but, have you considered a regular-expression?

String[] digitwords = input.split("\\D+");
int[] result = new int[digitwords.length];
for (int i = 0; i < result.length; i++) {
    result[i] = Integer.parseInt(digitwords[i]);
}
return result;

The split there, is "split on all sequences that do not contain digits"

Java8 may help (with an added filter to remove empty values, not in the loop above), with:

return Arrays.stream(input.split("\\D+"))
       .filter(word -> !word.isEmpty())
       .mapToInt(Integer::parseInt)
       .toArray();


Evaluating a polynomial You are given a polynomial of degree n. The polynomial is of the form

    P(x) = an · xn + an-1 · xn-1 + … + a0

  where the ai‘s are the coefficients. Given an integer
  x, write a program that will evaluate P(x).

  You are provided with a function named power( ) that takes two
  positive integers x and y and returns xy. If y is
  0, the function returns 1.

  The prototype of this function is

int power(int x, int y);

  INPUT:

  Line 1 contains the integers n and x separated by whitespace.
  Line 2 contains the coefficients an, an-1, …, a0 separated by whitespace.

  OUTPUT:

  A single integer which is P(x).

  CONSTRAINTS:

  The inputs will satisfy the following properties. It is not necessary
  to validate the inputs.

1 <= n <= 10
1 <= x <= 10
0 <= ai <=10

My code

#include<stdio.h>

int power(int x, int y);

int main()
{

int n,x,a[11],i; unsigned long long int sum=1;
scanf("%d%d",&n,&x);
if(n<1 || n>10) return 0;
if(x<1 || x>10) return 0;

for(i=0;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]< 0 || a[i]>10) return 0;
}
for(i=0;i<n;i++)
{

sum+=power(x,n-i)*a[i];
}
printf("%llu",sum);

    return 0;
}

int power(int x, int y)
 {
   int result = x,i;

   if(y == 0) return 1;
   if(x < 0 || y < 0) return 0;

   for(i = 1; i < y; ++i)
   result *= x;

   return result;
}

Recommend a uniform and more indented style.  E.g.

for(i=0;i<n;i++)
{
    sum+=power(x,n-i)*a[i];
}

Both a[11] and if(... n>10) rely on the same value.  Also to avoid undocumented magic numbers, consider the following (also the same for x and a[]):

#define n_MAX (10)
#define n_MIN (0)
int a[n_MAX + 1];
if(n<n_MIN || n>n_MAX) return 0;

unsigned long long int sum serves little value in protecting against numbers larger than INT_MAX as power() is the most likely candidate to overflow.  (Strictly speaking, it is not even known that LLONG_MAX is greater than INT_MAX.)  So if you want a larger range, re-write power() as unsigned long long power(int x, int y), otherwise leaving sum as int is OK.

Else suggest for marginal range improvement:

sum += (unsigned long long) power(x,n-i) * a[i];

BTW: should not it be:

unsigned long long int sum = 0;  //( 0 not 1)

Note: Stated objective says "It is not necessary to validate the inputs.".  Still I like the testing you have done.  Possible that the final reviewer (teacher?) may object to unneeded code.  Could wrap in an #if DEBUG macro...
Faster way to do power()
See no reason for x<0 test in if(x < 0 || y < 0) return 0;.  Could be

if (y < 0) return 0;

Do power() with unsigned rather than int as " function named power( ) that takes two positive integers x and y".
@Constructor comment leads to an excellent suggestion.  Calculate sum with a loop that does the below.  No need for a power function.  Running sum can be unsigned long long and code gets great range.  Its faster & simple.

// sum = (((a[n]*x + a[n-1])*x + a[n-2])*x + .... )*x + a[0];

// Something like
unsigned long long sum = 0;
for (int i=n; i>=0; i--) {
  sum *= x;
  sum += a[i];
}

Lastly, even the array a is not needed:

#include<stdio.h>
int main() {
  int n;
  unsigned x, a;
  unsigned long long sum = 0;
  scanf("%d%u", &n, &x);
  while (n-- >= 0) {
    scanf("%u", &a);
    sum *= x;
    sum += a;
  }
  printf("%llu", sum);
  return 0;
}


Removing all duplicated pairs in a Python list I need a function to remove duplicated pairs from a list. The following is example list:

a = [1, 1, 1, 2, 3, 5, 4, 4, 5, 2, 3, 3, 2, 3, 1, 6, 6, 6, 6]

I need remove all pairs [a[i], a[i+1]] if a[i] == a[i+1] until all such pairs eliminated:

[1, 1, 1, 2, 3, 5, 4, 4, 5, 2, 3, 3, 2, 3, 1, 6, 6, 6, 6]

[1, 2, 3, 5, 5, 2, 2, 3, 1]

[1, 2, 3, 3, 1]

[1, 2, 1] - final list

I wrote a removepairs function:

def removepairs(list):
    result_prev = list
    while True:
        result = __removepairs_once__(result_prev)
        if len(result) == len(result_prev):
            return result
        else:
            result_prev = result

def __removepairs_once__(list):
    result = []
    most_recent_element = None
    for i in list:
        if i != most_recent_element:
            if most_recent_element:
                result.append(most_recent_element)
            most_recent_element = i
        else:
            most_recent_element = None
    if most_recent_element:
        result.append(most_recent_element)
    return result

Please help me to make it better.

I think you should try re-making __removepairs_once__ only using results.
No most_recent_element.

So, you would want to retry you algorithm, most_recent_element can be results[-1].
Using this you should come to this stub code:

def _remove_pairs(list_):
    result = []
    for item in list:
        if item == results[-1]:
            # remove last item
            # don't add this item
        else:
            # add this item
    return result

Using this you should notice that it'll error if results is empty, this means you should use the else if it is.
The if block is surprisingly simple, it's results.pop(). And the else is results.append(item).

def _remove_pairs(list_):
    results = []
    for item in list_:
        if results and item == results[-1]:
            results.pop()
        else:
            results.append(item)
    return results

A quick test of this actually (unsurprisingly) returns the final list that you wanted.

Don't use __{}__ for anything! Only use it for pythons magic functions!

You should also not use list but list_ as then you can still convert something to a list.


We take take advantage of these features of numpy to reduce the code quite a bit:

array reshaping
array row, column and diagonal slices
np.prod to compute the product of all elements in an array
flipping the array to get anti-diagonals

Reshaping

Reshaping allows you to (for instance) reorganize a 1-dimensional array into a 2-dimenstional array. Just the dimension metadata is changed so the operation is very efficient:

a = np.array([1,2,3,4,5,6]).reshape(3,2)
print a

[[1 2]
 [3 4]
 [5 6]]

Slicing

Here are example of how to take row, column and diagonal slices of arrays:

import numpy as np

a = np.array( [[11,12,13,14,15,16],
               [21,22,23,24,25,26],
               [31,32,33,34,35,36],
               [41,42,43,44,45,46]
              ] )

print "row",     a[1][3:5]         # horizontal slice, row 1, columns 3..5
print "column:", a[:,4]            # column 4
print "diag:",   np.diagonal(a, 2) # 2nd diagonal

Note that row and column indices start from 0. In the case of diagonals, 0 is the main diagonal, with positive diagonals to the right and negative diagonals to the left of the main.

Products

And here is how to use np.prod:

a = np.array([5,6,7,8])
print np.prod(a)             # prints 1680

Anti-diagonals

We can get anti-diagonals by first flipping the matrix along one of its dimensions:

a = np.array([1,2,3,4,5,6,7,8]).reshape(2,4)
b = a[::-1,]
print b

b has the same shape as a and the diagonals of b are the anti-diagonals of a.

Solution

Putting it all together:

def euler11():
  data = """
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
"""
  a = np.array([ int(x) for x in data.split() ]).reshape(20,20)
  # print a
  b = a[::-1,]

  maxprod = 0
  for i in xrange(20):
    for j in xrange(20):
      r = np.prod( a[i][j:j+4] )
      c = np.prod( a[:,j][i:i+4] )
      k = min(i,j)
      d1 = np.prod( np.diagonal(a, j-i)[ k:k+4 ] )
      d2 = np.prod( np.diagonal(b, j-i)[ k:k+4 ] )
      maxprod = max([maxprod,r,c,d1,d2])
  print maxprod

Note here is i,j represents the upper left corner of either the row, column or diagonal we are taking the product of. That's why both range from 0 to 16 We just run both i and j from 0 through 19. We examine a few extra products (some with less than 4 terms), but since we are looking for the maximum it doesn't matter.


Sugestion on a better way to code this EF update? I have a block of code that pulls the current menu position and compares it to what users selected, if the selection is different the database is updated with the new selection. As I am still new with EF I was hoping for a general code review for suggestions on a possible better, more efficient, and/or easier way to code this. Here is my existing code:

using (var db = new SectionInfoAdmin())
{
    var dtCategories = (from n in db.Navigation
    where n.SectionID == SectionID
    select new
    {
       n.Category
    }).ToList();

 string PrimaryCategory = dtCategories[0].Category.ToString();

 if (ddlPrimaryCategory.SelectedValue != PrimaryCategory)
 {
    var Category = (from n in db.Navigation
    where n.Category == PrimaryCategory && n.SectionID == SectionID
       select n).First();

    Category.Category = PrimaryCategory;
 }

 if (dtCategories.Count > 1)
 {
    string SecondaryCategory = dtCategories[1].Category.ToString();
    if (ddlSecondaryCategory.SelectedValue == SecondaryCategory)
    {
       var Category = (from n in db.Navigation
       where n.Category == SecondaryCategory && n.SectionID == SectionID
          select n).First();
       Category.Category = SecondaryCategory;
    }
 }
 db.SaveChanges();
 lblResults.Text = "Information updated.";
}

As @dreza mentioned, you might want to move the code around your LINQ-Statements to a method.

public void changeCategoryTo(String newCategory){
   var record = (from n in db.Navigation where n.Category == newCategory
                   && n.SectionId == SectionID select n).First();
   record.Category = newCategory;
}

this greatly reduces duplication.

further points:

Try to stick to either camelCase or MixedCase to have consistent and speaking variable names:

something like var Category, String PrimaryCategory and similar are diffifult to associate to clear roles in your code.
try to refrain from naming your variables after their type only, this leads to greatly increased effort when handling multiple objects of the same type.

Your if-statement for updating the SecondaryCategory is different from the if-statement for updating PrimaryCategory


Graph Implementation in Java using adjacency list - v2 Updated version from Graph Implementation in Java using adjacency list

public class MyGraph {
    // add vertex name as key, and neighbors as values in set
    HashMap<String, HashSet<String>> adjList = new HashMap<>();

    public void addVertex(String name) {
        if (adjList.containsKey(name)) {
            throw new IllegalArgumentException();
        }
        adjList.put(name, new HashSet<>());
    }

    public void addEdge(String source, String destination) {
        // are both vertexes already in the graph?
        if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
            throw new IllegalArgumentException();
        }

        // does edge already exist?
        if (adjList.get(source).contains(destination)) {
            throw new IllegalArgumentException();
        } else {
            adjList.get(source).add(destination);
        }
    }

    public HashSet<String> getNeighbors(String name) {
        return adjList.get(name);
    }

    // return true if there is an edge from source -> destination
    public boolean isNeighbor(String source, String destination) {
        if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
            throw new IllegalArgumentException();
        }
        return adjList.get(source).contains(destination);
    }

    public void removeEdge(String source, String destination) {
        if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
            throw new IllegalArgumentException();
        }
        adjList.get(source).remove(destination);
    }

    public void removeVertex(String name) {
        if (!adjList.containsKey(name)) {
            throw new IllegalArgumentException();
        }
        // remove vertex and its neighbors, if any
        adjList.remove(name);

        // remove vertex as a neighbors from other vertexes
        Set vertexes = adjList.keySet();
        Iterator i = vertexes.iterator();
        while (i.hasNext()) {
            String vertex = (String) i.next();
            if (adjList.get(vertex).contains(name)) {
                adjList.get(vertex).remove(name);
            }
        }
    }

    // removes all vertexes/edges from graph
    public void clear() {
        adjList = new HashMap<>();
    }

    // returns the number of vertexes
    public int size() {
        return adjList.size();
    }

    public boolean isEmpty() {
        return adjList.isEmpty();
    }
}

You should make your class final unless you're explicitly intending it to be extended.
adjList should be private. You don't want other classes in your package reaching into a MyGraph and messing with its adjacencies. It would also be reasonable to make it final. Map defines a clear method you can use.
In general, prefer using interfaces where possible. Within your code, the fact that adjList is a HashMap and not a TreeMap is irrelevant. So just refer to it as a Map.
Most of your comments are noise. If the purpose of a block of code isn't obvious, you can usually create a new method with a name that makes it obvious.
There's no charge for extra characters, and it's easier to read adjacencyLists than adjList.
Is it really necessary to throw an error if the user asks you to do something you've already done for them? If they need to know if the edge already existed, you can return a boolean. This is how the Collections API works, and I think it's a good model.
You can't safely return a Set from your adjList, because if a user mucks with that, they're changing the internals of your graph. Use a new Set instance.
For isNeighbor and removeEdge, do those need to be exceptions?
Remember to use generics consistently.
There's no need to call contains in removeVertex. Sets don't break if you try to remove a non-existent element.
In removeVertex, it's a lot easier to just loop over the values in the map, rather than the keys.

If I were to refactor your code, a first pass might look something like:

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

public final class MyGraph {

    // add vertex name as key, and neighbors as values in set
    private final Map<String, Set<String>> adjacencyLists = new HashMap<>();

    public void addVertex(final String name) {
        if (this.adjacencyLists.containsKey(name)) {
            throw new IllegalArgumentException();
        }
        this.adjacencyLists.put(name, new HashSet<>());
    }

    public boolean addEdge(final String source, final String destination) {
        if (!this.adjacencyLists.containsKey(source) || !this.adjacencyLists.containsKey(destination)) {
            throw new IllegalArgumentException();
        }

        return this.adjacencyLists.get(source).add(destination);
    }

    public Set<String> getNeighbors(final String name) {
        return new HashSet<>(this.adjacencyLists.get(name));
    }

    /**
     * @return true if there is an edge from source -> destination
     */
    public boolean isNeighbor(final String source, final String destination) {
        if (!this.adjacencyLists.containsKey(source) || !this.adjacencyLists.containsKey(destination)) {
            throw new IllegalArgumentException();
        }
        return this.adjacencyLists.get(source).contains(destination);
    }

    public boolean removeEdge(final String source, final String destination) {
        if (!this.adjacencyLists.containsKey(source)) {
            return false;
        }

        return this.adjacencyLists.get(source).remove(destination);
    }

    public boolean removeVertex(final String name) {
        if (!this.adjacencyLists.containsKey(name)) {
            return false;
        }

        this.adjacencyLists.remove(name);

        for (final Set<String> adjacencies : this.adjacencyLists.values()) {
            adjacencies.remove(name);
        }

        return true;
    }

    /**
     * removes all vertexes/edges from graph
     */
    public void clear() {
        this.adjacencyLists.clear();
    }

    /**
     * @return the number of vertexes
     */
    public int size() {
        return this.adjacencyLists.size();
    }

    public boolean isEmpty() {
        return this.adjacencyLists.isEmpty();
    }
}


Minimizing a file path I have a simple program that "minimizes" a file path. Minimizing simply means replacing unnecessary file entries with entries that mean the same thing:

path1/path2/../path3 is replaced with path1/path3
path1/./path2 is replaced with path1/path2

I've achieved this using regex and it seems to cover all cases, but it also feels very slow and I have a hunch it might be prone to infinite loops:

private static final Pattern ONE_DOT = Pattern.compile("/\\./");
private static final Pattern TWO_DOTS = Pattern.compile("[^/]+/\\.\\./?");

public static String minimize(final String in) {
    String tmp = in;
    while (!stringIsMinimized(tmp)) {
        tmp = ONE_DOT.matcher(tmp).replaceAll("/");
        tmp = TWO_DOTS.matcher(tmp).replaceAll("");
    }
    return tmp;
}

public static boolean stringIsMinimized(final String str) {
    return !(ONE_DOT.matcher(str).find() || TWO_DOTS.matcher(str).find());
}

Your code actually doesn't work, because you use replaceAll. This means that your pattern will allow you to match ../../ and replace it with , resulting in a lost double-back. You can fix this two ways:

You could change the replaceAll to replaceFirst
You could change the pattern to exclude ../../ ([^/.]+/\\.\\./? works)

You can then simplify your loop since the ONE_DOT case will be matched properly so you don't need to split out a check for minimization.

Thus I would suggest:

private static final Pattern ONE_DOT = Pattern.compile("/\\./");
private static final Pattern TWO_DOTS = Pattern.compile("([^/.]+/\\.\\.)+/?");

public static String minimize(final String in) {
    String tmp = in;

    tmp = ONE_DOT.matcher(tmp).replaceAll("/");

    while (TWO_DOTS.matcher(tmp).matches())
        tmp = TWO_DOTS.matcher(tmp).replaceAll("");

    return tmp;
}

At least as a first-pass improvement. There may be a way to do it without the loop using some kind of counting regular expression, but off the top of my head I'm not sure.


A Scala Maze Generator in Functional Style I'm wondering if there is more I can do to incorporate more idiomatic scala and functional programming principles. I know the maze itself is mutable but i didn't see an easy solution to making it immutable. Also, if there is anything I can do to improve my algorithm, that would be great too. The reason I have the trait is so that I can implement more mazes: Prim's, Kruskal's, ... and get the functionality of the trait.

trait Maze {
  val height: Int
  val length: Int
  var maz: Array[Array[Int]]

  def maze: Maze

  override def toString() = {
    val strBuilder = new StringBuilder()
    for (i <- 0 until height) {
      for (j <- 0 until length) {
        strBuilder.append(maz(i)(j))
      }
      strBuilder.append("\n")
    }
    strBuilder.toString()
  }
}

class DepthFirstSearch(val height: Int, val length: Int, var maz: Array[Array[Int]]) extends Maze {

  def this(height: Int, length: Int) {
    this(height, length, Array.ofDim[Int](height, length))
  }

  override def maze = {
    maz(0)(0) = 1
    val stack = List[(Int, Int)]()
    mazify((0, 0) :: stack, (0, 0))
  }

  private def mazify(stack: List[(Int, Int)], currentCell: (Int, Int)): DepthFirstSearch = {
    if (stack.nonEmpty) {
      val unvisitedNeighbor = getRandomUnvisitedNeighbor(maz, currentCell)
      if (unvisitedNeighbor._1) {
        val newCurrentCell = unvisitedNeighbor._2
        maz(newCurrentCell._1)(newCurrentCell._2) = 1
        mazify(currentCell :: stack, newCurrentCell)
      } else if (stack.nonEmpty) {
        val newCurrentCell = stack.head
        mazify(stack.tail, newCurrentCell)
      }
    }
    new DepthFirstSearch(height, length, maz)
  }

  private def neighbors(cell: (Int, Int)) = {
    List((cell._1 - 1, cell._2), (cell._1 + 1, cell._2), (cell._1, cell._2 + 1), (cell._1, cell._2 - 1))
  }

  private def insideMaze(cell: (Int, Int)) = {
    cell._1 >= 0 && cell._1 < height && cell._2 >= 0 && cell._2 < length
  }

  private def notOriginalCell(cell: (Int, Int), originalCell: (Int, Int)) = {
    cell._1 != originalCell._1 && cell._2 != originalCell._2
  }

  private def cellVisited(cell: (Int, Int)) = {
    maz(cell._1)(cell._2) == DepthFirstSearch.Visited
  }

  private def hasValidNeighbors(cell: (Int, Int), originalCell: (Int, Int)) = {
    val neighboringCells = neighbors(cell)
    val filteredNeighbors = neighboringCells.filter(c => insideMaze(c) && cellVisited(c) && notOriginalCell(c, originalCell))
    val isValidCell = filteredNeighbors.isEmpty
    isValidCell
  }

  private def getUnvisitedNeighbors(maze: Array[Array[Int]], cell: (Int, Int)) = {
    val neighboringCells = neighbors(cell)
    val filteredNeighbors = neighboringCells.filter(c => c._1 >= 0 && c._1 < height && c._2 >= 0 && c._2 < length && maze(c._1)(c._2) != 1 && hasValidNeighbors(c, cell))
    filteredNeighbors
  }

  private def getRandomUnvisitedNeighbor(maze: Array[Array[Int]], cell: (Int, Int)): (Boolean, (Int, Int)) = {
    val neighbors = getUnvisitedNeighbors(maze, cell)
    if (neighbors.length > 0)
      (true, neighbors(Random.nextInt(neighbors.size)))
    else
      (false, (-1, -1))
  }
}

object DepthFirstSearch {
  private val Visited = 1

  def apply(height: Int, length: Int) = new DepthFirstSearch(height, length)
}

Prefer Classes to Multiple Tuples

There are lots of usages of cell: (Int, Int), with multiple occurrences of cell._1 and cell._2. Tuples are nice and suitable for various situations, but when there are too many of them, it reduces readability and increases risks of bugs. And you need to remember that _1 is x and _2 is y. Or vice versa. Or both.

So a simple way to improve it is just create an ad-hoc class

private class Cell(val x: Int, val y: Int)

It might also be a case class, if necessary.

Use Options

The method signature

private def getRandomUnvisitedNeighbor(maze: Array[Array[Int]], cell: (Int, Int)): (Boolean, (Int, Int))

is suspicious.

Not only it returns a tuple containing another tuple, but also it looks like the purpose of the Boolean is to show if the return object contains data or marks a missing value, according to mazify: if (unvisitedNeighbor._1) { ... }.

Scala has a dedicated Option[T] type for that:

private def getRandomUnvisitedNeighbor(maze: Array[Array[Int]], cell: (Int, Int)): Option[(Int, Int)] = {
  val neighbors = getUnvisitedNeighbors(maze, cell)
  if (neighbors.length > 0)
    Some(neighbors(Random.nextInt(neighbors.size))))
  else
    None
}

In mazify:

...
getRandomUnvisitedNeighbor(maz, currentCell) match {
  case cell: Some[(Int, Int)] => {
    val newCurrentCell = cell.get
    maz(newCurrentCell._1)(newCurrentCell._2) = 1
    mazify(currentCell :: stack, newCurrentCell)
  }
  case None => {
    val newCurrentCell = stack.head
    mazify(stack.tail, newCurrentCell)
  }
}

Nested fors

The nested for loops in Maze.toString look too imperative-style.

The nesting can be avoided with

for {
  i <- 0 until height
  j <- 0 until length
} {
  strBuilder.append(maz(i)(j))
  if (j == length - 1) strBuilder.append("\n")
}

  @jwill's question 2. What is the benefit of the for comprehensions? It looks like the same mutability as a double for loop.

Yes, there is no magic and it is equivalent to double/nested for loops.
As I already mentioned, when we have

for (bla-bla-bla_1) {
  for (bla-bla-bla_2) {
    // very clean code here
  }
}

It looks like the good/bad old imperative style. In Scala, foreach and others are functional style replacements for traditional for. The for-comprehension is a sort of shortcut allowing to iterate, filter and map (with yield). For example:

for {
  i <- 0 until height
  if i % 2 == 0
  j <- 0 until length
  if j % 2 == 0
} yield {
  (i, j)
}

Will produce tuples of even values of i and j.
It is completely equivalent to

(0 until height).filter(_ % 2 == 0).flatMap(i => {
   (0 until length).filter(_ % 2 == 0).map(j => (i, j))
})

But clearly more readable with for. And the nesting is not visible.

  @jwill's question 5. Is the stringbuilder frowned upon?

StringBuilder (either from java.lang or scala.collection) is THE object to use when you need to dynamically construct a String from numerous concatenations.

Readability

getUnvisitedNeighbors contains a terribly complex filtering condition and unnecessary vals. Slightly changed:

private def getUnvisitedNeighbors(maze: Array[Array[Int]], cell: (Int, Int)) = {
  def xInBounds(x: Int) = x >= 0 && x < length
  def yInBounds(y: Int) = y >= 0 && y < height
  neighbors(cell).filter(c => {
    xInBounds(c._2) &&
    yInBounds(c._1) &&
    maze(c._1)(c._2) != 1 &&
    hasValidNeighbors(c, cell)
  })
}

  @jwill's question 3. In getUnvisitedNeighbors, why did you write those intermediary calculations as defs rather than vals?

Briefly speaking, because def is a function that is invoked when necessary. val is a constant reference, calculated only once on first invocation. If vals were used here instead of defs, we would not be able to check the condition from within the filter method for each particular cell.

  @jwill's question 4. You also didn't mention anything about nesting the private defs inside the main override def maze function. Is that important at all, or a scala idiom to do so?

If you mean that def maze invokes private def mazify, that is absolutely OK and mazify should remain as a private function. Nesting defs within each other should not be overused. I would recommend it only when the nested function is 1) really short; 2) simplifies the readability of the parent one; 3) never needs to be invoked from other functions or itself; 4) does not call other functions of this entity. For def mazify most these conditions are not met.

Mutability

  @jwill's question 1. You didn't mention any adjustments for the mutations of the maze. How come? Does it follow under the principle of, "Keep your mutations in small, select locations"?

Indeed, I didn't cover it in the initial answer.

var is not necessary for maz field, it can and should be transformed to val. The reference is never changed throughout the code, but only the contents of the array changes. And I also think that there is no need to expose the array with public access at all.

The def maze in DepthFirstSearch also seems disturbing, because it recalculates the maze on each call and returns a new different instance of DepthFirstSearch. Was it really the intention?

It would be more logical to remove both var maz and def maze from trait Maze and define an accessor for cell values at the trait level:

trait Maze {
  val height: Int
  val length: Int
  def valueAtCell(x: Int, y: Int): Int
}

The implementing class will encapsulate the Array with cells values:

class DepthFirstSearch(override val height: Int,
                       override val length: Int) extends Maze {

  private val maze: Array[Array[Int]] = {
    val maz = Array.ofDim[Int](height, length)
    maz(0)(0) = 1
    mazify(List(), (0, 0))
    maz
  }

  override def valueAtCell(x: Int, y: Int): Int = maze(y)(x)

  private def mazify(stack: List[(Int, Int)], currentCell: (Int, Int)): Unit = {
    val unvisitedNeighbor = getRandomUnvisitedNeighbor(maze, currentCell)
    if (unvisitedNeighbor._1) {
      val newCurrentCell = unvisitedNeighbor._2
      maze(newCurrentCell._1)(newCurrentCell._2) = 1
      mazify(currentCell :: stack, newCurrentCell)
    } else if (stack.nonEmpty) {
      val newCurrentCell = stack.head
      mazify(stack.tail, newCurrentCell)
    }
  }
...
}


Basic JavaScript quiz app I struggled my way through the first quiz and here are the results.  Since I have some experience in jQuery I really wanted to use only vanilla JavaScript.  I know the code is pretty choppy and there is most likely a lot of room for improvement.

How can I make this code more succinct? What are some better practices that i can implement?

Here is a jsfiddle.

HTML:

How well do you know Matt

    <input type='submit' id='myBtn' value='' />

JavaScript:

var allQuestions = [
{
    question: "What is Matt favorite color?",
    choices: ["Blue", "Black", "Yellow", "Blank", "Clear" ],
    correctAnswer: 4
},
{
    question: "Who is Matt's Favorite fiction Author?",
    choices: ["Brennan Manning", "JD Salinger", "Stephen King", "Jack Kerouac"],
    correctAnswer: 3
},
{
    question: "What is Matt's favorite food?",
    choices: ["Pizza", "Wings", "Mexican", "Rally's"],
    correctAnswer: 0
}
];

var submitBtn = document.getElementById('myBtn');
var currentQuestion = 0;
var tally = 0;

var quizForm = document.getElementById('quiz');
var question;
var choices;
var radioButtons = document.getElementsByName('radioOption');
var index = 0;

function firstFunc() {
    if (currentQuestion === 0) {
        submitBtn.value = "Start Quiz";
    }
}

function askQuestion () {
    choices = allQuestions[currentQuestion].choices;
    question = allQuestions[currentQuestion].question;
    if (currentQuestion < allQuestions.length) {
        submitBtn.value = "Next";
        quizForm.innerHTML = "
" + question + "
";
        for (var i = 0; i < choices.length; i++) {
            quizForm.innerHTML += "<input type='radio' name='radioOption' value='" + choices[i] + "'/>" + choices[i] + "";
        }
        if (currentQuestion == allQuestions.length - 1) {
            submitBtn.value = "Submit";
        } else if (currentQuestion > allQuestions.length - 1) {
            calcQuiz();
        }
    }
}

function lookForChecked() {

    if (radioButtons.length > 1) {

            var checked = false;
        for (var i = 0; i < radioButtons.length; i++) {
            var selection = radioButtons[i];

             if (selection.checked) {

                var index = [i];
                if (i === allQuestions[currentQuestion].correctAnswer) {
                    tally++;

                }
                if (currentQuestion < allQuestions.length -1) {
                    currentQuestion++;

                } else {
                    console.log('you have ended the quiz');
                    calcQuiz();
                   return false;
                }
                break;
            }
        }
        if ($('input[name="radioOption"]:checked').length < 1) {
            alert('Please Make a Selection');
        }
    }
        askQuestion();
}

function calcQuiz() {
    quizForm.innerHTML = "
You have finished the quiz

You scored a total of " + tally + " out of " + allQuestions.length + "
";
    submitBtn.remove();
}
window.onload = firstFunc();
submitBtn.addEventListener('click', lookForChecked);

Design

You could remake this using Object-Oriented-Programming. For example, you could make a Question object, like this.

function Question(description, choices, correctChoiceIndex) {
    this.description = description;
    this.choices = choices;
    this.correctChoiceIndex = correctChoiceIndex;
}

You could then extend it with some methods, like askQuestion. For example, you could do something like this (Using prompt and alert because I'm on mobile.)

Question.prototype.askQuestion = function() {
    return prompt("Choices:\n" + this.choices.join("\n"));
}

You could then supply an additional method, checkAnswer, to see if the user got the answer correct.

Question.prototype.checkAnswer = function() {
    if(parseInt(this.askQuestion(), 10) === this.correctChoiceIndex) {
        alert("You got the question right!");
    }
    else {
        alert("Sorry, wrong answer.");
    }
}

Nitpicks

Some of your naming is not great. For example, firstFunc is an awful name for a function. It doesn't describe the purpose of the function in any way.

Preferably, names for variables/functions/classes should exhibit the following characteristics:

Describe the variable/function/class in detail.
Not have unnecessary abbreviations.
Not be too short.
Not be too long. (Unless you're programming in objective-c.)

Most of your variable names exhibit these characteristics, I just saw a few, like submitBtn that could be expanded to something like submitButton.

Moving on, I saw this line I your code:

var index = [i];

It isn't used anywhere in it's scope, and even if it was used, it would serve no purpose at this point.

Finally, when using the increment, ++, and decrement, -- operators, remember the differences between how they're placed.


Advent of Code #4 in Haskell - Ascending digits with double digit This problem is from Advent of Code day 4 (part 1). The problem is to find the number of ints in the given range satisfying:

all digits are non decreasing
there is at least one group of at least two equal digits in a row

combinations only generates non-decreasing sequences; for example:

λ> combinations 2 ['1'..'3']
["11","12","13","22","23","33"]

The algorithm generates all non-decreasing combinations from ['0'..'9'], then checks that there's at least one repeating character, that there are no leading zeros, and that the number is in range. Running it with the input 125730-579381 correctly prints 2081.

The main things I want to know about are whether there's a way to improve the algorithm, and whether the readability is good.

import Data.List (tails, group)
import Control.Arrow
import Control.Monad

-- all non-decreasing combinations of k from xs
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations k xs = do
  xs'@(x:_) <- tails xs
  map (x:) $ combinations (pred k) xs'

-- return True iff all predicates are satisfied
allF :: [a -> Bool] -> a -> Bool
allF fs x = and $ map ($ x) fs

-- all ints within the range satisfying:
  -- strictly increasing digits
  -- at least one sequence of exactly 2 of the same digit
solve :: Int -> Int -> Int
solve low hi = length . takeWhile (<= hi) . dropWhile (< low) . map read .
  filter (allF [hasDouble, noLeadingZeros]) $ combinations 6 ['0'..'9']
  where hasDouble = any ((> 1) . length) . group
        noLeadingZeros = (/= '0') . head

main :: IO ()
main = do
  (low, high) <- join (***) read <$> second tail <$> span (/= '-') <$> getLine
  print $ solve low high

Disclaimer: I don't know Haskell and I have never used it before.

solve low hi = length . takeWhile (<= hi) . dropWhile (< low) . map read .
  filter (allF [hasDouble, noLeadingZeros]) $ combinations 6 ['0'..'9']
  where hasDouble = any ((== 2) . length) . group
        noLeadingZeros = (/= '0') . head

Instead of running combinations 6 ['0'..'9'] and then chopping off everything which has a zero at the start, generate numbers from 100000..999999 and then convert it to a string. This would eliminate the combinations method.

I was able to make the following conclusions about the algorithm:

if the numbers are sorted from smallest to largest, then it should equal the original number (i.e. they are already sorted from smallest to greatest)
if the numbers with no duplicates does not equal the original number, then it means that there is at least two which were "de-duped", therefore it has two duplicates

I was able to produce the following code:

import Data.List

checkNum num = do return ((sort(show num) == (show num) && (nub (show num)) /= (show num)))
main = do checkNum 4222211

This checks if the sorted number (as a string) is equal to itself (which means that it is increasing correctly), and nub removes all duplicate digits.


Processing requests using the user's time zone I have an application in Ruby on Rails (3.2) and I want all the requests to take into account the currently logged in user's time zone. Also, I want to have a helper that will let me display date time fields using user's time zone.

I follow this approach:

Inside ApplicationController I hook an around_filter like this:

around_filter :user_time_zone, if: :current_user

The implementation of user_time_zone is:

def user_time_zone(&block)
  Time.use_zone(current_user.time_zone, &block)
end

In ApplicationController as well, I have a helper method like so:

helper_method :datetime_users_time_zone

with implementation:

def datetime_users_time_zone(datetime, user = nil)
  time_zone = user.present? ? user.time_zone : Time.zone_default
  datetime.in_time_zone(time_zone)
end

Is this good practice and implementation? What might be the gotchas? If I were to implement this for Rails 4, what changes should I make?

If your usecase is displaying localized time in views then please handle it in frontend, i.e. using http://timeago.yarp.com/

Handling timezone in backend will be big pain when you try to add caching (you will need to cache same piece of content for each timezone).


Wait for multiple functions to run In my loading scene I want to run multiple functions (IO from the disk) and start the app after they are completed.

This is in my loading class. (Note: This is unity 3d and the public variables to get access to other objects is based on Unity best practices).

public Logger MyLogger;
public Parser MyParser;
// ... more

private int coroutineCount = 0;

void Start()
{
    MyLogger.LogLastMonth(Callback);
    coroutineCount++;

    MyParser.ParseFiles(Callback);
    coroutineCount++;
}

public void Callback()
{
    coroutineCount--;

    if (coroutineCount <= 0)
    {
        SceneManager.LoadScene("GameScene");
    }
}

I do something similar in both Logger and Parser (counting coroutines and decrementing when they finish before invoking the callback received). Is there a better way to do this when I need to expand the number of functions I'm calling?

Your code is not thread-safe on many levels. Even if you replace regular increments/decrements with methods from Interlocked class, you will still need additional synchronization to make sure, that Callback is not called while Start is running.
Term coroutine has a specific meaning in context of Unity, so you should probably use different word to avoid confusion.
I don't know what is the recommended way of doing these things in Unity. In absence of TPL (I assume Unity still uses .Net 3.5), the easiest solution I can think of, that does not require good understanding of threading, is to return WaitHandles from your async methods:

void Start()
{
    var handles = new List<WiatHandle>();
    handles.Add(MyLogger.LogLastMonth());
    handles.Add(MyParser.ParseFiles());
    //etc...
    ThreadPool.QueueUserWorkItem(_ =>
    {
        WaitHandle.WaitAll(handles.ToArray());

        //at this point you might want to dispose handles
        //if you do not plan to re-use them

        //Make sure this call is thread-safe.
        //If it is not, you will have to dispatch this call back to main thread
        // or set some bool field here, and move the call to Update.
        SceneManager.LoadScene("GameScene");
    });
}


Return correct subclass instance, identified by string I have made a function which takes a string which can be any of "triangle", "square" or "rectangle".
Depending on the string I return a pointer to an instance of class Form. My class Form has subclasses Triangle, Square and Rectangle.
My constraints were:

use C++98
no STL library (no map, vector etc)
no friend, and no using namespace std;

#include <iostream>
#define NB_FORMS 3

/**/

class Form
{
  public:
    Form() { }
    virtual ~Form() { }
};

class Square : public Form
{
  public:
    Square() { std::cout << "Squareee!" << std::endl; }
     static Form *createForm(void)
     {
       return (new Square());
     }
};

class Rectangle : public Form
{
  public:
    Rectangle() { std::cout << "Rectangleee!" << std::endl; }
    static Form *createForm(void)
    {
      return (new Rectangle());
    }
};

class Triangle : public Form
{
  public:
    Triangle() { std::cout << "Triangleee!" << std::endl; }
    static Form *createForm(void)
    {
      return (new Triangle());
    }
};

struct        s_makeForms
{
    std::string        formName;
    Form            *(*makeForm)();
};

/* */

Form *func(std::string name)
{
  struct s_makeForms allForms[3] =
  {
      {"triangle",  Triangle::createForm},
      {"rectangle", Rectangle::createForm},
      {"square", Square::createForm}
  };
  for (int i = 0; i < NB_FORMS; i++)
  {
    if (name == allForms[i].formName)
      return (allForms[i].makeForm());
  }
  return (NULL);
}

int main()
{
  Form *myform;

  if (!(myform = func("square")))
  {
    std::cerr << "wrong name" << std::endl;
  }
  delete myForm;
}

Use all the power of the standard library
In your post on StackOverflow, you mentioned that you couldn't use std::map because you were not allowed to use it. Outside of the classroom, you should not limit yourself this way, and instead use the appropriate functions from the standard library that help you write concise and efficient code. The function func() could look like:
Form *func(std::string_view name)
{
    static const std::unordered_map<std::string_view, std::function<Form*()>> forms = {
        {"triangle",  []{return new Triangle;}},
        {"rectangle", []{return new Rectangle;}},
        ...
    };

    if (auto found = forms.find(name); found != forms.end()) {
        return found->second();
    } else {
        return nullptr;
    }
}

And instead of raw pointers, you should probably return std::unique_ptr<Form>.
In the rest of the review I'm going to assume you are limited to what you can use.
Prefer using = default
It's usually best to let the compiler generate default constructors, destructors and other operators. In some cases, you have to explicitly tell it to add one of those, for example when you want to ensure the destructor of Form is virtual. In that case, use = default instead of {}:
class Form
{
public:
    virtual ~Form() = default;
};

Use \n instead of std::endl
Prefer using \n instead of std::endl, the latter is equivalent to the former but also forces a flush of the output, which might be bad for performance if you are printing a lot.
Avoid unnnecessary parentheses and void
You can simplify the createForm() functions a bit:
static Form *createForm()
{
    return new Square;
}

The unnecessary parentheses and void in the argument list are just unnecessary distractions here.
Move s_makeForms into func()
You can move the definition of struct s_makeForm into func(), so it doesn't clutter the global namespace. In fact, you don't even have to give this struct a name, you can write:
Form *func(std::string &name)
{
    struct {
        std::string name;
        Form *(*createForm)();
    } forms[] = {
        "triangle", Triangle::createForm},
        ...
    }

    ...
}

Prefer const std::string & when passing string arguments
To avoid unnecessary copying of strings, prefer passing strings as const references:
Form *func(const std::string &name)
{
    ...
}

Avoid having to #define NB_FORMS
You can get the size of the array allForms in various ways, the typical trick that works both in C and all versions of C++ is:
struct ... allForms[] = {...};
size_t numForms = sizeof allForms / sizeof *allForms;

for (size_t i = 0; i < numForms; ++i)
{
    ...
}

You can also use a range-based for-loop to iterate over the array:
struct ... allForms[] = {...};

for (auto &form: allForms)
{
    if (name == form.formName)
        return form.makeForm();
}

Memory leak
There is a memory leak in your program, since you forgot to call delete myform. These kinds of errors can be avoided by using smart pointers, such as std::unique_ptr.


Print out symmetric matrix from compactly stored array I have an array of the form (3x3 case as an example)
$$A = [a_{11}, a_{12}, a_{22}, a_{13}, a_{23}, a_{33}] $$
corresponding to the symmetric matrix
$$\begin{pmatrix} a_{11} & a_{12} & a_{13}\\ a_{12} & a_{22} & a_{23} \\ a_{13} & a_{23} & a_{33} \end{pmatrix}$$
I want to print out this very matrix (in general of size NxN) given the array A (in general of length N*(N+1)/2) in a nice way.
My approach was
void print__symm_matrix_packed(double* arr, int N){

  int idx2 = 0;

  for(int i=0; i<N; i++){
    printf("(");

    int idx1 = i;

    for(int j=0; j<N; j++){
      if(j < i){
        printf("%f ", arr[idx2 + j]);
      } else {
        printf("%f ", arr[idx1]);
      }
      idx1 += j+1;
    }
    idx2 += i+1;
    printf(")\n");
  }
}

Is there room for some elegant improvement?

I think it the following is a good approach:
//use lowercase on non constant values
void print_symmetric_packed_matrix(double* compact_matrix, int n)
{
    const int entries = N*N;
    for (int i = 0; i < entries;)
    {
        //i++ here avoids i != 0 each iteration
        printf("%f ", compact_matrix[i++]);
        if (i % N == 0) printf("\n");
    }
}

I hope it helped you.


Get property value from object tree in a recursive way Consider the following structure,

let condition = { and: [ { id: 3 }, { pageId: '1' } ] }

I want to get the id property value in a recursive way, it can be also nested inside other conditions.

for example the structure could be like that

let condition = {or: [{ and: [ { id: 3 }, { pageId: '1' } ] }, {age: 10}]}

I ended using this but I don't like the final syntax

  function getIdConditionValue(cond) {
    if (isArray(cond.and)) {
      return map(cond.and, getIdConditionValue);
    } else if (isArray(cond.or)) {
      return map(cond.or, getIdConditionValue);
    }
    if (cond.id) return cond.id;
  }

const id = getIdConditionValue(condition).filter(x => x)[0];

It is working, but I would like to remove .filter(x => x)[0] part from the calling function, which I added because the returned value would be like this [1, undefined].

Given the map() function used at the question having the same signature as jQuery.map() function used at the question, in order to avoid chaining .filter() to get the value at index 0 of the returned, you can use destructuring to assign id to the value at index 0 of the array returned from the function.

function getIdConditionValue(cond) {
  if (Array.isArray(cond.and)) {
    return $.map(cond.and, getIdConditionValue);
  } else if (Array.isArray(cond.or)) {
    return $.map(cond.or, getIdConditionValue);
  }
  if (cond.id) return cond.id;
}

var condition = {
  or: [{
    and: [{
      id: 3
    }, {
      pageId: '1'
    }]
  }, {
    age: 10
  }]
}

const [id] = getIdConditionValue(condition);

console.log(id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

For Loash and Underscore signatures of map() signature (each library's _.map() returns an array having two elements, the fist is the expected result, the second undefined)  you can use

const [[id]] = getIdConditionValue(condition);

For an alternative recursive solution you can create a function that accepts an object and a property name for parameter, utilizes the recursive replacer function of JSON.stringify() and JSON.parse(). If the property name is found during recursive iteration of property names of the object passed, a parameter of an immediately invoked arrow function declared as undefined is set to the property value, else undefined is returned from the function.

const condition1 = {and: [{id:3}, {pageId:'1'}]};
const condition2 = {or: [{and: [{id: 3}, {pageId: '1'}]}, {age: 10 }]};
const condition3 = {and:[,,]};
const condition4 = {and:{or:[]}};
const condition5 = {or:[{or:[{id:1}]}]};

const getObjectPropertyValue = (o, prop) => (result =>
  (JSON[typeof o === 'string' ? 'parse' : 'stringify'](o, (key, value) =>
    key == prop ? (result = value) : value), result))(void 0);

let prop = 'id';

const id1 = getObjectPropertyValue(condition1, prop);

console.log(id1);

let condition2json = JSON.stringify(condition2);

const id2 = getObjectPropertyValue(condition2json, prop);

console.log(id2);

const id3 = getObjectPropertyValue(condition3, prop);

console.log(id3); // `undefined`

const id4 = getObjectPropertyValue(condition4, prop);

console.log(id4); // `undefined`

const id5 = getObjectPropertyValue(condition5, prop);

console.log(id5);


jQuery plugin for ajax select fill I've created my first jQuery plugin, so please try to understand :)

My plugin code looks like so:

(function($) {
$.fn.ajaxSelect = function(options) {
    var $this = this;
    //options
    var settings = $.extend({}, defaults, options);
    //disable select
    if ($.ui.selectmenu && settings.selectmenu && settings.disableOnLoad) {
        $this.selectmenu('disable');
    }
    //ajax call
    $.ajax({
        type: settings.type,
        contentType: settings.contentType,
        url: settings.url,
        dataType: settings.dataType,
        data: settings.data
    }).done(function(data) {
        var n = data.d || data;
        var list = "";
        $.each(n, function(i) {
            list += '<option value=' + n[i].Id + '>' + n[i].Nazwa + '</option>';
        });
        $this.filter("select").each(function() {
            $(this).empty();
            $(this).append(list);
            if ($.ui.selectmenu && settings.selectmenu) {
                $this.selectmenu();
            }
        });
        settings.success.call(this);
    }).fail(function() {
        settings.error.call(this);
    });

    return this;
};

var defaults = {
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: '/echo/json/',
    dataType: 'json',
    data: null,
    async: true,
    selectmenu: true,
    disableOnLoad: true,
    success: function() {},
    error: function() {}
};
})(jQuery);

Demo of usage is available at http://jsfiddle.net/Misiu/ncWEw/

What I was trying to accomplish:

Select multiple elements at one time
Filter only selects from selected items (in case selector would select other elemnts)
Makes only ONE request to server
First build option string and then append it instead of adding items in loop
Specify 2 callbacks: one for error and second for success

I think that it would be better to use more of deferred objects, but I don't have idea how.
Any improvements and hints are welcome :)

Your demo throws errors in console, something about uniqueId in ui.selectmenu.

Anyway:

You can expose $.ajax deferred so someone may use all features of jQuery.Deferred which is already there.
Call success callback with data as argument.

settings.success.call(this, n);

If you do not want to do anything special in case of failure, and just want to provide this to error callback, you do not have to create closure there.

.fail( settings.error );

..., unless you want to hide other rejection arguments.
Do not use each if for do the same (for performance reason):

for( var index = 0; index < n.length; index ++){
  list += '<option value=' + n[index].Id + '>' + n[index].Nazwa + '</option>';
}

Personally I don't like single char variable names, as they are really painful for future development

Instead of $(this).empty();$(this).append(list); you can simply use $(this).html(list);
You can expose jQuery.Deffered, for example as this.promise = $.ajax(..., example in here http://jsfiddle.net/dhRRN/5/
I would suggest also applying received options to ajax call, so your plugin's user could also alter request itself.


Find all letter Combinations of a Phone Number The task

is taken from LeetCode

  Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A
  mapping of digit to letters (just like on the telephone buttons) is
  given below. Note that 1 does not map to any letters.

  Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

  Note:

  Although the above answer is in lexicographical order, your answer could be in any order you want.

My solution

(I've been told I should provide additional information to my solution otherwise I get downvoted.)

is based on backtracking. Why I choosed that approach? Well, whenever you encounter a task where you have to combine or permutate things, then backtracking is a possible approach.

But if you know a better one, then please go ahead. Otherwise I only got generic questions to my code: Can you make it faster, cleaner, more readable, etc.?

Also I'm interested in functional programming. So, if you got a good functional approach, feel free to post it here, too. Other than that, I'm always interested in a different perspective. So, if you got a fancy or conservative approach, please feel free to post them here.

Imperative approach

/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function(digits) {
  if (digits === '') { return []; }
  const strDigits = {
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz',
  };

  if (digits.length === 1) { return [...strDigits[digits]]; }
  const res = [];
  const combine = (cur, n) => {
    if (cur.length === digits.length) {
      res.push(cur);
      return;
    }

    [...strDigits[digits[n]]].forEach(x => {
      combine(cur + x, n + 1);
    });

  };

  combine('', 0);
  return res;
};

Functional approach

/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function(digits) {
  if (digits === '') { return []; }

  const strDigits = {
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz',
  };

  const combine = (cur, n) => cur.length === digits.length
    ? cur
    : [...strDigits[digits[n]]].flatMap(x => combine(cur + x, n + 1));

  return combine('', 0);
};

whenever you encounter a task where you have to combine or permute things, then backtracking is a possible approach.

True. It is not necessarily the best though (in fact it is rarely the best).

In this particular case, the problem naturally maps to finding the next combination. In turn, it is no more than an increment of a number in some fancy numbering system. In your example, the minimal possible string is ad. Subsequent increments yield ae, then af, then ('f' + 1 is d and a carry bit does carry) bd, etc.

Consider implementing the increment/next method directly. The space complexity will definitely benefit; and it is trivial to convert into a generator. The time complexity is likely to also benefit, depending on the use case.

PS: thank you for posting your train of thoughts.


Storing a version number in a Python project If I have this simple structure:

$ tree
.
└── project
    ├── __init__.py
    └── my_script.py

where I want to define __version__ in __init__.py (this allows setup.py, in the parent directory, to import project.__version__):

$ cat __init__.py
# -*- coding: utf-8 -*-

__version__ = "0.1"

Now, I also want to use the value stored in __version__ from other scripts (possibly in subdirectories). I can write this in my_script.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __init__ import __version__

print(__version__)

It works, but looks so ugly. Is this really the way to do that?

EDIT:

The from . import __version__ unfortunately doesn't work:

$ ./my_script.py
Traceback (most recent call last):
  File "./my_script.py", line 4, in <module>
    from . import __version__
SystemError: Parent module '' not loaded, cannot perform relative import

A better approach is to install your script using a setuptools entry_point and let the argparse handle the parameter parsing.  Your project would look something like:
.
├── myproject
│   ├── __init__.py
│   └── cli.py
└── setup.py

Your setup.py would look like:
import setuptools

import myproject

setuptools.setup(
    name='myproject',
    version=myproject.version,
    description='Does stuff',
    url='https://github.com/me/myproject',
    packages=['myproject'],
    entry_points={
        'console_scripts': ['my-script = myproject.cli:entry_point'],
    },
)

When you install your package using pip, it will install a command line script named my-script somewhere like /usr/local/bin.  The command line script will load your package and any requirements, then run the entry_point function in your cli module.  So let's look at that module:
import argparse
import logging

from . import version

def entry_point():
    parser = argparse.ArgumentParser(
        description='Something ... something short',
        epilog='''Bacon ipsum dolor amet occaecat labore qui, ad
                  veniam boudin capicola flank. Dolore rump jerky magna
                  sirloin pancetta. Voluptate anim non minim nostrud ham.
                  Excepteur kevin turkey officia kielbasa pastrami ad ham
                  nostrud meatball tongue magna t-bone. Chuck salami mollit,
                  fatback pig velit officia ut. Cupidatat nulla jowl, tail
                  chicken occaecat excepteur pig beef salami non. Kevin
                  cupim bresaola filet mignon enim.''')
    parser.add_argument('--verbose', '-v', action='count',
                        help='increase verbosity.  Specify multiple times '
                             'for increased diagnostic output')
    parser.add_argument('--version', action='version',
                        version='%(prog)s {}'.format(version),
                        help='show the version number and exit')

    args = parser.parse_args()
    # do stuff here

if __name__ == '__main__':
    entry_point()

The argparse module handles the --version and --help arguments for you.  Since your code is installed and loaded as a proper package, you can use relative imports.  Of course, you are free to use import myproject as well.
I usually do my __init__.py file a little differently.  I follow the what the standard sys module does:
version_info = (0, 0, 0)
version = '.'.join(str(c) for c in version_info)

This makes it possible to use version_info to compare against the numeric version like version_info > (1, 0) which has some nice benefits.
Here's an example of the package in action:
$ python3.4 -mvenv env
$ env/bin/python setup.py install
$ env/bin/my-script --help
usage: my-script [-h] [--verbose] [--version]

Something ... something short

optional arguments:
  -h, --help     show this help message and exit
  --verbose, -v  increase verbosity. Specify multiple times for increased
                 diagnostic output
  --version      show the version number and exit

Bacon ipsum dolor amet occaecat labore qui, ad veniam boudin capicola flank.
Dolore rump jerky magna sirloin pancetta. Voluptate anim non minim nostrud
ham. Excepteur kevin turkey officia kielbasa pastrami ad ham nostrud meatball
tongue magna t-bone. Chuck salami mollit, fatback pig velit officia ut.
Cupidatat nulla jowl, tail chicken occaecat excepteur pig beef salami non.
Kevin cupim bresaola filet mignon enim. Kielbasa non occaecat flank t-bone ad,
sunt in tail esse deserunt id duis. Ut boudin turducken, pariatur labore
veniam lorem proident culpa laborum. Hamburger swine sunt aliqua, et bacon
shoulder jerky cillum. Meatloaf sed pork belly, dolore corned beef in
consectetur enim ball tip. Fugiat ribeye eiusmod sirloin ground round boudin
shoulder voluptate, reprehenderit tongue landjaeger hamburger. Fatback nisi
occaecat, bacon brisket consequat filet mignon fugiat laboris turducken eu. Ad
tempor frankfurter reprehenderit est corned beef voluptate.
$
$ env/bin/my-script --version
my-script 0.0.0

Then to run myproject/cli.py as a standalone script:
$ python -m myproject.cli --version
cli.py 0.0.0


Is this a proper use of a services project and an ASP.NET MVC controller? I'm a little unsure as to what code belongs in the services and what belongs in the controllers.

Lets say I'm creating a website that requires a fine grained level of permissions (e.g. a user has permissions based on their user level (if they're currently logged in) determining whether they can view, edit, add entities and each entity has it's own set of requirements).

The process is pretty much the same for all entities:

Get the current user, either a registered one or an anonymous one
Get the requested entity

Check that it is not null
Check it isn't locked by the system

Check that the user has permissions to view/edit on the entity, as well as all parent entities

So, what should go where?

Right now, my controller makes a call to the service to get the entity and passes in the user (or null for anonymous).

The service makes a call to the repository which gets the entity by the id. Then it makes sure that the user has permission to view it. The code is basically:

// Controller
public ActionResult Get(int id)
{
    string error;
    var entity = EntityService.Get(id, GetUser(), out error);
    if(entity == null)
      // Display error
    else
      // Display entity
}

// Service
public Entity Get(int id, User user, out string error)
{
   var entity = Repository.Get(id);
   // null check
   // permissions check
   // if it passes, return the entity, otherwise assign error and return null
}

I don't really like this way of doing it because if I need to do something like redirect the user or display a custom view, I can't just return an error string, I need an enum or something to tell me exactly why the Get failed so I can handle the case properly. Plus (and I'm not sure if this is actually considered a bad thing) whatever is going on in the services method is hidden from the controller.

Any suggestions on a better design?

My first instinct is to suggest using built-in ASP.NET Roles. This is handled at the ASP.NET level, so in general you can redirect to the appropriate View. You may have roles for 'Anon' 'Read' and 'ReadWrite' and possibly more. This will help with the first pass authorization, not at the specific database record level, but at a high level based on user type, aka role. However, its not required and the per record, per user access will work just as well.

If you have specific access requirements on a 'per record, per user' basis, you have a couple options.

A) Do what you're doing now, pass the User object to the Services layer, and let the services sort it out and return an appropriate error code. In this case, the service probably selects all of the data required to service the request, so if you expect a high level of authorization failures, this is probably not ideal because you'll waste a lot of database IO on requests that are going to fail. If in your list views, you arleady eliminate records the user doesn't have access to, and are your record level security is to prevent people from Uri snoopting (/Entity/Detail/#### for example) this might be sufficient.

B) Implement a method or two in your services layer which accepts a UserID and an EntityID. It then does the minimum database selection to determin if the UserID provided has access to the EntityID and it simply returns true/false. This is a good option if you expect that high number of requests for entities will fail authorization, since in the failed instances, you'll only select a few bits of data from the database and not the entire request; however, for requests that are permitted, you end up doing two selections. Only you can decide if this is worth it or not. But it does make the code a bit more simple:

if(! services.UserEntityAccess(userID, entityID))
{
    return View("NoAccessView");
}

return View(services.ReadEntity(entityID));

C) Hybrid of A and B, when you initialize a new instance of your service layer, make sure that your User object is a parameter in the constructor of the service, then your service can is always operating from within the "context" of a specific user. This is probably the way I would go, and internally, you can decide which of option A or B works best, based mostly on how many failed authorizations you expect, the advantage here is that if you guess wrong, it's easy to change, because its handeled internally to the class, and you wont need to change any calling code.

public ActionResult Get(int id)
{
    var svc = new ServicesLayer(GetUser());
    var entResponse = svc.GetEntity(id);

    if (entResponse.Error != null)
    {
        return View("ErrorView",entResponse.Error);
    }

    return View(entResponse.Entity);
}


Calculating shopping cart discounts I have a method that checks to see if a hash of given items should have discounts applied and if so, determines and returns the discount:

def get_discounts
  @items.each do |name, attr|
    @specials.each do |special|
      while name == special.sale_item && attr[:quantity] >= special.quantity
        @discounts << special.discount
        attr[:quantity] = attr[:quantity] - special.quantity
      end
    end
  end
  determine_discount
end

def determine_discount
  if @discounts.empty?
    @discounts = 0
  else
    @discounts = @discounts.inject(:+)
  end
end

This works perfectly, but is there a more concise way to write it?  I'm looking especially at the two each loops.  I'm also a bit iffy about the while loop - it was an if statement (if name == special.sale_item) but it felt like too much so I combined it into the while loop.

I agree with both of your suspected issues:

Pointless iteration through @items hash: As you suspected, iterating through all entries of a hash defeats the purpose of a hash.  That takes O(I * S) time — the number of items times the number of specials.   Why not iterate through @specials, then look up the item by name?  That's only O(S).
while loop: The loop can be replaced with arithmetic.

In addition, I would like to point out some more problems:

Surprising side-effect in getter: By convention, any method named get_*() is assumed to have no side-effects.  However, get_discounts() alters @items, reducing their quantity.  If that is intentional, you should rename the method to apply_discounts() or something even more suggestive that there is a side-effect.
Abuse of instance variable: @discounts is assumed to be pre-initialized to an empty array before get_discounts() is called.  get_discounts() populates the array, then calls determine_discount(), which converts it into a scalar.  That indicates that @discounts is not storing the state of the object, so using an instance variable for that purpose is abuse.

Here is a revised version of the code:

def get_discounts
  discount = 0
  @specials.each do |special|
    if item = @items[special.sale_item]
      multiples = (item[:quantity] / special.quantity).floor
      discount += multiples * special.discount

      # Suspicious side-effect...
      # item[:quantity] -= multiples * special.quantity
    end
  end
  return discount
end


Node secure randomness implementations I'm trying to generate secure randomness in Node as a personal challenge. I was wondering if the following implementations are correctly random or they have some flaws.

const crypto = require('crypto');

const secureRandomFloat = (bytes = 6) => {
  const size = Math.pow(2, bytes * 8);
  const hexString = crypto.randomBytes(bytes).toString('hex');
  const randInt = parseInt(hexString, 16);
  return randInt / size;
}

export const secureRandomIntRange = (min, max) => {
  const range = max - min; // max is the first not included integer [min, max)
  if (range > Number.MAX_SAFE_INTEGER) return null;
  // use an amount of bytes that will cover the range we need
  const bytes = Math.ceil(Math.log(range) / Math.log(256));
  const size = Math.pow(2, bytes * 8);
  // this is the "tail" of possible numbers. Using them that would
  // give us more chances to get lower values when using modulo
  const excess = size % range;

  let validRand = false;
  let hexString;
  let randInt;
  while (!validRand) {
    hexString = crypto.randomBytes(bytes).toString('hex');
    randInt = parseInt(hexString, 16);
    validRand = randInt + excess < size;
  }

  return min + randInt % range;
}

const secureRandomChoice = arr => {
  // This is to check that the "arr" is iterable, like an array
  // or a string, etc.
  if (arr == null) return null;
  if (typeof arr[Symbol.iterator] !== 'function') return null;
  if (!arr.hasOwnProperty('length')) return null;

  // use an amount of bytes that will cover the range we need
  const bytes = Math.ceil(Math.log(arr.length) / Math.log(256));

  const randIdx = secureRandomIntRange(0, arr.length);
  if (randIdx === null) return null;
  return arr[randIdx];
}

I've done some testing with a million iterations and results seem to be random, but I don't know if I'm missing something.

Are these implementations going to give me pseudo-randomness?

Culling

@Blindman67 has commented that culling, which I do in the while loop at secureRandomIntRange, is not going to give me random values. I don't have a strong argument to say that culling will give me random numbers, but I don't see why it won't.

I used culling because I remembered once I needed to generate random points in a sphere. To do that I took a random point in a cube (much simpler), and discarded the point if it was out of the sphere. I think it gave me a random distribution of points in the sphere.

I tried to apply this same idea to this problem. If I have 1 byte I can generate 256 possible combinations at random, say from number 0 to 255. If I wanted to select an integer from 0 to 99 (100 possible numbers), the naive way using modulo would give me the following relations:

randomByte:     0   1   2 ... 99 100 101 ... 199 200 201 ... 254 255
secureRandInt:  0   1   2 ... 99   0   1 ...  99   0   1 ...  54  55

But that way all numbers from 0-55 can be drawn from 3 different bytes, whereas numbers from 56-99 can only be drawn from 2 different bytes. Then, the way I thought could give me a random distribution in the range was assigning the numbers as follows:

randomByte:     0   1   2 ... 99 100 101 ... 199 200 201 ... 254 255
secureRandInt:  0   1   2 ... 99   0   1 ...  99   x   x ...   x   x

Where x means that the byte is not valid (!validRand) and I have to discard it and get a new byte at random.

In this example, the values for the different variables would be as follows:

range = 100
size = 256
excess = 56
isValid = randInt + excess < size
// isValid = randInt + 56 < 256 --> isValid = randInt < 200
// T for true and F for false
randomByte:  0   1   2 ... 99 100 101 ... 199 200 201 ... 254 255
isValid:     T   T   T ...  T   T   T ...   T   F   F ...   F   F

Do you think that approach is invalid to get random numbers?

secureRandomIntRange

Scheme

Basically what you generated with painstaking work is to create an implementation of the Complex Discard Method described in section A.5.2. That's a known secure scheme, so kudos for that.

I don't like the way bytes is calculated in the secureRandomIntRange function. It probably uses floating point and that may introduce rounding errors.  It took quite a search, but it is easy to calculate the bit length of the integer using Math.clz32(x) where x is the number:

sizeBytes = ((32 - Math.clz32(range)) + 7) / 8;

Note the name change from bytes to sizeBytes.

If you look closely you'll notice that this creates a problem with the value 0, as that is now represented by 0 bytes. Best not to allow ranges of zero elements. And for one element, you may just want to return that element. It also shows that going to 2^32 and over will represent problems, so that's a maximum for the range in this case (which is different from MAX_SAFE_INTEGER because that's 2^53).

Performance

If the range is somewhat higher than half of maxValueOfBytes then the scheme will loop with a 50% certainty. You can somewhat reduce that by deliberately generating a higher amount of bytes. That way you don't need as many bytes from the random number generator in the worst case scenario (at the obvious disadvantage of requiring more bytes for the good scenario). Note thought that you can get very unlucky tossing coins, and you might want to avoid such hickups where the while loop keeps on running.

One little trick that is sometimes performed is to check if range has just one bit set, i.e. is a power of two. In that case you can just randomly generate bits and return those. For instance, if the range is 256, then you can just return a single byte. If the range is 128 then you can generate a single byte, set the most significant bit to 0 and return the result. Basically, if you use precisely as many bits as required then your method degenerates to the Simple Discard Method.

secureRandomFloat

Random float is designed well, except that you might want to check how it handles precision for larger byte sizes. There is likely a maximum integer size as well, so rounding will probably get problematic for larger values of parameter bytes.

secureRandomChoice

It does seem to pick a random from a list of options. So sure, fine.

Code

Already mentioned in passing: there should be more guard checks on the input, especially on the secureRandomIntRange low end values.
Guard statements should result in an exception, not in a function returning null. You're not just propagating the billion dollar mistake, you're adding to it.
Try to avoid floating point operations. I know, I know, that's a stupid requirement for JavaScript, but really it is important because proving that your JavaScript doesn't have any rounding issues might be tricky. Hence the integer calculations performed for sizeBytes above: I'm sure that they work as long as everything is within the maximum size of a 32 bit integer.

That last note is probably going to be contested, especially since floats should not loose precision for calculations that stay within [0, 2^53). So you may want to keep an open mind to different arguments about it.