Temporary file utility class in Python I decided to write a tiny class to automatically write and delete a file given filename and content. It is intended to make testing IO less verbose. I include a small example usage.

temporary.py

import os

class Temporary:
    def __init__(self, name, content):
        self.name = name
        self.content = content

    def __enter__(self):
        with open(self.name, 'w+') as f:
            f.write(self.content)

    def __exit__(self,_,__,___):
        os.remove(self.name)

first_word.py

import doctest
from temporary import Temporary

def first_word_of_each_line(filename):
    """
    >>> txt = '\\n'.join(['first line', 'second line', 'bar bar'])
    >>> with Temporary('foo.txt', txt): first_word_of_each_line('foo.txt')
    ['first', 'second', 'bar']
    """
    with open(filename) as f:
        lines = f.read().splitlines()
        return [line.split()[0] for line in lines]

if __name__ == "__main__":
    doctest.testmod()

There, well, really isn't much to review here, so I have just a couple of points on this.

Add a docstring to the class Temporary. Describe what this class does in detail, and flesh it out with useful information about arguments as well.
You're missing some whitespace in between parameters in your __exit__ declaration. It should look like this def __exit__(self, _, __, ___).
You should add a method like write_to_file so that the user can change the contents of the file during runtime, before it's deleted.
As mentioned by @GarethRees, there's already a Python module built for this kind of use, tempfile.

I hope this helps! If there's anything else that you want me to cover on this, mention it in the comments, and I'll see if I can cover it.


Concatenating an already existing filename to create a new file I had answered this question from stackoverlow and the code below is code that I wrote to explain to the OP a possible way to achieve what I believe they were looking for.

The general idea that I got from them was that they were trying to open a file with a specified file name and if that file does exist that they in turn wanted to create a new file with the same filename but with extra characters appended to the filename.

This is the small program that I wrote to mimic that behavior.

#include <string>
#include <fstream>
#include <iostream>

int main() {
    std::string originalFilename("out.txt");
    std::string extension(".txt");
    std::string nextFilename;
    bool originalFileFound = false;

    // First test to see if original file exist by opening
    // if so then generate the next usable name
    std::fstream fileIn( originalFilename, std::ios::in );
    unsigned int counter = 0;

    if (fileIn.is_open()) {
        counter++;
        nextFilename = originalFilename.substr( 0, originalFilename.size() - extension.size() )
                       + "_" + std::to_string(counter) + extension;
        originalFileFound = true;
    }
    fileIn.close();

    // Generate a few files with the appended number system to
    // the end of the original filename if the original file was found.
    if ( originalFileFound ) {
        for ( int i = 1; i < 6; i++ ) {
            std::fstream nextFile;
            nextFile.open( nextFilename, std::ios::out );
            if (nextFile.is_open()) {
                nextFile << nextFilename; // Write this before updating...
                counter++;
                nextFilename = nextFilename.substr(0, nextFilename.find_first_of('_') + 1)
                               + std::to_string(counter) + extension;
            }
            nextFile.close();
        }
    }
    return 0;
}

I would like to know if there is a more elegant, more efficient and cleaner way to achieve this using modern C++. Writing this simple program in essence was basically self practice to improve my skills with string manipulation and the string's set of library functions and algorithms.

Prefer RAII-style opening the file in the constructor. You already done that with

    std::fstream fileIn( originalFilename, std::ios::in );

so why not follow the suit with

    std::fstream nextFile(nextFilename, std::ios::out);

There is no need to explicitly nextFile.close();. The destructor will take care of it at the end of each iteration.
There is nothing wrong with the early return. Instead of setting originalFileFound = true;, and testing it later on, quit immediately if opening fails. That would spare a boolean flag and a level of indentation.
Consolidate handling of nextFilename in one place. Consider

    if (!fileIn.is_open()) {
        print_error_message();
        return 1;
    }

    std::string prefix = originalFilename.substr(0, originalFilename.size() - extension.size());

    for (int i = 0, counter = 0; counter < 5; i++) {
        nextFilename = prefix + "_" + std::to_string(i) + extension;
        ....
    }

I would be very cautious to use this program, because it may overwrite existing files.


Reverse Groups challenge at CodeEval.com I am working through challenges at CodeEval.com and wanted to get your input on my code for this challenge.

  Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is.

  Input sample:

  Your program should accept as its first argument a path to a filename. Each line in this file contains a list of numbers and the number k, separated by a semicolon. The list of numbers are comma delimited.

  E.g. input:

1,2,3,4,5;2
1,2,3,4,5;3

  Output sample:

  Print out the new comma separated list of numbers
  obtained after reversing. E.g.

2,1,4,3,5
3,2,1,4,5

-(void)reversedGroups
{
    NSString *line = @"22,23,24,25,26,27,28,29,30;3";   //input sample
    NSArray *lineArray = [line componentsSeparatedByString:@";"];
    NSUInteger numbElements = [[lineArray lastObject] intValue];
    NSArray *elementsArray = [[lineArray objectAtIndex:0] componentsSeparatedByString:@","];
    NSMutableArray *resultLineArray = [[NSMutableArray alloc]init];

    NSUInteger pos = 0;
    while (pos<[elementsArray count]) {
        //itterating through the elements
        if (pos+numbElements <= [elementsArray count]) {
            //make sure that i have enough elements to reverse
            for (NSUInteger i = pos+numbElements; i>pos; i--) {
                //add elements in reverse to the result array
                [resultLineArray addObject:[elementsArray objectAtIndex:i-1]];
            }
        }else {
            for (NSUInteger j = pos; j<[elementsArray count]; j++) {
                //add elements that are left to the result array
                [resultLineArray addObject:[elementsArray objectAtIndex:j]];
            }
        }
        pos += numbElements;  // move the postion by number of elements to reverse
    }
    //convert results array to string and add comma after each element as required for output
    NSString *resultString = [[resultLineArray valueForKey:@"description"] componentsJoinedByString:@","];
    NSLog(@"%@",resultString);

}

It's pretty simple task and I think code does its job well. I would point couple minor style issues:

You don't need to use objectAtIndex method to access elements inside an array. elementsArray[i] is enough and it's more readable.
You can access count property using dot-notation - array.count. Again, it's more readable.
Combining result string from array looks cumbersome and complicated. And rely on description property. Why don't you create result string as you go without having to create temp array first?
You are dividing line into lineArray. Then you're accessing first and last element using lastObject and objectAtIndex:0. I would prefer to use either [0] and [1] or lastObject and firstObject.
Pass the code through standard Xcode formatter to clean up spacing and indentation.


Properties and tryparse I have a class with 3 properties, and I would like to know how I can write my code better. I want to use Single.TryParse so that if any token is unknown string, I could still get 0. But using this method, I need to use a temp variable, and as my properties list increases, I will have more temp variable, and this is not efficient. Is there any way to code this better?

public class GSA : NMEAMsg
{
    public float Pdop { set; get; }
    public float Hdop { set; get; }
    public float Vdop { set; get; }

    protected override void parseTokens(string[] tokens)
    {
        float pdop = 0;
        float hdop = 0;
        float vdop = 0;

        Single.TryParse(tokens[tokens.Length - 3], out pdop);
        Single.TryParse(tokens[tokens.Length - 2], out hdop);
        Single.TryParse(tokens[tokens.Length - 1], out vdop);

        Pdop = pdop;
        Hdop = hdop;
        Vdop = vdop;
    }
}

I have a class with 3 properties, [...] and as my properties list increases, [...]

Wait, stop - here, that.

Classes are the blueprint for an object - the public members are that object's interface, and that shouldn't need to change that way. The Open/Closed Principle tells us that classes should be opened for extension, and closed for modification.

I don't know what any of these members mean, but a design that needs to change all the time is a design that didn't integrate the need to change as a requirement.

A design that embraces change, is one that minimizes the amount of code that's required to add to extend a piece of existing functionality.

If, instead of saying "I need a class with a P, H and V 'dop' float values, and maybe a X, Y and Z too, eventually", you said "I need a class with an unknown bunch of 'dop' float values; for this version I'll have P, H and V values, nobody knows what future holds"... the design would have reflected that.

void parseTokens(string[] tokens)

You have a string[] array here, an IEnumerable<string> ready to play with: use it to your advantage, and ask yourself how you could possibly structure things so that parseTokens (which should really be ParseTokens - conventions FTW!) can be implemented with an iterative logic.

Consider an enum:

public enum Dop // whatever that means
{
    Pdop,
    Hdop,
    Vdop
}

To add support for a new property, you add an enum member. Then you can have a function that returns this:

return tokens
    .Select((value, index) =>
        {
            float dop;
            var success = float.TryParse(value, out dop);
            return new
            {
                Key = (Dop)index,
                Success = success,
                Value = dop
            };
        })
    .ToDictionary(item => item.Key, item => item.Success ? item.Value : (float?)null);

Notice float.TryParse is the same as Single.TryParse.

That's a Dictionary<Dop,float?>, where the float? value is null when the string couldn't be parsed into a float; you would take that and assign it to a private readonly field.

That's nice, but a Dictionary is not exactly the type of data structure you usually want to expose in your public interface - how about an indexer?

public float? this[Dop dop]
{
    get
    {
        float? value;
        return _tokens.TryGetValue(dop, out value)
            ? value
            : null;
     }
}

(assuming private readonly IDictionary<Dop,float?> _tokens; assigned in constructor)

That said, I'd like to bring your attention to the indexing here:

Single.TryParse(tokens[tokens.Length - 3], out pdop);
Single.TryParse(tokens[tokens.Length - 2], out hdop);
Single.TryParse(tokens[tokens.Length - 1], out vdop);

Whenever tokens has less than the expected number of items, things blow up. What's the index of the pdop value in the tokens array? As a maintainer you shouldn't have to be bothered with these riddles.

What does using an enum get us? Imagine the client code has an instance of a GSA class, named gsa:

var pdop = gsa[Dop.Pdop];
var hdop = gsa[Dop.Hdop];
var vdop = gsa[Dop.Vdop];

If gsa has a float value for Pdop, then pdop will contain that value. Otherwise, it will be null.

And to extend it, you now only need to do this:

public enum Dop
{
    Pdop,
    Hdop,
    Vdop,
    Xdop,
    Ydop,
    Zdop
}

...and make sure the tokens array provided has as many arguments / fail fast:

protected override void ParseTokens(string[] tokens)
{
    if (tokens.Length != Enum.GetNames(typeof(Dop)).Length)
    {
        throw new ArgumentException("Invalid number of tokens.");
    }

    //
}

Another thing that strikes me as not needed and potentially bug-prone, is exposing the setters for these hard-earned float values.

Also, the order of the accessors is unusual:

public float Pdop { set; get; }

I'm used to see the getter first.

public float Pdop { get; private set; }

With a private setter, the only way to set that value is to parse a new array of strings.

At this point I'd question the mutability of the type. How about simply this?

public class GSA : NMEAMsg
{
    private readonly IDictionary<Dop,float?> _tokens;

    public GSA(string[] tokens)
    {
        if (tokens.Length != Enum.GetNames(typeof(Dop)).Length)
        {
            throw new ArgumentException("Invalid number of tokens.");
        }

        _tokens = tokens
            .Select((value, index) =>
                {
                    float dop;
                    var success = float.TryParse(value, out dop);
                    return new
                    {
                        Key = (Dop)index,
                        Success = success,
                        Value = dop
                    };
                })
            .ToDictionary(item => item.Key, item => item.Success ? item.Value : (float?)null);
    }

    public float? this[Dop dop]
    {
        get
        {
            float? value;
            return _tokens.TryGetValue(dop, out value)
                ? value
                : null;
         }
    }
}


Project Euler 92: count sum-squared-digits chains that reach 89 A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.
For example:
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?

My solution doesn't finish in under a minute. I'm already caching the results of arrivesAt89, including all permutations. Any help is welcomed.
#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>

int sumOfDigitsSquared(int n) {
    auto digits = std::to_string(n);
    int sum = 0;

    for (auto c : digits) {
        sum = (c - '0') * (c - '0');
    }

    return sum;
}

std::vector<int> permutations(int n) {
    auto digits = std::to_string(n);
    std::vector<int> res;
    res.push_back(n);

    do {
        res.push_back(stoi(digits));
    } while (std::next_permutation(digits.begin(), digits.end()));

    return res;
}

bool arrivesAt89(int n) {
    static auto cache = std::unordered_map<int,bool>();

    int m = n;
    while (m != 1) {
        if(cache.find(m) != cache.end()) {
            return cache.find(m)->second;
        }
        if (m == 89) {
            auto perms = permutations(m);
            for (auto p : perms) {
                cache.insert({p, true});
            }
            return true;
        }
        m = sumOfDigitsSquared(m);
    }

    auto perms = permutations(n);
    for (auto p : perms) {
        cache.insert({p, false});
    }
    return false;
}

int main() {
    int numberOf89s = 0;

    for (int i = 1; i< 10000000; i++) {
        if (arrivesAt89(i)) numberOf89s++;
    }

    std::cout << numberOf89s << std::endl;
}

I guess the idea behind using permutations is that any permutation of the same digits will result in the same squared sum. However... in that case, shouldn't we simply calculate the squared sum and cache that?
It appears that we're only caching the permutations of the digits at the end of the chain. i.e. we'll only ever end up with 1, 89 and 98 in the map! We should probably be caching all the values in the chain up to the final result.
#include <string> for std::to_string.
Converting to and from std::string is probably quite slow. We can use simple integer arithmetic to extract the individual digits.
The implementation of sumOfDigitsSquared is clearly incorrect with basic testing.


Wordy LINQ for XML word list This code works as intended, however, I am sure that there is a way to condense the xmldataLoad method. If someone could maybe explain a better approach than what I have done with the method, I would be extremely grateful.
Essentially, what I am saying is I am rather new to using LINQ and don't fully understand the various ways of using it, and I am quite sure there are many people in the same boat as I am.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Xml.Serialization;
//using XMLControlLibrary;

namespace EJCTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        private void xmlDataLoad()
        {
            string xmlPath = @"C:\Users\Jesse\Source\Repos\AsyncSpeechSynth\EJCTest\XMLControlLibrary\newDictionary.xml";
            XDocument xdoc = XDocument.Load(xmlPath);

            var eng = from wordList in xdoc.Root.Elements("Word")
                      select wordList.Element("English").Value;
            engList.ItemsSource = eng.ToList();

            var rom = from wordList in xdoc.Root.Elements("Word")
                      select wordList.Element("Romaji").Value;
            romList.ItemsSource = rom.ToList();

            var jpn = from wordList in xdoc.Root.Elements("Word")
                      select wordList.Element("Japanese").Value;
            jpnList.ItemsSource = jpn.ToList();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            xmlDataLoad();
        }

        public class WordList
        {
            string english;
            string romaji;
            string japanese;

            public string English
            {
                get { return english; }
                set { english = value; }
            }

            public string Romaji
            {
                get { return romaji; }
                set { romaji = value; }
            }

            public string Japanese
            {
                get { return japanese; }
                set { japanese = value; }
            }
        }
    }
}

Your LINQ is fine.  All you're doing is simple navigation of an XDocument.  There's isn't any more you can do with LINQ there.  However, there are still some improvements that can be made.

Borrowing from janos' answer, you can create a helper method GetWords that takes XDocument xdoc and string name as parameters:

private List<string> GetWords(XDocument xdoc, string name)
{
    var words = from wordList in xdoc.Root.Elements("Word")
                select wordList.Element(name).Value;
    return words.ToList();
}

You can store the XML path as a constant at the class level:

private const string _cXmlPath = @"C:\Users\Jesse\Source\Repos\AsyncSpeechSynth\EJCTest\XMLControlLibrary\newDictionary.xml";

You can get rid of magic strings.

You can use auto properties.

Edit: You can rename the xmlDataLoad method using UpperCamelCase and to start with a verb.  Thanks @BCdotWEB and @RobH.

The new version of your class looks like this:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private const string _cXmlPath = @"C:\Users\Jesse\Source\Repos\AsyncSpeechSynth\EJCTest\XMLControlLibrary\newDictionary.xml";
    private const string _cWordName = "Word";
    private const string _cEnglishName = "English";
    private const string _cRomajiName = "Romaji";
    private const string _cJapaneseName = "Japanese";

    public MainWindow()
    {
        InitializeComponent();
    }

    private void LoadXmlData()
    {
        XDocument xdoc = XDocument.Load(_cXmlPath);

        engList.ItemsSource = GetWords(xdoc, _cEnglishName);
        romList.ItemsSource = GetWords(xdoc, _cRomajiName);
        jpnList.ItemsSource = GetWords(xdoc, _cJapaneseName);
    }

    private List<string> GetWords(XDocument xdoc, string name)
    {
        var words = from wordList in xdoc.Root.Elements(_cWordName)
                    select wordList.Element(name).Value;
        return words.ToList();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        LoadXmlData();
    }

    public class WordList
    {
        public string English { get; set; }
        public string Romaji { get; set; }
        public string Japanese { get; set; }
    }
}


Roman numeral converter I'm writing a program to convert integers to Roman numerals (naively -- it doesn't know how to do the subtraction trick yet). What I have is functional, but it is not "Good Ruby".

VALUES = [
  ["M", 1000],
  ["D", 500],
  ["C", 100],
  ["L", 50],
  ["X", 10],
  ["V", 5],
  ["I", 1],
]

def romanize n
  roman = ""

  VALUES.each do |pair|
    letter = pair[0]
    value = pair[1]
    roman += letter*(n / value)
    n = n % value
  end
  return roman
end

Perhaps a hash makes more sense than the array of arrays, but the way I update n, order matters. Passing in pair to the block is dumb, but passing letter, value didn't work in the way I expected.

I don't know what you mean about 'good ruby'. I show you a object-oriented version.
Instead of

romanize(4)

you can call

4.roman

My solution is similar to your solution. It is Hash-oriented, so you need ruby 1.9.

I also tried to use a array in array solution with ROMAN_NUMBERS.each do |value, letter| without any problem (I'm not sure if it is only ruby 1.9).

class Fixnum
  ROMAN_NUMBERS = {
    1000 => "M",
     900 => "CM",
     500 => "D",
     400 => "CD",
     100 => "C",
      90 => "XC",
      50 => "L",
      40 => "XL",
      10 => "X",
        9 => "IX",
        5 => "V",
        4 => "IV",
        1 => "I",
  }

  def roman
    n = self
    roman = ""
    ROMAN_NUMBERS.each do |value, letter|
      roman << letter*(n / value)
      n = n % value
    end
    return roman
  end
end

With ruby 1.8 you may add use ROMAN_NUMBERS.sort.each.

As an alternative, you can use a recursive solution:

class Fixnum
  ROMAN_NUMBERS = {
    1000 => "M",
     900 => "CM",
     500 => "D",
     400 => "CD",
     100 => "C",
      90 => "XC",
      50 => "L",
      40 => "XL",
      10 => "X",
        9 => "IX",
        5 => "V",
        4 => "IV",
        1 => "I",
        0 => "",
  }
  def roman
    return '' if self == 0
    ROMAN_NUMBERS.each do |value, letter|
      return ( letter * (self / value)) << (self % value).roman if value <= self
    end
    return (self % value).roman
  end
end

I don't recommend the recursive solution. Each number must start again with M.

A little testcode, to check the results:

require 'test/unit'

class NumberTest < Test::Unit::TestCase
  def test_0; assert_equal('',0.roman); end
  def test_1; assert_equal('I',1.roman); end
  def test_2; assert_equal('II',2.roman); end
  def test_3; assert_equal('III',3.roman); end
  def test_4; assert_equal('IV',4.roman); end
  def test_5; assert_equal('V',5.roman); end
  def test_6; assert_equal('VI',6.roman); end
  def test_7; assert_equal('VII',7.roman); end
  def test_8; assert_equal('VIII',8.roman); end
  def test_9; assert_equal('IX',9.roman); end
  def test_10; assert_equal('X',10.roman); end
  def test_11; assert_equal('XI',11.roman); end
  def test_12; assert_equal('XII',12.roman); end
  def test_13; assert_equal('XIII',13.roman); end
  def test_14; assert_equal('XIV',14.roman); end
  def test_15; assert_equal('XV',15.roman); end
  def test_16; assert_equal('XVI',16.roman); end
  def test_20; assert_equal('XX',20.roman); end
  def test_30; assert_equal('XXX',30.roman); end
  def test_40; assert_equal('XL',40.roman); end
  def test_50; assert_equal('L',50.roman); end
  def test_60; assert_equal('LX',60.roman); end
  def test_70; assert_equal('LXX',70.roman); end
  def test_80; assert_equal('LXXX',80.roman); end
  def test_90; assert_equal('XC',90.roman); end
  def test_99; assert_equal('XCIX',99.roman); end
  def test_100; assert_equal('C',100.roman); end
  def test_200; assert_equal('CC',200.roman); end
  def test_300; assert_equal('CCC',300.roman); end
  def test_400; assert_equal('CD',400.roman); end
  def test_500; assert_equal('D',500.roman); end
  def test_600; assert_equal('DC',600.roman); end
  def test_900; assert_equal('CM',900.roman); end
  def test_1000; assert_equal('M',1000.roman); end
  def test_2000; assert_equal('MM',2000.roman); end
  def test_2003; assert_equal('MMIII',2003.roman); end
end


Scan a spatio-temporal cube and run a cross-correlation on it I have a nested for-loop that looks like the following. The for-loop is used to scan a spatio-temporal (3D) cube and run a specific kind of cross-correlation used in seismology.
# some initialization
i,j,k = np.where(Pg1t > 0.1)
qp = np.sum(Pg1t[:-1,20:40,20:40],axis = 1)/20

corr_arr_x = np.zeros((1750,384,384))
corr_arr_y = np.zeros((1750,384,384))

# for-loop starts
for ii in range (0,1): # this range will actually go (0,1750)
    for jj in range (31,351):
        for kk in range (31,351):
            pulse_2d = np.zeros((39,63,63))
            pulse_2d[i,j,k] = Pressure[ii + i, jj - 31 + j, kk -31 + k]
            corr_arr_x[ii,jj,kk] = np.max(signal.correlate(np.sum(pulse_2d[:,20:40,20:40],axis = 2),qp))
            corr_arr_y[ii,jj,kk] = np.max(signal.correlate(np.sum(pulse_2d[:,20:40,20:40],axis = 1),qp))

Ofcourse this is not very smart way to do it and it takes 1 minute and 36 seconds to be executed. This means, if I select the first loop to run for (0 to 1750), then it will take around 40 hours or more. So I tried the itertools.
for x in itertools.product(np.linspace(0,1,1,dtype = 'int'), np.linspace(31,351-1,351-31,dtype = 'int'), np.linspace(31,351-1,351-31,dtype = 'int')):
    pulse_2d = np.zeros((39,63,63))
    pulse_2d[i,j,k] = Pressure[x[0] + i, x[1] - 31 + j, x[2] -31 + k]
    corr_arr_x[x[0],x[1],x[2]] = np.max(signal.correlate(np.sum(pulse_2d[:,20:40,20:40],axis = 2),qp))
    corr_arr_y[x[0],x[1],x[2]] = np.max(signal.correlate(np.sum(pulse_2d[:,20:40,20:40],axis = 1),qp))

However, this takes about 1 minute 27 seconds to be executed. Not a great improvement, may save an hour at best!
Is there any way to parallelize this code or optimize in any other way so that the execution time can be significantly decreased?

Scale
Since you have
for ii in range (0,1750):
    for jj in range (31,351):
        for kk in range (31,351):
            pulse_2d = np.zeros((39,63,63))

your inner loop will be on the order of
$$
1750 \cdot (351-31)^2 \cdot 39 \cdot 63^2 = 27,738,547,200,000
$$
That is well (well) beyond the point that I would give up Python altogether and drop down to C. Even if you were to vectorize this further with Numpy as much as possible (and I'm not clear on whether that's possible), I doubt that you could get this down to a sane execution time.
Strongly consider GSL and/or BLAS.


OOP design of code representing units of measurement I am developing a meta-data framework for monitoring systems such that I can easily create data adapters that can pull in data from different systems. One key component is the unit of measurement. To compare datasets which have different units I need to convert them to a common unit. To build adapters I need to have a system capable of describing complicated situations.

Units are just strings that define what the numbers mean e.g. 102 kWh is 102 kiloWatt hours, this can be converted to the SI unit for energy (Joules) by multiplying by a conversion factor (3600000 in this case).

Some data sources have built in conversion systems and provide me with data to a base unit that they specify, e.g. one database will give me energy data measured in various units (one may be called 'kWh*0.01', another 'Btu*1000'). These data will be provided along with a conversion factor to calculate the 'base unit' for that system which is e.g. GJ.

Here is my code to define units

class Unit(object):
    def __init__(self, base_unit, coefficient, name, suffix):
        self.name = name
        self.suffix = suffix
        self.base_unit = base_unit
        self.coefficient = float(coefficient)

    def to_base(self, value):
        return value * self.coefficient

    def from_base(self, value):
        return value / self.coefficient

    def to_unit(self, value, unit):
        if unit.base_unit != self.base_unit:
            raise TypeError, "Units derived from %s and %s are incompatible." % (self.base_unit, unit.base_unit)
        return unit.from_base(self.to_base(value))

    def __repr__(self):
        return "%s (%s)" % (self.name, self.suffix)

class BaseUnit(Unit):
    def __init__(self, name, suffix):
        super(BaseUnit, self).__init__(self, 1.0, name, suffix)

I use these classes to represent the unit information pulled from the source database. In this case, I pass in a record from the 'units' table and use the appropriate fields to construct a unit with the given description and abbreviation that can then be converted into the base unit provided by the system (GJ for energy, M3 for water).

def convert_unit(unit):
    """Convert a provided unit record into my unit"""
    desc = unit.description.strip()
    suffix = unit.abbreviation.strip()
    if unit.type == 'energy':
        base = BaseUnit("GigaJoules", "GJ")
        return Unit(base, float(unit.units_per_gj), desc, suffix)
    elif unit.type == 'water':
        base = BaseUnit("Cubic metres", "m3")
        return Unit(base, float(unit.units_per_m3), desc, suffix)
    else:
        return BaseUnit(desc, suffix)

When designing my classes I had in the back of my mind an idea to enforce a common base unit (e.g. Joules) for energy across multiple data sources, I think I can do this by adding another tier and simply making the current base unit a unit with a given base (may require hard coding the conversion factor between my base unit and GJ).

def convert_unit(unit):
    """Convert a provided unit record into my unit"""
    desc = unit.description.strip()
    suffix = unit.abbreviation.strip()
    if unit.type == 'energy':
        base = BaseUnit("Joules", "J")
        source_base = Unit(base, 1000000000, "GigaJoules", "GJ")
        return Unit(source_base, float(unit.units_per_gj), desc, suffix)
    elif unit.type == 'water':
        base = BaseUnit("Cubic metres", "m3")
        return Unit(base, float(unit.units_per_m3), desc, suffix)
    else:
        return BaseUnit(desc, suffix)

The to_base, from_base and to_unit methods are intended for use with numpy arrays of measurements. I typically use the unit classes inside a dataset class that holds data as a numpy array and a unit instance.

How does this look? It feels neat to me. Are there any style issues?

raise TypeError, "Units derived from %s and %s are incompatible." % (self.base_unit)

The python style guide recommends raising exceptions in the raise TypeError(message) form. TypeError is also questionable as the correct exception to throw here. The error here doesn't seem to be quite the same as making inappropriate use of python types. I'd have a UnitError class.

def __repr__(self):
     return "%s (%s)" % (self.name, self.suffix)

__repr__ is supposed to return either a valid python expression or something of the form <text>

base = BaseUnit("Cubic metres", "m3")

I'd make a global cubic meter object

My overall thought is: do you really need this? My inclination would be to convert all data to  the correct units as I read it. That way all data in my program would be using consistent units and I wouldn't have to worry about whether data is in some other exotic unit. Of course, depending on your exact scenario, that may not be a reasonable approach.


Passing connection for multiple classes/methods I have made a connection method which returns TCPMasterConnection.

public Class Connect{

String ipAddress;
int port;
TCPMasterConnection tcpCon;

    public TCPMasterConnection OverTCP(String ipAddress, int port)
    {
      this.ipAddress = ipAddress;
      this.port = port;

      TCPMasterConnection tcpConnection = null;

    try {
        tcpConnection = new TCPMasterConnection(InetAddress.getByName(ipAddress));
    } catch (Exception e) {
        e.getMessage();
    }
    tcpConnection.setPort(port);
    try {
        tcpConnection.connect();
    } catch (Exception e) {
        e.printStackTrace();
    }
      return tcpConnection;
    }

    public void setTcpCon(TCPMasterConnection tcpCon) {
       this.tcpCon = tcpCon;
    }
}

And I have multiple methods which uses TCPMasterConnection:

public Class Write extends Connect{

public int[] OverTCP_16Bit_Int(int unitID, int startAddress, int dataToWrite int count) throws Exception
{
   this.unitID = unitID;
   this.startAddress = startAddress;
   this.dataToWrite = dataToWrite;
   this.count = count;

   SimpleRegister reg = new SimpleRegister(dataToWrite);
   Register[] registers = new Register[count];

   for(int i = 0; i<registers.length; i++)
   {
       registers[i] = reg;
   }

   WriteMultipleRegistersRequest write_mreq = new WriteMultipleRegistersRequest();

   write_mreq.setReference(startAddress);
   write_mreq.setUnitID(unitID);
   write_mreq.setRegisters(registers);

   ModbusTCPTransaction transaction = new ModbusTCPTransaction(tcpCon);
   transaction.setRequest(write_mreq);
   transaction.execute();
   return transaction.getResponse();
  }
   public void setTcpCon(TCPMasterConnection tcpCon) {
     this.tcpCon = tcpCon;
   }
 }
}

public Class Read extends Connect{

public int[] OverTCP_16Bit_Int(int unitID, int startAddress, int count) throws Exception
{

this.unitID = unitID;
   this.startAddress = startAddress;
   this.count = count;
   this.x = new int [count];
   this.Stringas = new String[count];

   ReadMultipleRegistersRequest read_mreq = new ReadMultipleRegistersRequest();

   read_mreq.setUnitID(unitID);
   read_mreq.setReference(startAddress);
   read_mreq.setWordCount(count);

   ModbusTCPTransaction transaction = new ModbusTCPTransaction(tcpCon);
   transaction.setRequest(read_mreq);
   transaction.execute();
   ReadMultipleRegistersResponse read_mres = (ReadMultipleRegistersResponse) transaction.getResponse();

   for (int n = 0; n < read_mres.getWordCount(); n++)
   {
       x[n] = read_mres.getRegisterValue(n);
   }
  return x
  }
   public void setTcpCon(TCPMasterConnection tcpCon) {
      this.tcpCon = tcpCon;
 }
 }
}

So in main I do this:

public static void main(String[] args) throws Exception {

  String ip = "127.0.0.1";
  int port = 502;

  Connect connect = new Connect();

  Read read = new Read();
  Write write= new Write();

  TCPMasterConnection connectTCP = null;

  Connect[] objectList = new Connect[2];

  objectList[0] = read;
  objectList[1] = write;

  connectTCP = connect.OverTCP(ipAddress, port);

  for(Connect x: objectList){
      x.setTcpCon(connectTCP);
  }
}

Is this a proper way to do this?

So my point is to make a proper way to transfer connection through multiple classes for each method they have. So I don't have to do something like this every time user wants to use different function.

Connection connect = new Connect
TCPMasterConnection connectTCP = connect.OverTCP("127.0.0.1", 502);
read.setTcpCon(connectTCP);
read.DoStuff();

write.setTcpCon(connectTCP);
write.DoStuff();

I made in main class so that it transfers connection but I don't know if it is a proper way and overall I want to improve my code.

It may make sense to organize your objects in a different way.  With Read and Write extending Connect, you are basically treating them as if they are connections rather than being operations performed over a connection.

I think the most straightforward way to model operations over a connection would be something like this:

public static class GameConnection {
    private TCPMasterConnection conn;

    public void connectTo(String ipAddress, int port) throws IOException {
        conn = new TCPMasterConnection(InetAddress.getByName(ipAddress));
        conn.setPort(port);
        conn.connect();
    }

    public int[] read(int unitID, int startAddress, int count) throws IOException {
        // Do the read over this.conn
    }

    public int[] write(int unitID, int startAddress, int dataToWrite, int count) throws IOException {
        // Do the write over this.conn
    }

    public void close() throws IOException {
        conn.close();
    }
}

To use it, you then just

    GameConnection conn = new GameConnection();

    conn.connectTo("127.0.0.1", 8080);
    int[] readStuff = conn.read(1, 2, 3);
    int[] writeStuff = conn.write(1, 2, 3, 4);
    doSomeOtherThingsWithIt(conn);
    conn.close();

For more abstraction, you could make the GameConnection an interface and have different implementations for different transport protocols.


Coin Change: Minimum number of coins Problem:

  You are given n types of coin denominations of values \$v(1) < v(2) < ... < v(n)\$ (all integers). Assume \$v(1) = 1\$, so you can always make change for any amount of money \$C\$. Give an algorithm which makes change for an amount of money \$C\$ with as few coins as possible.

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

int main()
{
    int i,n,den[20],temp[20],min,min_idx, S, numcoins = 0;
    printf("Coin Change with min no. of coins\nEnter the total change you want: ");
    scanf("%d",&S);
    printf("Enter the no. of different denominations of coins available: ");
    scanf("%d",&n);
    printf("Enter the different denominations in ascending order: \n");
    for(i=0;i<n;i++)
        scanf("%d",&den[i]);
    while(S>0)
    {
        for(i=0;i<n;i++)
        temp[i] = S / den[i] ;
        /*calculate min from temp */
        min = temp[0] ;
        for(i=0;i<n;i++)
        {
            if(min > temp[i] && temp[i]!=0)
            {
                min = temp[i] ;
                min_idx = i ;
            }
        }
        numcoins += min ;
        S -= den[min_idx] * min ;
    }
    printf("min no of coins = %d" , numcoins) ;
    return 0;
}

In several solutions on the internet, I saw code using an array of the size of the total sum or value S, whereas I use only 2 arrays of size n, the number of different denominations available. That's why I was wondering whether my approach is correct or whether it's flawed.

Is it better or worse in terms of time complexity? Also, am I properly using dynamic programming principles in my code? Can it be made more efficient? The code ran correctly for several test cases.

I am sorry for poor code formatting and a not-so-clean code. It is a small code, so I hope it is understandable. My main concern is whether the code is dp or not, and if it can be improved for efficiency.

Currently, your code is next to unreadable.

The variable names are too cryptic. Names like den and S don't tell anything about the context of the variable.

Please, use descriptive names.

You don't give space for your variables to breath. You crammed everything up and that makes it harder to read.

An example:

for(i=0;i<n;i++)
temp[i] = S / den[i] ;

Could be written as

for(i = 0; i < n; i++)
temp[i] = S / den[i];

Still on the same for, you forgot to indent it.

Indentation is important to check what belongs where. Code is read far more times than written. Improve it's readability.

Still beating on that same for, you should always have brackets around your statements. Remember the Apple SSL bug? Well, it may happen with you.

Try this instead:

for(i = 0; i < n; i++)
{
    temp[i] = S / den[i];
}

You should declare your variables as close as possible of when you will use them.

One example is this:

for(i = 0; i < n; i++)
{
    temp[i] = S / den[i];
}

I would do like this:

for(int i = 0; i < n; i++)
{
    temp[i] = S / den[i];
}

A few lines below, you have this:

min = temp[0] ;
for(i=0;i<n;i++)

You start by giving min the value of temp[0]. Why don't you start the loop at 1? You reduce 1 iteration!

Like this:

int min = temp[0];
for(int i = 1; i < n; i++)

This would speed-up your code by a very small bit, but it is important to notice.

And to squeeze a tiny bit of performance, you can change:

if(min > temp[i] && temp[i]!=0)

Into this:

if(temp[i]!=0 && min > temp[i])

Now you ask: Why? And the answer is because of shortcut evaluation. If temp[0] is false, it won't evaluate min > temp[i], because we know that it will be false as well.

This won't save much, but you shave some comparisons. Which is really good!

If you want, I can even eliminate that tiny loop I've refered before:

int min = S / den[0];
int min_idx = 0;
for(int i = 1; i < n; i++)
{
    int temp = S / den[i];
    if(temp!=0 && min > temp)
    {
        min = temp;
        min_idx = i;
    }
}

And so, you can eliminate the tiny for and the temp[20]. This was untested and may not work!

You trust too much in the user. You have no validation what-so-ever! I could say I have 5 coins and then only give 2 denomination in the wrong order. What would happen?

Also, how can I say that I have a 0.5€ coin? Or a 2€ coin? Would it be 50 and 200?

I'm really sorry if I said something that might not fit at 100%. I'm not 100% confortable with C. But I hope I've helped you.


Parsing and converting DMS Coordinates from String to Double I have some coordinates looking like

  N47° 15' 36.75",E011° 20' 38.28",+001906.00

and I've created a class to parse and convert them to Double:

struct PLNWaypointCoordinate {
    var latitude: Double = 0.0
    var longitude: Double = 0.0

    init(coordinateString: String) {
        self.latitude = convertCoordinate(string: coordinateString.components(separatedBy: ",")[0])
        self.longitude = convertCoordinate(string: coordinateString.components(separatedBy: ",")[1])
    }

    private func convertCoordinate(string: String) -> Double {
        var separatedCoordinate = string.characters.split(separator: " ").map(String.init)

        let direction = separatedCoordinate[0].components(separatedBy: CharacterSet.letters.inverted).first
        let degrees = Double(separatedCoordinate[0].components(separatedBy: CharacterSet.decimalDigits.inverted)[1])
        let minutes = Double(separatedCoordinate[1].components(separatedBy: CharacterSet.decimalDigits.inverted)[0])
        let seconds = Double(separatedCoordinate[2].components(separatedBy: CharacterSet.decimalDigits.inverted)[0])

        return convert(degrees: degrees!, minutes: minutes!, seconds: seconds!, direction: direction!)
}

    private func convert(degrees: Double, minutes: Double, seconds: Double, direction: String) -> Double {
        let sign = (direction == "W" || direction == "S") ? -1.0 : 1.0
        return (degrees + (minutes + seconds/60.0)/60.0) * sign
    }

}

Is there a better and safer way to perform this conversion?

Last method I've picked up here. Sorry, but I can't find the link to reference it.

You have defined a value type (struct) and not a class, which is good. In

var latitude: Double = 0.0
var longitude: Double = 0.0

you can omit the type annotations because the compiler can infer the
type automatically:

var latitude = 0.0
var longitude = 0.0

But actually I would go the other way around and replace the initial
values by an init() method. The reason is that – since you defined
your own init method – there is no default memberwise initializer anymore.
Therefore I would start with

struct PLNWaypointCoordinate {
    var latitude: Double
    var longitude: Double

    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }

    // ...
}

which allows you to create a value not only from a string, but
also from a given latitude and longitude:

let c = PLNWaypointCoordinate(latitude: ..., longitude: ...)

Your init(coordinateString: String) method assumes that the given
string is in a valid format and can crash otherwise (by accesssing
out-of-bounds array elements or unwrapping nils). As
@Ashley already said in his answer, you should define a
failable initializer instead, which returns nil if the input is
invalid:

init?(coordinateString: String) { ... }

Alternatively, define a throwing initializer:

init(coordinateString: String) throws { ... }

which throws an error for invalid input.

Your helper methods convertCoordinate and convert are private,
which is good. They do not use any properties of the value, which means
that they can be made static.

The conversion helper function is very lenient, it will for example
accept X47 15 36.75 instead of N47° 15' 36.75"
as latitude. It does not check that the coordinate starts with
a valid direction, or that the proper separators are used.

I don't know what the final part +001906.00 stands for, but that
is ignored completely in your code.

There is also a flaw in your conversion, the fractional part
of the seconds is ignored, e.g. 36.75" is taken as 36 seconds.

I would suggest to use Scanner instead, which makes it relatively
easy to check for a valid input and simultaneously
parse the values into variables. To distinguish
 between latitude and longitude, two arguments for the positive
and the negative direction are passed to the helper method.

The complete code then looks like this:

struct PLNWaypointCoordinate {
    var latitude: Double
    var longitude: Double

    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }

    init?(coordinateString: String) {
        let components = coordinateString.components(separatedBy: ",")
        guard components.count >= 2,
            let latitude = PLNWaypointCoordinate.convertCoordinate(coordinate: components[0],
                                                                   positiveDirection: "N",
                                                                   negativeDirection: "S"),
            let longitude = PLNWaypointCoordinate.convertCoordinate(coordinate: components[1],
                                                                    positiveDirection: "E",
                                                                    negativeDirection: "W")
            else {
                return nil
        }
        self.init(latitude: latitude, longitude: longitude)
    }

    private static func convertCoordinate(coordinate: String,
                                          positiveDirection: String,
                                          negativeDirection: String) -> Double? {
        // Determine the sign from the first character:
        let sign: Double
        let scanner = Scanner(string: coordinate)
        if scanner.scanString(positiveDirection, into: nil) {
            sign = 1.0
        } else if scanner.scanString(negativeDirection, into: nil) {
            sign = -1.0
        } else {
            return nil
        }

        // Parse degrees, minutes, seconds:
        var degrees = 0
        var minutes = 0
        var seconds = 0.0
        guard scanner.scanInt(&degrees),         // Degrees (integer),
            scanner.scanString("°", into: nil),  // followed by °,
            scanner.scanInt(&minutes),           // minutes (integer)
            scanner.scanString("'", into: nil),  // followed by '
            scanner.scanDouble(&seconds),        // seconds (floating point),
            scanner.scanString("\"", into: nil), // followed by ",
            scanner.isAtEnd                      // and nothing else.
            else { return nil }

        return sign * (Double(degrees) + Double(minutes)/60.0 + seconds/3600.0)
    }
}


Boggle solver in Java This is a boggle solver in Java.  I would like code reviewers to optimize the code, suggest better coding practices, and help make it cleaner.

I am also unsure of the complexity and would appreciate an explanation of it.

public final class Boggle {

    private static final NavigableSet<String> dictionary;
    private final Map<Character, List<Character>> graph = new HashMap<Character, List<Character>>();

    static {
        dictionary = new TreeSet<String>();
        try {
            FileReader fr = new FileReader("/Users/ameya.patil/Desktop/text.txt");
            BufferedReader br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                dictionary.add(line.split(":")[0]);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error while reading dictionary");
        }
    }

    private Boggle() {}

    public static List<String> boggleSolver(char[][] m) {
        if (m == null) {
            throw new NullPointerException("The matrix cannot be null");
        }
        final List<String> validWords = new ArrayList<String>();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++) {
                solve(m, i, j, m[i][j] + "", validWords);
            }
        }
        return validWords;
    }

    private static void solve(char[][] m, int i, int j, String prefix, List<String> validWords) {
        assert m != null;
        assert validWords != null;

        for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {
            for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {
                if (i1 != i || j1 != j) {
                    String word = prefix+ m[i1][j1];

                    if (dictionary.contains(word)) {
                        validWords.add(word);
                    }

                    if (dictionary.subSet(word, word + Character.MAX_VALUE).size() > 0) {
                        solve(m, i1, j1, word, validWords);
                    }
                }
            }
        }
    }

    public static void main (String[] args) {
          char[][] board = { {'a', 'b', 'c', 'd' },
                             {'n', 'x', 'p', 'q' },
                             {'k', 't', 'i', 'w' },
                             {'e', 'f', 'g', 's' },
                          };

          List<String> list = Boggle.boggleSolver(board);
          for (String str :  list) {
              System.out.println(str);
          }
    }
}

According to the rules, you can only use each tile once per word.  You haven't attempted to keep track of tile usage.

Consider storing your dictionary using a trie, such as the implementation in Apache Commons.  It should provide an efficient .prefixMap(), which is like your dictionary.subSet().

You defined graph, but you never use it.

I think that an object-oriented interface would feel natural.  Create a new instance of Boggle by passing the char[][] matrix to the constructor.

Method names should be verbs, and shouldn't be redundant with the class name.  Therefore, .boggleSolver() should just be .solve().

The purpose of the loop…

for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {
    for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {
        if (i1 != i || j1 != j) {
            // loop body
        }
    }
}

… is to iterate through all the neighbours of tile (i, j).  A comment to that effect would be appreciated.  Also,  I would invert the if-condition to avoid a level of nesting:

// Iterate through the neighbours of tile (i, j)
for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {
    for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {
        // Skip the tile (i, j) itself
        if (i1 == i && j1 == j) continue;

        String word = prefix+ m[i1][j1];
        if (!dictionary.subSet(word, word + Character.MAX_VALUE).isEmpty()) {
            if (dictionary.contains(word)) {
                validWords.add(word);
            }
            solve(m, i1, j1, word, validWords);
        }
}

Note that the dictionary.contains(word) check can be moved inside the !dictionary.subSet(...).isEmpty() check.


Handling a response in a @Controller I have a simple spring controller which takes a @ModelAtrribute object and registers an employee. If it is a success, I forward it to a success, else an error page, and I am doing this via a boolean return value from @Service and Dao.

@Controller:

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView registerEmployee(@ModelAttribute LoginModel loginModel){
    LOGGER.info(" REGISTER Controller [{}] ",loginModel.toString());
    ModelAndView model = new ModelAndView();
    if(!registerService.registerEmployeeByAdmin(loginModel)){
      model.setViewName("register");
      model.addObject("errorMessage", "Unable to register user, Please try again");
      return model;
    }
    model.addObject("employee", loginModel);
    return model;
}

@Service:

public boolean registerEmployeeByAdmin(LoginModel loginModel){
    LOGGER.info("Saving Employee login info ",loginModel.toString());
    boolean registered = registerDao.registerEmployeeByAdmin(loginModel);
    if(registered)
        registerDao.registerEmployeeInfo(loginModel);

    return registered;   //the value returned
}

Dao:

public boolean registerEmployeeByAdmin(LoginModel loginModel) {
    boolean registered = false;
    String addEmployeeQuery = "insert into employee_login (loginid,password_hash,user_created_date,"
            + "email) values (?,?,?,?);";
    try (Connection conn = Database.getConnection(env);
            PreparedStatement pstmt = conn.prepareStatement(addEmployeeQuery);) {

        if (conn != null) {
            pstmt.setInt(1, loginModel.getUserid());
            pstmt.setString(2, EmployeeHelper.getHashFromPassword(loginModel.getPassword_hash()));
            pstmt.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis()));
            pstmt.setString(4, loginModel.getEmail());
            int rows = pstmt.executeUpdate();
            if (rows > 0)
                registered = true;
        }
    } catch (SQLException | NoSuchAlgorithmException e) {
        LOGGER.error("Error while adding user [{}] with error [{}]", loginModel.toString(), e);

    }
    return registered;
}

Is this the right way or can there be another way which is neat and clean?

There is another much simpler clean way.

Use ControllerAdvice and throw error from Service Layer itself. Build your common error response there. Yeah it is global exception handling.


Improving a robot's ability to navigate the plane with Karel J. Robot I am in my first year of formally learning computer programming in high school (we are using Java). One of the tools we used was Karel J. Robot, which can be downloaded here. Although we finished using Karel after a semester, I felt that there was a lot more I could do with it. I decided to use some of what we are now covering in the class and implement a coordinate system and other improvements. This may also become part of a larger project where I manipulate robot(s) on the plane to perform other tasks as part of an interpreter.

Here is the code I wrote:

//This class creates methods to govern the basic movements of the robot.
//The robot moves on a Cartesian plane with origin (1,1) and turns at 90˚ angles.
//Created 02/08/2016 by Trevor B. (Stack Exchange user Eridan)

import kareltherobot.Robot;

public class Commands extends Robot {
    private int xCoordinate;
    private int yCoordinate;
    private Direction currentDirection;
    private int beeperCount;

    public Commands(int street, int avenue, Direction direction, int beepers) {
        super(street, avenue, direction, beepers);

        xCoordinate = avenue;
        yCoordinate = street;
        currentDirection = direction;
        beeperCount = beepers;
    }

    //MOVEMENT

    public void move(int steps) {
        for(int i = 0; i < steps; i++) {
            super.move();
        }

        if(facingNorth()) {
            yCoordinate += steps;
        }
        else if(facingSouth()) {
            yCoordinate -= steps;
        }
        else if(facingEast()) {
            xCoordinate += steps;
        }
        else if(facingWest()) {
            xCoordinate -= steps;
        }
    }

    public void move() {
        move(1);
    }

    public void turnLeft(int leftTurns) {
        for(int i = 0; i < leftTurns; i++) {
            super.turnLeft();
        }
    }

    public void turnLeft() {
        turnLeft(1);
    }

    public void turnRight() {
        turnLeft(3);
    }

    public void turnAround() {
        turnLeft(2);
    }

    //DIRECTIONS

    public void faceNorth() {
        while(!facingNorth()) {
            turnLeft();
        }
        currentDirection = North;
    }

    public void faceSouth() {
        while(!facingSouth()) {
            turnLeft();
        }
        currentDirection = South;
    }

    public void faceEast() {
        while(!facingEast()) {
            turnLeft();
        }
        currentDirection = East;
    }

    public void faceWest() {
        while(!facingWest()) {
            turnLeft();
        }
        currentDirection = West;
    }

    //COORDINATE CHANGE

    public void coordinateChange(int xDestination, int yDestination) {
        int xDifference = xDestination - xCoordinate;
        int yDifference = yDestination - yCoordinate;

        if(xDifference > 0) {
            faceEast();
        }
        else if(xDifference < 0) {
            faceWest();
        }
        move(xDifference);

        if(yDifference > 0) {
            faceNorth();
        }
        else if(yDifference > 0) {
            faceSouth();
        }
        move(yDifference);
    }

    //BEEPER MANAGEMENT

    public void putBeeper(int drops) {
        for(int i = 0; i < drops; i++) {
            super.putBeeper();
        }
        beeperCount -= drops;
    }

    public void putBeeper() {
        putBeeper(1);
    }

    public void pickBeeper(int picks) {
        for(int i = 0; i < picks; i++) {
            super.pickBeeper();
        }
        beeperCount += picks;
    }

    public void pickBeeper() {
        pickBeeper(1);
    }

    public void putAllBeepers() {
        while(anyBeepersInBeeperBag()) {
            putBeeper();
        }
    }

    public void pickAllBeepers() {
        while(nextToABeeper()) {
            pickBeeper();
        }
    }
}

Is there anything I can do to improve this code? Please keep in mind that I'm a beginner to programming, so I apologize for any glaring failures to follow proper programming conventions.

Commands is a poor name for this class.  It's a robot of some kind.  Better names would be EnhancedRobot or GridAwareRobot or CartesianRobot.
What is the point of the currentDirection member variable?  It's a write-only variable, and is therefore useless.
Reusing code via inheritance is always tricky business, especially here, where the Robot class that you are extending is a bit of a poorly documented black box.
The way you use super calls is confusing.  For example, a call to Commands.move(2) chains to Robot.move().  However, to ensure that the zero-parameter .move() method on a Commands object works consistently, you also override Commands.move() to chain to move(1).  If you were to add another level of inheritance on top of this, it could get very difficult to trace what calls what, especially with overriding and overloading involved.
In addition, you also have to be concerned that the superclass methods to move, turn, and pick/drop beepers don't always succeed the way you would expect.  Indeed, a robot can enter a "crashed" state if it tries to drop a beeper when the bag is empty, or if it runs out of bounds, or if it runs into a wall (see the World class).  Since the Robot offers no way to detect and recover from such errors after the fact, you must proceed with extreme caution with every action.  This is especially important since your Commands and the underlying Robot are keeping track of the state independently, and your information could get out of sync if you assume that everything has gone smoothly.
The Robot's capabilities are actually deliberately limited to one primitive action at a time to force you to build reliable state machines in these exercises.  By writing a move(int steps) method, you are, in a sense, missing the point of these algorithm-design exercises.  What should happen if, say, Karel runs into a wall after 2 steps of a move(5)?  Karel has no remote-sensing capabilities, so your options are:

Let it crash, and fail the exercise. ☹

Move 2 steps, detect that the front is not clear, avoid telling the Robot superclass to move the third step, and somehow give your caller a way to query the position of the robot and deduce that the move(5) only got partially executed.  This is better than crashing, but puts your user in the nasty position of figuring out what to do with a partially-executed command.
And how would the user figure out what state Karel is in after a partially-executed command?  You'll notice that the language you are allowed to use in these exercises is a restricted subset of Java: you aren't supposed to assign or compare variables (except in a counting for-loop).1  In a sense, you have already cheated in writing this code, by assigning variables.  But with this strategy, you would also be forcing your user to cheat too.

Move 2 steps, detect that the front is not clear, turn around 180°, move 2 steps, and turn around 180° again.  This is known as atomically failing.  This kind of behaviour would restore sanity to your user's algorithms: at least you would be assured that after a move(5), the robot is in one of two states (either five steps ahead, or not moved at all).

Endow your Commands class with a canMove(int steps) method to emulate remote-sensing capability, which you implement by carefully walking out and walking back.  Then, if the user calls move(5) and crashes, it's not your fault.

You'll probably realize that none of these strategies is palatable, and do your exercises using a dumb Robot after all.

1 Based on the reference in Karel the Robot Learns Java, Appendix A


K Messed Array sort in Java Given an array of integers arr where each element is at most k places
  away from its sorted position, code an efficient function
  sortKMessedArray that sorts arr. For instance, for an input array of
  size 10 and k = 2, an element belonging to index 6 in the sorted array
  will be located at either index 4, 5, 6, 7 or 8 in the input array.

Analyze the time and space complexities of your solution.

  Example:

  input:  arr = [1, 4, 5, 2, 3, 7, 8, 6, 10, 9], k = 2

  output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Constraints:

[time limit] 5000ms

[input] array.integer arr

1 ≤ arr.length ≤ 100
[input] integer k

1 ≤ k ≤ 20
[output] array.integer

My approach improved :

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

class Solution {

  static int[] sortKMessedArray(int[] arr, int k) {

   int arrLen = arr.length;

   PriorityQueue<Integer> queue = new PriorityQueue<Integer>();

   //Store the first k+1 elements in the heap
   for( int i = 0; i <= k; i++ )
      queue.add(arr[i]);

   for( int i = k+1; i < arrLen; i++ )
   {
     //Extract the minimum element in the priority queue
     arr[i - (k + 1)] = queue.poll();

     //Add the next element to the queue
     queue.add(arr[i]);
   }

   //Extract the remaining elements from the queue and put it in the next index available
    for( int i = 0; i <= k; i++ )
      arr[ arrLen - k - 1 + i] = queue.poll();

   return arr;
  }

  public static void main(String[] args) {
   int [] arr = sortKMessedArray(new int[]{1,0},1);
   for( int m : arr )
      System.out.println(m);
  }

}

I have the following questions regarding my approach:

1) How can I further improve my approach?

2) Is there a better way to solve this question?

3) Are there any grave code violations that I have committed?

4) Can space and time complexity be further improved?

Reference

You should add a bounds check that k is not larger than your array, because I don't see that explicitly mentioned in the problem statement.

for( int i = 0; i <= k; i++ )
   queue.add(arr[i]);

I think you should always add braces, but that's my personal opinion.

//Store the first k+1 elements in the heap
for( int i = 0; i <= k; i++ )
   queue.add(arr[i]);

for( int i = k+1; i < arrLen; i++ )
{
  //Extract the minimum element in the priority queue
  arr[i - (k + 1)] = queue.poll();

  //Add the next element to the queue
  queue.add(arr[i]);
}

This bit would make more sense if you kept i as your arr index. Then swap the statement to get rid of the +1, ...

//Store the first k+1 elements in the heap
int i = 0;
for(; i < k; i++ )
   queue.add(arr[i]);

for( ; i < arrLen; i++ )
{
  //Add the next element to the queue
  queue.add(arr[i]);

  //Extract the minimum element in the priority queue
  arr[i - k] = queue.poll();
}

This also makes the next section pretty readable;

for( i -= k; i < arrLen; i++ ) //convert i into sorted array index by removing the k offset
  arr[i] = queue.poll();

You should also initialize the PriorityQueue with the capacity you're going to need; that's k + 1.


Calculate XOR of many consecutive and non-consecutive numbers question:

answer(start,length)

#start is the starting number of the matrix
 #length is number of rows.

example 1:

answer(0,3)

0 1 2 /
3 4 / 5
6 / 7 8

where the answer is 2 (by using  XOR (^) checksum is 0^1^2^3^4^6 == 2.)
example 2:

answer(17,4)

17 18 19 20 /
21 22 23 / 24
25 26 / 27 28
29 / 30 31 32

which produces the checksum 17^18^19^20^21^22^23^25^26^29 == 14.

All numbers are between 0 and 2000000000 inclusive, and the length of checkpoint line will always be at least 1.

input

(int) start = 0
(int) length = 3

Output:

(int) 2

Inputs:

(int) start = 17
(int) length = 4

Output:

(int) 14

my code:

def answer(start,length):
    num = start
    temp_len = length
    j = 0
    result = 0
    while num < (num+(length*length)) and temp_len > 0:
        #if required condition is not satisfied (when it reaches '/' in every row)
        if j == temp_len:
            j = 0
            num += length - temp_len
            temp_len -= 1
        #if required condition is satisfied
        else:
            j += 1
            #calculating XOR
            result ^= num
            num += 1
     return result

The problem with the code is that you are processing \$\sum _{ k=1 }^{ n }{ k } \$ (or \$1+2+3+(...)+n=\frac { n(n+1) }{ 2 }\$ ) integers. At most, you'll be processing 2 billion integers. A brute force method, such as the one you presented in your code, is inefficient and slow.

What you could do is take a different approach. Instead of XORing each integer, you could exploit a pattern that is present when XORing numbers. You exploit the pattern in each row, and then just XOR all the XOR sums you get from each processed row to get the checksum you need.

The XOR Pattern

Let us start by XORing numbers 0 to 3.

Obviously, XORing zero on its own gives us zero. Now, let's XOR 0 and 1 (0 ^ 1). We would get 1. XORing 0, 1, and 2 would give us 3. Lastly, XORing 0 to 3 would give us 0. Here's a visualization to make things simpler. Take note of the Output table.

0 => 0    0000 (0)    0000 (0)    0000 (0)        Output (0 to n)
        ^ 0001 (1)    0001 (1)    0001 (1)        -----------------
        ----------  ^ 0010 (2)    0010 (2)        (0 to 0) 0000 (0) # Equals to n
          0001 (1)  ----------  ^ 0011 (3)        (0 to 1) 0001 (1)
                      0011 (3)  ----------        (0 to 2) 0011 (3) # Equals to n + 1 (2 + 1)
                                  0000 (0)        (0 to 3) 0000 (0)

Let's now try XORing from 4 to 7. XORing 0 to 4 gives us 4. 0 to 5 gives us 1 (noticed anything yet?). 0 to 6 gives us 7. And lastly, 0 to 7 gives us 0.

  0000 (0)    0000 (0)    0000 (0)    0000 (0)    Output (0 to n)
  0001 (1)    0001 (1)    0001 (1)    0001 (1)    ---------------
  0010 (2)    0010 (2)    0010 (2)    0010 (2)    (0 to 4) 0100 (4) # Its' equal to n! (<= not a factorial)
  0011 (3)    0011 (3)    0011 (3)    0011 (3)    (0 to 5) 0001 (1) # Here goes this one again!
^ 0100 (4)    0100 (4)    0100 (4)    0100 (4)    (0 to 6) 0111 (7) # And it's equal to n + 1
----------  ^ 0101 (5)    0101 (5)    0101 (5)    (0 to 7) 0000 (0) # And this zero.
  0100 (4)  ----------  ^ 0110 (6)    0110 (6)
              0001 (1)  ----------  ^ 0111 (7)
                          0111 (7)  ----------
                                      0000 (0)

Have you noticed the pattern? It's right in front of you! We could definitely see that the pattern repeats every 4 numbers. Inferring from our output table, XORing to 0 and every fifth number would give us the fifth number; XORing to 1 and every sixth number would give us 1; XORing to 2 and every seventh number would give us 2 and the every seventh number plus one; and, XORing to 4 and every eigth number would give us 0.

From there, we easily get a pattern of n, 1, n + 1, 0. This also proves 200_success's answer where XORing to every fourth number (we're starting from 0) gives us 0.

Now that we have a pattern, we just need to create a function that will get the XOR sum from 0 to n. For this answer, let's call the function, f(). I'll leave the implementation to you as that is part of the challenge. We start at zero because the pattern starts at zero and could break if we start somewhere else. To get the XOR from a range (a to b), we just do f(b) ^ f(a - 1). Why it works? Read on.

Why Does \$f(b) \oplus f(a - 1)\$ Work?

The simple answer is that \$f(a - 1)\$ cancels out \$0 \oplus (...) \oplus (a - 1)\$ from \$f(b)\$ which is just \$0 \oplus (...) \oplus b\$.

Proof on why \$a \oplus (a + 1) \oplus (...) \oplus (b - 1) \oplus b = f(b) \oplus f(a - 1)\$

First of all, remember that XOR operations are associative, commutative, and reversable.

Let

$$n = a \oplus (a+1) \oplus (...) \oplus (b-1) \oplus (b) = 0$$

where \$a, b \in Z^{+}\$ and \$ a < b \$. \$n\$ is the XOR sum from \$a\$ to \$b\$.

Let us have a function \$f(b)\$ that gets the XOR sum from \$0\$ to \$b\$.

$$f(b) = 0 \oplus 1 \oplus 2 \oplus (...) \oplus b$$

Since \$a\$ is less than \$b\$ and XOR operations is associative, we can safely assume that

$$f(b) = (0 \oplus 1 \oplus (...) \oplus (a-1)) \oplus (a \oplus (a+1) \oplus (...) \oplus b)$$

Since \$(0 \oplus 1 \oplus (...) \oplus (a-1))\$ is equal to \$f(a-1)\$, and \$(a \oplus (a+1) \oplus (...) \oplus b)\$ is equal to \$n\$, we can simplify the equation above to

$$f(b) = f(a-1) \oplus n$$

Finally, since XOR operations are reversable, we get

$$n = f(a-1) \oplus f(b)$$

Through the commutative property of XOR operations, we finally get

$$n = f(b) \oplus f(a-1)$$

After getting the XOR sum of each row using f(b) ^ f(a - 1), we XOR all the XOR sums from each row, and we get the checksum that the problem requires.

Using the method I mentioned above, I can process answer(0, 50000) in approximately 0.08 seconds on my laptop with a Core i3 processor, and 4GB RAM.

Side note: These questions (1 and 2) can help you as well. I used the answers in those questions as a source for this answer, and in solving the same problem a few days ago (relative to writing this answer).


Assigning instance field inside method Look at the method setupCamera. I use it to reduce the size of the create method. As you can see, inside this method I instantiate camera and viewport, that are fields.
Is there any problem to do that, or exists  there any surer way to do that?

public class HudCameraSample extends ApplicationAdapter {

    private static final float SCREEN_WIDTH = 1280;
    private static final float SCREEN_HEIGHT = 720;
    private static final float SCENE_WIDTH = 12.8f;
    private static final float SCENE_HEIGHT = 7.2f;
    private static final float WORLD_TO_SCREEN = SCENE_HEIGHT / SCREEN_HEIGHT;

    private OrthographicCamera camera, hudCamera;
    private Viewport viewport, hudViewport;
    private SpriteBatch batch;

    @Override
    public void create() {
        setupCamera(camera, viewport, SCENE_WIDTH, SCENE_HEIGHT);
        setupCamera(hudCamera, hudViewport, SCREEN_WIDTH, SCREEN_HEIGHT);
    }

    private void setupCamera(Camera camera, Viewport viewport, float width, float height) {
        camera = new OrthographicCamera();
        viewport = new FillViewport(width, height, camera);
        camera.update();
    }

    @Override
    public void render() {

    }
}

Is there any problem to do that, or exists there any surer way to do that?

Yes, it's completely broken as in setupCamera you're assigning local variables and the fields remain untouched. There are no var parameters in Java. You'd actually need something allowing to return both camera and viewport. This is doable somehow, but too verbose for the little code you're trying to minimize.


Transformed and stored reversed order digits of an integer to a complete integer number Input:
Enter an integer number: 123456 [Any number of digits are allowed]

Output:
Completed integer number : 654321

I have solved this problem by following this strategy:
#include <stdio.h>
int main(void){
//put variables for further proceed
int number=get_input_validation();
int value=find_out_the_number_of_digit(number);
find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(number,value);
}
int get_input_validation(){

int number=0;

while(1){
//Taking input from the user
printf("Enter an integer number: ");
scanf("%d",&number);
if(number<=0){
    printf("Zero and negative numbers are not allowed here\n");
}
else{
    break;
}

}
return number;
}
int find_out_the_number_of_digit(int number){

int count=0;
int value=1;

//Getting total digits of a given integer number
while(number!=0){
    number=number/10;
    count++;
    if(count==1){
        value=1;
    }
    else{
        value=value*10;
    }

   }
   return value;
   }

 int find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(int number,int value){
 int complete_integer=0;

 while(number!=0){
    int last_digit=0;

    //get the last digit
    last_digit=number%10;

    //get the quotient
    number=number/10;

    complete_integer=complete_integer+last_digit*value;

    value=value/10;

   }

printf("Completed integer number : %d",complete_integer);
}

I am here for:
What about my indentation and comments? Will I face any problem for some conditions? How can I simplify my solution by reducing too much line of codes in an efficient way?

Indentation
The indentation of your post is very bad, mainly because it is very inconsistent. It doesn't really matter what indentation style you choose, as long as you consistently follow the style. However I strongly recommend the following things:

Use spaces around binary operators, after keywords, after comma's.
Use a single empty line around functions and if, case, do and while blocks.
Prefer foo += bar instead of foo = foo + bar to avoid repeating yourself.

So for example:
int find_out_the_number_of_digit(int number) {
    int count = 0;
    int value = 1;

    // Getting total digits of a given integer number
    while (number != 0) {
        number /= 10;
        count++;

        if (count == 1) {
            value = 1;
        } else {
            value *= 10;
        }
   }

   return value;
}

Try to write correctly formatted code at all times, it helps both yourself and others reading your code. If possible, configure your editor to automatically indent code for you. Be aware though that editors are usually a bit dumb and might not always produce correct indentation, in which case you should correct it yourself. You can also run your code through a program that indents the code for you, like indent or ClangFormat.
Comments
Use comments to clarify things that are not already clear from the code itself. Most of the comments you wrote are superfluous, because they repeat exactly what the code below does, or because it is already clear from the context. Let's look at your comments:
//put variables for further proceed
int number=get_input_validation();
int value=find_out_the_number_of_digit(number);

The sentence is not completely correct English, but it's clear that you mean you are storing information in variables for further processing. But that's just something that is done all the time when programming, it doesn't clarify anything here.
int get_input_validation(){
    ...
    //Taking input from the user
    printf("Enter an integer number: ");
    scanf("%d",&number);

It is already clear from both the name of the function and the two lines below that you are indeed reading input from the user. So in this case I would say the comment is superfluous. A comment like this might be useful however if you have a longer function that does multiple things, and where the comments then separate the various parts of the function, although in that case it is probably better to split such a function up into several smaller ones, which you already did here.
int find_out_the_number_of_digit(int number){
    ...
    //Getting total digits of a given integer number

Here the comment is just repeating what is already in the name of the function.
//get the last digit
last_digit=number%10;

//get the quotient
number=number/10;

Here each comment basically repeats exactly what the line below does. What would be better is to write a comment that explains what is happening at a higher level:
// Pop the last digit from number
last_digit = number % 10;
number /= 10;

Simplifying the solution
There is a simpler solution that is also more efficient, by avoiding the first pass over all the digits to find the length of the number. The solution could be a single loop that does this:
while (number != 0) {
    // Step 1: pop last digit from number
    ...

    // Step 2: push the digit to the back of complete_integer
    ...
}

Doing this will result in the order of the digits to be reversed. You already implemented popping the last digit from a number, now try to implement the reverse operation of pushing something to the back of a number, without having to know the exact length of that number.
About input validation
I wonder why you don't allow the number 0 to be reversed. It seems that this has a clear answer. You should be able to handle that case without having to write any additional code.
For negative numbers, you could indeed disallow them, or instead define how a negative number will be reversed. For example, you could say that the reverse of the number -123 will be -321, and then ensure your code implements this case. If the requirements for this project don't say anything about negative numbers, it is up to you.
Naming things
It is good to have descriptive names for functions and variables. One-letter names are usually bad, unless it's for very commonly used things such as i for a loop iterator, or x and y for coordinates. But too long names can be bad as well; they require more typing, and they are distracting. Not only try to be clear, also be concise. For example:
int find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(int number,int value){
    ...
}

That's a lot of text! Now compare the following:
int reverse_digits(int number) {
    ...
}

The name of this function, along with the type of the input parameters and return value, are still very descriptive; it tells you that if you give it a number as a parameter, the function will reverse the digits, and returns the result as an interger. The name is much more concise though.
Similarly, even though you shouldn't need this function, find_out_the_number_of_digit() could be shortened to count_digits().
On the other hand, also be aware of using too similar names. For example:
int number=get_input_validation();
int value=find_out_the_number_of_digit(number);

Now you have two variables, number and value. Now I have to look at what function was called to find out that value is actually the number of digits in number. Here is a suggestion for renaming it:
int input = get_input();
int digits_in_input = count_digits(input);


Vending machine change function Write a function that takes an amount of money M, a price P and returns the change given in the smallest number of coins. The following coins are available: 1c, 5c, 10c, 25c, 50c, and $1. Time: 20min.

I'm looking for all sorts of reviews considering the time limit and environment.

Here's my code:

#include <iostream>
#include <vector>

std::vector<int> getChange(double M, double P)
{
  /*
    1c, 5c, 10c, 25c, 50c, and $1
    getChange(3.14, 1.99) should return [0,1,1,0,0,1]
    getChange(4, 3.14) should return [1,0,1,1,1,0]
    getChange(0.45, 0.34) should return [1,0,1,0,0,0]
  */

  int denominations[] = {1, 5, 10, 25, 50, 100};
  std::vector<int> r(sizeof denominations / sizeof denominations[0]);

  // I had a floating-point problem here by computing cents = (M-P)*100;
  // it took me a few minutes to figure it out
  int cents = (int)(M*100) - (int)(P*100);

  for(int i = sizeof denominations / sizeof denominations[0] - 1; i >= 0; --i){
    r[i] = cents / denominations[i];
    cents = cents % denominations[i];
  }

  return r;
}

int main()
{
  auto change = getChange(5, 0.99);
  for(auto i : change){
      std::cout << i << ", ";
  }
  std::cout << std::endl;
  return 0;
}

You still have a floating point problem
If you change your line to this input:
auto change = getChange(0.04, 0.03);

you will get the following output:
2, 0, 0, 0, 0, 0,

As you can see, it answers with 2 pennies instead of one.  The problem is with the line that you "fixed":

// I had a floating-point problem here by computing cents = (M-P)*100;
// it took me a few minutes to figure it out
int cents = (int)(M*100) - (int)(P*100);

You did notice a problem with your floating point conversion but you came to the conclusion that it was the subtraction that was the problem.  The actual problem is that a floating point value of something like 0.03 can sometimes be slightly above or slightly below the actual value of 0.03.  In this case, it is slightly below.  When you convert this value to cents by using (int)(P*100), you end up converting something like 2.999999 to 2 instead of 3.
One way to avoid this problem is to round instead of truncate.  So you can change your line to this to fix the problem:
int cents = (int) (100*(M-P) + 0.5);


Decorating a timeout function I've picked up the timeout-function below from ActiveState's recipes for Python2 and polished it for python3.4.

Is there any leaner, less clunky way to write it?

import signal, time

class TimedOutExc(Exception):
    def __init__(self, value = "Timed Out"):
        self.value = value
    def __str__(self):
        return repr(self.value)

def TimedOutFn(f, timeout, *args, **kwargs):
    def handler(signum, frame):
        raise TimedOutExc()

    old = signal.signal(signal.SIGALRM, handler)
    signal.alarm(timeout)
    try:
        result = f(*args, **kwargs)
    finally:
        signal.signal(signal.SIGALRM, old)
    signal.alarm(0)
    return result

def timed_out(timeout):
    def decorate(f):
        def handler(signum, frame):
            raise TimedOutExc()

        def new_f(*args, **kwargs):
            old = signal.signal(signal.SIGALRM, handler)
            signal.alarm(timeout)
            try:
                result = f(*args, **kwargs)
            finally:
                signal.signal(signal.SIGALRM, old)
            signal.alarm(0)
            return result

        new_f.__name__ = f.__name__
        return new_f

    return decorate

def fn_1(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(4)
def fn_2(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(2)
def fn_3(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(2)
def fn_4(secs):
    try:
        time.sleep(secs)
        return "Finished"
    except TimedOutExc:
        print( "(Caught TimedOutExc, so cleaining up, and re-raising it) - ")
        raise TimedOutExc

if __name__ == '__main__':

    try:
        print( "fn_1 (sleep 2, timeout 4): ")
        print( TimedOutFn(fn_1, 4, 2) )
    except TimedOutExc:
        print( "took too long")

    try:
        print( "fn_2 (sleep 2, timeout 4): ")
        print( fn_2(2) )
    except TimedOutExc:
        print( "took too long")

    try:
        print( "fn_1 (sleep 4, timeout 2): ")
        print( TimedOutFn(fn_1, 2, 4) )
    except TimedOutExc:
        print( "took too long")

    try:
        print( "fn_3 (sleep 4, timeout 2): ")
        print( fn_3(4) )
    except TimedOutExc:
        print( "took too long")

    try:
        print( "fn_4 (sleep 4, timeout 2): ")
        print( fn_4(4) )
    except TimedOutExc:
        print( "took too long")

1. Review

There are no docstrings. What do these functions do? How am I supposed to use them?
The use of the alarm mechanism means that the timeout occurs asynchronously with respect to the timed out function, and so data structures may be left in an inconsistent state. It's important to warn the user about this: it's hard to write functions that are safe against timeouts of this kind.
The functions and classes could have better names: I suggest TimedOutExc → TimedOut (it's clear that it's an exception because of its superclass); TimedOutFn → call_with_timeout (following PEP8); timed_out → with_timeout.
There's no need to give the exception class its own __init__ and __str__ method: the Exception class already has these methods.
The implementation of the timed_out decorator is almost identical to TimedOutFn. It would be better for new_f to call TimedOutFn instead of repeating the code.
The decorator copies __name__ from the original function, but what about __doc__ and __module__ and __qualname__? It would be better to use the built-in functools.wraps.
I think it's slightly better for call_with_timeout to take the timeout argument first. That way the function and its arguments are adjacent.
In call_with_timeout, there are two state changes that need to be reverted: the updating of the signal handler, and the setting of the alarm. But only one of these is protected by a try: ... finally: ....
There's a lot of duplicated code in the test cases. This could be refactored into methods.
The test cases don't actually tell you whether the tests passed or failed (you have to know what the output is supposed to be in each case). It would be a good idea to use the facilities in the unittest module.

2. Revised code

import functools
import signal

class TimedOut(Exception):
    pass

def call_with_timeout(timeout, f, *args, **kwargs):
    """Call f with the given arguments, but if timeout seconds pass before
    f returns, raise TimedOut. The exception is raised asynchronously,
    so data structures being updated by f may be in an inconsistent state.

    """
    def handler(signum, frame):
        raise TimedOut("Timed out after {} seconds.".format(timeout))
    old = signal.signal(signal.SIGALRM, handler)
    try:
        signal.alarm(timeout)
        try:
            return f(*args, **kwargs)
        finally:
            signal.alarm(0)
    finally:
        signal.signal(signal.SIGALRM, old)

def with_timeout(timeout):
    """Decorator for a function that causes it to timeout after the given
    number of seconds.

    """
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            return call_with_timeout(timeout, f, *args, **kwargs)
        return wrapped
    return decorator


User account code with GET and POST I'm new to Python and GAE, but years of procedural programming. I have this code, but I know that there must be some better solution to avoid retyping code.

The first and last section of code are identical in both GET and POST methods, so I suppose there must be another way to share the identical code.

# This class manage the user account
class MyAccount(webapp2.RequestHandler):
        def get(self):
                """ Shows actual user account """

                # Get actual user
                user = users.get_current_user()

                if user:
                        # Get the actual user data
                        data = Person.gql("WHERE username = :nick",
                                                            nick=user.nickname()).get()

                        # Test if we found the user
                        if data:
                                templateValues['data'] = data
                                template = jinja_environment.get_template('myAccount.htm')
                        else:
                                templateValues['custom_msg'] = "The logged user is not available."
                                template = jinja_environment.get_template('customMessage.htm')

                else:
                        templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account"
                        template = jinja_environment.get_template('customMessage.htm')

                # Render the page
                self.response.out.write(template.render(templateValues))

        def post(self):
                """ Saves user updated data """

                # Get actual user
                user = users.get_current_user()

                if user:
                        # Get the actual user data
                        person = Person.gql("WHERE username = :nick",
                                                            nick=user.nickname()).get()

                        # Test if we found the user
                        if person:
                                person.username = self.request.get('username')
                                person.password = self.request.get('password')
                                if person.email: self.request.get('email')
                                person.name = self.request.get('name')
                                person.lastname = self.request.get('lastname')
                                person.idnumber = self.request.get('idnumber')

                                templateValues['data'] = person
                                template = jinja_environment.get_template('myAccount.htm')

                        else:
                                templateValues['custom_msg'] = "The logged user is not available."
                                template = jinja_environment.get_template('customMessage.htm')

                else:
                        templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account."
                        template = jinja_environment.get_template('customMessage.htm')

                # Render the page
                self.response.out.write(template.render(templateValues))

This line looks suspicious:

            if person.email: self.request.get('email')

I assume it should be:

            person.email = self.request.get('email')

Your code seem to be using excessive indentation. The python standard is four space per level.

You are using templateValues but don't seem to define it anywhere.

To refactor this, I'd start by removing the section of that that's different between the two methods into their own function:

# This class manage the user account
class MyAccount(webapp2.RequestHandler):

    def show_user(self, user):
        # Get the actual user data
        data = Person.gql("WHERE username = :nick",
                                            nick=user.nickname()).get()
        # Test if we found the user
        if data:
            templateValues['data'] = data
            template = jinja_environment.get_template('myAccount.htm')
        else:
            templateValues['custom_msg'] = "The logged user is not available."
            template = jinja_environment.get_template('customMessage.htm')

        return template, templateValues

    def get(self):
        """ Shows actual user account """

        # Get actual user
        user = users.get_current_user()
        if user:
            template, templateValues = self.show_user(user)
        else:
            templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account"
            template = jinja_environment.get_template('customMessage.htm')

        # Render the page
        self.response.out.write(template.render(templateValues))

    def update_user(self, user):
        # Get the actual user data
        person = Person.gql("WHERE username = :nick",
                nick=user.nickname()).get()
        # Test if we found the user
        if person:
            person.username = self.request.get('username')
            person.password = self.request.get('password')
            person.email = self.request.get('email')
            person.name = self.request.get('name')
            person.lastname = self.request.get('lastname')
            person.idnumber = self.request.get('idnumber')

            templateValues['data'] = person
            template = jinja_environment.get_template('myAccount.htm')
        else:
            templateValues['custom_msg'] = "The logged user is not available."
            template = jinja_environment.get_template('customMessage.htm')

        return template, templateValues

    def post(self):
        """ Saves user updated data """
        # Get actual user
        user = users.get_current_user()
        if user:
            template, templateValues = self.update_user(user)
        else:
            templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account."
            template = jinja_environment.get_template('customMessage.htm')
        # Render the page
        self.response.out.write(template.render(templateValues))

The only thing different between post and get is the function they call. We'll just pass the function as a parameter to a new function.

    def request(self, handler):
        """ Shows actual user account """

        # Get actual user
        user = users.get_current_user()
        if user:
            template, templateValues = handler(user)
        else:
            templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account"
            template = jinja_environment.get_template('customMessage.htm')

        # Render the page
        self.response.out.write(template.render(templateValues))

    def get(self):
        return self.request(self.show_user)

    def post(self):
        return self.request(self.update_user)

The current code repeats calls to get_template a lot. So we'll refactor it so that it only happens once. We'll just store the name of the template in a variable and load it just before we render it.

def show_user(self, user):
    # Get the actual user data
    data = Person.gql("WHERE username = :nick",
                                        nick=user.nickname()).get()
    # Test if we found the user
    if data:
        templateValues['data'] = data
        template = 'myAccount.htm'
    else:
        templateValues['custom_msg'] = "The logged user is not available."
        template = 'customMessage.htm'

    return template, templateValues

def request(self, handler):
    """ Shows actual user account """

    # Get actual user
    user = users.get_current_user()
    if user:
        template, templateValues = handler(user)
    else:
        templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account"
        template = 'customMessage.htm'

    # Render the page
    template = jinja_environment.get_template(template)
    self.response.out.write(template.render(templateValues))

But we can clean up our actual work functions a little more:

def show_user(self, user):
    # Get the actual user data
    data = Person.gql("WHERE username = :nick",
                                        nick=user.nickname()).get()
    # Test if we found the user
    if data:
        return 'myAccount.htm', {
                'data' : data
        }
    else:
        return 'custom_msg.htm', {
                'custom_msg' : "The logged user is not available."
        }


Is this a proper way to check a viewstate of type int? In page load I'm saving a query string int value in a viewstate. Then I save it to my DB. Here is the code I use to retrieve viewstate value and validating it:

protected int CurrentCom
{
    get
    {
        if (ViewState["CurrentCom"] == null)
            return 0;
        else
        {
            int temp;
            if (int.TryParse(ViewState["CurrentCom"].ToString(), out temp))
                return temp;
            else return 0;
        }

    }
    set { ViewState["CurrentCom"] = value; }
}

Is there a better way to make this shorter?

I usually do like this:

return (int)(ViewState["CurrentCom"] ?? 0);