Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
f0rk committed Mar 2, 2015
0 parents commit 3c580ac
Show file tree
Hide file tree
Showing 8 changed files with 350 additions and 0 deletions.
56 changes: 56 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml

# Translations
*.mo
*.pot

# Django stuff:
*.log

# Sphinx documentation
docs/_build/

# PyBuilder
target/
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2015 Truveris Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Overpunch Parser/Formatter

Extract and generate [overpunch](https://en.wikipedia.org/wiki/Signed_overpunch) formatted numbers.

## Examples:

```python
>>> import overpunch
>>> overpunch.format(123.45)
'1234E'
>>> overpunch.extract("1234E")
Decimal('123.45')
```

## Requirements:
* Python 2.7+

## Tests:
Without coverage:

```shell
$ nosetests
```

With coverage:

```shell
$ nosetests --with-coverage --cover-package=overpunch
```

137 changes: 137 additions & 0 deletions overpunch/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# Copyright 2015, Truveris Inc.

"""
Extract and generate overpunch formatted numbers.
"""

from decimal import Decimal, ROUND_HALF_UP


__copyright__ = "(c) 2015 Truveris"
__version__ = "1.0"


EXTRACT_REF = {
"0": ("+", "0"),
"1": ("+", "1"),
"2": ("+", "2"),
"3": ("+", "3"),
"4": ("+", "4"),
"5": ("+", "5"),
"6": ("+", "6"),
"7": ("+", "7"),
"8": ("+", "8"),
"9": ("+", "9"),
"{": ("+", "0"),
"A": ("+", "1"),
"B": ("+", "2"),
"C": ("+", "3"),
"D": ("+", "4"),
"E": ("+", "5"),
"F": ("+", "6"),
"G": ("+", "7"),
"H": ("+", "8"),
"I": ("+", "9"),
"}": ("-", "0"),
"J": ("-", "1"),
"K": ("-", "2"),
"L": ("-", "3"),
"M": ("-", "4"),
"N": ("-", "5"),
"O": ("-", "6"),
"P": ("-", "7"),
"Q": ("-", "8"),
"R": ("-", "9"),
}


def extract(raw, decimals=2):
"""Extract a number in the overpunch format to a Decimal object.
:param raw: The formmated value.
:param decimals: The implied decimal precision of this number (default: 2).
"""

length = len(raw)
last_char = raw[length - 1]
(sign, cent) = EXTRACT_REF[last_char]

if not decimals:
core = raw[:-1]
else:
core = raw[:length-decimals] + "." + raw[length-decimals:-1]

return Decimal(sign + core + cent)


FORMAT_REF = {
("+", "0"): "{",
("+", "1"): "A",
("+", "2"): "B",
("+", "3"): "C",
("+", "4"): "D",
("+", "5"): "E",
("+", "6"): "F",
("+", "7"): "G",
("+", "8"): "H",
("+", "9"): "I",
("-", "0"): "}",
("-", "1"): "J",
("-", "2"): "K",
("-", "3"): "L",
("-", "4"): "M",
("-", "5"): "N",
("-", "6"): "O",
("-", "7"): "P",
("-", "8"): "Q",
("-", "9"): "R",
}


def format(val, decimals=2, rounding=ROUND_HALF_UP):
"""Convert a number to an overpunch-formatted string.
:param val: The number to format.
:param decimals: How many decimals are implied in the formatted value
(default: 2).
:param rounding: When rounding a value during quantization, how that value
is to be rounded. Approrpiate values are the rounding constants from
the ``decimal`` library (default: ROUND_HALF_UP).
"""

if not isinstance(val, Decimal):
val = Decimal(str(val))

if val.is_nan():
raise ValueError("{} is NaN".format(val))

# force the correct number of decimal digits
quantize_str = "1"
if decimals:
quantize_str = quantize_str + "." + ("0" * decimals)

val = val.quantize(Decimal(quantize_str), rounding)

# we'll need this to figure out how to format the last character
if val.is_signed():
sign = "-"
else:
sign = "+"

# get rid of the sign
val = abs(val)

# turn into a string
val = str(val)

# remove the "."
val = val.replace(".", "")

# split, replace the last digit with the right format character, join
parts = list(val)
parts[-1] = FORMAT_REF[(sign, parts[-1])]

return "".join(parts)

Empty file added overpunch/tests/__init__.py
Empty file.
83 changes: 83 additions & 0 deletions overpunch/tests/test_overpunch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Copyright 2015, Truveris Inc.

import sys
import random
import unittest
from decimal import Decimal, ROUND_FLOOR

import overpunch


class TestCase(unittest.TestCase):

"""
Test cases for overpunched extraction and formatting.
"""

def test_extract_no_decimal_positive(self):
d = Decimal("1234.50")
self.assertEquals(overpunch.extract("12345{"), d)

def test_extract_no_decimal_negative(self):
d = Decimal("-1234.50")
self.assertEquals(overpunch.extract("12345}"), d)

def test_extract_4_decimal_negative(self):
d = Decimal("-12.3450")
self.assertEquals(overpunch.extract("12345}", decimals=4), d)

def test_extract_0_decimal_negative(self):
d = Decimal("-123450")
self.assertEquals(overpunch.extract("12345}", decimals=0), d)

def test_format_no_decimal_positive(self):
d = Decimal("1234.50")
self.assertEquals("12345{", overpunch.format(d))

def test_format_no_decimal_negative(self):
d = Decimal("-1234.50")
self.assertEquals("12345}", overpunch.format(d))

def test_format_4_decimal_negative(self):
d = Decimal("-12.3450")
self.assertEquals("12345}", overpunch.format(d, decimals=4))

def test_format_0_decimal_negative(self):
d = Decimal("-123450")
self.assertEquals("12345}", overpunch.format(d, decimals=0))

def test_format_2_decimal_round_default(self):
d = Decimal("12.3450")
self.assertEquals("123E", overpunch.format(d, decimals=2))

def test_format_2_decimal_negative_round_default(self):
d = Decimal("-12.3450")
self.assertEquals("123N", overpunch.format(d, decimals=2))

def test_format_2_decimal_round_custom(self):
d = Decimal("12.3450")
self.assertEquals("123D", overpunch.format(d, decimals=2,
rounding=ROUND_FLOOR))

def test_format_2_decimal_negative_round_custom(self):
d = Decimal("-12.3450")
self.assertEquals("123N", overpunch.format(d, decimals=2,
rounding=ROUND_FLOOR))

def test_nan_raises(self):
d = Decimal("NaN")
with self.assertRaises(ValueError) as cm:
overpunch.format(d)

def test_format_integer(self):
d = 150
self.assertEquals("15{", overpunch.format(d, decimals=0))

def test_random(self):
for i in range(1000):
d = Decimal(random.randint(0, sys.maxint)) / 100
if random.random() > 0.5:
d = -d

self.assertEquals(overpunch.extract(overpunch.format(d)), d)

23 changes: 23 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Copyright 2015, Truveris Inc.

try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages

from overpunch import __version__


setup(
name="overpunch",
version=__version__,
description="Overpunch Parser/Formatter",
author="Truveris Inc.",
author_email="[email protected]",
url="http://github.com/truveris/overpunch",
test_suite="nose.collector",
packages=find_packages(exclude=["ez_setup"]),
)

2 changes: 2 additions & 0 deletions stdeb.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[DEFAULT]
XS-Python-Version: >= 2.7

0 comments on commit 3c580ac

Please sign in to comment.