Navigation script and template Overview:

I'm using the following page template and scripts for navigation. I use a single page that loads menus and context content, and then use ajax or GET variable to load main-div's content, by passing $p variable to a php switch. Browser history is handled whith pushState function.

Main page:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="main-div">
<?php

if (isset($_GET['p'])) {
    $p = $_GET['p'];

} else {
    $p = "main";
}

require_once("assets/switch.php");

?>
    </div>

    <script>
    // Define state on first load
    function defineState() {
            "use strict";
            window.history.replaceState("<?php echo $p ?>", "", "");
        }
    window.onload = defineState;

    function navegacion(dashboard, history) {

       "use strict";
       var urlPath = dashboard;
       var xmlhttp;
       var ActiveXObject;

       if (window.XMLHttpRequest) {
           // code for IE7+, Firefox, Chrome, Opera, Safari
           xmlhttp = new XMLHttpRequest();
       } else {
           // code for IE6, IE5
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function() {
           if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {

                window.scrollTo(0, 0);

                //document.title = "TITLE";

                document.getElementById("main-div").innerHTML = xmlhttp.responseText;

                if(history !== 1) {
                    window.history.pushState(dashboard, "", "index.php?p="+urlPath);
                }

           }
       };
       xmlhttp.open("POST","assets/ajaxapi.php", true);
       xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
       xmlhttp.send("dashboard="+dashboard);

    }

    // Allows for back and forward browswe buttons

    window.onpopstate = function(e){
    "use strict";
    if(e.state){
        navegacion(e.state, 1);
    }
    };

    </script>

  </body>
</html>

ajaxapi.php:

<?php
if (isset($_POST['dashboard'])) {
    $p = $_POST['dashboard'];

} else {
    $p = NULL;
}

require_once("./switch.php");

Could there be any performance or error issues with this code, or how could this script be enhanced?

Thanks.

Security: XSS

You are open to reflected XSS via this payload:

p=foo","","");alert(1)//

Note that the injection takes place into a JavaScript context, which is worse than injections into HTML context because browser filters have a hard time catching it (if you try the payload with eg chrome, it will execute, while "</script><script>alert(1)</script> would not).

Standard HTML-encoding would solve your problem, but OWASP recommends escaping to prevent XSS in a JS context.

Misc

p isn't a great variable name. If it stands for page, just use $page instead (also for the GET index).
As your other variable and function names are in english, navegacion should be as well.


C++: Doubly linked list I have written the code for linked list in c++. It has function list_search(int)
which returns the node of the given number. list_insertfront(int) inserts the first element. list_insert(int) inserts the element. list_delete(int) deletes the element after searching its node.

#include <iostream>

class double_list{
  struct Node{
       int data;
       struct Node *next; //next will hold the address and *next will show value at that address
       struct Node *prev; //prev will hold the address and *prev will show value at that address
    } *head;
 public:
    double_list(){
    head=NULL; // all address in head are initialised to NULL
    }
     void list_insert(int);
     void list_insertfront(int);
     struct Node *list_search(int n){
        Node *node =new Node();
        node=head;
        while(node!=NULL){
            if(node->data==n) return node;
        node=node->next;}
        std::cout<<"No such elementin the list \n";
   }
    void list_delete(int);
    void display();
};
void double_list::list_insertfront(int n){
Node *node=new Node();
node->data=n;
node->next=head;
head=node;
node->prev=NULL;
}

void double_list::list_insert(int n){
   Node *node =new Node();
   Node *temp =new Node();
   node->data=n;
   node->next=NULL;
   temp=head;
   while(temp){
    if(temp->next==NULL){
        temp->next=node;
        break;
        }
        temp=temp->next;
   }
}

void double_list::list_delete(int n){

   Node *node=list_search(n);//to search node of the given number
   Node *temp=new Node();
   temp=head;
   if(temp==node){
    head=temp->next;
   }
   while(node!=NULL){
      if(temp->next==node) temp->next=node->next;
      temp=temp->next;
      return;
       }
}

void double_list::display(){
    Node *node=new Node();
    node =head;
   while(node!=NULL){
        std::cout<<node->data<<" ";
        node=node->next;
    }
}
int main()
{
    double_list list1;
   list1.list_insertfront(5);
    list1.list_insert(1);
    list1.list_insert(6);
    list1.list_insert(7);
    list1.display();
    list1.list_delete(1);
    std::cout<<"\n";
    list1.display();
    std::cout<<"\n";

    return 0;
}

What should I do to improve this code.

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


Password Validation in Python I coded a python solution for the question below. I am after the fastest solution. Also, I would be grateful if you could point out parts that are not pythonic / inefficient.

  Question: A website requires the users to input username and password
  to register. Write a program to check the validity of password input
  by users. Following are the criteria for checking the password:

  At least 1 letter between [a-z]
  At least 1 number between [0-9]
  At least 1 letter between [A-Z]
  At least 1 character from [$#@]
  Minimum length of transaction password: 6

import warnings
password = 'P@ss1234'
def check_number(s):
    ''' Check whether the input string is a digit. '''
    try:
        int(s)
        return True
    except:
        # do not catch error
        return False
def check_validity(pw):
    ''' Return True if input pw is valid, and return False if invalid.'''
    special_chars = ['$','#','@']
    if isinstance(pw,str): pw=list(pw) # I could have appointed to a diff var name
    else: warnings.warn('Password has to be a string object.')
    res = False
    valid_dict={'small_let':False, 'num':False, 'special_chars':False,
                'cap_let':False, 'len':False } # is using a dict efficient?
    if len(pw)>= 6: valid_dict['len']=True
    for i in pw:
        if i.islower(): valid_dict['small_let'] = True
        if i in special_chars: valid_dict['special_chars'] = True
        if i.isupper(): valid_dict['cap_let'] = True
        if not valid_dict['num']:  valid_dict['num'] = check_number(i)
    if all(valid_dict.values()): res = True
    return res

print check_validity(password)

P.S: I am not interested in a module / package that can do this faster or more securely. There does not actually exist a website or a username, this is a simple coding exercise.

Also, linked to this post.

You shouldn't use bare excepts, this is as it can prevent things like KeyboardInterrupt.
That's just bad.
password is a better variable name than pw, at first I was quite confused about what it was.
You can return early if you know the password is not valid.
This can save you a lot of checks in your program.
Your program goes through each character and checks if it's one of the four valid groups.
Instead you can check if it shares any items with that set.
If it doesn't it's not valid.
You're creating warnings un-neededly, currently, excluding the cast, the functionality is the same if it's a list.
Instead of a warning you should either raise an error, or return.

This is as if I pass ['P', 'a', '$', '2', 1, 2] it probably shouldn't return True, which it might on a different implementation.
Instead you can either hard limit your input to strings, or check if the contents of the input are strings. Or both.

In short, just change password to a set, and use & with the groups it needs to be a part of.
This can remove the need to make the function check_number, and makes the code much more readable:

import string

def check_validity(password):
    ''' Return True if input pw is valid, and return False if invalid.'''
    if isinstance(password, str) \
            or not all(isinstance(c, str) for c in password):
        return False

    if len(password) < 6:
        return False

    password = set(password)
    checks = [
        set(string.ascii_lowercase),
        set(string.ascii_uppercase),
        set(string.digits),
        {'$', '#', '@'},
    ]

    for check in checks:
        if not check & password:
            return False
    return True

print check_validity('P@ss1234')


Get a stock quote from a web page using F# I want to extract a price for a single index fund, the price of which is available on dynamic web pages.

Being new to this, my original idea was to download the single page of static HTML and get the price from that.  How hard could it be?  Inspired by an article on F# for fun and profit I imagined it would be easy.

Of course, the data isn't in the static page, as anyone who is familiar with web site development knows.  Just look at the huge amount of content on w3schools that describes how a modern page is built.  Much of it is dynamic and runs client code in the browser, like javascript.

Given that a simple HTTP request doesn't work, I opted to use a web browser control.

I found inspiration from these stackoverflow questions: How to use WebBrowser control DocumentCompleted event in C#?, View Generated Source (After AJAX/JavaScript) in C# and C# how to wait for a webpage to finish loading before continuing.

open System
open System.Windows.Forms
open System.Threading
open System.Text.RegularExpressions

let wb = new WebBrowser()
wb.ScrollBarsEnabled <- false
wb.ScriptErrorsSuppressed <- true

let rec GetPrice (wb:WebBrowser) =
    Application.DoEvents()  // Get the browser to do work
//    The following doesn't work
//    while (wb.ReadyState <> WebBrowserReadyState.Complete) do Application.DoEvents()

    let m = Regex.Match(wb.Document.Body.InnerText, """£(?<VIGSCA>\d{3}\.\d{4})[^\d]""")
    if m.Success
    then
        // by definition, a sucessful match is a float32 (Single) so this parse will work
        Single.Parse(m.Groups.["VIGSCA"].Value)
    else
        // it takes several seconds to get a result, let's give the CPU a rest before we try again
        Thread.Sleep 100
        GetPrice wb

let stockURL = Uri "https://www.vanguard.co.uk/uk/portal/detail/mf/overview?portId=9158&assetCode=EQUITY##overview"
wb.Navigate(stockURL)
while (wb.ReadyState <> WebBrowserReadyState.Complete) do Application.DoEvents()

let price = GetPrice wb
printfn "Price is %A" price

wb.Dispose()

Can you suggest improvements?  For example:

More idiomatic f#
Use an event instead of a loop.  This code doesn't work

let downloadComplete = Async.AwaitEvent (wb.DocumentCompleted) |> Async.Ignore
Async.RunSynchronously downloadComplete

An alternative way to download the price that doesn't use a web browser control

These related questions, Use Webbrowser control to get and post data?, How to use System.Windows.Forms.WebBrowser in a web app?, are interesting but don't help.

I have been doing my own research and here is my answer to point 3.

  An alternative way to download the price that doesn't use a web browser control

namespace ExcelVIGSCA

module getPrice =

    open ExcelDna.Integration
    open FSharp.Data

    let saveVIGSCAjson () =
        // Get a copy of the data shape, and save it in a file so that the compiler can type check it.
        // I used http://www.telerik.com/fiddler to find the correct data.
        let url = @"https://www.vanguard.co.uk/uk/portal/GetMFJsonForPortId.js?portId=9158"
        let response = Http.RequestString(url)
        let json = (response.Split('=')).[1]
        System.IO.File.WriteAllText(__SOURCE_DIRECTORY__ + "\VIGSCA.json",json) |> ignore

    // Clearly, VIGSCA.json has to exist at compile time, so saveVIGSCAjson() will have to be have been run during development.
    // This makes the program very fagile.
    type VIGSCAData = JsonProvider<"VIGSCA.json">

    // information about attributes & data types: http://exceldna.codeplex.com/wikipage?title=Reference&referringTitle=Documentation
    [<ExcelFunction(Description = "Price for VIGSCA")>]
    // Excel-DNA needs concrete types for input and output to work: it can't be generic.
    let VIGSCAprice () =
        saveVIGSCAjson() // save the current data.
        let VIGSCA = VIGSCAData.GetSample()
        // The compiler will use the file it has at **compile time** to build up the type data.  This WILL lead to a runtime
        // exception if the type has changed.
        VIGSCA.FundData.Fund.[0].NavPrice.Price.[0].Price

After some research, including this illuminating article, I realised just how complicated web scraping is.  Extracting some data from a static HTML page would have been easy.  But we are dealing with a dynamic web page built on ssl/https connection.

I know that this code is incredibly brittle.  I certainly wouldn't want to give it to anyone else to use.  Consider it a learning exercise, or a hint at what can be done.  To get the web page at all, you have to have previously been to Vanguard's web site and selected the "Individual Investor" option, which presumably saves a cookie to that effect.

My research suggests that there are 2 broad categories of getting data from a dynamic web page.

Use a web browser programmatically (as in the question) and then make sure that the whole page, or at least the bit you are interested in, has downloaded before you extract the data.  The use of a regular expressions seems OK for this.  This is "simple" in the sense that you know what the final page looks like so you know what data to extract.
Use a protocol analyser (like fiddler) and inspect the web page source to work out exactly what request has the data you want.  Then use a tool, like the wonderful FSharp.Data to extract it.  This is definitely more work but you have a better understanding of how the web site is structured so that, hopefully, it is easier to maintain.  It is definitely more focused.

Whatever approach is chosen, knowledge of how these dynamic pages are built (including some familiarity with javascript) is necessary.  Thank goodness for sites like w3schools


ListFind test conditions I am considering

        <input type="checkbox" name="arConfig[3]" value="payout"
            <cfif ListFind(attributes.config[3], "payout") NEQ 0>checked="checked"</cfif>  /> Payout

        <input type="checkbox" name="arConfig[3]" value="points"
            <cfif ListFind(attributes.config[3], "points") NEQ 0>checked="checked"</cfif>  /> Points

        <input type="checkbox" name="arConfig[3]" value="quarter"
            <cfif ListFind(attributes.config[3], "quarter") NEQ 0>checked="checked"</cfif>  /> Quarter

Vs

        <input type="checkbox" name="arConfig[3]" value="payout"
             <cfif ListFind(attributes.config[3], "payout") GT 0>checked="checked"</cfif>  /> Payout

        <input type="checkbox" name="arConfig[3]" value="points"
             <cfif ListFind(attributes.config[3], "points") GT 0>checked="checked"</cfif>  /> Points

        <input type="checkbox" name="arConfig[3]" value="quarter"
             <cfif ListFind(attributes.config[3], "quarter") GT 0>checked="checked"</cfif>  /> Quarter

Which is clearer the NEQ 0 or the GT 0 ?

You don't care what the numeric value here is, so don't test for it. You want a boolean, and I think the listFind() call is semantically boolean itself without the comparison.

So: "neither". Do this instead:

<cfif ListFind(attributes.config[3], "payout")>

Either/any option looks pretty cluttered as it is, so given yer repeating the same string except for the difference of the value, I'd put that lot in a loop over the values too, maybe?


How can I improve this Caesar encryption? I have the following method which encrypts a english text, given the plain text and the desired key:

/// <summary>
/// Encrypts english plain text using user defined key. Range for the key is from -25 to 25.
/// </summary>
/// <param name="plainText"></param>
/// <param name="keyValue"></param>
/// <returns></returns>
public static string encryptTextEng(String plainText,int keyValue)
{
    string encText = "";
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

    for (int i = 0; i < plainText.Length; i++)
    {
        if (plainText[i].ToString() == " ")
        {
            encText += " ";
        }

        for (int j = 0; j < alphabet.Length; j++)
        {
            if (String.Equals(alphabet[j].ToString(), plainText[i].ToString(), StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    encText += alphabet[j + keyValue];
                }
                catch (Exception ex)
                {
                    if (j + keyValue > 26)
                    {
                        encText += alphabet[j + keyValue - 26];
                    }
                    else if (j + keyValue < 0)
                    {
                        encText += alphabet[j + keyValue + 26];
                    }
                }
            }
        }
    }

    return encText;
}

What are good programming practices I am missing here? Also I am not sure about the try/catch part I guess there are better ways to do it? Would it be a good idea to add a switch case which checks if the char it is currently reading is a punctuation character?

You are correct in suspecting that the try/catch is not necessary. Generally speaking, Caesar ciphers are implemented using modular arithmetic. We can determine if a character is alphabetical by simply checking if alphabet contains that character; anything else (whitespace, digits, punctuation, etc.) can just be copied as-is, so neither the second for loop nor the proposed switch are necessary either. Here's an example of how you could simplify your code:

public static string encryptTextEng(string plainText, int keyValue)
{
    string encText = "";
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

    foreach (char c in plainText.ToUpper())
    {
        if (alphabet.Contains(c))
        {
            encText += alphabet[Mod((Array.IndexOf(alphabet, c) + keyValue), 26)];
        }
        else
        {
            encText += c;
        }
    }

    return encText;
}

private static int Mod(int dividend, int divisor)
{
    int remainder = dividend % divisor;
    return remainder < 0 ? remainder + divisor : remainder;
}

I threw the Mod method in there because the modulo operator does not work as you might expect with negative numbers.

As mentioned by Bruno in the comments below, a more performant way of checking if the current character is in alphabet and getting the index of that character would be:

foreach (char c in plainText.ToUpper())
{
    int idx = c - 'A';
    if (idx >= 0 && idx < alphabet.Length)
    {
        encText += alphabet[Mod(idx + keyValue, 26)];
    }
    else
    {
        encText += c;
    }
}


Python function to find all integers between two numbers whose sum of squared divisors is a perfect square Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!
Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number.
The result will be an array of arrays, each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors.

I have a working function as follows, however it does not execute fast enough.
from math import sqrt
def list_squared(m, n):
    def D(x):return sum(i**2 for i in range(1,x+1) if not x%i)
    return [[i,D(i)] for i in range(m,n) if sqrt(D(i)).is_integer()]

I have also tried a for loop instead of list comprehension, using a variable to save the output of the D function so it doesn't get called twice, and it didn't help. I have no experience optimizing code for speed.
from math import sqrt
def list_squared(m, n):
    def D(x):return sum(i**2 for i in range(1,x+1) if not x%i)
    z = []
    for i in range(m,n):
        x = D(i)
        if sqrt(x).is_integer():
            z.append([i,x])
    return z

#Examples
list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]

There is no need to go up to the number to know its factor, going up to the sqrt is enough:

def D(x):
    return sum(i**2 + int(((x / i) ** 2 if i * i != x else 0))  for i in range(1, floor(x ** 0.5) + 1) if not x%i)

That should speed up quite a bit the computation if you are dealing with big numbers


Getting JSON with jQuery, creating a function that displays the data from two separate feeds I have written my first JavaScript program from scratch and am looking for advice to check whether it is efficient and effective or how it could be improved.

        var apiURL = 'https://services.domain.com';

    function dataPlanOutput(countryCode) {
        document.getElementById("dataplan_list").innerHTML = "";
        network_url = apiURL + '/api/v4/countries/' + countryCode ;
        network_new_url = "http://cors.io/?" + network_url;
        $.getJSON(network_new_url, function (networkGroup) {
            $.each(networkGroup.list, function (i, list) {
                var countryName = list.region;
                var networkGroupId = list.networkGroupId;

                function myDataPlan(networkGroupId, countryCode) {
                    data_url = apiURL + '/api/v4/networkGroups/' + networkGroupId + '/plansExt?countryCode=' + countryCode;
                    data_new_url = "http://cors.io/?" + data_url;
                    $.getJSON(data_new_url, function (dataPlan) {
                        $.each(dataPlan.list, function (i, list) {
                            //Price
                            content = '
';
                            var currencyLetter = list.currency;
                            if (currencyLetter == 'USD') {
                                var curencySymbol = currencyLetter.replace("USD", "$");
                            }
                            else if (currencyLetter == 'GBP') {
                                var curencySymbol = currencyLetter.replace("GBP", "£");
                            }
                            else if (currencyLetter == 'JPY') {
                                var curencySymbol = currencyLetter.replace("JPY", "¥");
                            }
                            else if (currencyLetter == 'EUR') {
                                var curencySymbol = currencyLetter.replace("EUR", "€");
                            };
                            content += '' + curencySymbol + list.price + '	';
                            //Data Limits
                            var dataLimit;
                            if (list.dataUnlimited) {
                                dataLimit = 'Unlimited';
                            }
                            else {
                                var dataLimitInKB = list.dataLimitInKB;
                                if ((dataLimitInKB / (1024.0 * 1024.0)) >= 1.0) {
                                    var measure = " GB";
                                    var data = dataLimitInKB / ((1024.0) * (1024.0));
                                }
                                else if (dataLimitInKB / 1024.0 >= 1.0) {
                                    var measure = " MB";
                                    var data = dataLimitInKB / 1024.0;
                                }
                                data = Math.round(data * 100) / 100;
                                dataLimit = data + measure;
                            }
                            content += '' + dataLimit + '	';
                            //Data Length
                            content += '' + list.validityPeriodInDays + '&nbsp;Days	';
                            content += '
';
                            $(content).appendTo("#dataplan_list");
                        });
                    });
                }
                myDataPlan(networkGroupId, countryCode);
                document.getElementById('dataplan_list').innerHTML += '
' + countryName + '
';
            });
        });
    }

Code Cohesion

A great way to simplify code is to break things up so that each section focuses primarily on one specific task. I think your biggest problems with this are in your $.forEach(networkGroup.list loop, in which it appears you are mixing three separate tasks:

getting the symbol
getting the data limit
producing html

Price: getting the symbol

Here's a quick tip to simplify converting the currencyLetter to the currencySymbol. Instead of using a list of if else blocks, it would be best to factor this part of the code out into its own function and use an object to map the keys:

function getCurrencySymbol(currencyLetter) {
  return {
    "USD": "$",
    "GBP": "£",
    "JPY": "¥",
    "EUR": "€"
  }[currencyLetter];
}

This shortens the code, makes it easy to add other currencies, and allows the function to be used in other places.

$.each(dataPlan.list, function (i, list) {
  var currencySymbol = getCurrencySymbol(list.currency); // note you misspell curencySymbol

  //Price
  content = '
';
  content += '' + curencySymbol + list.price + '	';
  //Data Limits
  // ...

Data Limits: getting the data limit

I'd also recommend breaking out the part of code where you find the data limit into its own function for similar reasons:

function getDataLimit(list) {
  if (list.dataUnlimited) {
    return = 'Unlimited';
  }
  else {
    var dataLimitInKB = list.dataLimitInKB;
    var measure;
    var data;

    if ((dataLimitInKB / (1024.0 * 1024.0)) >= 1.0) {
      measure = " GB";
      data = dataLimitInKB / ((1024.0) * (1024.0));
    }
    else if (dataLimitInKB / 1024.0 >= 1.0) {
      measure = " MB";
      data = dataLimitInKB / 1024.0;
    }

    data = Math.round(data * 100) / 100;
    return data + measure;
  }
}

Now the code in the $.forEach loop is focused primarily on generating the HTML which makes it much easier to see what's going on:

$.forEach() {
  //Price
  content += '' + getCurrencySymbol(list.currency) + list.price + '	';

  //Data Limits
  content += '' + getDataLimit(list)+ '	';

  //Data Length
  content += '' + list.validityPeriodInDays + '&nbsp;Days	';
  content += '
';
  $(content).appendTo("#dataplan_list");
}

It would be a good idea to break up the code even more to limit how far the indentation gets. Currently, there are too many things nested inside of each other which adds a lot of complexity.

That all said, this is some pretty intense code for some of your first JavaScript. Nice work!


Calculate gcd of two numbers Following is my code to calculate gcd of two numbers. My intension is not to use any specialised algorithm, just simple maths. Do you see any problem in my solution?

#include <iostream>
#include <algorithm>

int main() {
    int n1, n2;

    std::cin >> n1 >> n2;

    int smaller = min(n1, n2);
    int greater = max(n1, n2);

    if(greater % smaller == 0)
    {
        std::cout << smaller;
        return 0;
    }

    int gcd = 1;

    for (int i = 2; i <= smaller / 2; i++) {
        if(smaller % i == 0 && greater % i == 0)
            gcd = i;
    }

    std::cout << gcd;
    return 0;
}

The code does not account for negative numbers, yet the number type (int) allows them. The program will print 1 for the input -15 10, although 5 is the correct answer.
The GCD is usually positive, but your program will print -10 on the input -10 10.
A function int gcd(int, int) will make it easier to test and re-use.
Since you provided a complete program you probably want to check whether the user actually inputs two numbers and not tree 0.1234 or something else that's not an int.

That being said, thank you for

not using namespace std;
properly indenting your code (you could add braces around the if, though)
using proper names where they were reasonable (n1 and n2 aren't long-lived enough)

I guess that you know that there are better algorithms, so for a simple algorithm like this there is not much to improve. You certainly have to consider negative numbers, though.

Also, some variables are available for the whole scope (n1 and n2), but only used for a short time. Try to limit the scope of a variable as much as possible, as it prevents errors like

for(i = 2; i <= n1 / 2; ++i) // should have been "smaller", whoops


ASCII graphic waveform generator Working on some documentation lately, I had a need to convert a number of asynchronous serial waveforms into ASCII graphics characters.  Rather than draw them by hand, I decided to write a program to do it for me.  I'm interested in a code review, and particularly if there are smarter/shorter ways of coding the class.

#include <iostream>
#include <vector>
#include <string>
#include <bitset>

class waveform
{
public:
    waveform(std::string &s) : data_(s) {}
    std::vector<bool> to_bits() const
    {
        std::vector<bool> bits;
        bits.reserve(data_.size() * 10);
        for (auto &ch : data_) {
            bits.push_back(0); // start bit
            for (int mask=1u; mask != 0x100; mask <<= 1) {
                bits.push_back(ch & mask);
            }
            bits.push_back(1); // stop bit
        }
        return bits;
    }
    friend std::ostream& operator<<(std::ostream& out, const waveform& w) {
        auto bits = w.to_bits();
        bool last = 1;
        for (const auto &b : bits) {
            out << (b ? "+---" : (last ? "+   " : "    "));
            last = b;
        }
        out << '\n';
        last = 1;
        for (const auto &b : bits) {
            out << (b != last ? "|   " : "    ");
            last = b;
        }
        out << '\n';
        last = 1;
        for (const auto &b : bits) {
            out << (b ? (last ? "    " : "+   ") : "+---");
            last = b;
        }
        out << '\n';
        int special = 0x201;
        for (const auto &b : bits) {
            if (special & 1) {
                out << (b ? "  P " : "  S ");
            } else {
                out << (b ? "  1 " : "  0 ");
            }
            special >>= 1;
            if (special == 0)
                special = 0x201;
        }
        out << '\n';
        return out;
    }
private:
    std::string data_;
};

Sample driver

int main()
{
    std::string msg{"ST"};
    std::cout << waveform(msg) << std::endl;
}

Sample output

+   +---+---+       +---+   +---+   +---+           +---+   +---+   +---+   +---
|   |       |       |   |   |   |   |   |           |   |   |   |   |   |   |
+---+       +---+---+   +---+   +---+   +---+---+---+   +---+   +---+   +---+
  S   1   1   0   0   1   0   1   0   P   S   0   0   1   0   1   0   1   0   P

Note that in this diagram, S stands for a start bit, P stands for a stop bit and the 8 data bits are sent least significant bit first.

The OOP design doesn't seem to be doing much for you.  It feels like you could get basically the same effect using just a function.  On the other hand, the operator<< method is basically a state machine, and it looks somewhat nastier than it needs to be.  There is copy-and-paste code, with bits of ASCII art all over the place, and a mini-Turing machine using the magic number 0x201.

Assuming that the to_bits() helper function isn't important to you (I assume it isn't that important, because you wrote #include <bitset> then changed your mind), you could do better by defining a filtering output stream.  Here's my attempt to implement such a thing:

#include <climits>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>

class waveform_ostream : public std::streambuf
{
public:
    explicit waveform_ostream(std::ostream &sink) : sink(sink) {}

protected:
    // Accept a byte of data
    virtual std::streambuf::int_type overflow(std::streambuf::int_type c) {
        output_bit(0, 'S');             // Start bit
        for (int i = 0; i < CHAR_BIT; ++i) {
            output_bit((c >> i) & 1);   // Data bits, LSB first
        }
        output_bit(1, 'P');             // Stop bit
        return c;
    }

    // Flush
    int sync() {
        for (int row = 0; row < 4; ++row) {
            std::string s = lines[row]->str();
            sink << s << '\n';
            lines[row]->str("");
        }
        sink << std::flush;
        return 0;   // success
    }

private:
    bool state = 1;
    std::ostream &sink;
    std::stringstream level[2], risefall, captions;
    std::stringstream *const lines[4] = {
        &level[1],
        &risefall,
        &level[0],
        &captions
    };

    void output_bit(bool b, char caption='\0') {
        level[!b] << ((b == state) ? "    " : "+   ");
        risefall  << ((b == state) ? "    " : "|   ");
        level[ b] <<                          "+---";
        captions  << "  " << (char)(caption ? caption : b ? '1' : '0') << ' ';
        state = b;
    }
};

int main()
{
    waveform_ostream wout(std::cout);
    std::ostream out(&wout);
    out << std::string("ST") << std::flush;
}


Restrict HTML input field to decimal I'd like to restrict user input in a form to a decimal with max two numbers before and 4 after decimal point.

Valid values would be:

50
0.1
1.23
4.5678
12.943

I'm currently doing the following:

$(function() {
  $('input').on('input', function() {
    this.value = this.value
      .replace(/[^\d.]/g, '')             // numbers and decimals only
      .replace(/(^[\d]{2})[\d]/g, '$1')   // not more than 2 digits at the beginning
      .replace(/(\..*)\./g, '$1')         // decimal can't exist more than once
      .replace(/(\.[\d]{4})./g, '$1');    // not more than 4 digits after decimal
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

This works just fine and I'm happy with the JS replace() method of restricting form input (yes I am doing server side validation as well).

I'm mostly interested to know if there is a more concise way to set up the regex(es) so I can reduce and/or eliminate some of the code here.  It seems like I should be able to get the same result with fewer replacements.

I think that you are going about this the wrong way. Rather than thinking of what you should remove, you should think of what you should match.

You are only allowing zero to two digits before a decimal place and so you can use the pattern \d{0,2}.

To include a decimal place you can use the pattern \.?.

And finally you can include zero to four numbers after the decimal place with the pattern \d{0,4}.

If you were to merge these together you will end up with \d{0,2}\.?\d{0,4}.
This has the problem of matching both fullstops, and numbers 6 digits long.

To amend this you can can use the or operator (i.e. |) but you will need to duplicate your regex.
And can result in \d{0,2}\.\d{0,4}|\d{0,2}.?|.?\d{0,4}.

As an alternate to this you can thank that you only include the second half if there is a decimal, and limits the input to two numbers rather than four. Via \d{0,2}(\.\d{0,4})?.

Both the above patterns have their pros and cons. Now you want to match these and so you don't want to use replace. This gives you the option of exec or match. I'd use match due to the simplicity. As you always want the first match and this will always return a match you can simply use something like str.match(//)[0].

This can result in:

$(function() {
  $('input').on('input', function() {
    this.value = this.value.match(/\d{0,2}(\.\d{0,4})?/)[0];
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

This has the problem that, if you enter 12.1234 and then change it to 123.1234 it'll be replaced to 12.
This is as you want it to ignore all numbers after the first two and match the decimal and the last four.
To explain this with the demonstration of capture groups you want (12)3(.1234) and then you'd just join them together.
To achieve this you will want to add capture groups to the above, and use a non-capture group to get empty strings, so (\d{0,2})((?:\.\d{0,4})?).
This doesn't capture the 3, and so to add this we'll need to capture everything apart from a decimal point. [^.]*.
Put this in the above function and you should get what you want. (\d{0,2})[^.]*((?:\.\d{0,4})?).
To properly use this we'll need to use exec rather than match too.

The other problem with the above is as 200_success says:

  For example, if you type 12 into the text field, then place the cursor before the 1, and press x, your code is able to discard just the x.
  Joe's answer, on the other hand, discards the x and everything after it.

You can change the single regex to account for this input x12.
But it won't work with 1x2 either.
To account for this we can use your first replace to limit the input to just numbers and decimals.

And, without adding 200_success' position stuff, should result in:

$(function() {
  $('input').on('input', function() {
    match = (/(\d{0,2})[^.]*((?:\.\d{0,4})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
    this.value = match[1] + match[2];
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

This as far as I can tell works exactly as yours does.
But there is one difference, that I don't think you really want.
If you copy and paste 1234.12345678 into both my input and yours they're different.

Mine results in 12.1234, where yours results in 124.1234678.


HDF Data File Format Validator As part of a personal project I am working on in python, I have started writing a command line utility to convert .hdf files into a JSON file. Before the conversion is done however, I have written some validation code to check that the file exists, has the correct extension, and has the correct basic format.

Here is the code so far

import sys
import h5py
from pathlib import Path

# -------------------------------------------------
# Utility classes defined below.
# -------------------------------------------------
class Validator:
    def print_help_text():
        print("The processor.py utility is designed to take a single argument, the path")
        print("to a NASA EarthData Global Fire Emissions Database GFED4.1s_yyyy.hdf5 file.")
        print("Example - $ ./preprocess.py some/directory/GFED4.1s_2015.hdf5\n")

        print("If a valid file path is passed to the utility it should output individual JSO")
        print("files for each month, that contain data in the format required to train the")
        print("emissions predictor.\n")

        print("By default the new files will be ouput to the same directory that contains")
        print("the script. Alternatively, you can provide a second argument with a path to")
        print("another directory for the output files to be placed in.")

    def valid_hdf_file(path_string):
        valid_extensions = ("hdf","hdf4","hdf5","h4","h5", "he2", "he5")
        if path_string.split(".")[-1] in valid_extensions:
            if Path(path_string).is_file():
                return True
            else:
                print("\n'" + path_string + "' is not a valid file.\n")
                return False
        else:
            print("\nThe input file must be an HDF file with a correct extension.\n")
            return False

    def valid_arguments(arguements):
        args = len(arguements)
        if (args == 2 or args == 3) and arguements[1] != "--help":
            path_to_data = arguements[1]
            return Validator.valid_hdf_file(path_to_data)
        else:
            Validator.print_help_text()
            return False

    def valid_leaf_groups(group, month, hdf_file):
        groups_and_leaves = {
            "biosphere": ("BB", "NPP", "Rh"),
            "burned_area": ("burned_fraction",),
            "emissions": ("C", "DM")
        }
        valid = True
        for leaf in groups_and_leaves[group]:
             full_group = group + "/" + ("%02d" % month) + "/" + leaf
            if full_group not in hdf_file:
                valid = False
                print("Expected group '" + full_group + "' not in HDF file.")
        return valid

    def valid_hdf_structure(hdf_file):
        valid = True
        for group in ("ancill/basis_regions", "lon", "lat"):
            if group not in hdf_file:
                valid = False
                print("Expected group '" + group + "' not in HDF file.")
        for group in ("biosphere", "burned_area", "emissions"):
            for month in range(1,13):
                full_group = group + "/" + ("%02d" % month)
                if full_group not in hdf_file:
                    valid = False
                    print("Expected group '" + full_group + "' not in HDF file.")
                else:
                    valid = valid and Validator.valid_leaf_groups(group, month, hdf_file)
        return valid

# -------------------------------------------------
# Script starts here.
# -------------------------------------------------

if __name__ == "__main__":
    if not Validator.valid_arguments(sys.argv):
        sys.exit()

    filename = sys.argv[1]
    print("Processing - " + filename)
    hdf_file = h5py.File(filename, 'r')

    if not Validator.valid_hdf_structure(hdf_file):
        sys.exit()

    print("Basic structure of hdf file confirmed to conform to GFED4 format.")

Some comments on your code.  In no particular order:

Blocks of text, should be blocks of text

Instead of a bunch of print statements, consider using one block of text, and a loop like:

  def print_help_text():
      help_text = """
          The processor.py utility is designed to take a single argument, the path
          to a NASA EarthData Global Fire Emissions Database GFED4.1s_yyyy.hdf5 file.
          Example - $ ./preprocess.py some/directory/GFED4.1s_2015.hdf5

          If a valid file path is passed to the utility it should output individual JSO
          files for each month, that contain data in the format required to train the
          emissions predictor."

          By default the new files will be ouput to the same directory that contains
          the script. Alternatively, you can provide a second argument with a path to
          another directory for the output files to be placed in.
      """
      for line in help_text.split()[1:-1]:
          print(line.strip())

in is handy

I would prefer to see this:

args = len(arguements)
if (args == 2 or args == 3) and arguements[1] != "--help":
    ...

as this:

if len(arguements) in (2, 3) and arguements[1] != "--help":
     ...

This construct makes it more obvious that you are looking for the length to be one of a specific list of values.

@staticmethod

Your Validator class has a bunch of staticmethods, but they are not declared as such. This is not terribly pythonic.  I suggest you investigate: https://docs.python.org/3/library/functions.html#staticmethod


Registering endpoints and HTTP method for exemption of authentication I have a set of API endpoints where the URL is not standardized, so I could either get "api/auth" or "api/auth/" (may or may not end with "/"). I'm 'registering' the endpoint, plus the HTTP Method that comes in, so I can exclude certain endpoints from having to authenticate.

I've written this piece of code, which has a lot of repetition. Any thoughts?

Private _ExemptEndpoints As New List(Of Tuple(Of String, Method))
Public Sub RegisterAuthExemptEndpoint(endpoint As String, method As Method) Implements IRestAuthenticator.RegisterAuthExemptEndpoint

    Dim endpoints As New List(Of Tuple(Of String, Method))
    Dim allMethods As Boolean = False
    If method = Nothing Then allMethods = True

    Dim ep1
    Dim ep2

    If Not endpoint.EndsWith("/") Then
        ep1 = endpoint
        ep2 = endpoint + "/"
    Else
        ep1 = endpoint.Remove(endpoint.Length - 1, 1)
        ep2 = endpoint
    End If

    If allMethods Then
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.GET))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.POST))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.PUT))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.DELETE))

        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.GET))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.POST))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.PUT))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.DELETE))
    Else
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method))
        _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method))
    End If

End Sub

Basically what you are asking is what can we do about this

    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.GET))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.POST))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.PUT))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method.DELETE))

    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.GET))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.POST))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.PUT))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method.DELETE))

and the contents of the else block as well.

I would create a method that takes the Endpoints ep1 and ep2 as parameters

something like

Public Sub MethodAddingEndpointsToExemptedList(endpoint As String)
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(endpoint, method.GET))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(endpoint, method.POST))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(endpoint, method.PUT))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(endpoint, method.DELETE))
End Sub

and then you can just call this method inside the if block like this

If allMethods Then
    MethodAddingEndpointsToExemptedList(ep1)
    MethodAddingEndpointsToExemptedList(ep2)
Else
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep1, method))
    _ExemptEndpoints.Add(Tuple.[New](Of String, Method)(ep2, method))
End If

You could go a step further and create a list of the endpoints and then use a foreach loop to add them to the list of Exempted endpoints.


Factory object with a dependency on a bean My problem is quite straightforward. I want to build a factory, but the kind of object returned depends on a value read from a bean that is somehow a cache. So of course, I can't call the bean's method from the static method in the factory:

public interface FinderService
{
    public String find(String name);
}

public class GeneralFinderService implements FinderService
{
    @Override
    public String find(String name)
    {
        return "general name";
    }
}

public class NorthFinderService implements FinderService
{
    @Override
    public String find(String name)
    {
        return "place in the north";
    }
}

public class SouthFinder implements FinderService
{
    @Override
    public String find(String name)
    {
        return "guy in the south";
    }
}

public class TestFinder
{
    public static void main(String[] args)
    {
        FinderService finderService = FinderFactory.getFinderService("my location");
        finderService.find("some guy");
    }
}

The options I think I have right now are either make the factory a bean, or use AppContext.getBean to get the bean in the factory. I like neither of them.

Option 1: make the factory a bean

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("finderFactory")
public class FinderFactory
{
    @Autowired
    private LocationCache locationCache;

    public FinderService getFinderService(String location)
    {
        if (locationCache.isInNorth(location))
        {
            return new NorthFinderService();
        }
        else if (locationCache.isInSouth(location))
        {
            return new SouthFinder();
        }
        else
        {
            return new GeneralFinderService();
        }
    }
}

Option 2: get the bean from the appcontext

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class FinderFactory
{
    private static LocationCache locationCache = (LocationCache) new ClassPathXmlApplicationContext().getBean("locationCache");

    public static FinderService getFinderService(String location)
    {
        if (locationCache.isInNorth(location))
        {
            return new NorthFinderService();
        }
        else if (locationCache.isInSouth(location))
        {
            return new SouthFinder();
        }
        else
        {
            return new GeneralFinderService();
        }
    }
}

Is there a better approach?

This looks like example code so I won't go into detail. If I had to choose between the two, I'd go with the first, because you should not be instantiating application contexts like this. There should be ONE application context and it should be created in main or ServletContextListener.contextInitialized or some such initialization method. In general service classes should be singleton scope (as opposed to prototype scope, not related to singleton pattern). Which means they should not be created using new in code.

@Component("finderFactory")
public class FinderFactory { // use standard java braces
    @Autowired private LocationCache locationCache;
    @Autowired private NorthFinderService northFinderService;
    @Autowired private SouthFinderService southFinderService; // use consistent names
    @Autowired private GeneralFinderService generalFinderService;

    public FinderService getFinderService(String location) {
        if (locationCache.isInNorth(location))
            return northFinderService;

        // you don't have to use `else`
        // when `if` is followed by a `return`.
        if (locationCache.isInSouth(location))
            return southFinderService;

        return generalFinderService;
    }
}


Working with forms in Meteor, using selectors for every input I'm trying to work with forms, and just getting a grasp on JavaScript. Basically I'm unsure if there is a more reusable way to handle forms with Meteor/jQuery.

// Creating a new prayer, including the preview
Template.newPrayer.events({
    'click input.save' : function() {
        var title = $("#prayer_title");
        var prayer = $("#prayer");
        var preview_container = $("#prayer_preview");
        var currentUser = Meteor.userId();

        if( currentUser !== null ) {
            Prayers.insert({
                title: title.val(),
                prayer: prayer.val(),
                user: currentUser });

            title.val('');
            prayer.val('');
            preview_container.fadeOut();
        }
    },
    // Auto-updating the preview
    'keyup #prayer' : function() {
        var preview_container = $("#prayer_preview");
        preview_container.fadeIn();
        var preview_formatted = prayer.value.replace(/\n/g,'
');
        $(".preview_text").html(preview_formatted);
    }
});

Is there a better way to do this, should my template be laid out in a different way?

<template name="newPrayer">

{{title}}

    <form id="new_prayer">
        Title
        <input id="prayer_title" class="item" type="text" tabindex="1"/>

        <textarea id="prayer" class="item" name="prayer" tabindex="2" required="true" wrap="soft" autofocus="true" cols="60" rows="10"></textarea>
        <input type="button" class="save item" value="Save Prayer" tabindex="3" />
    </form>

Preview

</template>

Is there a better way to handle form data and form display, without having selectors for every form element, and then having to clear each one?

It seems like I'm not utilizing the full potential of Meteor's reactivity and templating features. Also open to any other pointers/tips with my code. The code works as is.

P.S. This code is just me learning Meteor/JS and the beginning of a small project.

As far as I know, Meteor's reactivity is one-way: changes in data are reflected in the DOM. To go the other way (DOM to data) there's two common methods: 1) grabbing data directly from the DOM when it's needed (i.e. to save it) as you've done above and 2) binding DOM elements to data models, and using the data models for CRUD operations.

1 is simpler to implement, but 2 gives you more control over data-flow, subscriptions, and life-cycles. 2 has plenty of great libraries you can use, so you don't have to reinvent the wheel just to leverage these benefits. Backbone.js is probably the most well known plain-JavaScript library for this sort of thing (also check out Lo-Dash and Exoskeleton if you haven't), but the Meteor ecosystem may have a preferred library for this.


Generating Norwegian National Identification Numbers in Python I've written some Python-code to generate the Norwegian National Identification Numbers.

Being fairly new to Python, I'd really appreciate a review on this code in regards to best practices and style.

import calendar

def is_valid_date(d):
    dd,mm,yyyy = [int(i) for i in [d[:2],d[2:4],d[4:]]]
    days = {
        1: 31, 2: 29 if calendar.isleap(yyyy) else 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
    }

    if yyyy < 1900 or yyyy > 2039: return False
    if mm < 1 or mm > 12: return False
    if dd < 1 or dd > days[mm]: return False

    return True

def get_range(year):
    if year >= 1990 and year <= 1999: return range(500)
    if year >= 2000 and year <= 2039: return range(500,1000)
    return range(0)

def pad(n):
    return '{:03}'.format(n) if n < 100 else n

def generate(d):
    if type(d) is not str or is_valid_date(d) != True:
        raise ValueError('Expected a valid date-string with the form: ddmmyyyy')

    year, dt = int(d[4:]), [int(i) for i in d]
    for i in get_range(year):
        n = map(int,list(str(pad(i))))
        k1 = 11 - ((3*dt[0] + 7*dt[1] + 6*dt[2] + 1*dt[3] + 8*dt[-2] + 9*dt[-1] + 4*n[0] + 5*n[1] + 2*n[2]) % 11)
        k2 = 11 - ((5*dt[0] + 4*dt[1] + 3*dt[2] + 2*dt[3] + 7*dt[-2] + 6*dt[-1] + 5*n[0] + 4*n[1] + 3*n[2] + 2*k1) % 11)
        if k1 < 10 and k2 < 10:
            print ''.join(map(str,dt[:4] + dt[6:] + n + [k1,k2]))

generate('31101990')

I only started Python about 3 months ago, so take my advice with a grain of salt.

(also my first review here :)

PEP8

Try to follow the PEP8 styleguide. Most of the issues I have with this are some whitespace issues. For example:

Two empty lines between import calendar and def is_valid_date(d):
Two empty lines between def pad(n): and def generate(d):
Put some whitespace between variable declaration and operators for increased readability. See dd, mm, yyyy = [int(i) for i in [d[:2],d[2:4],d[4:]]]
Most variable names in the functions don't really have descriptive names. For example d of the is_valid_date or generate
Try not to put if-statements on a single line. (Not sure if this is PEP8, but still a good practice).
None of your functions have docstrings. Documenting your code is great if you need to modify the code later on. Try not to reiterate how the function does something (e.g. explaining the code - that's what the code is for), but rather on why you chose to make this function.

Now on to actual code.

The days dictionary of the is_valid_date function is not being modified. Rather than creating it every time the method is called, perhaps consider making it a global variable, and making it more readable:

days = {
    1: 31,
    2: 29 if calendar.isleap(yyyy) else 28,
    3: 31,
    4: 30,
    5: 31,
    6: 30,
    7: 31,
    8: 31,
    9: 30,
    10: 31,
    11: 30,
    12: 31
}

def is_valid_date(date):
    ...

However another way of doing this, is by using the already imported calendar module. This has the function calendar.monthrange(year, month), which also returns the number of days in the given month. This automatically takes care of leap years or other irregularities. Be wary that this returns 2 values though. To return only the amount of days in a month, you could use calendar.monthrange(year, month)[1].

In pad(n) you return either a formatted string, or a number. This means the there are two return types. You could have it return a string always:

def pad(n):
    return '{:03}'.format(n) if n < 100 else str(n)

or

def pad(n):
    n = str(n)
    if n < 100:
        return n.zfill(3)
    return n

which makes it a bit more readable. However, the pad function is not necessary, as the string.zfill(width) function can take of that for you:

>>>'75'.zfill(3)
'075'
>>>'655'.zfill(3)
'655'
>>>'{:03}'.format(75)
'075'
>>>'{:03}'.format(655)

Both functions only pad if necessary. This means you can do str(n).zfill(3) instead of the entire pad function.

In generate(d), your string type check is not python2 and 3 compatible. See this link for a better answer on string type checking.
The first line of the generate(d) function check for != True. As is_valid_date already returns a boolean value, using not would be a better choice:

def generate(d):
    if not isstring(d) or not is_valid_date(d):
        raise ValueError('Expected date string in format ddmmyyy, but got {}'.format(d))

Some more!

In get_range(year) you use

if year >= 1990 and year <= 1999:
    return range(500)

but this can also be written as:

if 1990 <= year <= 1999:
    return range(500)

or even:

if year in range(1990, 2000):  # more 'human' like.
    return range(500)

... which are both slightly more succinct. The first option (interval comparison) can also be applied in the is_valid_date function:

if 1900 > yyyy > 2039:
    return False
if 1 > mm > 12:
    return False
if 1 > dd > calendar.monthrange(yyyy, mm)[1]:
    return False

Another completely different direction you could go into, is converting the given date string to a datetime object:

from datetime import datetime

birthdate = datetime.strptime('%d%m%Y', datestring)

A nice bonus that comes with this, is that date validation is already done, as it will throw a ValueError if it's given an invalid date, thus eliminating the entire is_valid_date function.

This answer is already long enough, so I will keep it at that :)


Python class hierarchy, extend ancestor data I have a hierarchy of entities that should contain dictionaries with metadata. Any sub-class should inherit its ancestor dictionary and be able to add some key-values (delete inherit keys is not needed). The easiest solution I can think about is this:

class A(object):
    def __init__(self):
        self.doc = A.generate_doc()

    @staticmethod
    def generate_doc():
         return {'a': 0}

class B(A):
    def __init__(self):
        super().__init__()
        self.doc.update(B.generate_doc())

    @staticmethod
    def generate_doc():
        return {'b': 0}

class C(B):
    def __init__(self):
        super().__init__()
        self.doc.update(C.generate_doc())

    @staticmethod
    def generate_doc():
        return {'c': 0}

print(A().doc)  # {'a': 0}
print(B().doc)  # {'a': 0, 'b': 0}
print(C().doc)  # {'a': 0, 'b': 0, 'c': 0}

Is this a good design? Could the update() blocks be implicit maybe? I have more than one document in real code, so that would be nice.

Is this a good design?

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

  Could the update() blocks be implicit maybe?

Yeah, use metaclasses.

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

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

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

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

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

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

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

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

class D(B, C):
    pass

class E(C, B):
    pass

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


Simple jQuery photo slider I'm fairly new to front end web development, but finally felt confident enough to create my own jQuery slider. I wish to receive constructive criticism about my code, how I can optimize any line of code, or ideas on how I can make this a bit more interesting.

$(document).ready(function(){
    /*
    =====================================
        THE SLIDER SCRIPT STARTS HERE
    =====================================
    */
    var i = 0;
    var images = ["Slide/bandera_OK%202.png","Slide/CARAVANA_carta.png","Slide/KANGOO.png","Slide/mochila.png","Slide/RADICAL_OH_03_alta.png","Slide/SILVER_final.png"];

    setInterval(function(){
        var topDiv = $('[data-slide='+'top'+']');
        var topImg = $('[data-slide='+'top'+'] > img');
        var bottomDiv = $('[data-slide='+'bottom'+']');
        var bottomImg = $('[data-slide='+'bottom'+'] > img');

        i++;

        if(i == images.length){
            i = 0;
             bottomDiv.animate({left:'100%'},1500);
            topImg.attr('src',images[i]);
            setTimeout(function(){
                bottomDiv.css('z-index','0');
                topDiv.css('z-index','1');
            },2000);

            setTimeout(function(){
                bottomDiv.css('left','0px');
                bottomImg.attr('src',images[i+1]);
            },2500);

        }
        else if(i % 2 != 0){
            topDiv.animate({left:'100%'},1500);
            bottomImg.attr('src',images[i]);
            setTimeout(function(){
                topDiv.css('z-index','0');
                bottomDiv.css('z-index','1');
            },2000);

            setTimeout(function(){
                topDiv.css('left','0px');
                topImg.attr('src',images[i+1]);
            },2500);
        }
        else if(i % 2 == 0){
            bottomDiv.animate({left:'100%'},1500);
            topImg.attr('src',images[i]);
            setTimeout(function(){
                bottomDiv.css('z-index','0');
                topDiv.css('z-index','1');
            },2000);

            setTimeout(function(){
                bottomDiv.css('left','0px');
                bottomImg.attr('src',images[i+1]);
            },2500)

        }

    },3000);

});
.slider {
position: relative;
}

.slider div {
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
}

.slider div img {
width: 100%;
}

[data-slide='top'] {
z-index: 1;
}

.wrapper {
width: 100%;
height: 100%;
position: relative;
}

The first big things I got on your code, are:

you could define a function instead of passing an anonymous one to setInterval
you could move the dom serarch on the main scope to avoid the repetition on each iteration.
you could optimize the setTimeout function too, defining one on main scope and refer to a variable like selectedImage, instead of using the array.

Defining function, instead of using anonymous on the fly, help to avoid repeating yourself.

The "on the fly anonymous" are very good to cut off the development time, of for very short code or for examples.

But in production, it's better to came back and refactoring it.

Here how I would refactoring:

     $(document).ready(function(){
        /*
        =====================================
            THE SLIDER SCRIPT STARTS HERE
        =====================================
        */
        var i = 0;
        var images = ["Slide/bandera_OK%202.png","Slide/CARAVANA_carta.png","Slide/KANGOO.png","Slide/mochila.png","Slide/RADICAL_OH_03_alta.png","Slide/SILVER_final.png"];
        var topDiv = $('[data-slide='+'top'+']');
        var topImg = $('[data-slide='+'top'+'] > img');
        var bottomDiv = $('[data-slide='+'bottom'+']');
        var bottomImg = $('[data-slide='+'bottom'+'] > img');
        var selectedImage = null;

        function mySlider() {

            i++;

            if(i == images.length){
                i = 0;
                bottomDiv.animate({left:'100%'},1500);
                topImg.attr('src',images[i]);
                setTimeout(raiseTopDiv,2000);

                seletectImage = images[i+1];

                setTimeout(showSelectedImage,2500);

            }
            else if(i % 2 != 0){
                topDiv.animate({left:'100%'},1500);
                bottomImg.attr('src',images[i]);
                setTimeout(raiseBottomDiv,2000);

                seletectImage = images[i+1];

                setTimeout(showSelectedImage,2500);
            }
            else if(i % 2 == 0){
                bottomDiv.animate({left:'100%'},1500);
                topImg.attr('src',images[i]);

                setTimeout(raiseTopDiv,2000);

                seletectImage = images[i+1];

                setTimeout(showSelectedImage,2500)

            }

        }

        function raiseTopDiv() {
            bottomDiv.css('z-index','0');
            topDiv.css('z-index','1');
        }

        function raiseBottomDiv() {
            topDiv.css('z-index','0');
            bottomDiv.css('z-index','1');
        }

        function showSelectedImage() {
            bottomDiv.css('left','0px');
            bottomImg.attr('src',seletectImage);
        }

        setInterval(mySlider,3000);

    });


File parsing and data management This is part of a two-part post (Part 2).

Here, I have two recent projects that parse a file. The first uses a loop that's kind of hard to follow, and the second uses "modes" to decide what to do.

Project 1: A "bookmark manager" for managing URLs easier than a text editor.

The data structures:

typedef struct {
    char *text;
    int length;
} string;

typedef struct {
    string *path;
    string *title;
} url;

typedef struct {
    url **urls; // An array of pointers to urls
    int length;
    int sel_url;
    int modified;
    char *filename;
} urllist;

For the data, I am considering using a linked list instead of an array.

The parser:

void parse_file(char *fname, urllist *ul){
    /* Dumb char-by-char parser that follows the syntax "URL[Title]"
     * [Title] is optional. If left unspecified, then the url is used as
     * a title instead.
     *
     * There's some basic idiot-proofing:
     *
     * 1. Empty lines are ignored (lazy-ignore)
     *    Rather, '\n' and ' ' are skipped if they begin a line.
     *    " http://google.com" is still valid; it'll just take two
     *    iterations to extract anything from it
     *
     * 2. lines beginning in '[' or '#' are fully ignored (full-ignore).
     *    So you can write comments like "#this" or "[this]". The
     *    'comment char' has to be the first character on the line. If
     *    there is a space before it, for example, the parser will think
     *    it's a url.
     */
    int c;
    url *u;
    FILE *f = fopen(fname, "r");

    while(1){
        c = fgetc(f);
        if(c == -1){ /* Check EOF */
            break;
        }
        if(c != '\n' && c != ' ' && c != '[' && c != '#'){
            /* Thanks to the EOF check, I have to add the first char
             * NOW, while I still have it. This is also an opportunity
             * for a sanity check */
            u = new_url();
            string_push_char(u->path, c);
        } else if(c == '#' || c == '['){ /* full-ignore */
            while((c = fgetc(f)) != '\n');
            continue;
        } else { /* lazy-ignore */
            continue;
        }
        while(1){ /* Step through individual line */
            c = fgetc(f);
            if(c == '\n'){
                /* Line ends without title, copy path to title */
                string_copy(u->title, u->path);
                break;
            }
            if(c == '['){
                /* Title specified. */
                while(1){ /* Get it. */
                    c = fgetc(f);
                    if(c == ']'){
                        while(fgetc(f) != '\n');
                        break;
                    }
                    string_push_char(u->title, c);
                }
                break;
            }
            string_push_char(u->path, c);
        }
        url_push(ul, u);
    }
    fclose(f);
}

It works, but I feel like it could be done better. As I said earlier, it's hard to follow. You can tell because it's littered with comments, which I personally try to avoid unless describing a block of code as a whole.

An example file

# Cool sites
http://google.com/search?q=help+with+bananas[Google: banana help]
http://stackoverflow.com[Stack Overflow]

# YouTube stuff
http://youtube.com

Result

[Google: banana help                  ]
 Stack Overflow
 http://youtube.com

http://google.com/search?q=help with bananas

The code sure must be streamlined. I didn't find any better way to review but to rearrange the code and put my notes as comments.

    // First, you test the character against the same condition twice.
    // A more direct way would be to do it once

    if (c == '#' || c == '[') {
        while (fgetc(f) != '\n')
            ;
        continue;
    }
    if (c == ' ' || c == '\n')
        continue;

    // Notice that here you still have `c` intact (so the comment about
    // NOW is misleading). Time to initialize the `url`:

    u = new_url();

    // Since you have the first character of the `u->path`, a correct
    // idiom is a `do {} while ();` loop:

    do {
        string_push_char(u->path, c);
        c = fgetc(f);
    } while(c != '\n' && c != '[');

    // Here `c` is the reason of loop termination. Test it and proceed accordingly:

    if (c == '[') {
        while ((c = fgetc(f)) != ']') {
            string_push_char(u->title, c);
        }
        while(fgetc(f) != '\n')
            ;
    } else {
        string_copy(u->title, u->path);
    }

This almost it. The code parses the well-formed file, but will fall into an infinite loop if, for example, the title-closing bracket is missing.

As a side note, isspace(c) is strongly preferred to a manual testing.


Given a list of coordinates check if 4 points make a line I was doing some preparation for coding interviews and I came across the following question:

  Given a list of coordinates "x y" return True if there exists a line containing at least 4 of the points (ints), otherwise return False.

The only solution I can think about is in \$O(n^2)\$. It consist of calculating the slope between every coordinate: Given that if \$\frac{y_2-y_1}{x_2 –x_1} = \frac{y_3-y_2}{x_3-x_2}\$  then these three points are on the same line. I have been trying to think about a DP solution but haven't been able to think about one.

Here is the current code:

def points_in_lins(l):
    length = len(l)
    for i in range(0,length -1):
        gradients = {}
        for j in range(i+1, length):
            x1, y1 = l[i]
            x2, y2 = l[j]
            if x1 == x2:
               m = float("inf")
            else:
               m = float((y2 -y1) / (x2 - x1))
            if m in gradients:
                gradients[m] += 1
                if gradients[m] == 3:
                   return(True)
            else:
                gradients[m] = 1

    return(False)

General remarks

def points_in_lins(l):

The function and argument name can be improved. l is too short and does
not indicate at all that this is a list of points, and points_in_lins
(perhaps you meant points_in_line?) does not indicate that the function
looks for four points in a line.

gradients is in fact a dictionary counting slopes.

Iterating over all pairs of points can be simplified with
enumerate() and slices:

for idx, (x1, y1) in enumerate(l):
    gradients = {}
    for (x2, y2) in l[idx + 1:]:

The “set or increment” for gradients can be simplified with
defaultdict or a Counter:

gradients = Counter()

# ...

gradients[m] += 1
if gradients[m] == 3:
    return True

The parentheses in return(True) and return(False) are not necessary:

return False

The math

Computing the slope as the quotient

m = (y2 - y1) / (x2 - x1)

requires a separate check for a zero denominator, but is problematic
for another reason: Rounding errors can occur. As an example,

points_in_lins([(0, 300000000000000000), (1, 0), (1, 1), (1, 2)])

evaluates to True: The slopes from the first point to the
other three points all evaluate to the same floating point number.

A possible fix is to compare the “directions” , i.e. the (2-dimensional)
vectors between the two points, normalized in a way such that
two vectors pointing in the same (or opposite direction) are
considered equal.

If all coordinates are integers, then it is best to stick with pure
integer calculations. Normalizing the connecting vector can be
achieved by division by the greatest common divisor of the x- and
y-component, and possibly mirroring it.

Putting it together

from math import gcd
from collections import Counter

def four_points_in_line(points):
    for idx, (x1, y1) in enumerate(points):
        direction_counts = Counter()
        for (x2, y2) in points[idx + 1:]:
            # Compute normalized direction from (x1, y1) to (x2, y2):
            delta_x, delta_y = x2 - x1, y2 - y1
            g = gcd(delta_x, delta_y)
            delta_x, delta_y = delta_x // g, delta_y // g
            if delta_x < 0 or (delta_x == 0 and delta_y < 0):
                 delta_x, delta_y = -delta_x, -delta_y
            # Three identical directions from (x1, y1) means 4 collinear points:
            direction_counts[(delta_x, delta_y)] += 1
            if direction_counts[(delta_x, delta_y)] == 3:
                return True
    return False

It is still a \$ O(n^2) \$ algorithm, but more robust against
rounding and division by zero errors.

If the points are not guaranteed to be distinct then  identical points need have to be treated separately.


Shell script to rebuild a Java webapp I am asking for an experienced person to review my basic shell script. I do not write them at work, but I am a software developer. I am using this for my personal project that I am working on. Later, it will be integrated with Docker and a CI server maybe Jenkins/Travis CI.

I am just looking for someone to tell me if I am not following best practices
or conventions, or if certain parts need to be changed/revised.

#!/bin/bash
PATH=$PATH:$(npm bin)
set -x
webapp="/Users/earzate/Development/Career/profile-page-app"
serverapp="/Users/earzate/Development/Career/profile-server-ws/app-server"

#build profile-page-app
cd $webapp
echo "Building ng page app"
ng build --prod
echo "ng page app build complete"

#build app-server
echo "Cleaning static sources"

#clean old static web files
cd "$serverapp/src/main/resources"
echo "Deletic static web resources"
rm -r static

#make new static directory
echo "Creating static directory"
mkdir static

#copy web resources from webapp into serverapp static directory
echo "Copying static resources into directory"
cp -r "$webapp/dist/."  "$serverapp/src/main/resources/static"

#copy secured objects from secured directory
#secured objects not versioned in git
cp "$serverapp/secured/name/private-key.p12" "$serverapp/src/main/resources"

echo "Building jar"
cd "$serverapp"
./gradlew build

echo "Deploying app"
java -jar build/libs/app-server-0.0.1-SNAPSHOT.jar

Immediate security problem

Do you know which ng, cp, rm, gradlew does the script execute? You shouldn't rely on PATH.
Indirect security problem

rm and cp can fail midway, and you may end up deploying something unintended. Along the same lines, can ng produce something half-baked? Consider testing exit codes and act accordingly.
Every time you want to comment the behavior, consider factoring it into a well-named function, e.g.

recreate_static_directory() {
    cd "$1"
    echo "Deletic static web resources"
    rm -r static

    echo "Creating static directory"
    mkdir static

    echo "Copying static resources into directory"
    cp -r "$webapp/dist/."  "$1/static"
    cp "$serverapp/secured/emmanuel-arzate/private-key.p12" "$1"

I am not sure I follow the mix of cds and fully-qualified paths.


Overriding Backbone.Collection.add to enforce uniqueness on non-id property I've overridden Backbone.Collection.add for my Collection to ensure that the Collection never has two PlaylistItems who share a Song ID. My implementation seems incredibly verbose and I was curious if there's a better way to express my desires:

var PlaylistItems = MultiSelectCollection.extend(_.extend({}, SequencedCollectionMixin, {
    model: PlaylistItem,

    //  Don't allow duplicate PlaylistItems, determined by the PlaylistItem's Song's ID.
    add: function (items, options) {

        if (items instanceof Backbone.Collection) {
            items.each(function (item) {
                trySetDuplicateSongId.call(this, item);
            }.bind(this));
        }
        else if (_.isArray(items)) {
            _.each(items, function (item) {
                trySetDuplicateSongId.call(this, item);
            }.bind(this));
        } else {
            trySetDuplicateSongId.call(this, items);
        }

        return MultiSelectCollection.prototype.add.call(this, items, options);
    }

}));

function trySetDuplicateSongId(playlistItemToAdd) {
    var duplicatePlaylistItem = this.find(function (playlistItem) {
        return playlistItem.get('song').get('id') === playlistItemToAdd.get('song').get('id');
    });

    var duplicateFound = !_.isUndefined(duplicatePlaylistItem);

    if (duplicateFound) {

        //  Make their IDs match to prevent adding to the collection.
        if (duplicatePlaylistItem.has('id')) {
            playlistItemToAdd.set('id', duplicatePlaylistItem.get('id'));
        } else {
            playlistItemToAdd.cid = duplicatePlaylistItem.cid;
        }

    }
}

I've been looking at this since a while, it seems mostly verbose because you want to handle Backbone collections, and arrays, and single songs..

It seems simpler to normalize in all 3 scenario's items to something that you then process once. I am not 100% this works, but you should get the gist:

//  Don't allow duplicate PlaylistItems, determined by the PlaylistItem's Song's ID.
add: function (items, options) {

   if( !items.length ){
     //Anti duck typing, it's not an array or collection
     items = [items];
   }
   else if ( items instanceof Backbone.Collection ){
     //Provide direct access to the array
     items = items.models;
   }
   _.each(items, function (item) {
       trySetDuplicateSongId.call(this, item);
   }.bind(this));

    return MultiSelectCollection.prototype.add.call(this, items, options);
}

For trySetDuplicateSongId I would extract playlistItemToAdd.get('song').get('id') and cache it into a variable. This should make your search twice as fast. Also I would clean up the whole duplication finding, I find the code a bit verbose. Again, I am making some assumptions here with regards to what you set as defaults, but I would do this:

function trySetDuplicateSongId(playlistItemToAdd) {

    var songId = playlistItemToAdd.get('song').get('id'),
        duplicate = this.find(function (playlistItem) {
            return playlistItem.get('song').get('id') === songId;
        });

    if (duplicate) {
       //  Make their IDs match to prevent adding to the collection.
        if (duplicatePlaylistItem.has('id')) {
            playlistItemToAdd.set('id', duplicatePlaylistItem.get('id'));
        } else {
            playlistItemToAdd.cid = duplicatePlaylistItem.cid;
        }
    }
}

Furthermore, if you have to add lots of songs, then you will run into increasingly bad performance. I would probably have a separate list/object with just the song id's pointing to an object with item id or cid.

Finally, I am curious as to why you would not allow a playlist item to be shared by song lists ;P


Pancake sort inteview using java Given an array of integers arr:

Write a function flip(arr, k) that reverses the order of the first k elements in the array arr.
Write a function pancakeSort(arr) that sorts and returns the input array.

You are allowed to use only the function flip you wrote in the first step in order to make changes in the array.

Example:

input:  arr = [1, 5, 4, 3, 2]

output: [1, 2, 3, 4, 5] # to clarify, this is pancakeSort's output

My approach:

import java.io.*;
import java.util.*;

class Solution {

  static int[] pancakeSort(int[] arr) {
    // your code goes here
    int max = -1000,maxpos = 0 ;
    //3 1 2 4 6 5 -->  6 4 2 1 3 5
    for(int i = 0; i < arr.length; i++ )
    {
      max = -1000;
    for( int c = i; c < arr.length; c++ )
      {
        if( max <= arr[c] )
        {
          max = arr[c];
          maxpos = c;
        }
       }
      arr = flip(arr,i,maxpos+1);
    }
    arr = flip(arr,0,arr.length);
   return arr;
  }

  // 3 1 2 4 6 -> 6 4 2 1 3 5
  // k = 5 ->
  static int[] flip(int [] arr,int start , int k)
  {
     int temp;

     for(int i = start, j = k - 1; i < j; i++, j-- )
     {
           temp = arr[i];
           arr[i] = arr[j];
           arr[j] = temp;
     }
     return arr;
   }

  //
   //1 5 4 3  -> 3 4 5 1
//54321

  1 5 4 3 2 --> flip(arr, maxpos) -> 5 1 4 3 2 --> flip(arr,arr.length ) -> 2 3 4 1 5

  public static void main(String[] args) {

  }

}

I have the following questions about my code:

Can I further improve my space and time complexity?
Is there any other alternative, smarter way to attempt this question?
Any grave coding convention that I have violated in my code?

Reference

Flip

Use better variable names. i and j are harder to read than something like front and back.
It's preferable to define the temp value inside the loop and save a line of code.
The method should be private.
Depending on what the interviewer wants, it's much nicer to make a new array than to destructively modify the existing one. I'll assume you asked and they specified to modify the existing array. That being the case, you don't need to return the modified array.

Pancake Sort

You're not doing a pancake sort. It's nonsensical for you to describe a problem and then ask us to review code that breaks your own stated invariants to solve the problem.
-1000 is arbitrary. Use Integer.MIN_VALUE and your code will work for all negative numbers.
Don't use abbreviations or shorten variable names. The extra letters don't cost anything. max and maxPos are not sufficiently descriptive. Don't use c as an array index. Either use j or a descriptive name.
In the comments, you observe that pancake sort is inefficient. Yes, it is. The point was to pick a sort that most people haven't thought about so everybody starts on an even playing field for the interview question. The inefficiency is tied to the algorithmic limitation of only having flip() available. There are no significant performance gains to be had unless you break that limitation, at which point you're no longer doing a pancake sort.

Using an actual pancake sort and my other suggestions, your code might look something like:

class Solution {

    // return an int for convenient testing
    private static int[] pancakeSort(final int[] array) {
        boolean sorted = false;
        while (!sorted) {
            sorted = true;
            for (int i = 0; i < (array.length - 1); i++) {
                if (array[i] > array[i + 1]) {
                    flip(array, i + 1);
                    flip(array, i + 2);
                    flip(array, i + 1);
                    sorted = false;
                    break;
                }
            }
        }
        return array;
    }

    private static void flip(final int[] array, final int elementsToFlip) {
        for (int front = 0, back = elementsToFlip - 1; front < back; front++, back--) {
            final int temp = array[front];
            array[front] = array[back];
            array[back] = temp;
        }
    }

    public static void main(final String[] args) {
        System.out.println(Arrays.toString(pancakeSort(new int[] { 1 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 1, 2 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 2, 1 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 1, 2, 3 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 2, 1, 3 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 3, 1, 2 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 3, 2, 1 })));
        System.out.println(Arrays.toString(pancakeSort(new int[] { 3, 2, 1, 8, 4, 6, 5, 10, 7, 9 })));
    }
}


Reasonable way to implement "safe" math operations using _Generic? I've been thinking about a way to make it easier to safely use math operations with C's basic datatypes (e.g. using the CERT C coding standard).  So far, I've come up with something like this:

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

#define safe_add(x, y) _Generic((x + y),                    \
                            unsigned int: safe_add_uint,    \
                           unsigned long: safe_add_ulong    \
                       )(x, y, __FILE__, __LINE__)

unsigned long
safe_add_ulong(unsigned long x, unsigned long y,
               const char* filename, int line_num)
{
    if (x < ULONG_MAX - y)
        return x + y;
    else {
        fprintf(stderr,
                "Integer wrap-around occurred, File: %s, Line: %d\n",
                filename, line_num);
        exit(EXIT_FAILURE);
    }
}

unsigned int
safe_add_uint(unsigned int x, unsigned int y,
              const char* filename, int line_num)
{
    if (x < UINT_MAX - y)
        return x + y;
    else {
        fprintf(stderr,
                "Integer wrap-around occurred, File: %s, Line: %d\n",
                filename, line_num);
        exit(EXIT_FAILURE);
    }
}

int
main()
{
    /*
     *  usual arithmetic conversions results in this calling
     *  the uint version of safe_add...
     */
    safe_add(2000000000, 3000000000u);

    printf("We shouldn't get here...(unless unsigned int uses more than 32 bits)\n");
}

Output of the above would be something similar to:

  Integer wrap-around occurred, File: /.../main.c, Line: 41

and the program exits with a failure code (assuming the OS supports that).

Obviously, additional operations and types need to be added as well as handling signed arithmetic, but are there any problems with this overall method that I may be missing?

Is there perhaps an easier way to write this that I've overlooked?

Very impressive! A few notes:

I really like how you are using C11 stuff.

#define safe_add(x, y) _Generic((x + y),                    \
                            unsigned int: safe_add_uint,    \
                           unsigned long: safe_add_ulong    \
                       )(x, y, __FILE__, __LINE__)

It's good that you are using the more modern items the C standards have given us to use.  My only nitpick with this #define is that your aligning is a bit off.

#define safe_add(x, y) _Generic((x + y),                        \
                                unsigned int: safe_add_uint,    \
                                unsigned long: safe_add_ulong)  \
                                (x, y, __FILE__, __LINE__)

@Morwenn touches on your error handling a bit, but I want to go deeper.  For now, I want to talk about the style of error reporting I've come to adopt for such APIs. Options for error reporting from C functions include the following:

Return an error code from functions that can fail.
Provide a function like Windows GetLastError() or OpenGL's    glGetError() to retrieve the most recently occurring error code.
Provide a global (well, hopefully, thread-local) variable containing the most recent error, like POSIX errno.
Provide a function to return more information about an error, possibly in conjunction with one of the above approaches, like POSIX's strerror function.
Allow the client to register a callback when an error occurs, like GLFW's glfwSetErrorCallback.
Use an OS-specific mechanism like structured exception handling.
Write errors out to a logfile, stderr, or somewhere else.
Just assert() or somehow else terminate the program when an error occurs.

There are loads of tradeoffs among these options, and it's a matter of opinion as to which ones are better than others. Like all matters of style, unless a style is just plain unsuitable (like the last two options above might be for many uses), it's probably most important to apply the style you choose consistently.

Let me illustrate the style of error handling I use for C APIs with the following re-written function of yours:

unsigned int safe_add_uint(unsigned int x, unsigned int y,
      const char* filename, int line_num, char* error)

Where we call it as:

char* error = /* allocate memory */;
safe_add_uint(x, y, __FILE__, __LINE__, &error)`

Now your function can set the value of error within the functions, and then print the output in something such as an atexit() function.

You might think that this could be a bit cumbersome for an error handling system in C, but here's the catch: this C error handling style that plays nice with C++ exceptions too.  This can be nice when implementing an hourglass API.
You should probably be using exact-width integer types.
Always declare what parameters your function takes in, even if nothing.

int main(void)

You might wonder why we have to do this.  Imagine we have the function foo() declared as such:

int foo()

In C, this is known as an identifier list and means that it "can take any number of parameters of unknown types".  We can actually pass values to the function even though we don't mean to or intend to.  If the caller calls the function giving it some argument, the behavior is undefined. The stack could become corrupted for example, because the called function expects a different layout when it gains control.

Using identifier lists in function parameters is depreciated.  It is much better to do something like:

int foo(void)

In C, this is known as a parameter type list and defines that the function takes zero arguments (and also communicates that when reading it) - like with all cases where the function is declared using a parameter type list, which is called a prototype.   If the caller calls the function and gives it some argument, that is an error and the compiler spits out an appropriate error.

The second way of declaring a function has plenty of benefits. One of course is that amount and types of parameters are checked. Another difference is that because the compiler knows the parameter types, it can apply implicit conversions of the arguments to the type of the parameters. If no parameter type list is present, that can't be done, and arguments are converted to promoted types (that is called the default argument promotion). char will become int, for example, while float will become double.


Compute all the permutations for a given vector of integers The task is to compute all the permutations for a given vector of integers (but of course the specific integer type is not relevant for the solution)

The strategy is based on recursion + iterations

At each recursion, the state consists of

the root sequence a which is the set of elements already placed
the remaining elements set b which is the set of elements still to be placed

Inside the recursion, a loop places the N(i) (with i recursion index and) remaining elements producing the same amount of new root sequences and a new recursion is started so that N(i+1)=N(i)-1 hence meaning the overall complexity is O(N!) as expected

The recursion ends when there are no more elements to place hence b.empty() is true

Each recursion set ends with a valid sequence hence they are all merged together in a final list of sequences

Here is my CPP solution

#include <iostream>
#include <vector>
using namespace std;

vector<int> remove_item (const vector<int>& a, const unsigned int id)
{
    vector<int> res;
    for(unsigned int i=0; i<a.size(); ++i) if(i!=id) res.push_back(a[i]);
    return res;
}

vector<int> add_item(const vector<int>& a, const int b)
{
    vector<int> res=a;
    res.push_back(b);
    return res;
}

vector< vector<int> > merge(const vector< vector<int> >& a, const vector< vector<int> >& b)
{
    vector< vector<int> > res=a;
    for(const auto& e : b) res.push_back(e);
    return res;
}

vector< vector<int> > permutations(const vector<int>& b, const vector<int>& a={})
{

    if(b.empty()) return { a };

    vector< vector<int> > res;
    for(unsigned int i=0; i<b.size(); ++i) res=merge(res, permutations(remove_item(b,i), add_item(a, b[i])));
    return res;
}

int main() {
    // your code goes here

    auto res = permutations({1,2,3,4,5});
    cout << "Sol Num = " << res.size() << endl;
    for(const auto& a : res)
    {
        for(const auto& b : a) cout << to_string(b) << " ";
        cout << endl;
    }
    return 0;
}

A cleaner solution is to trust the standard library and try to re-use the generic components already available there. Your problem is solved by std::next_permutation, so you can proceed along the lines of:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> v = { 1, 2, 3, 4, 5 };

    do
    {
        for (auto e : v)
            std::cout << e << " ";
        std::cout << "\n";
    }
    while (std::next_permutation(v.begin(), v.end()));
}

For pedagogical purposes, if you wanted to keep your current structure, you could also use standard functions there. In particular, remove_item and merge could be rewritten to:

std::vector<int> remove_item(const std::vector<int>& a, int id)
{
    assert(id >= 0 && id < a.size());

    std::vector<int> res(a.begin(), a.begin() + id);
    res.insert(res.end(), a.begin() + id + 1, a.end());
    return res;
}

std::vector<std::vector<int> > merge(const std::vector<std::vector<int> >& a, const std::vector<std::vector<int> >& b)
{
    std::vector<std::vector<int> > res(a);
    std::copy(b.begin(), b.end(), std::back_inserter(res));
    return res;
}

Whatever you do, as general comments:

Avoid writing using namespace std;.
Don't write std::endl when \n will do.
You don't need std::to_string, just print b.
You are more likely to make mistakes when you put multiple statements on the same line. So instead of writing for(...) if(...) v.push_back(x); just write

for(...)
{
   if(...)
   {
      v.push_back(x);
   }
}

This also improves readability.


JavaScript function for logging the members of an object (with horizontal alignment) When iterating over the members of an object for logging the keys / values one gets a "stair case" effect.
Therefore I wrote myself this function which takes care for a left-alignment of the values.

Any hints concerning flaws and improvement-recommendations welcome.

// #### START TEST #######################
var person = {
  yourMobilPhoneNumber : 01234171819,
  firstName : 'theFirstName',
  lastName : 'theLastName',
  mail : 'myEmail@abc.com',
  zip : '12345',
  street : 'theNameOfMyStreet',
  city : 'someCitySomewhere',
  yourVeryPersonalWebpage : 'http://that-is-me.com',
  id : 12345,
  calculate: function() { return 3 + 4; }
};

displayMembers(person);
// #### END TEST #######################

// Displays the members of an assigned
//   object on the console.

// -- Parameter -------------
// Object - An object which members
//   shall be displayed.

function displayMembers(obj) {
  var i;
  var max = (function() {
    var ret = 0;
    var keys = Object.keys(obj);

    for (i = 0; i < keys.length; i++) {
      if (keys[i].length > ret)
        ret = keys[i].length;
    }

    return ret;
  })();

  var getSpacer = function(len, state) {

    if (state.length < len) {
      return getSpacer(len, state += ' ');
    } else {
      return state;
    }
  }

  for (i in obj) {
    console.log('%s: %s%s',
                i,
                getSpacer(max - i.length, ''),
                obj[i]);
  }
}

Simplification with for/in loops

Your loop through Object.keys() in the function you have for the max variable is reinventing JavaScript's for/in loop which loops over and objects keys. Here's how you could simplifying that code:

for(var key in obj) {
    if(!obj.hasOwnProperty(key)) {
        continue;
    }

    if(key.length > ret) {
        ret = key.length;
    }
}

Unnecessary recursion

Your getSpacer function is using recursion when it really does not need to be; the function would be a lot simpler and a lot faster if you used a neat JavaScript trick for repeating characters:

function getSpacer(len) {
    return Array(len + 1).join(" ");
}

Now, there's no need for recursion - that means there is less interaction with the stack - and, rather than switching to a loop, this nice solution can be used.