content
stringlengths
7
1.05M
class event_meta(object): def __init__(self): super(event_meta, self).__init__() def n_views(self): return max(self._n_views, 1) def refresh(self, meta_vec): self._n_views = len(meta_vec) self._x_min = [] self._y_min = [] self._x_max = [] self._y_max = [] self._y_n_pixels = [] self._x_n_pixels = [] x_ind = 0 y_ind = 1 for meta in meta_vec: self._x_min.append(meta.origin(0)) self._y_min.append(meta.origin(1)) self._x_max.append(meta.image_size(0) + meta.origin(0)) self._y_max.append(meta.image_size(1) + meta.origin(1)) self._x_n_pixels.append(meta.number_of_voxels(0)) self._y_n_pixels.append(meta.number_of_voxels(1)) for i in range(self._n_views): if self._x_min[i] == self._x_max[i]: self._x_max[i] = self._x_min[i] + self._x_n_pixels[i] if self._y_min[i] == self._y_max[i]: self._y_max[i] = self._y_min[i] + self._y_n_pixels[i] def cols(self, plane): return self._x_n_pixels[plane] def width(self, plane): return self._x_max[plane] - self._x_min[plane] def comp_x(self, plane): return self.width(plane) / self.cols(plane) def rows(self, plane): return self._y_n_pixels[plane] def height(self, plane): return self._y_max[plane] - self._y_min[plane] def comp_y(self, plane): return self.height(plane) / self.rows(plane) def wire_to_col(self, wire, plane): return self.cols(plane) * (1.0*(wire - self.min_x(plane)) / self.width(plane)) def time_to_row(self, time, plane): return self.rows(plane) * (1.0*(time - self.min_y(plane)) / self.height(plane)) def min_y(self, plane): return self._y_min[plane] def max_y(self, plane): return self._y_max[plane] def min_x(self, plane): return self._x_min[plane] def max_x(self, plane): return self._x_max[plane] def range(self, plane): if plane >= 0 and plane < self._n_views: return ((self._x_min[plane], self._x_min[plane] ), (self._x_min[plane], self._x_min[plane])) else: print("ERROR: plane {} not available.".format(plane)) return ((-1, 1), (-1, 1)) class event_meta3D(object): def __init__(self): super(event_meta3D, self).__init__() def refresh(self, meta): x_ind = 0 y_ind = 1 z_ind = 2 self._x_min = meta.origin(x_ind) self._y_min = meta.origin(y_ind) self._z_min = meta.origin(z_ind) self._x_max = meta.image_size(x_ind) + meta.origin(x_ind) self._y_max = meta.image_size(y_ind) + meta.origin(y_ind) self._z_max = meta.image_size(z_ind) + meta.origin(z_ind) self._y_n_pixels = meta.number_of_voxels(x_ind) self._x_n_pixels = meta.number_of_voxels(y_ind) self._z_n_pixels = meta.number_of_voxels(z_ind) def size_voxel_x(self): return (self._x_max - self._x_min) / self._x_n_pixels def size_voxel_y(self): return (self._y_max - self._y_min) / self._y_n_pixels def size_voxel_z(self): return (self._z_max - self._z_min) / self._z_n_pixels def n_voxels_x(self): return self._x_n_pixels def n_voxels_y(self): return self._y_n_pixels def n_voxels_z(self): return self._z_n_pixels def dim_x(self): return self._x_max - self._x_min def dim_y(self): return self._y_max - self._y_min def dim_z(self): return self._z_max - self._z_min def width(self): return self.dim_x() def height(self): return self.dim_y() def length(self): return self.dim_z() def min_y(self): return self._y_min def max_y(self): return self._y_max def min_x(self): return self._x_min def max_x(self): return self._x_max def min_z(self): return self._z_min def max_z(self): return self._z_max
def sum(a, b): return a + b a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) c = sum(a, b) print("The sum of the two numbers is: ", c)
#testing_loops.py """n = 1 # while the value of n is less than 5, print n. add 1 to n each time # use while loops for infinate loops or for a set number of executions/loops while n<5: print(n) n = n + 1""" """ num = float(input("Enter a postive number:")) while num <= 0: print("That's not a positive number!") num = float(input("Enter a positive number:")) """ """# use for loops to loop over a collection of items for letter in "Python": print(letter)""" # loop over a range of numbers with range / any positive #, n times # range(5) returns range of integers starting with 0 and up to, not including, 5. (0,1,2,3,4) """for n in range(5): print("Python is awesome")""" # you can give range a starting point (great for dice rolls) """for n in range(10,20): print(n * n)""" # you can use it to calculate a split check: amount = float(input("Enter an amount:")) for num_people in range(2,6): print(f"{num_people} people: ${amount / num_people:,.2f} each")
module_attribute = "hello!" def extension(app): """This extension will work""" return "extension loaded" def assertive_extension(app): """This extension won't work""" assert False
class Funcionario: def __init__(self, nome, cpf, salario): self.__nome = nome self.__cpf = cpf self.__salario = salario def get_nome(self): return self.__nome def get_cpf(self): return self.__cpf def get_salario(self): return self.__salario def set_nome(self, nome): self.__nome = nome def set_cpf(self, cpf): self.__cpf = cpf def set_salario(self, salario): self.__salario = salario # Programa Principal func1 = Funcionario("Pedro", "111222333-22", 1500.0) func1.set_salario(2000) # Altera o salário print("Nome:", func1.get_nome()) print("CPF:", func1.get_cpf()) print("Salário:", func1.get_salario())
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: positives_and_zero = collections.deque() negatives = collections.deque() for x in nums: if x < 0: negatives.appendleft(x * x) else: positives_and_zero.append(x * x) ans = [] while(len(negatives) > 0 and len(positives_and_zero) > 0): if positives_and_zero < negatives: ans.append(positives_and_zero.popleft()) else: ans.append(negatives.popleft()) # one of them is empty so order doesn't matter ans += positives_and_zero + negatives return ans
class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def computeGCD(self, x, y): if x > y: small = y else: small = x gcd = 1 for i in range(1, small + 1): if ((x % i == 0) and (y % i == 0)): gcd = i return gcd def maxPoints(self, A, B): N = len(A) if N <= 2: return N max_points = 0 for i in range(N): hash_map = {} horizontal = 0 vertical = 0 overlap = 1 x1, y1 = A[i], B[i] for j in range(i + 1, N): x2, y2 = A[j], B[j] if x1 == x2 and y1 == y2: overlap += 1 elif x1 == x2: vertical += 1 elif y1 == y2: horizontal += 1 else: dy = y2 - y1 dx = x2 - x1 slope = 1.0* dy / dx if slope in hash_map: hash_map[slope] = hash_map[slope] + 1 else: hash_map[slope] = 1 curr_max = max(list(hash_map.values()) + [vertical, horizontal]) curr_max += overlap max_points = max(max_points, curr_max) return max_points
TVOC =2300 if TVOC <=2500 and TVOC >=2000: print("Level-5", "Unhealty") print("Hygienic Rating - Situation not acceptable") print("Recommendation - Use only if unavoidable/Intense ventilation necessary") print("Exposure Limit - Hours")
for i in range(10): print(i) i = 1 while i < 6: print(i) i += 1
'''Spiral Matrix''' # spiral :: Int -> [[Int]] def spiral(n): '''The rows of a spiral matrix of order N. ''' def go(rows, cols, x): return [list(range(x, x + cols))] + [ list(reversed(x)) for x in zip(*go(cols, rows - 1, x + cols)) ] if 0 < rows else [[]] return go(n, n, 0) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Spiral matrix of order 5, in wiki table markup''' print(wikiTable( spiral(5) )) # FORMATTING ---------------------------------------------- # wikiTable :: [[a]] -> String def wikiTable(rows): '''Wiki markup for a no-frills tabulation of rows.''' return '{| class="wikitable" style="' + ( 'width:12em;height:12em;table-layout:fixed;"|-\n' ) + '\n|-\n'.join([ '| ' + ' || '.join([str(cell) for cell in row]) for row in rows ]) + '\n|}' # MAIN --- if __name__ == '__main__': main()
################################################## # 原始数据 # ################################################## # train.csv # 行数:8798815 (包括标题行) # 列数:3 trainCols = ['aid', 'uid', 'label'] # test1.csv # 行数:2265990 (包括标题行) # 列数:2 test1Cols = ['aid', 'uid'] # adFeature.csv # 行数:174 (包括标题行) # 列数:8 adFCols = ['aid', 'advertiserId', 'campaignId', 'creativeId', 'creativeSize', 'adCategoryId', 'productId', 'productType'] # userFeature.csv # 行数:11420040 (包括标题行) # 列数:24 userFCols = ['uid', 'age', 'gender', 'marriageStatus', 'education', 'consumptionAbility', 'LBS', 'interest1', 'interest2', 'interest3', 'interest4', 'interest5', 'kw1', 'kw2', 'kw3', 'topic1', 'topic2', 'topic3', 'appIdInstall', 'appIdAction', 'ct', 'os', 'carrier', 'house'] ################################################## # 预处理数据 # ################################################## # processed_data.csv # 来源:上下拼接train.csv与test1.csv,根据aid、uid merge全表,对marriageStatus、ct、os进行LabelEncoder处理,得到相应feature.1特征; # 对interest、kw、topic、appIdInstall、appIdAction进行w2v处理,得到相应feature0-feature9特征 # 行数:11064804 (包括标题行) # 列数:165 processedCols = ['aid', 'label', 'uid', 'advertiserId', 'campaignId', 'creativeSize', 'adCategoryId', 'productId', 'productType', 'age', 'gender', 'marriageStatus', 'education', 'consumptionAbility', 'LBS', 'interest1', 'interest2', 'interest3', 'interest4', 'interest5', 'kw1', 'kw2', 'kw3', 'topic1', 'topic2', 'topic3', 'appIdInstall', 'appIdAction', 'ct', 'os', 'carrier', 'house', 'marriageStatus.1', 'ct.1', 'os.1', 'interest10', 'interest11', 'interest12', 'interest13', 'interest14', 'interest15', 'interest16', 'interest17', 'interest18', 'interest19', 'interest20', 'interest21', 'interest22', 'interest23', 'interest24', 'interest25', 'interest26', 'interest27', 'interest28', 'interest29', 'interest30', 'interest31', 'interest32', 'interest33', 'interest34', 'interest35', 'interest36', 'interest37', 'interest38', 'interest39', 'interest40', 'interest41', 'interest42', 'interest43', 'interest44', 'interest45', 'interest46', 'interest47', 'interest48', 'interest49', 'interest50', 'interest51', 'interest52', 'interest53', 'interest54', 'interest55', 'interest56', 'interest57', 'interest58', 'interest59', 'kw10', 'kw11', 'kw12', 'kw13', 'kw14', 'kw15', 'kw16', 'kw17', 'kw18', 'kw19', 'kw20', 'kw21', 'kw22', 'kw23', 'kw24', 'kw25', 'kw26', 'kw27', 'kw28', 'kw29', 'kw30', 'kw31', 'kw32', 'kw33', 'kw34', 'kw35', 'kw36', 'kw37', 'kw38', 'kw39', 'topic10', 'topic11', 'topic12', 'topic13', 'topic14', 'topic15', 'topic16', 'topic17', 'topic18', 'topic19', 'topic20', 'topic21', 'topic22', 'topic23', 'topic24', 'topic25', 'topic26', 'topic27', 'topic28', 'topic29', 'topic30', 'topic31', 'topic32', 'topic33', 'topic34', 'topic35', 'topic36', 'topic37', 'topic38', 'topic39', 'appIdInstall0', 'appIdInstall1', 'appIdInstall2', 'appIdInstall3', 'appIdInstall4', 'appIdInstall5', 'appIdInstall6', 'appIdInstall7', 'appIdInstall8', 'appIdInstall9', 'appIdAction0', 'appIdAction1', 'appIdAction2', 'appIdAction3', 'appIdAction4', 'appIdAction5', 'appIdAction6', 'appIdAction7', 'appIdAction8', 'appIdAction9'] ################################################## # 特征工程数据 # ################################################## # engineered_features.csv # 来源:对appIdInstall、appIdAction进行0-1处理,有值为1缺省为0;对id特征进行计数处理,得到相应featureCount特征;对部分特征进行组合计数处理, # 得到相应feature1_feature2或feature1_feature2_feature3特征 # 使用:保持train.csv与test1.csv拼接顺序,可直接concat # 行数:11064804 (包括标题行) # 列数:121 fe1Cols = ['appIdInstall.1', 'appIdAction.1', 'aidCount', 'advertiserIdCount', 'campaignIdCount', 'adCategoryIdCount', 'productIdCount', 'uidCount', 'aidCount_uidCount', 'aidCount_productType', 'aidCount_age', 'aidCount_gender', 'aidCount_education', 'aidCount_consumptionAbility', 'aidCount_appIdInstall.1', 'aidCount_carrier', 'aidCount_house', 'aidCount_marriageStatus.1', 'aidCount_ct.1', 'aidCount_os.1', 'uidCount_productType', 'uidCount_age', 'uidCount_gender', 'uidCount_education', 'uidCount_consumptionAbility', 'uidCount_appIdInstall.1', 'uidCount_carrier', 'uidCount_house', 'uidCount_marriageStatus.1', 'uidCount_ct.1', 'uidCount_os.1', 'productType_age', 'productType_gender', 'productType_education', 'productType_consumptionAbility', 'productType_appIdInstall.1', 'productType_carrier', 'productType_house', 'productType_marriageStatus.1', 'productType_ct.1', 'productType_os.1', 'age_gender', 'age_education', 'age_consumptionAbility', 'age_appIdInstall.1', 'age_carrier', 'age_house', 'age_marriageStatus.1', 'age_ct.1', 'age_os.1', 'gender_education', 'gender_consumptionAbility', 'gender_appIdInstall.1', 'gender_carrier', 'gender_house', 'gender_marriageStatus.1', 'gender_ct.1', 'gender_os.1', 'education_consumptionAbility', 'education_appIdInstall.1', 'education_carrier', 'education_house', 'education_marriageStatus.1', 'education_ct.1', 'education_os.1', 'consumptionAbility_appIdInstall.1', 'consumptionAbility_carrier', 'consumptionAbility_house', 'consumptionAbility_marriageStatus.1', 'consumptionAbility_ct.1', 'consumptionAbility_os.1', 'appIdInstall.1_carrier', 'appIdInstall.1_house', 'appIdInstall.1_marriageStatus.1', 'appIdInstall.1_ct.1', 'appIdInstall.1_os.1', 'carrier_house', 'carrier_marriageStatus.1', 'carrier_ct.1', 'carrier_os.1', 'house_marriageStatus.1', 'house_ct.1', 'house_os.1', 'marriageStatus.1_ct.1', 'marriageStatus.1_os.1', 'ct.1_os.1', 'age_gender_education', 'age_gender_consumptionAbility', 'age_gender_house', 'age_gender_marriageStatus.1', 'age_gender_os.1', 'age_education_consumptionAbility', 'age_education_house', 'age_education_marriageStatus.1', 'age_education_os.1', 'age_consumptionAbility_house', 'age_consumptionAbility_marriageStatus.1', 'age_consumptionAbility_os.1', 'age_house_marriageStatus.1', 'age_house_os.1', 'age_marriageStatus.1_os.1', 'gender_education_consumptionAbility', 'gender_education_house', 'gender_education_marriageStatus.1', 'gender_education_os.1', 'gender_consumptionAbility_house', 'gender_consumptionAbility_marriageStatus.1', 'gender_consumptionAbility_os.1', 'gender_house_marriageStatus.1', 'gender_house_os.1', 'gender_marriageStatus.1_os.1', 'education_consumptionAbility_house', 'education_consumptionAbility_marriageStatus.1', 'education_consumptionAbility_os.1', 'education_house_marriageStatus.1', 'education_house_os.1', 'education_marriageStatus.1_os.1', 'consumptionAbility_house_marriageStatus.1', 'consumptionAbility_house_os.1', 'consumptionAbility_marriageStatus.1_os.1', 'house_marriageStatus.1_os.1'] # engineered_features_2.csv # 来源:对部分强特征进行组合计数处理,得到相应feature1_feature2或feature1_feature2_feature3特征 # 使用:保持train.csv与test1.csv拼接顺序,可直接concat # 行数:11064804 (包括标题行) # 列数:35 fe2Cols = ['aid_ct.1', 'aid_campaignId', 'aid_advertiserId', 'aid_marriageStatus.1', 'aid_age', 'ct.1_campaignId', 'ct.1_advertiserId', 'ct.1_marriageStatus.1', 'ct.1_age', 'campaignId_advertiserId', 'campaignId_marriageStatus.1', 'campaignId_age', 'advertiserId_marriageStatus.1', 'advertiserId_age', 'marriageStatus.1_age', 'aid_ct.1_campaignId', 'aid_ct.1_advertiserId', 'aid_ct.1_marriageStatus.1', 'aid_ct.1_age', 'aid_campaignId_advertiserId', 'aid_campaignId_marriageStatus.1', 'aid_campaignId_age', 'aid_advertiserId_marriageStatus.1', 'aid_advertiserId_age', 'aid_marriageStatus.1_age', 'ct.1_campaignId_advertiserId', 'ct.1_campaignId_marriageStatus.1', 'ct.1_campaignId_age', 'ct.1_advertiserId_marriageStatus.1', 'ct.1_advertiserId_age', 'ct.1_marriageStatus.1_age', 'campaignId_advertiserId_marriageStatus.1', 'campaignId_advertiserId_age', 'campaignId_marriageStatus.1_age', 'advertiserId_marriageStatus.1_age'] # fe_ff.csv # 来源:统计了各向量特征长度以及总长度,反映用户填写完整程度;统计了广告主-推广计划-广告之间的层级对应数量关系 # 使用:保持train.csv与test1.csv拼接顺序,可直接concat # 行数:11064804 (包括标题行) # 列数:14 feffCols = ['interest1_length', 'interest2_length', 'interest3_length', 'interest4_length', 'interest5_length', 'kw1_length', 'kw2_length', 'kw3_length', 'topic1_length', 'topic2_length', 'topic3_length', 'vector_num', 'map_advertiserId_campaignId', 'map_campaignId_aid'] # nlp_features.csv # 来源:https://github.com/LightR0/Tencent_Ads_2018 # 使用:保持train.csv与test1.csv拼接顺序,可直接concat # 行数:11064804 (包括标题行) # 列数:10 nlpCols = ['appIdInstall_score', 'appIdAction_score', 'interest1_score', 'interest2_score', 'interest5_score', 'kw1_score', 'kw2_score', 'topic1_score', 'topic2_score', 'campaignId_active_aid'] # w2v_features.csv # 来源:从processed_data.csv中提取的w2v特征 # 使用:保持train.csv与test1.csv拼接顺序,可直接concat # 行数:11064804 (包括标题行) # 列数:56 w2vCols = ['kw21', 'kw26', 'kw25', 'kw23', 'kw20', 'topic24', 'kw28', 'kw22', 'kw27', 'kw24', 'topic20', 'topic27', 'kw29', 'topic23', 'topic26', 'interest12', 'interest26', 'interest21', 'kw18', 'topic28', 'topic16', 'topic22', 'interest28', 'topic14', 'kw17', 'topic25', 'interest27', 'interest23', 'interest25', 'kw16', 'topic21', 'interest59', 'topic10', 'kw10', 'interest11', 'interest29', 'kw19', 'topic29', 'kw14', 'kw12', 'interest51', 'topic11', 'interest17', 'kw13', 'interest53', 'topic19', 'kw11', 'topic17', 'interest20', 'topic15', 'interest55', 'kw15', 'topic13', 'interest13', 'interest10', 'interest24'] # CTR_features.csv # 来源:提取部分重要性高的特征的转化率,得到相应feature_CTR特征 # 使用:保持train.csv与test1.csv拼接顺序,可直接concat # 行数:11064804 (包括标题行) # 列数:29 ctrCols = ['aid_CTR', 'ct.1_CTR', 'campaignId_CTR', 'advertiserId_CTR', 'marriageStatus.1_CTR', 'interest1_length_CTR', 'interest2_length_CTR', 'age_CTR', 'vector_num_CTR', 'kw2_length_CTR', 'interest5_length_CTR', 'education_CTR', 'adCategoryId_CTR', 'productType_age_CTR', 'uidCount_age_CTR', 'age_gender_consumptionAbility_CTR', 'uidCount_consumptionAbility_CTR', 'aidCount_gender_CTR', 'age_education_marriageStatus.1_CTR', 'aidCount_age_CTR', 'ct.1_marriageStatus.1_age_CTR', 'age_gender_os.1_CTR', 'age_consumptionAbility_house_CTR', 'ct.1_os.1_CTR', 'age_consumptionAbility_os.1_CTR', 'age_gender_CTR', 'age_gender_education_CTR', 'age_education_consumptionAbility_CTR', 'advertiserId_age_CTR']
""" This module contains some constants that can be reused ==================================== Copyright SSS_Says_Snek, 2021-present ==================================== """ __version__ = "2.0" __license__ = "MIT" __name__ = "hisock" __copyright__ = "SSS-Says-Snek, 2021-present" __author__ = "SSS-Says-Snek"
class Flight: def __init__(self, origin, destination, month, fare, currency, fare_type, date): self.origin = origin self.destination = destination self.month = month self.fare = fare self.currency = currency self.fare_type = fare_type self.date = date def __str__(self): return self.origin + self.destination + self.month + self.fare + self.currency + self.fare_type + self.date
""" --- Day 3: Spiral Memory --- You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this: 17 16 15 14 13 18 5 4 3 12 19 6 1 2 11 20 7 8 9 10 21 22 23---> ... While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1. For example: Data from square 1 is carried 0 steps, since it's at the access port. Data from square 12 is carried 3 steps, such as: down, left, left. Data from square 23 is carried only 2 steps: up twice. Data from square 1024 must be carried 31 steps. How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port? Your puzzle answer was 438. --- Part Two --- As a stress test on the system, the programs here clear the grid and then store the value 1 in square 1. Then, in the same allocation order as shown above, they store the sum of the values in all adjacent squares, including diagonals. So, the first few squares' values are chosen as follows: Square 1 starts with the value 1. Square 2 has only one adjacent filled square (with value 1), so it also stores 1. Square 3 has both of the above squares as neighbors and stores the sum of their values, 2. Square 4 has all three of the aforementioned squares as neighbors and stores the sum of their values, 4. Square 5 only has the first and fourth squares as neighbors, so it gets the value 5. Once a square is written, its value does not change. Therefore, the first few squares would receive the following values: 147 142 133 122 59 304 5 4 2 57 330 10 1 1 54 351 11 23 25 26 362 747 806---> ... What is the first value written that is larger than your puzzle input? Your puzzle answer was 266330. Both parts of this puzzle are complete! They provide two gold stars: ** At this point, you should return to your advent calendar and try another puzzle. Your puzzle input was 265149. """ def calculate_spiral(): yield 1, 0, 0 yield 2, 1, 0 x, y = 1, 1 digit = 2 direction = "right" while True: digit += 1 yield digit, x, y if x == y and x > 0 < y: # top right corner direction = "left" elif abs(x) == y and x < 0 < y: # top left corner direction = "down" elif x == y and x < 0 > y: # bottom left corner direction = "right" elif x == abs(y) and x > 0 > y: # bottom right corner direction = "up" x += 1 digit += 1 yield digit, x, y if direction == "right": x += 1 if direction == "left": x -= 1 if direction == "up": y += 1 if direction == "down": y -= 1 def calculate_manhattan_distance(to_digit): # Manhattan Distance between two points (x1, y1) and (x2, y2) is: |x1 – x2| + |y1 – y2| last = None for coordinates in calculate_spiral(): if coordinates[0] == to_digit: last = coordinates break last = last[1:] return sum(map(abs, last)) def stress_test(end_sum): cache = { (0, 0): 1, (1, 0): 1 } for coordinates in calculate_spiral(): if coordinates[0] > 2: position = coordinates[1:] adjacent_squares = filter( lambda p: p in cache, [ (position[0] - 1, position[1]), (position[0] + 1, position[1]), (position[0], position[1] - 1), (position[0], position[1] + 1), (position[0] + 1, position[1] + 1), (position[0] - 1, position[1] + 1), (position[0] - 1, position[1] - 1), (position[0] + 1, position[1] - 1), ]) sum_of_values = sum(map(lambda p: cache[p], adjacent_squares)) cache[position] = sum_of_values if sum_of_values > end_sum: return (sum_of_values, *position) if __name__ == "__main__": puzzle = 265149 print(f"part1: {calculate_manhattan_distance(puzzle)}") print(f"part2: {stress_test(puzzle)}")
# Users to create/delete users = [ {'name': 'user1', 'password': 'passwd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': True}, {'name': 'user3', 'password': 'paafdssswd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': False} ] # Roles to create/delete roles = [ {'name': 'SomeRole'} ] # Keypairs to create/delete # Connected to user's list keypairs = [ {'name': 'key1', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7' '/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly' '8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq' '+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkW' 'mTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmk' 'SHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'}, {'name': 'key2', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7' '/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly' '8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq' '+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkW' 'mTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmk' 'SHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'} ] # Images to create/delete images = [ {'name': 'image1', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/ci' 'rros-0.3.3-x86_64-disk.img', 'is_public': True}, {'name': 'image2', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/ci' 'rros-0.3.3-x86_64-disk.img', 'container_format': 'bare', 'disk_format': 'qcow2', 'is_public': False} ] # Flavors to create/delete flavors = [ {'name': 'm1.tiny'} # {'name': 'flavorname1', 'disk': '7', 'ram': '64', 'vcpus': '1'}, # Disabled for now, but in the future we need to generate non-pubic flavors # {'name': 'flavorname3', 'disk': '10', 'ram': '32', 'vcpus': '1', # 'is_public': False}, # {'name': 'flavorname2', 'disk': '5', 'ram': '48', 'vcpus': '2'} ] # Security groups to create/delete security_groups = [{'security_groups': [ {'name': 'sg11', 'description': 'Blah blah group', 'rules': [{'ip_protocol': 'icmp', 'from_port': '0', 'to_port': '255', 'cidr': '0.0.0.0/0'}, {'ip_protocol': 'tcp', 'from_port': '80', 'to_port': '80', 'cidr': '0.0.0.0/0'}]}, {'name': 'sg12', 'description': 'Blah blah group2'}]}] # Networks to create/delete # Connected to tenants ext_net = {'name': 'shared_net', 'admin_state_up': True, 'shared': True, 'router:external': True} networks = [ {'name': 'mynetwork1', 'admin_state_up': True}, ] # Subnets to create/delete ext_subnet = {'cidr': '172.18.10.0/24', 'ip_version': 4} subnets = [ {'cidr': '10.4.2.0/24', 'ip_version': 4}, ] # VM's to create/delete vms = [ {'name': 'server1', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server2', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server3', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server4', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server5', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server6', 'image': 'image1', 'flavor': 'm1.tiny'} ] routers = [ { 'router': { 'name': 'ext_router', 'external_gateway_info': { 'network_id': 'shared_net'}, 'admin_state_up': True}} ] # VM's snapshots to create/delete snapshots = [ {'server': 'server2', 'image_name': 'asdasd'} ] # Cinder images to create/delete cinder_volumes = [ {'name': 'cinder_volume1', 'size': 1}, {'name': 'cinder_volume2', 'size': 1, 'server_to_attach': 'server2', 'device': '/dev/vdb'} ] # Cinder snapshots to create/delete cinder_snapshots = [ {'display_name': 'snapsh1', 'volume_id': 'cinder_volume1'} ] # Emulate different VM states vm_states = [ {'name': 'server1', 'state': 'error'}, {'name': 'server2', 'state': 'stop'}, {'name': 'server3', 'state': 'suspend'}, {'name': 'server4', 'state': 'pause'}, {'name': 'server5', 'state': 'resize'} ] # Client's versions NOVA_CLIENT_VERSION = '1.1' GLANCE_CLIENT_VERSION = '1' NEUTRON_CLIENT_VERSION = '2.0' CINDER_CLIENT_VERSION = '1'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 15 16:13:20 2018 @author: efrem """ class Coordinate(object): def __init__(self,x,y): self.x = x self.y = y def getX(self): # Getter method for a Coordinate object's x coordinate. # Getter methods are better practice than just accessing an attribute directly return self.x def getY(self): # Getter method for a Coordinate object's y coordinate return self.y def __str__(self): return '<' + str(self.getX()) + ',' + str(self.getY()) + '>' def __eq__(self, other): return self.x == other.x and self.y == other.y def __repr__(self): return "Coordinate(%d,%d)" % (self.x, self.y)
# -*- coding: utf-8 -*- __title__ = 'ci_release_publisher' __description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases' __version__ = '0.2.0' __url__ = 'https://github.com/nurupo/ci-release-publisher' __author__ = 'Maxim Biro' __author_email__ = '[email protected]' __license__ = 'MIT' __copyright__ = 'Copyright 2018-2020 Maxim Biro'
n=1260 count=0 list=[500,100,50,10] for coin in list: count += n//coin n %= coin print(count)
#Faça um Programa que leia 5 números e informe o maior. maior = 0 i = 0 while i < 5: n = float(input("Digite um número: ")) if(n > maior): maior = n i = i + 1 print("O maior número é {}".format(maior))
bms_thresholds = {'temperature': {'min': 0, 'max': 45}, 'soc': {'min': 20, 'max': 80}, 'charging_rate': {'min': 0, 'max': 0.8}} bms_system_languages = {'en': 'BMS System configured with English', 'de':'BMS-System auf Englisch konfiguriert'} bms_system_temperature_unit = {'C': 'Celcius', 'F':'Fahrenheit'} bms_system_temperature_unit_notification = {'en': 'BMS Temperature measurement unit is set to ', 'de':'Die BMS-Temperaturmesseinheit ist auf eingestellt '} bms_input_param_status = {'en':['UNKNOWN PARAMETER','INVALID PARAMETER VALUE'], 'de':['UNBEKANNTER PARAMETER','UNGÜLTIGER PARAMETERWERT']} bms_console_output_messages = {'en':['OVERLIMIT', 'UNDERLIMIT', 'All Parameters are OK','BMS Operating in Unsafe Condition:'], 'de':['ÜBER DEM LIMIT','UNTERBEGRENZUNG', 'Alle Parameter sind in Ordnung','BMS arbeitet in unsicherem Zustand:']} bms_hazard_warning_message = {'en': '!!! WARNING !!!','de': '!!! WARNUNG !!!'} bms_controller_flags = {'low':1,'high':0} bms_controller_output_messages ={ 'en': {'temperature':['Turn ON BMS Cooler', 'Turn ON BMS Heater'], 'soc':['CUT OFF BMS Charging','SWITCH BMS TO POWER SAVING MODE'], 'charging_rate':['Decrease Charging Current','Increase Charging Current']}, 'de': {'temperature': ['Schalten Sie den BMS-Kühler ein', 'Schalten Sie die BMS-Heizung ein'], 'soc': ['BMS-Aufladung abschalten', 'Schalten Sie BMS in den Energiesparmodus'], 'charging_rate': ['Ladestrom verringern', 'Ladestrom erhöhen']} }
# MEDIUM # inorder traversal using iterative # Time O(N) Space O(H) class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: return self.iterative(root,k) self.index= 1 self.result = -1 self.inOrder(root,k) return self.result def iterative(self,root,k): stack = [] i = 1 while root or stack: while root: stack.append(root) root = root.left curr = stack.pop() # print(curr.val) if i == k: return curr.val i += 1 if curr.right: root = curr.right def inOrder(self,root,k): if not root: return self.inOrder(root.left,k) # print(root.val,self.index) if self.index == k: self.result = root.val self.index += 1 self.inOrder(root.right,k)
def solution(N): A, B = 0, 0 mult = 1 while N > 0: q, r = divmod(N, 10) if r == 5: A, B = A + mult * 2, B + mult * 3 elif r == 0: A, B = A + mult, B + mult * 9 q -= 1 else: A, B = A + mult, B + mult * (r - 1) mult *= 10 N = q print(A+B) return str(A) + ' ' + str(B) def main(): T = int(input()) for t in range(T): N = int(input()) answer = solution(N) print('Case #' + str(t+1) + ': ' + answer) if __name__ == '__main__': main()
def sum_digits(n): s=0 while n: s += n % 10 n /= 10 return s def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) def sum_factorial_digits(n): return sum_digits(factorial(n)) def main(): print(sum_factorial_digits(10)) print(sum_factorial_digits(100)) print(sum_factorial_digits(500)) if __name__ == "__main__": #test() main()
username = input("Please enter your name: ") lastLength = 0 while True: f = open('msgbuffer.txt', 'r+') messages = f.readlines() mailboxSize = len(messages) if mailboxSize > 0 and mailboxSize > lastLength: print( messages[-1] ) lastLength = mailboxSize message = input("|") if message == 'read': print( messages[-1] ) f.write( '%s:%s' % (username, message) ) f.write('\n') f.close()
def escape_reserved_characters(query): """ :param query: :return: escaped query Note: < and > can’t be escaped at all. The only way to prevent them from attempting to create a range query is to remove them from the query string entirely. """ reserved_characters = ['+', '-', '=', '&&', '||', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '\\', '/'] s = list(query) for i, c in enumerate(s): if c in ['<', '>']: s[i] = '' elif c in reserved_characters: if c == '\000': s[i] = '\\000' else: s[i] = '\\' + c return ''.join(s)
#! /usr/bin/env python # _*_ coding:utf-8 _*_ class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree(self, p, q): if not p and not q: return True elif not p or not q: return False elif p.val != q.val: return False if self.isSameTree(p.left, q.left): return self.isSameTree(p.right, q.right) else: return False def gen_tree(nums): for i, n in enumerate(nums): node = TreeNode(n) nums[i] = node root = nums[0] if __name__ == '__main__': so = Solution() def test(): pass test()
class disjoint_set: def __init__(self,vertex): self.parent = self self.rank = 0 self.vertex = vertex def find(self): if self.parent != self: self.parent = self.parent.find() return self.parent def joinSets(self,otherTree): root = self.find() otherTreeRoot = otherTree.find() if root == otherTreeRoot: return if root.rank < otherTreeRoot.rank: root.parent = otherTreeRoot elif otherTreeRoot.rank < root.rank: otherTreeRoot.parent = root else: otherTreeRoot.parent = root root.rank += 1
def get_test_data(): return { "contact": { "name": "Paul Kempa", "company": "Baltimore Steel Factory" }, "invoice": { "items": [ { "quantity": 12, "description": "Item description No.0", "unitprice": 12000.3, "linetotal": 20 }, { "quantity": 1290, "description": "Item description No.0", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.1", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.2", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.3", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.4", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.5", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.6", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.7", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.8", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.9", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.10", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.11", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.12", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.13", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.14", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.15", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.16", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.17", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.18", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.19", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.20", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.21", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.22", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.23", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.24", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.25", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.26", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.27", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.28", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.29", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.30", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.31", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.32", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.33", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.34", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.35", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.36", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.37", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.38", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.39", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.40", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.41", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.42", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.43", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.44", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.45", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.46", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.47", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.48", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.49", "unitprice": 12.3, "linetotal": 20000 } ], "total": 50000000.01 } }
class Node: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self, *args, **kwargs): self.head = Node(None) def appende(self, data): node = Node(data) node.next = self.head self.head = node # Print linked list def print_my_list(self): node = self.head while node.next is not None: print(node.data, end=" ") node = node.next # count number of node in linked list def countNodes(self): count = 0 node = self.head while node.next is not None: count += 1 node = node.next return count def Kth(self, k): # Count nodes in linked list n = self.countNodes() # check if k is valid if n < k: return if (2 * k - 1) == n: return x = self.head x_prev = Node(None) for i in range(k - 1): x_prev = x x = x.next y = self.head y_prev = Node(None) for i in range(n - k): y_prev = y y = y.next if x_prev is not None: x_prev.next = y # Same thing applies to y_prev if y_prev is not None: y_prev.next = x temp = x.next x.next = y.next y.next = temp # Change head pointers when k is 1 or n if k == 1: self.head = y if k == n: self.head = x if __name__ == '__main__': My_List = LinkedList() for i in range(8, 0, -1): My_List.appende(i) My_List.appende(7) My_List.appende(6) My_List.appende(5) My_List.appende(4) My_List.appende(3) My_List.appende(2) My_List.appende(1) My_List.print_my_list() for i in range(1, 9): My_List.Kth(i) print("Modified List for k = ", i) My_List.print_my_list() print("\n")
# # PySNMP MIB module Wellfleet-NPK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NPK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:34:31 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) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibIdentifier, Gauge32, Bits, Counter32, NotificationType, IpAddress, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Counter64, TimeTicks, ModuleIdentity, Integer32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "Bits", "Counter32", "NotificationType", "IpAddress", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Counter64", "TimeTicks", "ModuleIdentity", "Integer32", "ObjectIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") wfGameGroup, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfGameGroup") wfNpkBase = MibIdentifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8)) wfNpkBaseCreate = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseCreate.setStatus('mandatory') wfNpkBaseHash = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 2), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseHash.setStatus('mandatory') wfNpkBaseLastMod = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseLastMod.setStatus('mandatory') mibBuilder.exportSymbols("Wellfleet-NPK-MIB", wfNpkBase=wfNpkBase, wfNpkBaseHash=wfNpkBaseHash, wfNpkBaseLastMod=wfNpkBaseLastMod, wfNpkBaseCreate=wfNpkBaseCreate)
def retrieveDB_data(db, option, title): data_ref = db.collection(option).document(title) docs = data_ref.get() return docs.to_dict() async def initDB(db, objectList, objectDb, firestore): if objectList is None: data = {"create": "create"} objectDb.set(data) objectDb.update({"create": firestore.DELETE_FIELD}) return async def checkChannel(db, firestore, channelId, guildId): channel_fetch = retrieveDB_data(db, option="channel-list", title=str(guildId)) channel_DB_init = db.collection("channel-list").document(str(guildId)) await initDB(db, channel_fetch, channel_DB_init, firestore) try: channelVerify = channel_fetch[f"{channelId}"] except (KeyError, TypeError): return return channelVerify async def checkUser(db, firestore, userId, guildId): user_projects = retrieveDB_data(db, option="user-projects", title=str(guildId)) user_projectsDB = db.collection("user-projects").document(str(guildId)) await initDB(db, user_projects, user_projectsDB, firestore) try: userVerify = user_projects[str(userId)] except (KeyError, TypeError): return return userVerify async def check_existingProject(db, mention, project, guildId): user_projects = retrieveDB_data(db, option="user-projects", title=str(guildId)) userProject = user_projects[str(mention)] if str(userProject) != str(project): return userProject return
class Board: def __init__(self, data): self.rows = data self.marked = [[0 for _ in range(0, 5)] for _ in range(0, 5)] def __str__(self): """String representation""" res = "BOARD:" for r in self.rows: res = res + "\n" + str(r) res = res + "\nMARKED:" for r in self.marked: res = res + "\n" + str(r) return res def mark_number(self, number:int) -> None : """ Marks a number in the bingo board. :param number: Number to be looked up in the board's numbers. :return: None """ for i, row in enumerate(self.rows): for j, cell in enumerate(row): if cell == number: self.marked[i][j] = 1 def check_winning_conditions(self) -> bool: """ Checks whether a winning condition (5x "1" in a row or a columN) is fulfilled in the board. :return: Boolean, signifying win/loss """ for row in self.marked: # sum rows if sum(row) == 5: return True for i in range(0, 5): # sum columns if sum([x[i] for x in self.marked]) == 5: return True return False def calculate_score(self) -> int: """ Calculates sum of unmarked cells. :return: score """ score = 0 for i, row in enumerate(self.marked): for j, cell in enumerate(row): if cell == 0: # sum unmarked score += self.rows[i][j] return score
BLACK = -999 DEFAULT = 0 NORMAL = 1 PRIVATE = 10 ADMIN = 21 OWNER = 22 WHITE = 51 SUPERUSER = 999 SU = SUPERUSER
################################################# Cars = [["Lamborghini", 1000000, 2, 40000], ["Ferrari", 1500000, 2.5, 50000], ["BMW", 800000, 1.5, 20000]] ################################################# print("#"*80) print("#" + "Welcome to XYZ Car Dealership".center(78) + "#") print("#"*80 + "\n") while True: print("#"*80) print("#" + "What Would You Like To Do Today?".center(78) + "#") print("#" + "A) Buy A Car ".center(78) + "#") print("#" + "B) Rent A Car".center(78) + "#") print("#"*80 + "\n") mode = input("Choose Option (A/B):\t").lower() while mode not in "ab" and mode != "ab": mode = input("Choose Option (A/B):\t").lower() if mode == "a": print("#"*80) print("#" + "Choose A Car".center(78) + "#") print("#" + "1) Lamborghini ".center(78) + "#") print("#" + "2) Ferrari ".center(78) + "#") print("#" + "3) BMW ".center(78) + "#") print("#" + "4) Input Your own Car".center(78) + "#") print("#"*80) op = int(input("Choose Option: ")) while op != 1 and op != 2 and op != 3 and op != 4: op = int(input("Choose Option: ")) if op == 4: buyPrice = int(input("Enter Buy Price of Car: ")) maintainanceCostPercentage = int(input("Enter Annual Maintainance Percentage of Car: ")) years = int(input("How many Years: ")) else: i = op-1 print("Checking for " + Cars[i][0] + "...") years = int(input("How many Years: ")) buyPrice = Cars[i][1] maintainanceCostPercentage = Cars[i][2] Price = buyPrice + buyPrice * (years-1) * maintainanceCostPercentage / 100 p = "Buy For $" + str(Price) print("\n" + "#"*80) print("#" + "Receipt".center(78) + "#") print("#" + "-------".center(78) + "#") print("#" + "".center(78) + "#") print("#" + p.center(78) + "#") print("#"*80) elif mode == "b": print("#"*80) print("#" + "Choose A Car".center(78) + "#") print("#" + "1) Lamborghini ".center(78) + "#") print("#" + "2) Ferrari ".center(78) + "#") print("#" + "3) BMW ".center(78) + "#") print("#" + "4) Input Your own Car".center(78) + "#") print("#"*80) op = int(input("Choose Option: ")) while op != 1 and op != 2 and op != 3 and op != 4: op = int(input("Choose Option: ")) if op == 4: rent = int(input("Enter monthly Rental Price of Car: ")) months = int(input("How many Months: ")) else: i = op-1 months = int(input("How many Months: ")) rent = Cars[i][3] Price = months * rent p = "\n\nPrice to rent for " + str(months) + " months is $" + str(Price) print("\n" + "#"*80) print("#" + "Receipt".center(78) + "#") print("#" + "-------".center(78) + "#") print("#" + "".center(78) + "#") print("#" + p.center(78) + "#") print("#"*80) if input("Would You like to Exit? (y/n) ").lower() == "y": break print("#"*80) print("#" + "Thank You!".center(78) + "#") print("#"*80)
n1 = 0 n2 = 0 choice = 4 high_number = n1 while choice != 5: while choice == 4: print('=' * 50) n1 = int(input('Choose a number: ')) n2 = int(input('Choose another number: ')) if n1 > n2: high_number = n1 else: high_number = n2 print('=' * 45) print('What do you want to do with the numbers?') print('[1] to add them up.') print('[2] to multiply them.') print('[3] to find the higher number.') print('[4] to choose new numbers.') print('[5] nothing, quit the program.') choice = int(input('')) if choice == 1: print(f'The sum of the entered values is {n1 + n2}.') choice = 5 elif choice == 2: print(f'The product of the numbers entered is {n1 * n2}') choice = 5 elif choice == 3: print(f'The higher number entered was {high_number}') choice = 5
white = { "Flour": "100", "Water": "65", "Oil": "4", "Salt": "2", "Yeast": "1.5" }
class Row: def __init__(self, title=None, columns=None, properties=None): self.title = title self.columns = columns or [] self.properties = properties or [] def __str__(self): return str(self.title) def __len__(self): return len(self.title or '') def __iter__(self): yield from self.columns def add_cell(self, cell): self.columns.append(cell) def add_property(self, property): self.properties.append(property)
"""6.1.5 Multiple Definition of Product Group ID For each Product Group ID (type /$defs/product_group_id_t) Product Group elements (/product_tree/product_groups[]) it must be tested that the group_id was not already defined within the same document. The relevant path for this test is: /product_tree/product_groups[]/group_id Example 44 which fails the test: "product_tree": { "full_product_names": [ { "product_id": "CSAFPID-9080700", "name": "Product A" }, { "product_id": "CSAFPID-9080701", "name": "Product B" }, { "product_id": "CSAFPID-9080702", "name": "Product C" } ], "product_groups": [ { "group_id": "CSAFGID-1020300", "product_ids": [ "CSAFPID-9080700", "CSAFPID-9080701" ] }, { "group_id": "CSAFGID-1020300", "product_ids": [ "CSAFPID-9080700", "CSAFPID-9080702" ] } ] } CSAFGID-1020300 was defined twice. """ ID = (6, 1, 5) TOPIC = 'Multiple Definition of Product Group ID' CONDITION_PATH = '/product_tree/product_groups[]/group_id' CONDITION_JMES_PATH = CONDITION_PATH.lstrip('/').replace('/', '.') PATHS = (CONDITION_PATH,)
#!/usr/bin/env python3 def readFile(filename): #READFILE reads a file and returns its entire contents # file_contents = READFILE(filename) reads a file and returns its entire # contents in file_contents # # Load File with open(filename) as fid: file_contents = fid.read() #end return file_contents #end
#Entradas in json array_input = [ { '15' : 50.00 , '3' : 10.00, '5.30' : 15.50 }, { '10' : 35.00 , '7' : 14.00, '5.30' : 75.30 } ] #Código de cada peça 1 key = array_input[0] n_keys = [ n for n in key ] print("Código de uma peça 1 :", n_keys[0]) print("Todas as keys da peça 1: ", " ".join(n_keys)) print("Numero de peças presente: ", len(key) )
# values_only # Function which accepts a dictionary of key value pairs and returns a new flat list of only the values. # # Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and # returns a new list by appending the values to it. Best used on 1 level-deep key:value pair dictionaries and not # nested data-structures. def values_only(dictionary): lst = [] for v in dictionary.values(): lst.append(v) # for k, v in dictionary.items(): # lst.append(v) return lst ages = { "Peter": 10, "Isabel": 11, "Anna": 9, } print(values_only(ages)) # [10, 11, 9]
# Example 1: Showing the Root Mean Squared Error (RMSE) metric. Penalises large residuals # Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {"objective":"reg:linear", "max_depth":4} # Perform cross-validation: cv_results cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='rmse', as_pandas=True, seed=123) # Print cv_results print(cv_results) # Extract and print final boosting round metric print((cv_results["test-rmse-mean"]).tail(1)) # Example 2: Showing the Mean Absolute Error (MAE) metric # Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {"objective":"reg:linear", "max_depth":4} # Perform cross-validation: cv_results cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='mae', as_pandas=True, seed=123) # Print cv_results print(cv_results) # Extract and print final boosting round metric print((cv_results["test-mae-mean"]).tail(1))
buildcode=""" function Get-ExternalIP(){ $extern_ip_mask = @() while ($response.IPAddress -eq $null){ $response = Resolve-DnsName -Name myip.opendns.com -Server resolver1.opendns.com Start-Sleep -s 1 } $octet1, $octet2, $octet3, $octet4 = $response.IPAddress.Split(".") $extern_ip_mask += $response.IPAddress $extern_ip_mask += [string]$octet1 + "." + [string]$octet2 + "." + [string]$octet3 + ".0" $extern_ip_mask += [string]$octet1 + "." + [string]$octet2 + ".0.0" $extern_ip_mask += [string]$octet1 + ".0.0.0" return $extern_ip_mask } """ callcode=""" $key_combos += ,(Get-ExternalIP) """
# Python avançado função map def dobro(x): return x*2 valor = [1, 2, 3, 4, 5] valor_dobrado = map(dobro, valor) """ for v in valor_dobrado: print(v) """ # Convertendo em lista: valor_dobrado = list(valor_dobrado) print(valor_dobrado)
""" Constants definition """ ########################################## ## Configurable constants # AREA_WIDTH = 40.0 # width (in meters) of the drawing area CANVAS_WIDTH = 900 # width (in pixels) of the drawing area CANVAS_HEIGHT = 700 # height (in pixels) of the drawing area SCROLLABLE_CANVAS_WIDTH = 4 * CANVAS_WIDTH # scrollable width (in pxls) of the drawing area SCROLLABLE_CANVAS_HEIGHT = 4 * CANVAS_HEIGHT # scrollable height (in pxls) of the drawing area TRACK_WIDTH = 3.0 # track width in meters WAYPOINTS_RADIUS = 5 # radius (in pixels) of the circle corresponding to a waypoint CONE_RADIUS = 0.3 # radius (in meters) of the cones DEFAULT_SPACING_CONES = 3.0 # defaut distance between each cones DEFAULT_SPACING_ORANGE = 0.5 # default distance between orange cones DEFAULT_TURNING_RADIUS = 10.0 # default maximum turning radius (in m) DEFAULT_GRID_SIZE = 1.0 INIT_OFFSET_X = -2.0 # initial offset for the starting pose (along longitudinal axis) INIT_OFFSET_Y = 0.0 # initial offset for the starting pose (along lateral axis) INIT_OFFSET_YAW = 0.0 # initial offset for the starting pose (yaw, in degrees) ########################################## ## Useful constants # ADD_STATE = 'add' # Adding waypoints DELETE_STATE = 'delete' # Removing waypoints
# Author: Isabella Doyle # this is the menu def displayMenu(): print("What would you like to do?") print("\t(a) Add new student") print("\t(v) View students") print("\t(q) Quit") # strips any whitespace from the left/right of the string option = input("Please select an option (a/v/q): ").strip() return option def doAdd(students): studentDict = {} studentDict["Name"] = input("Enter student's name: ") studentDict["module"] = readModules() students.append(studentDict) def readModules(): modules = [] moduleName = input("\tEnter the first module name (blank to quit): ").strip() while moduleName != "": module = {} module["Name"] = moduleName module["Grade"] = int(input("\t\tEnter grade: ").strip()) modules.append(module) moduleName = input("\tEnter the next module name (blank to quit): ").strip() return modules def doView(): print(students) # main program students = [] selection = displayMenu() while (selection != ""): if selection == "a": doAdd(students) elif selection == "v": doView() else: print("Invalid input entered.") print(students)
def fatorial(num, show=False): """ -> Calcula o fatorial de um número. :param num: O número a ser calculado. :param show: (opcional) Mostra ou não a conta. :return: O valor do fatorial de um número num. """ print('-' * 30) f = 1 for c in range(num, 0, -1): f *= c if show: if c != 1: print(f'{c} x ', end='') else: print(f'{c} = ', end='') return f # Programa Principal print(fatorial(8, show=True)) help(fatorial)
def my_sum(n): return sum(list(map(int, n))) def resolve(): n, a, b = list(map(int, input().split())) counter = 0 for i in range(n + 1): if a <= my_sum(str(i)) <= b: counter += i print(counter)
""" Billing tests docstring """ # from django.test import TestCase # Create your tests here.
class AllJobsTerminated(Exception): """This class is a special exception that is raised if a job assigned to a thread should be properly terminated """ def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) def signal_cleanup_handler(signum, frame): """A function that cleans up the thread job properly if a specific signal is emitted. :raises: AllJobsTerminated: a job termination exception. """ raise AllJobsTerminated
""" Mergesort in Python https://en.wikipedia.org/wiki/Merge_sort """ def merge(left, right): """ Take two sorted lists and merge them into sorted list """ left_len = len(left) right_len = len(right) min_len = min(left_len, right_len) merged_lis = [] i, j = 0, 0 while i < min_len and j < min_len: if left[i] < right[j]: merged_lis.append(left[i]) i += 1 else: merged_lis.append(right[j]) j += 1 merged_lis.extend(left[i:]) merged_lis.extend(right[j:]) return merged_lis def mergesort(lis): """ Take a list and return sorted list using mergesort. Doesn't modify original list """ n = len(lis) if n == 1 or n == 0: # If list is empty or single element is present then return list (Base case of recursion) return lis mid = n//2 # Divide list in two parts: left_lis and right_lis at mid point left_lis = lis[:mid] right_lis = lis[mid:] left_lis = mergesort(left_lis) # Recursively sort left_lis by mergesort right_lis = mergesort(right_lis) # Recursively sort right_lis by mergesort mergesorted_lis = merge(left_lis, right_lis) # Merge sorted lists return mergesorted_lis def main(): assert mergesort([4, 1, 2, 3, 9]) == [1, 2, 3, 4, 9] assert mergesort([1]) == [1] assert mergesort([2, 2, 1, -1, 0, 4, 5, 2]) == [-1, 0, 1, 2, 2, 2, 4, 5] if __name__ == '__main__': main()
def main(): n=int(input()) a=list(map(int, input().split())) mp=(None,None) d=0 for i in range(0, n-1, 2): if a[i+1] - a[i] > d: mp=(i,i+1) a[mp[0]], a[mp[1]] = a[mp[1]], a[mp[0]] print(sum(a[::2])) if __name__ == '__main__': t=int(input()) for _ in range(t): main()
#!/usr/bin/env python # -*- coding: UTF-8 -*- __all__ = ["CoordinateFrame"] class CoordinateFrame(object): """ CoordinateFrame: Base coordinate frame class. Parameters ---------- frameName : str Name of the coordinate system. coordinateRanges : dict Dictionary with coordinate names as keys and two-element lists containing the lower and upper limits for the coordinate as values. """ def __init__(self, frameName="CoordinateFrame", coordinateRanges={}): self._frameName = frameName self._coordinateRanges = {} @property def frameName(self): return self._frameName @frameName.setter def frameName(self, value): self._frameName = value @frameName.deleter def frameName(self): del self._frameName @property def coordinateRanges(self): return self._coordinateRanges @coordinateRanges.setter def coordinateRanges(self, value): self._coordinateRanges = value @coordinateRanges.deleter def coordinateRanges(self): del self._coordinateRanges def convertToCartesian(self): """ This method should convert the coordinates from this frame to cartesian coordinates. This method is particularly used for plotting purposes. Throws NotImplementedError if not defined. """ raise NotImplementedError("convertToCartesian is not defined.") def surfaceElement(self): """ This method should calculate the surface element for this coordinate frame. This method is used when integrating over the surface of an asteroid. Throws NotImplementedError if not defined. """ raise NotImplementedError("surfaceElement is not defined.")
x = int(input('Enter an integer:')) y = int(input('Enter an integer:')) if x ^ y!=0: print(x,' and ', y, ' are different') else: print(x,' and ', y, ' are same')
#!/usr/bin/env python ####################################### # Installation module for AttackSurfaceMapper ####################################### DESCRIPTION="This module will install/update Attack Surface Mapper (ASM) by Andreas Georgiou - A tool that aim to automate the recon process" AUTHOR="Andrew Schwartz" INSTALL_TYPE="GIT" REPOSITORY_LOCATION="https://github.com/superhedgy/AttackSurfaceMapper.git" INSTALL_LOCATION="ASM" DEBIAN="python3,pip" AFTER_COMMANDS="cd {INSTALL_LOCATION},python3 -m pip install --no-cache-dir -r requirements.txt"
def k_to_c(k): c = (k - 273.15) return c k = 268.0 c = k_to_c(k) print("kelvin of" + str(k) + "is" + str(c) + "in kelvin" )
# Autogenerated file for Reflected light # Add missing from ... import const _JD_SERVICE_CLASS_REFLECTED_LIGHT = const(0x126c4cb2) _JD_REFLECTED_LIGHT_VARIANT_INFRARED_DIGITAL = const(0x1) _JD_REFLECTED_LIGHT_VARIANT_INFRARED_ANALOG = const(0x2) _JD_REFLECTED_LIGHT_REG_BRIGHTNESS = const(JD_REG_READING) _JD_REFLECTED_LIGHT_REG_VARIANT = const(JD_REG_VARIANT) _JD_REFLECTED_LIGHT_EV_DARK = const(JD_EV_INACTIVE) _JD_REFLECTED_LIGHT_EV_LIGHT = const(JD_EV_ACTIVE)
# https://leetcode.com/problems/unique-morse-code-words/ mapping = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] class Solution: def uniqueMorseRepresentations(self, words): """ :type words: List[str] :rtype: int """ transformations = set() for word in words: transformations.add(''.join([mapping[ord(c) - ord('a')] for c in word])) return len(transformations)
#!/bin/python3 # Designer Door Mat # https://www.hackerrank.com/challenges/designer-door-mat/problem n, m = map(int, input().split()) init = ".|." for i in range(n // 2): print(init.center(m, "-")) init = ".|." + init + ".|." print("WELCOME".center(m, "-")) for i in range(n // 2): linit = list(init) init = "".join(linit[3:len(linit) - 3]) print(init.center(m, "-"))
# albus.exceptions class AlbusError(Exception): def __init__(self, message, inner=None, detail=None): self.message = message self.inner = inner self.detail = detail
# Created by MechAviv # Nyen Damage Skin | (2438086) if sm.addDamageSkin(2438086): sm.chat("'Nyen Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
# -*- coding: utf-8 -*- # # Copyright 2016 Civic Knowledge. All Rights Reserved # This software may be modified and distributed under the terms of the BSD license. # See the LICENSE file for details. def get_root(): return ['do some magic?','or don\'t'] def get_measure_root(id): return "got id {} ({}) ".format(id, type(id))
# # PySNMP MIB module CHANNEL-CHANGE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHANNEL-CHANGE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:31:02 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) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection") InterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") Counter64, ModuleIdentity, Gauge32, ObjectIdentity, MibIdentifier, Integer32, Counter32, Unsigned32, iso, enterprises, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "ModuleIdentity", "Gauge32", "ObjectIdentity", "MibIdentifier", "Integer32", "Counter32", "Unsigned32", "iso", "enterprises", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "NotificationType", "TimeTicks") DisplayString, RowStatus, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention") channelChangeMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 1, 1, 1)) if mibBuilder.loadTexts: channelChangeMib.setLastUpdated('200205121638Z') if mibBuilder.loadTexts: channelChangeMib.setOrganization('FS VDSL Architecture Experts Group') fsan = MibIdentifier((1, 3, 6, 1, 4, 1, 1)) fsVdsl = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1)) channelChangeMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 1)) channelChangeMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 2)) channelTable = MibTable((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1), ) if mibBuilder.loadTexts: channelTable.setStatus('current') channelEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1), ).setIndexNames((0, "CHANNEL-CHANGE-MIB", "channelId")) if mibBuilder.loadTexts: channelEntry.setStatus('current') channelId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1), IpAddress()) if mibBuilder.loadTexts: channelId.setStatus('current') entitlementIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095))).setMaxAccess("readcreate") if mibBuilder.loadTexts: entitlementIndex.setStatus('current') networkPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 3), InterfaceIndex()).setMaxAccess("readcreate") if mibBuilder.loadTexts: networkPortId.setStatus('current') vpi = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readcreate") if mibBuilder.loadTexts: vpi.setStatus('current') vci = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(32, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: vci.setStatus('current') channelAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2), ("shuttingDown", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: channelAdminStatus.setStatus('current') channelRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 8), RowStatus().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: channelRowStatus.setStatus('current') customerTable = MibTable((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2), ) if mibBuilder.loadTexts: customerTable.setStatus('current') customerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1), ).setIndexNames((0, "CHANNEL-CHANGE-MIB", "onuId"), (0, "CHANNEL-CHANGE-MIB", "customerPortId")) if mibBuilder.loadTexts: customerEntry.setStatus('current') onuId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 1), InterfaceIndexOrZero()) if mibBuilder.loadTexts: onuId.setStatus('current') customerPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 2), InterfaceIndex()) if mibBuilder.loadTexts: customerPortId.setStatus('current') maxMulticastTraffic = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 3), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: maxMulticastTraffic.setStatus('current') maxMulticastStreams = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 4), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: maxMulticastStreams.setStatus('current') untimedEntitlements1 = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("readcreate") if mibBuilder.loadTexts: untimedEntitlements1.setStatus('current') untimedEntitlements2 = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("readcreate") if mibBuilder.loadTexts: untimedEntitlements2.setStatus('current') grantEntitlement = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 7), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: grantEntitlement.setStatus('current') revokeEntitlement = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 8), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: revokeEntitlement.setStatus('current') customerAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2), ("shuttingDown", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: customerAdminStatus.setStatus('current') customerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 10), RowStatus().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: customerRowStatus.setStatus('current') timedEntitlementTable = MibTable((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3), ) if mibBuilder.loadTexts: timedEntitlementTable.setStatus('current') timedEntitlementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1), ).setIndexNames((0, "CHANNEL-CHANGE-MIB", "timedEntitlementId")) if mibBuilder.loadTexts: timedEntitlementEntry.setStatus('current') timedEntitlementId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: timedEntitlementId.setStatus('current') timedEntitlementChannelId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 2), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: timedEntitlementChannelId.setStatus('current') startTime = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readcreate") if mibBuilder.loadTexts: startTime.setStatus('current') stopTime = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readcreate") if mibBuilder.loadTexts: stopTime.setStatus('current') entitlementRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 5), RowStatus().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: entitlementRowStatus.setStatus('current') customerTimedEntitlementTable = MibTable((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4), ) if mibBuilder.loadTexts: customerTimedEntitlementTable.setStatus('current') customerTimedEntitlementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1), ).setIndexNames((0, "CHANNEL-CHANGE-MIB", "custOnuId"), (0, "CHANNEL-CHANGE-MIB", "custPortId"), (0, "CHANNEL-CHANGE-MIB", "custTimedEntitlementId")) if mibBuilder.loadTexts: customerTimedEntitlementEntry.setStatus('current') custOnuId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 1), InterfaceIndexOrZero()) if mibBuilder.loadTexts: custOnuId.setStatus('current') custPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 2), InterfaceIndex()) if mibBuilder.loadTexts: custPortId.setStatus('current') custTimedEntitlementId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: custTimedEntitlementId.setStatus('current') custTimedEntitlementRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 4), RowStatus().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: custTimedEntitlementRowStatus.setStatus('current') channelChangeMibNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 2, 0)) channelChangeCAFailed = NotificationType((1, 3, 6, 1, 4, 1, 1, 1, 1, 2, 0, 1)).setObjects(("CHANNEL-CHANGE-MIB", "rejectedOnuId"), ("CHANNEL-CHANGE-MIB", "rejectedCustomerPortId")) if mibBuilder.loadTexts: channelChangeCAFailed.setStatus('current') rejectedOnuId = MibScalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 5), InterfaceIndexOrZero()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rejectedOnuId.setStatus('current') rejectedCustomerPortId = MibScalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 6), InterfaceIndex()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rejectedCustomerPortId.setStatus('current') caFailedNotificationStatus = MibScalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: caFailedNotificationStatus.setStatus('current') channelChangeMibConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3)) channelChangeMibCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 1)) channelChangeMibGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2)) channelChangeMibCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 1, 1)).setObjects(("CHANNEL-CHANGE-MIB", "channelChangeBasicGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeCACGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeBasicCAGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeCA4095ChannelsGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeCATimedEntitlementsGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeCANotificationsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeMibCompliance = channelChangeMibCompliance.setStatus('current') channelChangeBasicGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 1)).setObjects(("CHANNEL-CHANGE-MIB", "channelId"), ("CHANNEL-CHANGE-MIB", "networkPortId"), ("CHANNEL-CHANGE-MIB", "vpi"), ("CHANNEL-CHANGE-MIB", "vci"), ("CHANNEL-CHANGE-MIB", "channelAdminStatus"), ("CHANNEL-CHANGE-MIB", "channelRowStatus"), ("CHANNEL-CHANGE-MIB", "onuId"), ("CHANNEL-CHANGE-MIB", "customerPortId")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeBasicGroup = channelChangeBasicGroup.setStatus('current') channelChangeCACGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 2)).setObjects(("CHANNEL-CHANGE-MIB", "maxMulticastTraffic")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeCACGroup = channelChangeCACGroup.setStatus('current') channelChangeBasicCAGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 3)).setObjects(("CHANNEL-CHANGE-MIB", "maxMulticastStreams"), ("CHANNEL-CHANGE-MIB", "entitlementIndex"), ("CHANNEL-CHANGE-MIB", "untimedEntitlements1"), ("CHANNEL-CHANGE-MIB", "grantEntitlement"), ("CHANNEL-CHANGE-MIB", "revokeEntitlement"), ("CHANNEL-CHANGE-MIB", "rejectedOnuId"), ("CHANNEL-CHANGE-MIB", "rejectedCustomerPortId"), ("CHANNEL-CHANGE-MIB", "caFailedNotificationStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeBasicCAGroup = channelChangeBasicCAGroup.setStatus('current') channelChangeCA4095ChannelsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 4)).setObjects(("CHANNEL-CHANGE-MIB", "untimedEntitlements2")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeCA4095ChannelsGroup = channelChangeCA4095ChannelsGroup.setStatus('current') channelChangeCATimedEntitlementsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 5)).setObjects(("CHANNEL-CHANGE-MIB", "timedEntitlementId"), ("CHANNEL-CHANGE-MIB", "timedEntitlementChannelId"), ("CHANNEL-CHANGE-MIB", "startTime"), ("CHANNEL-CHANGE-MIB", "stopTime"), ("CHANNEL-CHANGE-MIB", "entitlementRowStatus"), ("CHANNEL-CHANGE-MIB", "custTimedEntitlementId"), ("CHANNEL-CHANGE-MIB", "custTimedEntitlementRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeCATimedEntitlementsGroup = channelChangeCATimedEntitlementsGroup.setStatus('current') channelChangeCANotificationsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 6)).setObjects(("CHANNEL-CHANGE-MIB", "channelChangeCAFailed")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeCANotificationsGroup = channelChangeCANotificationsGroup.setStatus('current') mibBuilder.exportSymbols("CHANNEL-CHANGE-MIB", networkPortId=networkPortId, timedEntitlementId=timedEntitlementId, customerTable=customerTable, channelChangeBasicCAGroup=channelChangeBasicCAGroup, channelAdminStatus=channelAdminStatus, channelChangeMibCompliance=channelChangeMibCompliance, customerRowStatus=customerRowStatus, customerTimedEntitlementEntry=customerTimedEntitlementEntry, customerPortId=customerPortId, timedEntitlementTable=timedEntitlementTable, channelRowStatus=channelRowStatus, channelEntry=channelEntry, channelChangeMibGroups=channelChangeMibGroups, entitlementIndex=entitlementIndex, customerAdminStatus=customerAdminStatus, untimedEntitlements2=untimedEntitlements2, grantEntitlement=grantEntitlement, channelChangeMibNotificationPrefix=channelChangeMibNotificationPrefix, fsVdsl=fsVdsl, customerTimedEntitlementTable=customerTimedEntitlementTable, channelId=channelId, timedEntitlementEntry=timedEntitlementEntry, channelTable=channelTable, channelChangeMibConformance=channelChangeMibConformance, maxMulticastTraffic=maxMulticastTraffic, channelChangeMibCompliances=channelChangeMibCompliances, channelChangeCA4095ChannelsGroup=channelChangeCA4095ChannelsGroup, stopTime=stopTime, channelChangeBasicGroup=channelChangeBasicGroup, channelChangeCAFailed=channelChangeCAFailed, channelChangeCACGroup=channelChangeCACGroup, custTimedEntitlementId=custTimedEntitlementId, maxMulticastStreams=maxMulticastStreams, channelChangeMib=channelChangeMib, vci=vci, untimedEntitlements1=untimedEntitlements1, channelChangeMibObjects=channelChangeMibObjects, timedEntitlementChannelId=timedEntitlementChannelId, rejectedCustomerPortId=rejectedCustomerPortId, caFailedNotificationStatus=caFailedNotificationStatus, onuId=onuId, custTimedEntitlementRowStatus=custTimedEntitlementRowStatus, startTime=startTime, vpi=vpi, channelChangeCATimedEntitlementsGroup=channelChangeCATimedEntitlementsGroup, PYSNMP_MODULE_ID=channelChangeMib, channelChangeMibNotifications=channelChangeMibNotifications, entitlementRowStatus=entitlementRowStatus, rejectedOnuId=rejectedOnuId, fsan=fsan, custOnuId=custOnuId, customerEntry=customerEntry, channelChangeCANotificationsGroup=channelChangeCANotificationsGroup, custPortId=custPortId, revokeEntitlement=revokeEntitlement)
x1 = 2 y1 = 2 x2 = 6 y2 = 10 m2 = (y2 - y1) / (x2 - x1) print(f'Slope = {m2:.2f}') # 9
def read_delimited_lines(file_handle, delimiter='|', omit_delimiter=False, read_size=4): delimited_line = "" data = file_handle.read(read_size) while data: delimiter_index = data.find(delimiter) if delimiter_index < 0: delimited_line += data else: delimited_line += data[:delimiter_index if omit_delimiter else delimiter_index + 1] yield delimited_line.strip() delimited_line = data[delimiter_index + 1:] data = file_handle.read(read_size) if len(delimited_line) > 0: yield delimited_line with open("lorem.txt") as colors_file: for line in read_delimited_lines(colors_file, "."): print(line)
""" Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price. Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. Thoughts: 1. Initial thought is to traverse the price list 2 times with time complexity O(n^2) 2. Do better? Better solution is use 2 pointers to keep track of the current_buying and current_saling index respectively """ class Solution: """ of course, we ran out of time limit """ def maxProfit(self, prices) -> int: max_profit = 0 for buying_day, buying_price in enumerate(prices): for saling_price in prices[buying_day+1:]: if saling_price-buying_price>max_profit: max_profit = saling_price-buying_price return max_profit class Solution2: def maxProfit(self, prices): buying_index = 0 current_index = 1 days = len(prices) max_profit = 0 while current_index < days: if prices[current_index] - prices[buying_index]>max_profit: max_profit = prices[current_index] - prices[buying_index] elif prices[current_index]<prices[buying_index]: buying_index = current_index current_index += 1 return max_profit if __name__ == "__main__": s = Solution2() test1 = [7,1,5,3,6,4] test2 = [7,6,4,3,1] print(s.maxProfit(test1)) print(s.maxProfit(test2))
"""Posenet model benchmark case list.""" POSE_ESTIMATION_MODEL_BENCHMARK_CASES = [ # PoseNet { "benchmark_name": "BM_PoseNet_MobileNetV1_075_353_481_WithDecoder", "model_path": "posenet/posenet_mobilenet_v1_075_353_481_16_quant_decoder", }, { "benchmark_name": "BM_PoseNet_MobileNetV1_075_481_641_WithDecoder", "model_path": "posenet/posenet_mobilenet_v1_075_481_641_16_quant_decoder", }, { "benchmark_name": "BM_PoseNet_MobileNetV1_075_721_1281_WithDecoder", "model_path": "posenet/posenet_mobilenet_v1_075_721_1281_16_quant_decoder", }, # MobileNet BodyPix { "benchmark_name": "BM_Bodypix_MobileNetV1_075_512_512_WithDecoder", "model_path": "posenet/bodypix_mobilenet_v1_075_512_512_16_quant_decoder", }, # MoveNet { "benchmark_name": "BM_MovenetLightning", "model_path": "movenet_single_pose_lightning_ptq", }, { "benchmark_name": "BM_MovenetThunder", "model_path": "movenet_single_pose_thunder_ptq", }, ]
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### response.logo = A(B(SPAN('M'),'eta',SPAN('B'),'ase'),XML('&trade;&nbsp;'), _class="navbar-brand",_href=URL('default', 'index'), _id="web2py-logo") response.title = request.application.replace('_',' ').title() response.subtitle = '' ## read more at http://dev.w3.org/html5/markup/meta.name.html response.meta.author = 'Ryan Marquardt <[email protected]>' response.meta.description = 'a cool new app' response.meta.keywords = 'web2py, python, framework' response.meta.generator = 'Web2py Web Framework' ## your http://google.com/analytics id response.google_analytics_id = None ######################################################################### ## this is the main application menu add/remove items as required ######################################################################### response.menu = [ (T('Home'), False, URL('default', 'index'), []), (T('Setup'), False, URL('setup', 'index'), []), ] DEVELOPMENT_MENU = (auth.user and (auth.user.id == 1)) ######################################################################### ## provide shortcuts for development. remove in production ######################################################################### def PAedit(path): return ('https://www.pythonanywhere.com/user/integralws/files' '/home/integralws/glean/applications/metabase/%s?edit') % path def _(): # shortcuts app = request.application ctr = request.controller # useful links to internal and external resources response.menu += [ (T('This App'), False, '#', [ (T('Design'), False, URL('admin', 'default', 'design/%s' % app)), LI(_class="divider"), (T('Controller'), False, URL( 'admin', 'default', 'edit/%s/controllers/%s.py' % (app, ctr))), (T('View'), False, URL( 'admin', 'default', 'edit/%s/views/%s' % (app, response.view))), (T('DB Model'), False, URL( 'admin', 'default', 'edit/%s/models/db.py' % app)), (T('Menu Model'), False, URL( 'admin', 'default', 'edit/%s/models/menu.py' % app)), (T('Config.ini'), False, URL( 'admin', 'default', 'edit/%s/private/appconfig.ini' % app)), (T('Layout'), False, URL( 'admin', 'default', 'edit/%s/views/layout.html' % app)), (T('Stylesheet'), False, URL( 'admin', 'default', 'edit/%s/static/css/web2py-bootstrap3.css' % app)), (T('Database'), False, URL(app, 'appadmin', 'index')), (T('Errors'), False, URL( 'admin', 'default', 'errors/' + app)), (T('About'), False, URL( 'admin', 'default', 'about/' + app)), ]), ] if DEVELOPMENT_MENU: _() if "auth" in locals(): auth.wikimenu()
def cluster_it(common_pos,no_sup,low_sup): topla=[] for x in common_pos: if x in no_sup+low_sup: continue else: topla.append(x) topla.sort() cluster={} r_cluster={} c_num=1 cluster['c_'+str(c_num)]=[] for i in range (0,len(topla)-1): pos1=topla[i] pos2=topla[i+1] Cd=abs(pos2 - pos1) if Cd <= 9: cluster['c_'+str(c_num)].append((pos1,pos2)) if Cd > 9: c_num = c_num+1 cluster['c_'+str(c_num)]=[] c_num=0 for keys in cluster: if len(cluster[keys]) >= 6: #this 6 actually means 7 cause counting in touples. remember to add +1 c_num=c_num+1 #print(c_num) r_cluster['c_'+str(c_num)]=cluster[keys] #r_cluster['c_'+str(c_num)].append(cluster[keys]) else: continue return cluster,r_cluster def CnandCs(r_cluster,kmer): print('The number of clusters found: {}\nCmsp; is the number of positions that make up a cluster while Cs is the cluster size'.format(len(r_cluster))) for r in r_cluster: Cs=r_cluster[r][-1][-1] - r_cluster[r][0][0] + kmer print ('Cmsp of cluster {} is {} and Cs is'.format(r,len(r_cluster[r])+1),Cs) def hotspots(r_cluster): a=list(r_cluster.keys()) hots={} c_num=1 hots['hotspot_'+str(c_num)]=[] for i in range(0,len(a)-1): pos1=r_cluster[a[i]][-1][-1] pos2=r_cluster[a[i+1]][0][0] Hd=pos2 - pos1 if Hd < 20: hots['hotspot_'+str(c_num)].append((a[i],a[i+1])) if Hd > 20: c_num=c_num+1 hots['hotspot_'+str(c_num)]=[] c_num=0 r_hots={} for keys in hots: if len(hots[keys]) > 0: c_num=c_num+1 #print(c_num) r_hots['hotspot_'+str(c_num)]=hots[keys] #r_cluster['c_'+str(c_num)].append(cluster[keys]) else: continue return hots,r_hots
def chipher(plaintext): alfabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя" chiphertext = "" for letter in plaintext: encrypted_letter = (len(alfabet) - 1 - alfabet.find(letter)) chiphertext = chiphertext + alfabet[encrypted_letter] return chiphertext print(chipher("айтигенио"))
# # PySNMP MIB module HIST-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HIST-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:31:14 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) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") iso, TimeTicks, Gauge32, enterprises, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Unsigned32, Integer32, Counter32, ObjectIdentity, NotificationType, MibIdentifier, experimental, IpAddress, Counter64, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "TimeTicks", "Gauge32", "enterprises", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Unsigned32", "Integer32", "Counter32", "ObjectIdentity", "NotificationType", "MibIdentifier", "experimental", "IpAddress", "Counter64", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") usr = MibIdentifier((1, 3, 6, 1, 4, 1, 429)) nas = MibIdentifier((1, 3, 6, 1, 4, 1, 429, 1)) mdmHist = MibIdentifier((1, 3, 6, 1, 4, 1, 429, 1, 30)) mdmNacHistCurrentTable = MibTable((1, 3, 6, 1, 4, 1, 429, 1, 30, 1), ) if mibBuilder.loadTexts: mdmNacHistCurrentTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentTable.setDescription('') mdmNacHistCurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1), ).setIndexNames((0, "HIST-MIB", "mdmNacHistCurrentIndex")) if mibBuilder.loadTexts: mdmNacHistCurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentEntry.setDescription('Objects that define the history stats for NAC current interval.') mdmNacHistCurrentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistCurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentIndex.setDescription('Index in to the Current NAC History table. This index contains a unique value for each card in the chassis.') mdmNacHistCurrentStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistCurrentStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentStartTime.setDescription('Specifies current interval start time in GMT.') mdmNacHistCurrentMgmtBusFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistCurrentMgmtBusFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentMgmtBusFailures.setDescription('Specifies number of Management Bus Failures occurred in the NAC during current interval so for.') mdmNacHistCurrentWatchdogTimouts = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistCurrentWatchdogTimouts.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentWatchdogTimouts.setDescription('Specifies number of Watchdog Timeouts occurred in the NAC during current interval so for.') mdmNacHistIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 429, 1, 30, 2), ) if mibBuilder.loadTexts: mdmNacHistIntervalTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalTable.setDescription('') mdmNacHistIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1), ).setIndexNames((0, "HIST-MIB", "mdmNacHistIntervalIndex"), (0, "HIST-MIB", "mdmNacHistIntervalNumber")) if mibBuilder.loadTexts: mdmNacHistIntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalEntry.setDescription('Objects that define history stats for NAC intervals.') mdmNacHistIntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalIndex.setDescription('Index in to NAC Interval History table. This index contains a unique value for each card in the chassis.') mdmNacHistIntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 104))).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalNumber.setDescription('This object is the index for one of 104 possibel history intervals for this NAC.') mdmNacHistIntervalStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalStartTime.setDescription('Specifies interval start time in GMT.') mdmNacHistIntervalMgmtBusFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalMgmtBusFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalMgmtBusFailures.setDescription('Specifies number of Management Bus Failures occurred in the NAC during the interval.') mdmNacHistIntervalWatchdogTimouts = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalWatchdogTimouts.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalWatchdogTimouts.setDescription('Specifies number of Watchdog Timeouts occurred in the NAC during the interval.') mdmHistCurrentTable = MibTable((1, 3, 6, 1, 4, 1, 429, 1, 30, 3), ) if mibBuilder.loadTexts: mdmHistCurrentTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentTable.setDescription('') mdmHistCurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1), ).setIndexNames((0, "HIST-MIB", "mdmHistCurrentIndex")) if mibBuilder.loadTexts: mdmHistCurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentEntry.setDescription('Objects that define the history stats for modem current interval.') mdmHistCurrentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentIndex.setDescription('Index in to the Current modem history table. This index contains the unique value associated with the modem as defined in the chassis MIB entity table.') mdmHistCurrentStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentStartTime.setDescription('Specifies current interval start time in GMT.') mdmHistCurrentInConnectEstabs = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectEstabs.setDescription('Specifies number of incoming calls established during current interval so for.') mdmHistCurrentInConnectFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectFailures.setDescription('Specifies number of incoming call failures during current interval so for.') mdmHistCurrentInConnectTerms = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectTerms.setDescription('Specifies number of incoming calls terminated during current interval so for.') mdmHistCurrentInConnectTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectTime.setDescription('Specifies length of all incoming calls during current interval so for.') mdmHistCurrentInTotalBytesRx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesRx.setDescription('Specifies number of bytes received through incoming calls during current interval so for.') mdmHistCurrentInTotalBytesTx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 8), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesTx.setDescription('Specifies number of bytes sent out through incoming calls during current interval so for.') mdmHistCurrentOutConnectEstabs = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 9), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectEstabs.setDescription('Specifies number of outgoing calls established during current interval so for.') mdmHistCurrentOutConnectFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 10), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectFailures.setDescription('Specifies number of outgoing call failures during current interval so for.') mdmHistCurrentOutConnectTerms = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 11), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectTerms.setDescription('Specifies number of outgoing calls terminated during current interval so for.') mdmHistCurrentOutConnectTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 12), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectTime.setDescription('Specifies length of all outgoing calls during current interval so for.') mdmHistCurrentOutTotalBytesRx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 13), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesRx.setDescription('Specifies number of bytes received through outgoing calls during current interval so for.') mdmHistCurrentOutTotalBytesTx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 14), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesTx.setDescription('Specifies number of bytes sent out through outgoing calls during current interval so for.') mdmHistCurrentBlers = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 15), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentBlers.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentBlers.setDescription('Specifies number of block errors received during current interval so for.') mdmHistCurrentFallBacks = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 16), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentFallBacks.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentFallBacks.setDescription('Specifies number of link speed fallbacks occured during current interval so for.') mdmHistIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 429, 1, 30, 4), ) if mibBuilder.loadTexts: mdmHistIntervalTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalTable.setDescription('') mdmHistIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1), ).setIndexNames((0, "HIST-MIB", "mdmHistIntervalIndex"), (0, "HIST-MIB", "mdmHistIntervalNumber")) if mibBuilder.loadTexts: mdmHistIntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalEntry.setDescription('Objects that define history stats for modem intervals.') mdmHistIntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalIndex.setDescription('Index in to the interval History table. This index contains the unique value associated with the modem as defined in the chassis MIB entity table.') mdmHistIntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 104))).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalNumber.setDescription('This object is the index for one of 104 possibel history intervals for this modem.') mdmHistIntervalStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalStartTime.setDescription('Specifies interval start time in GMT.') mdmHistIntervalInConnectEstabs = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectEstabs.setDescription('Specifies number of incoming calls established during the interval.') mdmHistIntervalInConnectFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectFailures.setDescription('Specifies number of incoming call failures during the interval.') mdmHistIntervalInConnectTerms = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectTerms.setDescription('Specifies number of incoming calls terminated during the interval.') mdmHistIntervalInConnectTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectTime.setDescription('Specifies length of all incoming calls during the intervals.') mdmHistIntervalInTotalBytesRx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 8), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesRx.setDescription('Specifies number of bytes received through incoming calls during the interval.') mdmHistIntervalInTotalBytesTx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 9), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesTx.setDescription('Specifies number of bytes sent out through incoming calls during the interval.') mdmHistIntervalOutConnectEstabs = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 10), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectEstabs.setDescription('Specifies number of outgoing calls established during the interval.') mdmHistIntervalOutConnectFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 11), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectFailures.setDescription('Specifies number of outgoing call failures during the interval.') mdmHistIntervalOutConnectTerms = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 12), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectTerms.setDescription('Specifies number of outgoing calls terminated during the interval.') mdmHistIntervalOutConnectTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 13), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectTime.setDescription('Specifies length of all outgoing calls during the interval.') mdmHistIntervalOutTotalBytesRx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 14), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesRx.setDescription('Specifies number of bytes received through outgoing calls during the interval.') mdmHistIntervalOutTotalBytesTx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 15), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesTx.setDescription('Specifies number of bytes sent out through outgoing calls during the interval.') mdmHistIntervalBlers = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 16), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalBlers.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalBlers.setDescription('Specifies number of block errors received during the interval.') mdmHistIntervalFallBacks = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 17), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalFallBacks.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalFallBacks.setDescription('Specifies number of link speed fallbacks occured during the interval.') mibBuilder.exportSymbols("HIST-MIB", mdmHistCurrentOutTotalBytesTx=mdmHistCurrentOutTotalBytesTx, mdmHistCurrentOutConnectEstabs=mdmHistCurrentOutConnectEstabs, mdmHistIntervalInConnectFailures=mdmHistIntervalInConnectFailures, mdmHistIntervalOutTotalBytesRx=mdmHistIntervalOutTotalBytesRx, mdmHistCurrentOutTotalBytesRx=mdmHistCurrentOutTotalBytesRx, mdmNacHistCurrentWatchdogTimouts=mdmNacHistCurrentWatchdogTimouts, mdmHistCurrentBlers=mdmHistCurrentBlers, mdmHistIntervalStartTime=mdmHistIntervalStartTime, mdmHistIntervalTable=mdmHistIntervalTable, mdmHistCurrentInConnectTime=mdmHistCurrentInConnectTime, mdmHistCurrentOutConnectTime=mdmHistCurrentOutConnectTime, mdmHistIntervalInTotalBytesTx=mdmHistIntervalInTotalBytesTx, mdmHistIntervalBlers=mdmHistIntervalBlers, mdmHistCurrentInConnectEstabs=mdmHistCurrentInConnectEstabs, mdmHistIntervalOutTotalBytesTx=mdmHistIntervalOutTotalBytesTx, mdmHistIntervalInConnectTerms=mdmHistIntervalInConnectTerms, mdmHistCurrentTable=mdmHistCurrentTable, mdmHistCurrentEntry=mdmHistCurrentEntry, mdmNacHistIntervalMgmtBusFailures=mdmNacHistIntervalMgmtBusFailures, mdmHistCurrentOutConnectFailures=mdmHistCurrentOutConnectFailures, nas=nas, mdmHistCurrentInTotalBytesRx=mdmHistCurrentInTotalBytesRx, mdmNacHistIntervalWatchdogTimouts=mdmNacHistIntervalWatchdogTimouts, mdmHistCurrentInConnectFailures=mdmHistCurrentInConnectFailures, mdmNacHistCurrentIndex=mdmNacHistCurrentIndex, mdmHistIntervalNumber=mdmHistIntervalNumber, mdmHistCurrentStartTime=mdmHistCurrentStartTime, mdmHistIntervalOutConnectEstabs=mdmHistIntervalOutConnectEstabs, mdmNacHistCurrentEntry=mdmNacHistCurrentEntry, mdmNacHistIntervalTable=mdmNacHistIntervalTable, mdmHistIntervalOutConnectTime=mdmHistIntervalOutConnectTime, mdmNacHistCurrentStartTime=mdmNacHistCurrentStartTime, mdmHistCurrentFallBacks=mdmHistCurrentFallBacks, mdmHistIntervalFallBacks=mdmHistIntervalFallBacks, mdmNacHistCurrentTable=mdmNacHistCurrentTable, mdmHistCurrentOutConnectTerms=mdmHistCurrentOutConnectTerms, mdmHistCurrentIndex=mdmHistCurrentIndex, mdmHistCurrentInConnectTerms=mdmHistCurrentInConnectTerms, mdmHistCurrentInTotalBytesTx=mdmHistCurrentInTotalBytesTx, mdmHistIntervalInConnectTime=mdmHistIntervalInConnectTime, mdmHistIntervalIndex=mdmHistIntervalIndex, mdmNacHistCurrentMgmtBusFailures=mdmNacHistCurrentMgmtBusFailures, usr=usr, mdmNacHistIntervalNumber=mdmNacHistIntervalNumber, mdmNacHistIntervalStartTime=mdmNacHistIntervalStartTime, mdmHistIntervalInConnectEstabs=mdmHistIntervalInConnectEstabs, mdmHistIntervalInTotalBytesRx=mdmHistIntervalInTotalBytesRx, mdmHistIntervalOutConnectFailures=mdmHistIntervalOutConnectFailures, mdmHist=mdmHist, mdmHistIntervalOutConnectTerms=mdmHistIntervalOutConnectTerms, mdmHistIntervalEntry=mdmHistIntervalEntry, mdmNacHistIntervalEntry=mdmNacHistIntervalEntry, mdmNacHistIntervalIndex=mdmNacHistIntervalIndex)
# ** CONTROL FLOW ** # IF, ELIF AND ELSE age = 21 if age >= 21: print("You can drive alone") elif age < 16: print("You are not allow to drive") else: print("You can drive with supervision") # FOR LOOPS # Iterate a List print("\nIterate a List:") my_list = [1, 2, 3, 4, 5] for item in my_list: print(item) # Iterate a Dictionary print("\nIterate a Dictionary:") my_dict = {"One": 1, "Two": 2, "Three": 3} for key in my_dict: print(key) # Print keys of the dictionary print(my_dict[key]) # Print the values # Iterate using Methods print("\nIterate using Methods:") for values in my_dict.values(): # Replace my_dict.keys to iterate keys print(values) # Iterate a Tuple - Tuple unpacking print("\nIterate Tuples:") my_pairs = [(1, 2), (3, 4), (5, 6)] # Tuples inside a list for item1, item2 in my_pairs: print(item1) print(item2) print("---") # WHILE LOOPS print("\nWhile Loops:") i = 1 while i < 5: print("i is: {}".format(i)) i += 1 # FOR AND RANGE print("\nFor and Range:") list_range = list(range(0, 20, 2)) # range(start, stop, step) print(list_range) for i in range(0, 20, 2): print(i) # Note: Range is a generator which save ton of memory # LIST COMPREHENSION print("\nList Comprehension:") x = [1, 2, 3, 4, 5] # Use List Comprehension to return items from x squares x_square = [item**2 for item in x] print(x_square)
dados = list() pessoas = list() pesados = list() leves = list() pesos = list() contador = 1 print(f'\033[1;34m{" MAIOR E MENOR PESO ":-^44}\033[m') while True: if contador == 1: while True: continuar = str(input('Deseja cadastrar alguem no sistema?[S][N]: ')) if continuar in 'SsNn': break else: print('Reposta inválida.Tente novamente!') if continuar in 'Nn': break dados.append(str(input(f'Digite o nome da {contador}ª pessoa: ')).strip().capitalize()) dados.append(float(input(f'Digite o peso de {dados[-1]}(Kg): '))) pessoas.append(dados[:]) while True: continuar = str(input('Deseja cadastrar mais alguem?[S][N]: ')) if continuar in 'SsNn': break else: print('Reposta inválida.Tente novamente!') if continuar in 'Nn': break contador += 1 dados.clear() if len(pessoas) == 1: print(f'Apenas uma pessoa se cadastrou no sistema: ', end='') print(f'{pessoas[0][0]}.') elif len(pessoas) == 2: print(f'{len(pessoas)} Pessoas se cadastraram no sistema: ', end='') print(f'{pessoas[0][0]} e {pessoas[1][0]}.') elif len(pessoas) > 2: print(f'{len(pessoas)} Pessoas se cadastraram no sistema: ', end='') for c in pessoas[:-2]: print(c[0], end=', ') print(f'{pessoas[-2][0]} e {pessoas[-1][0]}.') else: print('Nenhuma pessoa se cadastrou no sistema.') for p in pessoas: pesos.append(p[1]) for p1 in pessoas: if p1[1] == min(pesos): leves.append(p1) if p1[1] == max(pesos): pesados.append(p1) if len(pessoas) > 0: print(f'O maior peso foi {pesados[0][1]:.1f} Kg de ', end='') if len(pesados) == 1: print(pesados[0][0]) elif len(pesados) == 2: print(f'{pesados[0][0]} e {pesados[1][0]}.') elif len(pesados) > 2: for a in pesados[:-2]: print(a[0], end=', ') print(f'{pesados[-2][0]} e {pesados[-1][0]}.') print(f'O menor peso foi {leves[0][1]:.1f} Kg de ', end='') if len(leves) == 1: print(leves[0][0]) elif len(leves) == 2: print(f'{leves[0][0]} e {leves[1][0]}.') elif len(leves) > 2: for b in leves[:-2]: print(b[0], end=', ') print(f'{leves[-2][0]} e {leves[-1][0]}.')
################################### # SOLUTION ################################### def no_boring_zeros(n): j = n if j <= 0: j = -j x = list(range(0,100)) z = [] for k in x: if j/(10**k) != int(j/(10**k)): z.append((j/(10**k))*10) if n < 0: return -max(z) if n == 0: return 0 else: return max(z)
x = [ 100, 100, 100, 100, 100 ] y = 100 s = 50 speed = [ 1, 2, 3, 4, 5 ] def setup(): size(640, 360, P2D) def draw(): global x, y, s, speed background(127) for i in range(0, len(x)): ellipse(x[i], y + (i * s), s, s) x[i] += speed[i] if x[i] > width or x[i] < 0: speed[i] *= -1
n1 = int(input('Um valor: ')) n2 = int(input('Outro valor: ')) s = n1+n2 m = n1*n2 d = n1/n2 di = n1//n2 #divisão inteira e = n1**n2 #exponênciação #{} as chaves indicam as variáveis que serão inseridas. #{:.2f} indica que caso seja um número real, terá apenas 2 casas após o ponto flutuante. print('A soma é: {}, o produto é: {} e a divisão é: {:.2f}'.format(s, m, d), end=' ') #para que tudo saia na mesma linha basta usar o end=' ', como no exemplo à cima. #Também é possível quebrar a linha, utilizando \n print('A divisão inteira é: {} e a potência é: {}'.format(di, e))
def mph2fps(mph): return mph*5280/3600 def myhello(): print("Konchi_wa")
aux=0 aux2=0 while True: string=list(map(str,input().split())) if string[0]=="ABEND":break elif string[0]=='SALIDA': aux+=int(string[1]) aux2+=1 else: aux-=int(string[1]) aux2-=1 print(aux) print(aux2)
"""Try it yourself 9-1 """ class Restaurant(): def __init__(self,restaurant_name,cuisine_type): self.restaurant_name = restaurant_name.title() self.cuisine_type = cuisine_type def describe_restaurant(self): desc = self.restaurant_name + " nuestra comida es " + self.cuisine_type + "." print(desc) def open_restaurant(self): openR = self.restaurant_name + " Bienvenido nuestro restaurante esta abierto." print("\n"+ openR) restaurant = Restaurant("El gran buda de oro","Asiática") print(restaurant.restaurant_name) print(restaurant.cuisine_type) restaurant.describe_restaurant() restaurant.open_restaurant()
class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: arr.sort() l1 = arr[0:(len(arr)-1)] l2 = arr[1:] diffs = [abs(i-j) for i,j in zip(l1, l2)] if len(set(diffs)) == 1: return True return False
class Flower: """A flower.""" def __init__(self, name, petals, price): """Create a new flower instance. name the name of the flower (e.g. 'Spanish Oyster') petals the number of petals exists (e.g. 50) price price of each flower (measured in euros) """ self._name = str(name) self.set_petals(petals) self.set_price(price) def set_name(self, name): self._name = str(name) def get_name(self): return self._name def set_petals(self, petals): try: self._petals = int(petals) except (TypeError, ValueError): print('set_petals(): could not parse "%s" to int().' % petals) def get_petals(self): return self._petals def set_price(self, price): try: self._price = float(price) except (TypeError, ValueError): print('set_price(): You should parse "%s" to float().' % price) def get_price(self): return self._price if __name__ == '__main__': rose = Flower('Rose', 60, 1.3) print('%s contains %d petals costs %.2f euros.' % \ (rose.get_name(), rose.get_petals(), rose.get_price())) """Example with error.""" rose.set_petals('error')
"""Ensinando como documentar funções. Quando se trata de documentar funções, a primeira linha da função precisa ser a documentação. Caso a documentação possua mais de uma linha, a mesma pode continuar a expandir, porém a primeira linha sempre precisa fazer parte da documentação. Veniam et deserunt ex consectetur aliquip sint excepteur reprehenderit eu sint aute. Exercitation occaecat ad consectetur sint exercitation eu. Consequat magna labore ea ad velit. Duis nostrud et cillum nulla amet. Incididunt sit aute culpa deserunt mollit aute ea ullamco do minim consectetur reprehenderit excepteur. Consequat officia sunt non ad sit nostrud aliquip ea. Officia ullamco duis elit non cillum non veniam commodo qui qui consectetur consequat laborum deserunt. Duis do aliqua sint aute ea excepteur tempor culpa pariatur. Ut velit do pariatur minim duis commodo enim amet. Quis sunt anim mollit labore excepteur commodo veniam Lorem. Lorem ut laboris ut mollit in excepteur veniam dolore est pariatur. Consequat dolore occaecat id labore ullamco esse ea reprehenderit. Labore incididunt Lorem qui amet aute anim ipsum elit pariatur amet occaecat. Ut enim eu aliqua excepteur ea excepteur commodo Lorem irure. """ variavel_1 = "valor 1" def subtracao(x, y): """Subtração de x e y""" return x - y def soma(x, y, z=None): """Soma x, y e z. Soma os valores de x, y e z. Caso o programador não queira um terceiro valor (z) ele pode optar por não usá-lo. """ if z: return x + y + z return x + y variavel_2 = "valor 2" variavel_3 = "valor 3" variavel_4 = "valor 4"
class LanguageUtility: LANGUAGES = { "C": ("h",), "Clojure": ("clj",), "C++": ("cpp", "hpp", "h++",), "Crystal": ("cr",), "C#": ("cs", "csharp",), "CSS": (), "D": (), "Go": ("golang",), "HTML": ("htm",), "Java": (), "JavaScript": ("ecma", "ecmascript", "es", "js"), "Julia": (), "Less": (), "Lua": (), "Nim": (), "PHP": (), "Python": ("py",), "R": (), "Ruby": ("rb",), "Rust": ("rs",), "Sass": ("scss",), "Scala": ("sc",), "SQL": (), "Swift": (), "TypeScript": ("ts",), } @staticmethod async def resolve(language_string): for language, aliases in LanguageUtility.LANGUAGES.items(): if language_string.lower() in map(lambda x: x.lower(), (language, *aliases)): return language
# Recursion # Base Case: n < 2, return lst # Otherwise: # Divide list into 2, Sort each of them, Merge! def merge(left, right): # Compare first element # Take the smaller of the 2 # Repeat until no more elements results = [] while left and right: if left[0] < right[0]: results.append(left.pop(0)) else: results.append(right.pop(0)) results.extend(right) results.extend(left) return results def merge_sort(lst): if (len(lst) < 2): return lst mid = len(lst) // 2 left = merge_sort(lst[:mid]) # sort left right = merge_sort(lst[mid:]) # sort right return merge(left, right) print(merge_sort([2, 1, 99]))
__about__ = "Maximum no in a binary tree." class Node: def __init__(self, data): self.data = data self.left = None self.right= None class Tree: @staticmethod def insert(root = None,data = None): if root is None and data is not None: root = Node(data)
E, F, C = map(int, input().split()) bottles = E + F drank = 0 while bottles >= C: # while he still has enough empty bottles to purchase more bottles -= C - 1 # used F empty bottles to buy 1 drank += 1 print(drank)
NOTES = { 'C3': 130.8, 'CS3': 138.6, 'DF3': 138.6, 'D3': 146.8, 'DS3': 155.6, 'EF3': 155.6, 'E3': 164.8, 'F3': 174.6, 'FS3': 185.0, 'GF3': 185.0, 'G3': 196.0, 'GS3': 207.7, 'AF3': 207.7, 'A3': 220.0, 'AS3': 233.1, 'BF3': 233.1, 'B3': 246.9, 'C4': 261.6, 'CS4': 277.2, 'DF4': 277.2, 'D4': 293.7, 'DS4': 311.1, 'EF4': 311.1, 'E4': 329.6, 'F4': 349.2, 'FS4': 370.0, 'GF4': 370.0, 'G4': 392.0, 'GS4': 415.3, 'AF4': 415.3, 'A4': 440.0, 'AS4': 466.2, 'BF4': 466.2, 'B4': 493.9, 'C5': 523.3, 'CS5': 554.4, 'DF5': 554.4, 'D5': 587.3, 'DS5': 622.3, 'EF5': 622.3, 'E5': 659.3, 'F5': 698.5, 'FS5': 740.0, 'GF5': 740.0, 'G5': 784.0, 'GS5': 830.6, 'AF5': 830.6, 'A5': 880.0, 'AS5': 932.3, 'BF5': 932.3, 'B5': 987.8, }
# -*- coding: utf-8 -*- class HelloWorldController: __defaultName = None def __init__(self): self.__defaultName = "Pip User" def configure(self, config): self.__defaultName = config.get_as_string_with_default("default_name", self.__defaultName) def greeting(self, name): return f"Hello, {name if name else self.__defaultName} !"
edge_array = [0,100,-1,-30,130,-150,-1,-1,-1,10,10,-120,-10,160,-180,0,10,-180,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,120,-120,-100,30,-200,30,30,-200,20,30,-200,30,220,-230,40,20,-220,0,50,-30,-200,30,-30,30,30,-200,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,60,-160,-10,130,-190,0,40,-200,-1,0,-200,-50,30,-250,5,-50,-250,-1,80,-30,-50,30,-100,0,30,-200,-1,100,-130,-1,30,-50,-30,50,0,-1,30,-200,10,250,-250,0,-50,-250,-1,30,-30,-200,-250,-130,0,-30,250,-1,70,-150,-1,100,-130,-70,30,-200,-1,-30,-200,-1,30,30,0,30,-70,-1,30,-200,-250,0,-120,0,-30,-250,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,200,0,-1,230,-30,-1,220,-30,-1,150,-20,-1,250,-80,-1,100,-100,-1,220,30,-1,220,50,-1,200,-80,-1,-1,-30,-1,30,-30,-1,50,-50,-1,30,-50,-1,180,0,-1,30,0,-1,100,0,-1,30,0,-1,0,-30,-1,-1,0,-1,180,0,-1,180,0,-1,-1,0,-1,100,10,-1,0,0,-1,180,0,-1,120,10,-1,120,-100,-1,-1,30,-1,200,0,-1,180,0,-1,-1,0,-1,120,0,-1,100,0,-1,-1,50,-1,120,0,-1,120,-30,-1,-1,0,-1,-1,50,-1,120,30,-1,-1,100,-1,300,150,-1,200,80,-1,-1,50,-1,200,50,-1,140,0,-1,-1,80,-1,-1,0,-1,120,0,-1,-1,0,-1,-1,50,-1,140,0,-1,-1,0,-1,120,0,-1,100,-60,-1,-1,30,-1,-1,0,-1,220,10,-1,-1,0,-1,-1,0,-1,0,0,-1,-1,30,-1,-1,0,-1,50,30,-1,-1,-30,-1,-1,0,-1,-1,-10,-1,-1,-30,-1,-1,50,-1,120,0,-1,-1,0,-1,-1,0,-1,100,-60,-1,-1,50,-1,-1,0,-1,-1,0,-1,-1,-10,-1,-1,0,-1,-1,-50,-1,-1,10,-1,-1,-50,-1,0,-100,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-300] par =[0,0,0,0,0,0] i = 0 par2 =[0,0,0,0,0,0] for par[0] in range(0,3): for par[1] in range(0,3): for par[2] in range(0,3): for par[3] in range(0,3): for par[4] in range(0,3): for par[5] in range(0,3): index = par[0]+par[1]*3+par[2]*9+par[3]*27+par[4]*81+par[5]*243 if (index > i and index < 728): try: edge_array[index] = edge_array[i] except ValueError: pass j = 0 for par_each in par: if (par_each == 1): par2[j] = 2 elif (par_each == 2): par2[j] = 1 else: par2[j] = 0 j += 1 index2 = par2[0]*243+par2[1]*81+par2[2]*27+par2[3]*9+par2[4]*3+par2[5] if (index2 > i and index2 < 728): try: edge_array[index2] = -1 * edge_array[i] except ValueError: pass i += 1 print(edge_array) print(len(edge_array))
class LoginResponse: def __init__( self, access_token: str, fresh_token: str, token_type: str = "bearer" ): self.access_token = access_token self.fresh_token = fresh_token self.token_type = token_type def json(self): return dict( access_token=self.access_token, fresh_token=self.fresh_token, token_type=self.token_type )
# Iterating Through Dictionaries contacts = {"Daisy Johnson": "2468 Park Ave", "Leo Fitz": "1258 Monkey Dr"} # iterate through each key for name in contacts: print(name) # or, use keys() method for name in contacts.keys(): print(name) # using each key to print each value for name in contacts: # prints each address associated with each name print(contacts[name]) # iterate through each value using values() for address in contacts.values(): print(address) # iterate through keys and values using items() for name, address in contacts.items(): print(name + ", " + address)
to_do_list = ["0"] * 10 while True: command = input().split("-", maxsplit=1) if "End" in command: break to_do_list.insert(int(command[0]), command[1]) while "0" in to_do_list: to_do_list.remove("0") print(to_do_list)
N = int(input()) data = open("{}.txt".format(N), 'r') data = data.readline() data = [int(i) for i in data.split()] def parr(array): for i in array: print('{:4d}'.format(i), end=" ") def insertionsort(x): for i in range(1, len(x)): j = i - 1; key = x[i] while(x[j] > key and j>= 0): x[j+1] = x[j] j = j-1 x[j+1] = key parr(x); print() parr(data); print() insertionsort(data) parr(data); print()
def resolve(): n = int(input()) for i in range(1, n + 1): if i % 3 == 0 or "3" in str(i): print(" {}".format(i), end="") print()
''' * @Author: csy * @Date: 2019-04-28 08:15:26 * @Last Modified by: csy * @Last Modified time: 2019-04-28 08:15:26 ''' def greet_users(names): '''向列表中的每个用户发出简单问候''' for name in names: msg = 'Hello,'+name.title() print(msg) usernames = ['hannah', 'try', 'margot'] greet_users(usernames)
''' Make a 3x3 matrix and fill with numbers at the end show the matrix in a right format ''' cr = [[],[],[]] for c in range(0,3): cr[0].append(int(input(f'First line [1, {c+1}]: '))) for c in range(0,3): cr[1].append(int(input(f'Second line [2, {c+1}]: '))) for c in range(0,3): cr[2].append(int(input(f'Third line [3, {c+1}]: '))) print(f'''The matrix is:\n{cr[0]}\n{cr[1]}\n{cr[2]}''')
load( "@io_bazel_rules_dotnet//dotnet/private:context.bzl", "dotnet_context", ) load( "@io_bazel_rules_dotnet//dotnet/private:providers.bzl", "DotnetLibrary", ) load( "@io_bazel_rules_dotnet//dotnet/private:common.bzl", "paths", ) def _dotnet_nuget_impl(ctx, build_file = None, build_file_content = None): """dotnet_nuget_impl emits actions for exposing nunit assmebly.""" package = ctx.attr.package output_dir = ctx.path("") url = ctx.attr.source + "/" + ctx.attr.package + "/" + ctx.attr.version ctx.download_and_extract(url, output_dir, ctx.attr.sha256, type="zip") if build_file_content: ctx.file("BUILD", build_file_content) elif build_file: ctx.symlink(ctx.path(build_file), "BUILD") else: ctx.template("BUILD.bazel", Label("@io_bazel_rules_dotnet//dotnet/private:BUILD.nuget.bazel"), executable = False, ) dotnet_nuget = repository_rule( _dotnet_nuget_impl, attrs = { # Sources to download the nuget packages from "source":attr.string(default = "https://www.nuget.org/api/v2/package"), # The name of the nuget package "package":attr.string(mandatory=True), # The version of the nuget package "version":attr.string(mandatory=True), "sha256":attr.string(mandatory=True), }, ) def _dotnet_nuget_new_impl(repository_ctx): build_file = repository_ctx.attr.build_file build_file_content = repository_ctx.attr.build_file_content if not (build_file_content or build_file): fail("build_file or build_file_content is required") _dotnet_nuget_impl(repository_ctx, build_file, build_file_content) dotnet_nuget_new = repository_rule( _dotnet_nuget_new_impl, attrs = { # Sources to download the nuget packages from "source":attr.string(default = "https://www.nuget.org/api/v2/package"), # The name of the nuget package "package":attr.string(mandatory=True), # The version of the nuget package "version":attr.string(mandatory=True), "sha256":attr.string(mandatory=True), "build_file": attr.label( allow_files = True, ), "build_file_content": attr.string(), }, )
n = int(input()) for i in range(n): x = int(input()) print(len(bin(x)) - 2)
"""NA (Non-Available) values in R.""" NA_Character = None NA_Integer = None NA_Logical = None NA_Real = None NA_Complex = None
''' The class derived from more than 1 base called as a Multiple Inheritence. Programmer_name : BALAVIGNESH.M Implemented_Date : 11-11-2018 ''' class OS: SecurityOS = "Linux" DeveloperlikeOS = "Mac OS" Most_Personal_usage_OS = "Windows" class KernerlType: SecurityOS_Kernel = "MonoLithic Kernel" DeveloperlikeOS_Kernel = "XNU Kernel" Most_Personal_usage_OS_Kernel = "Hybrid Kernel" class OSINFO(OS,KernerlType): def __init__(self): self.SecurityOS_Owner = "Linus Tarvolds & maintained By Linux Foundation" self.DeveloperlikeOS_Owner = "Steve Jobs & Apple Inc." self.Most_Personal_usage_OS_Owner = "Bill Gates & Microsoft" def GetOSInfo(self): print("Most powerful Security OS is: {x}.\n Using Kernel Type: {y} .\n Developer & Owned Company is: {z}".format( x= self.SecurityOS , y = self.SecurityOS_Kernel , z = self.SecurityOS_Owner )) print() print("Most Developer and Trending OS is: {x}. \n Using Kernel Type: {y}.\n Developer & Owned Company is: {z}".format( x = self.DeveloperlikeOS , y = self.DeveloperlikeOS_Kernel , z = self.DeveloperlikeOS_Owner )) print() print("Favourite & number 1 Most user personal usage OS: {x}.\n Using Kernel Type: {y}.\n Developer & Owned Company is:{z} ".format( x = self.Most_Personal_usage_OS , y = self.Most_Personal_usage_OS_Kernel , z = self.Most_Personal_usage_OS_Owner )) osinfo = OSINFO() osinfo.GetOSInfo()