prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: <|fim_middle|> if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): <|fim_middle|> def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
self._balance = 0 self.__id = generate_id()
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): <|fim_middle|> def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): <|fim_middle|> def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
self._balance += amount return self._balance
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): <|fim_middle|> if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
return AdvancedBankAccount.MAX_BALANCE
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): <|fim_middle|> print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: <|fim_middle|> class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
def area(self): raise NotImplementedError
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): <|fim_middle|> class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
raise NotImplementedError
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): <|fim_middle|> class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): <|fim_middle|> def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
self.radius = radius
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): <|fim_middle|> class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
return math.pi * self.radius ** 2
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): <|fim_middle|> if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
def __init__(self, side): self.side = side def area(self): return self.side ** 2
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): <|fim_middle|> def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
self.side = side
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): <|fim_middle|> if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
return self.side ** 2
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: <|fim_middle|> else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
print('Sorry, minimum balance must be maintained.')
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: <|fim_middle|> # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
BankAccount.withdraw(self, amount)
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): <|fim_middle|> if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
raise ValueError
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: <|fim_middle|> self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
raise WithdrawError(amount)
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': <|fim_middle|> class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: <|fim_middle|> finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
print('no exception')
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s)
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def <|fim_middle|>(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
deposit
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def <|fim_middle|>(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
withdraw
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def <|fim_middle|>(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
make_account
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def <|fim_middle|>(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
deposit
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def <|fim_middle|>(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
withdraw
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def <|fim_middle|>(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
__init__
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def <|fim_middle|>(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
withdraw
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def <|fim_middle|>(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
deposit
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def <|fim_middle|>(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
__init__
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def <|fim_middle|>(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
withdraw
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def <|fim_middle|>(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
generate_id
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def <|fim_middle|>(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
__init__
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def <|fim_middle|>(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
__init__
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def <|fim_middle|>(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
withdraw
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def <|fim_middle|>(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
deposit
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def <|fim_middle|>(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
get_max_balance
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def <|fim_middle|>(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
tricky
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def <|fim_middle|>(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
area
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def <|fim_middle|>(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
__init__
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def <|fim_middle|>(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
area
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def <|fim_middle|>(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
__init__
<|file_name|>common_objects.py<|end_file_name|><|fim▁begin|>import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def <|fim_middle|>(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) <|fim▁end|>
area
<|file_name|>0007_auto_20160710_1833.py<|end_file_name|><|fim▁begin|><|fim▁hole|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0006_auto_20160616_1640'), ] operations = [ migrations.AlterField( model_name='episode', name='edit_key', field=models.CharField(blank=True, default='41086227', help_text='key to allow unauthenticated users to edit this item.', max_length=32, null=True), ), ]<|fim▁end|>
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-10 18:33 from __future__ import unicode_literals
<|file_name|>0007_auto_20160710_1833.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-10 18:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('main', '0006_auto_20160616_1640'), ] operations = [ migrations.AlterField( model_name='episode', name='edit_key', field=models.CharField(blank=True, default='41086227', help_text='key to allow unauthenticated users to edit this item.', max_length=32, null=True), ), ]
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point):<|fim▁hole|> def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a<|fim▁end|>
return self.a * point[0] + self.b * point[1] + self.c > 0
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): <|fim_middle|> class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): <|fim_middle|> def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
""" Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector()
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): <|fim_middle|> def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return self.edge_points3d[0]
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): <|fim_middle|> def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return self.edge_points3d[1]
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): <|fim_middle|> def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return self.edge_points3d[2]
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): <|fim_middle|> def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return self.edge_points3d[3]
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): <|fim_middle|> def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): <|fim_middle|> class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
""" :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): <|fim_middle|> class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
def __init__(self, surfaces): self.surfaces = surfaces
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): <|fim_middle|> class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
self.surfaces = surfaces
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): <|fim_middle|> class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model)
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): <|fim_middle|> def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
self.models = models or []
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): <|fim_middle|> class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
assert isinstance(model, Polyhedron) self.models.append(model)
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): <|fim_middle|> <|fim▁end|>
def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): <|fim_middle|> def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
""" Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): <|fim_middle|> def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return self.a * point[0] + self.b * point[1] + self.c > 0
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): <|fim_middle|> def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return self.a * point[0] + self.b * point[1] + self.c < 0
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): <|fim_middle|> def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return self.a * point[0] + self.b * point[1] + self.c == 0
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): <|fim_middle|> def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): <|fim_middle|> <|fim▁end|>
if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: <|fim_middle|> def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
self.a = -self.a self.b = -self.b self.c = -self.c
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: <|fim_middle|> return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return 0.0
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: <|fim_middle|> return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
return 0.0
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def <|fim_middle|>(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
__init__
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def <|fim_middle|>(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
top_left_corner3d
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def <|fim_middle|>(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
top_right_corner3d
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def <|fim_middle|>(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
bottom_right_corner3d
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def <|fim_middle|>(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
bottom_left_corner3d
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def <|fim_middle|>(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
distance_to_point
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def <|fim_middle|>(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
_get_normal_vector
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def <|fim_middle|>(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
__init__
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def <|fim_middle|>(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
__init__
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def <|fim_middle|>(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
add_model
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def <|fim_middle|>(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
__init__
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def <|fim_middle|>(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
is_point_on_left
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def <|fim_middle|>(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
is_point_on_right
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def <|fim_middle|>(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
is_point_on_line
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def <|fim_middle|>(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
get_y_from_x
<|file_name|>surface.py<|end_file_name|><|fim▁begin|>import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def <|fim_middle|>(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a <|fim▁end|>
get_x_from_y
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase<|fim▁hole|> return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
description = _("Comma-separated slug field") def get_internal_type(self):
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): <|fim_middle|> class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
"""A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): <|fim_middle|> class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): <|fim_middle|> class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): <|fim_middle|> def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
self.field = field
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): <|fim_middle|> def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name]
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): <|fim_middle|> def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): <|fim_middle|> class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): <|fim_middle|> class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
"""A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): <|fim_middle|> def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
return "%s_json" % self.name
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): <|fim_middle|> def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. <|fim_middle|> def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): <|fim_middle|> class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): <|fim_middle|> try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
"""Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): <|fim_middle|> def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])<|fim▁end|>
return "TextField"