content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
fps = 60 game_duration = 120 # in sec window_width = 1550 window_height = 800
fps = 60 game_duration = 120 window_width = 1550 window_height = 800
class Solution(object): def maxLength(self, arr): """ :type arr: List[str] :rtype: int """ if not arr: return 0 if len(arr) == 1: return len(arr[0]) result = [0] self.max_unique(arr, 0, "", result) return result[0] def max_unique(self, arr, index, current, result): """Finds the max possible length of s""" if index == len(arr) and (self.unique_chars(current) > result[0]): result[0] = self.unique_chars(current) return if index == len(arr): return self.max_unique(arr, index + 1, current, result) self.max_unique(arr, index + 1, current+arr[index], result) def unique_chars(self, word): """ Returns the length of the word if all chars are unique else -1 """ count = [0] * 26 offset = ord('a') for char in word: index = ord(char) - offset count[index] += 1 if count[index] > 1: return -1 return len(word) arr = ["un", "iq", "ue"] obj = Solution() result = obj.maxLength(arr) print(result)
class Solution(object): def max_length(self, arr): """ :type arr: List[str] :rtype: int """ if not arr: return 0 if len(arr) == 1: return len(arr[0]) result = [0] self.max_unique(arr, 0, '', result) return result[0] def max_unique(self, arr, index, current, result): """Finds the max possible length of s""" if index == len(arr) and self.unique_chars(current) > result[0]: result[0] = self.unique_chars(current) return if index == len(arr): return self.max_unique(arr, index + 1, current, result) self.max_unique(arr, index + 1, current + arr[index], result) def unique_chars(self, word): """ Returns the length of the word if all chars are unique else -1 """ count = [0] * 26 offset = ord('a') for char in word: index = ord(char) - offset count[index] += 1 if count[index] > 1: return -1 return len(word) arr = ['un', 'iq', 'ue'] obj = solution() result = obj.maxLength(arr) print(result)
def main(): ans = 1 for n in range(1, 501): ans += f(n) print(ans) def f(n): return 4 * (2 * n + 1)**2 - (12 * n) if __name__ == '__main__': main()
def main(): ans = 1 for n in range(1, 501): ans += f(n) print(ans) def f(n): return 4 * (2 * n + 1) ** 2 - 12 * n if __name__ == '__main__': main()
# -*- coding: utf-8 -*- __all__ = [ "StorageBackend" ] class StorageBackend(object): """Base class for storage backends.""" async def store_stats(self, stats): raise NotImplementedError
__all__ = ['StorageBackend'] class Storagebackend(object): """Base class for storage backends.""" async def store_stats(self, stats): raise NotImplementedError
""" discpy.types ~~~~~~~~~~~~~~ Typings for the Discord API :copyright: (c) 2021 The DiscPy Developers (c) 2015-2021 Rapptz :license: MIT, see LICENSE for more details. """
""" discpy.types ~~~~~~~~~~~~~~ Typings for the Discord API :copyright: (c) 2021 The DiscPy Developers (c) 2015-2021 Rapptz :license: MIT, see LICENSE for more details. """
def get_param_dict(self): """Get the parameters dict from ELUT Parameters ---------- self : ELUT an ELUT object Returns ---------- param_dict : dict a Dict object """ param_dict = {"R1": self.R1, "L1": self.L1, "T1_ref": self.T1_ref} return param_dict
def get_param_dict(self): """Get the parameters dict from ELUT Parameters ---------- self : ELUT an ELUT object Returns ---------- param_dict : dict a Dict object """ param_dict = {'R1': self.R1, 'L1': self.L1, 'T1_ref': self.T1_ref} return param_dict
class A(object): pass print(A.__sizeof__) # <ref>
class A(object): pass print(A.__sizeof__)
#Write a Python program to print the following floating numbers upto 2 decimal places with a sign. x = 3.1415926 y = 12.9999 a = float(+x) b = float(-y) print(round(a,2)) print(round(b,2))
x = 3.1415926 y = 12.9999 a = float(+x) b = float(-y) print(round(a, 2)) print(round(b, 2))
# A place for secret local/dev environment settings UNIFIED_DB = { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'DB_NAME', 'USER': 'username', 'PASSWORD': 'password', } MONGODB_DATABASES = { 'default': { 'NAME': 'wtc-console', 'USER': 'root', 'PASSWORD': 'root', } }
unified_db = {'ENGINE': 'django.db.backends.oracle', 'NAME': 'DB_NAME', 'USER': 'username', 'PASSWORD': 'password'} mongodb_databases = {'default': {'NAME': 'wtc-console', 'USER': 'root', 'PASSWORD': 'root'}}
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def pseudoPalindromicPaths (self, root: TreeNode) -> int: s = set() def dfs(root): if not root: return 0 if root.val in s: s.discard(root.val) else: s.add(root.val) res = dfs(root.left) + dfs(root.right) if not root.left and not root.right: res += len(s)<=1 if root.val in s: s.discard(root.val) else: s.add(root.val) return res return dfs(root)
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def pseudo_palindromic_paths(self, root: TreeNode) -> int: s = set() def dfs(root): if not root: return 0 if root.val in s: s.discard(root.val) else: s.add(root.val) res = dfs(root.left) + dfs(root.right) if not root.left and (not root.right): res += len(s) <= 1 if root.val in s: s.discard(root.val) else: s.add(root.val) return res return dfs(root)
'''For 18 points, answer the following questions: "Recursion" is when a function solves a problem by calling itself. Recursive functions have at least 2 parts: 1. Base case - This is where the function is finished. 2. Recursive case (aka Induction case) - this is where the function calls itself and gets closer to the base case. ''' #The Fibonacci sequence is a classic example of a recursive function. #The sequence is: 1,1,2,3,5,8,13,21,34,55, and so on. #You calculate the sequence by starting with two numbers (such as 1,1) #then you get the next number by adding the previous two numbers. #Here it is as a recursive function. def fibonacci(a,b,n): '''a and b are the starting numbers. n is how deep into the sequence you want to calculate.''' if n==0: return a+b else: return fibonacci(b,a+b,n-1) #1. Which case (the if or the else) is the base case and which #is the recursive case? #2. Write code that uses the function to print out the first 8 numbers #in the sequence. #3. What error do you get if you pass a decimal as the third argument #to the function? #4. How can you fix that error? #5. Write this function using loops. #You can factor using recursion. Check it out. #Note that start=2 defines an argument with a default value. #For example: If I write factor(10) then start defaults at the value 2 #If I write: factor(81,3) then start takes the value 3. def factor(number, start=2): if start > number: return [] elif number % start == 0: return [start]+factor(number/start, start) else: return factor(number,start+1) #6. Find all the factors of 360 using this function. #7. There are three cases in factor. Which are the base case(s)? #Which are the recursive case(s)?
"""For 18 points, answer the following questions: "Recursion" is when a function solves a problem by calling itself. Recursive functions have at least 2 parts: 1. Base case - This is where the function is finished. 2. Recursive case (aka Induction case) - this is where the function calls itself and gets closer to the base case. """ def fibonacci(a, b, n): """a and b are the starting numbers. n is how deep into the sequence you want to calculate.""" if n == 0: return a + b else: return fibonacci(b, a + b, n - 1) def factor(number, start=2): if start > number: return [] elif number % start == 0: return [start] + factor(number / start, start) else: return factor(number, start + 1)
''' Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Solution: Copyright 2017 Dave Cuthbert License MIT ''' def find_multiples(factor, limit): list_of_factors = [] for num in range(limit): if num % factor == 0: list_of_factors.append(num) return list_of_factors def sum_of_list(list_to_sum): list_sum = 0 for i in list_to_sum: list_sum += i return list_sum def clean_up_lists(list1, list2): tmp_list = list1[:] tmp_list.extend(list2) return set(tmp_list) def solve_problem(factor1, factor2, maximum): list_factor_1 = find_multiples(factor1, maximum) list_factor_2 = find_multiples(factor2, maximum) return(sum_of_list(clean_up_lists(list_factor_1, list_factor_2))) if __name__ == "__main__": MAX_VALUE = 1000 LIST_FACTOR_1 = 3 LIST_FACTOR_2 = 5 print(solve_problem(LIST_FACTOR_1, LIST_FACTOR_2, MAX_VALUE))
""" Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Solution: Copyright 2017 Dave Cuthbert License MIT """ def find_multiples(factor, limit): list_of_factors = [] for num in range(limit): if num % factor == 0: list_of_factors.append(num) return list_of_factors def sum_of_list(list_to_sum): list_sum = 0 for i in list_to_sum: list_sum += i return list_sum def clean_up_lists(list1, list2): tmp_list = list1[:] tmp_list.extend(list2) return set(tmp_list) def solve_problem(factor1, factor2, maximum): list_factor_1 = find_multiples(factor1, maximum) list_factor_2 = find_multiples(factor2, maximum) return sum_of_list(clean_up_lists(list_factor_1, list_factor_2)) if __name__ == '__main__': max_value = 1000 list_factor_1 = 3 list_factor_2 = 5 print(solve_problem(LIST_FACTOR_1, LIST_FACTOR_2, MAX_VALUE))
# Time: O(n) # Space: O(1) class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ result = [] i = 0 while i < len(intervals) and newInterval[0] > intervals[i][1]: result += intervals[i], i += 1 while i < len(intervals) and newInterval[1] >= intervals[i][0]: newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])] i += 1 result.append(newInterval) result.extend(intervals[i:]) return result
class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ result = [] i = 0 while i < len(intervals) and newInterval[0] > intervals[i][1]: result += (intervals[i],) i += 1 while i < len(intervals) and newInterval[1] >= intervals[i][0]: new_interval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])] i += 1 result.append(newInterval) result.extend(intervals[i:]) return result
d1=['13CS10001','12CS30016','12CS30043','12CS30042','12CS30043','13CS10038','12CS30017','12CS30044','13CS10041','12CS30041','12CS30010', '13CS10020','12CS30025','12CS30027','12CS30032','13CS10035','12CS30003','12CS30044','12CS30016','13CS10038','13CS10021','12CS30028', '12CS30016','13CS10006','13CS10046','13CS10034','12CS30037','12CS30017','13CS10025','12CS30014','13CS10035','12CS30005','12CS30036'] d1s = set(d1) print(len(d1)) print(len(d1s))
d1 = ['13CS10001', '12CS30016', '12CS30043', '12CS30042', '12CS30043', '13CS10038', '12CS30017', '12CS30044', '13CS10041', '12CS30041', '12CS30010', '13CS10020', '12CS30025', '12CS30027', '12CS30032', '13CS10035', '12CS30003', '12CS30044', '12CS30016', '13CS10038', '13CS10021', '12CS30028', '12CS30016', '13CS10006', '13CS10046', '13CS10034', '12CS30037', '12CS30017', '13CS10025', '12CS30014', '13CS10035', '12CS30005', '12CS30036'] d1s = set(d1) print(len(d1)) print(len(d1s))
# -*- coding: utf-8 -*- def includeme(config): config.add_route('index', '') config.include(admin_include, '/admin') config.include(post_include, '/post') config.add_route('firework', '/firework') config.add_route('baymax', '/baymax') def admin_include(config): config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('all_posts', '/all_posts') def post_include(config): config.add_route('new_post', '/new_post') config.add_route('post_detail', '/detail/{id}') config.add_route('post_edit', '/edit/{id}') config.add_route('post_delete', '/delete/{id}')
def includeme(config): config.add_route('index', '') config.include(admin_include, '/admin') config.include(post_include, '/post') config.add_route('firework', '/firework') config.add_route('baymax', '/baymax') def admin_include(config): config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('all_posts', '/all_posts') def post_include(config): config.add_route('new_post', '/new_post') config.add_route('post_detail', '/detail/{id}') config.add_route('post_edit', '/edit/{id}') config.add_route('post_delete', '/delete/{id}')
def ada_int(f, a, b, tol=1.0e-6, n=5, N=10): area = trapezoid(f, a, b, N) check = trapezoid(f, a, b, n) if abs(area - check) > tol: # bad accuracy, add more points to interval m = (b + a) / 2.0 area = ada_int(f, a, m) + ada_int(f, m, b) return area
def ada_int(f, a, b, tol=1e-06, n=5, N=10): area = trapezoid(f, a, b, N) check = trapezoid(f, a, b, n) if abs(area - check) > tol: m = (b + a) / 2.0 area = ada_int(f, a, m) + ada_int(f, m, b) return area
# -*- coding:utf-8 -*- # @Script: array_partition_1.py # @Author: Pradip Patil # @Contact: @pradip__patil # @Created: 2019-03-20 23:06:35 # @Last Modified By: Pradip Patil # @Last Modified: 2019-03-21 21:07:13 # @Description: https://leetcode.com/problems/array-partition-i/ ''' Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in the range of [-10000, 10000]. ''' class Solution: def arrayPairSum(self, nums): return sum(sorted(nums)[::2]) if __name__ == "__main__": print(Solution().arrayPairSum([1, 4, 3, 2])) print(Solution().arrayPairSum([]))
""" Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in the range of [-10000, 10000]. """ class Solution: def array_pair_sum(self, nums): return sum(sorted(nums)[::2]) if __name__ == '__main__': print(solution().arrayPairSum([1, 4, 3, 2])) print(solution().arrayPairSum([]))
# Options class SimpleOpt(): def __init__(self): self.method = 'gvae' self.graph_type = 'ENZYMES' self.data_dir = './data/ENZYMES_20-50_res.graphs' self.emb_size = 8 self.encode_dim = 32 self.layer_num = 3 self.decode_dim = 32 self.dropout = 0.5 self.logits = 10 # self.adj_thresh = 0.6 self.max_epochs = 50 self.lr = 0.003 self.gpu = '2' self.batch_size = 56 self.epochs_log = 1 # self.DATA_DIR = './data/dblp/' # self.output_dir = './output/' class Options(): def __init__(self): self.opt_type = 'simple' # self.opt_type = 'argparser @staticmethod def initialize(epoch_num=1800): opt = SimpleOpt() opt.max_epochs = epoch_num return opt
class Simpleopt: def __init__(self): self.method = 'gvae' self.graph_type = 'ENZYMES' self.data_dir = './data/ENZYMES_20-50_res.graphs' self.emb_size = 8 self.encode_dim = 32 self.layer_num = 3 self.decode_dim = 32 self.dropout = 0.5 self.logits = 10 self.max_epochs = 50 self.lr = 0.003 self.gpu = '2' self.batch_size = 56 self.epochs_log = 1 class Options: def __init__(self): self.opt_type = 'simple' @staticmethod def initialize(epoch_num=1800): opt = simple_opt() opt.max_epochs = epoch_num return opt
set_name(0x8013570C, "PresOnlyTestRoutine__Fv", SN_NOWARN) set_name(0x80135734, "FeInitBuffer__Fv", SN_NOWARN) set_name(0x80135760, "FeAddEntry__Fii8TXT_JUSTUsP7FeTableP5CFont", SN_NOWARN) set_name(0x801357E4, "FeAddTable__FP11FeMenuTablei", SN_NOWARN) set_name(0x80135860, "FeAddNameTable__FPUci", SN_NOWARN) set_name(0x80135988, "FeDrawBuffer__Fv", SN_NOWARN) set_name(0x80135FB4, "FeNewMenu__FP7FeTable", SN_NOWARN) set_name(0x80136034, "FePrevMenu__Fv", SN_NOWARN) set_name(0x8013617C, "FeSelUp__Fi", SN_NOWARN) set_name(0x80136264, "FeSelDown__Fi", SN_NOWARN) set_name(0x8013634C, "FeGetCursor__Fv", SN_NOWARN) set_name(0x80136360, "FeSelect__Fv", SN_NOWARN) set_name(0x801363B0, "FeMainKeyCtrl__FP7CScreen", SN_NOWARN) set_name(0x80136578, "InitDummyMenu__Fv", SN_NOWARN) set_name(0x80136580, "InitFrontEnd__FP9FE_CREATE", SN_NOWARN) set_name(0x801366A0, "FeInitMainMenu__Fv", SN_NOWARN) set_name(0x8013671C, "FeInitNewGameMenu__Fv", SN_NOWARN) set_name(0x801367D0, "FeNewGameMenuCtrl__Fv", SN_NOWARN) set_name(0x80136984, "FeInitPlayer1ClassMenu__Fv", SN_NOWARN) set_name(0x80136A08, "FeInitPlayer2ClassMenu__Fv", SN_NOWARN) set_name(0x80136A8C, "FePlayerClassMenuCtrl__Fv", SN_NOWARN) set_name(0x80136AD4, "FeDrawChrClass__Fv", SN_NOWARN) set_name(0x80136F6C, "FeInitNewP1NameMenu__Fv", SN_NOWARN) set_name(0x80136FC8, "FeInitNewP2NameMenu__Fv", SN_NOWARN) set_name(0x8013701C, "FeNewNameMenuCtrl__Fv", SN_NOWARN) set_name(0x801375E4, "FeCopyPlayerInfoForReturn__Fv", SN_NOWARN) set_name(0x80137710, "FeEnterGame__Fv", SN_NOWARN) set_name(0x80137738, "FeInitLoadMemcardSelect__Fv", SN_NOWARN) set_name(0x801377B8, "FeInitLoadChar1Menu__Fv", SN_NOWARN) set_name(0x80137820, "FeInitLoadChar2Menu__Fv", SN_NOWARN) set_name(0x80137890, "FeInitDifficultyMenu__Fv", SN_NOWARN) set_name(0x80137934, "FeDifficultyMenuCtrl__Fv", SN_NOWARN) set_name(0x80137A20, "FeInitBackgroundMenu__Fv", SN_NOWARN) set_name(0x80137A6C, "FeInitBook1Menu__Fv", SN_NOWARN) set_name(0x80137ABC, "FeInitBook2Menu__Fv", SN_NOWARN) set_name(0x80137B0C, "FeBackBookMenuCtrl__Fv", SN_NOWARN) set_name(0x80137D50, "PlayDemo__Fv", SN_NOWARN) set_name(0x80137D64, "FadeFEOut__Fv", SN_NOWARN) set_name(0x80137E28, "DrawBackTSK__FP4TASK", SN_NOWARN) set_name(0x80137FB0, "FeInitMainStuff__FP4TASK", SN_NOWARN) set_name(0x8013805C, "FrontEndTask__FP4TASK", SN_NOWARN) set_name(0x80138508, "DrawFeTwinkle__Fii", SN_NOWARN) set_name(0x801385E4, "___6Dialog", SN_NOWARN) set_name(0x8013860C, "__6Dialog", SN_NOWARN) set_name(0x8013868C, "GetOverlayOtBase__7CBlocks", SN_NOWARN) set_name(0x80138694, "CheckActive__4CPad", SN_NOWARN) set_name(0x80138CB0, "InitCredits__Fv", SN_NOWARN) set_name(0x80138D44, "PrintCredits__Fiiiiii", SN_NOWARN) set_name(0x80139574, "DrawCreditsTitle__Fiiiii", SN_NOWARN) set_name(0x8013962C, "DrawCreditsSubTitle__Fiiiii", SN_NOWARN) set_name(0x801396E4, "CredCountNL__Fi", SN_NOWARN) set_name(0x80139750, "DoCredits__Fv", SN_NOWARN) set_name(0x80139B38, "PRIM_GetPrim__FPP8POLY_FT4", SN_NOWARN) set_name(0x80139BB4, "ClearFont__5CFont", SN_NOWARN) set_name(0x80139BD8, "GetCharHeight__5CFontUc", SN_NOWARN) set_name(0x80139C18, "___7CScreen", SN_NOWARN) set_name(0x80139C38, "GetFr__7TextDati", SN_NOWARN) set_name(0x8013E1F4, "endian_swap__FPUci", SN_NOWARN) set_name(0x8013E228, "sjis_endian_swap__FPUci", SN_NOWARN) set_name(0x8013E270, "to_sjis__Fc", SN_NOWARN) set_name(0x8013E2F0, "to_ascii__FUs", SN_NOWARN) set_name(0x8013E378, "ascii_to_sjis__FPcPUs", SN_NOWARN) set_name(0x8013E3FC, "is_sjis__FPUc", SN_NOWARN) set_name(0x8013E408, "sjis_to_ascii__FPUsPc", SN_NOWARN) set_name(0x8013E490, "read_card_directory__Fi", SN_NOWARN) set_name(0x8013E6F0, "test_card_format__Fi", SN_NOWARN) set_name(0x8013E7E0, "checksum_data__FPci", SN_NOWARN) set_name(0x8013E81C, "delete_card_file__Fii", SN_NOWARN) set_name(0x8013E914, "read_card_file__FiiiPc", SN_NOWARN) set_name(0x8013EAF0, "format_card__Fi", SN_NOWARN) set_name(0x8013EBB4, "write_card_file__FiiPcT2PUcPUsiT4", SN_NOWARN) set_name(0x8013EED8, "new_card__Fi", SN_NOWARN) set_name(0x8013EF6C, "service_card__Fi", SN_NOWARN) set_name(0x80155064, "GetFileNumber__FiPc", SN_NOWARN) set_name(0x80155124, "DoSaveOptions__Fv", SN_NOWARN) set_name(0x8015514C, "DoSaveGame__Fv", SN_NOWARN) set_name(0x8015529C, "DoLoadGame__Fv", SN_NOWARN) set_name(0x80155340, "DoFrontEndLoadCharacter__Fi", SN_NOWARN) set_name(0x80155398, "McInitLoadCard1Menu__Fv", SN_NOWARN) set_name(0x801553D8, "McInitLoadCard2Menu__Fv", SN_NOWARN) set_name(0x80155418, "ChooseCardLoad__Fv", SN_NOWARN) set_name(0x801554B4, "McInitLoadGameMenu__Fv", SN_NOWARN) set_name(0x80155518, "McMainKeyCtrl__Fv", SN_NOWARN) set_name(0x80155768, "McCharCardMenuCtrl__Fv", SN_NOWARN) set_name(0x801559B0, "McMainCharKeyCtrl__Fv", SN_NOWARN) set_name(0x80155E28, "ShowAlertBox__Fv", SN_NOWARN) set_name(0x80156034, "GetLoadStatusMessage__FPc", SN_NOWARN) set_name(0x801560E8, "GetSaveStatusMessage__FiPc", SN_NOWARN) set_name(0x80156208, "ShowGameFiles__FPciiG4RECTi", SN_NOWARN) set_name(0x80156368, "ShowCharacterFiles__FiiG4RECTi", SN_NOWARN) set_name(0x801564E4, "PackItem__FP12PkItemStructPC10ItemStruct", SN_NOWARN) set_name(0x80156570, "PackPlayer__FP14PkPlayerStructi", SN_NOWARN) set_name(0x8015677C, "UnPackItem__FPC12PkItemStructP10ItemStruct", SN_NOWARN) set_name(0x80156884, "VerifyGoldSeeds__FP12PlayerStruct", SN_NOWARN) set_name(0x8015695C, "UnPackPlayer__FPC14PkPlayerStructiUc", SN_NOWARN) set_name(0x80156C20, "ConstructSlotName__FPci", SN_NOWARN) set_name(0x80156D18, "GetSpinnerWidth__Fi", SN_NOWARN) set_name(0x80156DBC, "ReconstructSlotName__Fii", SN_NOWARN) set_name(0x801571B4, "GetTick__C4CPad", SN_NOWARN) set_name(0x801571DC, "GetDown__C4CPad", SN_NOWARN) set_name(0x80157204, "SetPadTickMask__4CPadUs", SN_NOWARN) set_name(0x8015720C, "SetPadTick__4CPadUs", SN_NOWARN) set_name(0x80157214, "SetRGB__6DialogUcUcUc", SN_NOWARN) set_name(0x80157234, "SetBack__6Dialogi", SN_NOWARN) set_name(0x8015723C, "SetBorder__6Dialogi", SN_NOWARN) set_name(0x80157244, "___6Dialog_addr_80157244", SN_NOWARN) set_name(0x8015726C, "__6Dialog_addr_8015726C", SN_NOWARN) set_name(0x801572EC, "GetOverlayOtBase__7CBlocks_addr_801572EC", SN_NOWARN) set_name(0x801572F4, "BLoad__Fv", SN_NOWARN) set_name(0x80157310, "ILoad__Fv", SN_NOWARN) set_name(0x80157364, "OLoad__Fv", SN_NOWARN) set_name(0x80157388, "LoadQuest__Fi", SN_NOWARN) set_name(0x80157450, "BSave__Fc", SN_NOWARN) set_name(0x80157468, "ISave__Fi", SN_NOWARN) set_name(0x801574C8, "OSave__FUc", SN_NOWARN) set_name(0x8015750C, "SaveQuest__Fi", SN_NOWARN) set_name(0x801575D8, "PSX_GM_SaveGame__FiPcT1", SN_NOWARN) set_name(0x80157B38, "PSX_GM_LoadGame__FUcii", SN_NOWARN) set_name(0x80157C5C, "PSX_CH_LoadGame__Fi", SN_NOWARN) set_name(0x80157CFC, "PSX_CH_LoadBlock__Fii", SN_NOWARN) set_name(0x80157D24, "PSX_CH_SaveGame__Fii", SN_NOWARN) set_name(0x80157EA8, "RestorePads__Fv", SN_NOWARN) set_name(0x80157F68, "StorePads__Fv", SN_NOWARN) set_name(0x80158024, "GetIcon__Fv", SN_NOWARN) set_name(0x80158060, "PSX_OPT_LoadGame__Fiib", SN_NOWARN) set_name(0x801580BC, "PSX_OPT_SaveGame__FiPc", SN_NOWARN) set_name(0x801581F4, "LoadOptions__Fv", SN_NOWARN) set_name(0x801582CC, "SaveOptions__Fv", SN_NOWARN) set_name(0x80158370, "RestoreLoadedData__Fb", SN_NOWARN) set_name(0x801386C4, "CreditsText", SN_NOWARN) set_name(0x8013891C, "CreditsTable", SN_NOWARN) set_name(0x80139CF4, "card_dir", SN_NOWARN) set_name(0x8013A1F4, "card_header", SN_NOWARN) set_name(0x80139C54, "sjis_table", SN_NOWARN) set_name(0x8013F1C0, "save_buffer", SN_NOWARN) set_name(0x801531C4, "CharDataStruct", SN_NOWARN) set_name(0x80154FA4, "TempStr", SN_NOWARN) set_name(0x80154FE4, "AlertStr", SN_NOWARN) set_name(0x8013F118, "McLoadGameMenu", SN_NOWARN) set_name(0x8013F0C4, "ClassStrTbl", SN_NOWARN) set_name(0x8013F134, "McLoadCard1Menu", SN_NOWARN) set_name(0x8013F150, "McLoadCard2Menu", SN_NOWARN)
set_name(2148751116, 'PresOnlyTestRoutine__Fv', SN_NOWARN) set_name(2148751156, 'FeInitBuffer__Fv', SN_NOWARN) set_name(2148751200, 'FeAddEntry__Fii8TXT_JUSTUsP7FeTableP5CFont', SN_NOWARN) set_name(2148751332, 'FeAddTable__FP11FeMenuTablei', SN_NOWARN) set_name(2148751456, 'FeAddNameTable__FPUci', SN_NOWARN) set_name(2148751752, 'FeDrawBuffer__Fv', SN_NOWARN) set_name(2148753332, 'FeNewMenu__FP7FeTable', SN_NOWARN) set_name(2148753460, 'FePrevMenu__Fv', SN_NOWARN) set_name(2148753788, 'FeSelUp__Fi', SN_NOWARN) set_name(2148754020, 'FeSelDown__Fi', SN_NOWARN) set_name(2148754252, 'FeGetCursor__Fv', SN_NOWARN) set_name(2148754272, 'FeSelect__Fv', SN_NOWARN) set_name(2148754352, 'FeMainKeyCtrl__FP7CScreen', SN_NOWARN) set_name(2148754808, 'InitDummyMenu__Fv', SN_NOWARN) set_name(2148754816, 'InitFrontEnd__FP9FE_CREATE', SN_NOWARN) set_name(2148755104, 'FeInitMainMenu__Fv', SN_NOWARN) set_name(2148755228, 'FeInitNewGameMenu__Fv', SN_NOWARN) set_name(2148755408, 'FeNewGameMenuCtrl__Fv', SN_NOWARN) set_name(2148755844, 'FeInitPlayer1ClassMenu__Fv', SN_NOWARN) set_name(2148755976, 'FeInitPlayer2ClassMenu__Fv', SN_NOWARN) set_name(2148756108, 'FePlayerClassMenuCtrl__Fv', SN_NOWARN) set_name(2148756180, 'FeDrawChrClass__Fv', SN_NOWARN) set_name(2148757356, 'FeInitNewP1NameMenu__Fv', SN_NOWARN) set_name(2148757448, 'FeInitNewP2NameMenu__Fv', SN_NOWARN) set_name(2148757532, 'FeNewNameMenuCtrl__Fv', SN_NOWARN) set_name(2148759012, 'FeCopyPlayerInfoForReturn__Fv', SN_NOWARN) set_name(2148759312, 'FeEnterGame__Fv', SN_NOWARN) set_name(2148759352, 'FeInitLoadMemcardSelect__Fv', SN_NOWARN) set_name(2148759480, 'FeInitLoadChar1Menu__Fv', SN_NOWARN) set_name(2148759584, 'FeInitLoadChar2Menu__Fv', SN_NOWARN) set_name(2148759696, 'FeInitDifficultyMenu__Fv', SN_NOWARN) set_name(2148759860, 'FeDifficultyMenuCtrl__Fv', SN_NOWARN) set_name(2148760096, 'FeInitBackgroundMenu__Fv', SN_NOWARN) set_name(2148760172, 'FeInitBook1Menu__Fv', SN_NOWARN) set_name(2148760252, 'FeInitBook2Menu__Fv', SN_NOWARN) set_name(2148760332, 'FeBackBookMenuCtrl__Fv', SN_NOWARN) set_name(2148760912, 'PlayDemo__Fv', SN_NOWARN) set_name(2148760932, 'FadeFEOut__Fv', SN_NOWARN) set_name(2148761128, 'DrawBackTSK__FP4TASK', SN_NOWARN) set_name(2148761520, 'FeInitMainStuff__FP4TASK', SN_NOWARN) set_name(2148761692, 'FrontEndTask__FP4TASK', SN_NOWARN) set_name(2148762888, 'DrawFeTwinkle__Fii', SN_NOWARN) set_name(2148763108, '___6Dialog', SN_NOWARN) set_name(2148763148, '__6Dialog', SN_NOWARN) set_name(2148763276, 'GetOverlayOtBase__7CBlocks', SN_NOWARN) set_name(2148763284, 'CheckActive__4CPad', SN_NOWARN) set_name(2148764848, 'InitCredits__Fv', SN_NOWARN) set_name(2148764996, 'PrintCredits__Fiiiiii', SN_NOWARN) set_name(2148767092, 'DrawCreditsTitle__Fiiiii', SN_NOWARN) set_name(2148767276, 'DrawCreditsSubTitle__Fiiiii', SN_NOWARN) set_name(2148767460, 'CredCountNL__Fi', SN_NOWARN) set_name(2148767568, 'DoCredits__Fv', SN_NOWARN) set_name(2148768568, 'PRIM_GetPrim__FPP8POLY_FT4', SN_NOWARN) set_name(2148768692, 'ClearFont__5CFont', SN_NOWARN) set_name(2148768728, 'GetCharHeight__5CFontUc', SN_NOWARN) set_name(2148768792, '___7CScreen', SN_NOWARN) set_name(2148768824, 'GetFr__7TextDati', SN_NOWARN) set_name(2148786676, 'endian_swap__FPUci', SN_NOWARN) set_name(2148786728, 'sjis_endian_swap__FPUci', SN_NOWARN) set_name(2148786800, 'to_sjis__Fc', SN_NOWARN) set_name(2148786928, 'to_ascii__FUs', SN_NOWARN) set_name(2148787064, 'ascii_to_sjis__FPcPUs', SN_NOWARN) set_name(2148787196, 'is_sjis__FPUc', SN_NOWARN) set_name(2148787208, 'sjis_to_ascii__FPUsPc', SN_NOWARN) set_name(2148787344, 'read_card_directory__Fi', SN_NOWARN) set_name(2148787952, 'test_card_format__Fi', SN_NOWARN) set_name(2148788192, 'checksum_data__FPci', SN_NOWARN) set_name(2148788252, 'delete_card_file__Fii', SN_NOWARN) set_name(2148788500, 'read_card_file__FiiiPc', SN_NOWARN) set_name(2148788976, 'format_card__Fi', SN_NOWARN) set_name(2148789172, 'write_card_file__FiiPcT2PUcPUsiT4', SN_NOWARN) set_name(2148789976, 'new_card__Fi', SN_NOWARN) set_name(2148790124, 'service_card__Fi', SN_NOWARN) set_name(2148880484, 'GetFileNumber__FiPc', SN_NOWARN) set_name(2148880676, 'DoSaveOptions__Fv', SN_NOWARN) set_name(2148880716, 'DoSaveGame__Fv', SN_NOWARN) set_name(2148881052, 'DoLoadGame__Fv', SN_NOWARN) set_name(2148881216, 'DoFrontEndLoadCharacter__Fi', SN_NOWARN) set_name(2148881304, 'McInitLoadCard1Menu__Fv', SN_NOWARN) set_name(2148881368, 'McInitLoadCard2Menu__Fv', SN_NOWARN) set_name(2148881432, 'ChooseCardLoad__Fv', SN_NOWARN) set_name(2148881588, 'McInitLoadGameMenu__Fv', SN_NOWARN) set_name(2148881688, 'McMainKeyCtrl__Fv', SN_NOWARN) set_name(2148882280, 'McCharCardMenuCtrl__Fv', SN_NOWARN) set_name(2148882864, 'McMainCharKeyCtrl__Fv', SN_NOWARN) set_name(2148884008, 'ShowAlertBox__Fv', SN_NOWARN) set_name(2148884532, 'GetLoadStatusMessage__FPc', SN_NOWARN) set_name(2148884712, 'GetSaveStatusMessage__FiPc', SN_NOWARN) set_name(2148885000, 'ShowGameFiles__FPciiG4RECTi', SN_NOWARN) set_name(2148885352, 'ShowCharacterFiles__FiiG4RECTi', SN_NOWARN) set_name(2148885732, 'PackItem__FP12PkItemStructPC10ItemStruct', SN_NOWARN) set_name(2148885872, 'PackPlayer__FP14PkPlayerStructi', SN_NOWARN) set_name(2148886396, 'UnPackItem__FPC12PkItemStructP10ItemStruct', SN_NOWARN) set_name(2148886660, 'VerifyGoldSeeds__FP12PlayerStruct', SN_NOWARN) set_name(2148886876, 'UnPackPlayer__FPC14PkPlayerStructiUc', SN_NOWARN) set_name(2148887584, 'ConstructSlotName__FPci', SN_NOWARN) set_name(2148887832, 'GetSpinnerWidth__Fi', SN_NOWARN) set_name(2148887996, 'ReconstructSlotName__Fii', SN_NOWARN) set_name(2148889012, 'GetTick__C4CPad', SN_NOWARN) set_name(2148889052, 'GetDown__C4CPad', SN_NOWARN) set_name(2148889092, 'SetPadTickMask__4CPadUs', SN_NOWARN) set_name(2148889100, 'SetPadTick__4CPadUs', SN_NOWARN) set_name(2148889108, 'SetRGB__6DialogUcUcUc', SN_NOWARN) set_name(2148889140, 'SetBack__6Dialogi', SN_NOWARN) set_name(2148889148, 'SetBorder__6Dialogi', SN_NOWARN) set_name(2148889156, '___6Dialog_addr_80157244', SN_NOWARN) set_name(2148889196, '__6Dialog_addr_8015726C', SN_NOWARN) set_name(2148889324, 'GetOverlayOtBase__7CBlocks_addr_801572EC', SN_NOWARN) set_name(2148889332, 'BLoad__Fv', SN_NOWARN) set_name(2148889360, 'ILoad__Fv', SN_NOWARN) set_name(2148889444, 'OLoad__Fv', SN_NOWARN) set_name(2148889480, 'LoadQuest__Fi', SN_NOWARN) set_name(2148889680, 'BSave__Fc', SN_NOWARN) set_name(2148889704, 'ISave__Fi', SN_NOWARN) set_name(2148889800, 'OSave__FUc', SN_NOWARN) set_name(2148889868, 'SaveQuest__Fi', SN_NOWARN) set_name(2148890072, 'PSX_GM_SaveGame__FiPcT1', SN_NOWARN) set_name(2148891448, 'PSX_GM_LoadGame__FUcii', SN_NOWARN) set_name(2148891740, 'PSX_CH_LoadGame__Fi', SN_NOWARN) set_name(2148891900, 'PSX_CH_LoadBlock__Fii', SN_NOWARN) set_name(2148891940, 'PSX_CH_SaveGame__Fii', SN_NOWARN) set_name(2148892328, 'RestorePads__Fv', SN_NOWARN) set_name(2148892520, 'StorePads__Fv', SN_NOWARN) set_name(2148892708, 'GetIcon__Fv', SN_NOWARN) set_name(2148892768, 'PSX_OPT_LoadGame__Fiib', SN_NOWARN) set_name(2148892860, 'PSX_OPT_SaveGame__FiPc', SN_NOWARN) set_name(2148893172, 'LoadOptions__Fv', SN_NOWARN) set_name(2148893388, 'SaveOptions__Fv', SN_NOWARN) set_name(2148893552, 'RestoreLoadedData__Fb', SN_NOWARN) set_name(2148763332, 'CreditsText', SN_NOWARN) set_name(2148763932, 'CreditsTable', SN_NOWARN) set_name(2148769012, 'card_dir', SN_NOWARN) set_name(2148770292, 'card_header', SN_NOWARN) set_name(2148768852, 'sjis_table', SN_NOWARN) set_name(2148790720, 'save_buffer', SN_NOWARN) set_name(2148872644, 'CharDataStruct', SN_NOWARN) set_name(2148880292, 'TempStr', SN_NOWARN) set_name(2148880356, 'AlertStr', SN_NOWARN) set_name(2148790552, 'McLoadGameMenu', SN_NOWARN) set_name(2148790468, 'ClassStrTbl', SN_NOWARN) set_name(2148790580, 'McLoadCard1Menu', SN_NOWARN) set_name(2148790608, 'McLoadCard2Menu', SN_NOWARN)
APKG_COL = r''' INSERT INTO col VALUES( null, :creation_time, :modification_time, :modification_time, 11, 0, 0, 0, '{ "activeDecks": [ 1 ], "addToCur": true, "collapseTime": 1200, "curDeck": 1, "curModel": "' || :modification_time || '", "dueCounts": true, "estTimes": true, "newBury": true, "newSpread": 0, "nextPos": 1, "sortBackwards": false, "sortType": "noteFld", "timeLim": 0 }', :models, '{ "1": { "collapsed": false, "conf": 1, "desc": "", "dyn": 0, "extendNew": 10, "extendRev": 50, "id": 1, "lrnToday": [ 0, 0 ], "mod": 1425279151, "name": "Default", "newToday": [ 0, 0 ], "revToday": [ 0, 0 ], "timeToday": [ 0, 0 ], "usn": 0 }, "' || :deck_id || '": { "collapsed": false, "conf": ' || :options_id || ', "desc": "' || :description || '", "dyn": 0, "extendNew": 10, "extendRev": 50, "id": ' || :deck_id || ', "lrnToday": [ 5, 0 ], "mod": 1425278051, "name": "' || :name || '", "newToday": [ 5, 0 ], "revToday": [ 5, 0 ], "timeToday": [ 5, 0 ], "usn": -1 } }', '{ "' || :options_id || '": { "id": ' || :options_id || ', "autoplay": ' || :autoplay_audio || ', "lapse": { "delays": ' || :lapse_steps || ', "leechAction": ' || :leech_action || ', "leechFails": ' || :leech_threshold || ', "minInt": ' || :lapse_min_interval || ', "mult": ' || :leech_interval_multiplier || ' }, "maxTaken": ' || :max_time_per_answer || ', "mod": 0, "name": "' || :options_group_name || '", "new": { "bury": ' || :bury_related_new_cards || ', "delays": ' || :new_steps || ', "initialFactor": ' || :starting_ease || ', "ints": [ ' || :graduating_interval || ', ' || :easy_interval || ', 7 ], "order": ' || :order || ', "perDay": ' || :new_cards_per_day || ', "separate": true }, "replayq": ' || :replay_audio_for_answer || ', "rev": { "bury": ' || :bury_related_review_cards || ', "ease4": ' || :easy_bonus || ', "fuzz": 0.05, "ivlFct": ' || :interval_modifier || ', "maxIvl": ' || :max_interval || ', "minSpace": 1, "perDay": ' || :max_reviews_per_day || ' }, "timer": ' || :show_timer || ', "usn": 0 } }', '{}' ); '''
apkg_col = '\nINSERT INTO col VALUES(\n null,\n :creation_time,\n :modification_time,\n :modification_time,\n 11,\n 0,\n 0,\n 0,\n \'{\n "activeDecks": [\n 1\n ],\n "addToCur": true,\n "collapseTime": 1200,\n "curDeck": 1,\n "curModel": "\' || :modification_time || \'",\n "dueCounts": true,\n "estTimes": true,\n "newBury": true,\n "newSpread": 0,\n "nextPos": 1,\n "sortBackwards": false,\n "sortType": "noteFld",\n "timeLim": 0\n }\',\n :models,\n \'{\n "1": {\n "collapsed": false,\n "conf": 1,\n "desc": "",\n "dyn": 0,\n "extendNew": 10,\n "extendRev": 50,\n "id": 1,\n "lrnToday": [\n 0,\n 0\n ],\n "mod": 1425279151,\n "name": "Default",\n "newToday": [\n 0,\n 0\n ],\n "revToday": [\n 0,\n 0\n ],\n "timeToday": [\n 0,\n 0\n ],\n "usn": 0\n },\n "\' || :deck_id || \'": {\n "collapsed": false,\n "conf": \' || :options_id || \',\n "desc": "\' || :description || \'",\n "dyn": 0,\n "extendNew": 10,\n "extendRev": 50,\n "id": \' || :deck_id || \',\n "lrnToday": [\n 5,\n 0\n ],\n "mod": 1425278051,\n "name": "\' || :name || \'",\n "newToday": [\n 5,\n 0\n ],\n "revToday": [\n 5,\n 0\n ],\n "timeToday": [\n 5,\n 0\n ],\n "usn": -1\n }\n }\',\n \'{\n "\' || :options_id || \'": {\n "id": \' || :options_id || \',\n "autoplay": \' || :autoplay_audio || \',\n "lapse": {\n "delays": \' || :lapse_steps || \',\n "leechAction": \' || :leech_action || \',\n "leechFails": \' || :leech_threshold || \',\n "minInt": \' || :lapse_min_interval || \',\n "mult": \' || :leech_interval_multiplier || \'\n },\n "maxTaken": \' || :max_time_per_answer || \',\n "mod": 0,\n "name": "\' || :options_group_name || \'",\n "new": {\n "bury": \' || :bury_related_new_cards || \',\n "delays": \' || :new_steps || \',\n "initialFactor": \' || :starting_ease || \',\n "ints": [\n \' || :graduating_interval || \',\n \' || :easy_interval || \',\n 7\n ],\n "order": \' || :order || \',\n "perDay": \' || :new_cards_per_day || \',\n "separate": true\n },\n "replayq": \' || :replay_audio_for_answer || \',\n "rev": {\n "bury": \' || :bury_related_review_cards || \',\n "ease4": \' || :easy_bonus || \',\n "fuzz": 0.05,\n "ivlFct": \' || :interval_modifier || \',\n "maxIvl": \' || :max_interval || \',\n "minSpace": 1,\n "perDay": \' || :max_reviews_per_day || \'\n },\n "timer": \' || :show_timer || \',\n "usn": 0\n }\n }\',\n \'{}\'\n);\n'
def sum_numbers(text: str) -> int: return sum([int(x) for x in text.split() if x.isnumeric()]) if __name__ == '__main__': print("Example:") print(sum_numbers('hi')) # These "asserts" are used for self-checking and not for an auto-testing assert sum_numbers('hi') == 0 assert sum_numbers('who is 1st here') == 0 assert sum_numbers('my numbers is 2') == 2 assert sum_numbers( 'This picture is an oil on canvas painting by Danish artist Anna Petersen between 1845 and 1910 year' ) == 3755 assert sum_numbers('5 plus 6 is') == 11 assert sum_numbers('') == 0 print("Coding complete? Click 'Check' to earn cool rewards!")
def sum_numbers(text: str) -> int: return sum([int(x) for x in text.split() if x.isnumeric()]) if __name__ == '__main__': print('Example:') print(sum_numbers('hi')) assert sum_numbers('hi') == 0 assert sum_numbers('who is 1st here') == 0 assert sum_numbers('my numbers is 2') == 2 assert sum_numbers('This picture is an oil on canvas painting by Danish artist Anna Petersen between 1845 and 1910 year') == 3755 assert sum_numbers('5 plus 6 is') == 11 assert sum_numbers('') == 0 print("Coding complete? Click 'Check' to earn cool rewards!")
class snake: poison='venom' # shared by all instances def __init__(self, name): self.name=name # instance variable unique to each instance def change_name(self, new_name): self.name=new_name cobra= snake('cobra') print(cobra.name)
class Snake: poison = 'venom' def __init__(self, name): self.name = name def change_name(self, new_name): self.name = new_name cobra = snake('cobra') print(cobra.name)
name = input("Enter Your Username: ") age = int(input("Enter Your Age: ")) print(type(age)) if type(age) == int: print("Name :" ,name) print("Age :", age) else: print("Enter a valid Username or Age")
name = input('Enter Your Username: ') age = int(input('Enter Your Age: ')) print(type(age)) if type(age) == int: print('Name :', name) print('Age :', age) else: print('Enter a valid Username or Age')
# glob.py viewPortX = None viewPortY = None
view_port_x = None view_port_y = None
''' Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more. ''' def first_last6(nums): return nums[0] == 6 or nums[-1] == 6
""" Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more. """ def first_last6(nums): return nums[0] == 6 or nums[-1] == 6
def insertion_sort(lst): for i in range(len(lst)): j = (i - 1) temp = lst[i] while j >= 0 and temp < lst[j]: lst[j+1] = lst[j] j = j-1 lst[j + 1] = temp return lst
def insertion_sort(lst): for i in range(len(lst)): j = i - 1 temp = lst[i] while j >= 0 and temp < lst[j]: lst[j + 1] = lst[j] j = j - 1 lst[j + 1] = temp return lst
# the public parameters are passed as they are known globally def attacker(prime, root, alicepublic, bobpublic): attacksecret1=int(input("Enter a secret number1 for attacker: ")) attacksecret2=int(input("Enter a secret number2 for attacker: ")) print('\n') print ("Attacker's public key -> C=root^attacksecret(mod(prime))") attackpublic1=(root**attacksecret1)%prime attackpublic2=(root**attacksecret2)%prime print ("Attacker public key1 which is shared with Party1: ", attackpublic1) print ("Attacker public key2 which is shared with Party2: ", attackpublic2) print('\n') key1=(alicepublic**attacksecret1)%prime key2=(bobpublic**attacksecret2)%prime print("The key used to decrypt message from A and modify: ",key1) print("The key used to encrypt message to be sent to B is: ",key2) return(attackpublic1,attackpublic2) # Prime to be used print ("Both parties agree to a single prime") prime=int(input("Enter the prime number to be considered: ")) # Primitive root to be used print ("Both must agree with single primitive root to use") root=int(input("Enter the primitive root: ")) # Party1 chooses a secret number alicesecret=int(input("Enter a secret number for Party1: ")) # Party2 chooses a secret number bobsecret=int(input("Enter a secret number for Party2: ")) print('\n') # Party1 public key A=(root^alicesecret)*mod(prime) print ("Party1's public key -> A=root^alicesecret(mod(prime))") alicepublic=(root**alicesecret)%prime print ("Party1 public key is: ",alicepublic, "\n") # Party2 public key B=(root^bobsecret)*mod(prime) print ("Party2's public key -> B=root^bobsecret(mod(prime))") bobpublic=(root**bobsecret)%prime print ("Party2 public key is", bobpublic, "\n") # Party1 now calculates the shared key K1: # K1 = B^(alicesecret)*mod(prime) print ("Party1 calculates the shared key as K=B^alicesecret*(mod(prime))") alicekey=(bobpublic**alicesecret)%prime print ("Party1 calculates the shared key and results: ",alicekey, "\n") # Party2 calculates the shared key K2: # K2 = A^(bobsecret)*mod(prime) print ("Party2 calculates the shared key as K=A^bobsecret(mod(prime))") bobkey =(alicepublic**bobsecret)%prime print ("Party2 calculates the shared key and results: ", bobkey, "\n") #Both Alice and Bob now share a key which Eve cannot calculate print ("Attacker does not know the shared private key that Party1 & Party2 can now use") print("Now Eve implements Man In the Middle Attack !!") # Party1 and Party2 exchange their public keys # Eve(attacker) nows both parties public keys keys=attacker(prime, root, alicepublic, bobpublic) alicekey=(keys[0]**alicesecret)%prime print("Party1 calculates the shared key with attacker's public key1: ") print ("Shared final key: ",alicekey) bobkey =(keys[1]**bobsecret)%prime print("Party2 calculates the shared key with attacker's public key2: ") print ("Shared final key: ", bobkey, "\n") print("The final keys are different. ") ''' ----------OUTPUT---------- Both parties agree to a single prime Enter the prime number to be considered: 61 Both must agree with single primitive root to use Enter the primitive root: 43 Enter a secret number for Party1: 6756 Enter a secret number for Party2: 8356 Party1's public key -> A=root^alicesecret(mod(prime)) Party1 public key is: 34 Party2's public key -> B=root^bobsecret(mod(prime)) Party2 public key is 15 Party1 calculates the shared key as K=B^alicesecret*(mod(prime)) Party1 calculates the shared key and results: 34 Party2 calculates the shared key as K=A^bobsecret(mod(prime)) Party2 calculates the shared key and results: 34 Attacker does not know the shared private key that Party1 & Party2 can now use Now Eve implements Man In the Middle Attack !! Enter a secret number1 for attacker: 7349 Enter a secret number2 for attacker: 3560 Attacker's public key -> C=root^attacksecret(mod(prime)) Attacker public key1 which is shared with Party1: 17 Attacker public key2 which is shared with Party2: 47 The key used to decrypt message from A and modify: 9 The key used to encrypt message to be sent to B is: 47 Party1 calculates the shared key with attacker's public key1: Shared final key: 9 Party2 calculates the shared key with attacker's public key2: Shared final key: 47 The final keys are different. >>> ''' ''' Took help from: 1. https://sublimerobots.com/2015/01/simple-diffie-hellman-example-python/ 2. https://trinket.io/python/d574095364 3. https://www.wolframalpha.com/widgets/view.jsp?id=ef51422db7db201ebc03c8800f41ba99 Thanks for the help ! '''
def attacker(prime, root, alicepublic, bobpublic): attacksecret1 = int(input('Enter a secret number1 for attacker: ')) attacksecret2 = int(input('Enter a secret number2 for attacker: ')) print('\n') print("Attacker's public key -> C=root^attacksecret(mod(prime))") attackpublic1 = root ** attacksecret1 % prime attackpublic2 = root ** attacksecret2 % prime print('Attacker public key1 which is shared with Party1: ', attackpublic1) print('Attacker public key2 which is shared with Party2: ', attackpublic2) print('\n') key1 = alicepublic ** attacksecret1 % prime key2 = bobpublic ** attacksecret2 % prime print('The key used to decrypt message from A and modify: ', key1) print('The key used to encrypt message to be sent to B is: ', key2) return (attackpublic1, attackpublic2) print('Both parties agree to a single prime') prime = int(input('Enter the prime number to be considered: ')) print('Both must agree with single primitive root to use') root = int(input('Enter the primitive root: ')) alicesecret = int(input('Enter a secret number for Party1: ')) bobsecret = int(input('Enter a secret number for Party2: ')) print('\n') print("Party1's public key -> A=root^alicesecret(mod(prime))") alicepublic = root ** alicesecret % prime print('Party1 public key is: ', alicepublic, '\n') print("Party2's public key -> B=root^bobsecret(mod(prime))") bobpublic = root ** bobsecret % prime print('Party2 public key is', bobpublic, '\n') print('Party1 calculates the shared key as K=B^alicesecret*(mod(prime))') alicekey = bobpublic ** alicesecret % prime print('Party1 calculates the shared key and results: ', alicekey, '\n') print('Party2 calculates the shared key as K=A^bobsecret(mod(prime))') bobkey = alicepublic ** bobsecret % prime print('Party2 calculates the shared key and results: ', bobkey, '\n') print('Attacker does not know the shared private key that Party1 & Party2 can now use') print('Now Eve implements Man In the Middle Attack !!') keys = attacker(prime, root, alicepublic, bobpublic) alicekey = keys[0] ** alicesecret % prime print("Party1 calculates the shared key with attacker's public key1: ") print('Shared final key: ', alicekey) bobkey = keys[1] ** bobsecret % prime print("Party2 calculates the shared key with attacker's public key2: ") print('Shared final key: ', bobkey, '\n') print('The final keys are different. ') "\n----------OUTPUT----------\nBoth parties agree to a single prime\nEnter the prime number to be considered: 61\nBoth must agree with single primitive root to use\nEnter the primitive root: 43\nEnter a secret number for Party1: 6756\nEnter a secret number for Party2: 8356\n\n\nParty1's public key -> A=root^alicesecret(mod(prime))\nParty1 public key is: 34 \n\nParty2's public key -> B=root^bobsecret(mod(prime))\nParty2 public key is 15 \n\nParty1 calculates the shared key as K=B^alicesecret*(mod(prime))\nParty1 calculates the shared key and results: 34 \n\nParty2 calculates the shared key as K=A^bobsecret(mod(prime))\nParty2 calculates the shared key and results: 34 \n\nAttacker does not know the shared private key that Party1 & Party2 can now use\nNow Eve implements Man In the Middle Attack !!\nEnter a secret number1 for attacker: 7349\nEnter a secret number2 for attacker: 3560\n\n\nAttacker's public key -> C=root^attacksecret(mod(prime))\nAttacker public key1 which is shared with Party1: 17\nAttacker public key2 which is shared with Party2: 47\n\n\nThe key used to decrypt message from A and modify: 9\nThe key used to encrypt message to be sent to B is: 47\nParty1 calculates the shared key with attacker's public key1: \nShared final key: 9\nParty2 calculates the shared key with attacker's public key2: \nShared final key: 47 \n\nThe final keys are different. \n>>> \n" '\nTook help from:\n1. https://sublimerobots.com/2015/01/simple-diffie-hellman-example-python/\n2. https://trinket.io/python/d574095364\n3. https://www.wolframalpha.com/widgets/view.jsp?id=ef51422db7db201ebc03c8800f41ba99\nThanks for the help !\n'
REC1 = b"""cam a22002051 4500001001300000003000400013005001700017008004100034010001700075035001900092040001800111050001600129100003500145245017600180260004300356300001900399500002600418650002100444650004900465 00000002 DLC20040505165105.0800108s1899 ilu 000 0 eng  a 00000002  a(OCoLC)5853149 aDLCcDSIdDLC00aRX671b.A921 aAurand, Samuel Herbert,d1854-10aBotanical materia medica and pharmacology;bdrugs considered from a botanical, pharmaceutical, physiological, therapeutical and toxicological standpoint.cBy S. H. Aurand. aChicago,bP. H. Mallen Company,c1899. a406 p.c24 cm. aHomeopathic formulae. 0aBotany, Medical. 0aHomeopathyxMateria medica and therapeutics.""" REC_MX = b"""cpc a2200733 a 4500001001300000003000400013005001700017007000700034007001000041007000700051007000700058008004100065010001700106040002400123043001200147050001700159100005500176245003400231246004300265246005400308260001000362300006000372300006300432300005900495300006000554300004500614300006100659351073000720520069901450520033602149524010102485540008002586545032702666500012702993500007303120541011503193650005103308650004703359650005303406650006003459650006903519650005803588650004803646650006103694650006003755650005703815650005803872650006003930650006403990650005904054650006804113650006904181650006404250655004204314655004404356655003904400655004504439655005304484655004504537655005004582655005004632852009104682856010804773 00650024 DLC20101209130102.0kh|bo|gt|cj||s kg|b||kh|c||000724i19802005xxu eng  a 00650024  aDLCcDLCdDLCegihc an-us-dc00aGuide Record1 aHighsmith, Carol M.,d1946-ephotographer,edonor.10aHighsmith archiveh[graphic].33aCarol M. Highsmith archiveh[graphic].33aCarol M. Highsmith photograph archiveh[graphic]. c1980- a276 photographic prints :bgelatin silver ;c8 x 10 in. a241 photographic prints :bcibachrome, color ;c8 x 10 in. a824 transparencies :bfilm, color ;cchiefly 4 x 5 in. a1213 negatives :bsafety film, b&w ;cchiefly 4 x 5 in. a2 photographs (digital prints) :bcolor. a11,271 photographs :bdigital files, TIFF, mostly color. aFilm negatives and transparencies are organized by type of film and size in the following filing series: LC-HS503 (4x5 color transparencies), LC-HS505 (120 color slides), LC-HS507 (120 color slides, mounted), LC-HS513 (4x5 negatives), LC-HS543 (4x5 color negatvies) and LC-HS545 (120 color negatives) . Within each filing series negatives and transparencies are arranged numerically by a one-up number assigned by the photographer. Photographic prints or digital scans serve as reference copies for the negatives and transparencies and are organized by project or subject into groups with the call number designation LOT. Each LOT is cataloged separately and linked through the collection title: Carol M. Highsmith archive.0 aThe archive consists primarily of photographs documenting buildings, urban renewal efforts, and historic preservation. Many of the photographs document the Washington, D.C. area. Projects for the General Services Administration (GSA) show US government buildings through the United States. Projects for the Urban Land Institute document urban settings such as San Antonio, Texas and the greater Los Angeles, California region. Also included are photographs of President Ronald Reagan meeting with Republican Senatorial candidates and photographs of Lexington, Virginia. In addition, there are two photographs taken near the crash site of United Airlines Flight 93 in Shanksville, Pennsylvania.0 aIn 2007, the photographer began to add born digital photographs to the archive, beginning with a large project documenting the Library of Congress buildings; continuing the GSA building documentation; and in 2009 launching the Carol M. Highsmith's America project to document each state in the United States, starting with Alabama.8 aPublished images must bear the credit line: The Library of Congress, Carol M. Highsmith Archive. aNo known restrictions on publication. Photographs are in the public domain. aDistinguished architectural photographer, based in Washington, D.C., Highsmith documents architecture and architectural renovation projects in the nation's capitol and throughout the United States. She bases her career on the work of noted documentary and architectural photographer Frances Benjamin Johnston (1864-1952). aThis archive is open-ended; future gifts are expected. The catalog record will be updated as new accessions are processed. aCollection includes Highsmith's captions which accompany the images. cGift;aCarol M. Highsmith;d1992, 1994, 2002;e(DLC/PP-1992:189, DLC/PP-1994:020, DLC/PP-2002:038), and later. 7aArchitecturezUnited Statesy1980-2010.2lctgm 7aChurcheszUnited Statesy1980-2010.2lctgm 7aCities & townszUnited Statesy1980-2010.2lctgm 7aCommercial facilitieszUnited Statesy1980-2010.2lctgm 7aConservation & restorationzWashington (D.C.)y1980-2000.2lctgm 7aCultural facilitieszUnited Statesy1980-2010.2lctgm 7aDwellingszUnited Statesy1980-2010.2lctgm 7aEducational facilitieszUnited Statesy1980-2010.2lctgm 7aGovernment facilitieszUnited Statesy1980-2010.2lctgm 7aHistoric buildingszUnited Statesy1980-2010.2lctgm 7aMilitary facilitieszUnited Statesy1980-2010.2lctgm 7aMonuments & memorialszUnited Statesy1980-2010.2lctgm 7aSocial & civic facilitieszUnited Statesy1980-2010.2lctgm 7aParades & processionszUnited Statesy1980-20102lctgm 7aPresidents & the CongresszWashington (D.C.)y1980-1990.2lctgm 7aSports & recreation facilitieszUnited Statesy1980-2010.2lctgm 7aTransportation facilitieszUnited Statesy1980-2010.2lctgm 7aAerial photographsy1980-2010.2gmgpc 7aPortrait photographsy1980-1990.2gmgpc 7aGroup portraitsy1980-1990.2gmgpc 7aGelatin silver printsy1980-2000.2gmgpc 7aDye destruction printsxColory1980-2000.2gmgpc 7aSafety film negativesy1980-2010.2gmgpc 7aFilm transparenciesxColory1980-2010.2gmgpc 7aDigital photographsxColory2000-2010.2gmgpc aLibrary of CongressbPrints and Photographs DivisioneWashington, D.C., 20540 USAndcu41zSearch for Highsmith items in Prints & Photographs Online Cataloguhttp://hdl.loc.gov/loc.pnp/pp.highsm""" REC_MP = b"""cem a22002531 4500001001300000003000400013005001700017007000900034008004100043010001700084035002000101040002600121043001200147050002300159100003500182245017700217255001900394260004600413300003200459505012300491651002800614650005100642710002300693 00004452 DLC20121013005559.0ad canzn940812m18981906pau e eng  a 00004452  a(OCoLC)30935992 aDLCcPPiHidPPiDdDLC an-us-pa00aG1264.P6bH62 18981 aHopkins, Griffith Morgan,cJr.10aReal estate plat-book of the city of Pittsburgh :bfrom official records, private plans and actual surveys /cconstructed under the direction and published by G.M. Hopkins. aScales differ. aPhiladelphia :bG.M. Hopkins,c1898-1906. a4 v. :bcol. maps ;c59 cm.0 av.1. 13th-14th, 22nd-23rd wards -- v. 2. 18th-21st, 37th wards -- v. 3 6th-12th, 15th-17th wards -- v. 4. 1st-5th, 7th 0aPittsburgh (Pa.)vMaps. 0aReal propertyzPennsylvaniazPittsburghvMaps.2 aG.M. Hopkins & Co.""" REC_CF = b"""cmm a2200349 a 4500001001300000003000400013005001700017007001500034008004100049010001700090020001500107040001300122050001000135082001400145245013600159256003100295260007500326300004100401490005900442538024400501538020300745500002700948521004300975520012701018650002001145650001701165700002401182700002501206700002201231710004901253830007701302 00021631 DLC20030624102241.0co |||||||||||000110s2000 ohu f m eng  a 00021631  a1571170383 aDLCcDLC00aTA16510a620.121300aLeak testing CD-ROMh[computer file] /ctechnical editors, Charles N. Jackson, Jr., Charles N. Sherlock ; editor, Patrick O. Moore. aComputer data and program. aColumbus, Ohio :bAmerican Society for Nondestructive Testing,cc2000. a1 computer optical disc ;c4 3/4 in.1 aNondestructive testing handbook. Third edition ;vv. 1 aSystem requirements for Windows: i486 or Pentium processor-based PC; 8MB RAM on Windows 95 or 98 (16MB recommended); 16MB RAM on Windows NT (24MB recommended); Microsoft Windows 95, 98, or NT 4.0 with Service Pack 3 or later; CD-ROM drive. aSystem requirements for Macintosh: Apple Power Macintosh ; 4.5MB RAM available to Acrobat Reader (6.5 recommended); Apple System Software 7.1.2 or later; 8MB available hard disk space; CD-ROM drive. aTitle from disc label. aQuality control engineers, inspectors. aTheory and application of nondestructive tests for characterization and inspection of industrial materials and components. 0aLeak detectors. 0aGas leakage.1 aJackson, Charles N.1 aSherlock, Charles N.1 aMoore, Patrick O.2 aAmerican Society for Nondestructive Testing. 0aNondestructive testing handbook (3rd ed. : Electronic resource) ;vv. 1.""" REC_MU = b"""cjm a22002771a 4500001001300000003000400013005001700017007001500034008004100049050001400090010001700104020001100121024001700132028003400149035002300183040001800206042001300224100002400237245005000261260004700311300004100358500001800399511006100417505038100478650001600859 00000838 DLC20030506181700.0sd|zsngnnmmned000824s1998 nyuppn d00aSDA 16949 a 00000838  c$15.981 a60121531262102aUPTD 53126bUniversal Records a(OCoLC)ocm39655785 aOCOcOCOdDLC alcderive0 aMcGruffc(Musician)10aDestined to beh[sound recording] /cMcGruff. aNew York, NY :bUniversal Records,cp1998. a1 sound disc :bdigital ;c4 3/4 in. aCompact disc.0 aRap music performed by McGruff ; with accomp. musicians.0 aGruff express -- Harlem kidz get biz -- This is how we do -- Many know -- Exquisite -- The spot (interlude) -- What part of the game -- Who holds his own -- What cha doin' to me -- Destined to be -- Freestyle -- Dangerzone -- What you want -- Before we start -- Reppin' uptown (featuring The Lox) -- The signing (interlude) -- Stop it -- Before we start (remix) (bonus track). 0aRap (Music)""" REC_CR = b"""nas a2200157 a 4500001001300000003000400013005001700017008004100034010001700075035002000092040001300112042000700125245008500132260007400217500012100291 00000000 DLC19940915171908.0940906u19949999dcuuu 0 0eng  a 00000000  a(OCoLC)31054590 aDLCcDLC alc00aOnline test record /cJohn D. Levy, Serial Record Division, Library of Congress. aWashington, DC :bLibrary of Congress, Serial Record Division,c1994- aThis record provides a marker in the LC MUMS ONUM index that will prevent other records with this LCCN from loading.""" REC_VM = b"""cgm a22001817a 4500001001300000003000400013005001700017007002400034008004100058010001700099040001300116050003000129245008400159260004000243300005900283541008300342710005200425 00270273 DLC20000412151520.0m 991028s xxu v|eng  a 00270273  aDLCcDLC00aCGC 9600-9605 (ref print)00aAfflictionh[motion picture] /cLargo Entertainment; directed by Paul Schrader. aU.S. :bLargo Entertainment,c1997. a12r of 12 on 6 reels :bsd., col. ;c35 mm. ref print. dReceived: 3/24/00;3ref print;ccopyright deposit--407;aCopyright Collection.2 aCopyright Collection (Library of Congress)5DLC""" REC_02 = b"""cem a22002893a 4500001001300000003000400013005001700017007000900034007000700043008004100050010003000091017003400121034001400155040001300169050002400182052000900206110003000215245003700245255002700282260001900309300003400328530007900362651002300441752001700464852008600481856010100567 00552205DLC20000621074203.0aj|canzncr||||000313s1915 xx d 0 eng  a 00552205z 99446781  aF27747bU.S. Copyright Office0 aab140000 aDLCcDLC00aG4970 1915b.R3 TIL a49702 aRand McNally and Company.00aMap of the island of Porto Rico. aScale [ca. 1:140,000]. a[S.l.],c1915. a1 map :bcol. ;c71 x 160 cm. aAvailable also through the Library of Congress web site as a raster image. 0aPuerto RicovMaps. aPuerto Rico.0 aLibrary of CongressbGeography and Map DivisioneWashington, D.C. 20540-4650ndcu7 dg4970fct000492gurn:hdl:loc.gmd/g4970.ct000492uhttp://hdl.loc.gov/loc.gmd/g4970.ct0004922http"""
rec1 = b'cam a22002051 4500001001300000003000400013005001700017008004100034010001700075035001900092040001800111050001600129100003500145245017600180260004300356300001900399500002600418650002100444650004900465\x1e 00000002 \x1eDLC\x1e20040505165105.0\x1e800108s1899 ilu 000 0 eng \x1e \x1fa 00000002 \x1e \x1fa(OCoLC)5853149\x1e \x1faDLC\x1fcDSI\x1fdDLC\x1e00\x1faRX671\x1fb.A92\x1e1 \x1faAurand, Samuel Herbert,\x1fd1854-\x1e10\x1faBotanical materia medica and pharmacology;\x1fbdrugs considered from a botanical, pharmaceutical, physiological, therapeutical and toxicological standpoint.\x1fcBy S. H. Aurand.\x1e \x1faChicago,\x1fbP. H. Mallen Company,\x1fc1899.\x1e \x1fa406 p.\x1fc24 cm.\x1e \x1faHomeopathic formulae.\x1e 0\x1faBotany, Medical.\x1e 0\x1faHomeopathy\x1fxMateria medica and therapeutics.\x1e\x1d' rec_mx = b"cpc a2200733 a 4500001001300000003000400013005001700017007000700034007001000041007000700051007000700058008004100065010001700106040002400123043001200147050001700159100005500176245003400231246004300265246005400308260001000362300006000372300006300432300005900495300006000554300004500614300006100659351073000720520069901450520033602149524010102485540008002586545032702666500012702993500007303120541011503193650005103308650004703359650005303406650006003459650006903519650005803588650004803646650006103694650006003755650005703815650005803872650006003930650006403990650005904054650006804113650006904181650006404250655004204314655004404356655003904400655004504439655005304484655004504537655005004582655005004632852009104682856010804773\x1e 00650024 \x1eDLC\x1e20101209130102.0\x1ekh|bo|\x1egt|cj||s \x1ekg|b||\x1ekh|c||\x1e000724i19802005xxu eng \x1e \x1fa 00650024 \x1e \x1faDLC\x1fcDLC\x1fdDLC\x1fegihc\x1e \x1fan-us-dc\x1e00\x1faGuide Record\x1e1 \x1faHighsmith, Carol M.,\x1fd1946-\x1fephotographer,\x1fedonor.\x1e10\x1faHighsmith archive\x1fh[graphic].\x1e33\x1faCarol M. Highsmith archive\x1fh[graphic].\x1e33\x1faCarol M. Highsmith photograph archive\x1fh[graphic].\x1e \x1fc1980-\x1e \x1fa276 photographic prints :\x1fbgelatin silver ;\x1fc8 x 10 in.\x1e \x1fa241 photographic prints :\x1fbcibachrome, color ;\x1fc8 x 10 in.\x1e \x1fa824 transparencies :\x1fbfilm, color ;\x1fcchiefly 4 x 5 in.\x1e \x1fa1213 negatives :\x1fbsafety film, b&w ;\x1fcchiefly 4 x 5 in.\x1e \x1fa2 photographs (digital prints) :\x1fbcolor.\x1e \x1fa11,271 photographs :\x1fbdigital files, TIFF, mostly color.\x1e \x1faFilm negatives and transparencies are organized by type of film and size in the following filing series: LC-HS503 (4x5 color transparencies), LC-HS505 (120 color slides), LC-HS507 (120 color slides, mounted), LC-HS513 (4x5 negatives), LC-HS543 (4x5 color negatvies) and LC-HS545 (120 color negatives) . Within each filing series negatives and transparencies are arranged numerically by a one-up number assigned by the photographer. Photographic prints or digital scans serve as reference copies for the negatives and transparencies and are organized by project or subject into groups with the call number designation LOT. Each LOT is cataloged separately and linked through the collection title: Carol M. Highsmith archive.\x1e0 \x1faThe archive consists primarily of photographs documenting buildings, urban renewal efforts, and historic preservation. Many of the photographs document the Washington, D.C. area. Projects for the General Services Administration (GSA) show US government buildings through the United States. Projects for the Urban Land Institute document urban settings such as San Antonio, Texas and the greater Los Angeles, California region. Also included are photographs of President Ronald Reagan meeting with Republican Senatorial candidates and photographs of Lexington, Virginia. In addition, there are two photographs taken near the crash site of United Airlines Flight 93 in Shanksville, Pennsylvania.\x1e0 \x1faIn 2007, the photographer began to add born digital photographs to the archive, beginning with a large project documenting the Library of Congress buildings; continuing the GSA building documentation; and in 2009 launching the Carol M. Highsmith's America project to document each state in the United States, starting with Alabama.\x1e8 \x1faPublished images must bear the credit line: The Library of Congress, Carol M. Highsmith Archive.\x1e \x1faNo known restrictions on publication. Photographs are in the public domain.\x1e \x1faDistinguished architectural photographer, based in Washington, D.C., Highsmith documents architecture and architectural renovation projects in the nation's capitol and throughout the United States. She bases her career on the work of noted documentary and architectural photographer Frances Benjamin Johnston (1864-1952).\x1e \x1faThis archive is open-ended; future gifts are expected. The catalog record will be updated as new accessions are processed.\x1e \x1faCollection includes Highsmith's captions which accompany the images.\x1e \x1fcGift;\x1faCarol M. Highsmith;\x1fd1992, 1994, 2002;\x1fe(DLC/PP-1992:189, DLC/PP-1994:020, DLC/PP-2002:038), and later.\x1e 7\x1faArchitecture\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faChurches\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faCities & towns\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faCommercial facilities\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faConservation & restoration\x1fzWashington (D.C.)\x1fy1980-2000.\x1f2lctgm\x1e 7\x1faCultural facilities\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faDwellings\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faEducational facilities\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faGovernment facilities\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faHistoric buildings\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faMilitary facilities\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faMonuments & memorials\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faSocial & civic facilities\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faParades & processions\x1fzUnited States\x1fy1980-2010\x1f2lctgm\x1e 7\x1faPresidents & the Congress\x1fzWashington (D.C.)\x1fy1980-1990.\x1f2lctgm\x1e 7\x1faSports & recreation facilities\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faTransportation facilities\x1fzUnited States\x1fy1980-2010.\x1f2lctgm\x1e 7\x1faAerial photographs\x1fy1980-2010.\x1f2gmgpc\x1e 7\x1faPortrait photographs\x1fy1980-1990.\x1f2gmgpc\x1e 7\x1faGroup portraits\x1fy1980-1990.\x1f2gmgpc\x1e 7\x1faGelatin silver prints\x1fy1980-2000.\x1f2gmgpc\x1e 7\x1faDye destruction prints\x1fxColor\x1fy1980-2000.\x1f2gmgpc\x1e 7\x1faSafety film negatives\x1fy1980-2010.\x1f2gmgpc\x1e 7\x1faFilm transparencies\x1fxColor\x1fy1980-2010.\x1f2gmgpc\x1e 7\x1faDigital photographs\x1fxColor\x1fy2000-2010.\x1f2gmgpc\x1e \x1faLibrary of Congress\x1fbPrints and Photographs Division\x1feWashington, D.C., 20540 USA\x1fndcu\x1e41\x1fzSearch for Highsmith items in Prints & Photographs Online Catalog\x1fuhttp://hdl.loc.gov/loc.pnp/pp.highsm\x1e\x1d" rec_mp = b'cem a22002531 4500001001300000003000400013005001700017007000900034008004100043010001700084035002000101040002600121043001200147050002300159100003500182245017700217255001900394260004600413300003200459505012300491651002800614650005100642710002300693\x1e 00004452 \x1eDLC\x1e20121013005559.0\x1ead canzn\x1e940812m18981906pau e eng \x1e \x1fa 00004452 \x1e \x1fa(OCoLC)30935992\x1e \x1faDLC\x1fcPPiHi\x1fdPPiD\x1fdDLC\x1e \x1fan-us-pa\x1e00\x1faG1264.P6\x1fbH62 1898\x1e1 \x1faHopkins, Griffith Morgan,\x1fcJr.\x1e10\x1faReal estate plat-book of the city of Pittsburgh :\x1fbfrom official records, private plans and actual surveys /\x1fcconstructed under the direction and published by G.M. Hopkins.\x1e \x1faScales differ.\x1e \x1faPhiladelphia :\x1fbG.M. Hopkins,\x1fc1898-1906.\x1e \x1fa4 v. :\x1fbcol. maps ;\x1fc59 cm.\x1e0 \x1fav.1. 13th-14th, 22nd-23rd wards -- v. 2. 18th-21st, 37th wards -- v. 3 6th-12th, 15th-17th wards -- v. 4. 1st-5th, 7th\x1e 0\x1faPittsburgh (Pa.)\x1fvMaps.\x1e 0\x1faReal property\x1fzPennsylvania\x1fzPittsburgh\x1fvMaps.\x1e2 \x1faG.M. Hopkins & Co.\x1e\x1d' rec_cf = b'cmm a2200349 a 4500001001300000003000400013005001700017007001500034008004100049010001700090020001500107040001300122050001000135082001400145245013600159256003100295260007500326300004100401490005900442538024400501538020300745500002700948521004300975520012701018650002001145650001701165700002401182700002501206700002201231710004901253830007701302\x1e 00021631 \x1eDLC\x1e20030624102241.0\x1eco |||||||||||\x1e000110s2000 ohu f m eng \x1e \x1fa 00021631 \x1e \x1fa1571170383\x1e \x1faDLC\x1fcDLC\x1e00\x1faTA165\x1e10\x1fa620.1\x1f213\x1e00\x1faLeak testing CD-ROM\x1fh[computer file] /\x1fctechnical editors, Charles N. Jackson, Jr., Charles N. Sherlock ; editor, Patrick O. Moore.\x1e \x1faComputer data and program.\x1e \x1faColumbus, Ohio :\x1fbAmerican Society for Nondestructive Testing,\x1fcc2000.\x1e \x1fa1 computer optical disc ;\x1fc4 3/4 in.\x1e1 \x1faNondestructive testing handbook. Third edition ;\x1fvv. 1\x1e \x1faSystem requirements for Windows: i486 or Pentium processor-based PC; 8MB RAM on Windows 95 or 98 (16MB recommended); 16MB RAM on Windows NT (24MB recommended); Microsoft Windows 95, 98, or NT 4.0 with Service Pack 3 or later; CD-ROM drive.\x1e \x1faSystem requirements for Macintosh: Apple Power Macintosh ; 4.5MB RAM available to Acrobat Reader (6.5 recommended); Apple System Software 7.1.2 or later; 8MB available hard disk space; CD-ROM drive.\x1e \x1faTitle from disc label.\x1e \x1faQuality control engineers, inspectors.\x1e \x1faTheory and application of nondestructive tests for characterization and inspection of industrial materials and components.\x1e 0\x1faLeak detectors.\x1e 0\x1faGas leakage.\x1e1 \x1faJackson, Charles N.\x1e1 \x1faSherlock, Charles N.\x1e1 \x1faMoore, Patrick O.\x1e2 \x1faAmerican Society for Nondestructive Testing.\x1e 0\x1faNondestructive testing handbook (3rd ed. : Electronic resource) ;\x1fvv. 1.\x1e\x1d' rec_mu = b"cjm a22002771a 4500001001300000003000400013005001700017007001500034008004100049050001400090010001700104020001100121024001700132028003400149035002300183040001800206042001300224100002400237245005000261260004700311300004100358500001800399511006100417505038100478650001600859\x1e 00000838 \x1eDLC\x1e20030506181700.0\x1esd|zsngnnmmned\x1e000824s1998 nyuppn d\x1e00\x1faSDA 16949\x1e \x1fa 00000838 \x1e \x1fc$15.98\x1e1 \x1fa601215312621\x1e02\x1faUPTD 53126\x1fbUniversal Records\x1e \x1fa(OCoLC)ocm39655785\x1e \x1faOCO\x1fcOCO\x1fdDLC\x1e \x1falcderive\x1e0 \x1faMcGruff\x1fc(Musician)\x1e10\x1faDestined to be\x1fh[sound recording] /\x1fcMcGruff.\x1e \x1faNew York, NY :\x1fbUniversal Records,\x1fcp1998.\x1e \x1fa1 sound disc :\x1fbdigital ;\x1fc4 3/4 in.\x1e \x1faCompact disc.\x1e0 \x1faRap music performed by McGruff ; with accomp. musicians.\x1e0 \x1faGruff express -- Harlem kidz get biz -- This is how we do -- Many know -- Exquisite -- The spot (interlude) -- What part of the game -- Who holds his own -- What cha doin' to me -- Destined to be -- Freestyle -- Dangerzone -- What you want -- Before we start -- Reppin' uptown (featuring The Lox) -- The signing (interlude) -- Stop it -- Before we start (remix) (bonus track).\x1e 0\x1faRap (Music)\x1e\x1d" rec_cr = b'nas a2200157 a 4500001001300000003000400013005001700017008004100034010001700075035002000092040001300112042000700125245008500132260007400217500012100291\x1e 00000000 \x1eDLC\x1e19940915171908.0\x1e940906u19949999dcuuu 0 0eng \x1e \x1fa 00000000 \x1e \x1fa(OCoLC)31054590\x1e \x1faDLC\x1fcDLC\x1e \x1falc\x1e00\x1faOnline test record /\x1fcJohn D. Levy, Serial Record Division, Library of Congress.\x1e \x1faWashington, DC :\x1fbLibrary of Congress, Serial Record Division,\x1fc1994-\x1e \x1faThis record provides a marker in the LC MUMS ONUM index that will prevent other records with this LCCN from loading.\x1e\x1d' rec_vm = b'cgm a22001817a 4500001001300000003000400013005001700017007002400034008004100058010001700099040001300116050003000129245008400159260004000243300005900283541008300342710005200425\x1e 00270273 \x1eDLC\x1e20000412151520.0\x1em \x1e991028s xxu v|eng \x1e \x1fa 00270273 \x1e \x1faDLC\x1fcDLC\x1e00\x1faCGC 9600-9605 (ref print)\x1e00\x1faAffliction\x1fh[motion picture] /\x1fcLargo Entertainment; directed by Paul Schrader.\x1e \x1faU.S. :\x1fbLargo Entertainment,\x1fc1997.\x1e \x1fa12r of 12 on 6 reels :\x1fbsd., col. ;\x1fc35 mm. ref print.\x1e \x1fdReceived: 3/24/00;\x1f3ref print;\x1fccopyright deposit--407;\x1faCopyright Collection.\x1e2 \x1faCopyright Collection (Library of Congress)\x1f5DLC\x1e\x1d' rec_02 = b'cem a22002893a 4500001001300000003000400013005001700017007000900034007000700043008004100050010003000091017003400121034001400155040001300169050002400182052000900206110003000215245003700245255002700282260001900309300003400328530007900362651002300441752001700464852008600481856010100567\x1e 00552205\x1f\x1eDLC\x1e20000621074203.0\x1eaj|canzn\x1ecr||||\x1e000313s1915 xx d 0 eng \x1e \x1fa 00552205\x1fz 99446781 \x1e \x1faF27747\x1fbU.S. Copyright Office\x1e0 \x1faa\x1fb140000\x1e \x1faDLC\x1fcDLC\x1e00\x1faG4970 1915\x1fb.R3 TIL\x1e \x1fa4970\x1e2 \x1faRand McNally and Company.\x1e00\x1faMap of the island of Porto Rico.\x1e \x1faScale [ca. 1:140,000].\x1e \x1fa[S.l.],\x1fc1915.\x1e \x1fa1 map :\x1fbcol. ;\x1fc71 x 160 cm.\x1e \x1faAvailable also through the Library of Congress web site as a raster image.\x1e 0\x1faPuerto Rico\x1fvMaps.\x1e \x1faPuerto Rico.\x1e0 \x1faLibrary of Congress\x1fbGeography and Map Division\x1feWashington, D.C. 20540-4650\x1fndcu\x1e7 \x1fdg4970\x1ffct000492\x1fgurn:hdl:loc.gmd/g4970.ct000492\x1fuhttp://hdl.loc.gov/loc.gmd/g4970.ct000492\x1f2http\x1e\x1d'
"""A bunch of click related tools / helpers / patterns that have a potential of reuse across clis. TODO: We would improve sharing by moving these to a separate re-usable repository instead of copying. """
"""A bunch of click related tools / helpers / patterns that have a potential of reuse across clis. TODO: We would improve sharing by moving these to a separate re-usable repository instead of copying. """
''' your local settings. Note that if you install using setuptools, change this module first before running setup.py install. ''' oauthkey = '7dkss6x9fn5v' secret = 't5f28uhdmct7zhdr' country = 'US'
""" your local settings. Note that if you install using setuptools, change this module first before running setup.py install. """ oauthkey = '7dkss6x9fn5v' secret = 't5f28uhdmct7zhdr' country = 'US'
#!/usr/bin/env python3 # Conditional Statements def drink(money): if (money >= 2): return "You've got yourself a drink!" else: return "NO drink for you!" print(drink(3)) print(drink(1)) def alcohol(age, money): if (age >= 21) and (money >= 5): # if statement return "we're getting a drink!" elif (age >= 21) and (money < 5): # else-if statement return "Come back with more money!" elif (age < 21) and (money >= 5): return "Nice try, kid!" else: # else statement return "You're too poor and too young" print(alcohol(21, 5)) print(alcohol(21, 4)) print(alcohol(20, 4))
def drink(money): if money >= 2: return "You've got yourself a drink!" else: return 'NO drink for you!' print(drink(3)) print(drink(1)) def alcohol(age, money): if age >= 21 and money >= 5: return "we're getting a drink!" elif age >= 21 and money < 5: return 'Come back with more money!' elif age < 21 and money >= 5: return 'Nice try, kid!' else: return "You're too poor and too young" print(alcohol(21, 5)) print(alcohol(21, 4)) print(alcohol(20, 4))
def getUniqueID(inArray): ''' Given an int array that contains many duplicates and a single unique ID, find it and return it. ''' pairDictionary = {} for quadID in inArray: # print(quadID) # print(pairDictionary) if quadID in pairDictionary: del pairDictionary[quadID] else: pairDictionary[quadID] = 1 return pairDictionary.keys() def getUniqueIDSpaceOptimized(inArray): a = 0 for quadID in inArray: a = a ^ quadID return a def main(): # should return 9 as the unique integer testArray = [1,2,5,3,2,5,3,1,9,3,4,3,4] print("Unique ID was: %s"%(getUniqueID(testArray))) print("With space optimized solution, unique ID was: %s"%(getUniqueIDSpaceOptimized(testArray))) if __name__ == "__main__": main()
def get_unique_id(inArray): """ Given an int array that contains many duplicates and a single unique ID, find it and return it. """ pair_dictionary = {} for quad_id in inArray: if quadID in pairDictionary: del pairDictionary[quadID] else: pairDictionary[quadID] = 1 return pairDictionary.keys() def get_unique_id_space_optimized(inArray): a = 0 for quad_id in inArray: a = a ^ quadID return a def main(): test_array = [1, 2, 5, 3, 2, 5, 3, 1, 9, 3, 4, 3, 4] print('Unique ID was: %s' % get_unique_id(testArray)) print('With space optimized solution, unique ID was: %s' % get_unique_id_space_optimized(testArray)) if __name__ == '__main__': main()
# create a dictionary from two lists using zip() # More information using help('zip') and help('dict') # create two lists dict_keys = ['bananas', 'bread flour', 'cheese', 'milk'] dict_values = [2, 1, 4, 3] # iterate over lists using zip iterator_using_zip = zip(dict_keys, dict_values) # create the dictionary from the zip dictionary_from_zip = dict(iterator_using_zip) print(dictionary_from_zip) # prints {'bananas': 2, 'bread flour': 1, 'cheese': 4, 'milk': 3}
dict_keys = ['bananas', 'bread flour', 'cheese', 'milk'] dict_values = [2, 1, 4, 3] iterator_using_zip = zip(dict_keys, dict_values) dictionary_from_zip = dict(iterator_using_zip) print(dictionary_from_zip)
p = int(input()) q = int(input()) for i in range(1, 101): if i % p == q: print(i)
p = int(input()) q = int(input()) for i in range(1, 101): if i % p == q: print(i)
# PATH UPLOAD_FOLDER = './upload_file' GENERATE_PATH = './download_file' # DATABASE DATABASE = 'mysql' DATABASE_URL = 'localhost:3306' USERNAME = 'root' PASSWORD = 'root'
upload_folder = './upload_file' generate_path = './download_file' database = 'mysql' database_url = 'localhost:3306' username = 'root' password = 'root'
# TODO - bisect operations class SortedDictCore: def __init__(self, *a, **kw): self._items = [] self.dict = dict(*a,**kw) ## def __setitem__(self,k,v): self._items = [] self.dict[k]=v def __getitem__(self,k): return self.dict[k] def __delitem__(self,k): self._items = [] del self.dict[k] ## def sort(self): if self._items: return self._items = sorted(self.dict.items(),key=lambda x:(x[1],x[0])) def items(self): self.sort() return self._items def update(self,*a,**kw): self._items = [] self.dict.update(*a,**kw) class SortedDict(SortedDictCore): def sd_get(self,k): return self.dict.get(k) def sd_set(self,k,v): self[k] = v def sd_del(self,k): if k in self.dict: del self.dict[k] def sd_add(self,k,v): try: self[k] += v except KeyError: self[k] = v return self[k] def sd_items(self,a=None,b=None,c=None): if a is not None or b is not None or c is not None: return self.items() else: return self.items()[a:b:c] # *_many def sd_get_many(self,k_iter): return (self.sd_get(k) for k in k_iter) def sd_set_many(self,kv_iter): for k,v in kv_iter: self.sd_set(k,v) def sd_del_many(self,k_iter): for k in k_iter: self.sd_del(k) def sd_add_many(self,kv_iter): out = [] for k,v in kv_iter: x = self.sd_add(k,v) out.append(x) return out if __name__=="__main__": d = SortedDict(a=3,b=1,c=2,d=(2,2)) d['x'] = 1.5 d.sd_add('a',0.1) d.sd_add('y',0.1) print(d.items()[-2:])
class Sorteddictcore: def __init__(self, *a, **kw): self._items = [] self.dict = dict(*a, **kw) def __setitem__(self, k, v): self._items = [] self.dict[k] = v def __getitem__(self, k): return self.dict[k] def __delitem__(self, k): self._items = [] del self.dict[k] def sort(self): if self._items: return self._items = sorted(self.dict.items(), key=lambda x: (x[1], x[0])) def items(self): self.sort() return self._items def update(self, *a, **kw): self._items = [] self.dict.update(*a, **kw) class Sorteddict(SortedDictCore): def sd_get(self, k): return self.dict.get(k) def sd_set(self, k, v): self[k] = v def sd_del(self, k): if k in self.dict: del self.dict[k] def sd_add(self, k, v): try: self[k] += v except KeyError: self[k] = v return self[k] def sd_items(self, a=None, b=None, c=None): if a is not None or b is not None or c is not None: return self.items() else: return self.items()[a:b:c] def sd_get_many(self, k_iter): return (self.sd_get(k) for k in k_iter) def sd_set_many(self, kv_iter): for (k, v) in kv_iter: self.sd_set(k, v) def sd_del_many(self, k_iter): for k in k_iter: self.sd_del(k) def sd_add_many(self, kv_iter): out = [] for (k, v) in kv_iter: x = self.sd_add(k, v) out.append(x) return out if __name__ == '__main__': d = sorted_dict(a=3, b=1, c=2, d=(2, 2)) d['x'] = 1.5 d.sd_add('a', 0.1) d.sd_add('y', 0.1) print(d.items()[-2:])
n = 2001 number = 1 while n < 2101: if number % 10 == 0: print("\n") number += 1 if n % 100 == 0: if n % 400 == 0: print(n, end=" ") n += 1 number += 1 continue else: n += 1 continue else: if n % 4 == 0: print(n, end=" ") n += 1 number += 1 continue else: n += 1 continue
n = 2001 number = 1 while n < 2101: if number % 10 == 0: print('\n') number += 1 if n % 100 == 0: if n % 400 == 0: print(n, end=' ') n += 1 number += 1 continue else: n += 1 continue elif n % 4 == 0: print(n, end=' ') n += 1 number += 1 continue else: n += 1 continue
# Python - 3.6.0 def high_and_low(numbers): lst = [*map(int, numbers.split(' '))] return f'{max(lst)} {min(lst)}'
def high_and_low(numbers): lst = [*map(int, numbers.split(' '))] return f'{max(lst)} {min(lst)}'
online_store = { "keychain": 0.75, "tshirt": 8.50, "bottle": 10.00 } choicekey = int(input("How many keychains will you be purchasing? If not purchasing keychains, enter 0. ")) choicetshirt = int(input("How many t-shirts will you be purchasing? If not purchasing t-shirts, enter 0. ")) choicebottle = int(input("How many t-shirts will you be purchasing? If not purchasing water bottles, enter 0. ")) if choicekey > 9: online_store['keychain'] = 0.65 if choicetshirt > 9: online_store['tshirt'] = 8.00 if choicebottle > 9: online_store['bottle'] = 8.75 print("You are purchasing " + str(choicekey) + " keychains, " + str(choicetshirt) + " t-shirts, and " + str(choicebottle) + " water bottles.") perskey = input("Will you personalize the keychains for an additional $1.00 each? Type yes or no. ") perstshirt = input("Will you personalize the t-shirts for an additional $5.00 each? Type yes or no. ") persbottle = input("Will you personalize the water bottles for an additional $7.50 each? Type yes or no. ") if perskey == ("yes" or "Yes"): online_store['keychain'] = online_store['keychain'] + 1.00 if perstshirt == ("yes" or "Yes"): online_store['tshirt'] = online_store['tshirt'] + 5.00 if persbottle == ("yes" or "Yes"): online_store['bottle'] = online_store['bottle'] + 7.50 keychain = online_store['keychain'] tshirt = online_store['tshirt'] bottle = online_store['bottle'] totalkey = choicekey * keychain totaltshirt = choicetshirt * tshirt totalbottle = choicebottle * bottle grandtotal = totalkey + totaltshirt + totalbottle print("Keychain total: $" + str(totalkey)) print("T-shirt total: $" + str(totaltshirt)) print("Water bottle total: $" + str(totalbottle)) print("Your order total: $" + str(grandtotal))
online_store = {'keychain': 0.75, 'tshirt': 8.5, 'bottle': 10.0} choicekey = int(input('How many keychains will you be purchasing? If not purchasing keychains, enter 0. ')) choicetshirt = int(input('How many t-shirts will you be purchasing? If not purchasing t-shirts, enter 0. ')) choicebottle = int(input('How many t-shirts will you be purchasing? If not purchasing water bottles, enter 0. ')) if choicekey > 9: online_store['keychain'] = 0.65 if choicetshirt > 9: online_store['tshirt'] = 8.0 if choicebottle > 9: online_store['bottle'] = 8.75 print('You are purchasing ' + str(choicekey) + ' keychains, ' + str(choicetshirt) + ' t-shirts, and ' + str(choicebottle) + ' water bottles.') perskey = input('Will you personalize the keychains for an additional $1.00 each? Type yes or no. ') perstshirt = input('Will you personalize the t-shirts for an additional $5.00 each? Type yes or no. ') persbottle = input('Will you personalize the water bottles for an additional $7.50 each? Type yes or no. ') if perskey == ('yes' or 'Yes'): online_store['keychain'] = online_store['keychain'] + 1.0 if perstshirt == ('yes' or 'Yes'): online_store['tshirt'] = online_store['tshirt'] + 5.0 if persbottle == ('yes' or 'Yes'): online_store['bottle'] = online_store['bottle'] + 7.5 keychain = online_store['keychain'] tshirt = online_store['tshirt'] bottle = online_store['bottle'] totalkey = choicekey * keychain totaltshirt = choicetshirt * tshirt totalbottle = choicebottle * bottle grandtotal = totalkey + totaltshirt + totalbottle print('Keychain total: $' + str(totalkey)) print('T-shirt total: $' + str(totaltshirt)) print('Water bottle total: $' + str(totalbottle)) print('Your order total: $' + str(grandtotal))
# -*- coding: utf-8 -*- config = {} config['log_name'] = 'app_log.log' config['log_format'] = '%(asctime)s - %(levelname)s: %(message)s' config['log_date_format'] = '%Y-%m-%d %I:%M:%S' config['format'] = 'json' config['source_dir'] = 'data' config['output_dir'] = 'export' config['source_glob'] = 'monitoraggio_serviz_controllo_giornaliero_*.pdf' config['processed_dir'] = 'processed'
config = {} config['log_name'] = 'app_log.log' config['log_format'] = '%(asctime)s - %(levelname)s: %(message)s' config['log_date_format'] = '%Y-%m-%d %I:%M:%S' config['format'] = 'json' config['source_dir'] = 'data' config['output_dir'] = 'export' config['source_glob'] = 'monitoraggio_serviz_controllo_giornaliero_*.pdf' config['processed_dir'] = 'processed'
_mods = [] def get(): return _mods def add(mod): _mods.append(mod)
_mods = [] def get(): return _mods def add(mod): _mods.append(mod)
n = int(input()) lst = [list(map(int, input().split())) for _ in range(n)] dp = [[0]*3 for _ in range(n)] for i in range(3): dp[0][i] = lst[0][i] for i in range(1, n): dp[i][0] = max(dp[i-1][1], dp[i-1][2])+lst[i][0] dp[i][1] = max(dp[i-1][0], dp[i-1][2])+lst[i][1] dp[i][2] = max(dp[i-1][0], dp[i-1][1])+lst[i][2] print(max(dp[n-1]))
n = int(input()) lst = [list(map(int, input().split())) for _ in range(n)] dp = [[0] * 3 for _ in range(n)] for i in range(3): dp[0][i] = lst[0][i] for i in range(1, n): dp[i][0] = max(dp[i - 1][1], dp[i - 1][2]) + lst[i][0] dp[i][1] = max(dp[i - 1][0], dp[i - 1][2]) + lst[i][1] dp[i][2] = max(dp[i - 1][0], dp[i - 1][1]) + lst[i][2] print(max(dp[n - 1]))
# cases where FunctionAchievement should not unlock # >> CASE def test(): pass # >> CASE def func(): pass func # >> CASE def func(): pass f = func f() # >> CASE func() # >> CASE func
def test(): pass def func(): pass func def func(): pass f = func f() func() func
""" Tools to validate schema of python objects """ class RoyalValidationError(Exception): pass class SchemaValidator(object): def __init__(self, **kwargs): self.schema = kwargs self.checks = [] def validate(self, obj): for key in self.schema: if key not in obj: raise RoyalValidationError("Expected key '" + key + "' in object.") if isinstance(self.schema[key], type) and not isinstance(obj[key], self.schema[key]): raise RoyalValidationError("Expected key '" + key + "' to be of type: " + str(self.schema[key])) for check in self.checks: if not check(obj): raise RoyalValidationError("Object does not pass all checks") def add_check(self, check): self.checks.append(check)
""" Tools to validate schema of python objects """ class Royalvalidationerror(Exception): pass class Schemavalidator(object): def __init__(self, **kwargs): self.schema = kwargs self.checks = [] def validate(self, obj): for key in self.schema: if key not in obj: raise royal_validation_error("Expected key '" + key + "' in object.") if isinstance(self.schema[key], type) and (not isinstance(obj[key], self.schema[key])): raise royal_validation_error("Expected key '" + key + "' to be of type: " + str(self.schema[key])) for check in self.checks: if not check(obj): raise royal_validation_error('Object does not pass all checks') def add_check(self, check): self.checks.append(check)
class Solution: def removeDuplicates(self, nums: List[int]) -> int: return len(nums) if len(nums) < 2 else self.calculate(nums) @staticmethod def calculate(nums): result = 0 for i in range(1, len(nums)): if nums[i] != nums[result]: result += 1 nums[result] = nums[i] return result + 1
class Solution: def remove_duplicates(self, nums: List[int]) -> int: return len(nums) if len(nums) < 2 else self.calculate(nums) @staticmethod def calculate(nums): result = 0 for i in range(1, len(nums)): if nums[i] != nums[result]: result += 1 nums[result] = nums[i] return result + 1
# function with large number of arguments def fun(a, b, c, d, e, f, g): return a + b + c * d + e * f * g print(fun(1, 2, 3, 4, 5, 6, 7))
def fun(a, b, c, d, e, f, g): return a + b + c * d + e * f * g print(fun(1, 2, 3, 4, 5, 6, 7))
# Input: nums = [0,1,2,2,3,0,4,2], val = 2 # Output: 5, nums = [0,1,4,0,3] # Explanation: Your function should return length = 5, # with the first five elements of nums containing 0, 1, 3, 0, and 4. # Note that the order of those five elements can be arbitrary. # It doesn't matter what values are set beyond the returned length. class Solution: def removeElement(self, nums: List[int], val: int) -> int: try: while True: nums.remove(val) finally: return len(nums)
class Solution: def remove_element(self, nums: List[int], val: int) -> int: try: while True: nums.remove(val) finally: return len(nums)
"""Top-level package for py_tutis.""" __author__ = """Chidozie C. Okafor""" __email__ = "chidosiky2015@gmail.com" __version__ = "0.1.0"
"""Top-level package for py_tutis.""" __author__ = 'Chidozie C. Okafor' __email__ = 'chidosiky2015@gmail.com' __version__ = '0.1.0'
# Copyright 2021 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Partial implementation for Swift frameworks with third party interfaces.""" load( "@build_bazel_rules_apple//apple/internal:processor.bzl", "processor", ) load( "@build_bazel_rules_apple//apple/internal:swift_info_support.bzl", "swift_info_support", ) load( "@bazel_skylib//lib:partial.bzl", "partial", ) load( "@bazel_skylib//lib:paths.bzl", "paths", ) def _swift_framework_partial_impl( *, actions, avoid_deps, bundle_name, framework_modulemap, label_name, output_discriminator, swift_infos): """Implementation for the Swift framework processing partial.""" if len(swift_infos) == 0: fail(""" Internal error: Expected to find a SwiftInfo before entering this partial. Please file an \ issue with a reproducible error case. """) avoid_modules = swift_info_support.modules_from_avoid_deps(avoid_deps = avoid_deps) bundle_files = [] expected_module_name = bundle_name found_module_name = None found_generated_header = None modules_parent = paths.join("Modules", "{}.swiftmodule".format(expected_module_name)) for arch, swiftinfo in swift_infos.items(): swift_module = swift_info_support.swift_include_info( avoid_modules = avoid_modules, found_module_name = found_module_name, transitive_modules = swiftinfo.transitive_modules, ) # If headers are generated, they should be generated equally for all archs, so just take the # first one found. if (not found_generated_header) and swift_module.clang: if swift_module.clang.compilation_context.direct_headers: found_generated_header = swift_module.clang.compilation_context.direct_headers[0] found_module_name = swift_module.name bundle_interface = swift_info_support.declare_swiftinterface( actions = actions, arch = arch, label_name = label_name, output_discriminator = output_discriminator, swiftinterface = swift_module.swift.swiftinterface, ) bundle_files.append((processor.location.bundle, modules_parent, depset([bundle_interface]))) bundle_doc = swift_info_support.declare_swiftdoc( actions = actions, arch = arch, label_name = label_name, output_discriminator = output_discriminator, swiftdoc = swift_module.swift.swiftdoc, ) bundle_files.append((processor.location.bundle, modules_parent, depset([bundle_doc]))) swift_info_support.verify_found_module_name( bundle_name = expected_module_name, found_module_name = found_module_name, ) if found_generated_header: bundle_header = swift_info_support.declare_generated_header( actions = actions, generated_header = found_generated_header, label_name = label_name, output_discriminator = output_discriminator, module_name = expected_module_name, ) bundle_files.append((processor.location.bundle, "Headers", depset([bundle_header]))) modulemap = swift_info_support.declare_modulemap( actions = actions, framework_modulemap = framework_modulemap, label_name = label_name, output_discriminator = output_discriminator, module_name = expected_module_name, ) bundle_files.append((processor.location.bundle, "Modules", depset([modulemap]))) return struct(bundle_files = bundle_files) def swift_framework_partial( *, actions, avoid_deps = [], bundle_name, framework_modulemap = True, label_name, output_discriminator = None, swift_infos): """Constructor for the Swift framework processing partial. This partial collects and bundles the necessary files to construct a Swift based static framework. Args: actions: The actions provider from `ctx.actions`. avoid_deps: A list of library targets with modules to avoid, if specified. bundle_name: The name of the output bundle. framework_modulemap: Boolean to indicate if the generated modulemap should be for a framework instead of a library or a generic module. Defaults to `True`. label_name: Name of the target being built. output_discriminator: A string to differentiate between different target intermediate files or `None`. swift_infos: A dictionary with architectures as keys and the SwiftInfo provider containing the required artifacts for that architecture as values. Returns: A partial that returns the bundle location of the supporting Swift artifacts needed in a Swift based sdk framework. """ return partial.make( _swift_framework_partial_impl, actions = actions, avoid_deps = avoid_deps, bundle_name = bundle_name, framework_modulemap = framework_modulemap, label_name = label_name, output_discriminator = output_discriminator, swift_infos = swift_infos, )
"""Partial implementation for Swift frameworks with third party interfaces.""" load('@build_bazel_rules_apple//apple/internal:processor.bzl', 'processor') load('@build_bazel_rules_apple//apple/internal:swift_info_support.bzl', 'swift_info_support') load('@bazel_skylib//lib:partial.bzl', 'partial') load('@bazel_skylib//lib:paths.bzl', 'paths') def _swift_framework_partial_impl(*, actions, avoid_deps, bundle_name, framework_modulemap, label_name, output_discriminator, swift_infos): """Implementation for the Swift framework processing partial.""" if len(swift_infos) == 0: fail('\nInternal error: Expected to find a SwiftInfo before entering this partial. Please file an issue with a reproducible error case.\n') avoid_modules = swift_info_support.modules_from_avoid_deps(avoid_deps=avoid_deps) bundle_files = [] expected_module_name = bundle_name found_module_name = None found_generated_header = None modules_parent = paths.join('Modules', '{}.swiftmodule'.format(expected_module_name)) for (arch, swiftinfo) in swift_infos.items(): swift_module = swift_info_support.swift_include_info(avoid_modules=avoid_modules, found_module_name=found_module_name, transitive_modules=swiftinfo.transitive_modules) if not found_generated_header and swift_module.clang: if swift_module.clang.compilation_context.direct_headers: found_generated_header = swift_module.clang.compilation_context.direct_headers[0] found_module_name = swift_module.name bundle_interface = swift_info_support.declare_swiftinterface(actions=actions, arch=arch, label_name=label_name, output_discriminator=output_discriminator, swiftinterface=swift_module.swift.swiftinterface) bundle_files.append((processor.location.bundle, modules_parent, depset([bundle_interface]))) bundle_doc = swift_info_support.declare_swiftdoc(actions=actions, arch=arch, label_name=label_name, output_discriminator=output_discriminator, swiftdoc=swift_module.swift.swiftdoc) bundle_files.append((processor.location.bundle, modules_parent, depset([bundle_doc]))) swift_info_support.verify_found_module_name(bundle_name=expected_module_name, found_module_name=found_module_name) if found_generated_header: bundle_header = swift_info_support.declare_generated_header(actions=actions, generated_header=found_generated_header, label_name=label_name, output_discriminator=output_discriminator, module_name=expected_module_name) bundle_files.append((processor.location.bundle, 'Headers', depset([bundle_header]))) modulemap = swift_info_support.declare_modulemap(actions=actions, framework_modulemap=framework_modulemap, label_name=label_name, output_discriminator=output_discriminator, module_name=expected_module_name) bundle_files.append((processor.location.bundle, 'Modules', depset([modulemap]))) return struct(bundle_files=bundle_files) def swift_framework_partial(*, actions, avoid_deps=[], bundle_name, framework_modulemap=True, label_name, output_discriminator=None, swift_infos): """Constructor for the Swift framework processing partial. This partial collects and bundles the necessary files to construct a Swift based static framework. Args: actions: The actions provider from `ctx.actions`. avoid_deps: A list of library targets with modules to avoid, if specified. bundle_name: The name of the output bundle. framework_modulemap: Boolean to indicate if the generated modulemap should be for a framework instead of a library or a generic module. Defaults to `True`. label_name: Name of the target being built. output_discriminator: A string to differentiate between different target intermediate files or `None`. swift_infos: A dictionary with architectures as keys and the SwiftInfo provider containing the required artifacts for that architecture as values. Returns: A partial that returns the bundle location of the supporting Swift artifacts needed in a Swift based sdk framework. """ return partial.make(_swift_framework_partial_impl, actions=actions, avoid_deps=avoid_deps, bundle_name=bundle_name, framework_modulemap=framework_modulemap, label_name=label_name, output_discriminator=output_discriminator, swift_infos=swift_infos)
class Solution: def firstMissingPositive(self, nums: List[int], res: int = 1) -> int: for num in sorted(nums): res += num == res return res
class Solution: def first_missing_positive(self, nums: List[int], res: int=1) -> int: for num in sorted(nums): res += num == res return res
# # PySNMP MIB module Wellfleet-AOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-AOT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:32:37 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") NotificationType, Bits, Integer32, ModuleIdentity, ObjectIdentity, Counter32, TimeTicks, Gauge32, Counter64, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Bits", "Integer32", "ModuleIdentity", "ObjectIdentity", "Counter32", "TimeTicks", "Gauge32", "Counter64", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "MibIdentifier") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") wfAsyncOverTcpGroup, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfAsyncOverTcpGroup") wfAot = MibIdentifier((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1)) wfAotDelete = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotDelete.setStatus('mandatory') wfAotDisable = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotDisable.setStatus('mandatory') wfAotState = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("init", 3), ("notpresent", 4))).clone('down')).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotState.setStatus('mandatory') wfAotInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2), ) if mibBuilder.loadTexts: wfAotInterfaceTable.setStatus('mandatory') wfAotInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1), ).setIndexNames((0, "Wellfleet-AOT-MIB", "wfAotInterfaceSlotNumber"), (0, "Wellfleet-AOT-MIB", "wfAotInterfaceCctNumber")) if mibBuilder.loadTexts: wfAotInterfaceEntry.setStatus('mandatory') wfAotInterfaceDelete = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotInterfaceDelete.setStatus('mandatory') wfAotInterfaceDisable = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotInterfaceDisable.setStatus('mandatory') wfAotInterfaceCctNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotInterfaceCctNumber.setStatus('mandatory') wfAotInterfaceSlotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotInterfaceSlotNumber.setStatus('mandatory') wfAotInterfaceState = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("init", 3))).clone('down')).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotInterfaceState.setStatus('mandatory') wfAotInterfaceType = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("singledrop", 1), ("multidrop", 2))).clone('singledrop')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotInterfaceType.setStatus('mandatory') wfAotInterfaceAttachedTo = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("primary", 1), ("secondary", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotInterfaceAttachedTo.setStatus('mandatory') wfAotInterfacePktCnt = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotInterfacePktCnt.setStatus('mandatory') wfAotKeepaliveInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 86400)).clone(120)).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotKeepaliveInterval.setStatus('mandatory') wfAotKeepaliveRto = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 600)).clone(4)).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotKeepaliveRto.setStatus('mandatory') wfAotKeepaliveMaxRetry = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 99)).clone(5)).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotKeepaliveMaxRetry.setStatus('mandatory') wfAotPeerTable = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3), ) if mibBuilder.loadTexts: wfAotPeerTable.setStatus('mandatory') wfAotPeerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1), ).setIndexNames((0, "Wellfleet-AOT-MIB", "wfAotPeerSlotNumber"), (0, "Wellfleet-AOT-MIB", "wfAotPeerCctNumber"), (0, "Wellfleet-AOT-MIB", "wfAotPeerRemoteIpAddr"), (0, "Wellfleet-AOT-MIB", "wfAotPeerLocalTcpListenPort"), (0, "Wellfleet-AOT-MIB", "wfAotPeerRemoteTcpListenPort"), (0, "Wellfleet-AOT-MIB", "wfAotConnOriginator")) if mibBuilder.loadTexts: wfAotPeerEntry.setStatus('mandatory') wfAotPeerEntryDelete = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotPeerEntryDelete.setStatus('mandatory') wfAotPeerEntryDisable = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfAotPeerEntryDisable.setStatus('mandatory') wfAotPeerSlotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerSlotNumber.setStatus('mandatory') wfAotPeerCctNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerCctNumber.setStatus('mandatory') wfAotPeerRemoteIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 5), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerRemoteIpAddr.setStatus('mandatory') wfAotConnOriginator = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("self", 1), ("partner", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotConnOriginator.setStatus('mandatory') wfAotPeerLocalTcpListenPort = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1000, 9999))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerLocalTcpListenPort.setStatus('mandatory') wfAotPeerRemoteTcpListenPort = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1000, 9999))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerRemoteTcpListenPort.setStatus('mandatory') wfAotPeerLocalTcpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1000, 9999))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerLocalTcpPort.setStatus('mandatory') wfAotPeerRemoteTcpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1000, 9999))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfAotPeerRemoteTcpPort.setStatus('mandatory') mibBuilder.exportSymbols("Wellfleet-AOT-MIB", wfAotPeerRemoteIpAddr=wfAotPeerRemoteIpAddr, wfAotInterfaceState=wfAotInterfaceState, wfAotInterfaceAttachedTo=wfAotInterfaceAttachedTo, wfAotPeerTable=wfAotPeerTable, wfAotInterfaceCctNumber=wfAotInterfaceCctNumber, wfAotState=wfAotState, wfAotPeerEntryDisable=wfAotPeerEntryDisable, wfAotPeerLocalTcpListenPort=wfAotPeerLocalTcpListenPort, wfAotPeerLocalTcpPort=wfAotPeerLocalTcpPort, wfAotPeerEntryDelete=wfAotPeerEntryDelete, wfAotDelete=wfAotDelete, wfAotDisable=wfAotDisable, wfAotInterfaceType=wfAotInterfaceType, wfAotInterfaceEntry=wfAotInterfaceEntry, wfAotKeepaliveInterval=wfAotKeepaliveInterval, wfAotPeerSlotNumber=wfAotPeerSlotNumber, wfAotPeerCctNumber=wfAotPeerCctNumber, wfAotInterfaceDisable=wfAotInterfaceDisable, wfAotInterfaceSlotNumber=wfAotInterfaceSlotNumber, wfAotInterfaceTable=wfAotInterfaceTable, wfAotKeepaliveMaxRetry=wfAotKeepaliveMaxRetry, wfAotInterfaceDelete=wfAotInterfaceDelete, wfAotPeerEntry=wfAotPeerEntry, wfAotConnOriginator=wfAotConnOriginator, wfAotPeerRemoteTcpListenPort=wfAotPeerRemoteTcpListenPort, wfAotPeerRemoteTcpPort=wfAotPeerRemoteTcpPort, wfAotInterfacePktCnt=wfAotInterfacePktCnt, wfAot=wfAot, wfAotKeepaliveRto=wfAotKeepaliveRto)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, constraints_union, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (notification_type, bits, integer32, module_identity, object_identity, counter32, time_ticks, gauge32, counter64, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, unsigned32, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'Bits', 'Integer32', 'ModuleIdentity', 'ObjectIdentity', 'Counter32', 'TimeTicks', 'Gauge32', 'Counter64', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Unsigned32', 'MibIdentifier') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') (wf_async_over_tcp_group,) = mibBuilder.importSymbols('Wellfleet-COMMON-MIB', 'wfAsyncOverTcpGroup') wf_aot = mib_identifier((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1)) wf_aot_delete = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('created', 1), ('deleted', 2))).clone('created')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotDelete.setStatus('mandatory') wf_aot_disable = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('enabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotDisable.setStatus('mandatory') wf_aot_state = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('up', 1), ('down', 2), ('init', 3), ('notpresent', 4))).clone('down')).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotState.setStatus('mandatory') wf_aot_interface_table = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2)) if mibBuilder.loadTexts: wfAotInterfaceTable.setStatus('mandatory') wf_aot_interface_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1)).setIndexNames((0, 'Wellfleet-AOT-MIB', 'wfAotInterfaceSlotNumber'), (0, 'Wellfleet-AOT-MIB', 'wfAotInterfaceCctNumber')) if mibBuilder.loadTexts: wfAotInterfaceEntry.setStatus('mandatory') wf_aot_interface_delete = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('created', 1), ('deleted', 2))).clone('created')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotInterfaceDelete.setStatus('mandatory') wf_aot_interface_disable = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('enabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotInterfaceDisable.setStatus('mandatory') wf_aot_interface_cct_number = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotInterfaceCctNumber.setStatus('mandatory') wf_aot_interface_slot_number = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotInterfaceSlotNumber.setStatus('mandatory') wf_aot_interface_state = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('up', 1), ('down', 2), ('init', 3))).clone('down')).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotInterfaceState.setStatus('mandatory') wf_aot_interface_type = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('singledrop', 1), ('multidrop', 2))).clone('singledrop')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotInterfaceType.setStatus('mandatory') wf_aot_interface_attached_to = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('primary', 1), ('secondary', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotInterfaceAttachedTo.setStatus('mandatory') wf_aot_interface_pkt_cnt = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 8), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotInterfacePktCnt.setStatus('mandatory') wf_aot_keepalive_interval = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(0, 86400)).clone(120)).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotKeepaliveInterval.setStatus('mandatory') wf_aot_keepalive_rto = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(0, 600)).clone(4)).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotKeepaliveRto.setStatus('mandatory') wf_aot_keepalive_max_retry = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 2, 1, 11), integer32().subtype(subtypeSpec=value_range_constraint(0, 99)).clone(5)).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotKeepaliveMaxRetry.setStatus('mandatory') wf_aot_peer_table = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3)) if mibBuilder.loadTexts: wfAotPeerTable.setStatus('mandatory') wf_aot_peer_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1)).setIndexNames((0, 'Wellfleet-AOT-MIB', 'wfAotPeerSlotNumber'), (0, 'Wellfleet-AOT-MIB', 'wfAotPeerCctNumber'), (0, 'Wellfleet-AOT-MIB', 'wfAotPeerRemoteIpAddr'), (0, 'Wellfleet-AOT-MIB', 'wfAotPeerLocalTcpListenPort'), (0, 'Wellfleet-AOT-MIB', 'wfAotPeerRemoteTcpListenPort'), (0, 'Wellfleet-AOT-MIB', 'wfAotConnOriginator')) if mibBuilder.loadTexts: wfAotPeerEntry.setStatus('mandatory') wf_aot_peer_entry_delete = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('created', 1), ('deleted', 2))).clone('created')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotPeerEntryDelete.setStatus('mandatory') wf_aot_peer_entry_disable = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('enabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfAotPeerEntryDisable.setStatus('mandatory') wf_aot_peer_slot_number = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotPeerSlotNumber.setStatus('mandatory') wf_aot_peer_cct_number = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotPeerCctNumber.setStatus('mandatory') wf_aot_peer_remote_ip_addr = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 5), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotPeerRemoteIpAddr.setStatus('mandatory') wf_aot_conn_originator = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('self', 1), ('partner', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotConnOriginator.setStatus('mandatory') wf_aot_peer_local_tcp_listen_port = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(1000, 9999))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotPeerLocalTcpListenPort.setStatus('mandatory') wf_aot_peer_remote_tcp_listen_port = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(1000, 9999))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotPeerRemoteTcpListenPort.setStatus('mandatory') wf_aot_peer_local_tcp_port = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(1000, 9999))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotPeerLocalTcpPort.setStatus('mandatory') wf_aot_peer_remote_tcp_port = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 5, 21, 3, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(1000, 9999))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfAotPeerRemoteTcpPort.setStatus('mandatory') mibBuilder.exportSymbols('Wellfleet-AOT-MIB', wfAotPeerRemoteIpAddr=wfAotPeerRemoteIpAddr, wfAotInterfaceState=wfAotInterfaceState, wfAotInterfaceAttachedTo=wfAotInterfaceAttachedTo, wfAotPeerTable=wfAotPeerTable, wfAotInterfaceCctNumber=wfAotInterfaceCctNumber, wfAotState=wfAotState, wfAotPeerEntryDisable=wfAotPeerEntryDisable, wfAotPeerLocalTcpListenPort=wfAotPeerLocalTcpListenPort, wfAotPeerLocalTcpPort=wfAotPeerLocalTcpPort, wfAotPeerEntryDelete=wfAotPeerEntryDelete, wfAotDelete=wfAotDelete, wfAotDisable=wfAotDisable, wfAotInterfaceType=wfAotInterfaceType, wfAotInterfaceEntry=wfAotInterfaceEntry, wfAotKeepaliveInterval=wfAotKeepaliveInterval, wfAotPeerSlotNumber=wfAotPeerSlotNumber, wfAotPeerCctNumber=wfAotPeerCctNumber, wfAotInterfaceDisable=wfAotInterfaceDisable, wfAotInterfaceSlotNumber=wfAotInterfaceSlotNumber, wfAotInterfaceTable=wfAotInterfaceTable, wfAotKeepaliveMaxRetry=wfAotKeepaliveMaxRetry, wfAotInterfaceDelete=wfAotInterfaceDelete, wfAotPeerEntry=wfAotPeerEntry, wfAotConnOriginator=wfAotConnOriginator, wfAotPeerRemoteTcpListenPort=wfAotPeerRemoteTcpListenPort, wfAotPeerRemoteTcpPort=wfAotPeerRemoteTcpPort, wfAotInterfacePktCnt=wfAotInterfacePktCnt, wfAot=wfAot, wfAotKeepaliveRto=wfAotKeepaliveRto)
# absoluteimports/__init__.py print("inside absoluteimports/__init__.py")
print('inside absoluteimports/__init__.py')
''' 5 - Remapping categories To better understand survey respondents from airlines, you want to find out if there is a relationship between certain responses and the day of the week and wait time at the gate. The airlines DataFrame contains the day and wait_min columns, which are categorical and numerical respectively. The day column contains the exact day a flight took place, and wait_min contains the amount of minutes it took travelers to wait at the gate. To make your analysis easier, you want to create two new categorical variables: - wait_type: 'short' for 0-60 min, 'medium' for 60-180 and long for 180+ - day_week: 'weekday' if day is in the weekday, 'weekend' if day is in the weekend. The pandas and numpy packages have been imported as pd and np. Let's create some new categorical data! Instructions - Create the ranges and labels for the wait_type column mentioned in the description above. - Create the wait_type column by from wait_min by using pd.cut(), while inputting label_ranges and label_names in the correct arguments. - Create the mapping dictionary mapping weekdays to 'weekday' and weekend days to 'weekend'. - Create the day_week column by using .replace(). ''' # Create ranges for categories label_ranges = [0, 60, 180, np.inf] label_names = ['short', 'medium', 'long'] # Create wait_type column airlines['wait_type'] = pd.cut(airlines['wait_min'], bins=label_ranges, labels=label_names) # Create mappings and replace mappings = {'Monday': 'weekday', 'Tuesday': 'weekday', 'Wednesday': 'weekday', 'Thursday': 'weekday', 'Friday': 'weekday', 'Saturday': 'weekend', 'Sunday': 'weekend'} airlines['day_week'] = airlines['day'].replace(mappings) ''' Note: ---------------------------------------------------------------------- we just created two new categorical variables, that when combined with other columns, could produce really interesting analysis. Don't forget, we can always use an assert statement to check our changes passed. ---------------------------------------------------------------------- '''
""" 5 - Remapping categories To better understand survey respondents from airlines, you want to find out if there is a relationship between certain responses and the day of the week and wait time at the gate. The airlines DataFrame contains the day and wait_min columns, which are categorical and numerical respectively. The day column contains the exact day a flight took place, and wait_min contains the amount of minutes it took travelers to wait at the gate. To make your analysis easier, you want to create two new categorical variables: - wait_type: 'short' for 0-60 min, 'medium' for 60-180 and long for 180+ - day_week: 'weekday' if day is in the weekday, 'weekend' if day is in the weekend. The pandas and numpy packages have been imported as pd and np. Let's create some new categorical data! Instructions - Create the ranges and labels for the wait_type column mentioned in the description above. - Create the wait_type column by from wait_min by using pd.cut(), while inputting label_ranges and label_names in the correct arguments. - Create the mapping dictionary mapping weekdays to 'weekday' and weekend days to 'weekend'. - Create the day_week column by using .replace(). """ label_ranges = [0, 60, 180, np.inf] label_names = ['short', 'medium', 'long'] airlines['wait_type'] = pd.cut(airlines['wait_min'], bins=label_ranges, labels=label_names) mappings = {'Monday': 'weekday', 'Tuesday': 'weekday', 'Wednesday': 'weekday', 'Thursday': 'weekday', 'Friday': 'weekday', 'Saturday': 'weekend', 'Sunday': 'weekend'} airlines['day_week'] = airlines['day'].replace(mappings) "\nNote:\n----------------------------------------------------------------------\nwe just created two new categorical variables, that when combined with \nother columns, could produce really interesting analysis. Don't forget, \nwe can always use an assert statement to check our changes passed.\n----------------------------------------------------------------------\n"
def read_file(): file_input = open("data/file_input_data.txt", 'r') file_data = file_input.readlines() file_input.close() return file_data if __name__ == "__main__": data = read_file() print(type(data)) print(data) for line in data: print(line)
def read_file(): file_input = open('data/file_input_data.txt', 'r') file_data = file_input.readlines() file_input.close() return file_data if __name__ == '__main__': data = read_file() print(type(data)) print(data) for line in data: print(line)
def is_armstrong_number(number): digits = [int(i) for i in str(number)] d_len = len(digits) d_sum = 0 for digit in digits: d_sum += digit ** d_len return d_sum == number
def is_armstrong_number(number): digits = [int(i) for i in str(number)] d_len = len(digits) d_sum = 0 for digit in digits: d_sum += digit ** d_len return d_sum == number
# Preprocessing config SAMPLING_RATE = 22050 FFT_WINDOW_SIZE = 1024 HOP_LENGTH = 512 N_MELS = 80 F_MIN = 27.5 F_MAX = 8000 AUDIO_MAX_LENGTH = 90 # in seconds # Data augmentation config MAX_SHIFTING_PITCH = 0.3 MAX_STRETCHING = 0.3 MAX_LOUDNESS_DB = 10 BLOCK_MIXING_MIN = 0.2 BLOCK_MIXING_MAX = 0.5 # Model config LOSS = "binary_crossentropy" METRICS = ["binary_accuracy", "categorical_accuracy"] CLASSES = 2 # For audio augmentation - deprecated STRETCHING_MIN = 0.75 STRETCHING_MAX = 1.25 SHIFTING_MIN = -3.5 SHIFTING_MAX = 3.5
sampling_rate = 22050 fft_window_size = 1024 hop_length = 512 n_mels = 80 f_min = 27.5 f_max = 8000 audio_max_length = 90 max_shifting_pitch = 0.3 max_stretching = 0.3 max_loudness_db = 10 block_mixing_min = 0.2 block_mixing_max = 0.5 loss = 'binary_crossentropy' metrics = ['binary_accuracy', 'categorical_accuracy'] classes = 2 stretching_min = 0.75 stretching_max = 1.25 shifting_min = -3.5 shifting_max = 3.5
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def repo(): http_archive( name = "fmt", strip_prefix = "fmt-7.1.3", urls = ["https://github.com/fmtlib/fmt/releases/download/7.1.3/fmt-7.1.3.zip"], sha256 = "5d98c504d0205f912e22449ecdea776b78ce0bb096927334f80781e720084c9f", build_file = "@//third_party/fmt:fmt.BUILD", )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def repo(): http_archive(name='fmt', strip_prefix='fmt-7.1.3', urls=['https://github.com/fmtlib/fmt/releases/download/7.1.3/fmt-7.1.3.zip'], sha256='5d98c504d0205f912e22449ecdea776b78ce0bb096927334f80781e720084c9f', build_file='@//third_party/fmt:fmt.BUILD')
"""Constants and variables common to the whole program @var VISUALIZE: whether to generate video @var PRECONDITIONER_CLASS: class or function that returns preconditioner object (1-parameter callable object) for CG, see L{SGSPreconditioner} for example @var PRECONDITIONER: preconditioner object (1-parameter callable object) that returns I{z} for a given I{r} @var SGS_ITERATIONS: number of Symmetric Gauss-Seidel iterations @var OPTIMIZE_SGS: whether to use Fortran code for Symmetric Gauss-Seidel @var OPTIMIZE_AX: whether to use Fortran code for matrix-vector multiplication @var STIFFNESS_FUNCTION: coefficient function that returns stiffness for any point (x,y) """ VISUALIZE = True PRECONDITIONER_CLASS = None PRECONDITIONER = None SGS_ITERATIONS = None OPTIMIZE_SGS = True OPTIMIZE_AX = True STIFFNESS_FUNCTION = None
"""Constants and variables common to the whole program @var VISUALIZE: whether to generate video @var PRECONDITIONER_CLASS: class or function that returns preconditioner object (1-parameter callable object) for CG, see L{SGSPreconditioner} for example @var PRECONDITIONER: preconditioner object (1-parameter callable object) that returns I{z} for a given I{r} @var SGS_ITERATIONS: number of Symmetric Gauss-Seidel iterations @var OPTIMIZE_SGS: whether to use Fortran code for Symmetric Gauss-Seidel @var OPTIMIZE_AX: whether to use Fortran code for matrix-vector multiplication @var STIFFNESS_FUNCTION: coefficient function that returns stiffness for any point (x,y) """ visualize = True preconditioner_class = None preconditioner = None sgs_iterations = None optimize_sgs = True optimize_ax = True stiffness_function = None
""" In a given integer array nums, there is always exactly one largest element. Find whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwise return -1. Your runtime beats 80.31 % of python submissions. """ class Solution(object): def dominantIndex(self, nums): """ :type nums: List[int] :rtype: int """ """ Method 1 Using Python built-in functions Your runtime beats 80.31 % of python submissions. """ if len(nums) > 1: arr = sorted(nums, reverse=True) if arr[0] >= 2*arr[1]: return nums.index(arr[0]) else: return -1 return 0 """ Method 2 """ max_one = max_two = float("-inf") max_index = 0 if len(nums) > 1: for elem in range(0, len(nums)): if nums[elem] > max_one: max_two = max_one max_one = nums[elem] max_index = elem if max_one > nums[elem] > max_two: max_two = nums[elem] if max_one >= 2 * max_two: return max_index else: return -1 else: return 0
""" In a given integer array nums, there is always exactly one largest element. Find whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwise return -1. Your runtime beats 80.31 % of python submissions. """ class Solution(object): def dominant_index(self, nums): """ :type nums: List[int] :rtype: int """ '\n Method 1\n Using Python built-in functions\n Your runtime beats 80.31 % of python submissions.\n ' if len(nums) > 1: arr = sorted(nums, reverse=True) if arr[0] >= 2 * arr[1]: return nums.index(arr[0]) else: return -1 return 0 '\n Method 2\n ' max_one = max_two = float('-inf') max_index = 0 if len(nums) > 1: for elem in range(0, len(nums)): if nums[elem] > max_one: max_two = max_one max_one = nums[elem] max_index = elem if max_one > nums[elem] > max_two: max_two = nums[elem] if max_one >= 2 * max_two: return max_index else: return -1 else: return 0
# 1 - push # 2 - pop # 3 - print max element # 4 - print max element # last - print all elements n = int(input()) query = [] for _ in range(n): num = input().split() if num[0] == "1": query.append(int(num[1])) elif num[0] == "2": if query: query.pop() continue elif num[0] == "3": if query: # !!!!!!!!!!!!!!!!!!!!!!!!! print(max(query)) elif num[0] == "4": if query: # !!!!!!!!!!!!!!!!!!!!!!!!! print(min(query)) print(', '.join([str(x) for x in reversed(query)]))
n = int(input()) query = [] for _ in range(n): num = input().split() if num[0] == '1': query.append(int(num[1])) elif num[0] == '2': if query: query.pop() continue elif num[0] == '3': if query: print(max(query)) elif num[0] == '4': if query: print(min(query)) print(', '.join([str(x) for x in reversed(query)]))
# Constants for the image IMAGE_URL = str(input("Enter a valid image URL: ")) IMAGE_WIDTH = 280 IMAGE_HEIGHT = 200 blueUpFactor = int(input("How much more blue do you want this image | Enter a value between 1 and 255")) maxPixelValue = 255 image = Image(IMAGE_URL) image.set_position(70, 70) image.set_size(IMAGE_WIDTH, IMAGE_HEIGHT) add(image) # Filter to brighten an image def blueFilter(pixel): blue = blueColour(pixel[2]) return blue def blueColour(colorValue): return min(colorValue + blueUpFactor, maxPixelValue) def changePicture(): for x in range(image.get_width()): for y in range(image.get_height()): pixel = image.get_pixel(x,y) newColor = blueFilter(pixel) image.set_blue(x, y, newColor) # Give the image time to load print("Creating Blue Skies....") print("Might take a minute....") timer.set_timeout(changePicture, 1000)
image_url = str(input('Enter a valid image URL: ')) image_width = 280 image_height = 200 blue_up_factor = int(input('How much more blue do you want this image | Enter a value between 1 and 255')) max_pixel_value = 255 image = image(IMAGE_URL) image.set_position(70, 70) image.set_size(IMAGE_WIDTH, IMAGE_HEIGHT) add(image) def blue_filter(pixel): blue = blue_colour(pixel[2]) return blue def blue_colour(colorValue): return min(colorValue + blueUpFactor, maxPixelValue) def change_picture(): for x in range(image.get_width()): for y in range(image.get_height()): pixel = image.get_pixel(x, y) new_color = blue_filter(pixel) image.set_blue(x, y, newColor) print('Creating Blue Skies....') print('Might take a minute....') timer.set_timeout(changePicture, 1000)
class Solution: def reverseOnlyLetters(self, S: str) -> str: alpha = set([chr(i) for i in list(range(ord('a'), ord('z')+1)) + list(range(ord('A'), ord('Z')+1))]) words, res = [], list(S) for char in res: if char in alpha: words.append(char) for i in range(len(res)): if res[i] in alpha: res[i] = words.pop() return ''.join(res)
class Solution: def reverse_only_letters(self, S: str) -> str: alpha = set([chr(i) for i in list(range(ord('a'), ord('z') + 1)) + list(range(ord('A'), ord('Z') + 1))]) (words, res) = ([], list(S)) for char in res: if char in alpha: words.append(char) for i in range(len(res)): if res[i] in alpha: res[i] = words.pop() return ''.join(res)
# SPDX-FileCopyrightText: 2020 Splunk Inc. # # SPDX-License-Identifier: Apache-2.0 def normalize_to_unicode(value): """ string convert to unicode """ if hasattr(value, "decode") and not isinstance(value, str): return value.decode("utf-8") return value def normalize_to_str(value): """ unicode convert to string """ if hasattr(value, "encode") and isinstance(value, str): return value.encode("utf-8") return value
def normalize_to_unicode(value): """ string convert to unicode """ if hasattr(value, 'decode') and (not isinstance(value, str)): return value.decode('utf-8') return value def normalize_to_str(value): """ unicode convert to string """ if hasattr(value, 'encode') and isinstance(value, str): return value.encode('utf-8') return value
number = int(input()) while number < 1 or number > 100: print('Invalid number') number = int(input()) print(f'The number is: {number}')
number = int(input()) while number < 1 or number > 100: print('Invalid number') number = int(input()) print(f'The number is: {number}')
class Configuration(object): config={} def __str__(self): return str(Configuration.config) @staticmethod def defaults(): Configuration.config['api_base_link'] = 'https://api.twitch.tv/kraken/' @staticmethod def load(file=None): if file: with open (file, 'r', encoding='utf-8') as fh: Configuration.config['api_base_link'] = 'https://api.twitch.tv/kraken/' else: Configuration.defaults()
class Configuration(object): config = {} def __str__(self): return str(Configuration.config) @staticmethod def defaults(): Configuration.config['api_base_link'] = 'https://api.twitch.tv/kraken/' @staticmethod def load(file=None): if file: with open(file, 'r', encoding='utf-8') as fh: Configuration.config['api_base_link'] = 'https://api.twitch.tv/kraken/' else: Configuration.defaults()
# By Taiwo Kareem <taiwo.kareem36@gmail.com> # Github <https://github.com/tushortz> # Last updated (08-February-2016) # Card class class Card: # Initialize necessary field variables def __init__(self, *code): # Accept two character arguments if len(code) == 2: rank = code[0] suit = code[1] # Can also accept one string argument elif len(code) == 1: if len(code[0]) == 2: rank = code[0][0] suit = code[0][1] else: raise ValueError("card codes must be two characters") else: raise ValueError("card codes must be two characters") self.rank = rank self.suit = suit # All available ranks self.RANKS = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" ] # All available suits self.SUITS = ["C", "D", "H", "S"] # Error checks if not self.rank in self.RANKS: raise ValueError("Invalid rank") if not self.suit in self.SUITS: raise ValueError("Invalid suit") # String representation of cards def __str__(self): return "%s%s" % (self.rank, self.suit) # Class Methods def getRanks(self): return self.RANKS def getSuits(self): return self.SUITS def getRank(self): return self.rank def getSuit(self): return self.suit def hashCode(self): prime = 31 result = 1 result = str(prime * result) + self.rank result = str(prime * result) + self.suit return result def equals(self, thing): same = False if (thing == self): same = True elif (thing != None and isinstance(thing, Card)): if thing.rank == self.rank and thing.suit == self.suit: same = True else: same = False return same def compareTo(self, other): mySuit = self.SUITS.index(self.suit) otherSuit = self.SUITS.index(other.suit) difference = mySuit - otherSuit if difference == 0: myRank = self.RANKS.index(self.rank) otherRank = self.RANKS.index(other.rank) difference = myRank - otherRank return difference
class Card: def __init__(self, *code): if len(code) == 2: rank = code[0] suit = code[1] elif len(code) == 1: if len(code[0]) == 2: rank = code[0][0] suit = code[0][1] else: raise value_error('card codes must be two characters') else: raise value_error('card codes must be two characters') self.rank = rank self.suit = suit self.RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] self.SUITS = ['C', 'D', 'H', 'S'] if not self.rank in self.RANKS: raise value_error('Invalid rank') if not self.suit in self.SUITS: raise value_error('Invalid suit') def __str__(self): return '%s%s' % (self.rank, self.suit) def get_ranks(self): return self.RANKS def get_suits(self): return self.SUITS def get_rank(self): return self.rank def get_suit(self): return self.suit def hash_code(self): prime = 31 result = 1 result = str(prime * result) + self.rank result = str(prime * result) + self.suit return result def equals(self, thing): same = False if thing == self: same = True elif thing != None and isinstance(thing, Card): if thing.rank == self.rank and thing.suit == self.suit: same = True else: same = False return same def compare_to(self, other): my_suit = self.SUITS.index(self.suit) other_suit = self.SUITS.index(other.suit) difference = mySuit - otherSuit if difference == 0: my_rank = self.RANKS.index(self.rank) other_rank = self.RANKS.index(other.rank) difference = myRank - otherRank return difference
""" ______ __ ____ ____/ / __/ ____ ____ ____ ___ _________ _/ /_____ _____ / __ \/ __ / /_ / __ `/ _ \/ __ \/ _ \/ ___/ __ `/ __/ __ \/ ___/ / /_/ / /_/ / __/ / /_/ / __/ / / / __/ / / /_/ / /_/ /_/ / / / .___/\__,_/_/_____\__, /\___/_/ /_/\___/_/ \__,_/\__/\____/_/ /_/ /_____/____/ """ __title__ = 'PDF Generator' __version__ = '0.1.3' __author__ = 'Charles TISSIER' __license__ = 'MIT' __copyright__ = 'Copyright 2017 Charles TISSIER' # Version synonym VERSION = __version__ default_app_config = 'pdf_generator.apps.PdfGeneratorConfig'
""" ______ __ ____ ____/ / __/ ____ ____ ____ ___ _________ _/ /_____ _____ / __ \\/ __ / /_ / __ `/ _ \\/ __ \\/ _ \\/ ___/ __ `/ __/ __ \\/ ___/ / /_/ / /_/ / __/ / /_/ / __/ / / / __/ / / /_/ / /_/ /_/ / / / .___/\\__,_/_/_____\\__, /\\___/_/ /_/\\___/_/ \\__,_/\\__/\\____/_/ /_/ /_____/____/ """ __title__ = 'PDF Generator' __version__ = '0.1.3' __author__ = 'Charles TISSIER' __license__ = 'MIT' __copyright__ = 'Copyright 2017 Charles TISSIER' version = __version__ default_app_config = 'pdf_generator.apps.PdfGeneratorConfig'
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getMinimumDifference(self, root: TreeNode) -> int: def dfs(root): if not root: return dfs(root.left) nums.append(root.val) dfs(root.right) nums = [] dfs(root) res = float('inf') for i in range(1, len(nums)): res = min(res, nums[i] - nums[i - 1]) return res
class Solution: def get_minimum_difference(self, root: TreeNode) -> int: def dfs(root): if not root: return dfs(root.left) nums.append(root.val) dfs(root.right) nums = [] dfs(root) res = float('inf') for i in range(1, len(nums)): res = min(res, nums[i] - nums[i - 1]) return res
# -*- coding: utf-8 -*- __author__ = 'Andile Jaden Mbele' __email__ = 'andilembele020@gmail.com' __github__ = 'https://github.com/xeroxzen/genuine-fake' __package__ = 'genuine-fake' __version__ = '1.2.20'
__author__ = 'Andile Jaden Mbele' __email__ = 'andilembele020@gmail.com' __github__ = 'https://github.com/xeroxzen/genuine-fake' __package__ = 'genuine-fake' __version__ = '1.2.20'
def b2d(number): decimal_number = 0 i = 0 while number > 0: decimal_number += number % 10*(2**i) number = int(number / 10) i += 1 return decimal_number def d2b(number): binary_number = 0 i = 0 while number > 0: binary_number += number % 2*(10**i) number = int(number / 2) i += 1 return binary_number if __name__ == '__main__': choice = '' while not (choice == '1' or choice == '2'): choice = input("1 - decimal to binary\n2 - binary to decimal\nEnter your choice : ") if choice == '1': decimal_number = int(input('Enter a decimal number: ')) print(f'your binary conversion is {d2b(decimal_number)}') elif choice == '2': binary_number = int(input('Enter a binary number: ')) print(f'your deciml conversion is {b2d(binary_number)}') else: print('Enter a valid choice.')
def b2d(number): decimal_number = 0 i = 0 while number > 0: decimal_number += number % 10 * 2 ** i number = int(number / 10) i += 1 return decimal_number def d2b(number): binary_number = 0 i = 0 while number > 0: binary_number += number % 2 * 10 ** i number = int(number / 2) i += 1 return binary_number if __name__ == '__main__': choice = '' while not (choice == '1' or choice == '2'): choice = input('1 - decimal to binary\n2 - binary to decimal\nEnter your choice : ') if choice == '1': decimal_number = int(input('Enter a decimal number: ')) print(f'your binary conversion is {d2b(decimal_number)}') elif choice == '2': binary_number = int(input('Enter a binary number: ')) print(f'your deciml conversion is {b2d(binary_number)}') else: print('Enter a valid choice.')
''' 06 - Treating duplicates In the last exercise, you were able to verify that the new update feeding into ride_sharing contains a bug generating both complete and incomplete duplicated rows for some values of the ride_id column, with occasional discrepant values for the user_birth_year and duration columns. In this exercise, you will be treating those duplicated rows by first dropping complete duplicates, and then merging the incomplete duplicate rows into one while keeping the average duration, and the minimum user_birth_year for each set of incomplete duplicate rows. Instructions - Drop complete duplicates in ride_sharing and store the results in ride_dup. - Create the statistics dictionary which holds minimum aggregation for user_birth_year and mean aggregation for duration. - Drop incomplete duplicates by grouping by ride_id and applying the aggregation in statistics. - Find duplicates again and run the assert statement to verify de-duplication. ''' # Drop complete duplicates from ride_sharing ride_dup = ride_sharing.drop_duplicates() # Create statistics dictionary for aggregation function statistics = {'user_birth_year': 'min', 'duration': 'mean'} # Group by ride_id and compute new statistics ride_unique = ride_dup.groupby('ride_id').agg(statistics).reset_index() # Find duplicated values again duplicates = ride_unique.duplicated(subset='ride_id', keep=False) duplicated_rides = ride_unique[duplicates == True] # Assert duplicates are processed assert duplicated_rides.shape[0] == 0
""" 06 - Treating duplicates In the last exercise, you were able to verify that the new update feeding into ride_sharing contains a bug generating both complete and incomplete duplicated rows for some values of the ride_id column, with occasional discrepant values for the user_birth_year and duration columns. In this exercise, you will be treating those duplicated rows by first dropping complete duplicates, and then merging the incomplete duplicate rows into one while keeping the average duration, and the minimum user_birth_year for each set of incomplete duplicate rows. Instructions - Drop complete duplicates in ride_sharing and store the results in ride_dup. - Create the statistics dictionary which holds minimum aggregation for user_birth_year and mean aggregation for duration. - Drop incomplete duplicates by grouping by ride_id and applying the aggregation in statistics. - Find duplicates again and run the assert statement to verify de-duplication. """ ride_dup = ride_sharing.drop_duplicates() statistics = {'user_birth_year': 'min', 'duration': 'mean'} ride_unique = ride_dup.groupby('ride_id').agg(statistics).reset_index() duplicates = ride_unique.duplicated(subset='ride_id', keep=False) duplicated_rides = ride_unique[duplicates == True] assert duplicated_rides.shape[0] == 0
{ "name": """Website login background""", "summary": """Random background image to your taste at the website login page""", "category": "Website", "images": ["images/5.png"], "version": "14.0.1.0.3", "author": "IT-Projects LLC", "support": "help@itpp.dev", "website": "https://twitter.com/OdooFree", "license": "Other OSI approved licence", # MIT "depends": ["web_login_background", "website"], "external_dependencies": {"python": [], "bin": []}, "data": ["templates.xml"], "demo": ["demo/demo.xml"], "installable": True, "auto_install": True, }
{'name': 'Website login background', 'summary': 'Random background image to your taste at the website login page', 'category': 'Website', 'images': ['images/5.png'], 'version': '14.0.1.0.3', 'author': 'IT-Projects LLC', 'support': 'help@itpp.dev', 'website': 'https://twitter.com/OdooFree', 'license': 'Other OSI approved licence', 'depends': ['web_login_background', 'website'], 'external_dependencies': {'python': [], 'bin': []}, 'data': ['templates.xml'], 'demo': ['demo/demo.xml'], 'installable': True, 'auto_install': True}
""" This file will host global variables of config strings for the sims. We will only be varying one or two parameters, but we will need to write several copies of the all the parameters we have to specify. I believe this is the easiest way to do that. """ # NOTE with the class python wrapper this one is not necessary. class_config = """ *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~* * CLASS input parameter file * *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~* > This example of input file does not include all CLASS possibilities, but only the most useful ones for running in the basic LambdaCDM framework. For all possibilities, look at the longer 'explanatory.ini' file. > You can use an even more concise version, in which only the arguments in which you are interested would appear. > Only lines containing an equal sign not preceded by a sharp sign "#" are considered by the code. Hence, do not write an equal sign within a comment, the whole line would be interpreted as relevant input. > Input files must have an extension ".ini". *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~* * UATU notes * *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~* > This has been copied from the lcdm.ini file in class. It will replace the values of Omega_c, A_s, and input/output > locations for use with Uatu mPk's. All others will be left as defaults. ---------------------------- ----> background parameters: ---------------------------- 1) Hubble parameter : either 'H0' in km/s/Mpc or 'h' (default: 'h' set to 0.704) #H0 = 72. h =0.7 2) photon density: either 'T_cmb' in K or 'Omega_g' or 'omega_g' (default: 'T_cmb' set to 2.726) T_cmb = 2.726 #Omega_g = 5.050601e-05 #omega_g = 2.47479449e-5 3) baryon density: either 'Omega_b' or 'omega_b' (default: 'omega_b' set to 0.02253) Omega_b = 0.022 #omega_b = 0.0266691 4) ultra-relativistic species / massless neutrino density: either 'N_eff' or 'Omega_ur' or 'omega_ur' (default: 'N_eff' set to 3.04) N_eff = 3.04 #Omega_ur = 3.4869665e-05 #omega_ur = 1.70861334e-5 5) density of cdm (cold dark matter): 'Omega_cdm' or 'omega_cdm' (default: 'omega_cdm' set to 0.1122) Omega_cdm = {ocdm:f} #omega_cdm = 0.110616 6) cosmological constant / fluid with constant w and sound speed (can be used to model simple dark energy models): enter one parameter out of 'Omega_Lambda' or 'Omega_fld', the other one is inferred by the code in such way that (sum_i Omega_i) equals (1 + Omega_k) (default: 'Omega_fld' set to 0 and 'Omega_Lambda' to (1+Omega_k-Omega_tot)) # Omega_Lambda = 0.7 Omega_fld = 0 7) equation of state parameter (p/rho equal to w0+wa(1-a0/a) ) and sound speed of the fluid (this is the sound speed defined in the frame comoving with the fluid, i.e. obeying to the most sensible physical definition) w0_fld = -1.0 #w0_fld = -0.9 wa_fld = 0. cs2_fld = 1 -------------------------------- ----> thermodynamics parameters: -------------------------------- 1) primordial Helium fraction 'YHe' (default: set to 0.25) YHe = 0.25 2) enter one of 'z_reio' or 'tau_reio' (default: 'z_reio' set to 10.3) z_reio = 10. #tau_reio = 0.084522 ---------------------------------------------------- ----> define which perturbations should be computed: ---------------------------------------------------- 1) list of output spectra requested ('tCl' for temperature Cls, 'pCl' for polarization CLs, 'lCl' for lensing potential Cls, , 'dCl' for matter density Cls, 'mPk' for total matter power spectrum P(k) infered from gravitational potential, 'mTk' for matter transfer functions for of each species). Can be attached or separated by arbitrary characters. Given this list, all non-zero auto-correlation and cross-correlation spectra will be automatically computed. Can be left blank if you do not want to evolve cosmological perturbations at all. (default: set to blanck, no perturbation calculation) #output = tCl,pCl,lCl #output = tCl,pCl,lCl,mPk output = mPk 2) relevant only if you ask for scalars, temperature or polarisation Cls, and 'lCl': if you want the spectrum of lensed Cls, enter a word containing the letter 'y' or 'Y' (default: no lensed Cls) lensing = no --------------------------------------------- ----> define primordial perturbation spectra: --------------------------------------------- 1) pivot scale in Mpc-1 (default: set to 0.002) k_pivot = 0.05 2) scalar adiabatic perturbations: curvature power spectrum value at pivot scale, tilt at the same scale, and tilt running (default: set 'A_s' to 2.42e-9, 'n_s' to 0.967, 'alpha_s' to 0) A_s = {A_s:f} n_s = 0.96 alpha_s = 0. ------------------------------------- ----> define format of final spectra: ------------------------------------- 1) maximum l 'l_max_scalars', 'l_max_tensors' in Cls for scalars/tensors (default: set 'l_max_scalars' to 2500, 'l_max_tensors' to 500) l_max_scalars = 3000 l_max_tensors = 500 2) maximum k in P(k), 'P_k_max_h/Mpc' in units of h/Mpc or 'P_k_max_1/Mpc' in units of 1/Mpc. If scalar Cls are also requested, a minimum value is automatically imposed (the same as in scalar Cls computation) (default: set to 0.1h/Mpc) P_k_max_h/Mpc = 10. #P_k_max_1/Mpc = 0.7 3) value(s) 'z_pk' of redshift(s) for P(k,z) output file(s); can be ordered arbitrarily, but must be separated by comas (default: set 'z_pk' to 0) z_pk = 20. #z_pk = 0., 1.2, 3.5 4) if you need Cls for the matter density autocorrelation or cross density-temperature correlation (option 'dCl'), enter here a description of the selection functions W(z) of each redshift bin; selection can be set to 'gaussian', then pass a list of N mean redshifts in growing order separated by comas, and finally 1 or N widths separated by comas (default: set to 'gaussian',1,0.1) selection=gaussian selection_mean = 1. selection_width = 0.5 5) file name root 'root' for all output files (default: set 'root' to 'output/') (if Cl requested, written to '<root>cl.dat'; if P(k) requested, written to '<root>pk.dat'; plus similar files for scalars, tensors, pairs of initial conditions, etc.; if file with input parameters requested, written to '<root>parameters.ini') root = {output_root} 6) do you want headers at the beginning of each output file (giving precisions on the output units/ format) ? If 'headers' set to something containing the letter 'y' or 'Y', headers written, otherwise not written (default: written) headers = no 7) in all output files, do you want columns to be normalized and ordered with the default CLASS definitions or with the CAMB definitions (often idential to the CMBFAST one) ? Set 'format' to either 'class', 'CLASS', 'camb' or 'CAMB' (default: 'class') format = camb 8) if 'bessel file' set to something containing the letters 'y' or 'Y', the code tries to read bessel functions in a file; if the file is absent or not adequate, bessel functions are computed and written in a file. The file name is set by defaut to 'bessels.dat' but can be changed together with precision parameters: just set 'bessel_file_name' to '<name>' either here or in the precision parameter file. (defaut: 'bessel file' set to 'no' and bessel functions are always recomputed) bessel file = no 9) Do you want to have all input/precision parameters which have been read written in file '<root>parameters.ini', and those not written in file '<root>unused_parameters' ? If 'write parameters' set to something containing the letter 'y' or 'Y', file written, otherwise not written (default: not written) write parameters = yeap ---------------------------------------------------- ----> amount of information sent to standard output: ---------------------------------------------------- Increase integer values to make each module more talkative (default: all set to 0) background_verbose = 1 thermodynamics_verbose = 0 perturbations_verbose = 1 bessels_verbose = 0 transfer_verbose = 0 primordial_verbose = 1 spectra_verbose = 0 nonlinear_verbose = 1 lensing_verbose = 0 output_verbose = 1 """ # TODO have to fix the baryon numbers, they're wrong!!! picola_config = """ % =============================== % % This is the run parameters file % % =============================== % % Simulation outputs % ================== OutputDir {outputdir} % Directory for output. FileBase {file_base} % Base-filename of output files (appropriate additions are appended on at runtime) OutputRedshiftFile {outputdir}/output_redshifts.dat % The file containing the redshifts that we want snapshots for NumFilesWrittenInParallel 4 % limits the number of files that are written in parallel when outputting. % Simulation Specifications % ========================= UseCOLA 1 % Whether or not to use the COLA method (1=true, 0=false). Buffer 1.3 % The amount of extra memory to reserve for particles moving between tasks during runtime. Nmesh 512 % This is the size of the FFT grid used to compute the displacement field and gravitational forces. Nsample 512 % This sets the total number of particles in the simulation, such that Ntot = Nsample^3. Box 512.0 % The Periodic box size of simulation. Init_Redshift 20.0 % The redshift to begin timestepping from (redshift = 9 works well for COLA) Seed {seed} % Seed for IC-generator SphereMode 0 % If "1" only modes with |k| < k_Nyquist are used to generate initial conditions (i.e. a sphere in k-space), % otherwise modes with |k_x|,|k_y|,|k_z| < k_Nyquist are used (i.e. a cube in k-space). WhichSpectrum 1 % "0" - Use transfer function, not power spectrum % "1" - Use a tabulated power spectrum in the file 'FileWithInputSpectrum' % otherwise, Eisenstein and Hu (1998) parametrization is used % Non-Gaussian case requires "0" and that we use the transfer function WhichTransfer 0 % "0" - Use power spectrum, not transfer function % "1" - Use a tabulated transfer function in the file 'FileWithInputTransfer' % otherwise, Eisenstein and Hu (1998) parameterization used % For Non-Gaussian models this is required (rather than the power spectrum) FileWithInputSpectrum {outputdir}/class_pk.dat % filename of tabulated input spectrum (if used) % expecting k and Pk FileWithInputTransfer /home/users/swmclau2/picola/l-picola/files/input_transfer.dat % filename of tabulated transfer function (if used) % expecting k and T (unnormalized) % Cosmological Parameters % ======================= Omega {ocdm:.2f} % Total matter density (CDM + Baryons at z=0). OmegaBaryon {ob:.2f} % Baryon density (at z=0). OmegaLambda {olambda:.2f} % Dark Energy density (at z=0) HubbleParam 0.7 % Hubble parameter, 'little h' (only used for power spectrum parameterization). Sigma8 {sigma8:.2f} % Power spectrum normalization (power spectrum may already be normalized correctly). PrimordialIndex 0.96 % Used to tilt the power spectrum for non-tabulated power spectra (if != 1.0 and nongaussian, generic flag required) % Timestepping Options % ==================== StepDist 0 % The timestep spacing (0 for linear in a, 1 for logarithmic in a) DeltaA 0 % The type of timestepping: "0" - Use modified COLA timestepping for Kick and Drift. Please choose a value for nLPT. % The type of timestepping: "1" - Use modified COLA timestepping for Kick and standard Quinn timestepping for Drift. Please choose a value for nLPT. % The type of timestepping: "2" - Use standard Quinn timestepping for Kick and Drift % The type of timestepping: "3" - Use non-integral timestepping for Kick and Drift nLPT -2.5 % The value of nLPT to use for modified COLA timestepping % Units % ===== UnitLength_in_cm 3.085678e24 % defines length unit of output (in cm/h) UnitMass_in_g 1.989e43 % defines mass unit of output (in g/h) UnitVelocity_in_cm_per_s 1e5 % defines velocity unit of output (in cm/sec) InputSpectrum_UnitLength_in_cm 3.085678e24 % defines length unit of tabulated input spectrum in cm/h. % Note: This can be chosen different from UnitLength_in_cm % ================================================== % % Optional extras (must comment out if not required) % % ================================================== % % Non-Gaussianity % =============== %Fnl -400 % The value of Fnl. %Fnl_Redshift 49.0 % The redshift to apply the nongaussian potential %FileWithInputKernel /files/input_kernel_ortog.txt % the input kernel for generic non-gaussianity (only needed for GENERIC_FNL) % Lightcone simulations % ===================== Origin_x 0.0 % The position of the lightcone origin in the x-axis Origin_y 0.0 % The position of the lightcone origin in the y-axis Origin_z 0.0 % The position of the lightcone origin in the z-axis Nrep_neg_x 0 % The maximum number of box replicates in the negative x-direction Nrep_pos_x 0 % The maximum number of box replicates in the positive x-direction Nrep_neg_y 0 % The maximum number of box replicates in the negative y-direction Nrep_pos_y 0 % The maximum number of box replicates in the positive y-direction Nrep_neg_z 0 % The maximum number of box replicates in the negative z-direction Nrep_pos_z 0 % The maximum number of box replicates in the positive z-direction """
""" This file will host global variables of config strings for the sims. We will only be varying one or two parameters, but we will need to write several copies of the all the parameters we have to specify. I believe this is the easiest way to do that. """ class_config = '\n*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\n* CLASS input parameter file *\n*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\n\n> This example of input file does not include all CLASS possibilities, but only the most useful ones for running in the basic LambdaCDM framework. For all possibilities, look at the longer \'explanatory.ini\' file.\n> You can use an even more concise version, in which only the arguments in which you are interested would appear.\n> Only lines containing an equal sign not preceded by a sharp sign "#" are considered by the code. Hence, do not write an equal sign within a comment, the whole line would be interpreted as relevant input.\n> Input files must have an extension ".ini".\n\n*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\n* UATU notes *\n*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\n\n> This has been copied from the lcdm.ini file in class. It will replace the values of Omega_c, A_s, and input/output\n> locations for use with Uatu mPk\'s. All others will be left as defaults. \n\n----------------------------\n----> background parameters:\n----------------------------\n\n1) Hubble parameter : either \'H0\' in km/s/Mpc or \'h\' (default: \'h\' set to 0.704)\n\n#H0 = 72.\nh =0.7\n\n2) photon density: either \'T_cmb\' in K or \'Omega_g\' or \'omega_g\' (default: \'T_cmb\' set to 2.726)\n\nT_cmb = 2.726\n#Omega_g = 5.050601e-05\n#omega_g = 2.47479449e-5\n\n3) baryon density: either \'Omega_b\' or \'omega_b\' (default: \'omega_b\' set to 0.02253)\n\nOmega_b = 0.022\n#omega_b = 0.0266691\n\n4) ultra-relativistic species / massless neutrino density: either \'N_eff\' or \'Omega_ur\' or \'omega_ur\' (default: \'N_eff\' set to 3.04)\n\nN_eff = 3.04\n#Omega_ur = 3.4869665e-05\n#omega_ur = 1.70861334e-5\n\n5) density of cdm (cold dark matter): \'Omega_cdm\' or \'omega_cdm\' (default: \'omega_cdm\' set to 0.1122)\n\nOmega_cdm = {ocdm:f}\n#omega_cdm = 0.110616\n\n6) cosmological constant / fluid with constant w and sound speed (can be used to model simple dark energy models): enter one parameter out of \'Omega_Lambda\' or \'Omega_fld\', the other one is inferred by the code in such way that (sum_i Omega_i) equals (1 + Omega_k) (default: \'Omega_fld\' set to 0 and \'Omega_Lambda\' to (1+Omega_k-Omega_tot))\n\n# Omega_Lambda = 0.7\nOmega_fld = 0\n\n7) equation of state parameter (p/rho equal to w0+wa(1-a0/a) ) and sound speed of the fluid (this is the sound speed defined in the frame comoving with the fluid, i.e. obeying to the most sensible physical definition)\n\nw0_fld = -1.0\n#w0_fld = -0.9\nwa_fld = 0.\ncs2_fld = 1\n\n--------------------------------\n----> thermodynamics parameters:\n--------------------------------\n\n1) primordial Helium fraction \'YHe\' (default: set to 0.25)\n\nYHe = 0.25\n\n2) enter one of \'z_reio\' or \'tau_reio\' (default: \'z_reio\' set to 10.3)\n\nz_reio = 10.\n#tau_reio = 0.084522\n\n----------------------------------------------------\n----> define which perturbations should be computed:\n----------------------------------------------------\n\n1) list of output spectra requested (\'tCl\' for temperature Cls, \'pCl\' for polarization CLs, \'lCl\' for lensing potential Cls, , \'dCl\' for matter density Cls, \'mPk\' for total matter power spectrum P(k) infered from gravitational potential, \'mTk\' for matter transfer functions for of each species). Can be attached or separated by arbitrary characters. Given this list, all non-zero auto-correlation and cross-correlation spectra will be automatically computed. Can be left blank if you do not want to evolve cosmological perturbations at all. (default: set to blanck, no perturbation calculation)\n\n#output = tCl,pCl,lCl\n#output = tCl,pCl,lCl,mPk\noutput = mPk\n\n2) relevant only if you ask for scalars, temperature or polarisation Cls, and \'lCl\': if you want the spectrum of lensed Cls, enter a word containing the letter \'y\' or \'Y\' (default: no lensed Cls)\n\nlensing = no\n\n---------------------------------------------\n----> define primordial perturbation spectra:\n---------------------------------------------\n\n1) pivot scale in Mpc-1 (default: set to 0.002)\n\nk_pivot = 0.05\n\n2) scalar adiabatic perturbations: curvature power spectrum value at pivot scale, tilt at the same scale, and tilt running (default: set \'A_s\' to 2.42e-9, \'n_s\' to 0.967, \'alpha_s\' to 0)\n\nA_s = {A_s:f}\nn_s = 0.96\nalpha_s = 0.\n\n-------------------------------------\n----> define format of final spectra:\n-------------------------------------\n\n1) maximum l \'l_max_scalars\', \'l_max_tensors\' in Cls for scalars/tensors (default: set \'l_max_scalars\' to 2500, \'l_max_tensors\' to 500)\n\nl_max_scalars = 3000\nl_max_tensors = 500\n\n2) maximum k in P(k), \'P_k_max_h/Mpc\' in units of h/Mpc or \'P_k_max_1/Mpc\' in units of 1/Mpc. If scalar Cls are also requested, a minimum value is automatically imposed (the same as in scalar Cls computation) (default: set to 0.1h/Mpc)\n\nP_k_max_h/Mpc = 10.\n#P_k_max_1/Mpc = 0.7\n\n3) value(s) \'z_pk\' of redshift(s) for P(k,z) output file(s); can be ordered arbitrarily, but must be separated by comas (default: set \'z_pk\' to 0)\n\nz_pk = 20.\n#z_pk = 0., 1.2, 3.5\n\n4) if you need Cls for the matter density autocorrelation or cross density-temperature correlation (option \'dCl\'), enter here a description of the selection functions W(z) of each redshift bin; selection can be set to \'gaussian\', then pass a list of N mean redshifts in growing order separated by comas, and finally 1 or N widths separated by comas (default: set to \'gaussian\',1,0.1)\n\nselection=gaussian\nselection_mean = 1.\nselection_width = 0.5\n\n5) file name root \'root\' for all output files (default: set \'root\' to \'output/\') (if Cl requested, written to \'<root>cl.dat\'; if P(k) requested, written to \'<root>pk.dat\'; plus similar files for scalars, tensors, pairs of initial conditions, etc.; if file with input parameters requested, written to \'<root>parameters.ini\')\n\nroot = {output_root} \n\n6) do you want headers at the beginning of each output file (giving precisions on the output units/ format) ? If \'headers\' set to something containing the letter \'y\' or \'Y\', headers written, otherwise not written (default: written)\n\nheaders = no\n\n7) in all output files, do you want columns to be normalized and ordered with the default CLASS definitions or with the CAMB definitions (often idential to the CMBFAST one) ? Set \'format\' to either \'class\', \'CLASS\', \'camb\' or \'CAMB\' (default: \'class\')\n\nformat = camb\n\n8) if \'bessel file\' set to something containing the letters \'y\' or \'Y\', the code tries to read bessel functions in a file; if the file is absent or not adequate, bessel functions are computed and written in a file. The file name is set by defaut to \'bessels.dat\' but can be changed together with precision parameters: just set \'bessel_file_name\' to \'<name>\' either here or in the precision parameter file. (defaut: \'bessel file\' set to \'no\' and bessel functions are always recomputed)\n\nbessel file = no\n\n9) Do you want to have all input/precision parameters which have been read written in file \'<root>parameters.ini\', and those not written in file \'<root>unused_parameters\' ? If \'write parameters\' set to something containing the letter \'y\' or \'Y\', file written, otherwise not written (default: not written)\n\nwrite parameters = yeap\n\n----------------------------------------------------\n----> amount of information sent to standard output:\n----------------------------------------------------\n\nIncrease integer values to make each module more talkative (default: all set to 0)\n\nbackground_verbose = 1\nthermodynamics_verbose = 0\nperturbations_verbose = 1\nbessels_verbose = 0\ntransfer_verbose = 0\nprimordial_verbose = 1\nspectra_verbose = 0\nnonlinear_verbose = 1\nlensing_verbose = 0\noutput_verbose = 1\n\n' picola_config = '\n% =============================== %\n% This is the run parameters file %\n% =============================== %\n\n% Simulation outputs\n% ==================\nOutputDir {outputdir} % Directory for output.\nFileBase {file_base} % Base-filename of output files (appropriate additions are appended on at runtime)\nOutputRedshiftFile {outputdir}/output_redshifts.dat % The file containing the redshifts that we want snapshots for\nNumFilesWrittenInParallel 4 % limits the number of files that are written in parallel when outputting.\n\n% Simulation Specifications\n% =========================\nUseCOLA 1 % Whether or not to use the COLA method (1=true, 0=false).\nBuffer 1.3 % The amount of extra memory to reserve for particles moving between tasks during runtime.\nNmesh 512 % This is the size of the FFT grid used to compute the displacement field and gravitational forces.\nNsample 512 % This sets the total number of particles in the simulation, such that Ntot = Nsample^3.\nBox 512.0 % The Periodic box size of simulation.\nInit_Redshift 20.0 % The redshift to begin timestepping from (redshift = 9 works well for COLA)\nSeed {seed} % Seed for IC-generator\nSphereMode 0 % If "1" only modes with |k| < k_Nyquist are used to generate initial conditions (i.e. a sphere in k-space),\n % otherwise modes with |k_x|,|k_y|,|k_z| < k_Nyquist are used (i.e. a cube in k-space).\n\nWhichSpectrum 1 % "0" - Use transfer function, not power spectrum\n % "1" - Use a tabulated power spectrum in the file \'FileWithInputSpectrum\'\n % otherwise, Eisenstein and Hu (1998) parametrization is used\n % Non-Gaussian case requires "0" and that we use the transfer function\n\nWhichTransfer 0 % "0" - Use power spectrum, not transfer function\n % "1" - Use a tabulated transfer function in the file \'FileWithInputTransfer\'\n % otherwise, Eisenstein and Hu (1998) parameterization used\n % For Non-Gaussian models this is required (rather than the power spectrum)\n\nFileWithInputSpectrum {outputdir}/class_pk.dat % filename of tabulated input spectrum (if used)\n % expecting k and Pk\n\nFileWithInputTransfer /home/users/swmclau2/picola/l-picola/files/input_transfer.dat % filename of tabulated transfer function (if used)\n % expecting k and T (unnormalized)\n\n% Cosmological Parameters\n% =======================\nOmega {ocdm:.2f} % Total matter density (CDM + Baryons at z=0).\nOmegaBaryon {ob:.2f} % Baryon density (at z=0).\nOmegaLambda {olambda:.2f} % Dark Energy density (at z=0)\nHubbleParam 0.7 % Hubble parameter, \'little h\' (only used for power spectrum parameterization).\nSigma8 {sigma8:.2f} % Power spectrum normalization (power spectrum may already be normalized correctly).\nPrimordialIndex 0.96 % Used to tilt the power spectrum for non-tabulated power spectra (if != 1.0 and nongaussian, generic flag required)\n\n% Timestepping Options\n% ====================\nStepDist 0 % The timestep spacing (0 for linear in a, 1 for logarithmic in a)\nDeltaA 0 % The type of timestepping: "0" - Use modified COLA timestepping for Kick and Drift. Please choose a value for nLPT.\n % The type of timestepping: "1" - Use modified COLA timestepping for Kick and standard Quinn timestepping for Drift. Please choose a value for nLPT.\n % The type of timestepping: "2" - Use standard Quinn timestepping for Kick and Drift\n % The type of timestepping: "3" - Use non-integral timestepping for Kick and Drift\nnLPT -2.5 % The value of nLPT to use for modified COLA timestepping\n\n\n% Units\n% =====\nUnitLength_in_cm 3.085678e24 % defines length unit of output (in cm/h)\nUnitMass_in_g 1.989e43 % defines mass unit of output (in g/h)\nUnitVelocity_in_cm_per_s 1e5 % defines velocity unit of output (in cm/sec)\nInputSpectrum_UnitLength_in_cm 3.085678e24 % defines length unit of tabulated input spectrum in cm/h.\n % Note: This can be chosen different from UnitLength_in_cm\n\n% ================================================== %\n% Optional extras (must comment out if not required) %\n% ================================================== %\n\n% Non-Gaussianity\n% ===============\n%Fnl -400 % The value of Fnl.\n%Fnl_Redshift 49.0 % The redshift to apply the nongaussian potential\n%FileWithInputKernel /files/input_kernel_ortog.txt % the input kernel for generic non-gaussianity (only needed for GENERIC_FNL)\n\n\n% Lightcone simulations\n% =====================\nOrigin_x 0.0 % The position of the lightcone origin in the x-axis\nOrigin_y 0.0 % The position of the lightcone origin in the y-axis\nOrigin_z 0.0 % The position of the lightcone origin in the z-axis\nNrep_neg_x 0 % The maximum number of box replicates in the negative x-direction\nNrep_pos_x 0 % The maximum number of box replicates in the positive x-direction\nNrep_neg_y 0 % The maximum number of box replicates in the negative y-direction\nNrep_pos_y 0 % The maximum number of box replicates in the positive y-direction\nNrep_neg_z 0 % The maximum number of box replicates in the negative z-direction\nNrep_pos_z 0 % The maximum number of box replicates in the positive z-direction\n'
""" impyute.util.errors """ class BadInputError(Exception): "Error thrown when input args don't match spec" pass
""" impyute.util.errors """ class Badinputerror(Exception): """Error thrown when input args don't match spec""" pass
print("Welcome to RollerCoaster") height = int(input("Enter your height in cm : ")) bill = 0 # Comparison operators are used more > , <= , == , > , >= , != if height >= 120 : print("You can ride the RollerCoaster") age = int(input("Enter your age : ")) if age < 12 : bill = 5 print("Childeren tickets are $5") elif age <= 18 : bill = 7 print("youth tickets are $7") elif age >= 45 and age <=55 : bill = 0 print("Have a free ride") else : bill = 12 print("Adult tickets are $12") photo = input("Do you want photo (y or n) : ") if photo == 'y' : bill += 3 print(f"your total bill : {bill}") else : print("Sorry, you have to grow taller before you can ride")
print('Welcome to RollerCoaster') height = int(input('Enter your height in cm : ')) bill = 0 if height >= 120: print('You can ride the RollerCoaster') age = int(input('Enter your age : ')) if age < 12: bill = 5 print('Childeren tickets are $5') elif age <= 18: bill = 7 print('youth tickets are $7') elif age >= 45 and age <= 55: bill = 0 print('Have a free ride') else: bill = 12 print('Adult tickets are $12') photo = input('Do you want photo (y or n) : ') if photo == 'y': bill += 3 print(f'your total bill : {bill}') else: print('Sorry, you have to grow taller before you can ride')
class Revoked(Exception): pass class MintingNotAllowed(Exception): pass
class Revoked(Exception): pass class Mintingnotallowed(Exception): pass
class Time: def __init__(self): self.hours=0 self.minutes=0 self.seconds=0 def input_values(self): self.hours=int(input('Enter the hours: ')) self.minutes=int(input('Enter the minutes: ')) self.seconds=int(input('Enter the seconds: ')) def print_details(self): print(self.hours,':',self.minutes,':',self.seconds) def __add__(self,other): t=Time() t.seconds=self.seconds+other.seconds t.minutes=self.minutes+other.minutes+t.seconds//60 t.seconds=t.seconds%60 t.hours=self.hours+other.hours+t.minutes//60 t.minutes=t.minutes%60 t.hours=t.hours%24 t.print_details() return t def __sub__(self,other): t=Time() t.hours=self.hours-other.hours t.minutes=self.minutes-other.minutes if(t.minutes<0): t.minutes=t.minutes+60 t.hours=t.hours-1 t.seconds=self.seconds-other.seconds if(t.seconds<0): t.seconds=t.seconds+60 t.minutes=t.minutes-1 t.print_details() return t t1=Time() print('Enter the time 1') t1.input_values() t1.print_details() t2=Time() print('Enter the time 2') t2.input_values() t2.print_details() print('Added time') t3=t1+t2 print('Subtracted time') t3=t1-t2
class Time: def __init__(self): self.hours = 0 self.minutes = 0 self.seconds = 0 def input_values(self): self.hours = int(input('Enter the hours: ')) self.minutes = int(input('Enter the minutes: ')) self.seconds = int(input('Enter the seconds: ')) def print_details(self): print(self.hours, ':', self.minutes, ':', self.seconds) def __add__(self, other): t = time() t.seconds = self.seconds + other.seconds t.minutes = self.minutes + other.minutes + t.seconds // 60 t.seconds = t.seconds % 60 t.hours = self.hours + other.hours + t.minutes // 60 t.minutes = t.minutes % 60 t.hours = t.hours % 24 t.print_details() return t def __sub__(self, other): t = time() t.hours = self.hours - other.hours t.minutes = self.minutes - other.minutes if t.minutes < 0: t.minutes = t.minutes + 60 t.hours = t.hours - 1 t.seconds = self.seconds - other.seconds if t.seconds < 0: t.seconds = t.seconds + 60 t.minutes = t.minutes - 1 t.print_details() return t t1 = time() print('Enter the time 1') t1.input_values() t1.print_details() t2 = time() print('Enter the time 2') t2.input_values() t2.print_details() print('Added time') t3 = t1 + t2 print('Subtracted time') t3 = t1 - t2
#!/usr/bin/env python # encoding: utf-8 """ __init__.py Creating models for testing. See ticket for more detail. http://code.djangoproject.com/ticket/7835 """
""" __init__.py Creating models for testing. See ticket for more detail. http://code.djangoproject.com/ticket/7835 """
#!/usr/bin/python # -*- coding : utf-8 -*- """ pattern: Factory method: Define an interface for creating an object, but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses. AbstractProduct1 < = > AbstractProduct2 | | | | ProductA1 ProductB1 ProductA2 ProductB2 AbstractFactory | | FactoryA FactoryB (for ProductA1 and A2) (for ProductB1 and B2) *************************************************************** MaleAnimal < = > FemaleAnimal | | | | MaleLion MaleTiger FemaleLion FemaleTiger ; AnimalFactory | | LionFactory TigerFactory (for MaleLion and FemaleLion) (for MaleTiger and FemaleTiger) """ ########################################## # AbstractProduct1 class MaleAnimal: def __init__(self): self.boundary = 'MaleAnimal' self.state = self.boundary def __str__(self): return self.state # ProductA1 class MaleLion(MaleAnimal): def __init__(self): super(MaleLion, self).__init__(); self.state = self.boundary + ' - MaleLion' def __str__(self): return self.state # ProductB1 class MaleTiger(MaleAnimal): def __init__(self): super(MaleTiger, self).__init__(); self.state = self.boundary + ' - MaleTiger' def __str__(self): return self.state ########################################## # AbstractProduct2 class FemaleAnimal: def __init__(self): self.boundary = 'FemaleAnimal' self.state = self.boundary def __str__(self): return self.state # ProductA2 class FemaleLion(FemaleAnimal): def __init__(self): super(FemaleLion, self).__init__(); self.state = self.boundary + ' - FemaleLion' def __str__(self): return self.state # ProductB2 class FemaleTiger(FemaleAnimal): def __init__(self): super(FemaleTiger, self).__init__(); self.state = self.boundary + ' - FemaleTiger' def __str__(self): return self.state ########################################## # AbstractFactory class AnimalFactory(): def create_male_animal(self): pass def create_female_animal(self): pass # FactoryA class LionFactory(AnimalFactory): def __init__(self): print('Initialize LionFactory.') def create_male_animal(self): return MaleLion() def create_female_animal(self): return FemaleLion() # FactoryB class TigerFactory(AnimalFactory): def __init__(self): print('Initialize TigerFactory.') def create_male_animal(self): return MaleTiger() def create_female_animal(self): return FemaleTiger() if __name__ == '__main__': lion_factory = LionFactory() tiger_factory = TigerFactory() obj_a1 = lion_factory.create_male_animal() obj_a2 = lion_factory.create_female_animal() obj_b1 = tiger_factory.create_male_animal() obj_b2 = tiger_factory.create_female_animal() print('obj_a1: {0}'.format(obj_a1)) print('obj_a2: {0}'.format(obj_a2)) print('obj_b1: {0}'.format(obj_b1)) print('obj_b2: {0}'.format(obj_b2))
""" pattern: Factory method: Define an interface for creating an object, but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses. AbstractProduct1 < = > AbstractProduct2 | | | | ProductA1 ProductB1 ProductA2 ProductB2 AbstractFactory | | FactoryA FactoryB (for ProductA1 and A2) (for ProductB1 and B2) *************************************************************** MaleAnimal < = > FemaleAnimal | | | | MaleLion MaleTiger FemaleLion FemaleTiger ; AnimalFactory | | LionFactory TigerFactory (for MaleLion and FemaleLion) (for MaleTiger and FemaleTiger) """ class Maleanimal: def __init__(self): self.boundary = 'MaleAnimal' self.state = self.boundary def __str__(self): return self.state class Malelion(MaleAnimal): def __init__(self): super(MaleLion, self).__init__() self.state = self.boundary + ' - MaleLion' def __str__(self): return self.state class Maletiger(MaleAnimal): def __init__(self): super(MaleTiger, self).__init__() self.state = self.boundary + ' - MaleTiger' def __str__(self): return self.state class Femaleanimal: def __init__(self): self.boundary = 'FemaleAnimal' self.state = self.boundary def __str__(self): return self.state class Femalelion(FemaleAnimal): def __init__(self): super(FemaleLion, self).__init__() self.state = self.boundary + ' - FemaleLion' def __str__(self): return self.state class Femaletiger(FemaleAnimal): def __init__(self): super(FemaleTiger, self).__init__() self.state = self.boundary + ' - FemaleTiger' def __str__(self): return self.state class Animalfactory: def create_male_animal(self): pass def create_female_animal(self): pass class Lionfactory(AnimalFactory): def __init__(self): print('Initialize LionFactory.') def create_male_animal(self): return male_lion() def create_female_animal(self): return female_lion() class Tigerfactory(AnimalFactory): def __init__(self): print('Initialize TigerFactory.') def create_male_animal(self): return male_tiger() def create_female_animal(self): return female_tiger() if __name__ == '__main__': lion_factory = lion_factory() tiger_factory = tiger_factory() obj_a1 = lion_factory.create_male_animal() obj_a2 = lion_factory.create_female_animal() obj_b1 = tiger_factory.create_male_animal() obj_b2 = tiger_factory.create_female_animal() print('obj_a1: {0}'.format(obj_a1)) print('obj_a2: {0}'.format(obj_a2)) print('obj_b1: {0}'.format(obj_b1)) print('obj_b2: {0}'.format(obj_b2))
# Shape of number 2 using fucntions def for_2(): """ *'s printed in the shape of number 2 """ for row in range(9): for col in range(9): if row ==8 or row+col ==8 and row !=0 or row ==0 and col%8 !=0 or row ==1 and col ==0 or row ==2 and col ==0: print('*',end =' ') else: print(' ',end=' ') print() def while_2(): """ *'s printed in the shape of number 2 """ row =0 while row<9: col =0 while col <9: if row ==8 or row+col ==8 and row !=0 or row ==0 and col%8 !=0 or row ==1 and col ==0 or row ==2 and col ==0: print('*',end =' ') else: print(' ',end=' ') col+=1 print() row += 1
def for_2(): """ *'s printed in the shape of number 2 """ for row in range(9): for col in range(9): if row == 8 or (row + col == 8 and row != 0) or (row == 0 and col % 8 != 0) or (row == 1 and col == 0) or (row == 2 and col == 0): print('*', end=' ') else: print(' ', end=' ') print() def while_2(): """ *'s printed in the shape of number 2 """ row = 0 while row < 9: col = 0 while col < 9: if row == 8 or (row + col == 8 and row != 0) or (row == 0 and col % 8 != 0) or (row == 1 and col == 0) or (row == 2 and col == 0): print('*', end=' ') else: print(' ', end=' ') col += 1 print() row += 1
""" You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i. Example 1: Input: intervals = [[1,2]] Output: [-1] Explanation: There is only one interval in the collection, so it outputs -1. Example 2: Input: intervals = [[3,4],[2,3],[1,2]] Output: [-1,0,1] Explanation: There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3. The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2. IDEA: """ class Solution436: pass
""" You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i. Example 1: Input: intervals = [[1,2]] Output: [-1] Explanation: There is only one interval in the collection, so it outputs -1. Example 2: Input: intervals = [[3,4],[2,3],[1,2]] Output: [-1,0,1] Explanation: There is no right interval for [3,4]. The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3. The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2. IDEA: """ class Solution436: pass
class Solution: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ nums.sort() ans = nums[:] for i in range(1, len(nums), 2): nums[i] = ans.pop() for i in range(0, len(nums), 2): nums[i] = ans.pop()
class Solution: def wiggle_sort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ nums.sort() ans = nums[:] for i in range(1, len(nums), 2): nums[i] = ans.pop() for i in range(0, len(nums), 2): nums[i] = ans.pop()
PANEL_GROUP = 'default' PANEL_DASHBOARD = 'billing' PANEL = 'billing_invoices' # Python panel class of the PANEL to be added. ADD_PANEL = 'astutedashboard.dashboards.billing.invoices.panel.BillingInvoices'
panel_group = 'default' panel_dashboard = 'billing' panel = 'billing_invoices' add_panel = 'astutedashboard.dashboards.billing.invoices.panel.BillingInvoices'
def isPrime(n): if n <= 1: return False for i in range(2,int(n**.5)+1): if n % i == 0: return False return True def findPrime(n): k=1 for i in range(n): if isPrime(i): if(k>=10001):return i k+=1 print(findPrime(300000))
def is_prime(n): if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def find_prime(n): k = 1 for i in range(n): if is_prime(i): if k >= 10001: return i k += 1 print(find_prime(300000))
dict={'A': ['B', 'CB', 'D', 'E', 'F', 'GD', 'H', 'IE'], 'B': ['A', 'C', 'D', 'E', 'F', 'G', 'HE', 'I'], 'C': ['AB', 'GE', 'D', 'E', 'F', 'B', 'H', 'IF'], 'D': ['A', 'B', 'C', 'E', 'FE', 'G', 'H', 'I'], 'E': ['A', 'B', 'C', 'D', 'F', 'G', 'H', 'I'], 'F': ['A', 'B', 'C', 'DE', 'E', 'G', 'H', 'I'], 'G': ['AD', 'B', 'CE', 'D', 'E', 'F', 'H', 'IH'], 'H': ['A', 'BE', 'C', 'D', 'E', 'F', 'G', 'I'], 'I': ['AE', 'B', 'F', 'D', 'E', 'CF', 'GH', 'H']} def count_patterns_from(firstPoint, length): if length<=1 or length>9: return 1 if length==1 else 0 return helper(firstPoint, length, {firstPoint}, {"":0}, 1, [firstPoint]) def helper(cur, target, went, res, n, order): if n>=target: if n==target==len(order): res[""]+=1 return length=len(went) for i in dict[cur]: comp=went|{i[0]} if len(i)==1 else went|{i[0], i[1]} diff=len(comp)-length if (diff==1 and i[0] not in went) or diff==2: helper(i[0], target, comp, res, n+diff, order+[i[0]]) return res[""]
dict = {'A': ['B', 'CB', 'D', 'E', 'F', 'GD', 'H', 'IE'], 'B': ['A', 'C', 'D', 'E', 'F', 'G', 'HE', 'I'], 'C': ['AB', 'GE', 'D', 'E', 'F', 'B', 'H', 'IF'], 'D': ['A', 'B', 'C', 'E', 'FE', 'G', 'H', 'I'], 'E': ['A', 'B', 'C', 'D', 'F', 'G', 'H', 'I'], 'F': ['A', 'B', 'C', 'DE', 'E', 'G', 'H', 'I'], 'G': ['AD', 'B', 'CE', 'D', 'E', 'F', 'H', 'IH'], 'H': ['A', 'BE', 'C', 'D', 'E', 'F', 'G', 'I'], 'I': ['AE', 'B', 'F', 'D', 'E', 'CF', 'GH', 'H']} def count_patterns_from(firstPoint, length): if length <= 1 or length > 9: return 1 if length == 1 else 0 return helper(firstPoint, length, {firstPoint}, {'': 0}, 1, [firstPoint]) def helper(cur, target, went, res, n, order): if n >= target: if n == target == len(order): res[''] += 1 return length = len(went) for i in dict[cur]: comp = went | {i[0]} if len(i) == 1 else went | {i[0], i[1]} diff = len(comp) - length if diff == 1 and i[0] not in went or diff == 2: helper(i[0], target, comp, res, n + diff, order + [i[0]]) return res['']
test = { 'name': 'q4c', 'points': 10, 'suites': [ { 'cases': [ { 'code': '>>> len(prophet_forecast) == ' '5863\n' 'True', 'hidden': False, 'locked': False}, { 'code': '>>> ' 'len(prophet_forecast_holidays) ' '== 5863\n' 'True', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
test = {'name': 'q4c', 'points': 10, 'suites': [{'cases': [{'code': '>>> len(prophet_forecast) == 5863\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> len(prophet_forecast_holidays) == 5863\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
def read_blob(blob, bucket): return bucket.blob(blob).download_as_string().decode("utf-8", errors="ignore") def download_blob(blob, file_obj, bucket): return bucket.blob(blob).download_to_file(file_obj) def write_blob(key, file_obj, bucket): return bucket.blob(key).upload_from_file(file_obj)
def read_blob(blob, bucket): return bucket.blob(blob).download_as_string().decode('utf-8', errors='ignore') def download_blob(blob, file_obj, bucket): return bucket.blob(blob).download_to_file(file_obj) def write_blob(key, file_obj, bucket): return bucket.blob(key).upload_from_file(file_obj)
''' Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example 1: Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Note: 1 <= A.length <= 5000 0 <= A[i] <= 5000 ''' class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ B = list() for num in A: if num % 2 == 0: B.append(num) for num in A: if num % 2 != 0: B.append(num) return B mysolution = Solution() array = [3,1,2,4] print(mysolution.sortArrayByParity(array))
""" Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example 1: Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Note: 1 <= A.length <= 5000 0 <= A[i] <= 5000 """ class Solution(object): def sort_array_by_parity(self, A): """ :type A: List[int] :rtype: List[int] """ b = list() for num in A: if num % 2 == 0: B.append(num) for num in A: if num % 2 != 0: B.append(num) return B mysolution = solution() array = [3, 1, 2, 4] print(mysolution.sortArrayByParity(array))
# https://www.hackerrank.com/challenges/compare-the-triplets/problem?h_r=internal-search A = input().split() B = input().split() def compare(a, b): alice = 0 bob = 0 x = len(a) for i in range(x): if int(a[i]) > int(b[i]): alice += 1 elif int(a[i]) < int(b[i]): bob += 1 elif a[i] == b[i]: alice += 0 bob += 0 pass return [alice, bob] total = compare(A, B) print(total) """ Examples 17 28 30 99 16 8 output => 2, 1 5 6 7 3 6 10 output => 1, 1 """
a = input().split() b = input().split() def compare(a, b): alice = 0 bob = 0 x = len(a) for i in range(x): if int(a[i]) > int(b[i]): alice += 1 elif int(a[i]) < int(b[i]): bob += 1 elif a[i] == b[i]: alice += 0 bob += 0 pass return [alice, bob] total = compare(A, B) print(total) '\nExamples\n17 28 30\n99 16 8\noutput => 2, 1\n5 6 7\n3 6 10\noutput => 1, 1\n'
class Attachment: def __init__( self, fallback: str, color: str = None, pretext: str = None, text: str = None, author_name: str = None, author_link: str = None, author_icon: str = None, title: str = None, title_link: str = None, fields: list = None, image_url: str = None, thumb_url: str = None, ): self.fallback = fallback self.color = color self.pretext = pretext self.text = text self.author_name = author_name self.author_link = author_link self.author_icon = author_icon self.title = title self.title_link = title_link self.fields = fields self.image_url = image_url self.thumb_url = thumb_url payload = {"fallback": self.fallback} if self.color: payload["color"] = self.color if self.pretext: payload["pretext"] = self.pretext if self.text: payload["text"] = self.text if self.author_name: payload["author_name"] = self.author_name if self.author_link: payload["author_link"] = self.author_link if self.author_icon: payload["author_icon"] = self.author_icon if self.title: payload["title"] = self.title if self.title_link: payload["title_link"] = self.title_link if self.fields: payload["fields"] = self.fields if self.image_url: payload["image_url"] = self.image_url if self.thumb_url: payload["thumb_url"] = self.thumb_url self.payload = payload
class Attachment: def __init__(self, fallback: str, color: str=None, pretext: str=None, text: str=None, author_name: str=None, author_link: str=None, author_icon: str=None, title: str=None, title_link: str=None, fields: list=None, image_url: str=None, thumb_url: str=None): self.fallback = fallback self.color = color self.pretext = pretext self.text = text self.author_name = author_name self.author_link = author_link self.author_icon = author_icon self.title = title self.title_link = title_link self.fields = fields self.image_url = image_url self.thumb_url = thumb_url payload = {'fallback': self.fallback} if self.color: payload['color'] = self.color if self.pretext: payload['pretext'] = self.pretext if self.text: payload['text'] = self.text if self.author_name: payload['author_name'] = self.author_name if self.author_link: payload['author_link'] = self.author_link if self.author_icon: payload['author_icon'] = self.author_icon if self.title: payload['title'] = self.title if self.title_link: payload['title_link'] = self.title_link if self.fields: payload['fields'] = self.fields if self.image_url: payload['image_url'] = self.image_url if self.thumb_url: payload['thumb_url'] = self.thumb_url self.payload = payload
infile = open("sud3_results.csv","r") outfile = open("sud4_results.csv","w") keywords = infile.readline().strip().split(",")[1:] outfile.write("%s, %s" % ("filename", ",".join("Environment+Social+Economic", "Environment+Social+Economic+Cultural", "Environment+Social+Economic+Cultural+Institutional"))) three_pillars_keywords = ["environmental", "housing", "energy", "water", "social", "local", "community", "public", "economic"] four_pillars_keywords = three_pillars_keywords + ["cultural", "culture"] five_pillar_keywords = four_pillars_keywords + ["urban", "planning"] for line in infile.readlines(): data = line.split(",") filename = data[0] numerical = [int(entry) for entry in data[1:]]
infile = open('sud3_results.csv', 'r') outfile = open('sud4_results.csv', 'w') keywords = infile.readline().strip().split(',')[1:] outfile.write('%s, %s' % ('filename', ','.join('Environment+Social+Economic', 'Environment+Social+Economic+Cultural', 'Environment+Social+Economic+Cultural+Institutional'))) three_pillars_keywords = ['environmental', 'housing', 'energy', 'water', 'social', 'local', 'community', 'public', 'economic'] four_pillars_keywords = three_pillars_keywords + ['cultural', 'culture'] five_pillar_keywords = four_pillars_keywords + ['urban', 'planning'] for line in infile.readlines(): data = line.split(',') filename = data[0] numerical = [int(entry) for entry in data[1:]]
class EnvInfo(object): def __init__(self, frame_id, time_stamp, road_path, obstacle_array): # default params self.frame_id = frame_id self.time_stamp = time_stamp self.road_path = road_path self.obstacle_array = obstacle_array
class Envinfo(object): def __init__(self, frame_id, time_stamp, road_path, obstacle_array): self.frame_id = frame_id self.time_stamp = time_stamp self.road_path = road_path self.obstacle_array = obstacle_array
# Module for implementing gradients used in the autograd system __all__ = ["GradFunc"] def forward_grad(tensor): ## tensor here should be an AutogradTensor or a Tensor where we can set .grad try: grad_fn = tensor.grad_fn except AttributeError: return None # If a tensor doesn't have a grad_fn already attached to it, that means # it's a leaf of the graph and we want to accumulate the gradient if grad_fn is None and tensor.requires_grad: return Accumulate(tensor) else: return grad_fn class GradFunc: def __init__(self, *args): # This part builds our graph. It takes grad functions (if they exist) # from the input arguments and builds a tuple pointing to them. This way # we can use .next_functions to traverse through the entire graph. self.next_functions = tuple( filter(lambda x: x is not None, [forward_grad(arg) for arg in args]) ) self.result = None def gradient(self, grad): raise NotImplementedError def __setattr__(self, name, value): # Doing this because we want to pass in AutogradTensors so we can update # tensor.grad in Accumulate, but we also need native looking tensors for # the gradient operations in GradFuncs. try: value = value.child except AttributeError: pass object.__setattr__(self, name, value) def __call__(self, grad): return self.gradient(grad) def __repr__(self): return self.__class__.__name__ # Accumulate gradients at graph leafs class Accumulate: def __init__(self, tensor): # Note that tensor here should be an AutogradTensor so we can update # .grad appropriately self.next_functions = [] self.tensor = tensor def __call__(self, grad): if self.tensor.grad is not None: self.tensor.grad += grad else: self.tensor.grad = grad + 0 return () def __repr__(self): return self.__class__.__name__
__all__ = ['GradFunc'] def forward_grad(tensor): try: grad_fn = tensor.grad_fn except AttributeError: return None if grad_fn is None and tensor.requires_grad: return accumulate(tensor) else: return grad_fn class Gradfunc: def __init__(self, *args): self.next_functions = tuple(filter(lambda x: x is not None, [forward_grad(arg) for arg in args])) self.result = None def gradient(self, grad): raise NotImplementedError def __setattr__(self, name, value): try: value = value.child except AttributeError: pass object.__setattr__(self, name, value) def __call__(self, grad): return self.gradient(grad) def __repr__(self): return self.__class__.__name__ class Accumulate: def __init__(self, tensor): self.next_functions = [] self.tensor = tensor def __call__(self, grad): if self.tensor.grad is not None: self.tensor.grad += grad else: self.tensor.grad = grad + 0 return () def __repr__(self): return self.__class__.__name__
class KeywordsOnlyMeta(type): def __call__(cls, *args, **kwargs): if args: raise TypeError("Constructor for class {!r} does not accept positional arguments.".format(cls)) return super().__call__(cls, **kwargs) class ConstrainedToKeywords(metaclass=KeywordsOnlyMeta): def __init__(self, *args, **kwargs): print("args =", args) print("kwargs = ", kwargs)
class Keywordsonlymeta(type): def __call__(cls, *args, **kwargs): if args: raise type_error('Constructor for class {!r} does not accept positional arguments.'.format(cls)) return super().__call__(cls, **kwargs) class Constrainedtokeywords(metaclass=KeywordsOnlyMeta): def __init__(self, *args, **kwargs): print('args =', args) print('kwargs = ', kwargs)
if __name__ == "__main__": ans = "" for n in range(2, 10): for i in range(1, 10**(9 // n)): s = "".join(str(i * j) for j in range(1, n + 1)) if "".join(sorted(s)) == "123456789": ans = max(s, ans) print(ans)
if __name__ == '__main__': ans = '' for n in range(2, 10): for i in range(1, 10 ** (9 // n)): s = ''.join((str(i * j) for j in range(1, n + 1))) if ''.join(sorted(s)) == '123456789': ans = max(s, ans) print(ans)
""" The module identify push-down method refactoring opportunities in Java projects """ # Todo: Implementing a decent push-down method identification algorithm.
""" The module identify push-down method refactoring opportunities in Java projects """
COLORS = { 'Black': u'\u001b[30m', 'Red': u'\u001b[31m', 'Green': u'\u001b[32m', 'Yellow': u'\u001b[33m', 'Blue': u'\u001b[34m', 'Magenta': u'\u001b[35m', 'Cyan': u'\u001b[36m', 'White': u'\u001b[37m', 'Reset': u'\u001b[0m', }
colors = {'Black': u'\x1b[30m', 'Red': u'\x1b[31m', 'Green': u'\x1b[32m', 'Yellow': u'\x1b[33m', 'Blue': u'\x1b[34m', 'Magenta': u'\x1b[35m', 'Cyan': u'\x1b[36m', 'White': u'\x1b[37m', 'Reset': u'\x1b[0m'}
def mmc(x, y): if a == 0 or b == 0: return 0 return a * b // mdc(a, b) def mdc(a, b): if b == 0: return a return mdc(b, a % b) a, b = input().split() a, b = int(a), int(b) while a >= 0 and b >= 0: print(mmc(a, b)) a, b = input().split() a, b = int(a), int(b)
def mmc(x, y): if a == 0 or b == 0: return 0 return a * b // mdc(a, b) def mdc(a, b): if b == 0: return a return mdc(b, a % b) (a, b) = input().split() (a, b) = (int(a), int(b)) while a >= 0 and b >= 0: print(mmc(a, b)) (a, b) = input().split() (a, b) = (int(a), int(b))
# Puzzle Input with open('Day20_Input.txt') as puzzle_input: tiles = puzzle_input.read().split('\n\n') # Parse the tiles: Separate the ID and get the 4 sides: parsed_tiles = [] tiles_IDs = [] for original_tile in tiles: # For every tile: original_tile = original_tile.split('\n') # Split the original tile into rows tiles_IDs += [int(original_tile[0][5:-1])] # Get the ID of the tile -> Tile: XXXX, XXXX starts at index 5 parsed_tiles += [[]] # Next parsed tile left_side = '' right_side = '' for row in original_tile[1:]: # The left and right sides are the: left_side += row[0] # Beginning of rows right_side += row[-1] # End of rows parsed_tiles[-1] += original_tile[1][:], right_side[:], original_tile[-1][:], left_side[:] # Make connections between the tiles connections = [[] for _ in range(len(tiles_IDs))] # Create an empty list of connections for tile_index, tile in enumerate(parsed_tiles): # For every tile: tile_id = tiles_IDs[tile_index] # Get it's ID for other_tile_index, other_tile in enumerate(parsed_tiles): # Try to match it to every other tile if other_tile_index == tile_index: # If they're the same tile, go to the next continue other_tile_id = tiles_IDs[other_tile_index] # Get the other tile's ID if other_tile_id in connections[tile_index]: # The other tile has the connection, skip this continue for other_side in other_tile: # For every side in the other tile if other_side in tile or other_side[::-1] in tile: # See if either the side currently matches connections[tile_index] += [other_tile_id] # or if a rotated tile would match this tile connections[other_tile_index] += [tile_id] # then, add the connections # Get the product of the corners (the tiles that only have 2 connections) total = 1 for ID, conn in zip(tiles_IDs, connections): if len(conn) == 2: total *= ID # Show the result print(total)
with open('Day20_Input.txt') as puzzle_input: tiles = puzzle_input.read().split('\n\n') parsed_tiles = [] tiles_i_ds = [] for original_tile in tiles: original_tile = original_tile.split('\n') tiles_i_ds += [int(original_tile[0][5:-1])] parsed_tiles += [[]] left_side = '' right_side = '' for row in original_tile[1:]: left_side += row[0] right_side += row[-1] parsed_tiles[-1] += (original_tile[1][:], right_side[:], original_tile[-1][:], left_side[:]) connections = [[] for _ in range(len(tiles_IDs))] for (tile_index, tile) in enumerate(parsed_tiles): tile_id = tiles_IDs[tile_index] for (other_tile_index, other_tile) in enumerate(parsed_tiles): if other_tile_index == tile_index: continue other_tile_id = tiles_IDs[other_tile_index] if other_tile_id in connections[tile_index]: continue for other_side in other_tile: if other_side in tile or other_side[::-1] in tile: connections[tile_index] += [other_tile_id] connections[other_tile_index] += [tile_id] total = 1 for (id, conn) in zip(tiles_IDs, connections): if len(conn) == 2: total *= ID print(total)
"""Contains the package version number """ __version__ = '0.1.0-dev'
"""Contains the package version number """ __version__ = '0.1.0-dev'