content
stringlengths
7
1.05M
print('-'*10, 'TABUADA', '-'*10) n = 0 while True: num = int(input('Digite um nรบmero:')) if num < 0: break for c in range(1,11): print(f'{num} x {c} = {num * c}') print('Programa Tabuada encerrado. Atรฉ mais!')
# Note: The schema is stored in a .py file in order to take advantage of the # int() and float() type coercion functions. Otherwise it could easily stored as # as JSON or another serialized format. '''This schema has been changed compared to the Udacity schema, due to missing values for attributes 'user' and 'uid'. It makes sense to keep them in the schema for use of other OSM data.''' schema = { 'node': { 'type': 'dict', 'schema': { 'id': {'required': True, 'type': 'integer', 'coerce': int}, 'lat': {'required': True, 'type': 'float', 'coerce': float}, 'lon': {'required': True, 'type': 'float', 'coerce': float}, 'user': {'required': False, 'type': 'string'}, 'uid': {'required': False, 'type': 'integer', 'coerce': int}, 'version': {'required': True, 'type': 'string'}, 'changeset': {'required': True, 'type': 'integer', 'coerce': int}, 'timestamp': {'required': True, 'type': 'string'} } }, 'node_tags': { 'type': 'list', 'schema': { 'type': 'dict', 'schema': { 'id': {'required': True, 'type': 'integer', 'coerce': int}, 'key': {'required': True, 'type': 'string'}, 'value': {'required': True, 'type': 'string'}, 'type': {'required': True, 'type': 'string'} } } }, 'way': { 'type': 'dict', 'schema': { 'id': {'required': True, 'type': 'integer', 'coerce': int}, 'user': {'required': False, 'type': 'string'}, 'uid': {'required': False, 'type': 'integer', 'coerce': int}, 'version': {'required': True, 'type': 'string'}, 'changeset': {'required': True, 'type': 'integer', 'coerce': int}, 'timestamp': {'required': True, 'type': 'string'} } }, 'way_nodes': { 'type': 'list', 'schema': { 'type': 'dict', 'schema': { 'id': {'required': True, 'type': 'integer', 'coerce': int}, 'node_id': {'required': True, 'type': 'integer', 'coerce': int}, 'position': {'required': True, 'type': 'integer', 'coerce': int} } } }, 'way_tags': { 'type': 'list', 'schema': { 'type': 'dict', 'schema': { 'id': {'required': True, 'type': 'integer', 'coerce': int}, 'key': {'required': True, 'type': 'string'}, 'value': {'required': True, 'type': 'string'}, 'type': {'required': True, 'type': 'string'} } } } }
class Port: def __init__(self, mac_address, ip_address, mtu): self.mac_address = mac_address self.ip_address = ip_address self.mtu = mtu def __str__(self): return '(%s - %s - %d)' % (self.mac_address, self.ip_address, self.mtu)
class Context: def __init__(self, **kwargs): self.message = kwargs.get("message") self.command = kwargs.get("command") def print(self, content, *, indent=0, **kwargs): if indent > 0: lines = content.split("\n") for line in lines: prefix = "| " * indent print(prefix + line, **kwargs) else: print(content, **kwargs) def print_empty(self, indent=0): if indent > 0: print("| " * indent) else: print()
''' Config! Change as needed. NOTE: Please make sure that all information (except for authentication keys) are passed in lower-case! ''' # Your twitter access tokens. These are your accounts that you will enter giveaways from. # Add as many users as you want, and please make sure to enter your username in lower case! access_tokens = { "user1" : { 'consumer_key' : '', 'consumer_secret' : '', 'access_token' : '', 'access_token_secret' : '' }, "user2" : { 'consumer_key' : '', 'consumer_secret' : '', 'access_token' : '', 'access_token_secret' : '' }, "user3" : { 'consumer_key' : '', 'consumer_secret' : '', 'access_token' : '', 'access_token_secret' : '' } } # REQUIRED # Users that you would like to tag in the giveaway. Add three users here. tag_users = ["z1rk4", "user2", "user3"] #REQUIRED # Keywords that the bot will search for in tweets. Change/add as many as you want! keywords = ["giveaway", "coding", "python"] # OPTIONAL # Account names that you want to specifically search for giveaway tweets. # Add as many as you want! account_names = ["giveaway_account1", "giveaway_account2", "giveaway_account3"] # OPTIONAL # Add your own custom replies here that are triggered upon a specific keyword. # NOTE: Program may not be able to send reply if replies are too long! Please be careful # with how many custom replies you use :) custom_replies = { "keyword1" : "reply1", "keyword2" : "reply2", "keyword3" : "reply3", } ''' Leave the variables below alone if you do not have the respective information. ''' # OPTIONAL # Your steam trade link trade_link = "" # OPTIONAL # Your wax trade link wax_trade_link = "" # OPTIONAL # Your DatDrop profile link datdrop_profile_link = "" # IGNORE link_paste_keywords = ["tradelink", "trade link", " tl"]
class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ stack = [] for token in tokens: if token not in "+-*/": stack.append(int(token)) else: b = stack.pop() a = stack.pop() if token == "+": stack.append(a + b) elif token == "-": stack.append(a - b) elif token == "*": stack.append(a * b) else: if a * b < 0: stack.append(-(abs(a) / abs(b))) else: stack.append(a / b) return stack[0]
n, m = [int(x) for x in input().split()] edges = [[int(x) for x in input().split()] for _ in range(m)] if m < n - 1: print(0) exit() paths = [] start = 1 still_possible = True while still_possible: passed = [1] current = start for i in range(1, n): for e in edges: if e[0] == current and e[1] != current and not (e[1] in passed): for path in paths: if path[i] == e[1]: break else: passed.append(e[1]) current = e[1] break elif e[0] != current and e[1] == current and not (e[0] in passed): for path in paths: if path[i] == e[0]: break else: passed.append(e[0]) current = e[0] break else: # if e all in edges are not accepted if passed == [1]: still_possible = False break if len(passed) == n: paths.append(passed) print(len(paths))
def is_unique_points(points=None): if points is None: points = {} points_dict = {} for key, values in points.items(): new_key = '%s:%s' % tuple(values) is_exists = points_dict.get(new_key, None) if is_exists: return False else: points_dict[new_key] = key return True
def XXX(self, root: TreeNode) -> int: if root is None: return 0 m = 10 ** 5 # mไธบๆœ€ๅฐๆทฑๅบฆ def bfs(d, node): nonlocal m if node.left is None and node.right is None: m = min(m, d) return bfs(d + 1, node.left) if node.left else None bfs(d + 1, node.right) if node.right else None bfs(1, root) return m
""" Conditionally Yours Pseudocode: """ # Increase = Current Price - Original Price # Percent Increase = Increase / Original x 100 # Create integer variable for original_price # Create integer variable for current_price # Create float for threshold_to_buy # Create float for threshold_to_sell # Create float for portfolio balance # Create float for balance check # Create string for recommendation, default will be buy recommendation = "buy" # Calculate difference between current_price and original_price # Calculate percent increase # Print original_price print(f"Netflix's original stock price was ${original_price}") # Print current_price # Print percent increase # Determine if stock should be bought or sold # Print recommendation print("Recommendation: " + recommendation) print() print("But wait a minute... lets check your excess equity first.") # Challenge # Declare balance variable as a float # Declare balance_check variable balance_check = balance * 5 # Compare balance to recommendation, checking whether or not balance is 5 times more than current_price print(f"You currently have ${balance} in excess equity available in your portfolio.") # IF-ELSE Logic to determine recommendation based off of balance check
def containsDuplicate(nums): sorted = sorted(nums) for i in range(len(nums)-1): if nums[i] == nums[i+1]: return True return False
def find_max(root): if not root: return 0 if not root.left and not root.right: return root.val m = [0] helper(root, m) return m[0] def helper(n, m): if n.val > m[0]: m[0] = n.val if n.left: helper(n.left, m) if n.right: helper(n.right, m)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedListToBST(self, head: ListNode) -> TreeNode: def getMedian(left: ListNode, right: ListNode) -> ListNode: fast = slow = left while fast != right and fast.next != right: fast = fast.next.next slow = slow.next return slow def recursive(left, right): if left == right: return None mid = getMedian(left, right) root = TreeNode(mid.val) root.left = recursive(left, mid) root.right = recursive(mid.next, right) return root return recursive(head, None)
# -*- coding: utf-8 -*- """ Created on Wed Dec 13 11:06:08 2017 @author: James Jiang """ def position(range_firewall, time): offset = time % (2 * (range_firewall - 1)) if offset > range_firewall - 1: return(2 * (range_firewall - 1) - offset) else: return(offset) all_lines = [line.rstrip('\n') for line in open('Data.txt')] ranges = {} for i in all_lines: pair = i.split(': ') ranges[int(pair[0])] = int(pair[1]) severity = 0 for i in ranges: if position(ranges[i], i) == 0: severity += ranges[i] * i print(severity)
#!/usr/bin/env python3 def chdir(path, folder): return path+"/"+folder def previous(path): temp = "" for i in path.split("/")[1:-1]: temp += "/"+i return temp
# Bradley Grose data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%s" print(format_string % data)
""" Write a Python program to count number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters """ def count_k_dist(str1, k): str_len = len(str1) result = 0 ctr = [0] * 27 for i in range(0, str_len): dist_ctr = 0 ctr = [0] * 27 for j in range(i, str_len): if(ctr[ord(str1[j]) - 97] == 0): dist_ctr += 1 ctr[ord(str1[j]) - 97] += 1 if(dist_ctr == k): result += 1 if(dist_ctr > k): break return result str1 = input("Input a string (lowercase alphabets):") k = int(input("Input k: ")) print("Number of substrings with exactly", k, "distinct characters : ", end = "") print(count_k_dist(str1, k))
def winning_score(): while True: try: winning_score = int(input("\nHow many points should " "declare the winner? ")) except ValueError: print("\nInvalid input type. Enter a positive number.") continue else: if winning_score <= 0: print("\nInvalid input value. Enter a positive number.") continue return winning_score
''' Else Statements Code that executes if contitions checked evaluates to False. '''
class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: ret = [] for x in range(left, right + 1): y = x while y > 0: z = y % 10 if z == 0 or x % z != 0: break; y //= 10 if y == 0: ret.append(x) return ret
'''Jonatan Paschoal 22/04/2020 Desafio 8 - Faรงa um programa que receba um valor em metros e transforme para centรญmetros e milรญmetros.''' print('=='*30) x = float(input('Digite um valor em metros: ')) cent = x / 100 mili = x / 1000 print('{:.5f} em centรญmetros รฉ {:.5f} e em milรญmetros {:.5f}.'.format(x, cent, mili)) print('=='*30)
# -*- coding: utf_8 -*- __author__ = 'Yagg' class ShipGroup: def __init__(self, ownerName, count, shipType, driveTech, weaponTech, shieldTech, cargoTech, cargoType, cargoQuantity): self.count = count self.shipType = shipType self.driveTech = driveTech self.weaponTech = weaponTech self.shieldTech = shieldTech self.cargoTech = cargoTech self.cargoType = cargoType self.cargoQuantity = cargoQuantity self.ownerName = ownerName self.shipMass = 0 self.number = -1 self.liveCount = 0 self.battleStatus = '' self.destinationPlanet = '' self.sourcePlanet = '' self.range = 0.0 self.speed = 0.0 self.fleetName = '' self.groupStatus = ''
# ไนŸๆ˜ฏไบŒๅˆ†ๆณ• class Solution: def mySqrt(self, x: int) -> int: if x < 2: return x left, right = 2, x // 2 + 1 while left <= right: mid = left + (right - left) // 2 if mid * mid > x: right = mid - 1 elif mid * mid < x: left = mid + 1 else: return mid return right if __name__ == '__main__': s = Solution() res = s.mySqrt(0) print(res)
#!/usr/bin/python3 """ Analysis for a 4 load cells (2 strain gauges each) wired to give a single differential output. https://www.eevblog.com/forum/reviews/large-cheap-weight-digital-scale-options/ """ def deltav(V, R, r0, r1, r2, r3): """return the differential output voltage for the 4x load cell""" i0 = V / (4.0 * R + r0 - r3) i1 = V / (4.0 * R - r0 + r3) va = i0 * (2.0 * R - r1 - r3) vb = i1 * (2.0 * R + r2 + r3) return va - vb def main(): Ve = 5.0 Rn = 1000.0 x = deltav(Ve, Rn, 1, 1, 1, 1) print(x) x = deltav(Ve, Rn, 0, 0, 2, 2) print(x) x = deltav(Ve, Rn, 0, 2, 2, 0) print(x) x = deltav(Ve, Rn, 0, 1, 3, 0) print(x) x = deltav(Ve, Rn, 0, 0, 3, 1) print(x) x = deltav(Ve, Rn, 1, 0, 0, 3) print(x) main()
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/72/G # ่ฏฅ้ข˜็›ฎcfไธๆ”ฏๆŒpython~~ๅ› ๆญคไธๆ”พๅ…ฅๅ‘จ่ต›้ข˜ๅบ“.. n = int(input()) if n<2: print(1) else: l = [1,1] + [0]*(n-1) for i in range(2,n+1): l[i] = l[i-1] + l[i-2] print(l[-1])
class MyHookExtension(object): def post_create_hook(self, archive, product): pass def post_ingest_hook(self, archive, product): pass def post_pull_hook(self, archive, product): pass def post_remove_hook(self, archive, product): pass _hook_extensions = { 'myhooks': MyHookExtension() } def hook_extensions(): return _hook_extensions.keys() def hook_extension(name): return _hook_extensions[name]
# return a go-to-goal heading vector in the robot's reference frame def calculate_gtg_heading_vector( self ): # get the inverse of the robot's pose robot_inv_pos, robot_inv_theta = self.supervisor.estimated_pose().inverse().vector_unpack() # calculate the goal vector in the robot's reference frame goal = self.supervisor.goal() goal = linalg.rotate_and_translate_vector( goal, robot_inv_theta, robot_inv_pos ) return goal # calculate translational velocity # velocity is v_max when omega is 0, # drops rapidly to zero as |omega| rises v = self.supervisor.v_max() / ( abs( omega ) + 1 )**0.5
# Time: O(nlogn) # Space: O(n) class Solution(object): def stoneGameVI(self, aliceValues, bobValues): """ :type aliceValues: List[int] :type bobValues: List[int] :rtype: int """ sorted_vals = sorted(((a, b) for a, b in zip(aliceValues, bobValues)), key=sum, reverse=True) return cmp(sum(a for a, _ in sorted_vals[::2]), sum(b for _, b in sorted_vals[1::2]))
# pylint: disable=global-statement,missing-docstring,blacklisted-name foo = "test" def broken(): global foo bar = len(foo) foo = foo[bar]
def parse_input(): fin = open('input_day3.txt','r') inputs = [] for line in fin: inputs.append(line.strip('\n')) return inputs def plot_path(inputs, path, ref_path=None): x=0 y=0 c = 0 hits = [] for i in inputs.split(','): (d, v) = (i[0],int(i[1:])) fn = lambda x,y,p: (x,y) if d == 'R': fn = lambda x,y: (x + 1, y) elif d == 'L': fn = lambda x,y: (x - 1, y) elif d == 'U': fn = lambda x,y: (x, y + 1) elif d == 'D': fn = lambda x,y: (x, y - 1) for p in range(1,v+1): c+=1 x,y = fn(x,y) key = "{}_{}".format(x,y) if key in path: pass # first count of steps is retained else: path[key] = c # find intersections if ref_path and key in ref_path: hits.append(key) return hits def find_manhattan_dist(hits): md_list = [] for h in hits: (x,y) = map(int,h.split('_')) md_list.append(abs(x) + abs(y)) return md_list if __name__ == '__main__': inputs = parse_input() w1_path = {} w2_path = {} plot_path(inputs[0], w1_path) hits = plot_path(inputs[1], w2_path, w1_path) print('hits', hits) # part one md_list = find_manhattan_dist(hits) print('manhattan distances', md_list) print('Shortest', min(md_list)) # part two steps = [] for h in hits: steps.append(w1_path[h] + w2_path[h]) print('steps', steps); print('shortest step', min(steps))
if __name__ == "__main__": cadena = "Hola, Mundo" print("Imprimir Cadena") print(cadena) print("Imprimir Caracter por Caracter") for caracter in cadena: print(caracter) print("Imprimir lista =>") for entero in range(10): print(entero) # Secuencias de ruptura print("Imprimir Secuencias de Ruptura =>") for i in range(35): if i > 30 and i < 32: break # Si el nรบmero entre 1 y 35 es par if i % 2 == 0: print(i, end=" ") else: continue print("Print Inalcanzable") # Iterando sobre listas print() print("Imprimiendo una lista =>") myList = ['uno','dos','tres','cuatro','cinco'] for numero in myList: print(numero)
class Solution: def detectCycle(self, head): """O(n) time | O(1) space""" fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast is slow: return find_cycle(head, slow) return None def find_cycle(head, slow): while head is not slow: head = head.next slow = slow.next return slow
# This file is imported from __init__.py and exec'd from setup.py __version__ = "1.0.0+dev" VERSION = (1, 0, 0)
#returns list of groups. group is a list of strings, a string per person. def getgroups(): with open('Day6.txt', 'r') as file: groupList = [] currgroup = [] for line in file: if line not in ['\n', '\n\n']: currgroup.append(line.strip()) else: groupList.append(currgroup) currgroup = [] groupList.append(currgroup) return(groupList) def option1(): groupList = getgroups() norepeatsgroups = [] for group in groupList: combined = [] for person in group: for char in person: if char not in combined: combined.append(char) norepeatsgroups.append(combined) answer = 0 for group in norepeatsgroups: answer += len(group) print(answer, "unique 'yes'es ") def option2(): groupList = getgroups() count = 0 allyesgroups = [] for group in groupList: person1 = group[0] for person in group[1:]: for char in person1: #checks against the first person since first person must contain every letter(they all do but we have to pick one ok) if char not in person: person1 = person1.replace(char,'') #removes from first person if first person has a unique letter. if person1 != '': #removes empty lists. len([''])=1 allyesgroups.append(person1) count += len(person1) print(count, " communal 'yes'es ") def menu(): #privae grievance: yes's is silly. That is all. print("\nOption 1: Number of Unique yes's(Part A) \nOption 2: Number of communal yes's(Part B)\nOption 3: Exit\n\nType a number\n\n") try: option = int(input(">> ")) if option == 1: option1() elif option == 2: option2() elif option == 3: exit() else: print("Error: Incorrect Input\n\n") menu() except ValueError: print("Error: Incorrect Input. Enter a number\n\n") menu() if __name__ == "__main__": menu()
""" # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children """ class Solution: def levelOrder(self, root): """ :type root: Node :rtype: List[List[int]] """ if not root: return [] queue = [root] ans = [] while queue: arr = [] for _ in range(len(queue)): temp = queue.pop(0) arr.append(temp.val) for j in temp.children: queue.append(j) ans.append(arr) return ans
#!/usr/bin/env python # -*- coding: utf-8 -*- """Exits with status 0""" if __name__ == '__main__': exit(0)
# # @lc app=leetcode id=342 lang=python # # [342] Power of Four # # https://leetcode.com/problems/power-of-four/description/ # # algorithms # Easy (39.98%) # Likes: 315 # Dislikes: 141 # Total Accepted: 114.1K # Total Submissions: 283.1K # Testcase Example: '16' # # Given an integer (signed 32 bits), write a function to check whether it is a # power of 4. # # Example 1: # # # Input: 16 # Output: true # # # # Example 2: # # # Input: 5 # Output: false # # # Follow up: Could you solve it without loops/recursion? # class Solution(object): def _isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if num < 1: return False while num != 1: left, right = divmod(num, 4) if right != 0: return False num = left return True def __isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if num < 1: return False length = len(format(num, 'b')) return num & num - 1 == 0 and length % 2 == 1 def ___isPowerOfFour(self, num): """ :type num: int :rtype: bool """ return num > 0 and num & num - 1 == 0 and num % 3 == 1 def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ # 0x55555555 = 0b1010101010101010101010101010101 return num > 0 and num & num - 1 == 0 and num & 0x55555555 == num
list1=['Apple','Mango',1999,2000] print(list1) del list1[2] print("After deleting value at index 2:") print(list1) list2=['Apple','Mango',1999,2000,1111,2222,3333] print(list2) del list2[0:3] print("After deleting value till index 2:") print(list2)
# -*- coding: utf-8 -*- """ Created on Wed Dec 25 22:07:19 2019 @author: penko Returns information on all maps (e.g. Hanamura) in Overwatch, with options to return only OWL modes, and unique maps only (due to a quirk of the API). """ ''' # packages used in this function import requests import numpy as np import pandas as pd ''' # The guid's are fairly messed up within OW, with multiple guid's belonging to the # same map, each with different combinations of modes, including duplicates. # e.g. Hollywood - (Hybrid) and Hollywood - (Hybrid, Skirmish) will have different guid's # If we just want the list of unique maps and their type in the OWL then we can get rid of # duplicates and not worry about the lost guid's. # But since two matches/maps in the MatchStats might use different guid's for the same map, # it will be important to have all the possible guid's that have been used (the redundant part) # so that we can get the map name etc. This is further complicated by some 'map' values # being gone from the matches/maps section. Therefore, I will make uniqueness an argument def getMaps(unique = False, only_OWL_modes = False): maps = requests.get("https://api.overwatchleague.com/maps") if maps.status_code != 200: print("Error: Could not retrieve data from server. Code ", maps.status_code, sep='') return None m_json = maps.json() m_df = pd.DataFrame( [ { "guid": m['guid'], "id_string": m['id'], "name": m['name']['en_US'], "mode_id_name": [ (gm['Id'], gm['Name']) for gm in m['gameModes'] ] } for m in m_json if (m['guid'] not in ['0x08000000000006C7'] and m['id'] != "") ] ) # -First guid above is for VPP Green Room, which is a testing map for OWL devs # -The second part of if stmt (id string must exist) removes "maps" like Busan Sanctuary. # if this proves to be bad (e.g. a map id in the stats section needs # Busan Sactuary), then you can remove the 'and' portion. Perhaps in that # case, you could make the id_string = lower(name) # make a row for each game mode in the map m_df = m_df.explode('mode_id_name') m_df[['mode_id','mode_name']] = pd.DataFrame([*m_df.mode_id_name], m_df.index) m_df = m_df.drop(columns='mode_id_name') if only_OWL_modes == True: m_df = m_df[m_df.mode_name.isin(['Assault','Payload','Hybrid','Control'])] if unique == True: m_df.drop_duplicates(subset=['id_string','name','mode_id','mode_name'], inplace=True) # Gets rid of inaccurate Paris Hybrid entry. Otherwise left in for robustness m_df = m_df[np.logical_not(m_df.guid.isin(['0x0800000000000AF0']))] m_df.reset_index(drop=True, inplace=True) return m_df
base_vectors = [[0.001178571428571168, 1.9904285714285708, 0.0011071428571440833], [-0.013142857142857345, -0.0018571428571430015, 1.9921428571428583], [-0.0007499999999995843, 0.17799999999999994, -0.00024999999999630873], [-4.440892098500626e-16, -8.881784197001252e-16, 0.1769999999999996]] n = [8, 8, 6, 6] origin = [-3.4612499999999944, -7.169999999999995, -6.396750000000013] support_indices = [[0, 0, 1, 0], [0, 0, 1, 5], [0, 0, 5, 5], [0, 7, 1, 0], [7, 7, 0, 0]] support_xyz = [[-3.462, -6.992, -6.397], [-3.462, -6.992, -5.512], [-3.465, -6.28, -5.513], [-3.554, -7.005, 7.548], [-3.545, 6.75, 7.556]]
def solveProblem(inputPath): floor = 0 indexFloorInfo = 0 with open(inputPath) as fileP: valueLine = fileP.readline() for floorInfo in valueLine: indexFloorInfo += 1 if floorInfo == '(': floor += 1 elif floorInfo == ')': floor -= 1 if floor == -1: return indexFloorInfo print(solveProblem('InputD01Q2.txt'))
try: tests=int(input()) k=[] for i in range(tests): z=[] count=0 find,length=[int(x) for x in input().split(" ")] list1=list(map(int,input().rstrip().split())) for i in range(len(list1)): if list1[i]==find: z.append(i+1) count=count+1 if count>1: k.append(z) else: k.append("-1") if len(k)>1: for x in k: print(*x) except: pass
d = int(input('Quantos dias alugados? ')) k = float(input('Quantos Km rodados? ')) v = (d*60)+(0.15*k) print('O total a pagar รฉ de R$ {:.2f}'.format(v))
python = {'John':35,'Eric':36,'Michael':35,'Terry':38,'Graham':37,'TerryG':34} holy_grail = {'Arthur':40,'Galahad':35,'Lancelot':39,'Knight of NI':40, 'Zoot':17} life_of_brian = {'Brian':33,'Reg':35,'Stan/Loretta':32,'Biccus Diccus':45} #membership test print('Arthur' in holy_grail) if 'Arthur' not in python: print('He\'s not here!') people = {} people1 = {} people2 = {} #method 1 update people.update(python) people.update(holy_grail) people.update(life_of_brian) print(sorted(people.items())) #method 2 comprehension for groups in (python,holy_grail,life_of_brian) : people1.update(groups) print(sorted(people1.items())) #method 3 unpacking 3.5 later people2 = {**python,**holy_grail,**life_of_brian} print(sorted(people2.items())) print('The sum of the ages: ', sum(people.values()))
class Permission: """ An object representing a single permission overwrite. ``Permission(role='1234')`` allows users with role ID 1234 to use the command ``Permission(user='5678')`` allows user ID 5678 to use the command ``Permission(role='9012', allow=False)`` denies users with role ID 9012 from using the command """ def __init__(self, role=None, user=None, allow=True): if bool(role) == bool(user): raise ValueError("specify only one of role or user") self.type = 1 if role else 2 self.id = role or user self.permission = allow def dump(self): "Returns a dict representation of the permission" return {"type": self.type, "id": self.id, "permission": self.permission}
def dict_repr(self): return self.__dict__.__repr__() def dict_str(self): return self.__dict__.__str__() def round_price(price: float, exchange_precision: int) -> float: """Round prices to the nearest cent. Args: price (float) exchange_precision (int): number of decimal digits for exchange price Returns: float: The rounded price. """ return round(price, exchange_precision)
a, b, c = input().split(' ') a = float(a) b = float(b) c = float(c) areat = (a * c) / 2 areac = 3.14159 * c**2 areatp = (a + b) * c / 2 areaq = b * b arear = b * a print(f'TRIANGULO: {areat:.3f}') print(f'CIRCULO: {areac:.3f}') print(f'TRAPEZIO: {areatp:.3f}') print(f'QUADRADO: {areaq:.3f}') print(f'RETANGULO: {arear:.3f}')
#! python3 # aoc_05.py # Advent of code: # https://adventofcode.com/2021/day/5 # https://adventofcode.com/2021/day/5#part2 # def hello_world(): return 'hello world' class ventmap: def __init__(self, xmax, ymax): self.xmax = xmax self.ymax = ymax self.map = [[0 for i in range(xmax)] for j in range(ymax)] def check_line(x1,y1,x2,y2): return x1 == x2 or y1 == y2 def find_vents(input,x,y): mymap = ventmap(x,y) with open(input, 'r') as line_list: for line in line_list.readlines(): lstart, lend = line.split(' -> ') x1,y1 = lstart.split(',') x1 = int(x1) y1 = int(y1) x2,y2 = lend.split(',') x2= int(x2) y2 = int(y2) if check_line(x1,y1,x2,y2): if x1>x2 or y1 >y2: x1,x2 = x2,x1 y1,y2 = y2,y1 for i in range(x1,x2+1): for l in range(y1,y2+1): mymap.map[l][i]+=1 else: if x1>x2: x1,x2 = x2,x1 y1,y2 = y2,y1 if x1 < x2 and y1 < y2: #print("Diag down") for i in range(0,x2-x1+1): mymap.map[y1+i][x1+i] += 1 #diag down: else: #print("Diag up") for i in range(0,x2-x1+1): mymap.map[y1-i][x1+i] += 1 danger_points = 0 for line in mymap.map: for field in line: if field > 1: danger_points +=1 return danger_points print(find_vents("aoc_05_example.txt",10,10)) print(find_vents("aoc_05_input.txt",1000,1000))
# # PySNMP MIB module RAQMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAQMON-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:52:12 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, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint") InetPortNumber, InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetPortNumber", "InetAddress", "InetAddressType") rmon, = mibBuilder.importSymbols("RMON-MIB", "rmon") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") Bits, IpAddress, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, NotificationType, Counter64, Gauge32, iso, Integer32, Counter32, ModuleIdentity, Unsigned32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "IpAddress", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "NotificationType", "Counter64", "Gauge32", "iso", "Integer32", "Counter32", "ModuleIdentity", "Unsigned32", "ObjectIdentity") RowPointer, DisplayString, RowStatus, TruthValue, DateAndTime, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowPointer", "DisplayString", "RowStatus", "TruthValue", "DateAndTime", "TextualConvention") raqmonMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 16, 31)) raqmonMIB.setRevisions(('2006-10-10 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: raqmonMIB.setRevisionsDescriptions(('Initial version, published as RFC 4711.',)) if mibBuilder.loadTexts: raqmonMIB.setLastUpdated('200610100000Z') if mibBuilder.loadTexts: raqmonMIB.setOrganization('IETF RMON MIB Working Group') if mibBuilder.loadTexts: raqmonMIB.setContactInfo('WG Charter: http://www.ietf.org/html.charters/rmonmib-charter.html Mailing lists: General Discussion: [email protected] To Subscribe: [email protected] In Body: subscribe your_email_address Chair: Andy Bierman Email: [email protected] Editor: Dan Romascanu Avaya Email: [email protected]') if mibBuilder.loadTexts: raqmonMIB.setDescription('Real-Time Application QoS Monitoring MIB. Copyright (c) The Internet Society (2006). This version of this MIB module is part of RFC 4711; See the RFC itself for full legal notices.') raqmonNotifications = MibIdentifier((1, 3, 6, 1, 2, 1, 16, 31, 0)) raqmonSessionAlarm = NotificationType((1, 3, 6, 1, 2, 1, 16, 31, 0, 1)).setObjects(("RAQMON-MIB", "raqmonParticipantAddr"), ("RAQMON-MIB", "raqmonParticipantName"), ("RAQMON-MIB", "raqmonParticipantPeerAddrType"), ("RAQMON-MIB", "raqmonParticipantPeerAddr"), ("RAQMON-MIB", "raqmonQoSEnd2EndNetDelay"), ("RAQMON-MIB", "raqmonQoSInterArrivalJitter"), ("RAQMON-MIB", "raqmonQosLostPackets"), ("RAQMON-MIB", "raqmonQosRcvdPackets")) if mibBuilder.loadTexts: raqmonSessionAlarm.setStatus('current') if mibBuilder.loadTexts: raqmonSessionAlarm.setDescription('A notification generated by an entry in the raqmonSessionExceptionTable.') raqmonMIBObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 16, 31, 1)) raqmonSession = MibIdentifier((1, 3, 6, 1, 2, 1, 16, 31, 1, 1)) raqmonParticipantTable = MibTable((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1), ) if mibBuilder.loadTexts: raqmonParticipantTable.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantTable.setDescription('This table contains information about participants in both active and closed (terminated) sessions.') raqmonParticipantEntry = MibTableRow((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1), ).setIndexNames((0, "RAQMON-MIB", "raqmonParticipantStartDate"), (0, "RAQMON-MIB", "raqmonParticipantIndex")) if mibBuilder.loadTexts: raqmonParticipantEntry.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantEntry.setDescription('Each row contains information for a single session (application) run by one participant. Indexation by the start time of the session aims to ease sorting by management applications. Agents MUST NOT report identical start times for any two sessions on the same host. Rows are removed for inactive sessions when implementation-specific age or space limits are reached.') raqmonParticipantStartDate = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 1), DateAndTime()) if mibBuilder.loadTexts: raqmonParticipantStartDate.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantStartDate.setDescription('The date and time of this entry. It will be the date and time of the first report received.') raqmonParticipantIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: raqmonParticipantIndex.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantIndex.setDescription('The index of the conceptual row, which is for SNMP purposes only and has no relation to any protocol value. There is no requirement that these rows be created or maintained sequentially. The index will be unique for a particular date and time.') raqmonParticipantReportCaps = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 3), Bits().clone(namedValues=NamedValues(("raqmonPartRepDsrcName", 0), ("raqmonPartRepRecvName", 1), ("raqmonPartRepDsrcPort", 2), ("raqmonPartRepRecvPort", 3), ("raqmonPartRepSetupTime", 4), ("raqmonPartRepSetupDelay", 5), ("raqmonPartRepSessionDuration", 6), ("raqmonPartRepSetupStatus", 7), ("raqmonPartRepRTEnd2EndNetDelay", 8), ("raqmonPartRepOWEnd2EndNetDelay", 9), ("raqmonPartApplicationDelay", 10), ("raqmonPartRepIAJitter", 11), ("raqmonPartRepIPDV", 12), ("raqmonPartRepRcvdPackets", 13), ("raqmonPartRepRcvdOctets", 14), ("raqmonPartRepSentPackets", 15), ("raqmonPartRepSentOctets", 16), ("raqmonPartRepCumPacketsLoss", 17), ("raqmonPartRepFractionPacketsLoss", 18), ("raqmonPartRepCumDiscards", 19), ("raqmonPartRepFractionDiscards", 20), ("raqmonPartRepSrcPayloadType", 21), ("raqmonPartRepDestPayloadType", 22), ("raqmonPartRepSrcLayer2Priority", 23), ("raqmonPartRepSrcTosDscp", 24), ("raqmonPartRepDestLayer2Priority", 25), ("raqmonPartRepDestTosDscp", 26), ("raqmonPartRepCPU", 27), ("raqmonPartRepMemory", 28), ("raqmonPartRepAppName", 29)))).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantReportCaps.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantReportCaps.setDescription('The Report capabilities of the participant, as perceived by the Collector. If the participant can report the Data Source Name as defined in [RFC4710], Section 5.3, then the raqmonPartRepDsrcName bit will be set. If the participant can report the Receiver Name as defined in [RFC4710], Section 5.4, then the raqmonPartRepRecvName bit will be set. If the participant can report the Data Source Port as defined in [RFC4710], Section 5.5, then the raqmonPartRepDsrcPort bit will be set. If the participant can report the Receiver Port as defined in [RFC4710], Section 5.6, then the raqmonPartRepRecvPort bit will be set. If the participant can report the Session Setup Time as defined in [RFC4710], Section 5.7, then the raqmonPartRepSetupTime bit will be set. If the participant can report the Session Setup Delay as defined in [RFC4710], Section 5.8, then the raqmonPartRepSetupDelay bit will be set. If the participant can report the Session Duration as defined in [RFC4710], Section 5.9, then the raqmonPartRepSessionDuration bit will be set. If the participant can report the Setup Status as defined in [RFC4710], Section 5.10, then the raqmonPartRepSetupStatus bit will be set. If the participant can report the Round-Trip End-to-end Network Delay as defined in [RFC4710], Section 5.11, then the raqmonPartRepRTEnd2EndNetDelay bit will be set. If the participant can report the One-way End-to-end Network Delay as defined in [RFC4710], Section 5.12, then the raqmonPartRepOWEnd2EndNetDelay bit will be set. If the participant can report the Application Delay as defined in [RFC4710], Section 5.13, then the raqmonPartApplicationDelay bit will be set. If the participant can report the Inter-Arrival Jitter as defined in [RFC4710], Section 5.14, then the raqmonPartRepIAJitter bit will be set. If the participant can report the IP Packet Delay Variation as defined in [RFC4710], Section 5.15, then the raqmonPartRepIPDV bit will be set. If the participant can report the number of application packets received as defined in [RFC4710], Section 5.16, then the raqmonPartRepRcvdPackets bit will be set. If the participant can report the number of application octets received as defined in [RFC4710], Section 5.17, then the raqmonPartRepRcvdOctets bit will be set. If the participant can report the number of application packets sent as defined in [RFC4710], Section 5.18, then the raqmonPartRepSentPackets bit will be set. If the participant can report the number of application octets sent as defined in [RFC4710], Section 5.19, then the raqmonPartRepSentOctets bit will be set. If the participant can report the number of cumulative packets lost as defined in [RFC4710], Section 5.20, then the raqmonPartRepCumPacketsLoss bit will be set. If the participant can report the fraction of packet loss as defined in [RFC4710], Section 5.21, then the raqmonPartRepFractionPacketsLoss bit will be set. If the participant can report the number of cumulative discards as defined in [RFC4710], Section 5.22, then the raqmonPartRepCumDiscards bit will be set. If the participant can report the fraction of discards as defined in [RFC4710], Section 5.23, then the raqmonPartRepFractionDiscards bit will be set. If the participant can report the Source Payload Type as defined in [RFC4710], Section 5.24, then the raqmonPartRepSrcPayloadType bit will be set. If the participant can report the Destination Payload Type as defined in [RFC4710], Section 5.25, then the raqmonPartRepDestPayloadType bit will be set. If the participant can report the Source Layer 2 Priority as defined in [RFC4710], Section 5.26, then the raqmonPartRepSrcLayer2Priority bit will be set. If the participant can report the Source DSCP/ToS value as defined in [RFC4710], Section 5.27, then the raqmonPartRepSrcToSDscp bit will be set. If the participant can report the Destination Layer 2 Priority as defined in [RFC4710], Section 5.28, then the raqmonPartRepDestLayer2Priority bit will be set. If the participant can report the Destination DSCP/ToS Value as defined in [RFC4710], Section 5.29, then the raqmonPartRepDestToSDscp bit will be set. If the participant can report the CPU utilization as defined in [RFC4710], Section 5.30, then the raqmonPartRepCPU bit will be set. If the participant can report the memory utilization as defined in [RFC4710], Section 5.31, then the raqmonPartRepMemory bit will be set. If the participant can report the Application Name as defined in [RFC4710], Section 5.32, then the raqmonPartRepAppName bit will be set. The capability of reporting of a specific metric does not mandate that the metric must be reported permanently by the data source to the respective collector. Some data sources MAY be configured not to send a metric, or some metrics may not be relevant to the specific application.') raqmonParticipantAddrType = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 4), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantAddrType.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAddrType.setDescription('The type of the Internet address of the participant for this session.') raqmonParticipantAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 5), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantAddr.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAddr.setDescription('The Internet Address of the participant for this session. Formatting of this object is determined by the value of raqmonParticipantAddrType.') raqmonParticipantSendPort = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 6), InetPortNumber()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantSendPort.setReference('Section 5.5 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantSendPort.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantSendPort.setDescription('Port from which session data is sent. If the value was not reported to the collector, this object will have the value 0.') raqmonParticipantRecvPort = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 7), InetPortNumber()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantRecvPort.setReference('Section 5.6 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantRecvPort.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantRecvPort.setDescription('Port on which session data is received. If the value was not reported to the collector, this object will have the value 0.') raqmonParticipantSetupDelay = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantSetupDelay.setReference('Section 5.8 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantSetupDelay.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantSetupDelay.setDescription('Session setup time. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantName = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 9), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantName.setReference('Section 5.3 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantName.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantName.setDescription('The data source name for the participant.') raqmonParticipantAppName = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 10), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantAppName.setReference('Section 5.32 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantAppName.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAppName.setDescription("A string giving the name and possibly the version of the application generating the stream, e.g., 'videotool 1.2.' This information may be useful for debugging purposes and is similar to the Mailer or Mail-System-Version SMTP headers. The tool value is expected to remain constant for the duration of the session.") raqmonParticipantQosCount = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 11), Gauge32()).setUnits('entries').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantQosCount.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantQosCount.setDescription('The current number of entries in the raqmonQosTable for this participant and session.') raqmonParticipantEndDate = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 12), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantEndDate.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantEndDate.setDescription('The date and time of the most recent report received.') raqmonParticipantDestPayloadType = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 127), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantDestPayloadType.setReference('RFC 3551 and Section 5.25 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantDestPayloadType.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantDestPayloadType.setDescription('Destination Payload Type. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantSrcPayloadType = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 127), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantSrcPayloadType.setReference('RFC 3551 and Section 5.24 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantSrcPayloadType.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantSrcPayloadType.setDescription('Source Payload Type. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantActive = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 15), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantActive.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantActive.setDescription("Value 'true' indicates that the session for this participant is active (open). Value 'false' indicates that the session is closed (terminated).") raqmonParticipantPeer = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 16), RowPointer()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantPeer.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantPeer.setDescription('The pointer to the corresponding entry in this table for the other peer participant. If there is no such entry in the participant table of the collector represented by this SNMP agent, then the value will be { 0 0 }. ') raqmonParticipantPeerAddrType = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 17), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantPeerAddrType.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantPeerAddrType.setDescription('The type of the Internet address of the peer participant for this session.') raqmonParticipantPeerAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 18), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantPeerAddr.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantPeerAddr.setDescription('The Internet Address of the peer participant for this session. Formatting of this object is determined by the value of raqmonParticipantPeerAddrType.') raqmonParticipantSrcL2Priority = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 7), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantSrcL2Priority.setReference('Section 5.26 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantSrcL2Priority.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantSrcL2Priority.setDescription('Source Layer 2 Priority. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantDestL2Priority = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 7), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantDestL2Priority.setReference('Section 5.28 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantDestL2Priority.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantDestL2Priority.setDescription('Destination Layer 2 Priority. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantSrcDSCP = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 63), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantSrcDSCP.setReference('Section 5.27 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantSrcDSCP.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantSrcDSCP.setDescription('Source Layer 3 DSCP value. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantDestDSCP = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 63), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantDestDSCP.setReference('Section 5.29 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantDestDSCP.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantDestDSCP.setDescription('Destination Layer 3 DSCP value.') raqmonParticipantCpuMean = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 100), ))).setUnits('percents').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantCpuMean.setReference('Section 5.30 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantCpuMean.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantCpuMean.setDescription('Mean CPU utilization. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantCpuMin = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 100), ))).setUnits('percents').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantCpuMin.setReference('Section 5.30 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantCpuMin.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantCpuMin.setDescription('Minimum CPU utilization. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantCpuMax = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 100), ))).setUnits('percents').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantCpuMax.setReference('Section 5.30 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantCpuMax.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantCpuMax.setDescription('Maximum CPU utilization. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantMemoryMean = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 100), ))).setUnits('percents').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantMemoryMean.setReference('Section 5.31 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantMemoryMean.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantMemoryMean.setDescription('Mean memory utilization. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantMemoryMin = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 100), ))).setUnits('percents').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantMemoryMin.setReference('Section 5.31 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantMemoryMin.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantMemoryMin.setDescription('Minimum memory utilization. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantMemoryMax = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 100), ))).setUnits('percents').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantMemoryMax.setReference('Section 5.31 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantMemoryMax.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantMemoryMax.setDescription('Maximum memory utilization. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantNetRTTMean = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantNetRTTMean.setReference('Section 5.11 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantNetRTTMean.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantNetRTTMean.setDescription('Mean round-trip end-to-end network delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantNetRTTMin = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantNetRTTMin.setReference('Section 5.11 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantNetRTTMin.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantNetRTTMin.setDescription('Minimum round-trip end-to-end network delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantNetRTTMax = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantNetRTTMax.setReference('Section 5.11 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantNetRTTMax.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantNetRTTMax.setDescription('Maximum round-trip end-to-end network delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantIAJitterMean = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantIAJitterMean.setReference('Section 5.14 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantIAJitterMean.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantIAJitterMean.setDescription('Mean inter-arrival jitter over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantIAJitterMin = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantIAJitterMin.setReference('Section 5.14 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantIAJitterMin.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantIAJitterMin.setDescription('Minimum inter-arrival jitter over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantIAJitterMax = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 34), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantIAJitterMax.setReference('Section 5.14 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantIAJitterMax.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantIAJitterMax.setDescription('Maximum inter-arrival jitter over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantIPDVMean = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 35), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantIPDVMean.setReference('Section 5.15 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantIPDVMean.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantIPDVMean.setDescription('Mean IP packet delay variation over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantIPDVMin = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 36), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantIPDVMin.setReference('Section 5.15 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantIPDVMin.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantIPDVMin.setDescription('Minimum IP packet delay variation over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantIPDVMax = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantIPDVMax.setReference('Section 5.15 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantIPDVMax.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantIPDVMax.setDescription('Maximum IP packet delay variation over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantNetOwdMean = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 38), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantNetOwdMean.setReference('Section 5.12 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantNetOwdMean.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantNetOwdMean.setDescription('Mean Network one-way delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantNetOwdMin = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 39), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantNetOwdMin.setReference('Section 5.12 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantNetOwdMin.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantNetOwdMin.setDescription('Minimum Network one-way delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantNetOwdMax = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 40), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantNetOwdMax.setReference('Section 5.1 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantNetOwdMax.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantNetOwdMax.setDescription('Maximum Network one-way delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantAppDelayMean = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 41), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantAppDelayMean.setReference('Section 5.13 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantAppDelayMean.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAppDelayMean.setDescription('Mean application delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantAppDelayMin = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 42), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantAppDelayMin.setReference('Section 5.13 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantAppDelayMin.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAppDelayMin.setDescription('Minimum application delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantAppDelayMax = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 43), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantAppDelayMax.setReference('Section 5.13 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantAppDelayMax.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAppDelayMax.setDescription('Maximum application delay over the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantPacketsRcvd = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 44), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantPacketsRcvd.setReference('Section 5.16 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantPacketsRcvd.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantPacketsRcvd.setDescription('Count of packets received for the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantPacketsSent = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 45), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantPacketsSent.setReference('Section 5.17 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantPacketsSent.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantPacketsSent.setDescription('Count of packets sent for the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantOctetsRcvd = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 46), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantOctetsRcvd.setReference('Section 5.18 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantOctetsRcvd.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantOctetsRcvd.setDescription('Count of octets received for the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantOctetsSent = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 47), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantOctetsSent.setReference('Section 5.19 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantOctetsSent.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantOctetsSent.setDescription('Count of octets sent for the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantLostPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 48), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantLostPackets.setReference('Section 5.20 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantLostPackets.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantLostPackets.setDescription('Count of packets lost by this receiver for the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantLostPacketsFrct = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 49), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 100), ))).setUnits('percents').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantLostPacketsFrct.setReference('Section 5.21 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantLostPacketsFrct.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantLostPacketsFrct.setDescription('Fraction of lost packets out of total packets received. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantDiscards = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantDiscards.setReference('Section 5.22 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantDiscards.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantDiscards.setDescription('Count of packets discarded by this receiver for the entire session. If the value was not reported to the collector, this object will have the value -1.') raqmonParticipantDiscardsFrct = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 1, 1, 51), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 100), ))).setUnits('percents').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantDiscardsFrct.setReference('Section 5.23 of the [RFC4710]') if mibBuilder.loadTexts: raqmonParticipantDiscardsFrct.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantDiscardsFrct.setDescription('Fraction of discarded packets out of total packets received. If the value was not reported to the collector, this object will have the value -1.') raqmonQosTable = MibTable((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2), ) if mibBuilder.loadTexts: raqmonQosTable.setStatus('current') if mibBuilder.loadTexts: raqmonQosTable.setDescription('Table of historical information about quality-of-service data during sessions.') raqmonQosEntry = MibTableRow((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1), ).setIndexNames((0, "RAQMON-MIB", "raqmonParticipantStartDate"), (0, "RAQMON-MIB", "raqmonParticipantIndex"), (0, "RAQMON-MIB", "raqmonQosTime")) if mibBuilder.loadTexts: raqmonQosEntry.setStatus('current') if mibBuilder.loadTexts: raqmonQosEntry.setDescription('Each entry contains information from a single RAQMON packet, related to a single session (application) run by one participant. Indexation by the start time of the session aims to ease sorting by management applications. Agents MUST NOT report identical start times for any two sessions on the same host. Rows are removed for inactive sessions when implementation-specific time or space limits are reached.') raqmonQosTime = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setUnits('seconds') if mibBuilder.loadTexts: raqmonQosTime.setStatus('current') if mibBuilder.loadTexts: raqmonQosTime.setDescription('Time of this entry measured from the start of the corresponding participant session.') raqmonQoSEnd2EndNetDelay = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonQoSEnd2EndNetDelay.setReference('Section 5.11 of the [RFC4710]') if mibBuilder.loadTexts: raqmonQoSEnd2EndNetDelay.setStatus('current') if mibBuilder.loadTexts: raqmonQoSEnd2EndNetDelay.setDescription('The round-trip time. Will contain the previous value if there was no report for this time, or -1 if the value has never been reported.') raqmonQoSInterArrivalJitter = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('milliseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonQoSInterArrivalJitter.setReference('Section 5.14 of the [RFC4710]') if mibBuilder.loadTexts: raqmonQoSInterArrivalJitter.setStatus('current') if mibBuilder.loadTexts: raqmonQoSInterArrivalJitter.setDescription('An estimate of delay variation as observed by this receiver. Will contain the previous value if there was no report for this time, or -1 if the value has never been reported.') raqmonQosRcvdPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonQosRcvdPackets.setReference('Section 5.16 of the [RFC4710]') if mibBuilder.loadTexts: raqmonQosRcvdPackets.setStatus('current') if mibBuilder.loadTexts: raqmonQosRcvdPackets.setDescription('Count of packets received by this receiver since the previous entry. Will contain the previous value if there was no report for this time, or -1 if the value has never been reported.') raqmonQosRcvdOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('octets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonQosRcvdOctets.setReference('Section 5.18 of the [RFC4710]') if mibBuilder.loadTexts: raqmonQosRcvdOctets.setStatus('current') if mibBuilder.loadTexts: raqmonQosRcvdOctets.setDescription('Count of octets received by this receiver since the previous report. Will contain the previous value if there was no report for this time, or -1 if the value has never been reported.') raqmonQosSentPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonQosSentPackets.setReference('Section 5.17 of the [RFC4710]') if mibBuilder.loadTexts: raqmonQosSentPackets.setStatus('current') if mibBuilder.loadTexts: raqmonQosSentPackets.setDescription('Count of packets sent since the previous report. Will contain the previous value if there was no report for this time, or -1 if the value has never been reported.') raqmonQosSentOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('octets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonQosSentOctets.setReference('Section 5.19 of the [RFC4710]') if mibBuilder.loadTexts: raqmonQosSentOctets.setStatus('current') if mibBuilder.loadTexts: raqmonQosSentOctets.setDescription('Count of octets sent since the previous report. Will contain the previous value if there was no report for this time, or -1 if the value has never been reported.') raqmonQosLostPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-1, -1), ValueRangeConstraint(0, 2147483647), ))).setUnits('packets').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonQosLostPackets.setReference('Section 5.20 of the [RFC4710]') if mibBuilder.loadTexts: raqmonQosLostPackets.setStatus('current') if mibBuilder.loadTexts: raqmonQosLostPackets.setDescription('A count of packets lost as observed by this receiver since the previous report. Will contain the previous value if there was no report for this time, or -1 if the value has never been reported.') raqmonQosSessionStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 2, 1, 9), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonQosSessionStatus.setReference('Section 5.10 of the [RFC4710]') if mibBuilder.loadTexts: raqmonQosSessionStatus.setStatus('current') if mibBuilder.loadTexts: raqmonQosSessionStatus.setDescription('The session status. Will contain the previous value if there was no report for this time or the zero-length string if no value was ever reported.') raqmonParticipantAddrTable = MibTable((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 3), ) if mibBuilder.loadTexts: raqmonParticipantAddrTable.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAddrTable.setDescription('Maps raqmonParticipantAddr to the index of the raqmonParticipantTable. This table allows management applications to find entries sorted by raqmonParticipantAddr rather than raqmonParticipantStartDate.') raqmonParticipantAddrEntry = MibTableRow((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 3, 1), ).setIndexNames((0, "RAQMON-MIB", "raqmonParticipantAddrType"), (0, "RAQMON-MIB", "raqmonParticipantAddr"), (0, "RAQMON-MIB", "raqmonParticipantStartDate"), (0, "RAQMON-MIB", "raqmonParticipantIndex")) if mibBuilder.loadTexts: raqmonParticipantAddrEntry.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAddrEntry.setDescription('Each entry corresponds to exactly one entry in the raqmonParticipantEntry: the entry containing the index pair raqmonParticipantStartDate, raqmonParticipantIndex. Note that there is no concern about the indexation of this table exceeding the limits defined by RFC 2578, Section 3.5. According to [RFC4710], Section 5.1, only IPv4 and IPv6 addresses can be reported as participant addresses.') raqmonParticipantAddrEndDate = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 1, 3, 1, 1), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonParticipantAddrEndDate.setStatus('current') if mibBuilder.loadTexts: raqmonParticipantAddrEndDate.setDescription('The value of raqmonParticipantEndDate for the corresponding raqmonParticipantEntry.') raqmonException = MibIdentifier((1, 3, 6, 1, 2, 1, 16, 31, 1, 2)) raqmonSessionExceptionTable = MibTable((1, 3, 6, 1, 2, 1, 16, 31, 1, 2, 2), ) if mibBuilder.loadTexts: raqmonSessionExceptionTable.setStatus('current') if mibBuilder.loadTexts: raqmonSessionExceptionTable.setDescription('This table defines thresholds for the management station to get notifications about sessions that encountered poor quality of service. The information in this table MUST be persistent across agent reboots.') raqmonSessionExceptionEntry = MibTableRow((1, 3, 6, 1, 2, 1, 16, 31, 1, 2, 2, 1), ).setIndexNames((0, "RAQMON-MIB", "raqmonSessionExceptionIndex")) if mibBuilder.loadTexts: raqmonSessionExceptionEntry.setStatus('current') if mibBuilder.loadTexts: raqmonSessionExceptionEntry.setDescription('A conceptual row in the raqmonSessionExceptionTable.') raqmonSessionExceptionIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 2, 2, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))) if mibBuilder.loadTexts: raqmonSessionExceptionIndex.setStatus('current') if mibBuilder.loadTexts: raqmonSessionExceptionIndex.setDescription('An index that uniquely identifies an entry in the raqmonSessionExceptionTable. Management applications can determine unused indices by performing GetNext or GetBulk operations on the Table.') raqmonSessionExceptionIAJitterThreshold = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 2, 2, 1, 3), Unsigned32()).setUnits('milliseconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: raqmonSessionExceptionIAJitterThreshold.setStatus('current') if mibBuilder.loadTexts: raqmonSessionExceptionIAJitterThreshold.setDescription('Threshold for jitter. The value during a session must be greater than or equal to this value for an exception to be created.') raqmonSessionExceptionNetRTTThreshold = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 2, 2, 1, 4), Unsigned32()).setUnits('milliseconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: raqmonSessionExceptionNetRTTThreshold.setStatus('current') if mibBuilder.loadTexts: raqmonSessionExceptionNetRTTThreshold.setDescription('Threshold for round-trip time. The value during a session must be greater than or equal to this value for an exception to be created.') raqmonSessionExceptionLostPacketsThreshold = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 2, 2, 1, 5), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 1000))).setUnits('tenth of a percent').setMaxAccess("readcreate") if mibBuilder.loadTexts: raqmonSessionExceptionLostPacketsThreshold.setStatus('current') if mibBuilder.loadTexts: raqmonSessionExceptionLostPacketsThreshold.setDescription('Threshold for lost packets in units of tenths of a percent. The value during a session must be greater than or equal to this value for an exception to be created.') raqmonSessionExceptionRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 16, 31, 1, 2, 2, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: raqmonSessionExceptionRowStatus.setStatus('current') if mibBuilder.loadTexts: raqmonSessionExceptionRowStatus.setDescription("This object has a value of 'active' when exceptions are being monitored by the system. A newly-created conceptual row must have all the read-create objects initialized before becoming 'active'. A conceptual row that is in the 'notReady' or 'notInService' state MAY be removed after 5 minutes. No writeable objects can be changed while the row is active.") raqmonConfig = MibIdentifier((1, 3, 6, 1, 2, 1, 16, 31, 1, 3)) raqmonConfigPort = MibScalar((1, 3, 6, 1, 2, 1, 16, 31, 1, 3, 1), InetPortNumber()).setMaxAccess("readwrite") if mibBuilder.loadTexts: raqmonConfigPort.setStatus('current') if mibBuilder.loadTexts: raqmonConfigPort.setDescription('The UDP port to listen on for RAQMON reports, running on transport protocols other than SNMP. If the RAQMON PDU transport protocol is SNMP, a write operation on this object has no effect, as the standard port 162 is always used. The value of this object MUST be persistent across agent reboots.') raqmonConfigPduTransport = MibScalar((1, 3, 6, 1, 2, 1, 16, 31, 1, 3, 2), Bits().clone(namedValues=NamedValues(("other", 0), ("tcp", 1), ("snmp", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonConfigPduTransport.setStatus('current') if mibBuilder.loadTexts: raqmonConfigPduTransport.setDescription('The PDU transport(s) used by this collector. If other(0) is set, the collector supports a transport other than SNMP or TCP. If tcp(1) is set, the collector supports TCP as a transport protocol. If snmp(2) is set, the collector supports SNMP as a transport protocol.') raqmonConfigRaqmonPdus = MibScalar((1, 3, 6, 1, 2, 1, 16, 31, 1, 3, 3), Counter32()).setUnits('PDUs').setMaxAccess("readonly") if mibBuilder.loadTexts: raqmonConfigRaqmonPdus.setStatus('current') if mibBuilder.loadTexts: raqmonConfigRaqmonPdus.setDescription('Count of RAQMON PDUs received by the Collector.') raqmonConfigRDSTimeout = MibScalar((1, 3, 6, 1, 2, 1, 16, 31, 1, 3, 4), Unsigned32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: raqmonConfigRDSTimeout.setStatus('current') if mibBuilder.loadTexts: raqmonConfigRDSTimeout.setDescription('The number of seconds since the reception of the last RAQMON PDU from a RDS after which a session between the respective RDS and the collector will be considered terminated. The value of this object MUST be persistent across agent reboots.') raqmonConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 16, 31, 2)) raqmonCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 16, 31, 2, 1)) raqmonGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 16, 31, 2, 2)) raqmonCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 16, 31, 2, 1, 1)).setObjects(("RAQMON-MIB", "raqmonCollectorGroup"), ("RAQMON-MIB", "raqmonCollectorNotificationsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): raqmonCompliance = raqmonCompliance.setStatus('current') if mibBuilder.loadTexts: raqmonCompliance.setDescription('Describes the requirements for conformance to the RAQMON MIB.') raqmonCollectorGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 16, 31, 2, 2, 1)).setObjects(("RAQMON-MIB", "raqmonParticipantReportCaps"), ("RAQMON-MIB", "raqmonParticipantAddrType"), ("RAQMON-MIB", "raqmonParticipantAddr"), ("RAQMON-MIB", "raqmonParticipantSendPort"), ("RAQMON-MIB", "raqmonParticipantRecvPort"), ("RAQMON-MIB", "raqmonParticipantSetupDelay"), ("RAQMON-MIB", "raqmonParticipantName"), ("RAQMON-MIB", "raqmonParticipantAppName"), ("RAQMON-MIB", "raqmonParticipantQosCount"), ("RAQMON-MIB", "raqmonParticipantEndDate"), ("RAQMON-MIB", "raqmonParticipantDestPayloadType"), ("RAQMON-MIB", "raqmonParticipantSrcPayloadType"), ("RAQMON-MIB", "raqmonParticipantActive"), ("RAQMON-MIB", "raqmonParticipantPeer"), ("RAQMON-MIB", "raqmonParticipantPeerAddrType"), ("RAQMON-MIB", "raqmonParticipantPeerAddr"), ("RAQMON-MIB", "raqmonParticipantSrcL2Priority"), ("RAQMON-MIB", "raqmonParticipantDestL2Priority"), ("RAQMON-MIB", "raqmonParticipantSrcDSCP"), ("RAQMON-MIB", "raqmonParticipantDestDSCP"), ("RAQMON-MIB", "raqmonParticipantCpuMean"), ("RAQMON-MIB", "raqmonParticipantCpuMin"), ("RAQMON-MIB", "raqmonParticipantCpuMax"), ("RAQMON-MIB", "raqmonParticipantMemoryMean"), ("RAQMON-MIB", "raqmonParticipantMemoryMin"), ("RAQMON-MIB", "raqmonParticipantMemoryMax"), ("RAQMON-MIB", "raqmonParticipantNetRTTMean"), ("RAQMON-MIB", "raqmonParticipantNetRTTMin"), ("RAQMON-MIB", "raqmonParticipantNetRTTMax"), ("RAQMON-MIB", "raqmonParticipantIAJitterMean"), ("RAQMON-MIB", "raqmonParticipantIAJitterMin"), ("RAQMON-MIB", "raqmonParticipantIAJitterMax"), ("RAQMON-MIB", "raqmonParticipantIPDVMean"), ("RAQMON-MIB", "raqmonParticipantIPDVMin"), ("RAQMON-MIB", "raqmonParticipantIPDVMax"), ("RAQMON-MIB", "raqmonParticipantNetOwdMean"), ("RAQMON-MIB", "raqmonParticipantNetOwdMin"), ("RAQMON-MIB", "raqmonParticipantNetOwdMax"), ("RAQMON-MIB", "raqmonParticipantAppDelayMean"), ("RAQMON-MIB", "raqmonParticipantAppDelayMin"), ("RAQMON-MIB", "raqmonParticipantAppDelayMax"), ("RAQMON-MIB", "raqmonParticipantPacketsRcvd"), ("RAQMON-MIB", "raqmonParticipantPacketsSent"), ("RAQMON-MIB", "raqmonParticipantOctetsRcvd"), ("RAQMON-MIB", "raqmonParticipantOctetsSent"), ("RAQMON-MIB", "raqmonParticipantLostPackets"), ("RAQMON-MIB", "raqmonParticipantLostPacketsFrct"), ("RAQMON-MIB", "raqmonParticipantDiscards"), ("RAQMON-MIB", "raqmonParticipantDiscardsFrct"), ("RAQMON-MIB", "raqmonQoSEnd2EndNetDelay"), ("RAQMON-MIB", "raqmonQoSInterArrivalJitter"), ("RAQMON-MIB", "raqmonQosRcvdPackets"), ("RAQMON-MIB", "raqmonQosRcvdOctets"), ("RAQMON-MIB", "raqmonQosSentPackets"), ("RAQMON-MIB", "raqmonQosSentOctets"), ("RAQMON-MIB", "raqmonQosLostPackets"), ("RAQMON-MIB", "raqmonQosSessionStatus"), ("RAQMON-MIB", "raqmonParticipantAddrEndDate"), ("RAQMON-MIB", "raqmonConfigPort"), ("RAQMON-MIB", "raqmonSessionExceptionIAJitterThreshold"), ("RAQMON-MIB", "raqmonSessionExceptionNetRTTThreshold"), ("RAQMON-MIB", "raqmonSessionExceptionLostPacketsThreshold"), ("RAQMON-MIB", "raqmonSessionExceptionRowStatus"), ("RAQMON-MIB", "raqmonConfigPduTransport"), ("RAQMON-MIB", "raqmonConfigRaqmonPdus"), ("RAQMON-MIB", "raqmonConfigRDSTimeout")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): raqmonCollectorGroup = raqmonCollectorGroup.setStatus('current') if mibBuilder.loadTexts: raqmonCollectorGroup.setDescription('Objects used in RAQMON by a collector.') raqmonCollectorNotificationsGroup = NotificationGroup((1, 3, 6, 1, 2, 1, 16, 31, 2, 2, 2)).setObjects(("RAQMON-MIB", "raqmonSessionAlarm")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): raqmonCollectorNotificationsGroup = raqmonCollectorNotificationsGroup.setStatus('current') if mibBuilder.loadTexts: raqmonCollectorNotificationsGroup.setDescription('Notifications emitted by a RAQMON collector.') mibBuilder.exportSymbols("RAQMON-MIB", raqmonParticipantPacketsRcvd=raqmonParticipantPacketsRcvd, raqmonCompliance=raqmonCompliance, raqmonParticipantSetupDelay=raqmonParticipantSetupDelay, raqmonParticipantPacketsSent=raqmonParticipantPacketsSent, raqmonSessionExceptionTable=raqmonSessionExceptionTable, raqmonParticipantDestPayloadType=raqmonParticipantDestPayloadType, raqmonMIBObjects=raqmonMIBObjects, raqmonParticipantReportCaps=raqmonParticipantReportCaps, raqmonQoSEnd2EndNetDelay=raqmonQoSEnd2EndNetDelay, raqmonParticipantPeer=raqmonParticipantPeer, raqmonConformance=raqmonConformance, raqmonParticipantAppDelayMean=raqmonParticipantAppDelayMean, raqmonParticipantCpuMax=raqmonParticipantCpuMax, raqmonParticipantNetRTTMax=raqmonParticipantNetRTTMax, raqmonSessionExceptionIAJitterThreshold=raqmonSessionExceptionIAJitterThreshold, raqmonQosRcvdOctets=raqmonQosRcvdOctets, raqmonParticipantSrcL2Priority=raqmonParticipantSrcL2Priority, raqmonParticipantEndDate=raqmonParticipantEndDate, raqmonQosSentPackets=raqmonQosSentPackets, raqmonParticipantDestDSCP=raqmonParticipantDestDSCP, raqmonSessionExceptionRowStatus=raqmonSessionExceptionRowStatus, raqmonParticipantAppName=raqmonParticipantAppName, raqmonParticipantIAJitterMax=raqmonParticipantIAJitterMax, raqmonQosEntry=raqmonQosEntry, raqmonConfigRDSTimeout=raqmonConfigRDSTimeout, raqmonParticipantActive=raqmonParticipantActive, raqmonParticipantPeerAddrType=raqmonParticipantPeerAddrType, raqmonCompliances=raqmonCompliances, raqmonSessionExceptionEntry=raqmonSessionExceptionEntry, raqmonQosRcvdPackets=raqmonQosRcvdPackets, raqmonParticipantLostPacketsFrct=raqmonParticipantLostPacketsFrct, raqmonQosSessionStatus=raqmonQosSessionStatus, raqmonParticipantOctetsRcvd=raqmonParticipantOctetsRcvd, raqmonCollectorGroup=raqmonCollectorGroup, PYSNMP_MODULE_ID=raqmonMIB, raqmonParticipantIPDVMax=raqmonParticipantIPDVMax, raqmonParticipantTable=raqmonParticipantTable, raqmonParticipantDestL2Priority=raqmonParticipantDestL2Priority, raqmonCollectorNotificationsGroup=raqmonCollectorNotificationsGroup, raqmonParticipantMemoryMin=raqmonParticipantMemoryMin, raqmonParticipantLostPackets=raqmonParticipantLostPackets, raqmonParticipantDiscardsFrct=raqmonParticipantDiscardsFrct, raqmonParticipantAddrEndDate=raqmonParticipantAddrEndDate, raqmonParticipantSrcPayloadType=raqmonParticipantSrcPayloadType, raqmonSession=raqmonSession, raqmonQosLostPackets=raqmonQosLostPackets, raqmonParticipantNetOwdMin=raqmonParticipantNetOwdMin, raqmonQosTable=raqmonQosTable, raqmonParticipantIPDVMin=raqmonParticipantIPDVMin, raqmonParticipantCpuMin=raqmonParticipantCpuMin, raqmonParticipantNetRTTMin=raqmonParticipantNetRTTMin, raqmonParticipantQosCount=raqmonParticipantQosCount, raqmonConfigPduTransport=raqmonConfigPduTransport, raqmonParticipantSendPort=raqmonParticipantSendPort, raqmonParticipantAppDelayMin=raqmonParticipantAppDelayMin, raqmonConfig=raqmonConfig, raqmonGroups=raqmonGroups, raqmonSessionExceptionIndex=raqmonSessionExceptionIndex, raqmonConfigRaqmonPdus=raqmonConfigRaqmonPdus, raqmonConfigPort=raqmonConfigPort, raqmonParticipantSrcDSCP=raqmonParticipantSrcDSCP, raqmonMIB=raqmonMIB, raqmonQosTime=raqmonQosTime, raqmonParticipantIndex=raqmonParticipantIndex, raqmonParticipantRecvPort=raqmonParticipantRecvPort, raqmonSessionAlarm=raqmonSessionAlarm, raqmonParticipantStartDate=raqmonParticipantStartDate, raqmonSessionExceptionLostPacketsThreshold=raqmonSessionExceptionLostPacketsThreshold, raqmonParticipantAppDelayMax=raqmonParticipantAppDelayMax, raqmonParticipantDiscards=raqmonParticipantDiscards, raqmonParticipantAddrType=raqmonParticipantAddrType, raqmonParticipantCpuMean=raqmonParticipantCpuMean, raqmonParticipantIAJitterMin=raqmonParticipantIAJitterMin, raqmonParticipantOctetsSent=raqmonParticipantOctetsSent, raqmonNotifications=raqmonNotifications, raqmonParticipantNetRTTMean=raqmonParticipantNetRTTMean, raqmonParticipantMemoryMax=raqmonParticipantMemoryMax, raqmonParticipantAddr=raqmonParticipantAddr, raqmonQosSentOctets=raqmonQosSentOctets, raqmonParticipantMemoryMean=raqmonParticipantMemoryMean, raqmonParticipantPeerAddr=raqmonParticipantPeerAddr, raqmonParticipantName=raqmonParticipantName, raqmonSessionExceptionNetRTTThreshold=raqmonSessionExceptionNetRTTThreshold, raqmonParticipantAddrEntry=raqmonParticipantAddrEntry, raqmonParticipantIAJitterMean=raqmonParticipantIAJitterMean, raqmonParticipantEntry=raqmonParticipantEntry, raqmonParticipantAddrTable=raqmonParticipantAddrTable, raqmonQoSInterArrivalJitter=raqmonQoSInterArrivalJitter, raqmonParticipantIPDVMean=raqmonParticipantIPDVMean, raqmonParticipantNetOwdMean=raqmonParticipantNetOwdMean, raqmonParticipantNetOwdMax=raqmonParticipantNetOwdMax, raqmonException=raqmonException)
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Coupon_validity, obj[4]: Gender, obj[5]: Age, obj[6]: Children, obj[7]: Education, obj[8]: Occupation, obj[9]: Income, obj[10]: Bar, obj[11]: Coffeehouse, obj[12]: Restaurant20to50, obj[13]: Direction_same, obj[14]: Distance # {"feature": "Passanger", "instances": 127, "metric_value": 0.9978, "depth": 1} if obj[0]<=1: # {"feature": "Bar", "instances": 75, "metric_value": 0.971, "depth": 2} if obj[10]<=1.0: # {"feature": "Coupon", "instances": 45, "metric_value": 0.8673, "depth": 3} if obj[2]>0: # {"feature": "Occupation", "instances": 36, "metric_value": 0.9436, "depth": 4} if obj[8]<=14: # {"feature": "Coffeehouse", "instances": 31, "metric_value": 0.9812, "depth": 5} if obj[11]<=2.0: # {"feature": "Education", "instances": 27, "metric_value": 0.999, "depth": 6} if obj[7]>0: # {"feature": "Time", "instances": 17, "metric_value": 0.9367, "depth": 7} if obj[1]>0: # {"feature": "Age", "instances": 12, "metric_value": 1.0, "depth": 8} if obj[5]<=4: # {"feature": "Restaurant20to50", "instances": 10, "metric_value": 0.971, "depth": 9} if obj[12]>0.0: # {"feature": "Income", "instances": 8, "metric_value": 1.0, "depth": 10} if obj[9]>0: # {"feature": "Direction_same", "instances": 7, "metric_value": 0.9852, "depth": 11} if obj[13]<=0: # {"feature": "Coupon_validity", "instances": 6, "metric_value": 1.0, "depth": 12} if obj[3]<=0: # {"feature": "Distance", "instances": 5, "metric_value": 0.971, "depth": 13} if obj[14]>1: # {"feature": "Gender", "instances": 4, "metric_value": 1.0, "depth": 14} if obj[4]>0: # {"feature": "Children", "instances": 3, "metric_value": 0.9183, "depth": 15} if obj[6]<=0: return 'True' elif obj[6]>0: return 'False' else: return 'False' elif obj[4]<=0: return 'True' else: return 'True' elif obj[14]<=1: return 'False' else: return 'False' elif obj[3]>0: return 'True' else: return 'True' elif obj[13]>0: return 'False' else: return 'False' elif obj[9]<=0: return 'True' else: return 'True' elif obj[12]<=0.0: return 'False' else: return 'False' elif obj[5]>4: return 'True' else: return 'True' elif obj[1]<=0: return 'False' else: return 'False' elif obj[7]<=0: # {"feature": "Coupon_validity", "instances": 10, "metric_value": 0.8813, "depth": 7} if obj[3]>0: # {"feature": "Distance", "instances": 6, "metric_value": 1.0, "depth": 8} if obj[14]<=1: return 'True' elif obj[14]>1: return 'False' else: return 'False' elif obj[3]<=0: return 'True' else: return 'True' else: return 'True' elif obj[11]>2.0: return 'False' else: return 'False' elif obj[8]>14: return 'False' else: return 'False' elif obj[2]<=0: return 'False' else: return 'False' elif obj[10]>1.0: # {"feature": "Age", "instances": 30, "metric_value": 0.9871, "depth": 3} if obj[5]>0: # {"feature": "Income", "instances": 27, "metric_value": 0.951, "depth": 4} if obj[9]<=4: # {"feature": "Occupation", "instances": 21, "metric_value": 0.9984, "depth": 5} if obj[8]>1: # {"feature": "Restaurant20to50", "instances": 18, "metric_value": 0.9911, "depth": 6} if obj[12]>0.0: # {"feature": "Distance", "instances": 16, "metric_value": 1.0, "depth": 7} if obj[14]<=2: # {"feature": "Time", "instances": 14, "metric_value": 0.9852, "depth": 8} if obj[1]>0: # {"feature": "Education", "instances": 10, "metric_value": 0.8813, "depth": 9} if obj[7]<=3: # {"feature": "Children", "instances": 9, "metric_value": 0.7642, "depth": 10} if obj[6]<=0: # {"feature": "Gender", "instances": 7, "metric_value": 0.8631, "depth": 11} if obj[4]<=0: # {"feature": "Coupon_validity", "instances": 6, "metric_value": 0.65, "depth": 12} if obj[3]<=0: return 'True' elif obj[3]>0: # {"feature": "Coffeehouse", "instances": 2, "metric_value": 1.0, "depth": 13} if obj[11]>2.0: return 'False' elif obj[11]<=2.0: return 'True' else: return 'True' else: return 'False' elif obj[4]>0: return 'False' else: return 'False' elif obj[6]>0: return 'True' else: return 'True' elif obj[7]>3: return 'False' else: return 'False' elif obj[1]<=0: # {"feature": "Coupon", "instances": 4, "metric_value": 0.8113, "depth": 9} if obj[2]>3: return 'False' elif obj[2]<=3: return 'True' else: return 'True' else: return 'False' elif obj[14]>2: return 'False' else: return 'False' elif obj[12]<=0.0: return 'False' else: return 'False' elif obj[8]<=1: return 'True' else: return 'True' elif obj[9]>4: return 'True' else: return 'True' elif obj[5]<=0: return 'False' else: return 'False' else: return 'True' elif obj[0]>1: # {"feature": "Coupon", "instances": 52, "metric_value": 0.8667, "depth": 2} if obj[2]>1: # {"feature": "Coupon_validity", "instances": 38, "metric_value": 0.6892, "depth": 3} if obj[3]<=0: # {"feature": "Income", "instances": 20, "metric_value": 0.2864, "depth": 4} if obj[9]>1: return 'True' elif obj[9]<=1: # {"feature": "Age", "instances": 4, "metric_value": 0.8113, "depth": 5} if obj[5]<=3: return 'True' elif obj[5]>3: return 'False' else: return 'False' else: return 'True' elif obj[3]>0: # {"feature": "Age", "instances": 18, "metric_value": 0.9183, "depth": 4} if obj[5]<=4: # {"feature": "Occupation", "instances": 12, "metric_value": 1.0, "depth": 5} if obj[8]<=7: # {"feature": "Income", "instances": 7, "metric_value": 0.8631, "depth": 6} if obj[9]<=5: # {"feature": "Coffeehouse", "instances": 6, "metric_value": 0.65, "depth": 7} if obj[11]<=2.0: return 'False' elif obj[11]>2.0: # {"feature": "Time", "instances": 2, "metric_value": 1.0, "depth": 8} if obj[1]>2: return 'False' elif obj[1]<=2: return 'True' else: return 'True' else: return 'False' elif obj[9]>5: return 'True' else: return 'True' elif obj[8]>7: # {"feature": "Coffeehouse", "instances": 5, "metric_value": 0.7219, "depth": 6} if obj[11]>0.0: return 'True' elif obj[11]<=0.0: return 'False' else: return 'False' else: return 'True' elif obj[5]>4: return 'True' else: return 'True' else: return 'True' elif obj[2]<=1: # {"feature": "Bar", "instances": 14, "metric_value": 0.9852, "depth": 3} if obj[10]>0.0: # {"feature": "Age", "instances": 9, "metric_value": 0.9183, "depth": 4} if obj[5]>3: return 'True' elif obj[5]<=3: # {"feature": "Income", "instances": 4, "metric_value": 0.8113, "depth": 5} if obj[9]>2: return 'False' elif obj[9]<=2: return 'True' else: return 'True' else: return 'False' elif obj[10]<=0.0: return 'False' else: return 'False' else: return 'False' else: return 'True'
def fib(x): if x < 2: return x return fib(x - 1) + fib(x-2) if __name__ == "__main__": N = int(input()) while N > 0: x = int(input()) print(fib(x)) N = N - 1
T = int(input()) for _ in range(T): for i in range(1, 1001): print(i**2) a = int(input()) if a==0: continue else: break
"""Tiered Lists - a simple way to group items into tiers (at insertion time) while maintaining uniqueness.""" class TieredLists(object): def __init__(self, tiers): self.tiers = sorted(tiers, reverse=True) self.bags = {} for t in self.tiers: self.bags[t] = set() def get_tier(self, key): """Determine in which tier a key should be inserted. Returns ------- int if the value is greater than at least one of the tiers None if the value is less than the least tier.""" tier = None for t in self.tiers: if key >= t: tier = t break return tier def add(self, key, value): """Adds a value to a tier based upon where key fits in the tiers Parameters ---------- key : int used to select the tier into which this value will be inserted value : basestring to be inserted in the set for the tier. Returns ------- int int identifying into which tier the item was inserted. None if the key was too low for the lowest tier.""" tier = self.get_tier(key) if tier is not None: self.bags[tier].add(value) return tier def bag(self, tier): return self.bags[tier] def __str__(self): msg = "{{ tiers: {}, bags: {{".format(self.tiers) for t, vals in sorted(self.bags.items(), reverse=True): msg += "\n{}: {}, {}".format(t, len(vals), vals) msg += "} }" return msg
class BaseException(object): ''' The base exception class (equivalent to System.Exception) ''' def __init__(self): self.message = None
"""Module responsible for client implementation """ class ScrollClient: """ ScrollClient ------------ Class responsible for client implementation """ def __init__(self): self._comm_channel = None @property def comm_channel(self): return self._comm_channel @comm_channel.setter def comm_channel(self, channel_obj): self._comm_channel = channel_obj def show_commands_output(self, cmd_output): cmd_output = cmd_output.decode("utf8") print(cmd_output) def command_loop(self): command_input = "" while command_input != "quit": command_input = input(">> ") command_to_send = self.parse_command_input(command_input) cmd_output = self._comm_channel.send_command(command_to_send) self.show_commands_output(cmd_output)
class Name(object): def __init__(self, normal: str, folded: str): self.normal = normal self.folded = folded
#series็ณปๅˆ—ใฎๆˆ็ธพไธŠไฝxๅ˜ไฝๅˆ†ใฎ้‡็އใ‚’wใซๅค‰ๆ›ดใ™ใ‚‹ใจใ„ใ†ใ“ใจ def top_grades_series(s_dict, series, credits, w): s_dict_name_series = {} #seriesใงๆŒ‡ๅฎšใ•ใ‚ŒใŸ็ณปๅˆ—ใ‚’s_dictๅ†…ใ‹ใ‚‰ๆŠฝๅ‡บใ—ใŸใ‚‚ใฎ array = [] for s in series: #่พžๆ›ธ่ฆ็ด ใซใ€ๆ—ขใซใ‚ใ‚‹point, credit, weightใซๅŠ ใˆใฆใ€seriesใ‚’่ฟฝๅŠ  for name in s_dict[s].keys(): s_dict_name_series[name] = s array += list(s_dict[s].items()) array = sorted(array, key=lambda x:x[1]["point"], reverse=True) for i in range(len(array)): if credits <= 0: break else: #ใใฎ็ง‘็›ฎใฎๅๅ‰ name = array[i][0] #ใใฎ็ง‘็›ฎใฎ็ณปๅˆ— s = s_dict_name_series[name] credit = array[i][1]["credit"] if credit <= credits: modified_weight = w else: modified_weight = float( (credits*w + (credit-credits)*w*0.1) / credit ) s_dict[s][name]["weight"] = modified_weight #print(name, credit, credits, modified_weight) credits -= credit return s_dict #namesๅ†…ใฎๆˆ็ธพไธŠไฝxๅ˜ไฝๅˆ†ใฎ้‡็އใ‚’wใซๅค‰ๆ›ดใ™ใ‚‹ใจใ„ใ†ใ“ใจ def top_grades_name(s_dict, names, credits, w): s_dict_name_series = {} #seriesใงๆŒ‡ๅฎšใ•ใ‚ŒใŸ็ณปๅˆ—ใ‚’s_dictๅ†…ใ‹ใ‚‰ๆŠฝๅ‡บใ—ใŸใ‚‚ใฎ array = [] for s in s_dict.keys(): #่พžๆ›ธ่ฆ็ด ใซใ€ๆ—ขใซใ‚ใ‚‹point, credit, weightใซๅŠ ใˆใฆใ€seriesใ‚’่ฟฝๅŠ  for name in s_dict[s].keys(): for n in names: if name in n: s_dict_name_series[name] = s array += list({name: s_dict[s][name]}.items()) array = sorted(array, key=lambda x:x[1]["point"], reverse=True) for i in range(len(array)): if credits <= 0: break else: #ใใฎ็ง‘็›ฎใฎๅๅ‰ name = array[i][0] #ใใฎ็ง‘็›ฎใฎ็ณปๅˆ— s = s_dict_name_series[name] credit = array[i][1]["credit"] if credit <= credits: modified_weight = w else: modified_weight = float( (credits*w + (credit-credits)*w*0.1) / credit ) s_dict[s][name]["weight"] = modified_weight #print(name, credit, credits, modified_weight) credits -= credit return s_dict
a = b'hello' b = 'ๅ“ˆๅ“ˆ'.encode() print(a,b) print(type(a),type(b)) c = b'haha' d = 'ไฝ ๅฅฝ'.encode() print(c) print(type(c))
#!/usr/bin/env python # -*- coding: utf-8 -*- """ author: meng.xiang date: 2019-05-08 description: """ class CAP_STYLE(object): round = 1 flat = 2 square = 3 class JOIN_STYLE(object): round = 1 mitre = 2 bevel = 3
n = int(input()) x = list(map(int, input().split())) m = 0 e = 0 c = 0 for n in x: m += abs(n) e += n ** 2 c = max(c, abs(n)) print(m) print(e ** 0.5) print(c)
""" @Author : sean cheng @Email : [email protected] @CreateTime : 2018/9/10 @Program : ๅ…จๅฑ€ๅ˜้‡็š„ไฟๅญ˜ """ class SettingVar: def __init__(self): # ้ขœ่‰ฒ่ฏๅ…ธ self.COLOR_DICT = {'white': (255, 255, 255), # ็™ฝ่‰ฒ 'ivory': (255, 255, 240), # ่ฑก็‰™่‰ฒ 'yellow': (255, 255, 0), # ้ป„่‰ฒ 'seashell': (255, 245, 238), # ๆตท่ด่‰ฒ 'bisque': (255, 228, 196), # ๆฉ˜้ป„่‰ฒ 'gold': (255, 215, 0), # ้‡‘่‰ฒ 'pink': (255, 192, 203), # ็ฒ‰็บข่‰ฒ 'lightpink': (255, 182, 193), # ไบฎ็ฒ‰็บข่‰ฒ 'orange': (255, 165, 0), # ๆฉ™่‰ฒ 'coral': (255, 127, 80), # ็Š็‘š่‰ฒ 'tomato': (255, 99, 71), # ็•ช่Œ„่‰ฒ 'magenta': (255, 0, 255), # ๆด‹็บข่‰ฒ 'wheat': (245, 222, 179), # ๅฐ้บฆ่‰ฒ 'violet': (238, 130, 238), # ็ดซ็ฝ—ๅ…ฐ่‰ฒ 'silver': (192, 192, 192), # ้“ถ็™ฝ่‰ฒ 'brown': (165, 42, 42), # ๆฃ•่‰ฒ 'gray': (128, 128, 128), # ็ฐ่‰ฒ 'olive': (128, 128, 0), # ๆฉ„ๆฆ„่‰ฒ 'purple': (128, 0, 128), # ็ดซ่‰ฒ 'turquoise': (64, 224, 208), # ็ปฟๅฎ็Ÿณ่‰ฒ 'seagreen': (46, 139, 87), # ๆตทๆด‹็ปฟ่‰ฒ 'cyan': (0, 255, 255), # ้’่‰ฒ 'green': (0, 128, 0), # ็บฏ็ปฟ่‰ฒ 'blue': (0, 0, 255), # ็บฏ่“่‰ฒ 'darkblue': (0, 0, 139), # ๆทฑ่“่‰ฒ 'navy': (0, 0, 128), # ๆตทๅ†›่“่‰ฒ 'black': (0, 0, 0), # ็บฏ้ป‘่‰ฒ } # ๅ…ƒ็ด ็š„ๆ•ฐๅญ—้ขœ่‰ฒ self.NUM_COLOR_DICT = {'2': self.COLOR_DICT['gray'], '4': self.COLOR_DICT['brown'], '8': self.COLOR_DICT['violet'], '16': self.COLOR_DICT['wheat'], '32': self.COLOR_DICT['coral'], '64': self.COLOR_DICT['turquoise'], '128': self.COLOR_DICT['navy'], '256': self.COLOR_DICT['olive'], '512': self.COLOR_DICT['orange'], '1024': self.COLOR_DICT['seagreen'], '2048': self.COLOR_DICT['purple']} self.TILE_SIZE = 80 self.WINDOW_BLOCK_NUM = 4
'''https://www.geeksforgeeks.org/minimum-edges-reverse-make-path-source-destination/ Given a directed graph and a source node and destination node, we need to find how many edges we need to reverse in order to make at least 1 path from source node to destination node. Examples: In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students. In above graph there were two paths from node 0 to node 6, 0 -> 1 -> 2 -> 3 -> 6 0 -> 1 -> 5 -> 4 -> 6 But for first path only two edges need to be reversed, so answer will be 2 only. This problem can be solved assuming a different version of the given graph. In this version we make a reverse edge corresponding to every edge and we assign that a weight 1 and assign a weight 0 to original edge. After this modification above graph looks something like below, Now we can see that we have modified the graph in such a way that, if we move towards original edge, no cost is incurred, but if we move toward reverse edge 1 cost is added. So if we apply Dijkstraโ€™s shortest path on this modified graph from given source, then that will give us minimum cost to reach from source to destination i.e. minimum edge reversal from source to destination. Below is the code based on above concept. ''' # Python3 Program to find minimum edge reversal to get # atleast one path from source to destination # method adds a directed edge from u to v with weight w def addEdge(u, v, w): global adj adj[u].append((v, w)) # Prints shortest paths from src to all other vertices def shortestPath(src): # Create a set to store vertices that are being # prerocessed setds = {} # Create a vector for distances and initialize all # distances as infinite (INF) dist = [10**18 for i in range(V)] # Insert source itself in Set and initialize its global adj setds[(0, src)] = 1 dist[src] = 0 # /* Looping till all shortest distance are finalized # then setds will become empty */ while (len(setds) > 0): # The first vertex in Set is the minimum distance # vertex, extract it from set. tmp = list(setds.keys())[0] del setds[tmp] # vertex label is stored in second of pair (it # has to be done this way to keep the vertices # sorted distance (distance must be first item # in pair) u = tmp[1] # 'i' is used to get all adjacent vertices of a vertex # list< pair<int, int> >::iterator i; for i in adj[u]: # Get vertex label and weight of current adjacent # of u. v = i[0] weight = i[1] # If there is shorter path to v through u. if (dist[v] > dist[u] + weight): # /* If distance of v is not INF then it must be in # our set, so removing it and inserting again # with updated less distance. # Note : We extract only those vertices from Set # for which distance is finalized. So for them, # we would never reach here. */ if (dist[v] != 10**18): del setds[(dist[v], v)] # Updating distance of v dist[v] = dist[u] + weight setds[(dist[v], v)] = 1 return dist # /* method adds reverse edge of each original edge # in the graph. It gives reverse edge a weight = 1 # and all original edges a weight of 0. Now, the # length of the shortest path will give us the answer. # If shortest path is p: it means we used p reverse # edges in the shortest path. */ def modelGraphWithEdgeWeight(edge, E, V): global adj for i in range(E): # original edge : weight 0 addEdge(edge[i][0], edge[i][1], 0) # reverse edge : weight 1 addEdge(edge[i][1], edge[i][0], 1) # Method returns minimum number of edges to be # reversed to reach from src to dest def getMinEdgeReversal(edge, E, V, src, dest): # get modified graph with edge weight modelGraphWithEdgeWeight(edge, E, V) # get shortes path vector dist = shortestPath(src) # If distance of destination is still INF, # not possible if (dist[dest] == 10**18): return -1 else: return dist[dest] # Driver code if __name__ == '__main__': V = 7 edge = [[0, 1], [2, 1], [2, 3], [5, 1], [4, 5], [6, 4], [6, 3]] E, adj = len(edge), [[] for i in range(V + 1)] minEdgeToReverse = getMinEdgeReversal(edge, E, V, 0, 6) if (minEdgeToReverse != -1): print(minEdgeToReverse) else: print("Not possible")
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 1: output = strs[0] if strs == []: output = "" else: output = '' j = 0 Flag = True try: while Flag: tmp = 0 for i in range(len(strs)): if strs[i] == "": return "" elif strs[0][j] == strs[i][j]: tmp += 1 if tmp == len(strs): output += strs[0][j] j += 1 else: Flag = False except IndexError: pass return output
""" @date: 5-14-16 Description: Creates the conflict and broad outlines of story relations """ class Conflict: def __init__(relation_outline_array=None): self.conflict_outline = relation_outline_array def add_relation(relation_outline): self.conflict_outline.append(relation_outline)
#!/usr/bin/env python3 # String to be evaluated s = "azcbobobegghakl" # Initialize count count = 0 # Vowels that will be evaluted inside s vowels = "aeiou" # For loop to count vowels in var s for letter in s: if letter in vowels: count += 1 # Prints final count to terminal print("Number of vowels in " + s + ": " + str(count))
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ ls=s.split(" ") lt=[] for x in ls: x=x[::-1] lt.append(x) return " ".join(lt)
def diglet(i_buraco_origem, buracos): if buracos[i_buraco_origem] == -99: return 0 else: i_buraco_destino = buracos[i_buraco_origem] - 1 buracos[i_buraco_origem] = -99 return 1 + diglet(i_buraco_destino, buracos) def mdc_euclide(a, b): if b == 0: return a else: return mdc_euclide(b, a % b) n = int(input()) buracos = list(map(int, input().split())) caminhos = [] for i in range(0, n): ciclo = diglet(i, buracos) if ciclo != 0: caminhos.append(ciclo) mmc = caminhos[0] for j in range(0, len(caminhos) - 1): mmc = mmc * caminhos[j+1] / mdc_euclide(mmc, caminhos[j+1]) print("%i" % mmc)
x = ['happy','sad','cheerful'] print('{0},{1},{2}'.format(x[0],x[1].x[2])) ##-------------------------------------------## a = "{x}, {y}".format(x=5, y=12) print(a)
class UpdateContext: """ Used when updating data. Helps keeping track of whether the data was updated or not. """ data: str data_was_updated: bool = False def __init__(self, data: str): self.data = data def override_data(self, new_data: str) -> None: self.data = new_data self.data_was_updated = True
""" MadQt - Tutorials and Tools for PyQt and PySide All the Code in this package can be used freely for personal and commercial projects under a MIT License but remember that because this is an extension of the PyQt framework you will need to abide to the QT licensing scheme when releasing. ## $MADQT_BEGIN_LICENSE ## MIT License ## ## Copyright (c) 2021 Fabio Goncalves ## ## Permission is hereby granted, free of charge, to any person obtaining a copy ## of this software and associated documentation files (the "Software"), to deal ## in the Software without restriction, including without limitation the rights ## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ## copies of the Software, and to permit persons to whom the Software is ## furnished to do so, subject to the following conditions: ## ## The above copyright notice and this permission notice shall be included in all ## copies or substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ## SOFTWARE. ## $MADQT_END_LICENSE ## $QT_BEGIN_LICENSE:BSD$ ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance with the commercial license agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and The Qt Company. For licensing terms ## and conditions see https://www.qt.io/terms-conditions. For further ## information use the contact form at https://www.qt.io/contact-us. ## ## BSD License Usage ## Alternatively, you may use this file under the terms of the BSD license ## as follows: ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in ## the documentation and/or other materials provided with the ## distribution. ## * Neither the name of The Qt Company Ltd nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## ## $QT_END_LICENSE$ """
class Book: def __init__(self,title,author): self.title = title self.author = author def __str__(self): return '{} by {}'.format(self.title,self.author) class Bookcase(): def __init__(self,books=None): self.books = books @classmethod def create_bookcase(cls,book_list): books = [] for title, author in book_list: books.append(Book(title,author)) return cls(books)
class FileSystemWatcher(Component): """ Listens to the file system change notifications and raises events when a directory,or file in a directory,changes. FileSystemWatcher() FileSystemWatcher(path: str) FileSystemWatcher(path: str,filter: str) """ def ZZZ(self): """hardcoded/mock instance of the class""" return FileSystemWatcher() instance=ZZZ() """hardcoded/returns an instance of the class""" def BeginInit(self): """ BeginInit(self: FileSystemWatcher) Begins the initialization of a System.IO.FileSystemWatcher used on a form or used by another component. The initialization occurs at run time. """ pass def Dispose(self): """ Dispose(self: FileSystemWatcher,disposing: bool) Releases the unmanaged resources used by the System.IO.FileSystemWatcher and optionally releases the managed resources. disposing: true to release both managed and unmanaged resources; false to release only unmanaged resources. """ pass def EndInit(self): """ EndInit(self: FileSystemWatcher) Ends the initialization of a System.IO.FileSystemWatcher used on a form or used by another component. The initialization occurs at run time. """ pass def GetService(self,*args): """ GetService(self: Component,service: Type) -> object Returns an object that represents a service provided by the System.ComponentModel.Component or by its System.ComponentModel.Container. service: A service provided by the System.ComponentModel.Component. Returns: An System.Object that represents a service provided by the System.ComponentModel.Component,or null if the System.ComponentModel.Component does not provide the specified service. """ pass def MemberwiseClone(self,*args): """ MemberwiseClone(self: MarshalByRefObject,cloneIdentity: bool) -> MarshalByRefObject Creates a shallow copy of the current System.MarshalByRefObject object. cloneIdentity: false to delete the current System.MarshalByRefObject object's identity,which will cause the object to be assigned a new identity when it is marshaled across a remoting boundary. A value of false is usually appropriate. true to copy the current System.MarshalByRefObject object's identity to its clone,which will cause remoting client calls to be routed to the remote server object. Returns: A shallow copy of the current System.MarshalByRefObject object. MemberwiseClone(self: object) -> object Creates a shallow copy of the current System.Object. Returns: A shallow copy of the current System.Object. """ pass def OnChanged(self,*args): """ OnChanged(self: FileSystemWatcher,e: FileSystemEventArgs) Raises the System.IO.FileSystemWatcher.Changed event. e: A System.IO.FileSystemEventArgs that contains the event data. """ pass def OnCreated(self,*args): """ OnCreated(self: FileSystemWatcher,e: FileSystemEventArgs) Raises the System.IO.FileSystemWatcher.Created event. e: A System.IO.FileSystemEventArgs that contains the event data. """ pass def OnDeleted(self,*args): """ OnDeleted(self: FileSystemWatcher,e: FileSystemEventArgs) Raises the System.IO.FileSystemWatcher.Deleted event. e: A System.IO.FileSystemEventArgs that contains the event data. """ pass def OnError(self,*args): """ OnError(self: FileSystemWatcher,e: ErrorEventArgs) Raises the System.IO.FileSystemWatcher.Error event. e: An System.IO.ErrorEventArgs that contains the event data. """ pass def OnRenamed(self,*args): """ OnRenamed(self: FileSystemWatcher,e: RenamedEventArgs) Raises the System.IO.FileSystemWatcher.Renamed event. e: A System.IO.RenamedEventArgs that contains the event data. """ pass def WaitForChanged(self,changeType,timeout=None): """ WaitForChanged(self: FileSystemWatcher,changeType: WatcherChangeTypes) -> WaitForChangedResult A synchronous method that returns a structure that contains specific information on the change that occurred,given the type of change you want to monitor. changeType: The System.IO.WatcherChangeTypes to watch for. Returns: A System.IO.WaitForChangedResult that contains specific information on the change that occurred. WaitForChanged(self: FileSystemWatcher,changeType: WatcherChangeTypes,timeout: int) -> WaitForChangedResult A synchronous method that returns a structure that contains specific information on the change that occurred,given the type of change you want to monitor and the time (in milliseconds) to wait before timing out. changeType: The System.IO.WatcherChangeTypes to watch for. timeout: The time (in milliseconds) to wait before timing out. Returns: A System.IO.WaitForChangedResult that contains specific information on the change that occurred. """ pass def __enter__(self,*args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self,*args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ 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 @staticmethod def __new__(self,path=None,filter=None): """ __new__(cls: type) __new__(cls: type,path: str) __new__(cls: type,path: str,filter: str) """ pass def __str__(self,*args): pass CanRaiseEvents=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether the component can raise an event. """ DesignMode=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value that indicates whether the System.ComponentModel.Component is currently in design mode. """ EnableRaisingEvents=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets a value indicating whether the component is enabled. Get: EnableRaisingEvents(self: FileSystemWatcher) -> bool Set: EnableRaisingEvents(self: FileSystemWatcher)=value """ Events=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the list of event handlers that are attached to this System.ComponentModel.Component. """ Filter=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the filter string used to determine what files are monitored in a directory. Get: Filter(self: FileSystemWatcher) -> str Set: Filter(self: FileSystemWatcher)=value """ IncludeSubdirectories=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets a value indicating whether subdirectories within the specified path should be monitored. Get: IncludeSubdirectories(self: FileSystemWatcher) -> bool Set: IncludeSubdirectories(self: FileSystemWatcher)=value """ InternalBufferSize=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the size (in bytes) of the internal buffer. Get: InternalBufferSize(self: FileSystemWatcher) -> int Set: InternalBufferSize(self: FileSystemWatcher)=value """ NotifyFilter=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the type of changes to watch for. Get: NotifyFilter(self: FileSystemWatcher) -> NotifyFilters Set: NotifyFilter(self: FileSystemWatcher)=value """ Path=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the path of the directory to watch. Get: Path(self: FileSystemWatcher) -> str Set: Path(self: FileSystemWatcher)=value """ Site=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets an System.ComponentModel.ISite for the System.IO.FileSystemWatcher. Get: Site(self: FileSystemWatcher) -> ISite Set: Site(self: FileSystemWatcher)=value """ SynchronizingObject=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the object used to marshal the event handler calls issued as a result of a directory change. Get: SynchronizingObject(self: FileSystemWatcher) -> ISynchronizeInvoke Set: SynchronizingObject(self: FileSystemWatcher)=value """ Changed=None Created=None Deleted=None Error=None Renamed=None
# # Copyright (c) 2017 - The MITRE Corporation # For license information, see the LICENSE.txt file __version__ = "1.3.0"
class car(): def __init__(self, make, model, year ): self.make = make self.model = model self.year = year self.odometer = 0 def describe_car(self): long_name = str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): print('This car has '+str(self.odometer)+' miles on it.') def update_odometer(self, mileage): if mileage < self.odometer: print('You cannot roll back the odometer !') else: print('The odometer has updated !') def increase_odometer(self, increment): self.odometer += increment
expected_output = { "route-information": { "route-table": [ { "active-route-count": "16", "destination-count": "16", "hidden-route-count": "0", "holddown-route-count": "0", "rt": [ { "rt-announced-count": "1", "rt-destination": "10.1.0.0", "rt-entry": { "as-path": "AS path: I", "bgp-path-attributes": { "attr-as-path-effective": { "aspath-effective-string": "AS path:", "attr-value": "I", } }, "bgp-rt-flag": "Accepted", "local-preference": "100", "nh": {"to": "10.64.4.4"}, }, "rt-entry-count": {"#text": "2"}, "rt-prefix-length": "24", }, { "rt-announced-count": "1", "rt-destination": "10.64.4.4", "rt-entry": { "as-path": "AS path: I", "bgp-path-attributes": { "attr-as-path-effective": { "aspath-effective-string": "AS path:", "attr-value": "I", } }, "bgp-rt-flag": "Accepted", "local-preference": "100", "nh": {"to": "10.64.4.4"}, }, "rt-entry-count": {"#text": "2"}, "rt-prefix-length": "32", }, { "rt-announced-count": "1", "rt-destination": "10.145.0.0", "rt-entry": { "as-path": "AS path: I", "bgp-path-attributes": { "attr-as-path-effective": { "aspath-effective-string": "AS path:", "attr-value": "I", } }, "bgp-rt-flag": "Accepted", "local-preference": "100", "nh": {"to": "10.64.4.4"}, }, "rt-entry-count": {"#text": "2"}, "rt-prefix-length": "24", }, { "active-tag": "* ", "rt-announced-count": "1", "rt-destination": "192.168.220.0", "rt-entry": { "as-path": "AS path: I", "bgp-path-attributes": { "attr-as-path-effective": { "aspath-effective-string": "AS path:", "attr-value": "I", } }, "bgp-rt-flag": "Accepted", "local-preference": "100", "nh": {"to": "10.64.4.4"}, }, "rt-entry-count": {"#text": "1"}, "rt-prefix-length": "24", }, { "active-tag": "* ", "rt-announced-count": "1", "rt-destination": "192.168.240.0", "rt-entry": { "as-path": "AS path: 200000 4 5 6 I", "bgp-path-attributes": { "attr-as-path-effective": { "aspath-effective-string": "AS path:", "attr-value": "200000 4 5 6 I", } }, "bgp-rt-flag": "Accepted", "local-preference": "100", "nh": {"to": "10.64.4.4"}, }, "rt-entry-count": {"#text": "1"}, "rt-prefix-length": "24", }, { "active-tag": "* ", "rt-announced-count": "1", "rt-destination": "192.168.205.0", "rt-entry": { "as-path": "AS path: 200000 4 7 8 I", "bgp-path-attributes": { "attr-as-path-effective": { "aspath-effective-string": "AS path:", "attr-value": "200000 4 7 8 I", } }, "bgp-rt-flag": "Accepted", "local-preference": "100", "nh": {"to": "10.64.4.4"}, }, "rt-entry-count": {"#text": "1"}, "rt-prefix-length": "24", }, { "active-tag": "* ", "rt-announced-count": "1", "rt-destination": "192.168.115.0", "rt-entry": { "as-path": "AS path: 200000 4 100000 8 I", "bgp-path-attributes": { "attr-as-path-effective": { "aspath-effective-string": "AS path:", "attr-value": "200000 4 100000 8 I", } }, "bgp-rt-flag": "Accepted", "local-preference": "100", "nh": {"to": "10.64.4.4"}, }, "rt-entry-count": {"#text": "1"}, "rt-prefix-length": "24", }, ], "table-name": "inet.0", "total-route-count": "19", }, { "active-route-count": "18", "destination-count": "18", "hidden-route-count": "0", "holddown-route-count": "0", "table-name": "inet6.0", "total-route-count": "20", }, ] } }
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? https://projecteuler.net/problem=7 """ # Cache a few primes to get the algorithm started. # Note: the odd values allow the step of 2 in next_prime() primes = [2, 3, 5] # Shortcut for multi-use: save the largest non-prime # tested for subsequent prime searches # test_val = primes[-1] def prime_number(count): """ Returns the nth prime. Adapted from code in prob3.py """ test_val = primes[-1] while len(primes) <= count: # No point testing even numbers test_val += 2 divisible = False # Compare to known primes for i in primes: if test_val % i == 0: divisible = True break if not divisible: # New prime found! primes.append(test_val) # print(primes, count, primes[count - 1]) result = primes[count - 1] # print("Prime #{} is {}".format(count, result)) return primes[count - 1] assert prime_number(1) == 2 assert prime_number(2) == 3 assert prime_number(3) == 5 assert prime_number(4) == 7 assert prime_number(5) == 11 assert prime_number(6) == 13 print(prime_number(10001))
command = input() numbers = [int(n) for n in input().split()] command_numbers = [] def add_command_numbers(num): if (num % 2 == 0 and command == "Even") or (num % 2 != 0 and command == "Odd"): command_numbers.append(num) for n in numbers: add_command_numbers(n) print(sum(command_numbers)*len(numbers))
""" @ ์ปดํ”„๋ฆฌํ•ธ์…˜ (comprehension) ` ํ•˜๋‚˜ ์ด์ƒ์˜ ์ดํ„ฐ๋ ˆ์ดํ„ฐ๋กœ๋ถ€ํ„ฐ ํŒŒ์ด์ฌ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๋งŒ๋“œ๋Š” ์ปดํŒฉํŠธํ•œ ๋ฐฉ๋ฒ• ` ๋น„๊ต์  ๊ฐ„๋‹จํ•œ ๊ตฌ๋ฌธ์œผ๋กœ ๋ฐ˜๋ณต๋ฌธ๊ณผ ์กฐ๊ฑด ํ…Œ์ŠคํŠธ๋ฅผ ๊ฒฐํ•ฉ * ๋ฆฌ์ŠคํŠธ ์ปจํ”„๋ฆฌํ•ธ์…˜ [ ํ‘œํ˜„์‹ for ํ•ญ๋ชฉ in ์ˆœํšŒ๊ฐ€๋Šฅ๊ฐ์ฒด ] [ ํ‘œํ˜„์‹ for ํ•ญ๋ชฉ in ์ˆœํšŒ๊ฐ€๋Šฅ๊ฐ์ฒด if ์กฐ๊ฑด ] * ๋”•์…”๋Ÿฌ๋ฆฌ ์ปจํ”„๋ฆฌํ•ธ์…˜ { ํ‚ค_ํ‘œํ˜„์‹: ๊ฐ’_ํ‘œํ˜„์‹ for ํ‘œํ˜„์‹ in ์ˆœํšŒ๊ฐ€๋Šฅ๊ฐ์ฒด } * ์…‹ ์ปจํ”„๋ฆฌํ•ธ์…˜ { ํ‘œํ˜„์‹ for ํ‘œํ˜„์‹ in ์ˆœํšŒ๊ฐ€๋Šฅ๊ฐ์ฒด } """ # ์ปจํ”„๋ฆฌํ•ธ์…˜ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ ''' alist = [] alist.append(1) alist.append(2) alist.append(3) alist.append(4) alist.append(5) alist.append(6) print(alist) alist = [] for n in range(1,6): alist.append(n) print(alist) alist = list(range(1,6)) print(alist) ''' #------------------------------------------------ # ๋ฆฌ์ŠคํŠธ ์ปจํ”„๋ฆฌํ•ธ์…˜ # [์˜ˆ] [1, 2, 3, 4, 5, 6] blist = [n ** 2 for n in range(1, 7)] print(blist) clist = [n for n in range(1, 11) if n % 2 == 0] print(clist) rows = range(1, 4) # 1, 2, 3 cols = range(1, 6, 2) # 1, 3, 5 dlist = [(r, c) for r in rows for c in cols] print(dlist) # dlist์—์„œ ๊ฐ ์š”์†Œ ์ถ”์ถœํ•˜์—ฌ ์ถœ๋ ฅ for data in dlist: print(data) for (frist, second) in dlist: print(frist, second) #------------------------------------------- # ๋”•์…”๋Ÿฌ๋‹ˆ ์ปจํ”„๋ฆฌํ•ธ์…˜ # {ํ‚ค : ๊ฐ’} a = {x : x**2 for x in (2, 3, 4)} print(a) # {2: 4, 3: 9, 4: 16} word = "LOVE LOL" wcnt = {letter: word.count(letter) for letter in word} print(wcnt) # {'L': 3, 'O': 2, 'V': 1, 'E': 1, ' ': 1}, ๊ฐ’์€ ๋ฌธ์ž๋Š” ๊ฐ™์€ ํ‚ค๊ฐ’์„ ๊ฐ€์ง„๋‹ค. #------------------------------------------- # ์…‹ ์ปจํ”„๋ฆฌํ•ธ์…˜ # {1, 2, 3, 4, 5, 6} data = [1, 2, 3, 1, 3, 5, 6, 2] alist = [n for n in data if n % 2 == 1] # ๋ฆฌ์ŠคํŠธ print(alist) aset = {n for n in range(1, 7)} # ์…‹ print(aset) """ @ ๋ฆฌ์ŠคํŠธ ์ปจํ”„๋ฆฌํ•ธ์…˜๊ณผ ์…‹ ์ปจํ”„๋ฆฌํ•ธ์…˜์˜ ์ฐจ์ด๋Š”? ๋ฆฌ์ŠคํŠธ : ์ธ๋ฑ์Šค / ์ค‘๋ณตํ—ˆ์šฉ / ๋ณ€๊ฒฝ๊ฐ€๋Šฅ ํŠœํ”Œ : ์ธ๋ฑ์Šค / ์ค‘๋ณตํ—ˆ์šฉ / ๋ณ€๊ฒฝ๋ถˆ๊ฐ€ ์…‹ : ์ธ๋ฑ์Šค X / ์ค‘๋ณต X / ๋ณ€๊ฒฝ๊ฐ€๋Šฅ ๋”•์…”๋„ˆ๋ฆฌ : ํ‚ค์™€ ๊ฐ’ / ํ‚ค๋Š” ์ค‘๋ณต X / ์ธ๋ฑ์Šค X """ #------------------------------------------- # [์ฐธ๊ณ ] ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ์ปจํ”„๋ฆฌํ•ธ์…˜ # ()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํŠœํ”Œ์ด๋ผ ์ƒ๊ฐํ•˜์ง€๋งŒ ํŠœํ”Œ์€ ์ปจํ”„๋ฆฌํ•ธ์…˜์ด ์—†๋‹ค. # ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ์ปจํ”„๋ฆฌํ•ธ์…˜์€ ํ•œ ๋ฒˆ๋งŒ ์‹คํ–‰ # ์ฆ‰์„์—์„œ ๊ทธ ๊ฐ’์„ ์ƒ์„ฑํ•˜๊ณ  ์ดํ„ฐ๋ ˆ์ดํ„ฐ๋ฅผ ํ†ตํ•ด ํ•œ ๋ฒˆ์— ๊ฐ’์„ ํ•˜๋‚˜์”ฉ ์ฒ˜๋ฆฌํ•˜๊ณ  ์ €์žฅํ•˜์ง€ ์•Š์Œ data = [1, 2, 3, 1, 3, 5, 6, 2] alist = (n for n in data if n % 2 == 1) # ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ์ปจํ”„๋ฆฌํ•ธ์…˜(์ ˆ๋Œ€๋กœ ํŠœํ”Œ์ด ์•„๋‹˜) print(alist) print(type(alist)) print(list(alist)) print(list(alist)) ''' # ์—ฐ์Šต # BMI(Body Mass Index)๋Š” ์ฒด์ค‘(kg)์„ ์‹ ์žฅ(m)์˜ ์ œ๊ณฑ(**2)์œผ๋กœ๋‚˜๋ˆˆ ๊ฐ’์œผ๋กœ ์ฒด์ง€๋ฐฉ ์ถ•์ ์„ ์ž˜ ๋ฐ˜์˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋น„๋งŒ๋„ ํŒ์ •์— # ๋งŽ์ด ์‚ฌ์šฉํ•œ๋‹ค. ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์‹ ์žฅ๊ณผ ์ฒด์ค‘์„์ž…๋ ฅ ๋ฐ›์•„์„œ BMI ๊ฐ’์— ๋”ฐ๋ผ์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์—ฌ ๋ณด์ž. kg = float(input("์ฒด์ค‘์„์ž…๋ ฅํ•˜์„ธ์š”:")) m = float(input("์‹ ์žฅ์„์ž…๋ ฅํ•˜์„ธ์š”:")) bmi = kg / m ** 2 print("๋‹น์‹ ์˜ BMI: %.2f" % bmi) if 20 <= bmi >= 24.9: print("์ •์ƒ์ž…๋‹ˆ๋‹ค.") elif 25 <= bmi <= 29.9: print("๊ณผ์ฒด์ค‘์ž…๋‹ˆ๋‹ค.") elif bmi >= 30: print("๋น„๋งŒ์ž…๋‹ˆ๋‹ค.") # ์—ฐ์Šต2 # 1๋ถ€ํ„ฐ 99๊นŒ์ง€ 2์ž๋ฆฌ์˜ ์ •์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ๋ณต๊ถŒ์ด ์žˆ๋‹ค๊ณ  ํ•˜์ž. 2์ž๋ฆฌ๊ฐ€ ์ „๋ถ€ ์ผ์น˜ํ•˜๋ฉด 1๋“ฑ์ƒ 100๋งŒ์›์„ ๋ฐ›๋Š”๋‹ค. # 2์ž๋ฆฌ์ค‘์—์„œ ํ•˜๋‚˜๋งŒ ์ผ์น˜ํ•˜๋ฉด 50๋งŒ์›์„ ๋ฐ›๊ณ  ํ•˜๋‚˜๋„ ์ผ์น˜ํ•˜์ง€ ์•Š์œผ๋ฉด ์ƒ๊ธˆ์€ ์—†๋‹ค. # 1์—์„œ 100 ์‚ฌ์ด์˜ ๋‚œ์ˆ˜๊ฐ€ ๋ฐœ์ƒ๋œ๋‹ค. num = int(input('๋ณต๊ถŒ ๋ฒˆํ˜ธ(1-99)๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค ')) import random number = random.randint(1, 100) print('์ž…๋ ฅ๋ฒˆํ˜ธ : ', num) print('๋‹น์ฒจ๋ฒˆํ˜ธ : ', number) num_sp = list(str(num)) if len(num_sp) != 2: num_sp = ['0'] + num_sp # print(num_sp) number_sp = list(str(number)) if len(number_sp) != 2: number_sp = ['0'] + number_sp aa = list(zip(num_sp, number_sp)) print(aa) # [('0', '6'), ('3', '8')] score = 0 for a, b in aa: if a == b: score += 50 print(score, "๋งŒ์›") '''
class Env(object): user='test' password='test' port=5432 host='localhost' dbname='todo' development=False env = Env()
def get_phase_dir(self): """Return the Rotation direction of the stator phases Parameters ---------- self : LUT A LUT object Returns ------- phase_dir : int Rotation direction of the stator phase """ return self.output_list[0].elec.phase_dir
day09 = __import__("day-09") process = day09.process_gen rotor = { 0: {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}, 1: {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}, } diff = { 'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0), } def draw(data, panels): direction = 'N' coord = (0, 0) try: inp = [] g = process(data, inp) while True: current_color = panels.get(coord, 0) inp.append(current_color) color = next(g) panels[coord] = color rotate = next(g) direction = rotor[rotate][direction] dd = diff[direction] coord = coord[0] + dd[0], coord[1] + dd[1] except StopIteration: pass return panels def test_case1(): with open('day-11.txt', 'r') as f: text = f.read().strip() data = [int(x) for x in text.split(',')] panels = dict() draw(data, panels) xmin = min(x[0] for x in panels.keys()) xmax = max(x[0] for x in panels.keys()) ymin = min(x[1] for x in panels.keys()) ymax = max(x[1] for x in panels.keys()) w = xmax - xmin h = ymax - ymin for j in range(ymin, ymax): for i in range(xmin, xmax): c = (i, j) color = panels.get(c, 0) print('#' if color == 1 else '.', end='') print() assert len(panels) == 2339 def test_case2(): with open('day-11.txt', 'r') as f: text = f.read().strip() data = [int(x) for x in text.split(',')] panels = dict() panels[(0, 0)] = 1 draw(data, panels) xmin = min(x[0] for x in panels.keys()) - 2 xmax = max(x[0] for x in panels.keys()) + 2 ymin = min(x[1] for x in panels.keys()) - 2 ymax = max(x[1] for x in panels.keys()) + 2 w = xmax - xmin h = ymax - ymin for j in range(ymax, ymin, -1): for i in range(xmin, xmax): c = (i, j) color = panels.get(c, 0) print('#' if color == 1 else '.', end='') print() assert False
# from enum import IntEnum LEVEL_UNKNOWN_DEATH = int(0) LEVEL_NOS = int(-1) LEVEL_FINISHED = int(-2) LEVEL_MAX = 21 LEVELS_PER_ZONE = 4 TOTAL_ZONES = 5 # class LevelSpecial(IntEnum): # UNKNOWN_DEATH = 0, # NOS = -1, # FINISHED = -2 # # # class Level(object): # @staticmethod # def fromstr(level_str: str) -> int or None: # args = level_str.split('-') # if len(args) == 2: # try: # zone = int(args[0]) # lvl = int(args[1]) # if (1 <= zone <= TOTAL_ZONES and 1 <= lvl <= LEVELS_PER_ZONE) or (zone == 5 and lvl == 5): # return Level(zone=zone, level=lvl) # except ValueError: # return None # return None # # def __init__( # self, # zone: int = None, # level: int = None, # total_level: int = None, # level_special: LevelSpecial = None # ) -> None: # if total_level is not None: # self.zone = min(((total_level - 1) // LEVELS_PER_ZONE) + 1, TOTAL_ZONES) # self.level = total_level - LEVELS_PER_ZONE * (self.zone - 1) # # self.zone = zone # self.level = level # self.level_special = level_special # # def __int__(self) -> int: # if self.is_normal_level: # return 4*(self.zone - 1) + self.level # else: # return int(self.level_special) # # def __str__(self) -> str: # if self.is_normal_level is None: # return '{0}-{1}'.format(self.zone, self.level) # elif self.is_normal_level == LevelSpecial.UNKNOWN_DEATH: # return 'unknown death' # elif self.is_normal_level == LevelSpecial.NOS: # return 'unknown' # elif self.is_normal_level == LevelSpecial.FINISHED: # return 'finished' # # @property # def is_normal_level(self) -> bool: # return self.level_special is not None # # def sortval(self, reverse: bool = False) -> int: # if self.level_special == LevelSpecial.FINISHED: # return LEVEL_MAX + 1 # elif reverse: # return LEVEL_MAX - self.__int__() if self.__init__() > 0 else 0 # else: # return self.__int__() def from_str(level_str: str) -> int: """With level_str in the form x-y, return the level as a number from 1 to 21, or LEVEL_NOS if invalid""" args = level_str.split('-') if len(args) == 2: try: world = int(args[0]) lvl = int(args[1]) if (1 <= world <= TOTAL_ZONES and 1 <= lvl <= LEVELS_PER_ZONE) or (world == 5 and lvl == 5): return LEVELS_PER_ZONE*(world-1) + lvl except ValueError: return LEVEL_NOS return LEVEL_NOS def to_str(level: int) -> str: """Convert a level number from 1 to 21 into the appropriate x-y format; otherwise return an empty string.""" if 1 <= level <= LEVEL_MAX: world = min(((level-1) // LEVELS_PER_ZONE) + 1, TOTAL_ZONES) lvl = level - LEVELS_PER_ZONE*(world-1) return '{0}-{1}'.format(world, lvl) else: return '' def level_sortval(level: int, reverse=False) -> int: """Return an int that will cause levels to sort correctly.""" if level == LEVEL_FINISHED: return LEVEL_MAX + 1 elif reverse: return LEVEL_MAX - level if level > 0 else level else: return level
class MagicalGirlLevelOneDivTwo: def theMinDistance(self, d, x, y): return min( sorted( (a ** 2 + b ** 2) ** 0.5 for a in xrange(x - d, x + d + 1) for b in xrange(y - d, y + d + 1) ) )
test = 1 while True: n = int(input()) if n == 0: break participantes = [int(x) for x in input().split()] vencedor = [participantes[x] for x in range(n) if participantes[x] == (x + 1)] print(f'Teste {test}') test += 1 print(vencedor[0]) print()
# Check if there are two adjacent digits that are the same def adjacent_in_list(li=()): for c in range(0, len(li)-1): if li[c] == li[c+1]: return True return False # Check if the list doesn't get smaller as the index increases def list_gets_bigger(li=()): for c in range(0, len(li)-1): if li[c] > li[c+1]: return False else: return True def password_criteria(n, mini, maxi): n_list = [] n = str(n) for c in range(0, len(n)): n_list += [int(n[c])] if int(n) > maxi or int(n) < mini: # Check if the number is in the range return False elif not adjacent_in_list(n_list): return False elif list_gets_bigger(n_list): return True passwords = [] for c0 in range(146810, 612564): if password_criteria(c0, 146810, 612564): passwords += [c0] print(len(passwords), passwords)
FARMINGPRACTICES_TYPE_URI = "https://w3id.org/okn/o/sdm#FarmingPractices" FARMINGPRACTICES_TYPE_NAME = "FarmingPractices" POINTBASEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#PointBasedGrid" POINTBASEDGRID_TYPE_NAME = "PointBasedGrid" SUBSIDY_TYPE_URI = "https://w3id.org/okn/o/sdm#Subsidy" SUBSIDY_TYPE_NAME = "Subsidy" GRID_TYPE_URI = "https://w3id.org/okn/o/sdm#Grid" GRID_TYPE_NAME = "Grid" TIMEINTERVAL_TYPE_URI = "https://w3id.org/okn/o/sdm#TimeInterval" TIMEINTERVAL_TYPE_NAME = "TimeInterval" EMPIRICALMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#EmpiricalModel" EMPIRICALMODEL_TYPE_NAME = "EmpiricalModel" GEOSHAPE_TYPE_URI = "https://w3id.org/okn/o/sdm#GeoShape" GEOSHAPE_TYPE_NAME = "GeoShape" MODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#Model" MODEL_TYPE_NAME = "Model" REGION_TYPE_URI = "https://w3id.org/okn/o/sdm#Region" REGION_TYPE_NAME = "Region" GEOCOORDINATES_TYPE_URI = "https://w3id.org/okn/o/sdm#GeoCoordinates" GEOCOORDINATES_TYPE_NAME = "GeoCoordinates" SPATIALLYDISTRIBUTEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#SpatiallyDistributedGrid" SPATIALLYDISTRIBUTEDGRID_TYPE_NAME = "SpatiallyDistributedGrid" EMULATOR_TYPE_URI = "https://w3id.org/okn/o/sdm#Emulator" EMULATOR_TYPE_NAME = "Emulator" MODELCONFIGURATION_TYPE_URI = "https://w3id.org/okn/o/sdm#ModelConfiguration" MODELCONFIGURATION_TYPE_NAME = "ModelConfiguration" THEORYGUIDEDMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#Theory-GuidedModel" THEORYGUIDEDMODEL_TYPE_NAME = "Theory-GuidedModel" NUMERICALINDEX_TYPE_URI = "https://w3id.org/okn/o/sdm#NumericalIndex" NUMERICALINDEX_TYPE_NAME = "NumericalIndex" PROCESS_TYPE_URI = "https://w3id.org/okn/o/sdm#Process" PROCESS_TYPE_NAME = "Process" HYBRIDMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#HybridModel" HYBRIDMODEL_TYPE_NAME = "HybridModel" MODELCONFIGURATIONSETUP_TYPE_URI = "https://w3id.org/okn/o/sdm#ModelConfigurationSetup" MODELCONFIGURATIONSETUP_TYPE_NAME = "ModelConfigurationSetup" CAUSALDIAGRAM_TYPE_URI = "https://w3id.org/okn/o/sdm#CausalDiagram" CAUSALDIAGRAM_TYPE_NAME = "CausalDiagram" SPATIALRESOLUTION_TYPE_URI = "https://w3id.org/okn/o/sdm#SpatialResolution" SPATIALRESOLUTION_TYPE_NAME = "SpatialResolution" EQUATION_TYPE_URI = "https://w3id.org/okn/o/sdm#Equation" EQUATION_TYPE_NAME = "Equation" INTERVENTION_TYPE_URI = "https://w3id.org/okn/o/sdm#Intervention" INTERVENTION_TYPE_NAME = "Intervention" SAMPLEEXECUTION_TYPE_URI = "https://w3id.org/okn/o/sd#SampleExecution" SAMPLEEXECUTION_TYPE_NAME = "SampleExecution" VISUALIZATION_TYPE_URI = "https://w3id.org/okn/o/sd#Visualization" VISUALIZATION_TYPE_NAME = "Visualization" IMAGE_TYPE_URI = "https://w3id.org/okn/o/sd#Image" IMAGE_TYPE_NAME = "Image" SOURCECODE_TYPE_URI = "https://w3id.org/okn/o/sd#SourceCode" SOURCECODE_TYPE_NAME = "SourceCode" ORGANIZATION_TYPE_URI = "https://w3id.org/okn/o/sd#Organization" ORGANIZATION_TYPE_NAME = "Organization" DATASETSPECIFICATION_TYPE_URI = "https://w3id.org/okn/o/sd#DatasetSpecification" DATASETSPECIFICATION_TYPE_NAME = "DatasetSpecification" UNIT_TYPE_URI = "https://w3id.org/okn/o/sd#Unit" UNIT_TYPE_NAME = "Unit" CONFIGURATIONSETUP_TYPE_URI = "https://w3id.org/okn/o/sd#ConfigurationSetup" CONFIGURATIONSETUP_TYPE_NAME = "ConfigurationSetup" ICASAVARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#ICASAVariable" ICASAVARIABLE_TYPE_NAME = "ICASAVariable" SAMPLECOLLECTION_TYPE_URI = "https://w3id.org/okn/o/sd#SampleCollection" SAMPLECOLLECTION_TYPE_NAME = "SampleCollection" STANDARDVARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#StandardVariable" STANDARDVARIABLE_TYPE_NAME = "StandardVariable" SOFTWAREIMAGE_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareImage" SOFTWAREIMAGE_TYPE_NAME = "SoftwareImage" SOFTWARE_TYPE_URI = "https://w3id.org/okn/o/sd#Software" SOFTWARE_TYPE_NAME = "Software" VARIABLEPRESENTATION_TYPE_URI = "https://w3id.org/okn/o/sd#VariablePresentation" VARIABLEPRESENTATION_TYPE_NAME = "VariablePresentation" SOFTWARECONFIGURATION_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareConfiguration" SOFTWARECONFIGURATION_TYPE_NAME = "SoftwareConfiguration" SOFTWAREVERSION_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareVersion" SOFTWAREVERSION_TYPE_NAME = "SoftwareVersion" FUNDINGINFORMATION_TYPE_URI = "https://w3id.org/okn/o/sd#FundingInformation" FUNDINGINFORMATION_TYPE_NAME = "FundingInformation" SAMPLERESOURCE_TYPE_URI = "https://w3id.org/okn/o/sd#SampleResource" SAMPLERESOURCE_TYPE_NAME = "SampleResource" PARAMETER_TYPE_URI = "https://w3id.org/okn/o/sd#Parameter" PARAMETER_TYPE_NAME = "Parameter" SVOVARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#SVOVariable" SVOVARIABLE_TYPE_NAME = "SVOVariable" PERSON_TYPE_URI = "https://w3id.org/okn/o/sd#Person" PERSON_TYPE_NAME = "Person" VARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#Variable" VARIABLE_TYPE_NAME = "Variable"
# # @lc app=leetcode id=49 lang=python3 # # [49] Group Anagrams # # https://leetcode.com/problems/group-anagrams/description/ # # algorithms # Medium (60.66%) # Likes: 7901 # Dislikes: 277 # Total Accepted: 1.2M # Total Submissions: 1.9M # Testcase Example: '["eat","tea","tan","ate","nat","bat"]' # # Given an array of strings strs, group the anagrams together. You can return # the answer in any order. # # An Anagram is a word or phrase formed by rearranging the letters of a # different word or phrase, typically using all the original letters exactly # once. # # # Example 1: # Input: strs = ["eat","tea","tan","ate","nat","bat"] # Output: [["bat"],["nat","tan"],["ate","eat","tea"]] # Example 2: # Input: strs = [""] # Output: [[""]] # Example 3: # Input: strs = ["a"] # Output: [["a"]] # # # Constraints: # # # 1 <= strs.length <= 10^4 # 0 <= strs[i].length <= 100 # strs[i] consists of lowercase English letters. # # # # @lc code=start class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = {} for str in strs: str_sort = ''.join(sorted(str)) if str_sort in d: d[str_sort].append(str) else: d[str_sort] = [str] return list(d.values()) # @lc code=end
# Copyright (c) 2019 Pavel Vavruska # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. class Config: def __init__( self, fov, is_perspective_correction_on, is_metric_on, pixel_size, dynamic_lighting, texture_filtering ): self.__fov = fov self.__is_perspective_correction_on = is_perspective_correction_on self.__is_metric_on = is_metric_on self.__pixel_size = pixel_size self.__dynamic_lighting = dynamic_lighting self.__texture_filtering = texture_filtering @property def fov(self): return self.__fov @property def is_perspective_correction_on(self): return self.__is_perspective_correction_on @property def is_metric_on(self): return self.__is_metric_on @property def pixel_size(self): return self.__pixel_size @property def dynamic_lighting(self): return self.__dynamic_lighting @property def texture_filtering(self): return self.__texture_filtering def set_fov(self, fov): self.__fov = fov def toggle_perspective_correction_on(self): self.__is_perspective_correction_on = not self.is_perspective_correction_on def toggle_metric_on(self): self.__is_metric_on = not self.__is_metric_on def set_pixel_size(self, pixel_size): self.__pixel_size = pixel_size def increase_pixel_size(self): if self.pixel_size < 10: self.__pixel_size = self.pixel_size + 1 def decrease_pixel_size(self): if self.pixel_size > 1: self.__pixel_size = self.pixel_size - 1 def toggle_dynamic_lighting(self): self.__dynamic_lighting = not self.__dynamic_lighting def toggle_texture_filtering(self): self.__texture_filtering = not self.__texture_filtering
def dijkstra(graph): start = "A" times = {a: float("inf") for a in graph.keys()} times[start] = 0 a = list(times) while a: node_selected = min(a, key=lambda k: times[k]) print("node selected", node_selected) a.remove(node_selected) for node, t in graph[node_selected].items(): if times[node_selected] + t < times[node]: times[node] = times[node_selected] + t print(times) graph = { "A": {"B": 4, "D": 3}, "B": {"C": 1}, "C": {}, "D": {"B": 1, "C": 3} } dijkstra(graph)
# Nodes in lattice graph and associated modules class LatticeNode: def __init__(self, dimensions: tuple): self._parents = list() self._children = list() self._is_pruned = False self.superpattern_count = -1 self.dimensions = dimensions def is_node_pruned(self): return self._is_pruned def prune_node(self): self._is_pruned = True def add_parents(self, parents: list) -> None: """Args: parents (list): list of lattice node instances """ self._parents.extend(parents) def get_parents(self) -> list: return self._parents def add_children(self, children: list) -> None: """Args: children (list): list of lattice node instances """ self._children.extend(children) def get_children(self) -> list: return self._children
globalVar = 0 dataset = 'berlin' max_len = 1024 nb_features = 36 nb_attention_param = 256 attention_init_value = 1.0 / 256 nb_hidden_units = 512 # number of hidden layer units dropout_rate = 0.5 nb_lstm_cells = 128 nb_classes = 7 frame_size = 0.025 # 25 msec segments step = 0.01 # 10 msec time step
# new_user() # show_global_para() # run_pdf() # read_calib_file_new() # check_latest_scan_id(init_guess=60000, search_size=100) ################################### def load_xanes_ref(*arg): """ load reference spectrum, use it as: ref = load_xanes_ref(Ni, Ni2, Ni3) each spectrum is two-column array, containing: energy(1st column) and absortion(2nd column) It returns a dictionary, which can be used as: spectrum_ref['ref0'], spectrum_ref['ref1'] .... """ num_ref = len(arg) assert num_ref > 1, "num of reference should larger than 1" spectrum_ref = {} for i in range(num_ref): spectrum_ref[f"ref{i}"] = arg[i] return spectrum_ref def fit_2D_xanes_non_iter(img_xanes, eng, spectrum_ref, error_thresh=0.1): """ Solve equation of Ax=b, where: Inputs: ---------- A: reference spectrum (2-colume array: xray_energy vs. absorption_spectrum) X: fitted coefficient of each ref spectrum b: experimental 2D XANES data Outputs: ---------- fit_coef: the 'x' in the equation 'Ax=b': fitted coefficient of each ref spectrum cost: cost between fitted spectrum and raw data """ num_ref = len(spectrum_ref) spec_interp = {} comp = {} A = [] s = img_xanes.shape for i in range(num_ref): tmp = interp1d( spectrum_ref[f"ref{i}"][:, 0], spectrum_ref[f"ref{i}"][:, 1], kind="cubic" ) A.append(tmp(eng).reshape(1, len(eng))) spec_interp[f"ref{i}"] = tmp(eng).reshape(1, len(eng)) comp[f"A{i}"] = spec_interp[f"ref{i}"].reshape(len(eng), 1) comp[f"A{i}_t"] = comp[f"A{i}"].T # e.g., spectrum_ref contains: ref1, ref2, ref3 # e.g., comp contains: A1, A2, A3, A1_t, A2_t, A3_t # A1 = ref1.reshape(110, 1) # A1_t = A1.T A = np.squeeze(A).T M = np.zeros([num_ref + 1, num_ref + 1]) for i in range(num_ref): for j in range(num_ref): M[i, j] = np.dot(comp[f"A{i}_t"], comp[f"A{j}"]) M[i, num_ref] = 1 M[num_ref] = np.ones((1, num_ref + 1)) M[num_ref, -1] = 0 # e.g. # M = np.array([[float(np.dot(A1_t, A1)), float(np.dot(A1_t, A2)), float(np.dot(A1_t, A3)), 1.], # [float(np.dot(A2_t, A1)), float(np.dot(A2_t, A2)), float(np.dot(A2_t, A3)), 1.], # [float(np.dot(A3_t, A1)), float(np.dot(A3_t, A2)), float(np.dot(A3_t, A3)), 1.], # [1., 1., 1., 0.]]) M_inv = np.linalg.inv(M) b_tot = img_xanes.reshape(s[0], -1) B = np.ones([num_ref + 1, b_tot.shape[1]]) for i in range(num_ref): B[i] = np.dot(comp[f"A{i}_t"], b_tot) x = np.dot(M_inv, B) x = x[:-1] x[x < 0] = 0 x_sum = np.sum(x, axis=0, keepdims=True) x = x / x_sum cost = np.sum((np.dot(A, x) - b_tot) ** 2, axis=0) / s[0] cost = cost.reshape(s[1], s[2]) x = x.reshape(num_ref, s[1], s[2]) # cost = compute_xanes_fit_cost(img_xanes, x, spec_interp) mask = compute_xanes_fit_mask(cost, error_thresh) mask = mask.reshape(s[1], s[2]) mask_tile = np.tile(mask, (x.shape[0], 1, 1)) x = x * mask_tile cost = cost * mask return x, cost def fit_2D_xanes_iter( img_xanes, eng, spectrum_ref, coef0=None, learning_rate=0.005, n_iter=10, bounds=[0, 1], error_thresh=0.1, ): """ Solve the equation A*x = b iteratively Inputs: ------- img_xanes: 3D xanes image stack eng: energy list of xanes spectrum_ref: dictionary, obtained from, e.g. spectrum_ref = load_xanes_ref(Ni2, Ni3) coef0: initial guess of the fitted coefficient, it has dimention of [num_of_referece, img_xanes.shape[1], img_xanes.shape[2]] learning_rate: float n_iter: int bounds: [low_limit, high_limit] can be 'None', which give no boundary limit error_thresh: float used to generate a mask, mask[fitting_cost > error_thresh] = 0 Outputs: --------- w: fitted 2D_xanes coefficient it has dimention of [num_of_referece, img_xanes.shape[1], img_xanes.shape[2]] cost: 2D fitting cost """ num_ref = len(spectrum_ref) A = [] for i in range(num_ref): tmp = interp1d( spectrum_ref[f"ref{i}"][:, 0], spectrum_ref[f"ref{i}"][:, 1], kind="cubic" ) A.append(tmp(eng).reshape(1, len(eng))) A = np.squeeze(A).T Y = img_xanes.reshape(img_xanes.shape[0], -1) if not coef0 is None: W = coef0.reshape(coef0.shape[0], -1) w, cost = lsq_fit_iter2(A, Y, W, learning_rate, n_iter, bounds, print_flag=1) w = w.reshape(len(w), img_xanes.shape[1], img_xanes.shape[2]) cost = cost.reshape(cost.shape[0], img_xanes.shape[1], img_xanes.shape[2]) mask = compute_xanes_fit_mask(cost[-1], error_thresh) mask_tile = np.tile(mask, (w.shape[0], 1, 1)) w = w * mask_tile mask_tile2 = np.tile(mask, (cost.shape[0], 1, 1)) cost = cost * mask_tile2 return w, cost def compute_xanes_fit_cost(img_xanes, fit_coef, spec_interp): # compute the cost num_ref = len(spec_interp) y_fit = np.zeros(img_xanes.shape) for i in range(img_xanes.shape[0]): for j in range(num_ref): y_fit[i] = y_fit[i] + fit_coef[j] * np.squeeze(spec_interp[f"ref{j}"])[i] y_dif = np.power(y_fit - img_xanes, 2) cost = np.sum(y_dif, axis=0) / img_xanes.shape[0] return cost def compute_xanes_fit_mask(cost, error_thresh=0.1): mask = np.ones(cost.shape) mask[cost > error_thresh] = 0 return mask def xanes_fit_demo(): f = h5py.File("img_xanes_normed.h5", "r") img_xanes = np.array(f["img"]) eng = np.array(f["X_eng"]) f.close() img_xanes = bin_ndarray( img_xanes, (img_xanes.shape[0], int(img_xanes.shape[1] / 2), int(img_xanes.shape[2] / 2)), ) Ni = np.loadtxt( "/NSLS2/xf18id1/users/2018Q1/MING_Proposal_000/xanes_ref/Ni_xanes_norm.txt" ) Ni2 = np.loadtxt( "/NSLS2/xf18id1/users/2018Q1/MING_Proposal_000/xanes_ref/NiO_xanes_norm.txt" ) Ni3 = np.loadtxt( "/NSLS2/xf18id1/users/2018Q1/MING_Proposal_000/xanes_ref/LiNiO2_xanes_norm.txt" ) spectrum_ref = load_xanes_ref(Ni2, Ni3) w1, c1 = fit_2D_xanes_non_iter(img_xanes, eng, spectrum_ref, error_thresh=0.1) plt.figure() plt.subplot(121) plt.imshow(w1[0]) plt.subplot(122) plt.imshow(w1[1]) def temp(): # os.mkdir('recon_image') scan_id = np.arange(15198, 15256) n = len(scan_id) for i in range(n): fn = f"fly_scan_id_{int(scan_id[i])}.h5" print(f"reconstructing: {fn} ... ") img = get_img(db[int(scan_id[i])], sli=[0, 1]) s = img.shape if s[-1] > 2000: sli = [200, 1900] binning = 2 else: sli = [100, 950] binning = 1 rot_cen = find_rot(fn) recon(fn, rot_cen, sli=sli, binning=binning) try: f_recon = ( f"recon_scan_{int(scan_id[i])}_sli_{sli[0]}_{sli[1]}_bin{binning}.h5" ) f = h5py.File(f_recon, "r") sli_choose = int((sli[0] + sli[1]) / 2) img_recon = np.array(f["img"][sli_choose], dtype=np.float32) sid = scan_id[i] f.close() fn_img_save = f"recon_image/recon_{int(sid)}_sli_{sli_choose}.tiff" print(f"saving {fn_img_save}\n") io.imsave(fn_img_save, img_recon) except: pass def multipos_tomo( exposure_time, x_list, y_list, z_list, out_x, out_y, out_z, out_r, rs, relative_rot_angle=185, period=0.05, relative_move_flag=0, traditional_sequence_flag=1, repeat=1, sleep_time=0, note="", ): n = len(x_list) txt = f"starting multiposition_flyscan: (repeating for {repeat} times)" insert_text(txt) for rep in range(repeat): for i in range(n): txt = f"\n################\nrepeat #{rep+1}:\nmoving to the {i+1} position: x={x_list[i]}, y={y_list[i]}, z={z_list[i]}" print(txt) insert_text(txt) yield from mv(zps.sx, x_list[i], zps.sy, y_list[i], zps.sz, z_list[i]) yield from fly_scan( exposure_time=exposure_time, relative_rot_angle=relative_rot_angle, period=period, chunk_size=20, out_x=out_x, out_y=out_y, out_z=out_z, out_r=out_r, rs=rs, simu=False, relative_move_flag=relative_move_flag, traditional_sequence_flag=traditional_sequence_flag, note=note, md=None, ) print(f"sleeping for {sleep_time:3.1f} s") yield from bps.sleep(sleep_time) def create_lists(x0, y0, z0, dx, dy, dz, Nx, Ny, Nz): Ntotal = Nx * Ny * Nz x_list = np.zeros(Ntotal) y_list = np.zeros(Ntotal) z_list = np.zeros(Ntotal) j = 0 for iz in range(Nz): for ix in range(Nx): for iy in range(Ny): j = iy + ix * Ny + iz * Ny * Nx #!!! y_list[j] = y0 + dy * iy x_list[j] = x0 + dx * ix z_list[j] = z0 + dz * iz return x_list, y_list, z_list def fan_scan( eng_list, x_list_2d, y_list_2d, z_list_2d, r_list_2d, x_list_3d, y_list_3d, z_list_3d, r_list_3d, out_x, out_y, out_z, out_r, relative_rot_angle, rs=3, exposure_time=0.05, chunk_size=4, sleep_time=0, repeat=1, relative_move_flag=True, note="", ): export_pdf(1) insert_text("start multiposition 2D xanes and 3D xanes") for i in range(repeat): print(f"\nrepeat # {i+1}") # print(f'start xanes 2D scan:') # yield from multipos_2D_xanes_scan2(eng_list, x_list_2d, y_list_2d, z_list_2d, r_list_2d, out_x, out_y, out_z, out_r, repeat_num=1, exposure_time=exposure_time, sleep_time=1, chunk_size=chunk_size, simu=False, relative_move_flag=relative_move_flag, note=note, md=None) print("\n\nstart multi 3D xanes:") yield from multi_pos_xanes_3D( eng_list, x_list_3d, y_list_3d, z_list_3d, r_list_3d, exposure_time=exposure_time, relative_rot_angle=relative_rot_angle, period=exposure_time, out_x=out_x, out_y=out_y, out_z=out_z, out_r=out_r, rs=rs, simu=False, relative_move_flag=relative_move_flag, traditional_sequence_flag=1, note=note, sleep_time=0, repeat=1, ) insert_text("finished multiposition 2D xanes and 3D xanes") export_pdf(1) Ni_eng_list_101pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Ni/eng_list_Ni_xanes_standard_101pnt.txt" ) Ni_eng_list_63pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Ni/eng_list_Ni_xanes_standard_63pnt.txt" ) Ni_eng_list_wl = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Ni/eng_list_Ni_s_xanes_standard_21pnt.txt" ) Mn_eng_list_101pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Mn/eng_list_Mn_xanes_standard_101pnt.txt" ) Mn_eng_list_63pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Mn/eng_list_Mn_xanes_standard_63pnt.txt" ) Mn_eng_list_wl = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Mn/eng_list_Mn_s_xanes_standard_21pnt.txt" ) Co_eng_list_101pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Co/eng_list_Co_xanes_standard_101pnt.txt" ) Co_eng_list_63pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Co/eng_list_Co_xanes_standard_63pnt.txt" ) Co_eng_list_wl = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Co/eng_list_Co_s_xanes_standard_21pnt.txt" ) Fe_eng_list_101pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Fe/eng_list_Fe_xanes_standard_101pnt.txt" ) Fe_eng_list_63pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Fe/eng_list_Fe_xanes_standard_63pnt.txt" ) Fe_eng_list_wl = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Fe/eng_list_Fe_s_xanes_standard_21pnt.txt" ) V_eng_list_101pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/V/eng_list_V_xanes_standard_101pnt.txt" ) V_eng_list_63pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/V/eng_list_V_xanes_standard_63pnt.txt" ) V_eng_list_wl = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/V/eng_list_V_s_xanes_standard_21pnt.txt" ) Cr_eng_list_101pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Cr/eng_list_Cr_xanes_standard_101pnt.txt" ) Cr_eng_list_63pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Cr/eng_list_Cr_xanes_standard_63pnt.txt" ) Cr_eng_list_wl = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Cr/eng_list_Cr_s_xanes_standard_21pnt.txt" ) Cu_eng_list_101pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Cu/eng_list_Cu_xanes_standard_101pnt.txt" ) Cu_eng_list_63pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Cu/eng_list_Cu_xanes_standard_63pnt.txt" ) Cu_eng_list_wl = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Cu/eng_list_Cu_s_xanes_standard_21pnt.txt" ) Zn_eng_list_101pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Zn/eng_list_Zn_xanes_standard_101pnt.txt" ) Zn_eng_list_63pnt = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Zn/eng_list_Zn_xanes_standard_63pnt.txt" ) Zn_eng_list_wl = np.genfromtxt( "/NSLS2/xf18id1/SW/xanes_ref/Zn/eng_list_Zn_s_xanes_standard_21pnt.txt" ) # def scan_3D_2D_overnight(n): # # Ni_eng_list_insitu = np.arange(8.344, 8.363, 0.001) # pos1 = [30, -933, -578] # pos2 = [-203, -1077, 563] # x_list = [pos1[0]] # y_list = [pos1[1], pos2[1]] # z_list = [pos1[2], pos2[2]] # r_list = [-71, -71] # # # # # #RE(multipos_2D_xanes_scan2(Ni_eng_list_insitu, x_list, y_list, z_list, [-40, -40], out_x=None, out_y=None, out_z=-2500, out_r=-90, repeat_num=1, exposure_time=0.1, sleep_time=1, chunk_size=5, simu=False, relative_move_flag=0, note='NC_insitu')) # # RE(mv(zps.sx, pos1[0], zps.sy, pos1[1], zps.sz, pos1[2], zps.pi_r, 0)) # RE(xanes_scan2(Ni_eng_list_insitu, exposure_time=0.1, chunk_size=5, out_x=None, out_y=None, out_z=-3000, out_r=-90, simu=False, relative_move_flag=0, note='NC_insitu') # # pos1 = [30, -929, -568] # pos_cen = [-191, -813, -563] # for i in range(5): # print(f'repeating {i+1}/{5}') # # RE(mv(zps.sx, pos1[0], zps.sy, pos1[1], zps.sz, pos1[2], zps.pi_r, -72)) # RE(xanes_3D(Ni_eng_list_insitu, exposure_time=0.1, relative_rot_angle=138, period=0.1, out_x=None, out_y=None, out_z=-3000, out_r=-90, rs=2, simu=False, relative_move_flag=0, traditional_sequence_flag=1, note='NC_insitu')) # # # RE(mv(zps.sx, pos_cen[0], zps.sy, pos_cen[1], zps.sz, pos_cen[2], zps.pi_r, 0)) # RE(raster_2D_scan(x_range=[-1,1],y_range=[-1,1],exposure_time=0.1, out_x=None, out_y=None, out_z=-3000, out_r=-90, img_sizeX=640,img_sizeY=540,pxl=80, simu=False, relative_move_flag=0,rot_first_flag=1,note='NC_insitu')) # # RE(raster_2D_xanes2(Ni_eng_list_insitu, x_range=[-1,1],y_range=[-1,1],exposure_time=0.1, out_x=None, out_y=None, out_z=-3000, out_r=-90, img_sizeX=640, img_sizeY=540, pxl=80, simu=False, relative_move_flag=0, rot_first_flag=1,note='NC_insitu')) # # RE(mv(zps.sx, pos1[0], zps.sy, pos1[1], zps.sz, pos1[2], zps.pi_r, -72)) # RE(fly_scan(exposure_time=0.1, relative_rot_angle =138, period=0.1, chunk_size=20, out_x=None, out_y=None, out_z=-3000, out_r=-90, rs=1.5, simu=False, relative_move_flag=0, traditional_sequence_flag=0, note='NC_insitu')) # # RE(bps.sleep(600)) # print('sleep for 600sec') ############################### def mono_scan_repeatibility_test(pzt_cm_bender_pos_list, pbsl_y_pos_list, eng_start, eng_end, steps, delay_time=0.5, repeat=1): for ii in range(repeat): yield from load_cell_scan(pzt_cm_bender_pos_list, pbsl_y_pos_list, 1, eng_start, eng_end, steps, delay_time=delay_time)
# Problem: https://docs.google.com/document/d/1D-3t64PnsEpcF6kKz5ZaquoMMB-r5UyYGyZzM4hjyi0/edit?usp=sharing def create_dict(): ''' Create a dictionary including the roles and their damages. ''' n = int(input('Enter the number of your party members: ')) party = {} # initialize a dictionary named party for _ in range(n): # prompt the user for the role and its damage inputs = input('Enter the role and its nominal damage (separated by a space): ').split() role = inputs[0] damage = float(inputs[1]) party[damage] = role return party def main(): ''' define main function. ''' party = create_dict() # determine the dictionary named party sorted_damage = sorted(party) # sorted the roles' damage print() # for readability # determine and display the role who attacks from front damage_front = party[sorted_damage[-1]] print('The role who attacks from front:', damage_front) # determine and display the role who attacks from one side damage_side = party[sorted_damage[-3]] print('The role who attacks from one side:', damage_side) # determine and display the role who attacks from other side damage_other_side = party[sorted_damage[-4]] print('The role who attacks from other side:', damage_other_side) # determine and display the role who attacks from back damage_back = party[sorted_damage[-2]] print('The role who attacks from back:', damage_back) # determine and display the total damaged total_damaged = sorted_damage[-1]/2 + sum(sorted_damage[-4:-2]) + sorted_damage[-2]*2 print('The total damage dealt to the cyclops by the party:', total_damaged) # call main funciton main()
class Solution: def kthGrammar(self, n: int, k: int) -> int: if n == 1: return 0 noOfBits = (2 ** (n-1) ) / 2 if k <= noOfBits: return self.kthGrammar(n-1, k) else: return int (not self.kthGrammar(n-1, k - noOfBits))
#!/usr/bin/env python3 def execute(): with open('input.12.txt') as inp: lines = inp.readlines() return sum_plant_position([l.strip() for l in lines if len(l.strip()) > 0], 20) def sum_plant_position(program, generations): state = '...' + program[0][len('initial state: '):] + '...' offset = -3 rules = dict([s.split(' => ') for s in program[2:] if s[-1] == '#']) for _ in range(generations): new_state = '..' for i in range(2, len(state) - 2): if state[i-2:i+3] in rules: if i == 2: new_state += '.' offset -= 1 new_state += '#' if i == len(state) - 3: new_state += '.' else: new_state += '.' state = new_state + '..' return sum([z[1] for z in zip(state, range(offset, len(state))) if z[0] == '#']) def verify(a, b): if (a == b): print("โœ“") return print (locals()) def test_cases(): test_input="""initial state: #..#.#..##......###...### ...## => # ..#.. => # .#... => # .#.#. => # .#.## => # .##.. => # .#### => # #.#.# => # #.### => # ##.#. => # ##.## => # ###.. => # ###.# => # ####. => #""" verify(sum_plant_position(test_input.split('\n'), 20), 325) if __name__ == "__main__": test_cases() print(execute())
# Testing def print_hi(name): print(f'Hi, {name}') # Spewcialized max function # arr = [2, 5, 6, 1, 7, 4] def my_bad_max(a_list): temp_max = 0 counter = 0 for index, num in enumerate(a_list): for other_num in a_list[0:index]: counter = counter + 1 value = num - other_num if value > temp_max: temp_max = value print(f'I\'ve itrerated {counter} times...') return temp_max def my_good_max(a_list): temp_max = 0 temp_max_value = 0 counter = 0 for value in reversed(a_list): counter = counter + 1 if value > temp_max_value: temp_max_value = value if temp_max_value - value > temp_max: temp_max = temp_max_value - value print(f'I\'ve itrerated {counter} times...') return temp_max if __name__ == '__main__': arr = [2, 5, 6, 1, 7, 4] print(my_good_max(arr))
""" # Definition for a QuadTree node. class Node: def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): self.val = val self.isLeaf = isLeaf self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft self.bottomRight = bottomRight """ class Solution: def intersect(self, quadTree1, quadTree2): """ :type quadTree1: Node :type quadTree2: Node :rtype: Node """ if quadTree1.isLeaf: return quadTree1.val and quadTree1 or quadTree2 elif quadTree2.isLeaf: return quadTree2.val and quadTree2 or quadTree1 else: topLeft = self.intersect(quadTree1.topLeft, quadTree2.topLeft) topRight = self.intersect(quadTree1.topRight, quadTree2.topRight) bottomLeft = self.intersect(quadTree1.bottomLeft, quadTree2.bottomLeft) bottomRight = self.intersect(quadTree1.bottomRight, quadTree2.bottomRight) children = [topLeft, topRight, bottomLeft, bottomRight] leaves = [child.isLeaf for child in children] values = [child.val for child in children] if all(leaves) and (sum(values) in (0, 4)): return Node(topLeft.val, True, None, None, None, None) else: return Node(False, False, topLeft, topRight, bottomLeft, bottomRight)
class ForthException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class CompileException(ForthException): pass
print('Super gerado de PA') print('-=' * 15) primeiro = int(input('Digite o termo: ')) razao = int(input('Digite a razรฃo: ')) c = 1 opรงao = '' termo = primeiro total = 0 mais = 10 while mais != 0: total = total + mais while c <= total: print(termo, 'โ†’', end=' ') termo += razao c += 1 print('Pausa') mais = int(input('Quantos termos a mais vocรช deseja? ')) print('FIM') print('Ao total foram lidos {} termos.'.format(total))
detik_input = int(input()) jam = detik_input // 3600 detik_input -= jam * 3600 menit = detik_input // 60 detik_input -= menit * 60 detik = detik_input print(jam) print(menit) print(detik)