prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, NetworkThread from test_framework.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP from binascii import hexlify, unhexlify import cStringIO import time def cltv_invalidate(tx): '''Modify the signature in vin 0 of the tx to fail CLTV Prepends -1 CLTV DROP in the scriptSig itself. ''' tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] + list(CScript(tx.vin[0].scriptSig))) ''' This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY) Connect to a single node. Mine 2 (version 3) blocks (save the coinbases for later). Generate 98 more version 3 blocks, verify the node accepts. Mine 749 version 4 blocks, verify the node accepts. Check that the new CLTV rules are not enforced on the 750th version 4 block. Check that the new CLTV rules are enforced on the 751st version 4 block. Mine 199 new version blocks. Mine 1 old-version block. Mine 1 new version block. Mine 1 old version block, see that the node rejects. ''' class BIP65Test(ComparisonTestFramework): def __init__(self): self.num_nodes = 1 def <|fim_middle|>(self): # Must set the blockversion for this test self.nodes = start_nodes(1, self.options.tmpdir, extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']], binary=[self.options.testbinary]) def run_test(self): test = TestManager(self, self.options.tmpdir) test.add_all_connections(self.nodes) NetworkThread().start() # Start up network handling in another thread test.run() def create_transaction(self, node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransaction(rawtx) tx = CTransaction() f = cStringIO.StringIO(unhexlify(signresult['hex'])) tx.deserialize(f) return tx def get_tests(self): self.coinbase_blocks = self.nodes[0].setgenerate(True, 2) self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0) self.nodeaddress = self.nodes[0].getnewaddress() self.last_block_time = time.time() ''' 98 more version 3 blocks ''' test_blocks = [] for i in xrange(98): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 749 version 4 blocks ''' test_blocks = [] for i in xrange(749): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Check that the new CLTV rules are not enforced in the 750th version 3 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[0], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Check that the new CLTV rules are enforced in the 751st version 4 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) ''' Mine 199 new version blocks on last valid tip ''' test_blocks = [] for i in xrange(199): block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 1 old version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 new version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 old version block, should be invalid ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) if __name__ == '__main__': BIP65Test().main() <|fim▁end|>
setup_network
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, NetworkThread from test_framework.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP from binascii import hexlify, unhexlify import cStringIO import time def cltv_invalidate(tx): '''Modify the signature in vin 0 of the tx to fail CLTV Prepends -1 CLTV DROP in the scriptSig itself. ''' tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] + list(CScript(tx.vin[0].scriptSig))) ''' This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY) Connect to a single node. Mine 2 (version 3) blocks (save the coinbases for later). Generate 98 more version 3 blocks, verify the node accepts. Mine 749 version 4 blocks, verify the node accepts. Check that the new CLTV rules are not enforced on the 750th version 4 block. Check that the new CLTV rules are enforced on the 751st version 4 block. Mine 199 new version blocks. Mine 1 old-version block. Mine 1 new version block. Mine 1 old version block, see that the node rejects. ''' class BIP65Test(ComparisonTestFramework): def __init__(self): self.num_nodes = 1 def setup_network(self): # Must set the blockversion for this test self.nodes = start_nodes(1, self.options.tmpdir, extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']], binary=[self.options.testbinary]) def <|fim_middle|>(self): test = TestManager(self, self.options.tmpdir) test.add_all_connections(self.nodes) NetworkThread().start() # Start up network handling in another thread test.run() def create_transaction(self, node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransaction(rawtx) tx = CTransaction() f = cStringIO.StringIO(unhexlify(signresult['hex'])) tx.deserialize(f) return tx def get_tests(self): self.coinbase_blocks = self.nodes[0].setgenerate(True, 2) self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0) self.nodeaddress = self.nodes[0].getnewaddress() self.last_block_time = time.time() ''' 98 more version 3 blocks ''' test_blocks = [] for i in xrange(98): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 749 version 4 blocks ''' test_blocks = [] for i in xrange(749): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Check that the new CLTV rules are not enforced in the 750th version 3 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[0], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Check that the new CLTV rules are enforced in the 751st version 4 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) ''' Mine 199 new version blocks on last valid tip ''' test_blocks = [] for i in xrange(199): block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 1 old version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 new version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 old version block, should be invalid ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) if __name__ == '__main__': BIP65Test().main() <|fim▁end|>
run_test
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, NetworkThread from test_framework.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP from binascii import hexlify, unhexlify import cStringIO import time def cltv_invalidate(tx): '''Modify the signature in vin 0 of the tx to fail CLTV Prepends -1 CLTV DROP in the scriptSig itself. ''' tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] + list(CScript(tx.vin[0].scriptSig))) ''' This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY) Connect to a single node. Mine 2 (version 3) blocks (save the coinbases for later). Generate 98 more version 3 blocks, verify the node accepts. Mine 749 version 4 blocks, verify the node accepts. Check that the new CLTV rules are not enforced on the 750th version 4 block. Check that the new CLTV rules are enforced on the 751st version 4 block. Mine 199 new version blocks. Mine 1 old-version block. Mine 1 new version block. Mine 1 old version block, see that the node rejects. ''' class BIP65Test(ComparisonTestFramework): def __init__(self): self.num_nodes = 1 def setup_network(self): # Must set the blockversion for this test self.nodes = start_nodes(1, self.options.tmpdir, extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']], binary=[self.options.testbinary]) def run_test(self): test = TestManager(self, self.options.tmpdir) test.add_all_connections(self.nodes) NetworkThread().start() # Start up network handling in another thread test.run() def <|fim_middle|>(self, node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransaction(rawtx) tx = CTransaction() f = cStringIO.StringIO(unhexlify(signresult['hex'])) tx.deserialize(f) return tx def get_tests(self): self.coinbase_blocks = self.nodes[0].setgenerate(True, 2) self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0) self.nodeaddress = self.nodes[0].getnewaddress() self.last_block_time = time.time() ''' 98 more version 3 blocks ''' test_blocks = [] for i in xrange(98): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 749 version 4 blocks ''' test_blocks = [] for i in xrange(749): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Check that the new CLTV rules are not enforced in the 750th version 3 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[0], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Check that the new CLTV rules are enforced in the 751st version 4 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) ''' Mine 199 new version blocks on last valid tip ''' test_blocks = [] for i in xrange(199): block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 1 old version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 new version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 old version block, should be invalid ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) if __name__ == '__main__': BIP65Test().main() <|fim▁end|>
create_transaction
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, NetworkThread from test_framework.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP from binascii import hexlify, unhexlify import cStringIO import time def cltv_invalidate(tx): '''Modify the signature in vin 0 of the tx to fail CLTV Prepends -1 CLTV DROP in the scriptSig itself. ''' tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] + list(CScript(tx.vin[0].scriptSig))) ''' This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY) Connect to a single node. Mine 2 (version 3) blocks (save the coinbases for later). Generate 98 more version 3 blocks, verify the node accepts. Mine 749 version 4 blocks, verify the node accepts. Check that the new CLTV rules are not enforced on the 750th version 4 block. Check that the new CLTV rules are enforced on the 751st version 4 block. Mine 199 new version blocks. Mine 1 old-version block. Mine 1 new version block. Mine 1 old version block, see that the node rejects. ''' class BIP65Test(ComparisonTestFramework): def __init__(self): self.num_nodes = 1 def setup_network(self): # Must set the blockversion for this test self.nodes = start_nodes(1, self.options.tmpdir, extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']], binary=[self.options.testbinary]) def run_test(self): test = TestManager(self, self.options.tmpdir) test.add_all_connections(self.nodes) NetworkThread().start() # Start up network handling in another thread test.run() def create_transaction(self, node, coinbase, to_address, amount): from_txid = node.getblock(coinbase)['tx'][0] inputs = [{ "txid" : from_txid, "vout" : 0}] outputs = { to_address : amount } rawtx = node.createrawtransaction(inputs, outputs) signresult = node.signrawtransaction(rawtx) tx = CTransaction() f = cStringIO.StringIO(unhexlify(signresult['hex'])) tx.deserialize(f) return tx def <|fim_middle|>(self): self.coinbase_blocks = self.nodes[0].setgenerate(True, 2) self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0) self.nodeaddress = self.nodes[0].getnewaddress() self.last_block_time = time.time() ''' 98 more version 3 blocks ''' test_blocks = [] for i in xrange(98): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 749 version 4 blocks ''' test_blocks = [] for i in xrange(749): block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Check that the new CLTV rules are not enforced in the 750th version 3 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[0], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Check that the new CLTV rules are enforced in the 751st version 4 block. ''' spendtx = self.create_transaction(self.nodes[0], self.coinbase_blocks[1], self.nodeaddress, 1.0) cltv_invalidate(spendtx) spendtx.rehash() block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.vtx.append(spendtx) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) ''' Mine 199 new version blocks on last valid tip ''' test_blocks = [] for i in xrange(199): block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() test_blocks.append([block, True]) self.last_block_time += 1 self.tip = block.sha256 yield TestInstance(test_blocks, sync_every_block=False) ''' Mine 1 old version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 new version block ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 4 block.rehash() block.solve() self.last_block_time += 1 self.tip = block.sha256 yield TestInstance([[block, True]]) ''' Mine 1 old version block, should be invalid ''' block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1) block.nVersion = 3 block.rehash() block.solve() self.last_block_time += 1 yield TestInstance([[block, False]]) if __name__ == '__main__': BIP65Test().main() <|fim▁end|>
get_tests
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == "__main__":<|fim▁hole|> execute_from_command_line(sys.argv)<|fim▁end|>
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Sharing.settings") from django.core.management import execute_from_command_line
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Sharing.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
<|file_name|>cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.<|fim▁hole|># Snippet for GetTagKey # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-resourcemanager # [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] from google.cloud import resourcemanager_v3 async def sample_get_tag_key(): # Create a client client = resourcemanager_v3.TagKeysAsyncClient() # Initialize request argument(s) request = resourcemanager_v3.GetTagKeyRequest( name="name_value", ) # Make the request response = await client.get_tag_key(request=request) # Handle the response print(response) # [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async]<|fim▁end|>
# # Generated code. DO NOT EDIT! #
<|file_name|>cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for GetTagKey # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-resourcemanager # [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] from google.cloud import resourcemanager_v3 async def sample_get_tag_key(): # Create a client <|fim_middle|> # [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] <|fim▁end|>
client = resourcemanager_v3.TagKeysAsyncClient() # Initialize request argument(s) request = resourcemanager_v3.GetTagKeyRequest( name="name_value", ) # Make the request response = await client.get_tag_key(request=request) # Handle the response print(response)
<|file_name|>cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for GetTagKey # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-resourcemanager # [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] from google.cloud import resourcemanager_v3 async def <|fim_middle|>(): # Create a client client = resourcemanager_v3.TagKeysAsyncClient() # Initialize request argument(s) request = resourcemanager_v3.GetTagKeyRequest( name="name_value", ) # Make the request response = await client.get_tag_key(request=request) # Handle the response print(response) # [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] <|fim▁end|>
sample_get_tag_key
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>from rest_framework import serializers from . import models <|fim▁hole|> 'id', 'name', 'additional_infos', 'owner', 'creation_date', 'update_date', )<|fim▁end|>
class Invoice(serializers.ModelSerializer): class Meta: model = models.Invoice fields = (
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>from rest_framework import serializers from . import models class Invoice(serializers.ModelSerializer): <|fim_middle|> <|fim▁end|>
class Meta: model = models.Invoice fields = ( 'id', 'name', 'additional_infos', 'owner', 'creation_date', 'update_date', )
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>from rest_framework import serializers from . import models class Invoice(serializers.ModelSerializer): class Meta: <|fim_middle|> <|fim▁end|>
model = models.Invoice fields = ( 'id', 'name', 'additional_infos', 'owner', 'creation_date', 'update_date', )
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew<|fim▁hole|> strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0)<|fim▁end|>
strInt = left strInt = strNew
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: <|fim_middle|> _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
"Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x)
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): <|fim_middle|> def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
self.pattern = pattern
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): <|fim_middle|> def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
return self.pattern % obj
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): <|fim_middle|> def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
return "%s('%s')" % (self.__class__.__name__, self.pattern)
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): <|fim_middle|> _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
return self.format(x)
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): <|fim_middle|> if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
"""lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) )
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): <|fim_middle|> def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): <|fim_middle|> def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
'''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V])
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers <|fim_middle|> def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): <|fim_middle|> if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) )
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): <|fim_middle|> t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD'))
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': <|fim_middle|> else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
self.calcPlaces = self._calcPlaces
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: <|fim_middle|> self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
self.places = places
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: <|fim_middle|> places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
num = -num
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: <|fim_middle|> strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
places = -places
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: <|fim_middle|> else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1]
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: <|fim_middle|> else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1]
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: <|fim_middle|> if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
strFrac = ''
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: <|fim_middle|> strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew <|fim_middle|> else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
strNew = right + strNew
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: <|fim_middle|> strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
strNew = self.comma + right + strNew
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: <|fim_middle|> if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
strBody = '-' + strBody
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: <|fim_middle|> if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
strBody = self.prefix + strBody
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: <|fim_middle|> return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
strBody = strBody + self.suffix
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': <|fim_middle|> <|fim▁end|>
def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0)
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def <|fim_middle|>(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
__init__
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def <|fim_middle|>(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
format
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def <|fim_middle|>(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
__repr__
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def <|fim_middle|>(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
__call__
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def <|fim_middle|>(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
__init__
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def <|fim_middle|>(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
_calcPlaces
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def <|fim_middle|>(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
format
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def <|fim_middle|>(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
__repr__
<|file_name|>formatters.py<|end_file_name|><|fim▁begin|>#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def <|fim_middle|>(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) <|fim▁end|>
t
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {}<|fim▁hole|> def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
@staticmethod
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): <|fim_middle|> <|fim▁end|>
""" A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): <|fim_middle|> def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
self.__doc__ = getattr(func, '__doc__') self.func = func
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): <|fim_middle|> @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname]
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): <|fim_middle|> @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
"""clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {}
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): <|fim_middle|> <|fim▁end|>
if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: <|fim_middle|> propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
return self
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): <|fim_middle|> if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
obj._cached_properties = {}
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: <|fim_middle|> return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj)
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): <|fim_middle|> @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
obj._cached_properties = {}
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: <|fim_middle|> else: return False<|fim▁end|>
return True
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: <|fim_middle|> <|fim▁end|>
return False
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def <|fim_middle|>(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
__init__
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def <|fim_middle|>(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
__get__
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def <|fim_middle|>(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def is_cached(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
clear
<|file_name|>CachedProperty.py<|end_file_name|><|fim▁begin|># NOTE: this should inherit from (object) to function correctly with python 2.7 class CachedProperty(object): """ A property that is only computed once per instance and then stores the result in _cached_properties of the object. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self propname = self.func.__name__ if not hasattr(obj, '_cached_properties'): obj._cached_properties = {} if propname not in obj._cached_properties: obj._cached_properties[propname] = self.func(obj) # value = obj.__dict__[propname] = self.func(obj) return obj._cached_properties[propname] @staticmethod def clear(obj): """clears cache of obj""" if hasattr(obj, '_cached_properties'): obj._cached_properties = {} @staticmethod def <|fim_middle|>(obj, propname): if hasattr(obj, '_cached_properties') and propname in obj._cached_properties: return True else: return False<|fim▁end|>
is_cached
<|file_name|>greedy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # 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. """ TODO... """ __all__ = ['GreedyPlayer'] import random<|fim▁hole|>class GreedyPlayer(Player): """ TODO... """ def play(self, game, state): """ TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) return choosen_action<|fim▁end|>
from jdhp.tictactoe.player.abstract import Player
<|file_name|>greedy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # 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. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): ""<|fim_middle|> <|fim▁end|>
" TODO... """ def play(self, game, state): """ TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) return choosen_action
<|file_name|>greedy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # 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. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """ TODO... """ def play(self, game, state): ""<|fim_middle|> <|fim▁end|>
" TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) return choosen_action
<|file_name|>greedy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # 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. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """ TODO... """ def play(self, game, state): """ TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): ch <|fim_middle|> # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) return choosen_action <|fim▁end|>
oosen_action = action break
<|file_name|>greedy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # 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. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """ TODO... """ def play(self, game, state): """ TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug ch <|fim_middle|> return choosen_action <|fim▁end|>
oosen_action = random.choice(action_list)
<|file_name|>greedy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org) # 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. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """ TODO... """ def pl<|fim_middle|>elf, game, state): """ TODO... """ action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) return choosen_action <|fim▁end|>
ay(s
<|file_name|>test_codec.py<|end_file_name|><|fim▁begin|>import unittest from elasticmagic.types import Integer, Float, Boolean from elasticmagic.ext.queryfilter.codec import SimpleCodec class SimpleCodecTest(unittest.TestCase): def test_decode(self): codec = SimpleCodec() self.assertEqual( codec.decode({'country': ['ru', 'ua', 'null']}), { 'country': { 'exact': [['ru'], ['ua'], [None]], } } ) self.assertEqual( codec.decode({'category': ['5', '6:a', 'b:c', 'null']}, {'category': [Integer]}), { 'category': { 'exact': [[5], [6, 'a'], [None]] } } ) self.assertEqual( codec.decode({'manu': ['1:nokia:true', '2:samsung:false']}, {'manu': [Integer, None, Boolean]}), { 'manu': { 'exact': [[1, 'nokia', True], [2, 'samsung', False]],<|fim▁hole|> self.assertEqual( codec.decode({'is_active': ['true']}, {'is_active': Boolean}), { 'is_active': { 'exact': [[True]], } } ) self.assertEqual( codec.decode([('price__gte', ['100.1', '101.0']), ('price__lte', ['200'])], {'price': Float}), { 'price': { 'gte': [[100.1], [101.0]], 'lte': [[200.0]], } } ) self.assertEqual( codec.decode({'price__lte': '123a:bc'}, {'price': [Float]}), {} ) self.assertRaises(TypeError, lambda: codec.decode(''))<|fim▁end|>
} } )
<|file_name|>test_codec.py<|end_file_name|><|fim▁begin|>import unittest from elasticmagic.types import Integer, Float, Boolean from elasticmagic.ext.queryfilter.codec import SimpleCodec class SimpleCodecTest(unittest.TestCase): <|fim_middle|> <|fim▁end|>
def test_decode(self): codec = SimpleCodec() self.assertEqual( codec.decode({'country': ['ru', 'ua', 'null']}), { 'country': { 'exact': [['ru'], ['ua'], [None]], } } ) self.assertEqual( codec.decode({'category': ['5', '6:a', 'b:c', 'null']}, {'category': [Integer]}), { 'category': { 'exact': [[5], [6, 'a'], [None]] } } ) self.assertEqual( codec.decode({'manu': ['1:nokia:true', '2:samsung:false']}, {'manu': [Integer, None, Boolean]}), { 'manu': { 'exact': [[1, 'nokia', True], [2, 'samsung', False]], } } ) self.assertEqual( codec.decode({'is_active': ['true']}, {'is_active': Boolean}), { 'is_active': { 'exact': [[True]], } } ) self.assertEqual( codec.decode([('price__gte', ['100.1', '101.0']), ('price__lte', ['200'])], {'price': Float}), { 'price': { 'gte': [[100.1], [101.0]], 'lte': [[200.0]], } } ) self.assertEqual( codec.decode({'price__lte': '123a:bc'}, {'price': [Float]}), {} ) self.assertRaises(TypeError, lambda: codec.decode(''))
<|file_name|>test_codec.py<|end_file_name|><|fim▁begin|>import unittest from elasticmagic.types import Integer, Float, Boolean from elasticmagic.ext.queryfilter.codec import SimpleCodec class SimpleCodecTest(unittest.TestCase): def test_decode(self): <|fim_middle|> <|fim▁end|>
codec = SimpleCodec() self.assertEqual( codec.decode({'country': ['ru', 'ua', 'null']}), { 'country': { 'exact': [['ru'], ['ua'], [None]], } } ) self.assertEqual( codec.decode({'category': ['5', '6:a', 'b:c', 'null']}, {'category': [Integer]}), { 'category': { 'exact': [[5], [6, 'a'], [None]] } } ) self.assertEqual( codec.decode({'manu': ['1:nokia:true', '2:samsung:false']}, {'manu': [Integer, None, Boolean]}), { 'manu': { 'exact': [[1, 'nokia', True], [2, 'samsung', False]], } } ) self.assertEqual( codec.decode({'is_active': ['true']}, {'is_active': Boolean}), { 'is_active': { 'exact': [[True]], } } ) self.assertEqual( codec.decode([('price__gte', ['100.1', '101.0']), ('price__lte', ['200'])], {'price': Float}), { 'price': { 'gte': [[100.1], [101.0]], 'lte': [[200.0]], } } ) self.assertEqual( codec.decode({'price__lte': '123a:bc'}, {'price': [Float]}), {} ) self.assertRaises(TypeError, lambda: codec.decode(''))
<|file_name|>test_codec.py<|end_file_name|><|fim▁begin|>import unittest from elasticmagic.types import Integer, Float, Boolean from elasticmagic.ext.queryfilter.codec import SimpleCodec class SimpleCodecTest(unittest.TestCase): def <|fim_middle|>(self): codec = SimpleCodec() self.assertEqual( codec.decode({'country': ['ru', 'ua', 'null']}), { 'country': { 'exact': [['ru'], ['ua'], [None]], } } ) self.assertEqual( codec.decode({'category': ['5', '6:a', 'b:c', 'null']}, {'category': [Integer]}), { 'category': { 'exact': [[5], [6, 'a'], [None]] } } ) self.assertEqual( codec.decode({'manu': ['1:nokia:true', '2:samsung:false']}, {'manu': [Integer, None, Boolean]}), { 'manu': { 'exact': [[1, 'nokia', True], [2, 'samsung', False]], } } ) self.assertEqual( codec.decode({'is_active': ['true']}, {'is_active': Boolean}), { 'is_active': { 'exact': [[True]], } } ) self.assertEqual( codec.decode([('price__gte', ['100.1', '101.0']), ('price__lte', ['200'])], {'price': Float}), { 'price': { 'gte': [[100.1], [101.0]], 'lte': [[200.0]], } } ) self.assertEqual( codec.decode({'price__lte': '123a:bc'}, {'price': [Float]}), {} ) self.assertRaises(TypeError, lambda: codec.decode('')) <|fim▁end|>
test_decode
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False<|fim▁hole|> response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response<|fim▁end|>
frames[3].showBoundary=False return frames def member_list_pdf(request):
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): <|fim_middle|> class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, })
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): <|fim_middle|> def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', }))
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): <|fim_middle|> def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): <|fim_middle|> <|fim▁end|>
response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: <|fim_middle|> # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.")
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: <|fim_middle|> messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list')
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): <|fim_middle|> # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, })
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def <|fim_middle|>(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
member_list
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def <|fim_middle|>(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
build_frames
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def <|fim_middle|>(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response <|fim▁end|>
member_list_pdf
<|file_name|>test_successor.py<|end_file_name|><|fim▁begin|>from must import MustHavePatterns from successor import Successor <|fim▁hole|>class TestSuccessor(object): @classmethod def setup_class(cls): cls.test_patterns = MustHavePatterns(Successor) def test_successor(self): try: self.test_patterns.create(Successor) raise Exception("Recursive structure did not explode.") except RuntimeError as re: assert str(re).startswith("maximum recursion depth")<|fim▁end|>
<|file_name|>test_successor.py<|end_file_name|><|fim▁begin|>from must import MustHavePatterns from successor import Successor class TestSuccessor(object): <|fim_middle|> <|fim▁end|>
@classmethod def setup_class(cls): cls.test_patterns = MustHavePatterns(Successor) def test_successor(self): try: self.test_patterns.create(Successor) raise Exception("Recursive structure did not explode.") except RuntimeError as re: assert str(re).startswith("maximum recursion depth")
<|file_name|>test_successor.py<|end_file_name|><|fim▁begin|>from must import MustHavePatterns from successor import Successor class TestSuccessor(object): @classmethod def setup_class(cls): <|fim_middle|> def test_successor(self): try: self.test_patterns.create(Successor) raise Exception("Recursive structure did not explode.") except RuntimeError as re: assert str(re).startswith("maximum recursion depth") <|fim▁end|>
cls.test_patterns = MustHavePatterns(Successor)
<|file_name|>test_successor.py<|end_file_name|><|fim▁begin|>from must import MustHavePatterns from successor import Successor class TestSuccessor(object): @classmethod def setup_class(cls): cls.test_patterns = MustHavePatterns(Successor) def test_successor(self): <|fim_middle|> <|fim▁end|>
try: self.test_patterns.create(Successor) raise Exception("Recursive structure did not explode.") except RuntimeError as re: assert str(re).startswith("maximum recursion depth")
<|file_name|>test_successor.py<|end_file_name|><|fim▁begin|>from must import MustHavePatterns from successor import Successor class TestSuccessor(object): @classmethod def <|fim_middle|>(cls): cls.test_patterns = MustHavePatterns(Successor) def test_successor(self): try: self.test_patterns.create(Successor) raise Exception("Recursive structure did not explode.") except RuntimeError as re: assert str(re).startswith("maximum recursion depth") <|fim▁end|>
setup_class
<|file_name|>test_successor.py<|end_file_name|><|fim▁begin|>from must import MustHavePatterns from successor import Successor class TestSuccessor(object): @classmethod def setup_class(cls): cls.test_patterns = MustHavePatterns(Successor) def <|fim_middle|>(self): try: self.test_patterns.create(Successor) raise Exception("Recursive structure did not explode.") except RuntimeError as re: assert str(re).startswith("maximum recursion depth") <|fim▁end|>
test_successor
<|file_name|>test_bar.py<|end_file_name|><|fim▁begin|>''' This file contains tests for the bar plot. ''' import matplotlib.pyplot as plt import pytest import shap from .utils import explainer # (pytest fixture do not remove) pylint: disable=unused-import @pytest.mark.mpl_image_compare def test_simple_bar(explainer): # pylint: disable=redefined-outer-name<|fim▁hole|> """ shap_values = explainer(explainer.data) fig = plt.figure() shap.plots.bar(shap_values, show=False) plt.tight_layout() return fig<|fim▁end|>
""" Check that the bar plot is unchanged.
<|file_name|>test_bar.py<|end_file_name|><|fim▁begin|>''' This file contains tests for the bar plot. ''' import matplotlib.pyplot as plt import pytest import shap from .utils import explainer # (pytest fixture do not remove) pylint: disable=unused-import @pytest.mark.mpl_image_compare def test_simple_bar(explainer): # pylint: disable=redefined-outer-name <|fim_middle|> <|fim▁end|>
""" Check that the bar plot is unchanged. """ shap_values = explainer(explainer.data) fig = plt.figure() shap.plots.bar(shap_values, show=False) plt.tight_layout() return fig
<|file_name|>test_bar.py<|end_file_name|><|fim▁begin|>''' This file contains tests for the bar plot. ''' import matplotlib.pyplot as plt import pytest import shap from .utils import explainer # (pytest fixture do not remove) pylint: disable=unused-import @pytest.mark.mpl_image_compare def <|fim_middle|>(explainer): # pylint: disable=redefined-outer-name """ Check that the bar plot is unchanged. """ shap_values = explainer(explainer.data) fig = plt.figure() shap.plots.bar(shap_values, show=False) plt.tight_layout() return fig <|fim▁end|>
test_simple_bar
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin # Register your models here. from rcps.models import * class IngredientToRecipeInline(admin.TabularInline): model = Ingredient.recipes.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class EquipmentInline(admin.TabularInline): model = Equipment.equipment_recipes.through verbose_name = 'Инструмент' verbose_name_plural = 'Инструменты' class TagInline(admin.TabularInline):<|fim▁hole|> class RecipeAdmin(admin.ModelAdmin): model = Recipe fields = ['recipe_name', 'recipe_link'] inlines = ( IngredientToRecipeInline, EquipmentInline, TagInline, ) class IngredientComponentInAlternativeInline(admin.TabularInline): model = IngredientAlternative.ingredients.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class IngredientAlternativeAdmin(admin.ModelAdmin): model = IngredientAlternative inlines = ( IngredientComponentInAlternativeInline, ) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient) admin.site.register(IngredientAlternative, IngredientAlternativeAdmin) admin.site.register(IngredientCategory) admin.site.register(Equipment) admin.site.register(EquipmentCategory) admin.site.register(IngredientReplacement) admin.site.register(Tag)<|fim▁end|>
model = Tag.tag_recipes.through verbose_name = 'Тег' verbose_name_plural = 'Теги'
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin # Register your models here. from rcps.models import * class IngredientToRecipeInline(admin.TabularInline): <|fim_middle|> ine(admin.TabularInline): model = Equipment.equipment_recipes.through verbose_name = 'Инструмент' verbose_name_plural = 'Инструменты' class TagInline(admin.TabularInline): model = Tag.tag_recipes.through verbose_name = 'Тег' verbose_name_plural = 'Теги' class RecipeAdmin(admin.ModelAdmin): model = Recipe fields = ['recipe_name', 'recipe_link'] inlines = ( IngredientToRecipeInline, EquipmentInline, TagInline, ) class IngredientComponentInAlternativeInline(admin.TabularInline): model = IngredientAlternative.ingredients.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class IngredientAlternativeAdmin(admin.ModelAdmin): model = IngredientAlternative inlines = ( IngredientComponentInAlternativeInline, ) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient) admin.site.register(IngredientAlternative, IngredientAlternativeAdmin) admin.site.register(IngredientCategory) admin.site.register(Equipment) admin.site.register(EquipmentCategory) admin.site.register(IngredientReplacement) admin.site.register(Tag)<|fim▁end|>
model = Ingredient.recipes.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class EquipmentInl
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin # Register your models here. from rcps.models import * class IngredientToRecipeInline(admin.TabularInline): model = Ingredient.recipes.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class EquipmentInline(admin.TabularInline): model = Equipment.equ<|fim_middle|> model = Tag.tag_recipes.through verbose_name = 'Тег' verbose_name_plural = 'Теги' class RecipeAdmin(admin.ModelAdmin): model = Recipe fields = ['recipe_name', 'recipe_link'] inlines = ( IngredientToRecipeInline, EquipmentInline, TagInline, ) class IngredientComponentInAlternativeInline(admin.TabularInline): model = IngredientAlternative.ingredients.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class IngredientAlternativeAdmin(admin.ModelAdmin): model = IngredientAlternative inlines = ( IngredientComponentInAlternativeInline, ) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient) admin.site.register(IngredientAlternative, IngredientAlternativeAdmin) admin.site.register(IngredientCategory) admin.site.register(Equipment) admin.site.register(EquipmentCategory) admin.site.register(IngredientReplacement) admin.site.register(Tag)<|fim▁end|>
ipment_recipes.through verbose_name = 'Инструмент' verbose_name_plural = 'Инструменты' class TagInline(admin.TabularInline):
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin # Register your models here. from rcps.models import * class IngredientToRecipeInline(admin.TabularInline): model = Ingredient.recipes.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class EquipmentInline(admin.TabularInline): model = Equipment.equipment_recipes.through verbose_name = 'Инструмент' verbose_name_plural = 'Инструменты' class TagInline(admin.TabularInline): model = Tag.tag_recipes.through verbos<|fim_middle|> = Recipe fields = ['recipe_name', 'recipe_link'] inlines = ( IngredientToRecipeInline, EquipmentInline, TagInline, ) class IngredientComponentInAlternativeInline(admin.TabularInline): model = IngredientAlternative.ingredients.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class IngredientAlternativeAdmin(admin.ModelAdmin): model = IngredientAlternative inlines = ( IngredientComponentInAlternativeInline, ) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient) admin.site.register(IngredientAlternative, IngredientAlternativeAdmin) admin.site.register(IngredientCategory) admin.site.register(Equipment) admin.site.register(EquipmentCategory) admin.site.register(IngredientReplacement) admin.site.register(Tag)<|fim▁end|>
e_name = 'Тег' verbose_name_plural = 'Теги' class RecipeAdmin(admin.ModelAdmin): model
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin # Register your models here. from rcps.models import * class IngredientToRecipeInline(admin.TabularInline): model = Ingredient.recipes.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class EquipmentInline(admin.TabularInline): model = Equipment.equipment_recipes.through verbose_name = 'Инструмент' verbose_name_plural = 'Инструменты' class TagInline(admin.TabularInline): model = Tag.tag_recipes.through verbose_name = 'Тег' verbose_name_plural = 'Теги' class RecipeAdmin(admin.ModelAdmin): model = Recipe fields = ['recipe_name', 'reci<|fim_middle|> dmin.TabularInline): model = IngredientAlternative.ingredients.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class IngredientAlternativeAdmin(admin.ModelAdmin): model = IngredientAlternative inlines = ( IngredientComponentInAlternativeInline, ) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient) admin.site.register(IngredientAlternative, IngredientAlternativeAdmin) admin.site.register(IngredientCategory) admin.site.register(Equipment) admin.site.register(EquipmentCategory) admin.site.register(IngredientReplacement) admin.site.register(Tag)<|fim▁end|>
pe_link'] inlines = ( IngredientToRecipeInline, EquipmentInline, TagInline, ) class IngredientComponentInAlternativeInline(a
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin # Register your models here. from rcps.models import * class IngredientToRecipeInline(admin.TabularInline): model = Ingredient.recipes.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class EquipmentInline(admin.TabularInline): model = Equipment.equipment_recipes.through verbose_name = 'Инструмент' verbose_name_plural = 'Инструменты' class TagInline(admin.TabularInline): model = Tag.tag_recipes.through verbose_name = 'Тег' verbose_name_plural = 'Теги' class RecipeAdmin(admin.ModelAdmin): model = Recipe fields = ['recipe_name', 'recipe_link'] inlines = ( IngredientToRecipeInline, EquipmentInline, TagInline, ) class IngredientComponentInAlternativeInline(admin.TabularInline): model = IngredientAlternative.ingredients.through<|fim_middle|> redientAlternative inlines = ( IngredientComponentInAlternativeInline, ) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient) admin.site.register(IngredientAlternative, IngredientAlternativeAdmin) admin.site.register(IngredientCategory) admin.site.register(Equipment) admin.site.register(EquipmentCategory) admin.site.register(IngredientReplacement) admin.site.register(Tag)<|fim▁end|>
verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class IngredientAlternativeAdmin(admin.ModelAdmin): model = Ing
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin # Register your models here. from rcps.models import * class IngredientToRecipeInline(admin.TabularInline): model = Ingredient.recipes.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class EquipmentInline(admin.TabularInline): model = Equipment.equipment_recipes.through verbose_name = 'Инструмент' verbose_name_plural = 'Инструменты' class TagInline(admin.TabularInline): model = Tag.tag_recipes.through verbose_name = 'Тег' verbose_name_plural = 'Теги' class RecipeAdmin(admin.ModelAdmin): model = Recipe fields = ['recipe_name', 'recipe_link'] inlines = ( IngredientToRecipeInline, EquipmentInline, TagInline, ) class IngredientComponentInAlternativeInline(admin.TabularInline): model = IngredientAlternative.ingredients.through verbose_name = 'Ингредиент' verbose_name_plural = 'Ингредиенты' class IngredientAlternativeAdmin(admin.ModelAdmin): model = IngredientAlternative inlines = ( IngredientCompon<|fim_middle|> ient) admin.site.register(IngredientAlternative, IngredientAlternativeAdmin) admin.site.register(IngredientCategory) admin.site.register(Equipment) admin.site.register(EquipmentCategory) admin.site.register(IngredientReplacement) admin.site.register(Tag)<|fim▁end|>
entInAlternativeInline, ) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingred