content
stringlengths
7
1.05M
def f(): print("this is the f() function") return 0 def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) def fib_not_recursive(n): x = 0 y = 1 if n == 0: return x elif n == 1: return y while n-2 >= 0: x,y = y,x+y n -= 1 return y if __name__ == '__main__': fib_generated_by_recurse = [fib(i) for i in range(0,20)] fib_generated_by_non_recurse = [fib_not_recursive(i) for i in range(0,20)] print(fib_generated_by_recurse) print(fib_generated_by_non_recurse)
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class BTreeData: def __init__(self, n: Node, isTarget: bool): self.n = n self.isTarget = isTarget class Solution: def findSecondLargest(self, root: Node) -> Node: return self._helper(root).n def findSecondLargest2(self, root: Node) -> Node: if root.right is not None: secondGreatestInRightSubtree = self.findSecondLargest2(root.right) if secondGreatestInRightSubtree is None: return root else: return secondGreatestInRightSubtree else: if root.left is not None: return root.left else: return None def _helper(self, n: Node) -> BTreeData: if n.right is not None: data = self._helper(n.right) if data.isTarget == False: data = BTreeData(n, True) return data else: return BTreeData(None, False ) if n.left is None else BTreeData(n.left, True)
numeros = [] while True: numeros.append(float(input("\nDigite um valor: "))) if numeros[-1].is_integer(): numeros[-1] = int(numeros[-1]) while True: op = input("\nQuer continuar [S/N]? ").strip().upper() if op in ['S','N']: break if op == 'N': break print(f'\nVocê digitou {len(numeros)} elementos.\n') print(f'Os valores em ordem decrescente são: {sorted(numeros, reverse=True)}\n') if 5 in numeros: print('O valor 5 faz parte da lista!\n') else: print('O valor 5 não faz parte da lista!\n')
__all__ = ['ImgFormat'] class ImgFormat(): JPEG = 'jpeg' PNG = 'png'
#!usr/bin/env python3 # Use standard library functions to search strings for content sample_str = "The quick brown fox jumps over the lazy dog" # startsWith and endsWith functions print(sample_str.startswith("The")) print(sample_str.startswith("the")) print(sample_str.endswith("dog")) # the find function starts searching from the left/start side of the str) # and rfind function starts searching from the right hand-side of the str # they both return the index at which the substring was found print(sample_str.find("the")) print(sample_str.rfind("the")) # for knowing if a substr is contained in the str print("the" in sample_str) # using replace new_str = sample_str.replace("lazy", "tired") print(new_str) # counting instances of substrings print(sample_str.count("over")) # CONSOLE OUTPUT: # True # False # True # 31 # 31 # True # The quick brown fox jumps over the tired dog # 1
self.description = "Install a package with an existing file matching a negated --overwrite pattern" p = pmpkg("dummy") p.files = ["foobar"] self.addpkg(p) self.filesystem = ["foobar*"] self.args = "-U --overwrite=foobar --overwrite=!foo* %s" % p.filename() self.addrule("!PACMAN_RETCODE=0") self.addrule("!PKG_EXIST=dummy") self.addrule("!FILE_MODIFIED=foobar")
# @Title: 课程表 (Course Schedule) # @Author: KivenC # @Date: 2020-08-04 09:43:58 # @Runtime: 52 ms # @Memory: 14.3 MB class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # 拓扑排序 # 考虑排在栈的最底层的元素,是没有任何先决条件的 # [a, b] 可用有向图表示 a <- b # 也就是在栈的最底层, 该元素的入度为 0 # 将其出栈后,与其相连的元素入度减 1 # 最后比较出栈次数与总元素个数是否相符 edges = collections.defaultdict(list) indegree = [0] * numCourses visited = 0 for a, b in prerequisites: edges[b].append(a) indegree[a] += 1 # 将入度为 0 的元素入栈 stack = collections.deque([i for i in range(numCourses) if indegree[i] == 0]) while stack: visited += 1 v = stack.popleft() for n in edges[v]: indegree[n] -= 1 if indegree[n] == 0: stack.append(n) return visited == numCourses
config_DMLPDTP2_linear = { "lr": 0.0000001, "target_stepsize": 0.0403226567555006, "feedback_wd": 9.821494271391093e-05, "lr_fb": 0.0022485520139920064, "sigma": 0.06086642605203958, "out_dir": "logs/STRegression/DMLPDTP2_linear", "network_type": "DMLPDTP2", "recurrent_input": False, "hidden_fb_activation": "linear", "size_mlp_fb": None, "fb_activation": "linear", "initialization": "xavier_normal", } config_DTP_pretrained = { "lr": 0.0000001, "target_stepsize": 0.01186235243557516, "feedback_wd": 1.084514667138376e-05, "lr_fb": 0.003289433723080337, "sigma": 0.09999731226483778, "out_dir": "logs/mnist/DTP_improved", "network_type": "DTP", "initialization": "xavier_normal", "fb_activation": "tanh", } config_collection = { "DMLPDTP2_linear": config_DMLPDTP2_linear, "DTP_pretrained": config_DTP_pretrained, } result_keys = [ "loss_train", "loss_test", "bp_angles", "nullspace_relative_norm_angles", "rec_loss", ] config_fixed = { "dataset": "student_teacher", "optimizer": "SGD", "optimizer_fb": "SGD", "momentum": 0.0, "parallel": True, "normalize_lr": True, "batch_size": 1, "forward_wd": 0.0, "epochs_fb": 30, "not_randomized": True, "not_randomized_fb": True, "extra_fb_minibatches": 0, "extra_fb_epochs": 1, "num_train": 400, "num_test": 200, "epochs": 5, "train_only_feedback_parameters": False, "freeze_forward_weights": True, "num_hidden": 2, "size_hidden": 6, "size_input": 6, "size_output": 2, "hidden_activation": "tanh", "output_activation": "linear", "no_bias": False, "no_cuda": False, "random_seed": 42, "cuda_deterministic": False, "freeze_BPlayers": False, "multiple_hpsearch": False, "save_logs": True, "save_BP_angle": True, "save_GN_angle": False, "save_GN_activations_angle": False, "save_BP_activations_angle": False, "save_nullspace_norm_ratio": True, "gn_damping": 0.0, "hpsearch": False, "plots": "compute", "log_interval": 10, } if __name__ == "__main__": pass
''' #list1 = ["Jiggu","JJ","gg","GG"] tuple = ("Jiggu","JJ","gg","GG") #for item in list1: #print(item) for item in tuple: print(item) '''
class DisplayUnitType(Enum,IComparable,IFormattable,IConvertible): """ The units and display format used to format numbers as strings. Also used for unit conversions. enum DisplayUnitType,values: DUT_1_RATIO (182),DUT_ACRES (7),DUT_AMPERES (69),DUT_ATMOSPHERES (54),DUT_BARS (55),DUT_BRITISH_THERMAL_UNIT_PER_FAHRENHEIT (186),DUT_BRITISH_THERMAL_UNITS (31),DUT_BRITISH_THERMAL_UNITS_PER_HOUR (42),DUT_BRITISH_THERMAL_UNITS_PER_HOUR_CUBIC_FOOT (167),DUT_BRITISH_THERMAL_UNITS_PER_HOUR_FOOT_FAHRENHEIT (231),DUT_BRITISH_THERMAL_UNITS_PER_HOUR_SQUARE_FOOT (166),DUT_BRITISH_THERMAL_UNITS_PER_HOUR_SQUARE_FOOT_FAHRENHEIT (155),DUT_BRITISH_THERMAL_UNITS_PER_POUND (233),DUT_BRITISH_THERMAL_UNITS_PER_POUND_FAHRENHEIT (232),DUT_BRITISH_THERMAL_UNITS_PER_SECOND (41),DUT_CALORIES (32),DUT_CALORIES_PER_SECOND (43),DUT_CANDELAS (81),DUT_CANDELAS_PER_SQUARE_METER (80),DUT_CANDLEPOWER (82),DUT_CELSIUS (57),DUT_CELSIUS_DIFFERENCE (244),DUT_CENTIMETERS (1),DUT_CENTIMETERS_PER_MINUTE (62),DUT_CENTIMETERS_TO_THE_FOURTH_POWER (200),DUT_CENTIMETERS_TO_THE_SIXTH_POWER (205),DUT_CENTIPOISES (131),DUT_CUBIC_CENTIMETERS (24),DUT_CUBIC_FEET (13),DUT_CUBIC_FEET_PER_KIP (124),DUT_CUBIC_FEET_PER_MINUTE (63),DUT_CUBIC_FEET_PER_MINUTE_CUBIC_FOOT (169),DUT_CUBIC_FEET_PER_MINUTE_SQUARE_FOOT (156),DUT_CUBIC_FEET_PER_MINUTE_TON_OF_REFRIGERATION (171),DUT_CUBIC_INCHES (23),DUT_CUBIC_METERS (14),DUT_CUBIC_METERS_PER_HOUR (66),DUT_CUBIC_METERS_PER_KILONEWTON (123),DUT_CUBIC_METERS_PER_SECOND (65),DUT_CUBIC_MILLIMETERS (25),DUT_CUBIC_YARDS (10),DUT_CURRENCY (175),DUT_CUSTOM (-1),DUT_CYCLES_PER_SECOND (76),DUT_DECANEWTON_METERS (112),DUT_DECANEWTON_METERS_PER_METER (140),DUT_DECANEWTONS (88),DUT_DECANEWTONS_PER_METER (96),DUT_DECANEWTONS_PER_SQUARE_METER (104),DUT_DECIMAL_DEGREES (15),DUT_DECIMAL_FEET (3),DUT_DECIMAL_INCHES (6),DUT_DECIMETERS (236),DUT_DEGREES_AND_MINUTES (16),DUT_FAHRENHEIT (56),DUT_FAHRENHEIT_DIFFERENCE (243),DUT_FEET_FRACTIONAL_INCHES (4),DUT_FEET_OF_WATER (128),DUT_FEET_OF_WATER_PER_100FT (127),DUT_FEET_PER_KIP (120),DUT_FEET_PER_MINUTE (60),DUT_FEET_PER_SECOND (132),DUT_FEET_PER_SECOND_SQUARED (195),DUT_FEET_TO_THE_FOURTH_POWER (197),DUT_FEET_TO_THE_SIXTH_POWER (202),DUT_FIXED (18),DUT_FOOTCANDLES (78),DUT_FOOTLAMBERTS (79),DUT_FRACTIONAL_INCHES (5),DUT_GALLONS_US (27),DUT_GALLONS_US_PER_HOUR (68),DUT_GALLONS_US_PER_MINUTE (67),DUT_GENERAL (17),DUT_GRADS (215),DUT_GRAINS_PER_HOUR_SQUARE_FOOT_INCH_MERCURY (234),DUT_HECTARES (8),DUT_HERTZ (75),DUT_HORSEPOWER (86),DUT_HOUR_SQUARE_FOOT_FAHRENHEIT_PER_BRITISH_THERMAL_UNIT (184),DUT_HOURS (220),DUT_INCHES_OF_MERCURY (52),DUT_INCHES_OF_WATER (47),DUT_INCHES_OF_WATER_PER_100FT (37),DUT_INCHES_PER_SECOND_SQUARED (194),DUT_INCHES_TO_THE_FOURTH_POWER (198),DUT_INCHES_TO_THE_SIXTH_POWER (203),DUT_INV_CELSIUS (138),DUT_INV_FAHRENHEIT (137),DUT_INV_KILONEWTONS (125),DUT_INV_KIPS (126),DUT_JOULES (34),DUT_JOULES_PER_GRAM (228),DUT_JOULES_PER_GRAM_CELSIUS (227),DUT_JOULES_PER_KELVIN (187),DUT_JOULES_PER_KILOGRAM_CELSIUS (237),DUT_KELVIN (58),DUT_KELVIN_DIFFERENCE (245),DUT_KILOAMPERES (70),DUT_KILOCALORIES (33),DUT_KILOCALORIES_PER_SECOND (44),DUT_KILOGRAM_FORCE_METERS (116),DUT_KILOGRAM_FORCE_METERS_PER_METER (144),DUT_KILOGRAMS_FORCE (92),DUT_KILOGRAMS_FORCE_PER_METER (100),DUT_KILOGRAMS_FORCE_PER_SQUARE_METER (108),DUT_KILOGRAMS_MASS (189),DUT_KILOGRAMS_MASS_PER_METER (212),DUT_KILOGRAMS_MASS_PER_SQUARE_METER (224),DUT_KILOGRAMS_PER_CUBIC_METER (28),DUT_KILOJOULES (223),DUT_KILOJOULES_PER_KELVIN (188),DUT_KILOMETERS_PER_HOUR (221),DUT_KILOMETERS_PER_SECOND_SQUARED (193),DUT_KILONEWTON_METERS (113),DUT_KILONEWTON_METERS_PER_DEGREE (151),DUT_KILONEWTON_METERS_PER_DEGREE_PER_METER (153),DUT_KILONEWTON_METERS_PER_METER (141),DUT_KILONEWTONS (89),DUT_KILONEWTONS_PER_CUBIC_METER (134),DUT_KILONEWTONS_PER_METER (97),DUT_KILONEWTONS_PER_SQUARE_CENTIMETER (178),DUT_KILONEWTONS_PER_SQUARE_METER (105),DUT_KILONEWTONS_PER_SQUARE_MILLIMETER (180),DUT_KILOPASCALS (49),DUT_KILOVOLT_AMPERES (85),DUT_KILOVOLTS (73),DUT_KILOWATT_HOURS (35),DUT_KILOWATTS (40),DUT_KIP_FEET (115),DUT_KIP_FEET_PER_DEGREE (150),DUT_KIP_FEET_PER_DEGREE_PER_FOOT (152),DUT_KIP_FEET_PER_FOOT (143),DUT_KIPS (91),DUT_KIPS_PER_CUBIC_FOOT (149),DUT_KIPS_PER_CUBIC_INCH (136),DUT_KIPS_PER_FOOT (99),DUT_KIPS_PER_INCH (148),DUT_KIPS_PER_SQUARE_FOOT (107),DUT_KIPS_PER_SQUARE_INCH (133),DUT_LITERS (26),DUT_LITERS_PER_MINUTE (242),DUT_LITERS_PER_SECOND (64),DUT_LITERS_PER_SECOND_CUBIC_METER (170),DUT_LITERS_PER_SECOND_KILOWATTS (172),DUT_LITERS_PER_SECOND_SQUARE_METER (157),DUT_LUMENS (83),DUT_LUMENS_PER_WATT (176),DUT_LUX (77),DUT_MEGANEWTON_METERS (114),DUT_MEGANEWTON_METERS_PER_METER (142),DUT_MEGANEWTONS (90),DUT_MEGANEWTONS_PER_METER (98),DUT_MEGANEWTONS_PER_SQUARE_METER (106),DUT_MEGAPASCALS (50),DUT_METERS (0),DUT_METERS_CENTIMETERS (9),DUT_METERS_PER_KILONEWTON (119),DUT_METERS_PER_SECOND (61),DUT_METERS_PER_SECOND_SQUARED (192),DUT_METERS_TO_THE_FOURTH_POWER (201),DUT_METERS_TO_THE_SIXTH_POWER (206),DUT_MICROINCHES_PER_INCH_FAHRENHEIT (239),DUT_MICROMETERS_PER_METER_CELSIUS (238),DUT_MILES_PER_HOUR (222),DUT_MILES_PER_SECOND_SQUARED (196),DUT_MILISECONDS (217),DUT_MILLIAMPERES (71),DUT_MILLIMETERS (2),DUT_MILLIMETERS_OF_MERCURY (53),DUT_MILLIMETERS_TO_THE_FOURTH_POWER (199),DUT_MILLIMETERS_TO_THE_SIXTH_POWER (204),DUT_MILLIVOLTS (74),DUT_MINUTES (219),DUT_NANOGRAMS_PER_PASCAL_SECOND_SQUARE_METER (229),DUT_NEWTON_METERS (111),DUT_NEWTON_METERS_PER_METER (139),DUT_NEWTONS (87),DUT_NEWTONS_PER_METER (95),DUT_NEWTONS_PER_SQUARE_METER (103),DUT_NEWTONS_PER_SQUARE_MILLIMETER (179),DUT_OHM_METERS (230),DUT_PASCAL_SECONDS (129),DUT_PASCALS (48),DUT_PASCALS_PER_METER (38),DUT_PER_MILLE (235),DUT_PERCENTAGE (19),DUT_POUND_FORCE_FEET (118),DUT_POUND_FORCE_FEET_PER_FOOT (146),DUT_POUNDS_FORCE (94),DUT_POUNDS_FORCE_PER_CUBIC_FOOT (135),DUT_POUNDS_FORCE_PER_FOOT (102),DUT_POUNDS_FORCE_PER_SQUARE_FOOT (110),DUT_POUNDS_FORCE_PER_SQUARE_INCH (51),DUT_POUNDS_MASS (191),DUT_POUNDS_MASS_PER_CUBIC_FOOT (29),DUT_POUNDS_MASS_PER_CUBIC_INCH (30),DUT_POUNDS_MASS_PER_FOOT (213),DUT_POUNDS_MASS_PER_FOOT_HOUR (147),DUT_POUNDS_MASS_PER_FOOT_SECOND (130),DUT_POUNDS_MASS_PER_SQUARE_FOOT (225),DUT_RADIANS (214),DUT_RADIANS_PER_SECOND (216),DUT_RANKINE (59),DUT_RANKINE_DIFFERENCE (246),DUT_RATIO_10 (158),DUT_RATIO_12 (159),DUT_RISE_OVER_10_FEET (183),DUT_RISE_OVER_120_INCHES (181),DUT_RISE_OVER_FOOT (162),DUT_RISE_OVER_INCHES (161),DUT_RISE_OVER_MMS (163),DUT_SECONDS (218),DUT_SLOPE_DEGREES (160),DUT_SQUARE_CENTIMETERS (21),DUT_SQUARE_CENTIMETERS_PER_METER (210),DUT_SQUARE_FEET (11),DUT_SQUARE_FEET_PER_FOOT (207),DUT_SQUARE_FEET_PER_KIP (122),DUT_SQUARE_FEET_PER_THOUSAND_BRITISH_THERMAL_UNITS_PER_HOUR (177),DUT_SQUARE_FEET_PER_TON_OF_REFRIGERATION (173),DUT_SQUARE_INCHES (20),DUT_SQUARE_INCHES_PER_FOOT (208),DUT_SQUARE_METER_KELVIN_PER_WATT (185),DUT_SQUARE_METERS (12),DUT_SQUARE_METERS_PER_KILONEWTON (121),DUT_SQUARE_METERS_PER_KILOWATTS (174),DUT_SQUARE_METERS_PER_METER (211),DUT_SQUARE_MILLIMETERS (22),DUT_SQUARE_MILLIMETERS_PER_METER (209),DUT_THERMS (36),DUT_TON_OF_REFRIGERATION (168),DUT_TONNE_FORCE_METERS (117),DUT_TONNE_FORCE_METERS_PER_METER (145),DUT_TONNES_FORCE (93),DUT_TONNES_FORCE_PER_METER (101),DUT_TONNES_FORCE_PER_SQUARE_METER (109),DUT_TONNES_MASS (190),DUT_UNDEFINED (-2),DUT_USTONNES_FORCE (241),DUT_USTONNES_MASS (240),DUT_VOLT_AMPERES (84),DUT_VOLTS (72),DUT_WATTS (39),DUT_WATTS_PER_CUBIC_FOOT (164),DUT_WATTS_PER_CUBIC_METER (165),DUT_WATTS_PER_METER_KELVIN (226),DUT_WATTS_PER_SQUARE_FOOT (45),DUT_WATTS_PER_SQUARE_METER (46),DUT_WATTS_PER_SQUARE_METER_KELVIN (154) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self,*args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self,*args): pass def __gt__(self,*args): pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self,*args): pass def __lt__(self,*args): pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass DUT_1_RATIO=None DUT_ACRES=None DUT_AMPERES=None DUT_ATMOSPHERES=None DUT_BARS=None DUT_BRITISH_THERMAL_UNITS=None DUT_BRITISH_THERMAL_UNITS_PER_HOUR=None DUT_BRITISH_THERMAL_UNITS_PER_HOUR_CUBIC_FOOT=None DUT_BRITISH_THERMAL_UNITS_PER_HOUR_FOOT_FAHRENHEIT=None DUT_BRITISH_THERMAL_UNITS_PER_HOUR_SQUARE_FOOT=None DUT_BRITISH_THERMAL_UNITS_PER_HOUR_SQUARE_FOOT_FAHRENHEIT=None DUT_BRITISH_THERMAL_UNITS_PER_POUND=None DUT_BRITISH_THERMAL_UNITS_PER_POUND_FAHRENHEIT=None DUT_BRITISH_THERMAL_UNITS_PER_SECOND=None DUT_BRITISH_THERMAL_UNIT_PER_FAHRENHEIT=None DUT_CALORIES=None DUT_CALORIES_PER_SECOND=None DUT_CANDELAS=None DUT_CANDELAS_PER_SQUARE_METER=None DUT_CANDLEPOWER=None DUT_CELSIUS=None DUT_CELSIUS_DIFFERENCE=None DUT_CENTIMETERS=None DUT_CENTIMETERS_PER_MINUTE=None DUT_CENTIMETERS_TO_THE_FOURTH_POWER=None DUT_CENTIMETERS_TO_THE_SIXTH_POWER=None DUT_CENTIPOISES=None DUT_CUBIC_CENTIMETERS=None DUT_CUBIC_FEET=None DUT_CUBIC_FEET_PER_KIP=None DUT_CUBIC_FEET_PER_MINUTE=None DUT_CUBIC_FEET_PER_MINUTE_CUBIC_FOOT=None DUT_CUBIC_FEET_PER_MINUTE_SQUARE_FOOT=None DUT_CUBIC_FEET_PER_MINUTE_TON_OF_REFRIGERATION=None DUT_CUBIC_INCHES=None DUT_CUBIC_METERS=None DUT_CUBIC_METERS_PER_HOUR=None DUT_CUBIC_METERS_PER_KILONEWTON=None DUT_CUBIC_METERS_PER_SECOND=None DUT_CUBIC_MILLIMETERS=None DUT_CUBIC_YARDS=None DUT_CURRENCY=None DUT_CUSTOM=None DUT_CYCLES_PER_SECOND=None DUT_DECANEWTONS=None DUT_DECANEWTONS_PER_METER=None DUT_DECANEWTONS_PER_SQUARE_METER=None DUT_DECANEWTON_METERS=None DUT_DECANEWTON_METERS_PER_METER=None DUT_DECIMAL_DEGREES=None DUT_DECIMAL_FEET=None DUT_DECIMAL_INCHES=None DUT_DECIMETERS=None DUT_DEGREES_AND_MINUTES=None DUT_FAHRENHEIT=None DUT_FAHRENHEIT_DIFFERENCE=None DUT_FEET_FRACTIONAL_INCHES=None DUT_FEET_OF_WATER=None DUT_FEET_OF_WATER_PER_100FT=None DUT_FEET_PER_KIP=None DUT_FEET_PER_MINUTE=None DUT_FEET_PER_SECOND=None DUT_FEET_PER_SECOND_SQUARED=None DUT_FEET_TO_THE_FOURTH_POWER=None DUT_FEET_TO_THE_SIXTH_POWER=None DUT_FIXED=None DUT_FOOTCANDLES=None DUT_FOOTLAMBERTS=None DUT_FRACTIONAL_INCHES=None DUT_GALLONS_US=None DUT_GALLONS_US_PER_HOUR=None DUT_GALLONS_US_PER_MINUTE=None DUT_GENERAL=None DUT_GRADS=None DUT_GRAINS_PER_HOUR_SQUARE_FOOT_INCH_MERCURY=None DUT_HECTARES=None DUT_HERTZ=None DUT_HORSEPOWER=None DUT_HOURS=None DUT_HOUR_SQUARE_FOOT_FAHRENHEIT_PER_BRITISH_THERMAL_UNIT=None DUT_INCHES_OF_MERCURY=None DUT_INCHES_OF_WATER=None DUT_INCHES_OF_WATER_PER_100FT=None DUT_INCHES_PER_SECOND_SQUARED=None DUT_INCHES_TO_THE_FOURTH_POWER=None DUT_INCHES_TO_THE_SIXTH_POWER=None DUT_INV_CELSIUS=None DUT_INV_FAHRENHEIT=None DUT_INV_KILONEWTONS=None DUT_INV_KIPS=None DUT_JOULES=None DUT_JOULES_PER_GRAM=None DUT_JOULES_PER_GRAM_CELSIUS=None DUT_JOULES_PER_KELVIN=None DUT_JOULES_PER_KILOGRAM_CELSIUS=None DUT_KELVIN=None DUT_KELVIN_DIFFERENCE=None DUT_KILOAMPERES=None DUT_KILOCALORIES=None DUT_KILOCALORIES_PER_SECOND=None DUT_KILOGRAMS_FORCE=None DUT_KILOGRAMS_FORCE_PER_METER=None DUT_KILOGRAMS_FORCE_PER_SQUARE_METER=None DUT_KILOGRAMS_MASS=None DUT_KILOGRAMS_MASS_PER_METER=None DUT_KILOGRAMS_MASS_PER_SQUARE_METER=None DUT_KILOGRAMS_PER_CUBIC_METER=None DUT_KILOGRAM_FORCE_METERS=None DUT_KILOGRAM_FORCE_METERS_PER_METER=None DUT_KILOJOULES=None DUT_KILOJOULES_PER_KELVIN=None DUT_KILOMETERS_PER_HOUR=None DUT_KILOMETERS_PER_SECOND_SQUARED=None DUT_KILONEWTONS=None DUT_KILONEWTONS_PER_CUBIC_METER=None DUT_KILONEWTONS_PER_METER=None DUT_KILONEWTONS_PER_SQUARE_CENTIMETER=None DUT_KILONEWTONS_PER_SQUARE_METER=None DUT_KILONEWTONS_PER_SQUARE_MILLIMETER=None DUT_KILONEWTON_METERS=None DUT_KILONEWTON_METERS_PER_DEGREE=None DUT_KILONEWTON_METERS_PER_DEGREE_PER_METER=None DUT_KILONEWTON_METERS_PER_METER=None DUT_KILOPASCALS=None DUT_KILOVOLTS=None DUT_KILOVOLT_AMPERES=None DUT_KILOWATTS=None DUT_KILOWATT_HOURS=None DUT_KIPS=None DUT_KIPS_PER_CUBIC_FOOT=None DUT_KIPS_PER_CUBIC_INCH=None DUT_KIPS_PER_FOOT=None DUT_KIPS_PER_INCH=None DUT_KIPS_PER_SQUARE_FOOT=None DUT_KIPS_PER_SQUARE_INCH=None DUT_KIP_FEET=None DUT_KIP_FEET_PER_DEGREE=None DUT_KIP_FEET_PER_DEGREE_PER_FOOT=None DUT_KIP_FEET_PER_FOOT=None DUT_LITERS=None DUT_LITERS_PER_MINUTE=None DUT_LITERS_PER_SECOND=None DUT_LITERS_PER_SECOND_CUBIC_METER=None DUT_LITERS_PER_SECOND_KILOWATTS=None DUT_LITERS_PER_SECOND_SQUARE_METER=None DUT_LUMENS=None DUT_LUMENS_PER_WATT=None DUT_LUX=None DUT_MEGANEWTONS=None DUT_MEGANEWTONS_PER_METER=None DUT_MEGANEWTONS_PER_SQUARE_METER=None DUT_MEGANEWTON_METERS=None DUT_MEGANEWTON_METERS_PER_METER=None DUT_MEGAPASCALS=None DUT_METERS=None DUT_METERS_CENTIMETERS=None DUT_METERS_PER_KILONEWTON=None DUT_METERS_PER_SECOND=None DUT_METERS_PER_SECOND_SQUARED=None DUT_METERS_TO_THE_FOURTH_POWER=None DUT_METERS_TO_THE_SIXTH_POWER=None DUT_MICROINCHES_PER_INCH_FAHRENHEIT=None DUT_MICROMETERS_PER_METER_CELSIUS=None DUT_MILES_PER_HOUR=None DUT_MILES_PER_SECOND_SQUARED=None DUT_MILISECONDS=None DUT_MILLIAMPERES=None DUT_MILLIMETERS=None DUT_MILLIMETERS_OF_MERCURY=None DUT_MILLIMETERS_TO_THE_FOURTH_POWER=None DUT_MILLIMETERS_TO_THE_SIXTH_POWER=None DUT_MILLIVOLTS=None DUT_MINUTES=None DUT_NANOGRAMS_PER_PASCAL_SECOND_SQUARE_METER=None DUT_NEWTONS=None DUT_NEWTONS_PER_METER=None DUT_NEWTONS_PER_SQUARE_METER=None DUT_NEWTONS_PER_SQUARE_MILLIMETER=None DUT_NEWTON_METERS=None DUT_NEWTON_METERS_PER_METER=None DUT_OHM_METERS=None DUT_PASCALS=None DUT_PASCALS_PER_METER=None DUT_PASCAL_SECONDS=None DUT_PERCENTAGE=None DUT_PER_MILLE=None DUT_POUNDS_FORCE=None DUT_POUNDS_FORCE_PER_CUBIC_FOOT=None DUT_POUNDS_FORCE_PER_FOOT=None DUT_POUNDS_FORCE_PER_SQUARE_FOOT=None DUT_POUNDS_FORCE_PER_SQUARE_INCH=None DUT_POUNDS_MASS=None DUT_POUNDS_MASS_PER_CUBIC_FOOT=None DUT_POUNDS_MASS_PER_CUBIC_INCH=None DUT_POUNDS_MASS_PER_FOOT=None DUT_POUNDS_MASS_PER_FOOT_HOUR=None DUT_POUNDS_MASS_PER_FOOT_SECOND=None DUT_POUNDS_MASS_PER_SQUARE_FOOT=None DUT_POUND_FORCE_FEET=None DUT_POUND_FORCE_FEET_PER_FOOT=None DUT_RADIANS=None DUT_RADIANS_PER_SECOND=None DUT_RANKINE=None DUT_RANKINE_DIFFERENCE=None DUT_RATIO_10=None DUT_RATIO_12=None DUT_RISE_OVER_10_FEET=None DUT_RISE_OVER_120_INCHES=None DUT_RISE_OVER_FOOT=None DUT_RISE_OVER_INCHES=None DUT_RISE_OVER_MMS=None DUT_SECONDS=None DUT_SLOPE_DEGREES=None DUT_SQUARE_CENTIMETERS=None DUT_SQUARE_CENTIMETERS_PER_METER=None DUT_SQUARE_FEET=None DUT_SQUARE_FEET_PER_FOOT=None DUT_SQUARE_FEET_PER_KIP=None DUT_SQUARE_FEET_PER_THOUSAND_BRITISH_THERMAL_UNITS_PER_HOUR=None DUT_SQUARE_FEET_PER_TON_OF_REFRIGERATION=None DUT_SQUARE_INCHES=None DUT_SQUARE_INCHES_PER_FOOT=None DUT_SQUARE_METERS=None DUT_SQUARE_METERS_PER_KILONEWTON=None DUT_SQUARE_METERS_PER_KILOWATTS=None DUT_SQUARE_METERS_PER_METER=None DUT_SQUARE_METER_KELVIN_PER_WATT=None DUT_SQUARE_MILLIMETERS=None DUT_SQUARE_MILLIMETERS_PER_METER=None DUT_THERMS=None DUT_TONNES_FORCE=None DUT_TONNES_FORCE_PER_METER=None DUT_TONNES_FORCE_PER_SQUARE_METER=None DUT_TONNES_MASS=None DUT_TONNE_FORCE_METERS=None DUT_TONNE_FORCE_METERS_PER_METER=None DUT_TON_OF_REFRIGERATION=None DUT_UNDEFINED=None DUT_USTONNES_FORCE=None DUT_USTONNES_MASS=None DUT_VOLTS=None DUT_VOLT_AMPERES=None DUT_WATTS=None DUT_WATTS_PER_CUBIC_FOOT=None DUT_WATTS_PER_CUBIC_METER=None DUT_WATTS_PER_METER_KELVIN=None DUT_WATTS_PER_SQUARE_FOOT=None DUT_WATTS_PER_SQUARE_METER=None DUT_WATTS_PER_SQUARE_METER_KELVIN=None value__=None
# program for check two strings are anagram or not # https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/ # time complexity is O(n) and space is O(1) def isAnagram(str1, str2): if(len(str1) != len(str2)): return False count = 0 # sum up all the chars ascii values for i in str1: count += ord(i) # subtract next string each char from sum for i in str2: count -= ord(i) # if count contains 0 then it's anagram return count == 0 # time complexity is O(nlogn) def is_anagram(str1, str2): # anagram string should be same length if(len(str1) != len(str2)): return False # sorting the string in ascending order str1 = sorted(str1) str2 = sorted(str2) # if both contains same chars return True return str1 == str2 if __name__ == '__main__': str1 = input('Enter string ').lower() str2 = input('Enter another string ').lower() # invoke the first function ana = is_anagram(str1, str2) anagram = isAnagram(str1, str2) if(ana and anagram): print('Strings are anagram') else: print('Strings are not anagram')
# MIT License # (C) Copyright 2021 Hewlett Packard Enterprise Development LP. # # interfaceLabels : Save and delete labels for interfaces def get_all_interface_labels( self, active: bool = None, ) -> dict: """Get all configured interface labels. Can filter response for active labels or inactive labels with ``active`` parameter. .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - interfaceLabels - GET - /gms/interfaceLabels :param active: ``True`` to filter for active labels, ``False`` to filter for inactive labels. :type active: bool, optional :return: Returns dictionary of configured interface labels \n * keyword **wan** (`dict`): Dictionary of wan interface labels\n * keyword **<label_id>** (`dict`): Interface label id \n * keyword **name** (`str`): Name of interface label * keyword **topology** (`int`): Allowed topology for building tunnels. ``0`` allows full mesh, ``2`` limits to hub & spoke topology. * keyword **active** (`bool`): ``True`` if active, ``False`` if inactive * keyword **lan** (`dict`): Dictionary of lan interface labels\n * keyword **<label_id>** (`dict`): Interface label id \n * keyword **name** (`str`): Name of interface label * keyword **topology** (`int`): Allowed topology for building tunnels. ``0`` allows full mesh, ``2`` limits to hub & spoke topology. * keyword **active** (`bool`): ``True`` if active, ``False`` if inactive :rtype: dict """ path = "/gms/interfaceLabels" if active is not None: path = path + "?active={}".format(active) return self._get(path) def update_interface_labels( self, interface_label_config: dict, delete_dependencies: bool = None, ) -> bool: """Save interface labels, **NOTE** this will completely replace the current implementation. You cannot remove labels that are in use in an overlay. Label ids have to be unique across both wan and lan. .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - interfaceLabels - POST - /gms/interfaceLabels **Example:** .. code-block:: interface_label_config = { "wan": { "1": { "name": "MPLS1", "active": true, "topology": 0 }, "2": { "name": "INET1", "active": true, "topology": 0 }, "3": { "name": "LTE", "active": true, "topology": 2 }, "6": { "name": "INET2", "active": true, "topology": 0 }, "7": { "name": "MPLS2", "active": true, "topology": 0 } }, "lan": { "4": { "name": "Voice", "active": true, "topology": 0 }, "5": { "name": "Data", "active": true, "topology": 0 } } } :param interface_label_config: Interface label configuration \n * keyword **wan** (`dict`): Dictionary of wan interface labels\n * keyword **<label_id>** (`dict`): Unique interface label id as a string integer, e.g. ``1`` \n * keyword **name** (`str`): Name of interface label * keyword **topology** (`int`): Allowed topology for building tunnels. ``0`` allows full mesh, ``2`` limits to hub & spoke topology. * keyword **active** (`bool`): ``True`` if active, ``False`` if inactive * keyword **lan** (`dict`): Dictionary of lan interface labels\n * keyword **<label_id>** (`dict`): Unique interface label id as a string integer, e.g. ``1`` \n * keyword **name** (`str`): Name of interface label * keyword **topology** (`int`): Allowed topology for building tunnels. ``0`` allows full mesh, ``2`` limits to hub & spoke topology. * keyword **active** (`bool`): ``True`` if active, ``False`` if inactive :type interface_label_config: dict :param delete_dependencies: ``True`` to delete labels from port profiles and templates using it, ``False`` to not remove them. :type delete_dependencies: bool, optional :return: Returns True/False based on successful call :rtype: bool """ path = "/gms/interfaceLabels" if delete_dependencies is not None: path = path + "?deleteDependencies={}".format(delete_dependencies) return self._post( "/gms/interfaceLabels", data=interface_label_config, expected_status=[204], return_type="bool", ) def get_interface_labels_by_type( self, label_type: str, active: bool = None, ) -> dict: """Get all configured interface labels of either wan or lan. Can filter response for active labels or inactive labels with ``active`` parameter. .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - interfaceLabels - GET - /gms/interfaceLabels/{type} :param label_type: ``wan`` to return wan-related labels, ``lan`` to return lan-related labels :type label_type: str :param active: ``True`` to filter for active labels, ``False`` to filter for inactive labels. :type active: bool, optional :return: Returns dictionary of wan or lan interface labels \n * keyword **<label_id>** (`dict`): Interface label id \n * keyword **name** (`str`): Name of interface label * keyword **topology** (`int`): Allowed topology for building tunnels. ``0`` allows full mesh, ``2`` limits to hub & spoke topology. * keyword **active** (`bool`): ``True`` if active, ``False`` if inactive :rtype: dict """ path = "/gms/interfaceLabels/{}".format(label_type) if active is not None: path = path + "?active={}".format(active) return self._get(path) def push_interface_labels_to_appliance( self, ne_pk: str, ) -> dict: """Pushes the active interface labels on Orchestrator to an appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - interfaceLabels - POST - /interfaceLabels/{nePk} :param ne_pk: Appliance id in the format of integer.NE e.g. ``3.NE`` :type ne_pk: str :return: Returns True/False based on successful call :rtype: bool """ return self._post("interfaceLabels/{}".format(ne_pk), return_type="bool")
''' Provides one variable __version__. Caution: All code in here will be executed by setup.py. ''' __version__ = '0.2.2'
def my_name(): print("name") # calls my_name my_name() def square(x): # devuelve el valor return x * x n = square(5) print(n) # declarandro función power # que recibe dos paramatros y los # llamo "x" y "n". def power(x, n): p = 1 for i in range(n): # p = p * x p *= x return p power_2 = power(2, 2) # 4 print(power_2) # define una función que devuelva una nota ("A", "B", ...) # para el numero que le pase def many_return(x): if x % 2 == 0: return "even" else: return "odd" print(many_return(5)) # def nota(puntos, valor_de_examen): # porcentage = puntos / valor_de_examen # grade(porcentage) # example of one function calling another function def even_or_odd(n): if n % 2 == 0: return "even" else: return "odd" def can_fly(wing_span): oddness = even_or_odd(wing_span) if oddness == "even": return True else: return False # recursive function # that calculates factorial numbers def factorial(n): if n <= 2: return n else: n * factorial(n - 1)
class Pipe(object): def __init__(self, function): self.function = function def __ror__(self, other): return self.function(other) def __call__(self, *args, **kwargs): return Pipe(lambda x: self.function(x, *args, **kwargs))
def cprint(c): r, i = c.real, c.imag if r != 0: if i > 0: print('{:.2f} + {:.2f}i'.format(r, i)) elif i < 0: print('{:.2f} - {:.2f}i'.format(r, abs(i))) else: print('{:.2f}'.format(r)) else: if i != 0: print('{:.2f}i'.format(i)) else: print('{:.2f}'.format(0)) cr, ci = map(float, input().split()) dr, di = map(float, input().split()) c = complex(cr, ci) d = complex(dr, di) cprint(c+d) cprint(c-d) cprint(c*d) cprint(c/d) print('{0:.2f}'.format(abs(c))) print('{0:.2f}'.format(abs(d)))
# this is the content of the HTML file which might be better # used as a simple open.read but we need to put in the bs4.... SRC_HTML = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Test Source HTML</title> <style type="text/css"> a, body, div, span, td {font-family:Lucida Sans Unicode,Arial Unicode MS,Lucida Sans,Helvetica,Arial,sans-serif} </style> </head> <body> <div id="A"> <h2>A</h2> <p>All nouns beginning with <span lang="HAW">a-</span> or <span lang="HAW">ā-</span> may be preceded by the article <span lang="HAW">ke</span>. Nouns beginning with <span lang="HAW">ʻa-</span> or <span lang="HAW">ʻā-</span> may be preceded by the article <span lang="HAW">ka</span>, unless otherwise stated.</p> <div id="A.1"> <span lang="HAW">a </span> <p><span>1.</span> <span>prep.</span> Of, acquired by. This <span lang="HAW">a</span> forms part of the possessives, as in <span lang="HAW">ka'u</span>, mine, and <span lang="HAW">kāna</span>, his. (<span>Gram. 9.6.1</span>.)<span lang="HAW">ʻUmi-a-Līloa</span>, <span lang="ENG"><span lang="HAW">ʻUmi</span>, [son] of <span lang="HAW">Līloa</span></span>. <span lang="HAW">Hale-a-ka-lā</span>, <span lang="ENG">house acquired [or used] by the sun [mountain name]</span>. (PPN <span lang="HAW">ʻa</span>.)</p> <p><span>2.</span> <em>(Cap.)</em> <span>nvs.</span> Abbreviation of <span lang="HAW">ʻākau</span>, north, as in surveying reports.</p> </div> <div id="A.2"> <span lang="HAW">-a </span> <p>Pas/imp. suffix. (<span>Gram. 6.6.3</span>.) (PPN <span lang="HAW">-a</span>.)</p> </div> <div id="A.15"> <span lang="HAW">ʻaʻa.ʻā </span> <p><span>1.</span> Redup. of <span lang="HAW">ʻaʻā</span> 1; lava cave.</p> <p><span>2.</span> Redup. of <span lang="HAW">ʻāʻā</span> 1.</p> </div> <div id="A.18"> <span lang="HAW">ʻaʻa.ahi </span> <p><span>n.</span> Bag for carrying fire-making equipment (<span lang="HAW">ʻaʻa</span>, <span lang="ENG">bag</span>, and <span lang="HAW">ahi</span>, <span lang="ENG">fire</span>).</p> </div> <div id="A.1762"> <span lang="HAW">&#699;&#257;.w&#299;.w&#299; </span> <p><span>vi.</span> To hurry; speedy, swift, quick, fast.</p> </div> </div> </body> </html> """ SRC_TEXT = """ Test Source HTML a, body, div, span, td {font-family:Lucida Sans Unicode,Arial Unicode MS,Lucida Sans,Helvetica,Arial,sans-serif} A All nouns beginning with a- or ā- may be preceded by the article ke. Nouns beginning with ʻa- or ʻā- may be preceded by the article ka, unless otherwise stated. a 1. prep. Of, acquired by. This a forms part of the possessives, as in ka'u, mine, and kāna, his. (Gram. 9.6.1.)ʻUmi-a-Līloa, ʻUmi, [son] of Līloa. Hale-a-ka-lā, house acquired [or used] by the sun [mountain name]. (PPN ʻa.) 2. (Cap.) nvs. Abbreviation of ʻākau, north, as in surveying reports. -a Pas/imp. suffix. (Gram. 6.6.3.) (PPN -a.) ʻaʻa.ʻā 1. Redup. of ʻaʻā 1; lava cave. 2. Redup. of ʻāʻā 1. ʻaʻa.ahi n. Bag for carrying fire-making equipment (ʻaʻa, bag, and ahi, fire). ʻā.wī.wī vi. To hurry; speedy, swift, quick, fast. """
"""October 5th, 2020: Write a Python function called counts that takes a list as input and returns a dictionary of unique items in the list as keys and the number of times each item appears as values. So, the input ['A', 'A', 'B', 'C', 'A'] should have output {'A': 3, 'B': 1, 'C': 1} . Your code should not depend on any module from the standard library or otherwise. You should research the task first and include a description with references of your algorithm in the notebook.""" # Creating an empty Dictionary """https://www.geeksforgeeks.org/python-dictionary/#:~:text=Creating%20a%20Dictionary,element%20being%20its%20Key%3Avalue%20.""" Dict = {} # Your code should not depend on any module from the standard library or otherwise. # I have used Bubble sort as an alternative to inbuilt function sorted. # There are many ready made sort algorithms such as Merge Sort, Tim Sort (which Python uses) each have their own strengths. # I have copied the Bubble sort code and comments in its entirety from url below. # Bubble sort is not always the fastest. I have used this Bubble sort code because it is concise and well commented by the author. """https://realpython.com/sorting-algorithms-python/""" def bubble_sort(array): n = len(array) for i in range(n): # Create a flag that will allow the function to # terminate early if there's nothing left to sort already_sorted = True # Start looking at each item of the list one by one, # comparing it with its adjacent value. With each # iteration, the portion of the array that you look at # shrinks because the remaining items have already been # sorted. for j in range(n - i - 1): if array[j] > array[j + 1]: # If the item you're looking at is greater than its # adjacent value, then swap them array[j], array[j + 1] = array[j + 1], array[j] # Since you had to swap two elements, # set the `already_sorted` flag to `False` so the # algorithm doesn't finish prematurely already_sorted = False # If there were no swaps during the last iteration, # the array is already sorted, and you can terminate if already_sorted: break return array #takes a list of inputs separated by commas "https://pynative.com/python-accept-list-input-from-user/" input_string = input("Enter a list elements separated by COMMA ") userList = input_string.split(",") print("user list is ", userList) #calls the User list and applies the bubble_sort function to sort it str = userList print("The sorted list is:", bubble_sort(str)) my_sorted_dictionary_keys = bubble_sort(str) #python counting letters without count function """https://stackoverflow.com/questions/28966495/python-counting-letters-in-string-without-count-function""" def count_letters(my_letter): count = 0 for i in userList: if i == my_letter: count = count + 1 else: continue return (count) #add key value pairs to dictionary #call function count_letters """https://www.geeksforgeeks.org/add-a-keyvalue-pair-to-dictionary-in-python/""" for letter in my_sorted_dictionary_keys: Dict[letter] = count_letters(letter) print("Dictionary sorted by keys from list, count of each letter in list", Dict)
#"__bases__" es una tupla, contiene clases (no nombres de clases) # que son superclases directas para la clase. #Nota: solo las clases tienen este atributo - los objetos no. #Nota: una clase sin superclases explícitas apunta al objeto # (una clase de Python predefinida) como su antecesor directo class SuperUno: pass class SuperDos: pass class Sub(SuperUno, SuperDos): pass def printBases(cls): print('( ', end='') for x in cls.__bases__: print(x.__name__, end=' ') print(')') printBases(SuperUno) printBases(SuperDos) printBases(Sub)
ei = 3 suu1 = int(ei) suu2 = int(ei*ei) suu3 = int(ei*ei*ei) print(suu1 + suu2 + suu3)
# -*- coding: utf-8 -*- # 商户会员卡服务 class CardService: __client = None def __init__(self, client): self.__client = client def upload_image(self, image_base_6_4): """ 上传图片 :param imageBase64:上传图片 """ return self.__client.call("eleme.card.uploadImage", {"imageBase64": image_base_6_4}) def create_template(self, template_info): """ 创建模板 :param templateInfo:模板信息 """ return self.__client.call("eleme.card.createTemplate", {"templateInfo": template_info}) def mget_template_info(self, template_id): """ 查询模板信息 :param templateId:模板id列表 """ return self.__client.call("eleme.card.mgetTemplateInfo", {"templateId": template_id}) def update_template(self, template_id, template_info): """ 更新模板信息 :param templateId:模板id :param templateInfo:模板更新信息 """ return self.__client.call("eleme.card.updateTemplate", {"templateId": template_id, "templateInfo": template_info}) def mget_shop_ids_by_template_ids(self, template_id): """ 查询模板应用的店铺 :param templateId:模板id列表 """ return self.__client.call("eleme.card.mgetShopIdsByTemplateIds", {"templateId": template_id}) def apply_template(self, template_id, shop_ids): """ 应用模板 :param templateId:模板id :param shopIds:店铺列表 """ return self.__client.call("eleme.card.applyTemplate", {"templateId": template_id, "shopIds": shop_ids}) def open_card(self, template_id, card_user_info, card_account_info): """ 开卡 :param templateId:模板ID :param cardUserInfo:会员用户信息 :param cardAccountInfo:会员账户信息 """ return self.__client.call("eleme.card.openCard", {"templateId": template_id, "cardUserInfo": card_user_info, "cardAccountInfo": card_account_info}) def update_user_info(self, card_user_info, card_account_info): """ 更新会员信息 :param cardUserInfo:用户基本信息 :param cardAccountInfo:用户账户信息 """ return self.__client.call("eleme.card.updateUserInfo", {"cardUserInfo": card_user_info, "cardAccountInfo": card_account_info}) def get_user_by_token(self, user_token): """ 根据userToken获取用户信息 :param userToken:userToken有效期10分钟。饿了么app上跳转到外部H5页面www.abc.com/aaa?userToken=aaabbbccc,aaabbbccc为userToken,用其作为该接口的入参获取到用户信息 """ return self.__client.call("eleme.card.getUserByToken", {"userToken": user_token})
# Write your frequency_dictionary function here: def frequency_dictionary(words): freqs = {} for word in words: if word not in freqs: freqs[word] = 0 freqs[word] += 1 return freqs # Uncomment these function calls to test your function: print(frequency_dictionary(["apple", "apple", "cat", 1])) # should print {"apple":2, "cat":1, 1:1} print(frequency_dictionary([0,0,0,0,0])) # should print {0:5}
a = {} a["ad ad asd"] = 4 b = 4 if (b is a["ad ad asd"]): print("jaka") else: print ("luka") print (str([[0, 0, 0], [0, 0, 0], [0, 0, 0]]))
def calc_percentage_at_k(test, pred, k): # sort scores, ascending pred, test = zip(*sorted(zip(pred, test))) pred, test = list(pred), list(test) pred.reverse() test.reverse() # calculates number of values to consider n_percentage = round(len(pred) * k / 100) # check if predicted is equal to true value, and count it # set true and false positive counters tp, fp = 0, 0 for i in range(n_percentage): # true positive if test[i] == 1: tp += 1 precision_at_k = tp / n_percentage return round(precision_at_k * 100, 2)
print("Enter elements:") arr=list(map(int,input().split())) for i in range(1, len(arr)): val=arr[i] j=i-1 while j>=0 and val<arr[j]: arr[j+1]=arr[j] j-=1 arr[j+1]=val print(arr)
class Solution: def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: n, m = len(nums), len(multipliers) dp = [[0] * (m + 1) for _ in range(m + 1)] for i in range(m - 1, -1, -1): for left in range(i, -1, -1): mult = multipliers[i] right = n - 1 - (i - left) dp[i][left] = max(mult * nums[left] + dp[i + 1][left + 1], mult * nums[right] + dp[i + 1][left]) return dp[0][0] def maximumScore1(self, nums: List[int], mult: List[int]) -> int: @functools.lru_cache(maxsize=2000) def dp(left, i): if i >= len(mult): return 0 right = len(nums) - 1 - (i - left) return max(mult[i] * nums[left] + dp(left+1, i+1), mult[i] * nums[right] + dp(left, i+1)) return dp(0, 0)
HOST = 'localhost' PORT = 27017 # -- HTTP-SESSION Settings -- HTTP_SESSION_TOKEN_TIMEOUT = 0 HTTP_SESSION_TOKEN_SIZE = 24 # -- Existing Commands -- COMMANDS_UNKNOWN = ['login', 'me', 'asset', 'user', 'plugin'] COMMANDS_USER = ['login', 'user', 'me', 'asset', 'logout', 'plugin', 'document', 'following', 'followers', 'follow'] COMMANDS_ADMIN = [''].append(COMMANDS_USER) # -- MACE MACE_FOLDER = 'mace/' MACE_ANNOTATIONS = 'argotario.csv' MACE_COMPETENCES = 'competence' MACE_PREDICTIONS = 'prediction' MACE_TIMEOUT = 60 * 60 * 4 MIN_VOTINGS = 4 # -- COMMUNICATION-SESSION SESSION_TIMEOUT = 86400 # --GAME-SESSION GSESSION_TICKER = 4 GSESSION_TIMEOUT = 86400 # --DB-TIMEOUT DB_RETRY = 5 DB_SERVER_SELECTION_TIMEOUT = 100 # -- GENERAL SETTINGS NAME = 'Argotario Python Backend Server' WELCOME = 'Welcome!' WEBSITE = 'https://argue.ukp.informatik.tu-darmstadt.de' VERSION = '1.0-SNAPSHOT' # --EMAIL SETTINGS MAIL_FROM = 'argotario@example.com' MAIL_TO = 'text@example.com' MAIL_SMTP = 'smtp.example.com' MAIL_PASSWORD = 'random_generated_safe_password'
# -*- coding: utf-8 -*- # Scrapy settings for book_spider project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'book_spider' SPIDER_MODULES = ['book_spider.spiders'] NEWSPIDER_MODULE = 'book_spider.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'book_spider (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 1 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'book_spider.middlewares.MyCustomSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'book_spider.middlewares.MyCustomDownloaderMiddleware': 543, #} DOWNLOADER_MIDDLEWARES = { 'book_spider.middlewares.RandomUserAgent': 100, # 'book_spider.middlewares.RandomProxy': 200 } User_Agents = [ 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60 ', 'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50 ', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0 ', 'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 ', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11 ', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36 ', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER ', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER) ', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)”', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400) ', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)', 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0 ', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 UBrowser/4.0.3214.0 Safari/537.36', 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5', 'Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5', 'Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5 ', 'Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5', 'Mozilla/5.0 (Linux; U; Android 2.2.1; zh-cn; HTC_Wildfire_A3333 Build/FRG83D) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 ', 'Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1', 'MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1', 'Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10', 'Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13', 'Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+', 'Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0', 'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)' ] PROXIES = [ {'ip_port':'111.155.116.222:8123','user_passwd':''}, {'ip_port':'61.135.217.7:80','user_passwd':''}, {'ip_port':'61.135.217.7:80','user_passwd':''} ] # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'book_spider.pipelines.BookSpiderPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
# Time: O(n) # Space: O(n) # mono stack, prefix sum, optimized from solution2 class Solution(object): def totalStrength(self, strength): """ :type strength: List[int] :rtype: int """ MOD = 10**9+7 curr = 0 prefix = [0]*(len(strength)+1) for i in xrange(len(strength)): curr = (curr+strength[i])%MOD prefix[i+1] = (prefix[i]+curr)%MOD stk, result = [-1], 0 for i in xrange(len(strength)+1): while stk[-1] != -1 and (i == len(strength) or strength[stk[-1]] >= strength[i]): x, y, z = stk[-2]+1, stk.pop(), i-1 # assert(all(strength[j] >= strength[y] for j in xrange(x, y+1))) # assert(all(strength[j] > strength[y] for j in xrange(y+1, z+1))) result = (result+(strength[y]*((y-x+1)*(prefix[z+1]-prefix[y])-(z-y+1)*(prefix[y]-prefix[max(x-1, 0)]))))%MOD stk.append(i) return result # Time: O(n) # Space: O(n) # mono stack, prefix sum class Solution2(object): def totalStrength(self, strength): """ :type strength: List[int] :rtype: int """ MOD = 10**9+7 prefix, prefix2 = [0]*(len(strength)+1), [0]*(len(strength)+1) for i in xrange(len(strength)): prefix[i+1] = (prefix[i]+strength[i])%MOD prefix2[i+1] = (prefix2[i]+strength[i]*(i+1))%MOD suffix, suffix2 = [0]*(len(strength)+1), [0]*(len(strength)+1) for i in reversed(xrange(len(strength))): suffix[i] = (suffix[i+1]+strength[i])%MOD suffix2[i] = (suffix2[i+1]+strength[i]*(len(strength)-i))%MOD stk, result = [-1], 0 for i in xrange(len(strength)+1): while stk[-1] != -1 and (i == len(strength) or strength[stk[-1]] >= strength[i]): x, y, z = stk[-2]+1, stk.pop(), i-1 # assert(all(strength[j] >= strength[y] for j in xrange(x, y+1))) # assert(all(strength[j] > strength[y] for j in xrange(y+1, z+1))) result = (result+(strength[y]*((z-y+1)*((prefix2[y+1]-prefix2[x])-x*(prefix[y+1]-prefix[x]))+ (y-x+1)*((suffix2[y+1]-suffix2[z+1])-(len(strength)-(z+1))*(suffix[y+1]-suffix[z+1])))))%MOD stk.append(i) return result
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param p, a tree node # @param q, a tree node # @return a boolean def isSameTree(self, p, q): if p == None or q == None: return p == q return p.val == q.val and self.isSameTree(p.left, q.left) \ and self.isSameTree(p.right, q.right)
class CommodityModel: def __init__(self, cid=0, name="", price=0, cm=0): self.cid = cid self.name = name self.price = price self.cm = cm def __str__(self): return f"商品名称是{self.name},编号是{self.cid},价格是{self.price},识别码是{self.cm}" def __eq__(self, other): return self.cm == other.cm class CommodityView: def __init__(self): self.__controller = CommodityController() def __display_veiw_menu(self): print("按1键录入商品信息") print("按2键显示商品信息") print("按3键删除商品信息") print("按4键修改商品信息") def __select_menu(self): giao = int(input("请输入按键")) if giao == 1: self.__input_commodity_info() elif giao == 2: self.__display_commodity_info() elif giao == 3: self.__remove_commodity_info() elif giao == 4: self.__update_commodity_info() def __input_commodity_info(self): ccm = CommodityModel() ccm.name = input("请输入商品名称:") ccm.price = int(input("请输入商品价格:")) ccm.cid = int(input("请输入商品编号:")) self.__controller.addto_datebase_of_Commodityinfo(ccm) print("成功!!!") def main(self): while 1: self.__display_veiw_menu() self.__select_menu() def __display_commodity_info(self): for i in self.__controller.list_of_commodity: print(i) def __remove_commodity_info(self): cm = int(input("请输入您要删除的商品的商品识别码:")) if self.__controller.removed_info(cm): print("删除成功") else: print("删除失败") def __update_commodity_info(self): ccm = CommodityModel() ccm.cm = int(input("请输入您需要修改的商品的编号:")) ccm.cid = input("请输入商品编号") ccm.name = input("请输入商名称") ccm.price = input("请输入商品价格") if self.__controller.update_info(ccm): print("修改成功") else: print("修改失败") class CommodityController: def __init__(self): self.__list_of_commodity = [] self.number_of_cm = 1000 @property def list_of_commodity(self): return self.__list_of_commodity def addto_datebase_of_Commodityinfo(self, comdity_info): comdity_info.cm = self.number_of_cm self.number_of_cm += 1 self.__list_of_commodity.append(comdity_info) def removed_info(self, cm): cm1 = CommodityModel(cm=cm) if cm1 in self.__list_of_commodity: self.__list_of_commodity.remove(cm1) return True else: return False def update_info(self, ccm): for i in self.__list_of_commodity: if i.cm == ccm.cm: i.__dict__ = ccm.__dict__ return True return False v = CommodityView() v.main()
sentence = "What is the Airspeed Velocity of an Unladen Swallow?".split() count = {word:len(word) for word in sentence} print(count)
"""Day 2 funcs""" def interpret_instructions(instructions: str) -> list[tuple[str, int]]: """Reads instructions and returns a list of directions and numbers""" ret: list[tuple[str, int]] = [] instruction_list = instructions.split("\n") for instruction in instruction_list: instruction_tokens = instruction.split(" ") # First element in each instruction is a direction. # Convert second element in each instruction to distance. try: direction: str = instruction_tokens[0] distance: int = int(instruction_tokens[1]) ret.append((direction, distance)) except TypeError: print("Malformed Instructions") return ret def steer_submarine(instructions: list[tuple[str, int]]) -> int: """Steer the sub based on a list of instructions""" hor_axis: int = 0 depth: int = 0 for instruction in instructions: match instruction[0]: case "forward": hor_axis += instruction[1] case "up": depth -= instruction[1] case "down": depth += instruction[1] return hor_axis * depth
skaitli = [1, 5, 3, 9, 7, 11, 4] skaitli2 = [5, 8, 12, 77, 44, 13] print(skaitli) print(skaitli[4]) sajauts_saraksts = ["Maris", 1, 2, 3, "Liepa", ["burkani", 12]] print(sajauts_saraksts) skaitli_kopa = skaitli + skaitli2 skaitli_kopa.sort() print(skaitli_kopa)
""" Helper to get relation to extractors, questions and their weights """ def weight_to_string(extractor, weight_index, question: str = None): """ naming for a weight :param extractor: :param weight_index: :return: """ if extractor == 'action': if weight_index == 0: return 'position' elif weight_index == 1: return 'frequency' elif weight_index == 2: return 'named_entity' elif extractor == 'cause': if weight_index == 0: return 'position' elif weight_index == 1: return 'clausal conjunction' elif weight_index == 2: return 'adverbial indicator' elif weight_index == 3: return 'NP-VP-NP' elif extractor == 'environment': if question.startswith('where'): if weight_index == 0: return 'position' elif weight_index == 1: return 'frequency' elif weight_index == 2: return 'entailment' elif weight_index == 3: return 'accurate' if question.startswith('when'): if weight_index == 0: return 'position' elif weight_index == 1: return 'frequency' elif weight_index == 2: return 'entailment' elif weight_index == 3: return 'distance_from_publisher_date' elif weight_index == 4: return 'accurate' elif extractor == 'method': if weight_index == 0: return 'position' elif weight_index == 1: return 'frequency' elif weight_index == 2: return 'conjunction' elif weight_index == 3: return 'adjectives_adverbs' else: return 'no_mapping' def question_to_extractor(question: str): """ extractor for a given question :param question: :return: """ if question == 'who' or question == 'what': return 'action' elif question == 'why': return 'cause' elif question == 'where' or question == 'when': return 'environment' elif question == 'how': return 'method' else: return 'no_mapping' def extractor_to_question(extractor: str): """ return questions for a extractor in a tuple :param extractor: :return: """ if extractor == 'action': return ('who', 'what') elif extractor == 'cause': return ('why',) elif extractor == 'environment': return ('where', 'when') elif extractor == 'method': return ('how',) else: return ('no_mapping',)
TIME_FORMAT = "%Y-%m-%d, %H:%M:%S" FILE_TRAIN_DATA_STATS = "train_data_stats.txt" FILE_EVAL_DATA_STATS = "eval_data_stats.txt" FILE_PREV_EVAL_DATA_STATS = "prev_eval_data_stats.txt" FILE_DATA_SCHEMA = "schema.txt" FILE_EVAL_RESULT = "eval_result.txt" VALIDATION_SUCCESS = "success" VALIDATION_FAIL = "fail"
class Color(object): def __init__(self, r : float, g : float, b : float): self.r = r self.g = g self.b = b def tuple(self): return (self.r, self.g, self.b) class Gray(Color): # intensity bet def __init__(self, intensity : float): self.r = self.g = self.b = intensity self.intensity = intensity def __repr__(self): return "colors.Gray(%s)" % (self.intensity,) Black = Gray(0) White = Gray(1)
# # PySNMP MIB module MPLS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MPLS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:04:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion") jnxMibs, = mibBuilder.importSymbols("JUNIPER-SMI", "jnxMibs") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibIdentifier, TimeTicks, NotificationType, ObjectIdentity, ModuleIdentity, Bits, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Unsigned32, Counter32, iso, IpAddress, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "TimeTicks", "NotificationType", "ObjectIdentity", "ModuleIdentity", "Bits", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Unsigned32", "Counter32", "iso", "IpAddress", "Counter64") TextualConvention, DisplayString, TimeStamp = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TimeStamp") mpls = ModuleIdentity((1, 3, 6, 1, 4, 1, 2636, 3, 2)) mpls.setRevisions(('2009-02-23 14:45',)) if mibBuilder.loadTexts: mpls.setLastUpdated('200902231445Z') if mibBuilder.loadTexts: mpls.setOrganization('Juniper Networks, Inc.') mplsInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 2, 1)) mplsVersion = MibScalar((1, 3, 6, 1, 4, 1, 2636, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsVersion.setStatus('current') mplsSignalingProto = MibScalar((1, 3, 6, 1, 4, 1, 2636, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("other", 2), ("rsvp", 3), ("ldp", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsSignalingProto.setStatus('current') mplsConfiguredLsps = MibScalar((1, 3, 6, 1, 4, 1, 2636, 3, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsConfiguredLsps.setStatus('current') mplsActiveLsps = MibScalar((1, 3, 6, 1, 4, 1, 2636, 3, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsActiveLsps.setStatus('current') mplsTEInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 2, 2)) mplsTEDistProtocol = MibScalar((1, 3, 6, 1, 4, 1, 2636, 3, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("isis", 2), ("ospf", 3), ("isis-ospf", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsTEDistProtocol.setStatus('current') mplsAdminGroupList = MibTable((1, 3, 6, 1, 4, 1, 2636, 3, 2, 2, 2), ) if mibBuilder.loadTexts: mplsAdminGroupList.setStatus('current') mplsAdminGroup = MibTableRow((1, 3, 6, 1, 4, 1, 2636, 3, 2, 2, 2, 1), ).setIndexNames((0, "MPLS-MIB", "mplsAdminGroupNumber")) if mibBuilder.loadTexts: mplsAdminGroup.setStatus('current') mplsAdminGroupNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 31))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsAdminGroupNumber.setStatus('current') mplsAdminGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 2, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsAdminGroupName.setStatus('current') mplsLspList = MibTable((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3), ) if mibBuilder.loadTexts: mplsLspList.setStatus('deprecated') mplsLspEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1), ).setIndexNames((0, "MPLS-MIB", "mplsLspName")) if mibBuilder.loadTexts: mplsLspEntry.setStatus('deprecated') mplsLspName = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(32, 32)).setFixedLength(32)).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspName.setStatus('deprecated') mplsLspState = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("unknown", 1), ("up", 2), ("down", 3), ("notInService", 4), ("backupActive", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspState.setStatus('deprecated') mplsLspOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspOctets.setStatus('deprecated') mplsLspPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspPackets.setStatus('deprecated') mplsLspAge = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 5), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspAge.setStatus('deprecated') mplsLspTimeUp = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 6), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspTimeUp.setStatus('deprecated') mplsLspPrimaryTimeUp = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 7), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspPrimaryTimeUp.setStatus('deprecated') mplsLspTransitions = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspTransitions.setStatus('deprecated') mplsLspLastTransition = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 9), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspLastTransition.setStatus('deprecated') mplsLspPathChanges = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspPathChanges.setStatus('deprecated') mplsLspLastPathChange = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 11), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspLastPathChange.setStatus('deprecated') mplsLspConfiguredPaths = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspConfiguredPaths.setStatus('deprecated') mplsLspStandbyPaths = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspStandbyPaths.setStatus('deprecated') mplsLspOperationalPaths = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 14), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspOperationalPaths.setStatus('deprecated') mplsLspFrom = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 15), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspFrom.setStatus('deprecated') mplsLspTo = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 16), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspTo.setStatus('deprecated') mplsPathName = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 17), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathName.setStatus('deprecated') mplsPathType = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("primary", 2), ("standby", 3), ("secondary", 4), ("bypass", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathType.setStatus('deprecated') mplsPathExplicitRoute = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 19), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathExplicitRoute.setStatus('deprecated') mplsPathRecordRoute = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 20), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathRecordRoute.setStatus('deprecated') mplsPathBandwidth = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 21), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathBandwidth.setStatus('deprecated') mplsPathCOS = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 7), ValueRangeConstraint(255, 255), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathCOS.setStatus('deprecated') mplsPathInclude = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 23), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInclude.setStatus('deprecated') mplsPathExclude = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 24), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathExclude.setStatus('deprecated') mplsPathSetupPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 25), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathSetupPriority.setStatus('deprecated') mplsPathHoldPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathHoldPriority.setStatus('deprecated') mplsPathProperties = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 3, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 4, 8, 16, 32, 64))).clone(namedValues=NamedValues(("record-route", 1), ("adaptive", 2), ("cspf", 4), ("mergeable", 8), ("preemptable", 16), ("preemptive", 32), ("fast-reroute", 64)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathProperties.setStatus('deprecated') mplsLspInfoList = MibTable((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5), ) if mibBuilder.loadTexts: mplsLspInfoList.setStatus('current') mplsLspInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1), ).setIndexNames((1, "MPLS-MIB", "mplsLspInfoName")) if mibBuilder.loadTexts: mplsLspInfoEntry.setStatus('current') mplsLspInfoName = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: mplsLspInfoName.setStatus('current') mplsLspInfoState = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("unknown", 1), ("up", 2), ("down", 3), ("notInService", 4), ("backupActive", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoState.setStatus('current') mplsLspInfoOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoOctets.setStatus('current') mplsLspInfoPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoPackets.setStatus('current') mplsLspInfoAge = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 5), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoAge.setStatus('current') mplsLspInfoTimeUp = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 6), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoTimeUp.setStatus('current') mplsLspInfoPrimaryTimeUp = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 7), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoPrimaryTimeUp.setStatus('current') mplsLspInfoTransitions = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoTransitions.setStatus('current') mplsLspInfoLastTransition = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 9), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoLastTransition.setStatus('current') mplsLspInfoPathChanges = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoPathChanges.setStatus('current') mplsLspInfoLastPathChange = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 11), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoLastPathChange.setStatus('current') mplsLspInfoConfiguredPaths = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoConfiguredPaths.setStatus('current') mplsLspInfoStandbyPaths = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoStandbyPaths.setStatus('current') mplsLspInfoOperationalPaths = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 14), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoOperationalPaths.setStatus('current') mplsLspInfoFrom = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 15), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoFrom.setStatus('current') mplsLspInfoTo = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 16), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoTo.setStatus('current') mplsPathInfoName = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 17), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoName.setStatus('current') mplsPathInfoType = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("primary", 2), ("standby", 3), ("secondary", 4), ("bypass", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoType.setStatus('current') mplsPathInfoExplicitRoute = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 19), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoExplicitRoute.setStatus('current') mplsPathInfoRecordRoute = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 20), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoRecordRoute.setStatus('current') mplsPathInfoBandwidth = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 21), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoBandwidth.setStatus('current') mplsPathInfoCOS = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 7), ValueRangeConstraint(255, 255), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoCOS.setStatus('current') mplsPathInfoInclude = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 23), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoInclude.setStatus('current') mplsPathInfoExclude = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 24), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoExclude.setStatus('current') mplsPathInfoSetupPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 25), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoSetupPriority.setStatus('current') mplsPathInfoHoldPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoHoldPriority.setStatus('current') mplsPathInfoProperties = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 4, 8, 16, 32, 64))).clone(namedValues=NamedValues(("record-route", 1), ("adaptive", 2), ("cspf", 4), ("mergeable", 8), ("preemptable", 16), ("preemptive", 32), ("fast-reroute", 64)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoProperties.setStatus('current') mplsLspInfoAggrOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 28), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoAggrOctets.setStatus('current') mplsLspInfoAggrPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 29), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLspInfoAggrPackets.setStatus('current') mplsPathInfoRecordRouteWithLabels = MibTableColumn((1, 3, 6, 1, 4, 1, 2636, 3, 2, 5, 1, 30), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsPathInfoRecordRouteWithLabels.setStatus('current') mplsTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 2, 4)) mplsLspUp = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 4, 1)).setObjects(("MPLS-MIB", "mplsLspName"), ("MPLS-MIB", "mplsPathName")) if mibBuilder.loadTexts: mplsLspUp.setStatus('deprecated') mplsLspDown = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 4, 2)).setObjects(("MPLS-MIB", "mplsLspName"), ("MPLS-MIB", "mplsPathName")) if mibBuilder.loadTexts: mplsLspDown.setStatus('deprecated') mplsLspChange = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 4, 3)).setObjects(("MPLS-MIB", "mplsLspName"), ("MPLS-MIB", "mplsPathName")) if mibBuilder.loadTexts: mplsLspChange.setStatus('deprecated') mplsLspPathDown = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 4, 4)).setObjects(("MPLS-MIB", "mplsLspName"), ("MPLS-MIB", "mplsPathName")) if mibBuilder.loadTexts: mplsLspPathDown.setStatus('deprecated') mplsLspPathUp = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 4, 5)).setObjects(("MPLS-MIB", "mplsLspName"), ("MPLS-MIB", "mplsPathName")) if mibBuilder.loadTexts: mplsLspPathUp.setStatus('deprecated') mplsLspTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 2636, 3, 2, 0)) mplsLspInfoUp = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 0, 1)).setObjects(("MPLS-MIB", "mplsLspInfoName"), ("MPLS-MIB", "mplsPathInfoName")) if mibBuilder.loadTexts: mplsLspInfoUp.setStatus('current') mplsLspInfoDown = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 0, 2)).setObjects(("MPLS-MIB", "mplsLspInfoName"), ("MPLS-MIB", "mplsPathInfoName")) if mibBuilder.loadTexts: mplsLspInfoDown.setStatus('current') mplsLspInfoChange = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 0, 3)).setObjects(("MPLS-MIB", "mplsLspInfoName"), ("MPLS-MIB", "mplsPathInfoName")) if mibBuilder.loadTexts: mplsLspInfoChange.setStatus('current') mplsLspInfoPathDown = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 0, 4)).setObjects(("MPLS-MIB", "mplsLspInfoName"), ("MPLS-MIB", "mplsPathInfoName")) if mibBuilder.loadTexts: mplsLspInfoPathDown.setStatus('current') mplsLspInfoPathUp = NotificationType((1, 3, 6, 1, 4, 1, 2636, 3, 2, 0, 5)).setObjects(("MPLS-MIB", "mplsLspInfoName"), ("MPLS-MIB", "mplsPathInfoName")) if mibBuilder.loadTexts: mplsLspInfoPathUp.setStatus('current') mibBuilder.exportSymbols("MPLS-MIB", mplsLspInfoPathUp=mplsLspInfoPathUp, mplsLspAge=mplsLspAge, mplsPathInfoProperties=mplsPathInfoProperties, mplsLspTransitions=mplsLspTransitions, mplsPathExclude=mplsPathExclude, mplsPathInfoType=mplsPathInfoType, mplsLspTraps=mplsLspTraps, mplsLspOperationalPaths=mplsLspOperationalPaths, mplsLspInfoAge=mplsLspInfoAge, mplsLspTo=mplsLspTo, mplsTEDistProtocol=mplsTEDistProtocol, mplsLspInfoAggrOctets=mplsLspInfoAggrOctets, mplsPathRecordRoute=mplsPathRecordRoute, mplsLspInfoStandbyPaths=mplsLspInfoStandbyPaths, mplsLspInfoChange=mplsLspInfoChange, mplsPathType=mplsPathType, mplsPathExplicitRoute=mplsPathExplicitRoute, mplsLspDown=mplsLspDown, mplsLspInfoPackets=mplsLspInfoPackets, mplsAdminGroupList=mplsAdminGroupList, mplsAdminGroupName=mplsAdminGroupName, mplsPathInclude=mplsPathInclude, mplsLspEntry=mplsLspEntry, mplsLspInfoLastPathChange=mplsLspInfoLastPathChange, mplsPathProperties=mplsPathProperties, mplsTEInfo=mplsTEInfo, mplsLspInfoDown=mplsLspInfoDown, mplsPathName=mplsPathName, mplsLspInfoTo=mplsLspInfoTo, mplsVersion=mplsVersion, mplsPathInfoExplicitRoute=mplsPathInfoExplicitRoute, mplsPathInfoHoldPriority=mplsPathInfoHoldPriority, mplsLspState=mplsLspState, mplsPathInfoRecordRouteWithLabels=mplsPathInfoRecordRouteWithLabels, mplsLspFrom=mplsLspFrom, mplsLspInfoTransitions=mplsLspInfoTransitions, mplsPathInfoRecordRoute=mplsPathInfoRecordRoute, mplsActiveLsps=mplsActiveLsps, mplsSignalingProto=mplsSignalingProto, mplsAdminGroupNumber=mplsAdminGroupNumber, mplsPathInfoBandwidth=mplsPathInfoBandwidth, mplsPathInfoExclude=mplsPathInfoExclude, mplsConfiguredLsps=mplsConfiguredLsps, mplsLspPathDown=mplsLspPathDown, mpls=mpls, mplsLspInfoList=mplsLspInfoList, mplsLspInfoState=mplsLspInfoState, mplsLspInfoPathChanges=mplsLspInfoPathChanges, mplsLspTimeUp=mplsLspTimeUp, mplsLspInfoAggrPackets=mplsLspInfoAggrPackets, mplsLspPathUp=mplsLspPathUp, mplsPathHoldPriority=mplsPathHoldPriority, mplsAdminGroup=mplsAdminGroup, mplsPathInfoCOS=mplsPathInfoCOS, mplsPathInfoSetupPriority=mplsPathInfoSetupPriority, mplsLspPrimaryTimeUp=mplsLspPrimaryTimeUp, mplsLspUp=mplsLspUp, mplsLspInfoPrimaryTimeUp=mplsLspInfoPrimaryTimeUp, mplsLspLastTransition=mplsLspLastTransition, mplsTraps=mplsTraps, mplsLspInfoPathDown=mplsLspInfoPathDown, mplsLspOctets=mplsLspOctets, mplsLspInfoConfiguredPaths=mplsLspInfoConfiguredPaths, mplsLspStandbyPaths=mplsLspStandbyPaths, mplsLspPackets=mplsLspPackets, mplsPathBandwidth=mplsPathBandwidth, mplsLspList=mplsLspList, mplsPathSetupPriority=mplsPathSetupPriority, mplsLspInfoFrom=mplsLspInfoFrom, mplsLspLastPathChange=mplsLspLastPathChange, mplsLspInfoName=mplsLspInfoName, mplsLspPathChanges=mplsLspPathChanges, PYSNMP_MODULE_ID=mpls, mplsLspInfoTimeUp=mplsLspInfoTimeUp, mplsLspInfoLastTransition=mplsLspInfoLastTransition, mplsLspInfoUp=mplsLspInfoUp, mplsLspConfiguredPaths=mplsLspConfiguredPaths, mplsPathInfoInclude=mplsPathInfoInclude, mplsLspInfoOctets=mplsLspInfoOctets, mplsLspInfoEntry=mplsLspInfoEntry, mplsInfo=mplsInfo, mplsLspInfoOperationalPaths=mplsLspInfoOperationalPaths, mplsPathCOS=mplsPathCOS, mplsLspChange=mplsLspChange, mplsLspName=mplsLspName, mplsPathInfoName=mplsPathInfoName)
def RC(value, tolerance=5.0, power=None, package="0603",pkgcode="07"): res = {"manufacturer": "Yageo"} suffix = ['R', 'K', 'M'] digits = 3 if tolerance < 5 else 2 while value >= 1000: value = value/1000. suffix.pop(0) suffix = suffix[0] whole = str(int(value)) decimal = str(round((value-int(value)) * 10**(digits-len(whole)))) v_str = (whole+suffix+decimal).strip("0") if v_str == "R": v_str = "0R" if tolerance == 0.5: t_str = 'D' elif tolerance == 1.0: t_str = 'F' else: t_str = 'J' res["MPN"] = "RC{}{}R-{}{}L".format(package, t_str, pkgcode, v_str) return res _cc_voltages = {6300: '5', 10000: '6', 16000: '7', 25000: '8', 50000: '9'} def CC_XxR(value, tolerance=10, voltage=16, package='0603', pkgcode='R', dielectric="X7R"): res = {"manufacturer": "Yageo"} c_pf = int(value * 1e12) exp = 0 while c_pf >= 100: exp += 1 c_pf /= 10 if package > '0603' and pkgcode == 'R': pkgcode = 'K' c_str = str(int(c_pf))+str(exp) v_mv = round(voltage*1e3) v_str = _cc_voltages.get(v_mv, '9') t_str = 'K' res["MPN"] = "CC{}{}{}{}{}BB{}".format(package, t_str, pkgcode, dielectric, v_str, c_str) return res
class Animal(object): def run(self): print('Animal is running...') def eat(self): print('Animal is eating...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def __init__(self): self.name = 'Tom' def __str__(self): return self.name def __len__(self): return 100 dog = Dog() dog.run() dog.eat() cat = Cat() cat.run() print(cat)
x = [15 ,12, 8, 8, 7, 7, 7, 6, 5, 3] y = [10 ,25, 17, 11, 13, 17, 20, 13, 9, 15] n = len(x) xy = [x[i] * y[i] for i in range(n)] x_square = [x[i] * x[i] for i in range(n)] avg_x = sum(x) / n avg_y = sum(y) / n avg_xy = sum(xy) / n avg_xsqr = sum(x_square) / n m = ((avg_x * avg_y) - avg_xy) / (avg_x ** 2 - avg_xsqr) c = avg_y - (m * avg_x) print(round((m * 10 + c), 2))
#MenuTitle: Activate all Bold instances # -*- coding: utf-8 -*- __doc__=""" Activate all Bold instances (and deactivates all others) Ignores instances where custom parameter "familyName" == "Master Condensed" or "Master Wide" """ thisFont = Glyphs.font Glyphs.clearLog() Glyphs.showMacroWindow() for instance in thisFont.instances: if instance.active: instance.active = False if instance.weight == "Bold": instance.active = True if instance.familyName == "Master Condensed": instance.active = False if instance.familyName == "Master Wide": instance.active = False
""" Sorting the array into a wave-like array. For eg: arr[] = {1,2,3,4,5} Output: 2 1 4 3 5 """ def convertToWave(length,array): for i in range(0, length - length%2, 2): #swapping alternatively temp=array[i] array[i]=array[i+1] array[i+1]=temp return array arr = list(map(int,input("Enter the elements of the array : ").split())) N = len(arr) # length of the array arr = convertToWave(N,arr) print("Wave Array: ") for el in arr: print(el, end=" ") """ Time complexity : O(1) Space complexity : O(1) INPUT:- Enter the elements of the array : 1 2 3 4 5 6 7 OUTPUT:- Wave Array: 2 1 4 3 6 5 7 """
filename_prefix = 'Rebuttal-SawyerLift-ADR' xlabel = 'Environment steps (3M)' ylabel = "Average Discounted Rewards" mopa_cutoff_step = 1000000 others_cutoff_step = 2000000 max_step = 3000000 max_y_axis_value = 110 legend = False data_key = "train_ep/rew_discounted" bc_y_value = 34.77 plot_labels = { "Ours": [ 'Rebuttal_Ours_Lift_1234_smart-river-671', 'Rebuttal_Ours_Lift_200_clean-cherry-673', 'Rebuttal_Ours_Lift_2320_clear-water-695', 'Rebuttal_Ours_Lift_500_vivid-lake-675', 'Rebuttal_Ours_Lift_1800_lilac-butterfly-676', ], "Ours (w/o BC smoothing)": [ 'Rebuttal_Ours(wo_bc_smoothing)_Lift_1234_sparkling-terrain-670', 'Rebuttal_Ours(wo_bc_smoothing)_Lift_200_toasty-pine-678', 'Rebuttal_Ours(wo_bc_smoothing)_Lift_2320_ethereal-deluge-692', 'Rebuttal_Ours(wo_bc_smoothing)_Lift_500_floral-water-679', 'Rebuttal_Ours(wo_bc_smoothing)_Lift_1800_youthful-microwave-674', ], "CoL": [ 'Rebuttal_CoL_MoPA_Lift_1234_stoic-fire-187', 'Rebuttal_CoL_MoPA_Lift_200_wandering-waterfall-188', 'Rebuttal_CoL_MoPA_Lift_2320_desert-flower-696', 'Rebuttal_CoL_MoPA_Lift_500_expert-brook-189', 'Rebuttal_CoL_MoPA_Lift_1800_usual-cloud-224', ], "CoL(w BC smoothing)": [ 'Rebuttal_CoL_Lift_1234_scarlet-yogurt-681', 'Rebuttal_CoL_Lift_200_lunar-sun-683', 'Rebuttal_CoL_Lift_2320_lyric-frog-689', 'Rebuttal_CoL_Lift_500_scarlet-eon-685', 'Rebuttal_CoL_Lift_1800_astral-night-671', ], "MoPA Asym. SAC": [ 'Rebuttal_MoPA-Asym._SAC_Lift_1234_rl.SawyerLiftObstacle-v0.08.21.07.52.Asymmetric-MoPA-SAC.0', 'Rebuttal_MoPA-Asym._SAC_Lift_200_rl.SawyerLiftObstacle-v0.08.22.01.30.Asymmetric-MoPA-SAC.0', 'Rebuttal_MoPA-Asym._SAC_Lift_2320_rl.SawyerLiftObstacle-v0.08.28.15.22.Asymmetric-MoPA-SAC.0', 'Rebuttal_MoPA-Asym._SAC_Lift_500_rl.SawyerLiftObstacle-v0.08.22.01.35.Asymmetric-MoPA-SAC.0', 'Rebuttal_MoPA-Asym._SAC_Lift_1800_rl.SawyerLiftObstacle-v0.08.30.07.28.Asymmetric-MoPA-SAC.0', ], "Asym. SAC": [ 'Rebuttal_Asym._SAC_Lift_1234_fast-bee-631', 'Rebuttal_Asym._SAC_Lift_200_swift-smoke-632', 'Rebuttal_Asym._SAC_Lift_500_visionary-dream-633', 'Rebuttal_Asym._SAC_Lift_2320_MyMachine_rural-valley-691', 'Rebuttal_Asym._SAC_Lift_1800_zany-wave-684', ], } # choosing Rebuttal_Asym._SAC_Assembly_200_comfy-violet-635 because it has 3m env. steps line_labels = { "BC-Visual": ['Rebuttal_Asym._SAC_Assembly_200_comfy-violet-635'], } line_colors = { 'Ours': 'C0', 'Ours (w/o BC smoothing)': 'C1', 'CoL': 'C2', 'CoL(w BC smoothing)': 'C3', 'MoPA Asym. SAC': 'C4', 'Asym. SAC': 'C5', 'BC-Visual': 'C6', } mopa_curve = { "Ours": 'Rebuttal_MoPA_RL_Lift_2000_rl.SawyerLiftObstacle-v0.08.27.MoPA-SAC.2000', "Ours (w/o BC smoothing)": 'Rebuttal_MoPA_RL_Lift_2000_rl.SawyerLiftObstacle-v0.08.27.MoPA-SAC.2000', "CoL": 'Rebuttal_MoPA_RL_Lift_2000_rl.SawyerLiftObstacle-v0.08.27.MoPA-SAC.2000', "CoL(w BC smoothing)": 'Rebuttal_MoPA_RL_Lift_2000_rl.SawyerLiftObstacle-v0.08.27.MoPA-SAC.2000', } # plot_labels = { # "Ours": [], # "Ours (w/o BC smoothing)": [], # "CoL": [], # "CoL(w BC smoothing)": [], # "MoPA Asym. SAC": [], # "Asym. SAC": [], # } # line_labels = { # "BC-Visual": [], # }
class Credential: """ Class that generates new instances of users. """ credential_list = [] def __init__(self,credential_name,user_name,password,email): self.credential_name = credential_name self.user_name = user_name self.password = password self.email = email def save_credential(self): Credential.credential_list.append(self) def delete_credential(self): Credential.credential_list.remove(self) @classmethod def find_by_name(cls,name): for credential in cls.credential_list: if credential.credential_name == name: return credential @classmethod def credential_exist(cls,name): for credential in cls.credential_list: if credential.password == name: return credential return False @classmethod def display_credential(cls): return cls.credential_list
def say_hello(): print('Hello') def say_goodbye(): print('Goodbye')
# coding: utf-8 """***************************************************************************** * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************""" ################################################################################ ########## EVSYS DATABASE COMPONENTS ##################### ################################################################################ global user global generator global path global channel global evsysInstanceName global InterruptVector global InterruptHandler global InterruptHandlerLock channel = 0 path = {} user = {} generator = {} generator_module = {} user_module = {} def userStatus(symbol, event): global channelUserMap global user channelNumber = int(str(symbol.getID()).split( "EVSYS_CHANNEL_")[1].split("_USER_READY")[0]) if event["id"].startswith("EVSYS_USER_"): channelAssigned = event["value"] - 1 channelUser = user.get(int(event["id"].split("EVSYS_USER_")[1])) channelUserMap[event["id"]] = channelAssigned userAvailable = False for key in channelUserMap.keys(): if channelUserMap.get(key) == channelNumber: if Database.getSymbolValue(event["namespace"], "USER_" + user.get(int(key.split("EVSYS_USER_")[1])) + "_READY") == False: userAvailable = False break else: userAvailable = True symbol.setValue(userAvailable, 2) def channelSource(symbol, event): global evsysGenerator channelNumber = int(str(symbol.getID()).split( "EVSYS_CHANNEL_")[1].split("_GENERATOR_ACTIVE")[0]) symbol.setValue(Database.getSymbolValue(event["namespace"], "GENERATOR_" + str( evsysGenerator[channelNumber].getSelectedKey()) + "_ACTIVE"), 2) def channelMenu(symbol, event): symbol.setVisible(event["value"]) def channelClockEnable(symbol, event): chID = event["id"].split('EVSYS_CHANNEL_')[1] if event["value"] == True: Database.setSymbolValue( "core", evsysInstanceName.getValue() + "_" + chID + "_CLOCK_ENABLE", True, 1) else: Database.setSymbolValue("core", evsysInstanceName.getValue( ) + "_" + chID + "_CLOCK_ENABLE", False, 1) def overrunInterrupt(interrupt, event): interrupt.setVisible(event["value"] != 2) def eventInterrupt(interrupt, event): interrupt.setVisible(event["value"] != 2) def evsysIntset(interrupt, val): global InterruptVector global InterruptHandler global InterruptHandlerLock global numsyncChannels channel = int(interrupt.getID().split("EVSYS_INTERRUPT_MODE")[1]) event = Database.getSymbolValue( val["namespace"], "EVSYS_CHANNEL_" + str(channel) + "_EVENT") overflow = Database.getSymbolValue( val["namespace"], "EVSYS_CHANNEL_" + str(channel) + "_OVERRUN") result = event or overflow interrupt.setValue(result, 2) if Database.getSymbolValue(val["namespace"], "INTERRUPT_ACTIVE") != result: Database.setSymbolValue(val["namespace"], "INTERRUPT_ACTIVE", result, 2) if channel > len(InterruptVector) - 1: Database.setSymbolValue(val["namespace"], "EVSYS_INTERRUPT_MODE_OTHER", False, 2) for id in range(len(InterruptVector) - 1 , numsyncChannels): if (Database.getSymbolValue(val["namespace"], "EVSYS_CHANNEL_" + str(id) + "_EVENT") or Database.getSymbolValue(val["namespace"], "EVSYS_CHANNEL_" + str(id) + "_OVERRUN")): Database.setSymbolValue(val["namespace"], "EVSYS_INTERRUPT_MODE_OTHER", True, 2) if channel > len(InterruptVector) - 1: channel = len(InterruptVector) - 1 Database.setSymbolValue("core", InterruptVector[channel], result, 2) Database.setSymbolValue("core", InterruptHandlerLock[channel], result, 2) if result: Database.setSymbolValue("core", InterruptHandler[channel], str( InterruptHandler[channel].split("_INTERRUPT_HANDLER")[0]) + "_InterruptHandler", 2) else: Database.setSymbolValue("core", InterruptHandler[channel], InterruptHandler[channel].split( "_INTERRUPT_HANDLER")[0] + "_Handler", 2) def updateEVSYSInterruptWarringStatus(symbol, event): if evsysInterrupt.getValue() == True: symbol.setVisible(event["value"]) def instantiateComponent(evsysComponent): global evsysInstanceName global InterruptVector InterruptVector=[] global InterruptHandler InterruptHandler=[] global InterruptHandlerLock InterruptHandlerLock=[] InterruptVectorUpdate=[] global evsysInterrupt global numsyncChannels global user global channel global channelUserMap channelUserMap={} global evsysGenerator evsysGenerator=[] channelUserDependency=[] # Get the number of channels supporting Synchronous and asynchronous path dummyNode=ATDF.getNode( '/avr-tools-device-file/modules/module@[name="EVSYS"]/register-group@[name="EVSYS"]/register@[name="INTSTATUS"]') numsyncChannels=len(dummyNode.getChildren()) - 1 evsysInstanceName=evsysComponent.createStringSymbol( "EVSYS_INSTANCE_NAME", None) evsysInstanceName.setVisible(False) evsysInstanceName.setDefaultValue(evsysComponent.getID().upper()) Log.writeInfoMessage("Running " + evsysInstanceName.getValue()) # EVSYS Main Menu evsysSym_Menu=evsysComponent.createMenuSymbol("EVSYS_MENU", None) evsysSym_Menu.setLabel("EVSYS MODULE SETTINGS ") generatorSymbol=[] generatorsNode=ATDF.getNode( "/avr-tools-device-file/devices/device/events/generators") for id in range(0, len(generatorsNode.getChildren())): generator[generatorsNode.getChildren()[id].getAttribute("name")]=int( generatorsNode.getChildren()[id].getAttribute("index")) generatorActive=evsysComponent.createBooleanSymbol( "GENERATOR_" + str(generatorsNode.getChildren()[id].getAttribute("name")) + "_ACTIVE", evsysSym_Menu) generatorActive.setVisible(False) generatorActive.setDefaultValue(False) generatorSymbol.append( "GENERATOR_" + str(generatorsNode.getChildren()[id].getAttribute("name")) + "_ACTIVE") usersNode=ATDF.getNode( "/avr-tools-device-file/devices/device/events/users") for id in range(0, len(usersNode.getChildren())): user[int(usersNode.getChildren()[id].getAttribute("index")) ]=usersNode.getChildren()[id].getAttribute("name") userReady=evsysComponent.createBooleanSymbol( "USER_" + str(usersNode.getChildren()[id].getAttribute("name")) + "_READY", evsysSym_Menu) userReady.setVisible(False) userReady.setDefaultValue(False) channelUserMap["EVSYS_USER_" + str(usersNode.getChildren()[id].getAttribute("index"))]= -1 channelUserDependency.append( "EVSYS_USER_" + str(usersNode.getChildren()[id].getAttribute("index"))) channelUserDependency.append( "USER_" + str(usersNode.getChildren()[id].getAttribute("name")) + "_READY") channelNode=ATDF.getNode( '/avr-tools-device-file/devices/device/peripherals/module@[name="EVSYS"]/instance@[name="' + evsysInstanceName.getValue() + '"]/parameters') for id in range(0, len(channelNode.getChildren())): if channelNode.getChildren()[id].getAttribute("name") == "CHANNELS": channel=int(channelNode.getChildren()[id].getAttribute("value")) break evsysChannelNum=evsysComponent.createIntegerSymbol( "EVSYS_CHANNEL_NUMBER", evsysSym_Menu) evsysChannelNum.setVisible(False) evsysChannelNum.setDefaultValue(int(channel)) evsysChannelNum.setVisible(False) evsysChannelNum=evsysComponent.createIntegerSymbol( "NUM_SYNC_CHANNELS", evsysSym_Menu) evsysChannelNum.setVisible(False) evsysChannelNum.setDefaultValue(int(numsyncChannels)) evsysUserNum=evsysComponent.createIntegerSymbol( "EVSYS_USER_NUMBER", evsysSym_Menu) evsysUserNum.setVisible(False) evsysUserNum.setDefaultValue(int(max(user.keys()))) evsysPriority=evsysComponent.createKeyValueSetSymbol( "EVSYS_CHANNEL_SCHEDULING", evsysSym_Menu) evsysPriority.setLabel("Scheduling Policy") evsysPriority.addKey( "STATIC", "0", "Static scheduling scheme for channels with level priority") evsysPriority.addKey( "ROUND-ROBIN", "1", "Round-robin scheduling scheme for channels with level priority") evsysPriority.setOutputMode("Value") for id in range(0, channel): evsysChannel=evsysComponent.createBooleanSymbol( "EVSYS_CHANNEL_" + str(id), evsysSym_Menu) evsysChannel.setLabel("Enable Channel" + str(id)) evsysChannel.setDefaultValue(False) # Dummy symbol to control clock enable evsysClockEnable=evsysComponent.createBooleanSymbol( "EVSYS_CLOCK_ENABLE_" + str(id), evsysSym_Menu) evsysClockEnable.setDefaultValue(False) evsysClockEnable.setVisible(False) evsysClockEnable.setDependencies( channelClockEnable, ["EVSYS_CHANNEL_" + str(id)]) evsysChannelMenu=evsysComponent.createMenuSymbol( "EVSYS_MENU_" + str(id), evsysChannel) evsysChannelMenu.setLabel("EVSYS Channel Configuration") evsysChannelMenu.setVisible(False) evsysChannelMenu.setDependencies( channelMenu, ["EVSYS_CHANNEL_" + str(id)]) evsysGenerator.append(id) evsysGenerator[id]=evsysComponent.createKeyValueSetSymbol( "EVSYS_CHANNEL_" + str(id) + "_GENERATOR", evsysChannelMenu) evsysGenerator[id].setLabel("Event Generator") evsysGenerator[id].setOutputMode("Value") for key in sorted(generator.keys()): evsysGenerator[id].addKey(key, str(generator.get(key)), key) evsysGeneratorActive=evsysComponent.createBooleanSymbol( "EVSYS_CHANNEL_" + str(id) + "_GENERATOR_ACTIVE", evsysChannelMenu) evsysGeneratorActive.setDefaultValue(False) evsysGeneratorActive.setVisible(True) evsysGeneratorActive.setLabel("Channel Generator source Active") generatorSymbol.append("EVSYS_CHANNEL_" + str(id) + "_GENERATOR") evsysGeneratorActive.setDependencies(channelSource, generatorSymbol) del generatorSymbol[-1] evsysPath=evsysComponent.createKeyValueSetSymbol( "EVSYS_CHANNEL_" + str(id) + "_PATH", evsysChannelMenu) evsysPath.setLabel("Path Selection") evsysPath.setOutputMode("Value") pathNode=ATDF.getNode( '/avr-tools-device-file/modules/module@[name="EVSYS"]/value-group@[name="EVSYS_CHANNEL__PATH"]') for i in range(0, len(pathNode.getChildren())): evsysPath.addKey(pathNode.getChildren()[i].getAttribute("name"), str(pathNode.getChildren()[ i].getAttribute("value")), pathNode.getChildren()[i].getAttribute("caption")) evsysPath.setDefaultValue(2) if id > numsyncChannels: evsysPath.setReadOnly(True) evsysEdge=evsysComponent.createKeyValueSetSymbol( "EVSYS_CHANNEL_" + str(id) + "_EDGE", evsysChannelMenu) evsysEdge.setLabel("Event Edge Selection") edgeNode=ATDF.getNode( '/avr-tools-device-file/modules/module@[name="EVSYS"]/value-group@[name="EVSYS_CHANNEL__EDGSEL"]') for i in range(0, len(edgeNode.getChildren())): evsysEdge.addKey(edgeNode.getChildren()[i].getAttribute("name"), str(edgeNode.getChildren()[ i].getAttribute("value")), edgeNode.getChildren()[i].getAttribute("caption")) evsysEdge.setDefaultValue(0) evsysEdge.setOutputMode("Value") evsysOnDemand=evsysComponent.createBooleanSymbol( "EVSYS_CHANNEL_" + str(id) + "_ONDEMAND", evsysChannelMenu) evsysOnDemand.setLabel("Generic Clock On Demand") evsysOnDemand.setDefaultValue(False) evsysRunStandby=evsysComponent.createBooleanSymbol( "EVSYS_CHANNEL_" + str(id) + "_RUNSTANDBY", evsysChannelMenu) evsysRunStandby.setLabel("Run In Standby Sleep Mode") evsysRunStandby.setDefaultValue(False) evsysEvent=evsysComponent.createBooleanSymbol( "EVSYS_CHANNEL_" + str(id) + "_EVENT", evsysChannelMenu) evsysEvent.setLabel("Enable Event Detection Interrupt") evsysEvent.setDefaultValue(False) evsysEvent.setVisible(False) evsysEvent.setDependencies( eventInterrupt, ["EVSYS_CHANNEL_" + str(id) + "_PATH"]) evsysOverRun=evsysComponent.createBooleanSymbol( "EVSYS_CHANNEL_" + str(id) + "_OVERRUN", evsysChannelMenu) evsysOverRun.setLabel("Enable Overrun Interrupt") evsysOverRun.setDefaultValue(False) evsysOverRun.setVisible(False) evsysOverRun.setDependencies( overrunInterrupt, ["EVSYS_CHANNEL_" + str(id) + "_PATH"]) evsysUserReady=evsysComponent.createBooleanSymbol( "EVSYS_CHANNEL_" + str(id) + "_USER_READY", evsysChannelMenu) evsysUserReady.setDefaultValue(False) evsysUserReady.setVisible(False) evsysUserReady.setLabel("Channel" + str(id) + "Users Ready") evsysUserReady.setDependencies(userStatus, channelUserDependency) if id <= numsyncChannels: evsysInterrupt=evsysComponent.createBooleanSymbol( "EVSYS_INTERRUPT_MODE" + str(id), evsysSym_Menu) evsysInterrupt.setVisible(False) evsysInterrupt.setDefaultValue(False) evsysInterrupt.setDependencies(evsysIntset, [ "EVSYS_CHANNEL_" + str(id) + "_OVERRUN", "EVSYS_CHANNEL_" + str(id) + "_EVENT"]) evsysUserMenu=evsysComponent.createMenuSymbol( "EVSYS_USER_MENU", evsysSym_Menu) evsysUserMenu.setLabel("EVSYS User SETTINGS ") for id in user.keys(): evsysUserChannel=evsysComponent.createKeyValueSetSymbol( "EVSYS_USER_" + str(id), evsysUserMenu) evsysUserChannel.setLabel(str(user.get(id)) + " Chanel Selection") evsysUserChannel.addKey("NONE", str(0), "No Channel Selected") for i in range(0, channel): evsysUserChannel.addKey( "CHANNEL_" + str(i), str(hex(i + 1)), "Use Channel" + str(id)) evsysUserChannel.setOutputMode("Value") ############################################################################ #### Dependency #### ############################################################################ vectorNode=ATDF.getNode( "/avr-tools-device-file/devices/device/interrupts") vectorValues=vectorNode.getChildren() for id in range(0, len(vectorNode.getChildren())): if vectorValues[id].getAttribute("module-instance") == "EVSYS": name=vectorValues[id].getAttribute("name") InterruptVector.append(name + "_INTERRUPT_ENABLE") InterruptHandler.append(name + "_INTERRUPT_HANDLER") InterruptHandlerLock.append(name + "_INTERRUPT_HANDLER_LOCK") InterruptVectorUpdate.append( "core." + name + "_INTERRUPT_ENABLE_UPDATE") # Interrupt Warning status evsysSym_IntEnComment=evsysComponent.createCommentSymbol( "EVSYS_INTERRUPT_ENABLE_COMMENT", None) evsysSym_IntEnComment.setVisible(False) evsysSym_IntEnComment.setLabel( "Warning!!! EVSYS Interrupt is Disabled in Interrupt Manager") evsysSym_IntEnComment.setDependencies( updateEVSYSInterruptWarringStatus, InterruptVectorUpdate) evsysInterruptMode = evsysComponent.createBooleanSymbol("INTERRUPT_ACTIVE", None) evsysInterruptMode.setDefaultValue(False) evsysInterruptMode.setVisible(False) if numsyncChannels > len(InterruptVector): evsysIntOther = evsysComponent.createBooleanSymbol( "EVSYS_INTERRUPT_MODE_OTHER", evsysSym_Menu) evsysIntOther.setVisible(False) # ################################################################################ # ########## CODE GENERATION ############################# # ################################################################################ configName=Variables.get("__CONFIGURATION_NAME") evsysSym_HeaderFile=evsysComponent.createFileSymbol("EVSYS_HEADER", None) evsysSym_HeaderFile.setSourcePath( "../peripheral/evsys_u2504/templates/plib_evsys.h.ftl") evsysSym_HeaderFile.setOutputName( "plib_" + evsysInstanceName.getValue().lower() + ".h") evsysSym_HeaderFile.setDestPath("peripheral/evsys") evsysSym_HeaderFile.setProjectPath( "config/" + configName + "/peripheral/evsys") evsysSym_HeaderFile.setType("HEADER") evsysSym_HeaderFile.setMarkup(True) evsysSym_SourceFile=evsysComponent.createFileSymbol("EVSYS_SOURCE", None) evsysSym_SourceFile.setSourcePath( "../peripheral/evsys_u2504/templates/plib_evsys.c.ftl") evsysSym_SourceFile.setOutputName( "plib_" + evsysInstanceName.getValue().lower() + ".c") evsysSym_SourceFile.setDestPath("peripheral/evsys") evsysSym_SourceFile.setProjectPath( "config/" + configName + "/peripheral/evsys") evsysSym_SourceFile.setType("SOURCE") evsysSym_SourceFile.setMarkup(True) evsysSystemInitFile=evsysComponent.createFileSymbol( "EVSYS_SYS_INIT", None) evsysSystemInitFile.setType("STRING") evsysSystemInitFile.setOutputName( "core.LIST_SYSTEM_INIT_C_SYS_INITIALIZE_PERIPHERALS") evsysSystemInitFile.setSourcePath( "../peripheral/evsys_u2504/templates/system/initialization.c.ftl") evsysSystemInitFile.setMarkup(True) evsysSystemDefFile=evsysComponent.createFileSymbol("EVSYS_SYS_DEF", None) evsysSystemDefFile.setType("STRING") evsysSystemDefFile.setOutputName("core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES") evsysSystemDefFile.setSourcePath( "../peripheral/evsys_u2504/templates/system/definitions.h.ftl") evsysSystemDefFile.setMarkup(True) evsysComponent.addPlugin( "../peripheral/evsys_u2504/plugin/eventsystem.jar")
# ----------------------------------------------------------- # Copyright (c) 2021. Danil Smirnov # Write a program that reads the names of the two primary # colors for mixing. If the user enters anything other than # red, blue, or yellow, the program should display an error # message. Otherwise, the program should print the name of # the secondary color that will be the result. # ----------------------------------------------------------- all_colors: dict = {'red': 'красный', 'yellow': 'желтый', 'blue': 'синий', 'purple': 'фиолетовый', 'green': 'зеленый', 'orange': 'оранжевый'} class ColorMixer: def __init__(self, color: str, color_: str): self.color: str = self.mix_colors(color, color_) def mix_colors(self, color: str, color_: str) -> str: if self.is_purple(color, color_): return all_colors['purple'] if self.is_green(color, color_): return all_colors['green'] if self.is_orange(color, color_): return all_colors['orange'] if self.is_same(color, color_): return color return 'ошибка цвета' def is_purple(self, color: str, color_: str) -> bool: return (color == all_colors['red'] and color_ == all_colors['blue']) or ( color == all_colors['blue'] and color_ == all_colors['red']) def is_green(self, color: str, color_: str) -> bool: return (color == all_colors['yellow'] and color_ == all_colors['blue']) or ( color == all_colors['blue'] and color_ == all_colors['yellow']) def is_orange(self, color: str, color_: str) -> bool: return (color == all_colors['red'] and color_ == all_colors['yellow']) or ( color == all_colors['yellow'] and color_ == all_colors['red']) def is_same(self, color: str, color_: str) -> bool: return color == color_ == all_colors['red'] or color == color_ == all_colors['yellow'] or \ color == color_ == all_colors['blue'] if __name__ == '__main__': color_mixer = ColorMixer(str(input()), str(input())) print(color_mixer.color)
_base_ = "./ss_v1_dibr_mlBCE_FreezeBN_woCenter_refinePM10_ape.py" OUTPUT_DIR = "output/self6dpp/ssLM/ss_v1_dibr_mlBCE_FreezeBN_woCenter_refinePM10/glue" DATASETS = dict( TRAIN=("lm_real_glue_train",), TRAIN2=("lm_pbr_glue_train",), TRAIN2_RATIO=0.0, TEST=("lm_real_glue_test",) ) MODEL = dict( WEIGHTS="output/gdrn/lm_pbr/resnest50d_a6_AugCosyAAEGray_BG05_mlBCE_lm_pbr_100e/glue_Rsym/model_final_wo_optim-324d8f16.pth" )
class DefaultConfigurations: @staticmethod def get(): return {}
freeze('../../../../../../Micropython-Library-Development/lib/', 'uasyncio/asyn.py') freeze('../../../../../../Micropython-Library-Development/lib/', 'uasyncio/core.py') freeze('../../../../../../Micropython-Library-Development/lib/', 'uasyncio/__init__.py') freeze('../../../../../../Micropython-Library-Development/lib/', 'uasyncio/queues.py') freeze('../../../../../../Micropython-Library-Development/lib/', 'uasyncio/synchro.py') freeze('../../../../../../Micropython-Library-Development/lib/', 'unittest.py') freeze('../../../../../../Micropython-Library-Development/lib/', 'upysh.py')
# Sistemas de perguntas e respostas com dicionários Python. perg = { 'Pergunta 1': { 'pergunta':'Quanto é 2+2?', 'respostas': {'a':'1','b':'4','c':'5',}, 'resposta_certa':'b', }, 'Pergunta 2': { 'pergunta':'Quanto é 3+2?', 'respostas': {'a':'4','b':'10','c':'6',}, 'resposta_certa':'c', }, } res_certas = 0 for pk, pv in perg.items(): print(f'{pk}: {pv["pergunta"]}') print('Respostas: ') for rk, rv in pv['respostas'].items(): print(f'[{rk}]: {rv}') rep_usr = input('Sua Resposta: ') if rep_usr == pv['resposta_certa']: print('EEEEHHH!!! Você acertou!!') res_certas += 1 else: print('IXIIIII!!! Voce Errou!') print() qtd_perg = len(perg) perc_act = res_certas/qtd_perg * 100 print(f'total de perguntas são {qtd_perg}. ') print(f'Voce acertou {res_certas} respostas.') print(f'Sua porcentagem de acerto foi de {perc_act:.2f}%.')
name = "Bob" greeting = "Hello, Bob" print(greeting) name = "Rolf" print(greeting) greeting = f"Hello, {name}" print(greeting) # -- name = "Anne" print( greeting ) # This still prints "Hello, Rolf" because `greeting` was calculated earlier. print( f"Hello, {name}" ) # This is correct, since it uses `name` at the current point in time. # -- Using .format() -- # We can define template strings and then replace parts of it with another value, instead of doing it directly in the string. greeting = "Hello, {}" with_name = greeting.format("Rolf") print(with_name) longer_phrase = "Hello, {}. Today is {}." formatted = longer_phrase.format("Rolf", "Monday") print(formatted)
""" Brian Kerninghan - Count the number of set bits in an integer Time Complexity - O(log n) Key idea: n & (n-1) """ def count(n): count = 0 while (n != 0): n = n & (n-1) count += 1 return count #n = int(raw_input("Enter any interger \n")) #print brian_kerninghan(n)
class Player: def __init__(self, player_id: int, nickname: str, websocket, is_vip: bool = False): self.player_id = player_id self.nickname = nickname self.is_vip = is_vip self.websocket = websocket def __repr__(self): return 'Player({}, {})'.format(self.player_id, self.nickname)
Word = "Hello" Letters = [] for w in Word: print(w) if w == "e": print("Funny") Letters.append(w) print(Letters) Numbers = [1,2,3,4,5] for l in Numbers: print(l) Numbers1 = [] # for num in range(10): for num in range(-1, 13, 3): Numbers.append(num) print(num) # While loops counter = 1 while (counter <= 10): print(counter) counter += 1 # Break loop Participants = ["Jen", "Alex", "Tina", "Joe", "Ben"] position = 1 for name in Participants: if name == "Tina": print("About to break") break print("About to increment") position = position + 1 print(position) # Continue loop for number in range(10): if number % 3 == 0: print(number) continue print("Not")
def ROTRIGHT(i: int, bits: int) -> int: return i >> bits | i << 32 - bits # Two Extreme Bits (8 bits) def TEB(i: int) -> int: return ((i & 0x80) >> 6) | (i & 1) # Two Extreme Bits Reversed (8 bits) def TEBR(i: int) -> int: return (i & 0xFF) >> 7 | (i & 1) << 1 # Middles Extreme Bits (32 bits) def MEB(i: int) -> int: return TEB(i >> 24) << 6 | TEB(i >> 16) << 4 | TEB(i >> 8) << 2 | TEB(i) lookup_reversed_bytes = [ 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71, 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1, 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2, 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73, 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3, 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74, 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4, 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75, 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5, 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76, 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6, 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77, 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7, 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78, 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8, 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79, 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9, 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A, 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA, 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B, 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB, 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C, 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC, 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D, 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD, 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E, 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE, 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F, 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF, ] def kkv_hash(data: bytes) -> int: length = len(data) if length == 0 or (length == 1 and data[0] == 0): return 0 hash, i = length, 0 hash ^= data[i] << 24 while i < length: hash = (hash << 3) & 0xFFFFFFFF hash ^= hash >> 2 hash |= 0x80000000 hash += lookup_reversed_bytes[data[i]] hash &= 0xFFFFFFFF hash ^= ROTRIGHT(hash, 17) hash += ROTRIGHT(hash ^ MEB(hash), TEBR(data[i])) hash &= 0xFFFFFFFF hash >>= 1 i += 1 hash ^= (MEB(hash) << 23) & 0xFFFFFFFF | (MEB(hash) << 7) & 0xFFFFFFFF return hash
game = [[0, 0, 0, ' '], [0, 0, 0, ' '], [0, 0, 0, ' '], [0, 0, 0, ' '], [0, 0, 0, ' ']] frame_counter = 0 # Ask score for frames for frame in game: if frame_counter < 4: shot_number = 0 for shot in range(2): game[frame_counter][shot_number] = int(input(f'Score for frame {frame_counter + 1}, shot {shot_number + 1}: ')) shot_number += 1 frame_counter += 1 if 0 > game[frame_counter][0] + game[frame_counter][0] > 10: raise ValueError('values are too large or too small') else: for shot in range(game[frame_counter].count(0) - 1): game[4][shot] = int(input(f'Score for frame 10, shot {shot + 1}: ')) if 0 > game[4][shot] > 10: raise ValueError('Value is too large or too small') if game[4][0] == 10 and game[4][1] == 10: game[4] = ([10, 10, 20, 'X', 'X'], [0, 0, ' ']) game[4][1][0] = int(input('Score for frame 10, shot 3: ')) game[4][1][1] = game[4][1][0] elif game[4][0] == 10: game[4] = ([10, 10, 'X'], [game[4][1], 0, 0, ' ']) game[4][1][1] = int(input('Score for frame 10, shot 3: ')) elif game[4][0] + game[4][1] == 10: game[4] = ([game[4][0], game[4][1], 10, '/'], [0, 0, ' ']) game[4][1][0] = int(input('Score for frame 10, shot 3: ')) game[4][1][1] = game[4][1][0] frame_counter = 1 print(game) game.reverse() # Count and organize scores for frame in game[1:]: if frame[0] == 10 and frame[1] == 0: game[frame_counter][2] = 10 + game[frame_counter - 1][0] if game[frame_counter - 1][0] == 10 and frame_counter != 1: game[frame_counter][2] += game[frame_counter - 2][0] else: game[frame_counter][2] += game[frame_counter - 1][1] game[frame_counter][3] = 'X' elif frame[0] + frame[1] == 10: game[frame_counter][2] = 10 + game[frame_counter - 1][0] game[frame_counter][3] = '/' elif 0 < frame[0] + frame[1] < 10: game[frame_counter][2] = frame[0] + frame[1] game[frame_counter][3] = f'{frame[0] + frame[1]}' elif frame[0] + frame[1] == 0: game[frame_counter][2] = 0 game[frame_counter][3] = '0' print(f'frame {4 - frame_counter} finished') print(game) frame_counter += 1 game.reverse() print(game)
# Prime Numbers, Sieve of Eratosthenes def prime_list(min_num, max_num): sieve = [True] * (max_num + 1) # Sieve of Eratosthenes m = int(max_num ** 0.5) # sqrt(n) for i in range(2, m + 1): if sieve[i] == True: for j in range(i+i, max_num+1, i): sieve[j] = False sieve[1] = False return [i for i in range(min_num, max_num+1) if sieve[i] == True] M, N = map(int, input().split(" ")) primes = prime_list(M, N) for prime in primes: print(prime)
class Status(object): """This encapsulates the Twitter reply to a tweet.""" def __init__(self, status): """This initializes the object storing metadata.""" self._status = status @property def id(self): return self._status.id @property def username(self): """This formats the username.""" return '@{}'.format(self._status.user.screen_name) @property def link(self): """This formats the URL to the link for the tweet.""" return 'https://twitter.com/{0.user.screen_name}/status/{0.id}'.format( self._status, ) @property def text(self): return self._status.text @property def time(self): """This provides access to creation time.""" return self._status.created_at def __repr__(self): """This returns a representation of the status object.""" return '{0.time} {0.id} {0.username} {0.text}'.format(self)
letters = ['o', 's', 'h', 'a', 'd', 'a'] print(letters.index('h')) print(letters.index('d')) print(max(letters)) print(min(letters)) print(letters.count('a')) print(letters.remove('h')) #after remove r from the list print(letters) #reverse the whole list print(letters.reverse()) print(letters)
# DESAFIO 051 # Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostra os 10 primeiros # termos dessa progressão. print('=' * 30) print(f'{"10 TERMOS DE UMA PA":^30}') print('=' * 30) n1 = int(input('Digite o primeiro termo da PA: ')) rz = int(input('Digite a razão da PA: ')) pr = 1 for c in range(0, 10): pr = n1 + (rz * c) print(pr, end=' ➝ ') print('ACABOU')
def isPalindromeLinkedList(self, head: ListNode) -> bool: arr = [] while head: arr.append(head.val) head = head.next return arr == arr[::-1]
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/1020/A def f(l): dist = lambda a,b:a-b if a>b else b-a global a,b ta,fa,tb,fb = l ht = dist(ta,tb) if (fa>=a and fa<=b) or (fb>=a and fb<=b) or ht==0: return ht + dist(fa,fb) return ht + min(dist(fa,a)+dist(fb,a),dist(fa,b)+dist(fb,b)) n,h,a,b,k = list(map(int,input().split())) [print(f(list(map(int,input().split())))) for _ in range(k)]
#!/usr/bin/env python # -*- coding: utf-8 -*- # 目的: 条件分岐について学ぶためのサンプルコード # 説明文を表示 print("0時から24時までの任意の時間を入力してみよう") # 変数 "time" に説明文のあとに入力された文字を数値として入れる(代入) time = int(raw_input("時間(0〜24の範囲の数字)を入力: ")) # 区切りを表示 print("------------------------------------------") # 「変数 "time" が12より小さい」かつ「変数 "time" が0以上」のとき,「AMです!」と表示 if time < 12 and time >= 0: print("AMです!") # 「変数 "time" が12以下」かつ「変数 "time" が24以下」のとき,「PMです!」と表示 elif time >= 12 and time <= 24: print("PMです!") # 上2つの条件に当てはまらない場合の説明を表示 else: print("{}時なんて存在しないよ!".format(time))
#!/usr/bin/env python data = [ [ 7, [ 3.50016331673, 7.37909364700, 8.02381229401, 8.01285839081, 9.77704334259, 9.15692901611, 8.73682498932, 7.93067312241 ], ], [ 4.202, [ 2.06499981880, 2.08285713196, 2.18571448326, 2.19214320183, 2.19214320183, 2.19357180595, 2.19500041008, 2.19714307785 ], ], [ 9.8592, [ 3.56500029564, 3.61142873764, 3.63214302063, 3.63357162476, 3.63428616524, 3.63428616524, 3.63428616524, 3.63428568840, 3.63285756111 ] ] ] # setup path = [] text = [] dx, dy = 48, -24 nx, ny = 8, 12 # axes X = dx * nx Y = dy * ny U = dx V = dy * 2 M = nx N = ny // 2 path += [ '<path fill="none" stroke="currentColor" stroke-width="1" d="', 'M0 0h%sv%sh%sz' % (X, Y, -X), 'M0 0' + ('m%s -4v4' % U * (M - 1)), 'M0 0' + ('m4 %sh-4' % V * (N - 1)), 'M0 %s' % Y + ('m%s 4v-4' % U * (M - 1)), 'M%s 0' % X + ('m-4 %sh4' % V * (N - 1)), '" />' ] # data marker = 'square' for tflops, tt in data: x = 0 d = 'M0 %.1f' % (dy * tt[0]) for t in tt[1:]: x += dx y = dy * t d += ' %.0f %.1f' % (x, y) a = '<text x="%s" y="%s">%.0fTFlops</text>' % (x, y + 24, tflops) text.append(a) path.append( '<path fill="none" stroke="currentColor" stroke-width="3"' ' marker-start="url(#%s)"' % marker + ' marker-mid="url(#%s)"' % marker + ' marker-end="url(#%s)"' % marker + ' d="%s" />' % d ) marker = 'circle' # axes text for i in range(0, N + 1, 2): y = V * i + 6 t = 2 * i a = '<text x="-8" y="%s" text-anchor="end">%s</text>' % (y, t) text.append(a) for i in range(0, nx + 1): x = dx * i if i > 4: t = '%sk' % (4 ** (i - 5)) else: t = 4 ** i a = '<text x="%s" y="20">%s</text>' % (x, t) text.append(a) # labels for x, y, u, v, t in [ (4, 12, 0, -12, 'Runtime/step (s)'), (4, 9.8, 0, -12, 'TACC Ranger (8M elem/core)'), (4, 3.6, 0, -16, 'ALCF Intrepid (1M elem/core)'), (4, 2.2, 0, 24, 'ALCF Vesta (1M elem/core)'), (4, 0, 0, 40, 'Cores'), ]: x = x * dx + u y = y * dy + v s = '<text x="%.0f" y="%.0f">' % (x, y) + t + '</text>' text.append(s) # SVG output x = 64 + X y = 80 - Y out = [ '<svg width="%s" height="auto"' % x + ' viewBox="%s %s %s %s"' % (-32, Y - 32, x, y) + ' fill="#fff" stroke="#fff"' ' xmlns="http://www.w3.org/2000/svg">', '<defs>', '<marker id="circle"' ' refX="4" refY="4" markerWidth="8" markerHeight="8">', '<circle stroke="currentColor" stroke-width="1" r="1" cx="4" cy="4"/>', '</marker>', '<marker id="square"' ' refX="4" refY="4" markerWidth="8" markerHeight="8">', '<path stroke="currentColor" stroke-width="1" d="M3 3h2v2h-2z" />', '</marker>', '</defs>' ] + path + [ '<g fill="none" stroke-width="8" font-size="16" text-anchor="middle"' ' font-family="-apple-system, sans-serif">' ] + text + [ '</g>', '<g fill="currentColor" stroke="none" font-size="16" text-anchor="middle"' ' font-family="-apple-system, sans-serif">' ] + text + [ '</g>', '</svg>' ] out = '\n'.join(out) + '\n' out = out.encode('utf-8') open('SORD-Benchmark.svg', 'w').write(out)
def solution(string, markers): output = [] for line in string.split("\n"): containsCommentIndicator = "" for c in line: if c in markers: containsCommentIndicator = c break if containsCommentIndicator != "": line = line[:line.find(containsCommentIndicator)] line = line.rstrip(" ") output.append(line) return '\n'.join(output) print(solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]))
__author__ = 'The dashQC_fmri developers' __copyright__ = 'Copyright 2018, The SIMEXP lab' __credits__ = [ 'Jonathan Armoza', 'Pierre Bellec', 'Yassine Benhajali', 'Sebastian Urchs' ] __license__ = 'MIT' __maintainer__ = 'Sebastian Urchs' __email__ = 'sebastian.urchs@mail.mcgill.com' __status__ = 'Prototype' __url__ = 'https://github.com/SIMEXP/bids_qcdash' __packagename__ = 'dashQC_fmri' # TODO update description __description__ = ("dashQC_fmri is an interactive quality control dashboard that facilitates " "the manual rating of resting state fMRI focused preprocessing.") # TODO long description __longdesc__ = """\ Coming soon. """ SETUP_REQUIRES = [ 'setuptools>=18.0', ] REQUIRES = [ 'numpy', 'pandas', 'nibabel', 'pillow', 'matplotlib', 'nilearn', 'scipy', 'scikit-learn' ] LINKS_REQUIRES = [ ] TESTS_REQUIRES = [ ] CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Image Analysis', 'License :: MIT License', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ]
# -*- coding: utf-8 -*- print("""*************** xxxxx Atmsine Hoşgeldiniz. İşlemler; 1. Bakiye Sorgulama 2. Para Yatırma 3. Para Çekme Kart iadesi için 'q' basın *************** """) bakiye = 4000 while True: islem = input("İşlemi seçiniz: ") if (islem == "q"): print("Yine Bekleriz") break elif (islem == "1"): print("Bakiyeniz: {} tl'dir".format(bakiye)) elif (islem == "2"): miktar = int(input("Yatırmak istediğiniz miktarı giriniz: ")) bakiye += miktar elif (islem == "3"): miktar1 = int(input("Çekmek istediğiniz miktarı giriniz: ")) if (bakiye - miktar1 < 0): print("Bakiye yeterli değil") continue bakiye -= miktar1 else: print("Geçersiz İşlem")
__title__ = 'fipeapi' __description__ = 'Python Extra Oficial API for REST Request to consult Vehicles Prices.' __url__ = 'https://github.com/deibsoncarvalho/tabela-fipe-api' __version__ = '0.1.0' __author__ = 'Deibson Carvalho' __author_email__ = 'eu@deibsoncarvalho.com' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2020 Deibson Carvalho'
def _update_Spr(Gp, Gr, Rpr, Spr_shape, I, B, t): # F Reconstruction F = np.zeros(Spr_shape) F += np.linalg.multi_dot((Gp.T, Rpr[0], Gr)) Gk = Gp * I[:, t][:, np.newaxis] Ik = np.reshape(I[:, t], (len(I[:, t]), 1)) bk = np.reshape(B[t, :], (1, len(B[t, :]))) F += 2*np.linalg.multi_dot((Gk.T, Ik, bk)) # # C construction # C = np.zeros(Spr_shape) # Gks = [] # bks = [] # for l in range(len(Rpr)): # C += np.linalg.multi_dot((Gp.T, Rpr[l], Gr)) # for tk in range(I.shape[1]): # Gk = Gp * I[:, tk][:, np.newaxis] # Gks.append(Gk) # Ik = np.reshape(I[:, tk], (len(I[:, tk]), 1)) # bk = np.reshape(B[tk, :], (1, len(B[tk, :]))) # bks.append(bk) # C += 2*np.linalg.multi_dot((Gk.T, Ik, bk)) # print(C.shape) # A construction A = Gp.T.dot(Gp) C = Gk.T.dot(Gk) # for tk in range(I.shape[1]): # A.append(2*Gks[tk].T.dot(Gks[tk])) #print(A) # B construction B = Gr.T.dot(Gr) D = bk.T.dot(bk) pinv_C = np.linalg.pinv(C) pinv_B = np.linalg.pinv(B) A_new = pinv_C.dot(A) B_new = D.dot(pinv_B) C_new = pinv_C.dot(F.dot(pinv_B)) return solve_sylvester(A_new, B_new, C_new) # for tk in range(I.shape[1]): # B.append(bks[tk].T.dot(bks[tk])) #print(B) # print("sto cominciando gd") # S = np.zeros(Spr_shape) # mu = 1e-7 # for i in range(100): # S_old = S # print("siamo all'iterzione ", i) # # print(_M(A=A, B=B, X=S)) # #print(C) # grad = (_M(A=A, B=B, X=S) - C) # S = S + mu * (grad) # #print(S) # if np.linalg.norm(S-S_old) < 1e-3: # break # print(S) # print("numero di iterazioni fatte %d, valore a convergenza %4f" %(i, np.linalg.norm(S-S_old))) # # gss = GeneralizedSylvesterSolver(max_iter=500, verbose=0) # gss.fit(A, B, C) #return S def _update_B(Gp, Spr, I): B = np.zeros((I.shape[1], Spr[0].shape[1])) for t in range(I.shape[1]): y = np.reshape(I[:, t], (len(I[:, t]), 1)) X = Gp.dot(Spr[0]) * y ls = LinearRegression() ls.fit(X, y) B[t, :] = ls.coef_ return B def _iterative_gradient_solver(A, B, C, tol=1e-3, max_iter=500, verbose=0, random_state=0): return None # # Xs = [random_state.randn(C.shape[0], C.shape[1])] # iterates_error = [] # objective_error = [] # mu = (1/2*np.sum([np.linalg.norm(Aj)*np.linalg.norm(Bj) # for Aj, Bj in zip(A, B)]))-1e-5 # for _iter in range(max_iter): # AXB = _M(A=A, B=B, X=Xs[-1].copy()) # gradients = [] # for i in range(len(A)): # gradients.append(np.linalg.multi_dot((A[i].T, C - AXB, B[i].T))) # if(np.any(np.isnan(np.array(gradients)))): # print("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb") # break # X = np.sum(np.array([Xs[-1] + mu*grad # for grad in gradients]), axis=0)/len(A) # if(np.any(np.isnan(X))): # print("aaaaaaaaaaaaaaaaaaaaaaaaaacle") # break # Xs.append(X) # iterates_error.append(np.linalg.norm(Xs[-2] - Xs[-1])) # objective_error.append(np.linalg.norm(C - _M(A, B, Xs[-1]))) # # if objective_error[-1] < tol: # print("iteration %d" % _iter) # break # else: # print("The algorithm did not converge") # return X # # def _iterative_gradient_smaller_solver(A, B, F, tol=1e-3, max_iter=200, verbose=0, random_state=0): return None # # Xs = [np.zeros(C.shape)] # iterates_error = [] # objective_error = [] # print(2*np.sum([np.linalg.norm(Aj)*np.linalg.norm(Bj) # for Aj, Bj in zip(A, B)])) # mu = (1/(2*np.sum([np.linalg.norm(Aj)*np.linalg.norm(Bj) # for Aj, Bj in zip(A, B)])))-1e-7 # print(mu) # a = A[0] # c = A[1] # b = B[0] # d = B[1] # for _iter in range(max_iter): # grad = F - a.dot(Xs[-1]).dot(b) - c.dot(Xs[-1]).dot(d) # print(grad) # X_1 = Xs[-1] + mu * a.T.dot(grad).dot(b.T) # X_2 = Xs[-1] + mu * c.T.dot(grad).dot(d.T) # Xs.append(np.array((X_1 + X_2)/2)) # # print(Xs[-2]) # # print(Xs[-1]) # diff = Xs[-2] - Xs[-1] # # print(1e-4 < 1e-3) # # print(np.linalg.norm(diff)) # # print(tol) # iterates_error.append(np.linalg.norm(diff)/F.shape[0]) # #print(iterates_error[-1]) # # objective_error.append(np.linalg.norm(F - _M(A=A, B=B, X=Xs[-1]))/F.shape[0]) # # print(objective_error[-1]) # # print(float(objective_error[-1]) < float(tol)) # if objective_error[-1] < tol: # print("iteration %d" % _iter) # break # else: # print("The algorithm did not converge") # return Xs[-1]tr
with open("vocab_origin.txt", "r") as f: lines = f.readlines() for i in range(185): lines.append("<s_{}>".format(i)) with open("vocab.txt", "w") as f: for line in lines: f.write(line.strip() + "\n")
# Go to http://apps.twitter.com and create an app. # The consumer key and secret will be generated for you API_KEY = "" API_SECRET_KEY = "" # After the step above, you will be redirected to your app's page. # Create an access token under the the "Your access token" section ACCESS_TOKEN = "" ACCESS_TOKEN_SECRET = ""
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. UNTRIAGED = 0 TRIAGED_INCORRECT = 1 TRIAGED_CORRECT = 2 TRIAGED_UNSURE = 3 TRIAGE_STATUS_TO_DESCRIPTION = { UNTRIAGED: 'Untriaged', TRIAGED_INCORRECT: 'Incorrect', TRIAGED_CORRECT: 'Correct', TRIAGED_UNSURE: 'Unsure', }
#!/usr/bin/env python Nmp = 345 nbound = [0]*1037 step = 0 for l in open('test'): step += 1 for i in range(Nmp): if int(l[i]) > 0: nbound[i] += 1 for i in range(Nmp): print ('%i %i %f' % (i+1, nbound[i], nbound[i] / float(step)))
def file_upload(f): with open('static/upload/'+f.name,'wb+') as destination: for i in f.chunks(): destination.write(i)
def calculate_s(data_counts, qubit_indices, pauli_bases): number_of_data_points = 0 s = 0 #print("qubit_indices", qubit_indices) #print("pauli_bases", pauli_bases) #print("data_counts", data_counts.items()) # loop through indices and read measurments for key, value in data_counts.items(): number_of_data_points += value number_of_1s = 0 for i in range(len(qubit_indices)): # indexing a string ordered from left qubit to right if key[qubit_indices[i]] == "1": if pauli_bases[qubit_indices[i]] != 'I': # when not Identity basis number_of_1s += 1 if number_of_1s % 2 == 1: # odd number of 1s s -= value else: # even number of 1s s += value # turn counts into probabilities final_s = s / number_of_data_points return final_s
def longest_linked_list_chain(keys, buckets, loops=10): """ Rolls `keys` number of random keys into `buckets` buckets and counts the collisions. Run `loops` number of times. """ for i in range(loops): key_counts = {} for i in range(buckets): key_counts[i] = 0 for i in range(keys): random_key = str(random.random()) hash_index = hash(random_key) % buckets key_counts[hash_index] += 1 largest_n = 0 for key in key_counts: if key_counts[key] > largest_n: largest_n = key_counts[key] print( f"Longest Linked List Chain for {keys} keys in {buckets} buckets (Load Factor: {keys/buckets:.2f}): {largest_n}" ) longest_linked_list_chain(4, 16, 5) longest_linked_list_chain(16, 16, 5) longest_linked_list_chain(32, 16, 5) longest_linked_list_chain(1024, 128, 5)
lisi = 1 lisi1 = 1 lisi2 = 2 zhangsan3 = 3 lisi3 = 3 dev = 1
#################################################################### # ### k8s_resource_keys.py ### #################################################################### # ### Author: SAS Institute Inc. ### #################################################################### # ### # Copyright (c) 2021, SAS Institute Inc., Cary, NC, USA. ### # All Rights Reserved. ### # SPDX-License-Identifier: Apache-2.0 ### # ### #################################################################### class KubernetesResourceKeys(object): """ Class providing static access to commonly used key names in Kubernetes resources (list is not all-inclusive). """ ADDRESSES = "addresses" ANNOTATIONS = "annotations" ANNOTATION_PROXY_BODY_SIZE = "nginx.ingress.kubernetes.io/proxy-body-size" ANNOTATION_COMPONENT_NAME = "sas.com/component-name" ANNOTATION_COMPONENT_VERSION = "sas.com/component-version" ANNOTATION_VERSION = "sas.com/version" API_VERSION = "apiVersion" ARCHITECTURE = "architecture" AVAILABLE_REPLICAS = "availableReplicas" BACKEND = "backend" CAPACITY = "capacity" CLUSTER_IP = "clusterIP" COLLISION_COUNT = "collisionCount" COMPLETION_TIME = "completionTime" CONDITIONS = "conditions" CONTAINER_RUNTIME_VERSION = "containerRuntimeVersion" CONTAINER_STATUSES = "containerStatuses" CONTAINERS = "containers" CONTROLLER_TEMPLATE = "controllerTemplate" CREATION_TIMESTAMP = "creationTimestamp" CURRENT_REPLICAS = "currentReplicas" DATA = "data" DESTINATION = "destination" ENV = "env" EXACT = "exact" FULLY_LABELED_REPLICAS = "fullyLabeledReplicas" GATEWAYS = "gateways" GENERATION = "generation" HTTP = "http" HOST = "host" HOSTS = "hosts" HOST_IP = "hostIP" IMAGE = "image" IMAGES = "images" INIT_CONTAINERS = "initContainers" ITEMS = "items" KERNEL_VERSION = "kernelVersion" KIND = "kind" KUBE_PROXY_VERSION = "kubeProxyVersion" KUBELET_VERSION = "kubeletVersion" LABEL_CAS_NODE_TYPE = "cas-node-type" LABEL_CAS_SERVER = "cas-server" LABEL_MANAGED_BY = "app.kubernetes.io/managed-by" LABEL_PG_CLUSTER = "pg-cluster" LABEL_PG_DEPLOYMENT_NAME = "deployment-name" LABEL_PG_SERVICE_NAME = "service-name" LABEL_SAS_DEPLOYMENT = "sas.com/deployment" LABELS = "labels" MANAGED_FIELDS = "managedFields" MATCH = "match" MATCH_LABELS = "matchLabels" METADATA = "metadata" NAME = "name" NAMESPACE = "namespace" NODE_INFO = "nodeInfo" NODE_NAME = "nodeName" NUMBER = "number" OBSERVED_GENERATION = "observedGeneration" OPERATING_SYSTEM = "operatingSystem" OS_IMAGE = "osImage" OWNER_REFERENCES = "ownerReferences" PARAMETERS = "parameters" PATH = "path" PATHS = "paths" PHASE = "phase" POD_CIDR = "podCIDR" POD_CIDRS = "podCIDRs" POD_IP = "podIP" POD_IPS = "podIPs" PORT = "port" PORTS = "ports" PROTOCOL = "protocol" PROVISIONER = "provisioner" PUBLISH_NODE_PORT_SERVICE = "publishNodePortService" READY = "ready" READY_REPLICAS = "readyReplicas" REPLICAS = "replicas" RESOURCES = "resources" RESOURCE_VERSION = "resourceVersion" RESTART_COUNT = "restartCount" ROUTE = "route" ROUTES = "routes" RULES = "rules" SELECTOR = "selector" SELF_LINK = "selfLink" SERVICE = "service" SERVICE_PORT = "servicePort" SERVICE_NAME = "serviceName" SERVICES = "services" SPEC = "spec" START_TIME = "startTime" STARTED = "started" STATE = "state" STATUS = "status" SUCCEEDED = "succeeded" TARGET_PORT = "targetPort" TCP = "tcp" TO = "to" TEMPLATE = "template" TYPE = "type" UID = "uid" URI = "uri" UPDATED_REPLICAS = "updatedReplicas" UNAVAILABLE_REPLICAS = "unavailableReplicas" WORKER_TEMPLATE = "workerTemplate" WORKERS = "workers"
''' Create a tuple with all teams of the Brazilian Championship, in classification order. After the show the following: 1 - The first 5 teams. 2 - The last 4 teams. 3 - A list with the teams in alphabetical order. 4 - In which position is the Chapecoense team. ''' table = ( 'RB Bragantino', 'Athletico-PR', 'Palmeiras', 'Fortaleza', 'Bahia', 'Santos', 'Atlético-GO', 'Atlético-MG', 'Fluminense', 'Flamengo', 'Corinthians', 'Ceara', 'Internacional', 'Juventude', 'Sport Recife', 'Cuiaba', 'São Paulo', 'Chapecoense', 'América-MG', 'Grêmio' ) print(f'The teams are: \033[32m{table}\033[m') questions = ('first', 'last', 'alphabetical', 'position') for question in questions: if question == 'first': print(f'The first 5 teams are: \033[34m{table[:5]}\033[m') elif question == 'last': print('The last 4 teams are: ') for team in range(-4, 0, 1): print(f'\033[34m{table[team]}\033[m') elif question == 'alphabetical': print(f'The table in alphabetical order is \033[32m{sorted(table)}\033[m') elif question == 'position': print(f'\033[34mChapecoense\033[m is in position \033[32m{table.index("Chapecoense") + 1}\033[m')
decimal = int(input("Decimal: ")) binary = "" while decimal != 0: rest = decimal % 2 binary = str(rest) + binary decimal = decimal // 2 print ("Binary: %s" % binary)
def swap_in_place(arr, idx1, idx2): new_arr = arr[:] if idx1 > len(arr) - 1 or idx2 > len(arr) - 1: return arr new_arr.insert(idx1, new_arr.pop(idx2)) #print(new_arr) new_arr.insert(idx2, new_arr.pop(idx1 + 1)) return new_arr def test_case(arr, idx1, idx2, solution, test_func): output = test_func(arr, idx1, idx2) if output == solution: print("Passed") else: print(f"Failed, expected {solution}, got {output}") test_case([1, 2, 3, 4, 5], 1, 3, [1, 4, 3, 2, 5], swap_in_place) test_case([1, 2, 3, 4, 5], 0, 4, [5, 2, 3, 4, 1], swap_in_place) test_case([1, 2], 0, 1, [2, 1], swap_in_place) test_case([], 0, 0, [], swap_in_place)
""" This file provides a library of music exception types that are used throughout the project to better report errors to the user. Exception Types: TabException - general exception type for the project used to report general errors in the tab that cannot be reported more specifically MeasureException - caused by the construction of a Measure whose length is not <= 1 TabFileException - error caused by incorrect input tab file TabIOException - error caused by file reading/writing in tab program. TabConfigurationException - exception caused by incorrect program configuration file StaffException - caused by illegal StaffString object construction StaffOutOfBoundsException - caused by accessing a StaffString index that is out of bounds LoggingException - caused by failure of logging operations. Some of these exceptions are used in try-except clauses that handle a more generic Python exception (e.g. ValueError, IOError) and then raise one of these exception types to better inform the user. author: Chami Lamelas date: Summer 2019 """ UNIDENTIFIED_LINE_IN_FILE = -1 # for exceptions that report a file line no. as part of the error, use this to report that line couldn't be found class TabException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return str(self.msg) class MeasureException(TabException): def __init__(self, op, reason): super().__init__("Operation on Measure failed: {0}. Reason: {1}.".format(op, reason)) class TabFileException(TabException): def __init__(self, issue = "unknown", reason="unknown", line=UNIDENTIFIED_LINE_IN_FILE): self.issue = issue self.reason = reason self.line = line errorMsg = "Issue with the tab file: \"{0}\". Reason: {1}.".format(issue, reason) if line != UNIDENTIFIED_LINE_IN_FILE: errorMsg += " Approximate line number: {0}.".format(line) super().__init__(errorMsg) class TabIOException(TabException): def __init__(self, issue, reason): super().__init__("I/O Error with \"{0}\". Reason: {1}.".format(issue, reason)) class TabConfigurationException(TabException): def __init__(self, reason="not specified", line=UNIDENTIFIED_LINE_IN_FILE): errorMsg = "Program configuration failed. Reason: {0}.".format(reason) if line != UNIDENTIFIED_LINE_IN_FILE: errorMsg += " Approximate line number: {0}.".format(line) errorMsg += " To reset the config. file, you can redownload it from the repository." super().__init__(errorMsg) class StaffException(TabException): def __init__(self, op, reason, str): super().__init__("Staff operation cannot be performed: \"{0}\", Reason: {1}. str={2}".format(op, reason, str)) class StaffOutOfBoundsException(TabException): def __init__(self, reason, viol): super().__init__("Bounds Violation, reason: {0} ({1})".format(reason, viol)) class LoggingException(Exception): def __init__(self, op, reason): self.msg = "Log operation \"{0}\" failed. Reason: {1}".format(op, reason) def __str__(self): return str(self.msg)
# you can use print for debugging purposes, e.g. # print "this is a debug message" # The strategy is to iterate through the string, putting each character onto # a specific stack, depending on its type. # A, When we put the character onto the stack, we check to see if the one before it # is an opposite - eg. { then } are opposites. If we find an opposite pair, we annihilate them. # When a pair is annihilated, we check to see if any other types have priority # The strategy is to iterate through the array, putting each character onto the stack. If the opposite character is present on the stack, immediately annihilate both. At the end if the size of the stack is zero, the string is properly formatted. def solution(S): annihilate = { ')': '(', ']': '[', '}': '{', } stack = [] if not S: return 1 for char in S: #print char if char in annihilate.keys() and len(stack) > 0: if stack[-1] == annihilate[char]: stack.pop() else: stack.append(char) else: stack.append(char) #print stack if len(stack) == 0: return 1 else: return 0
""" Functions for positioning geometry """ def CheckFeasibility(newPart, candidatePositionIndex, sheet): candidatePosition = sheet.extremePoints[candidatePositionIndex] check = True for i in range(2): # check if violate sheet limits if newPart.Dim[i] + candidatePosition[i] > sheet.useableSize[i]: check = False for j in range(len(sheet.currentParts)): # check if overlap with current parts if overlap(newPart,candidatePosition, sheet.currentParts[j]): check = False return check def overlap(Part1, position, Part2): ov = True if position[0] >= Part2.Dim[0] + Part2.Position[0]: ov = False if Part2.Position[0] >= position[0] + Part1.Dim[0]: ov = False if position[1] >= Part2.Dim[1] + Part2.Position[1]: ov = False if Part2.Position[1] >= position[1] + Part1.Dim[1]: ov = False return ov def TakesProjection(Part1, Part2, proj_dir): pd = proj_dir od = 1-pd check = True if Part2.Dim[pd] + Part2.Position[pd] > Part1.Position[pd]: #i.e. piece is further from axis in projection direction check = False if Part2.Position[od] > Part1.Position[od]: #i.e. piece too far check = False if Part2.Position[od] + Part2.Dim[od] < Part1.Position[od] : # i.e. piece not far enough check = False return check
def prepare(base_class, engine): """ Reflect base class to current database engine. """ base_class.prepare(engine, reflect=True)
class Pattern_Twenty_Three: '''Pattern twenty_three ooooooooooooooooo ooooooooooooooooo ooooooooooooooooo oooo oooo oooo ooooooooooooooooo ooooooooooooooooo ooooooooooooooooo oooo oooo oooo ooooooooooooooooo ooooooooooooooooo ooooooooooooooooo ''' def __init__(self, strings='o'): if not isinstance(strings, str): strings = str(strings) for i in range(15): if i == 0: print(f' {strings * 17}') elif i in [3, 4, 5]: print(f'{strings * 4}') elif i in [9, 10, 11]: print(f'{(strings * 4).rjust(17)}') elif i in [1, 2, 6, 7, 8, 12, 13, 14]: print(f'{strings * 17}') if __name__ == '__main__': Pattern_Twenty_Three()
expected_output = { 'chassis_feature': 'V2 AC PEM', 'clei': 'IPMUP00BRB', 'desc': 'ASR 9006 4 Line Card Slot Chassis with V2 AC PEM', 'device_family': 'ASR', 'device_series': '9006', 'num_line_cards': 4, 'pid': 'ASR-9006-AC-V2', 'rack_num': 0, 'sn': 'FOX1810G8LR', 'top_assy_num': '68-4235-02', 'vid': 'V02'}
# -*- coding: utf-8 -*- # Busca em Largura(sem nós repetidos) def busca_largura(tab_inicial): fila = [tab_inicial] filaRepet = [tab_inicial] # usada para verificar expanção de repetidos nos_exp = 0 # numero de nós expandidos while (len(fila) > 0): nodoTemp = fila.pop(0) # retira do início da fila nos_exp = nos_exp + 1 print('No expandido:', nos_exp) imprime_tabuleiro(nodoTemp) if verifica_objetivo(nodoTemp): print("*** Solução encontrada! Parabéns! ***") imprime_jogadas(nodoTemp) break else: #nodos_filhos = expandir(nodoTemp) for nt in nodos_filhos: #verifica se ja foi expandido ja_existe = False for x in filaRepet: if tabuleiros_iguais(nt, x): ja_existe = True break # se achou repetido para a busca if not ja_existe: fila.append(nt) filaRepet.append(nt) #busca heurística a* #def busca_astar(tab_inicial):
directions_2 = [ [ 1, 0 ], [ 0, 1 ], [ 2, 0 ], [ 0, 2 ], [ 1, 1 ], [ 1, -1 ], [ 3, 0 ], [ 0, 3 ], [ 1, 2 ], [ 2, 1 ], [ 1, -2 ], [-2, 1 ], [ 4, 0 ], [ 0, 4 ], [ 1, 3 ], [ 3, 1 ], [ 1, -3 ], [-3, 1 ], [ 2, 2 ], [ 2, -2 ], [ 5, 0 ], [ 0, 5 ], [ 1, 4 ], [ 4, 1 ], [ 1, -4 ], [-4, 1 ], [ 2, 3 ], [ 3, 2 ], [ 2, -3 ], [-3, 2 ], [-1, 0 ], [ 0, -1 ], [-2, 0 ], [ 0, -2 ], [-1, -1 ], [-1, 1 ], [-3, 0 ], [ 0, -3 ], [-1, -2 ], [-2, -1 ], [-1, 2 ], [ 2, -1 ], [-4, 0 ], [ 0, -4 ], [-1, -3 ], [-3, -1 ], [-1, 3 ], [ 3, -1 ], [-2, -2 ], [-2, 2 ], [-5, 0 ], [ 0, -5 ], [-1, -4 ], [-4, -1 ], [-1, 4 ], [ 4, -1 ], [-2, -3 ], [-3, -2 ], [-2, 3 ], [ 3, -2 ], [ 0, 0 ] ] directions_3 = [ [ 1, 0, 0], [ 0, 1, 0], [ 0, 0, 1], [-1, 1, 1], [ 1, -1, 1], [ 1, 1, -1], [-2, 1, 0], [ 1, -2, 0], [-2, 0, 1], [ 0, -2, 1], [ 1, 0, -2], [ 0, 1, -2], [-1, 0, 0], [ 0, -1, 0], [ 0, 0, -1], [ 1, -1, -1], [-1, 1, -1], [-1, -1, 1], [ 2, -1, 0], [-1, 2, 0], [ 2, 0, -1], [ 0, 2, -1], [-1, 0, 2], [ 0, -1, 2], [ 3, 0, 0], [ 0, 3, 0], [ 0, 0, 3], [ 2, 1, 0], [ 2, 0, 1], [ 1, 2, 0], [ 0, 2, 1], [ 1, 0, 2], [ 0, 1, 2], [ 1, 1, 1], [-3, 0, 0], [ 0, -3, 0], [ 0, 0, -3], [-2, -1, 0], [-2, 0, -1], [-1, -2, 0], [ 0, -2, -1], [-1, 0, -2], [ 0, -1, -2], [-1, -1, -1] ] def idx_ppar( directions, idx, coo ): """ Return a pair [ index, data_name ]""" cood = ["x", "y", "z"] return [ directions.index(idx) * 6 + cood.index(coo) * 2, "[%s] in %s-axis" % ( ', '.join( map( str, idx ) ), coo ) ]
ALL_NODES_TYPE = '<all>' ALL_PRIMITIVES_TYPES = '<all-primitives>' ALL_REGION_TYPES = '<all-regions>' ALL_CONDITIONS_TYPES = '<all-conditions>' LOCATION_OR_WAYPOINT = '<location-or-waypoint>' STRING_TYPE = '<string>' NUMBER_TYPE = '<number>' BOOLEAN_TYPE = '<boolean>' ENUM_TYPE = '<enum>' ARBITRARY_OBJ_TYPE = '<arbitrary-obj>' PARAMETERS_FIELD_DCT = '<parameters>'
# 2021-02-08 # Emma Benjaminson # Implementation of Linked List # for ch2-p1 (at least) # need init, delete methods (possibly traverse?) # singly linked list for now # class Node # this will contain init method # attribute is next which is pointer to the next node class Node: def __init__(self, data): self.data = data self.next = None # this can be replaced later def __repr__(self): # the repr is a machine-friendly string representation (__str__ supersedes __repr__ if present) return self.data # class LinkedList # contain init, delete methods # internal traverse method? class LinkedList: def __init__(self, nodes=None): # what parameters do I need here? head? Do I pass in head? or not, for now? self.head = None # if nodes is not None, then we have to add them to the list # we use pop to remove elements from nodes # we assign the first node to the head # then we iterate through the remaining nodes and create new nodes that are connected if nodes is not None: node = Node(data=nodes.pop(0)) self.head = node for elem in nodes: node.next = Node(data=elem) node = node.next def __repr__(self): # this prints a machine-friendly string representing the class object (superseded by __str__ if present) node = self.head nodes = [] while node is not None: nodes.append(node.data) node = node.next nodes.append("None") return " -> ".join(nodes) def __iter__(self): # this makes the LinkedList class iterable node = self.head while node is not None: yield node node = node.next def add_first(self, node): # this node is going to become the head # first set node.next equal to current head # then make current head equal to node node.next = self.head self.head = node def add_last(self, node): # check that the list is not empty # if it is, then we just make node the head if not self.head: self.head = node return # run through the nodes (while node.next is not none) # then arrive at the last node # assign its next pointer to the new node # assign the pointer of this new last node to none for curr_node in self: pass curr_node.next = node def remove_node(self, target_node): # check that the list is not empty # otherwise raise an exception if not self.head: raise Exception('List is empty') # check if the target_node is the head if self.head == target_node: self.head = self.head.next return # save the head as the previous node prev_node = self.head # iterate through the nodes for node in self: # if node is the target_node then assign prev_node.next = node.next if node == target_node: prev_node.next = node.next return prev_node = node raise Exception('Node with data %s is not in linked list.' % target_node.data)
#To find first index of an element in an array. def firstIndex(arr, si, x): l = len(arr) #length of array. if l == 0: #base case return -1 if arr[si] == x: #if element is found at start index of an array then return that index. return si return firstIndex(arr, si+1, x) #recursive call. arr = [] #initialised array. n=int(input("Enter size of array : ")) for i in range(n): #input array. ele=int(input()) arr.append(ele) x=int(input("Enter element to be searched ")) #element to be searched print(firstIndex(arr, 0, x))
rest_api_version = 99 extensions = dict( required_params=['training_frame', 'x'], validate_required_params="", set_required_params=""" parms$training_frame <- training_frame if(!missing(x)) parms$ignored_columns <- .verify_datacols(training_frame, x)$cols_ignore """, with_model=""" model@model$aggregated_frame_id <- model@model$output_frame$name """, module=""" #' Retrieve an aggregated frame from an Aggregator model #' #' Retrieve an aggregated frame from the Aggregator model and use it to create a new frame. #' #' @param model an \linkS4class{H2OClusteringModel} corresponding from a \code{h2o.aggregator} call. #' @examples #' \dontrun{ #' library(h2o) #' h2o.init() #' df <- h2o.createFrame(rows = 100, #' cols = 5, #' categorical_fraction = 0.6, #' integer_fraction = 0, #' binary_fraction = 0, #' real_range = 100, #' integer_range = 100, #' missing_fraction = 0) #' target_num_exemplars = 1000 #' rel_tol_num_exemplars = 0.5 #' encoding = "Eigen" #' agg <- h2o.aggregator(training_frame = df, #' target_num_exemplars = target_num_exemplars, #' rel_tol_num_exemplars = rel_tol_num_exemplars, #' categorical_encoding = encoding) #' # Use the aggregated frame to create a new dataframe #' new_df <- h2o.aggregated_frame(agg) #' } #' @export h2o.aggregated_frame <- function(model) { key <- model@model$aggregated_frame_id h2o.getFrame(key) } """, ) doc = dict( preamble=""" Build an Aggregated Frame Builds an Aggregated Frame of an H2OFrame. """, params=dict( x="""A vector containing the \code{character} names of the predictors in the model.""" ), examples=""" library(h2o) h2o.init() df <- h2o.createFrame(rows = 100, cols = 5, categorical_fraction = 0.6, integer_fraction = 0, binary_fraction = 0, real_range = 100, integer_range = 100, missing_fraction = 0) target_num_exemplars = 1000 rel_tol_num_exemplars = 0.5 encoding = "Eigen" agg <- h2o.aggregator(training_frame = df, target_num_exemplars = target_num_exemplars, rel_tol_num_exemplars = rel_tol_num_exemplars, categorical_encoding = encoding) """ )
# SPDX-License-Identifier: MIT # Copyright (c) 2020 Akumatic # #https://adventofcode.com/2020/day/12 def readFile() -> list: with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f: return [line.strip() for line in f.readlines()] def part1(input: list) -> int: x, y = 0, 0 dirs = ((1,0), (0, 1), (-1, 0), (0, -1)) idx = 0 for instruction in input: action = instruction[0] value = int(instruction[1:]) if action == "N": y += value elif action == "S": y -= value elif action == "E": x += value elif action == "W": x -= value elif action == "F": x += dirs[idx][0] * value y += dirs[idx][1] * value else: # action in ("R", "L") sig = 1 if action == "L" else -1 idx = (idx + sig * value // 90) % 4 return abs(x) + abs(y) def part2(input: list) -> int: x, y, wx, wy = 0, 0, 10, 1 dirs = ((1,1), (-1, 1), (-1, -1), (1, -1)) idx = 0 for instruction in input: action = instruction[0] value = int(instruction[1:]) if action == "N": wy += value elif action == "S": wy -= value elif action == "E": wx += value elif action == "W": wx -= value elif action == "F": x += wx * value y += wy * value else: # action in ("R", "L") sig = 1 if action == "L" else -1 for _ in range(value // 90): idx_prev, idx = idx, (idx + sig) % 4 tmp_wx = wx wx = wy * dirs[idx_prev][1] * dirs[idx][0] wy = tmp_wx * dirs[idx_prev][0] * dirs[idx][1] return abs(x) + abs(y) if __name__ == "__main__": input = readFile() print(f"Part 1: {part1(input)}") print(f"Part 2: {part2(input)}")
print("Please inser the following") print() adjective = input("adjetive: ") animal = input("animal: ") verb1 = input("verb: ") exclamation = input("exclamation: ") verb2 = input ("verb: ") verb3 = input("verb: ") print() print() print("Your story is: ") print() print(f"The other day, I was really in trouble. It all started when I saw a very\n{adjective} {animal} {verb1} down the hallway. '{exclamation}!' I yelled. but all\nI could think to do was to {verb2} over and over. Miraculously, \nthat caused it to stop, but not before it tried to {verb3}\nright in front of my family.")
# JS console is having a very hard time running my logic, # so I rewrote it in Python to ensure I was on the right track. # Still trying to get JS to run the one-linerized code. def run(input, turns): input = input.split(',') last = {int(n): i + 1 for (i, n) in enumerate(input)} spoken = int(input[-1]) for turn in xrange(len(input), turns): new_spoken = turn - last[spoken] if spoken in last else 0 last[spoken] = turn spoken = new_spoken return spoken run('13,0,10,12,1,5,8', 30000000)
# # PySNMP MIB module DMTF-MONITOR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DMTF-MONITOR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:36:16 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, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint") DmiString, dmiCompId, dmiEventSubSystem, dmiEventStateKey, dmiEventDateTime, dmiEventSeverity, dmiEventAssociatedGroup, dmiEventSystem = mibBuilder.importSymbols("DMTF-DMI-MIB", "DmiString", "dmiCompId", "dmiEventSubSystem", "dmiEventStateKey", "dmiEventDateTime", "dmiEventSeverity", "dmiEventAssociatedGroup", "dmiEventSystem") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Unsigned32, TimeTicks, Gauge32, MibIdentifier, ModuleIdentity, iso, enterprises, NotificationType, Bits, IpAddress, Counter64, Integer32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Unsigned32", "TimeTicks", "Gauge32", "MibIdentifier", "ModuleIdentity", "iso", "enterprises", "NotificationType", "Bits", "IpAddress", "Counter64", "Integer32", "Counter32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") class DmiCounter(Counter32): pass class DmiCounter64(Counter64): pass class DmiGauge(Gauge32): pass class DmiInteger(Integer32): pass class DmiOctetstring(OctetString): pass class DmiCompId(Integer32): pass class DmiGroupId(Integer32): pass dmtf = MibIdentifier((1, 3, 6, 1, 4, 1, 412)) dmtfStdMifs = MibIdentifier((1, 3, 6, 1, 4, 1, 412, 2)) dmtfDynOids = MibIdentifier((1, 3, 6, 1, 4, 1, 412, 3)) dmtfMonitorMIF = ModuleIdentity((1, 3, 6, 1, 4, 1, 412, 2, 6)) if mibBuilder.loadTexts: dmtfMonitorMIF.setLastUpdated('9710221800Z') if mibBuilder.loadTexts: dmtfMonitorMIF.setOrganization('Desktop Management Task Force') dmtfMonitorAdditionalInformationsTable = MibTable((1, 3, 6, 1, 4, 1, 412, 2, 6, 1), ) if mibBuilder.loadTexts: dmtfMonitorAdditionalInformationsTable.setStatus('current') dmtfMonitorAdditionalInformationsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 412, 2, 6, 1, 1), ).setIndexNames((0, "DMTF-MONITOR-MIB", "DmiCompId"), (0, "DMTF-MONITOR-MIB", "DmiGroupId")) if mibBuilder.loadTexts: dmtfMonitorAdditionalInformationsEntry.setStatus('current') assetTag = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 1, 1, 1), DmiString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: assetTag.setStatus('current') monitorLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 1, 1, 2), DmiString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: monitorLocation.setStatus('current') monitorPrimaryUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 1, 1, 3), DmiString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: monitorPrimaryUserName.setStatus('current') monitorPrimaryUserPhone = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 1, 1, 4), DmiString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: monitorPrimaryUserPhone.setStatus('current') dmtfMonitorResolutionsTable = MibTable((1, 3, 6, 1, 4, 1, 412, 2, 6, 2), ) if mibBuilder.loadTexts: dmtfMonitorResolutionsTable.setStatus('current') dmtfMonitorResolutionsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1), ).setIndexNames((0, "DMTF-MONITOR-MIB", "DmiCompId"), (0, "DMTF-MONITOR-MIB", "DmiGroupId"), (0, "DMTF-MONITOR-MIB", "monitorResolutionIndex")) if mibBuilder.loadTexts: dmtfMonitorResolutionsEntry.setStatus('current') dmtfMonitorResolutionsState = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1, 0), Integer32().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("readwrite") if mibBuilder.loadTexts: dmtfMonitorResolutionsState.setStatus('current') monitorResolutionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1, 1), DmiInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: monitorResolutionIndex.setStatus('current') horizontalResolution = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1, 2), DmiInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: horizontalResolution.setStatus('current') verticalResolution = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1, 3), DmiInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: verticalResolution.setStatus('current') refreshRate = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1, 4), DmiInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: refreshRate.setStatus('current') verticalScanMode = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("unknown", 2), ("unsupported", 3), ("notInterlaced", 4), ("interlaced", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: verticalScanMode.setStatus('current') minimumMonitorRefreshRate = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1, 6), DmiInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: minimumMonitorRefreshRate.setStatus('current') maximumMonitorRefreshRate = MibTableColumn((1, 3, 6, 1, 4, 1, 412, 2, 6, 2, 1, 7), DmiInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: maximumMonitorRefreshRate.setStatus('current') mibBuilder.exportSymbols("DMTF-MONITOR-MIB", dmtfMonitorMIF=dmtfMonitorMIF, DmiInteger=DmiInteger, dmtfMonitorResolutionsState=dmtfMonitorResolutionsState, horizontalResolution=horizontalResolution, refreshRate=refreshRate, monitorPrimaryUserPhone=monitorPrimaryUserPhone, dmtfDynOids=dmtfDynOids, PYSNMP_MODULE_ID=dmtfMonitorMIF, dmtfMonitorResolutionsTable=dmtfMonitorResolutionsTable, dmtf=dmtf, monitorPrimaryUserName=monitorPrimaryUserName, dmtfMonitorResolutionsEntry=dmtfMonitorResolutionsEntry, dmtfStdMifs=dmtfStdMifs, maximumMonitorRefreshRate=maximumMonitorRefreshRate, DmiCompId=DmiCompId, dmtfMonitorAdditionalInformationsTable=dmtfMonitorAdditionalInformationsTable, verticalResolution=verticalResolution, minimumMonitorRefreshRate=minimumMonitorRefreshRate, monitorResolutionIndex=monitorResolutionIndex, dmtfMonitorAdditionalInformationsEntry=dmtfMonitorAdditionalInformationsEntry, DmiGroupId=DmiGroupId, monitorLocation=monitorLocation, verticalScanMode=verticalScanMode, assetTag=assetTag, DmiCounter=DmiCounter, DmiOctetstring=DmiOctetstring, DmiCounter64=DmiCounter64, DmiGauge=DmiGauge)
""" @author: Alfons @contact: alfons_xh@163.com @file: 15-03-for.py @time: 18-7-1 下午10:48 @version: v1.0 """ for i in range(10): print("Hello, I'm little {i}.".format(i=i)) else: print("I'm else.") # 执行完for循环后运行