content
stringlengths
7
1.05M
__author__ = 'roeiherz' """ Given two straight line segments (represents as a start point and end point), compute the point of intersection, if any. """ class Line: def __init__(self, point1, point2): self.point1 = point1 self.point2 = point2 self.m = self.slope() self.n = self.get_n() def slope(self): # X=5 if self.point1[0] == self.point2[0]: return None # Y=3 if self.point1[1] == self.point2[1]: return 0 # Y=mX+N return (self.point2[1] - self.point1[1]) / float(self.point2[0] - self.point1[0]) def get_n(self): if self.m is None: return None return self.point1[1] - self.m * self.point1[0] def find_intersection(line1, line2): # both lines are x=5 and x=3; no intersection if line1.m is None and line2.m is None: return None # both lines are y=5 and y=3; no intersection if line1.n is None and line2.n is None: return None # Only one of the lines is x=5; and other y=mx+n if line1.m is None: x = line1.point1[0] y = line2.m * x + line2.n return (x, y) if line2.m is None: x = line2.point1[0] y = line1.m * x + line1.n return (x, y) # Find intersection point if line2.m != line1.m: x = (line1.n - line2.n) / (line2.m - line1.m) y = line2.m * x + line2.n return (x, y) else: # Parallel return None if __name__ == '__main__': line1 = Line((5, 3), (4, 2)) line2 = Line((3, 5), (2, 4)) inter = find_intersection(line1, line2)
def sortStack(stack): if len(stack) == 0: return stack top = stack.pop() sortStack(stack) insertInSortedOrder(stack, top) return stack def insertInSortedOrder(stack, value): if len(stack) == 0 or stack[-1] <= value: stack.append(value) return top = stack.pop() insertInSortedOrder(stack, top) stack.append(top)
def safe_strftime(d, format_str='%Y-%m-%d %H:%M:%S') -> str: try: return d.strftime(format_str) except Exception: return ''
# WebSite Name WebSiteName = 'Articles Journal' ###################################################################################### # Pages __HOST = 'http://127.0.0.1:8000' ############# # Register SignUP = __HOST + '/Register/SignUP' SignUP_Template = 'Register/SignUP.html' Login = __HOST + '/Register/Login' Login_Template = 'Register/Login.html' ############# # Articles Articles = __HOST Articles_Template = 'Articles/Articles.html' MakeArticle = __HOST + '/Articles/MakeArticle' MakeArticle_Template = 'Articles/MakeArticle.html' EditArticle = __HOST + '/Articles/EditArticle/' EditArticle_Template = 'Articles/EditArticle.html' MakeOrEditSuccess_Template = 'Articles/MakeOrEditSuccess.HTML' Article = __HOST + '/Articles/Article/' Article_Template = 'Articles/Article.html' ############# # Profile Settings = __HOST + '/Profile/Settings' Settings_Template = 'Profile/Settings/Settings.html' Settings_Name_Template = 'Profile/Settings/Name.html' Settings_Password_Template = 'Profile/Settings/Password.html' Settings_Picture_Template = 'Profile/Settings/Picture.html' Settings_DeActivate_Template = 'Profile/Settings/DeActivate.html' MyProfile = __HOST + '/Profile/MyProfile' MyProfile_Template = 'Profile/MyProfile.HTML' User = __HOST + '/Profile/User/' User_Template = 'Profile/User.HTML' Notifications = __HOST + '/Profile/MyNotifications' Notifications_Template = 'Profile/MyNotifications.HTML' ############# # Services Help = __HOST + '/Services/Help' Help_Template = 'Services/Help.html' Policy = __HOST + '/Services/Policy' Policy_Template = 'Services/Policy.html' ###################################################################################### # Status Pages __StatusPages = 'StatusPages/' UnAuthurithedUserPage = __StatusPages + 'UnAuthurithedUserPage.HTML' ErrorPage = __StatusPages + 'ErrorPage.HTML' LogOutPage = __StatusPages + 'LogOutPage.HTML' NotFoundPage = __StatusPages + '404.HTML' ###################################################################################### # Messages MessageBox = 'MessageBoxs/MessageBox.html' ###################################################################################### # Picture Folder __Pictures = 'Pictures/' # Main Pictures LOGO = __Pictures + 'LOGO.JPG' OnlineUser = __Pictures + 'OnlineUser.PNG' OfflineUser = __Pictures + 'OfflineUser.PNG' AddPicture = __Pictures + 'AddPicture.PNG' NoNotification = __Pictures + 'NoNotification.PNG' Notification = __Pictures + 'Notification.PNG' Send = __Pictures + 'Send.PNG' DropDown = __Pictures + 'DropDown.PNG' ###################################################################################### # Length # Sign UP Name_Len = 40 Email_Len = 100 Password_Len = 40 Picture_Len = 40 # Make Article Article_Len = 2000 ArticleTitle_Len = 50 ArticleTags_Len = 100 # Articles id_Len = 15 # Settings Picture_Byte_Len = 2097152 # Article Comment_Len = 500 # Notifications NotificationsType_Len = 1 NotificationsMessage_Len = 300 ###################################################################################### # Layouts Base = 'Base.html' ###################################################################################### # JavaScript Folder __JavaScript = 'JavaScript/' ################# # important functions __MainScripts = __JavaScript + 'MainScripts/' JQueryScript = __MainScripts + 'jquery-3.3.1.js' BootStrapScript = __MainScripts + 'BootStrap.js' MiniBootStrapScript = __MainScripts + 'MiniBootStrap.js' DropBoxScript = __MainScripts + 'BodyLoadScript.js' JQueryRotateScript = __MainScripts + 'JQueryRotate.js' #################### # Global Functions __Global_Scripts = __JavaScript + 'GlobalFunctions/' CheckLenScript = __Global_Scripts + 'CheckLen.js' CheckinputLenScript = __Global_Scripts + 'CheckinputLen.js' CheckPasswordScript = __Global_Scripts + 'CheckPassword.js' CheckPatternScript = __Global_Scripts + 'CheckPattern.js' TrigerMessageScript = __Global_Scripts + 'TriggerMessage.js' ErrorFunctionScript = __Global_Scripts + 'SetError_Function.js' AddPictureScript = __Global_Scripts + 'AddPicture.js' TrigerFormScript = __Global_Scripts + 'TriggerForm.js' CheckNameScript = __Global_Scripts + 'CheckName.js' ################### # Pages Scripts PagesScripts = __JavaScript + 'PagesScripts/' ###################################################################################### # CSS Folder __CSS = 'CSS/' # Main CSS Folders __MainCSS = __CSS + 'MainCSS/' AllPagesCSS = __MainCSS + 'AllPagesCSS.CSS' # Boot Strap BootStrapCSS = __MainCSS + 'BootStrap/bootstrap.css' MiniBootStrapCSS = __MainCSS + 'BootStrap/bootstrap.min.css' ################### # Pages CSS PagesCSS = __CSS + 'PagesCSS/' ###################################################################################### # BackEnd Pages __BackEnd = __HOST + '/BackEnd/' CheckName = __BackEnd + 'CheckName' CheckEmail = __BackEnd + 'CheckEmail' LogOut = __BackEnd + 'LogOut' GetPosts = __BackEnd + 'GetPosts' MakeCommentPage = __BackEnd + 'MakeComment' LikeDisLikePostPage = __BackEnd + 'LikeDisLikePost' DeletePostPage = __BackEnd + 'DeletePost' GetNotificationsPage = __BackEnd + 'GetNotifications' ###################################################################################### # Small Headers __Headers = 'Headers/' ################## __BasicHeaders = __Headers + 'BasicHeaders/' NavBar = __BasicHeaders + 'NavBar.html' UserLogged = __BasicHeaders + 'UserLogged.html' UserNotLogged = __BasicHeaders + 'UserNotLogged.html' Notifications_Header = __BasicHeaders + 'Notifications_Header.HTML' Header = __Headers + 'Header.html' def GetLinks(String): Links = [] while True: Start = String.find('[') if Start == -1: return String = String[Start:] End = String.find(']') if End == -1: return Text = String[:End+1] String = String[End+1:] for i in range(len(String)): if String[i] != ' ': if String[i] != '(': return else: String = String[i:] break Start = String.find('(') if Start == -1: return String = String[Start:] End = String.find(')') if End == -1: return Link = String[:End+1] String = String[End+1:] Links.append([Text, Link]) Test = 'My Link is ss[Hady] (http://findhouse.com) . i (Am) [Here] (Because ) Of You' Test2 = '[My Link is (HAHAHA)(] ( )' Test3 = '' GetLinks(Test3)
def compute_opt(exact_filename, preprocessing_filename): datasets = set() # Dataset names exact_solution_lookup = {} # Maps dataset names to OPT with open(exact_filename, 'r') as infile: # Discard header infile.readline() for line in infile.readlines(): line = line.split(',') if line[1] == 'ilp': datasets.add(line[0]) exact_solution_lookup[line[0]] = int(line[3]) oct_removed_lookup = {} # Maps dataset names to V_o with open(preprocessing_filename, 'r') as infile: # Discard header infile.readline() for line in infile.readlines(): line = line.split(',') oct_removed_lookup[line[0]] = int(line[5]) before_oct_lookup = {} # Maps dataset names to OCT on raw data for dataset in datasets: before_oct_lookup[dataset] = exact_solution_lookup[dataset] +\ oct_removed_lookup[dataset] clusters = ['aa-er', 'aa-cl', 'aa-ba', 'aa-to', 'j-er', 'j-cl', 'j-ba', 'j-to', 'b-50-er', 'b-50-cl', 'b-50-ba', 'b-50-to', 'b-100-er', 'b-100-cl', 'b-100-ba', 'b-100-to', 'gka-er', 'gka-cl', 'gka-ba', 'gka-to'] oct_before = {} # clustered by dataset oct_after = {} print(before_oct_lookup) for cluster in clusters: oct_before[cluster] = [] oct_after[cluster] = [] for dataset in datasets: if 'aa' in dataset: if '-er' in dataset: oct_before['aa-er'].append(before_oct_lookup[dataset]) oct_after['aa-er'].append(exact_solution_lookup[dataset]) elif '-cl' in dataset: oct_before['aa-cl'].append(before_oct_lookup[dataset]) oct_after['aa-cl'].append(exact_solution_lookup[dataset]) elif '-ba' in dataset: oct_before['aa-ba'].append(before_oct_lookup[dataset]) oct_after['aa-ba'].append(exact_solution_lookup[dataset]) elif '-to' in dataset: oct_before['aa-to'].append(before_oct_lookup[dataset]) oct_after['aa-to'].append(exact_solution_lookup[dataset]) elif 'j' in dataset: if '-er' in dataset: oct_before['j-er'].append(before_oct_lookup[dataset]) oct_after['j-er'].append(exact_solution_lookup[dataset]) elif '-cl' in dataset: oct_before['j-cl'].append(before_oct_lookup[dataset]) oct_after['j-cl'].append(exact_solution_lookup[dataset]) elif '-ba' in dataset: oct_before['j-ba'].append(before_oct_lookup[dataset]) oct_after['j-ba'].append(exact_solution_lookup[dataset]) elif '-to' in dataset: oct_before['j-to'].append(before_oct_lookup[dataset]) oct_after['j-to'].append(exact_solution_lookup[dataset]) elif 'b-50' in dataset: if '-er' in dataset: oct_before['b-50-er'].append(before_oct_lookup[dataset]) oct_after['b-50-er'].append(exact_solution_lookup[dataset]) elif '-cl' in dataset: oct_before['b-50-cl'].append(before_oct_lookup[dataset]) oct_after['b-50-cl'].append(exact_solution_lookup[dataset]) elif '-ba' in dataset: oct_before['b-50-ba'].append(before_oct_lookup[dataset]) oct_after['b-50-ba'].append(exact_solution_lookup[dataset]) elif '-to' in dataset: oct_before['b-50-to'].append(before_oct_lookup[dataset]) oct_after['b-50-to'].append(exact_solution_lookup[dataset]) elif 'b-100' in dataset: if '-er' in dataset: oct_before['b-100-er'].append(before_oct_lookup[dataset]) oct_after['b-100-er'].append(exact_solution_lookup[dataset]) elif '-cl' in dataset: oct_before['b-100-cl'].append(before_oct_lookup[dataset]) oct_after['b-100-cl'].append(exact_solution_lookup[dataset]) elif '-ba' in dataset: oct_before['b-100-ba'].append(before_oct_lookup[dataset]) oct_after['b-100-ba'].append(exact_solution_lookup[dataset]) elif '-to' in dataset: oct_before['b-100-to'].append(before_oct_lookup[dataset]) oct_after['b-100-to'].append(exact_solution_lookup[dataset]) elif 'gka' in dataset: if '-er' in dataset: oct_before['gka-er'].append(before_oct_lookup[dataset]) oct_after['gka-er'].append(exact_solution_lookup[dataset]) elif '-cl' in dataset: oct_before['gka-cl'].append(before_oct_lookup[dataset]) oct_after['gka-cl'].append(exact_solution_lookup[dataset]) elif '-ba' in dataset: oct_before['gka-ba'].append(before_oct_lookup[dataset]) oct_after['gka-ba'].append(exact_solution_lookup[dataset]) elif '-to' in dataset: oct_before['gka-to'].append(before_oct_lookup[dataset]) oct_after['gka-to'].append(exact_solution_lookup[dataset]) print(oct_after) for cluster in clusters: try: print('{} before'.format(cluster), min(oct_before[cluster]), max(oct_before[cluster])) print('{} after:'.format(cluster), min(oct_after[cluster]), max(oct_after[cluster])) except: pass if __name__ == "__main__": compute_opt('results/exact_results.csv', 'results/final_preprocessing.csv')
brd = { 'name': ('StickIt! MPU-9150 V1'), 'port': { 'pmod': { 'default' : { 'scl': 'd1', 'clkin': 'd2', 'sda': 'd3', 'int': 'd5', 'fsync': 'd7' } }, 'wing': { 'default' : { 'scl': 'd0', 'clkin': 'd3', 'sda': 'd2', 'int': 'd5', 'fsync': 'd7' } } } }
def for_K(): """ Upper case Alphabet letter 'K' pattern using Python Python for loop""" for row in range(6): for col in range(4): if col==0 or row+col==3 or row-col==2: print('*', end = ' ') else: print(' ', end = ' ') print() def while_K(): """ Upper case Alphabet letter 'K' pattern using Python Python while loop""" row = 0 while row<6: col = 0 while col<4: if col==0 or row+col==3 or row-col==2: print('*', end = ' ') else: print(' ', end = ' ') col += 1 print() row += 1
class BlockTerminationNotice(Exception): pass class IncorrectLocationException(Exception): pass class SootMethodNotLoadedException(Exception): pass class SootFieldNotLoadedException(Exception): pass
class TipoCadastro: nomeC = '' dataN = '' tel = 0 ender = '' serie = 0 def menu(): vetAluno = [] while True: print('__'*30) print('Menu de opções:') print('1.Cadastrar alunos') print('2.Consulta por nome') print('3.Visualizar todos os dados') print('4.Sair') comando = int(input('Informe a opção: ')) if comando == 1: cadastro(vetAluno) elif comando == 2: consulta(vetAluno) elif comando == 3: visuTodDados(vetAluno) elif comando == 4: print('Saída efetuada') break else: print('Opção inválida') def consulta(vetAluno): consultaA = input('Informe o nome completo do aluno: ') for i in range(len(vetAluno)): if vetAluno[i].nomeC == consultaA: print('__'*30) print('Nome: {}\nData de nascimento: {}\nTelefone: {}\nEndereço: {}\nSérie: {}'.format(vetAluno[i].nomeC, vetAluno[i].dataN, vetAluno[i].tel, vetAluno[i].ender, vetAluno[i].serie)) print('__'*30) else: print('__'*30) print('Aluno não encontrado') print('__'*30) def visuTodDados(vetAluno): for i in range(len(vetAluno)): print('__'*30) print('Nome: {}\nData de nascimento: {}\nTelefone: {}\nEndereço: {}\nSérie: {}'.format(vetAluno[i].nomeC, vetAluno[i].dataN, vetAluno[i].tel, vetAluno[i].ender, vetAluno[i].serie)) print('__'*30) def cadastro(vetAluno): CA = TipoCadastro() CA.nomeC = input('Nome completo do aluno: ') CA.dataN = input('Data de nascimento: ') CA.tel = int(input('Telefone: ')) CA.ender = input('Endereço: ') CA.serie = int(input('Série(número): ')) vetAluno.append(CA) return vetAluno def main(): menu() main()
# description: various useful helpers class DataKeys(object): """standard names for features and transformations of features """ # core data keys FEATURES = "features" LABELS = "labels" PROBABILITIES = "probs" LOGITS = "logits" LOGITS_NORM = "{}.norm".format(LOGITS) ORIG_SEQ = "sequence" SEQ_METADATA = "example_metadata" # ensembles LOGITS_MULTIMODEL = "{}.multimodel".format(LOGITS) LOGITS_MULTIMODEL_NORM = "{}.norm".format(LOGITS_MULTIMODEL) LOGITS_CI = "{}.ci".format(LOGITS) LOGITS_CI_THRESH = "{}.thresh".format(LOGITS_CI) # playing with feature transforms HIDDEN_LAYER_FEATURES = "{}.nn_transform".format(FEATURES) # for feature importance extraction IMPORTANCE_ANCHORS = "anchors" IMPORTANCE_GRADIENTS = "gradients" WEIGHTED_SEQ = "{}-weighted".format(ORIG_SEQ) WEIGHTED_SEQ_THRESHOLDS = "{}.thresholds".format(WEIGHTED_SEQ) # clipping ORIG_SEQ_ACTIVE = "{}.active".format(ORIG_SEQ) ORIG_SEQ_ACTIVE_STRING = "{}.string".format(ORIG_SEQ_ACTIVE) WEIGHTED_SEQ_ACTIVE = "{}.active".format(WEIGHTED_SEQ) GC_CONTENT = "{}.gc_fract".format(ORIG_SEQ_ACTIVE) WEIGHTED_SEQ_ACTIVE_CI = "{}.ci".format(WEIGHTED_SEQ_ACTIVE) WEIGHTED_SEQ_ACTIVE_CI_THRESH = "{}.thresh".format(WEIGHTED_SEQ_ACTIVE_CI) WEIGHTED_SEQ_MULTIMODEL = "{}.multimodel".format(WEIGHTED_SEQ_ACTIVE) # for shuffles (generated for null models) SHUFFLE_SUFFIX = "shuffles" ACTIVE_SHUFFLES = SHUFFLE_SUFFIX ORIG_SEQ_SHUF = "{}.{}".format(ORIG_SEQ, SHUFFLE_SUFFIX) WEIGHTED_SEQ_SHUF = "{}.{}".format(WEIGHTED_SEQ, SHUFFLE_SUFFIX) ORIG_SEQ_ACTIVE_SHUF = "{}.{}".format(ORIG_SEQ_ACTIVE, SHUFFLE_SUFFIX) WEIGHTED_SEQ_ACTIVE_SHUF = "{}.{}".format(WEIGHTED_SEQ_ACTIVE, SHUFFLE_SUFFIX) LOGITS_SHUF = "{}.{}".format(LOGITS, SHUFFLE_SUFFIX) # pwm transformation keys PWM_SCORES_ROOT = "pwm-scores" ORIG_SEQ_PWM_HITS = "{}.pwm-hits".format(ORIG_SEQ_ACTIVE) ORIG_SEQ_PWM_HITS_COUNT = "{}.count".format(ORIG_SEQ_PWM_HITS) ORIG_SEQ_PWM_SCORES = "{}.{}".format(ORIG_SEQ_ACTIVE, PWM_SCORES_ROOT) ORIG_SEQ_PWM_SCORES_THRESH = "{}.thresh".format(ORIG_SEQ_PWM_SCORES) ORIG_SEQ_PWM_SCORES_THRESHOLDS = "{}.thresholds".format(ORIG_SEQ_PWM_SCORES) ORIG_SEQ_PWM_SCORES_SUM = "{}.sum".format(ORIG_SEQ_PWM_SCORES_THRESH) ORIG_SEQ_SHUF_PWM_SCORES = "{}.{}".format(ORIG_SEQ_ACTIVE_SHUF, PWM_SCORES_ROOT) ORIG_SEQ_PWM_DENSITIES = "{}.densities".format(ORIG_SEQ_PWM_HITS) ORIG_SEQ_PWM_MAX_DENSITIES = "{}.max".format(ORIG_SEQ_PWM_DENSITIES) WEIGHTED_SEQ_PWM_HITS = "{}.pwm-hits".format(WEIGHTED_SEQ_ACTIVE) WEIGHTED_SEQ_PWM_HITS_COUNT = "{}.count".format(WEIGHTED_SEQ_PWM_HITS) WEIGHTED_SEQ_PWM_SCORES = "{}.{}".format(WEIGHTED_SEQ_ACTIVE, PWM_SCORES_ROOT) WEIGHTED_SEQ_PWM_SCORES_THRESH = "{}.thresh".format(WEIGHTED_SEQ_PWM_SCORES) WEIGHTED_SEQ_PWM_SCORES_THRESHOLDS = "{}.thresholds".format(WEIGHTED_SEQ_PWM_SCORES) WEIGHTED_SEQ_PWM_SCORES_SUM = "{}.sum".format(WEIGHTED_SEQ_PWM_SCORES_THRESH) # CHECK some downstream change here WEIGHTED_SEQ_SHUF_PWM_SCORES = "{}.{}".format(WEIGHTED_SEQ_ACTIVE_SHUF, PWM_SCORES_ROOT) # pwm positions ORIG_PWM_SCORES_POSITION_MAX_VAL = "{}.max.val".format(ORIG_SEQ_PWM_SCORES_THRESH) ORIG_PWM_SCORES_POSITION_MAX_IDX = "{}.max.idx".format(ORIG_SEQ_PWM_SCORES_THRESH) WEIGHTED_PWM_SCORES_POSITION_MAX_VAL = "{}.max.val".format(WEIGHTED_SEQ_PWM_SCORES_THRESH) WEIGHTED_PWM_SCORES_POSITION_MAX_IDX = "{}.max.idx".format(WEIGHTED_SEQ_PWM_SCORES_THRESH) WEIGHTED_PWM_SCORES_POSITION_MAX_VAL_MUT = "{}.max.val.motif_mut".format(WEIGHTED_SEQ_PWM_SCORES_THRESH) WEIGHTED_PWM_SCORES_POSITION_MAX_IDX_MUT = "{}.max.idx.motif_mut".format(WEIGHTED_SEQ_PWM_SCORES_THRESH) NULL_PWM_POSITION_INDICES = "{}.null.idx".format(PWM_SCORES_ROOT) # significant pwms PWM_DIFF_GROUP = "pwms.differential" PWM_PVALS = "pwms.pvals" PWM_SIG_ROOT = "pwms.sig" PWM_SIG_GLOBAL = "{}.global".format(PWM_SIG_ROOT) PWM_SCORES_AGG_GLOBAL = "{}.agg".format(PWM_SIG_GLOBAL) PWM_SIG_CLUST = "{}.clusters".format(PWM_SIG_ROOT) PWM_SIG_CLUST_ALL = "{}.all".format(PWM_SIG_CLUST) PWM_SCORES_AGG_CLUST = "{}.agg".format(PWM_SIG_CLUST_ALL) # manifold keys MANIFOLD_ROOT = "manifold" MANIFOLD_CENTERS = "{}.centers".format(MANIFOLD_ROOT) MANIFOLD_THRESHOLDS = "{}.thresholds".format(MANIFOLD_ROOT) MANIFOLD_CLUST = "{}.clusters".format(MANIFOLD_ROOT) MANIFOLD_SCORES = "{}.scores".format(MANIFOLD_ROOT) # manifold sig pwm keys MANIFOLD_PWM_ROOT = "{}.pwms".format(MANIFOLD_ROOT) MANIFOLD_PWM_SIG_GLOBAL = "{}.global".format(MANIFOLD_PWM_ROOT) MANIFOLD_PWM_SCORES_AGG_GLOBAL = "{}.agg".format(MANIFOLD_PWM_SIG_GLOBAL) MANIFOLD_PWM_SIG_CLUST = "{}.clusters".format(MANIFOLD_PWM_ROOT) MANIFOLD_PWM_SIG_CLUST_ALL = "{}.all".format(MANIFOLD_PWM_SIG_CLUST) MANIFOLD_PWM_SCORES_AGG_CLUST = "{}.agg".format(MANIFOLD_PWM_SIG_CLUST_ALL) # cluster keys CLUSTERS = "clusters" # dfim transformation keys MUT_MOTIF_ORIG_SEQ = "{}.motif_mut".format(ORIG_SEQ) MUT_MOTIF_WEIGHTED_SEQ = "{}.motif_mut".format(WEIGHTED_SEQ) MUT_MOTIF_POS = "{}.pos".format(MUT_MOTIF_ORIG_SEQ) MUT_MOTIF_MASK = "{}.mask".format(MUT_MOTIF_ORIG_SEQ) MUT_MOTIF_PRESENT = "{}.motif_mut_present".format(ORIG_SEQ) MUT_MOTIF_LOGITS = "{}.motif_mut".format(LOGITS) MUT_MOTIF_LOGITS_SIG = "{}.motif_mut.sig".format(LOGITS) DFIM_SCORES = "{}.delta".format(MUT_MOTIF_WEIGHTED_SEQ) DFIM_SCORES_DX = "{}.delta.dx".format(MUT_MOTIF_WEIGHTED_SEQ) MUT_MOTIF_WEIGHTED_SEQ_CI = "{}.ci".format(MUT_MOTIF_WEIGHTED_SEQ) MUT_MOTIF_WEIGHTED_SEQ_CI_THRESH = "{}.thresh".format(MUT_MOTIF_WEIGHTED_SEQ_CI) MUT_MOTIF_LOGITS_MULTIMODEL = "{}.multimodel".format(MUT_MOTIF_LOGITS) # dmim agg results keys DMIM_SCORES = "dmim.motif_mut.scores" DMIM_SCORES_SIG = "{}.sig".format(DMIM_SCORES) DMIM_DIFF_GROUP = "dmim.differential" DMIM_PVALS = "dmim.pvals" DMIM_SIG_ROOT = "dmim.sig" DMIM_SIG_ALL = "{}.all".format(DMIM_SIG_ROOT) DMIM_ROOT = "{}.{}".format(DFIM_SCORES, PWM_SCORES_ROOT) DMIM_SIG_RESULTS = "{}.agg.sig".format(DMIM_ROOT) # grammar keys GRAMMAR_ROOT = "grammar" GRAMMAR_LABELS = "{}.labels".format(GRAMMAR_ROOT) # synergy keys SYNERGY_ROOT = "synergy" SYNERGY_SCORES = "{}.scores".format(SYNERGY_ROOT) SYNERGY_DIFF = "{}.diff".format(SYNERGY_SCORES) SYNERGY_DIFF_SIG = "{}.sig".format(SYNERGY_DIFF) SYNERGY_DIST = "{}.dist".format(SYNERGY_ROOT) SYNERGY_MAX_DIST = "{}.max".format(SYNERGY_DIST) # variant keys VARIANT_ROOT = "variants" VARIANT_ID = "{}.id.string".format(VARIANT_ROOT) VARIANT_INFO = "{}.info.string".format(VARIANT_ROOT) VARIANT_IDX = "{}.idx".format(VARIANT_ROOT) VARIANT_DMIM = "{}.dmim".format(VARIANT_ROOT) VARIANT_SIG = "{}.sig".format(VARIANT_ROOT) VARIANT_IMPORTANCE = "{}.impt_score".format(VARIANT_ROOT) # split TASK_IDX_ROOT = "taskidx" class MetaKeys(object): """standard names for metadata keys """ REGION_ID = "region" ACTIVE_ID = "active" FEATURES_ID = "features" class ParamKeys(object): """standard names for params""" # tensor management AUX_ROOT = "{}.aux".format(DataKeys.FEATURES) NUM_AUX = "{}.num".format(AUX_ROOT)
class Corner(object): def __init__(self, row, column, lines): self.row = row self.column = column self.lines = lines self.done = False for line in self.lines: line.add_corner(self) self.line_number = None def check_values(self): if self.done: return empty = 0 full = 0 for line in self.lines: if line.is_full: full += 1 if line.is_empty: empty += 1 print(self.row, self.column, full, empty, len(self.lines)) if full + empty == len(self.lines): return False if full == 2: print("two lines so other empty") for line in self.lines: if not line.is_full: line.set_empty() else: print("skip ", line.column, line.row, line.horizontal) self.done = True return True elif full == 1: if len(self.lines) - empty == 2: print("One line and one option") for line in self.lines: if not line.is_empty: line.set_full() self.done = True return True else: if len(self.lines) - empty == 1: print("only one still empty") for line in self.lines: if not line.is_full: line.set_empty() self.done = True return True return False
#Table used for the example 2split.py ################################################################################################# source_path = "/home/user/Scrivania/Ducks/"# Where the images are output_path = "/home/user/Scrivania/Ducks/"# Where the two directory with the cutted images will be stored RIGHT_CUT_DIR_NAME = "right_duck" #Name of the directory thay contains the right cuts LEFT_CUT_DIR_NAME = "left_duck" #Name of the directory thay contains the left cuts LEFT_PREFIX = "left_quacky" #Prefix for left cuts RIGHT_PREFIX = "right_quacky" #Prefix for right cuts #################################################################################################
''' Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: A) Quantos números foram digitados. B) A lista de valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado e está ou não na lista. ''' num = [] while True: num.append(int(input('Digite um número: '))) escolha = str(input('Deseja continuar? [S/N] ')).strip().upper() if escolha in 'Nn': break print('=-' * 30) print(f'Foram digitados {len(num)} números!') num.sort(reverse=True) print(f'A lista de valores em ordem decrescente são: {num}') if 5 in num: print('O número 5 faz parte da lista!') else: print('O número 5 NÃO faz parte da lista!') print('=-' * 30)
def logic(value, a, b): if value: return a return b hero.moveXY(20, 24); a = hero.findNearestFriend().getSecretA() b = hero.findNearestFriend().getSecretB() c = hero.findNearestFriend().getSecretC() hero.moveXY(30, logic(a and b and c, 33, 15)) hero.moveXY(logic(a or b or c, 20, 40), 24) hero.moveXY(30, logic(a and b and c, 33, 15))
def a(mem): seen = set() tup = tuple(mem) count = 0 while tup not in seen: seen.add(tup) index = 0 max = 0 for i in range(len(mem)): n = mem[i] if(n > max): max = n index = i mem[index] = 0 index += 1 while(max > 0): mem[index%len(mem)] += 1 max -= 1 index += 1 count += 1 tup = tuple(mem) return count def b(mem): seen = [] tup = tuple(mem) count = 0 while tup not in seen: seen.append(tup) index = 0 max = 0 for i in range(len(mem)): n = mem[i] if(n > max): max = n index = i mem[index] = 0 index += 1 while(max > 0): mem[index%len(mem)] += 1 max -= 1 index += 1 count += 1 tup = tuple(mem) return count - seen.index(tup) with open("input.txt") as f: nums = [int(x.strip()) for x in f.read().split("\t")] print("Part A:", a(nums)) with open("input.txt") as f: nums = [int(x.strip()) for x in f.read().split("\t")] print("Part B:", b(nums))
def mergeSort(l): if len(l) > 1: mid = len(l) // 2 L = l[:mid] R = l[mid:] mergeSort(L) mergeSort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: l[k] = L[i] i += 1 else: l[k] = R[j] j += 1 k += 1 while i < len(L): l[k] = L[i] i += 1 k += 1 while j < len(R): l[k] = R[j] j += 1 k += 1 l = [8, 7, 12, 10, 2, 999, 45] print(l) mergeSort(l) print(l)
class Solution: def minAbbreviation(self, target: str, dictionary: List[str]) -> str: m = len(target) def getMask(word: str) -> int: # mask[i] = 0 := target[i] == word[i] # mask[i] = 1 := target[i] != word[i] # e.g. target = "apple" # word = "blade" # mask = 11110 mask = 0 for i, c in enumerate(word): if c != target[i]: mask |= 1 << m - 1 - i return mask masks = [getMask(word) for word in dictionary if len(word) == m] if not masks: return str(m) abbrs = [] def getAbbr(cand: int) -> str: abbr = '' replacedCount = 0 for i, c in enumerate(target): if cand >> m - 1 - i & 1: # cand[i] = 1, abbr should show the original character if replacedCount: abbr += str(replacedCount) abbr += c replacedCount = 0 else: # cand[i] = 0, abbr can be replaced replacedCount += 1 if replacedCount: abbr += str(replacedCount) return abbr # for all candidate representation of target for cand in range(2**m): # all masks have at lease one bit different from candidate if all(cand & mask for mask in masks): abbr = getAbbr(cand) abbrs.append(abbr) def getAbbrLen(abbr: str) -> int: abbrLen = 0 i = 0 j = 0 while i < len(abbr): if abbr[j].isalpha(): j += 1 else: while j < len(abbr) and abbr[j].isdigit(): j += 1 abbrLen += 1 i = j return abbrLen return min(abbrs, key=lambda x: getAbbrLen(x))
#! python3 # __author__ = "YangJiaHao" # date: 2018/2/8 class Solution: def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if len(digits) <= 0: return [] keys = [[''], [''], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r', 's'], ['t', 'u', 'v'], ['w', 'x', 'y', 'z']] result = [""] for i in digits: temp = [] for one in result: for w in keys[int(i)]: temp.append(one + w) result = temp return result class Solution2: def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ result = [] if len(digits) == 0: return result result = [''] string = [[], [], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r', 's'], ['t', 'u', 'v'], ['w', 'x', 'y', 'z']] for c in digits: tmp = [] for c1 in result: for c2 in string[int(c)]: tmp.append(c1 + c2) result = tmp return result if __name__ == '__main__': so = Solution2() ret = so.letterCombinations("234") print(ret)
{ "targets": [ { "target_name": "example", "sources": [ "example.cxx", "example_wrap.cxx" ] } ] }
'''exemplo1''' print('Olá Mundo') print(5 + 10) print('5'+'10') '''#exemplo2''' print('Olá Mundo', 10) '''#exemplo3''' nome = 'Xand_LIn' idade = 20 peso = 55 print('Nome:', nome, '\nidade:', idade, '\nPeso:', peso) '''#exemplo4''' nome1 = input('Qual é o seu nome?: ') idade1 = input('Sua idade?: ') peso1 = input('Qual é seu peso?: ') print(nome1, idade1, peso1) '''#exemplo5''' nome2 = input('Qual é o seu nome?: ') print('Olá', nome2, 'Seja Bem Vindo') resposta = input('Você esta bem?: ') if resposta == 'não' or resposta == 'Não': resposta = input('Posso te ajudar e algo?: ') if resposta == 'não' or 'Não': print('Que pena acontence \nvai dormir deve melhorar') else: print('Que ótimo, vai estudar') '''#exemplo6''' print('Dgite sua Data de Nascimento:') dia = input('Dia: ') mes = input('Mês: ') ano = input('Ano: ') print('Data de Nascimento: ', dia, '/', mes, '/', ano) '''#exemplo7''' soma = int(input('Digite o primeiro numero: ')) soma1 = int(input('Digite o segundo numero: ')) print('Soma: ', soma+soma1)
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Solution to programming exercises 6.1 Q2 # Purpose: A program to find the GCD of any two positive integers # Determines if one number is a factor of the other def isFactor(a1, a2): if a2 % a1 == 0: return True else: return False # Returns a list containing all the factors of n def getFactors(n): factors = [] for i in range(1, n+1): if isFactor(i, n): factors.append(i) return factors # Returns the greatest common divisor # This is the largest number that is common to both lists def gcd(l1, l2): # sets don't contain duplicates set1 = set(l1) set2 = set(l2) common_factors = set1.intersection(set2) # set1 & set2 return(max(common_factors)) # Main program n1 = int(input("Enter the first number: ")) n2 = int(input("Enter the second number: ")) list_of_factors1 = getFactors(n1) list_of_factors2 = getFactors(n2) ans = gcd(list_of_factors1, list_of_factors2) print("The GCD of %d and %d is %d" %(n1, n2, ans)) ''' # Alternative solution def gcd(a, b): while b: a, b = b, a % b print(a) gcd(27, 63) '''
assert format(5, "b") == "101" try: format(2, 3) except TypeError: pass else: assert False, "TypeError not raised when format is called with a number"
#!/usr/bin/env python3 names = ['Alice', 'Bob', 'John'] for name in names: print(name)
''' Exception classes for cr-vision library ''' # Definitive guide to Python exceptions https://julien.danjou.info/python-exceptions-guide/ class CRVError(Exception): '''Base exception class''' class InvalidNumDimensionsError(CRVError): '''Invalid number of dimensions error''' class InvalidNumChannelsError(CRVError): ''' Invalid number of channels error''' def __init__(self, expected_channels, actual_channels): message = 'Invalid number of channels. Expected: {}, Actual: {}'.format( expected_channels, actual_channels) super().__init__(message) class NotU8C1Error(CRVError): '''Image is not grayscale 8 bit unsigned''' class NotU8C3Error(CRVError): '''Image is not 8 bit unsigned 3 channel color image''' class UnsupportedImageFormatError(CRVError): """Unsupported image format""" def check_ndim(actual_ndim, expected_min_ndim=None, expected_max_ndim=None): ''' Checks if the number of dimensions is correct''' message = None if expected_min_ndim is not None and expected_max_ndim is not None: if expected_min_ndim == expected_max_ndim: if actual_ndim != expected_min_ndim: message = 'Invalid number of dimensions. Expected: {}, Actual: {}'.format( expected_min_ndim, actual_ndim) else: if actual_ndim < expected_min_ndim or actual_ndim > expected_max_ndim: message = 'Invalid dimensions. Expected between: {}-{}, Actual: {}'.format( expected_min_ndim, expected_max_ndim, actual_ndim) elif expected_min_ndim is not None: if actual_ndim < expected_min_ndim: message = 'Expected Minimum: {}, Actual: {}'.format( expected_min_ndim, actual_ndim) elif expected_max_ndim is not None: if actual_ndim > expected_max_ndim: message = 'Expected Maximum: {}, Actual: {}'.format( expected_max_ndim, actual_ndim) if message is not None: raise InvalidNumDimensionsError(message) def check_nchannels(expected_channels, actual_channels): '''Checks if number of channels is correct''' if actual_channels != expected_channels: raise InvalidNumChannelsError(expected_channels, actual_channels) def check_u8c1(image): '''Checks that the image is an unsigned 8 bit image with one channel''' if image.dtype != 'uint8': raise NotU8C1Error('The image data type is not unsigned 8 bit') if image.ndim == 1: raise NotU8C1Error('It is a vector. Expected an image.') elif image.ndim == 2: # all good pass elif image.ndim == 3: if image.shape[2] != 1: raise NotU8C1Error('Image has more than one channels') else: raise NotU8C1Error('Invalid dimensions') def check_u8c3(image): '''Chcecks that the image is an unsigned 8 bit image with 3 channels''' if image.dtype != 'uint8': raise NotU8C3Error('The image data type is not unsigned 8 bit') if image.ndim != 3: raise NotU8C3Error('Image must have 3 dimensions') if image.shape[2] != 3: raise NotU8C3Error('Image must have 3 channels') def error_unsupported_image_format(format=None): """Raises UnsupportedImageFormatError exception""" if format is None: raise UnsupportedImageFormatError("Unsupported image format") message = "Unsupported image format: {}".format(format) raise UnsupportedImageFormatError(message)
# 存在安全风险 doc_title_html_tag = '<div class="doc_title">{}</div>' doc_info_html_tag = '<div class="doc_info">{}</div>' doc_body_html_tag = '<div class="doc_line"">{}</div>' doc_empty_lint_tag = '<div style="height: 10pt;"></div>' class LegalDoc(object): def __init__(self, title: str = None, court: str = None, case_num: str = None, case_type: str = None, case_body: list = None, judge_date:str = None,judges: list = None, tail:list = None) -> None: super().__init__() self.title = title self.court = court self.case_num = case_num self.case_type = case_type self.case_body = case_body self.judges = judges self.judge_date = judge_date self.tail = tail def read_from_str(self, text_str) -> bool: text_list = text_str.split("\n") if len(text_list) < 4: return False self.title = text_list[0] self.court = text_list[1] self.case_type = text_list[2] self.case_num = text_list[3] self.case_body = [] self.judges = [] self.judge_date = "" self.tail = [] bk = 0 for x in range(4, len(text_list)): t = text_list[x] if is_judge(t): bk = x break self.case_body.append(t) bk = bk if bk > 0 else len(text_list) for x in range(bk, len(text_list)): t = text_list[x] if "年" in t and "月" in t and "日" in t: bk = x + 1 self.judge_date = t break self.judges.append(t) for x in range(bk, len(text_list)): t = text_list[x] self.tail.append(t) return True def to_dict(self) -> dict: return { "title": self.title, "court": self.court, "case_num": self.case_num, "case_type": self.case_type, "case_body": self.case_body, "judges": self.judges, "judge_date": self.judge_date, "tail":self.tail } def html_generate(self) -> str: """ 可能导致前端被注入恶意代码,仅用于流程记录,页面测试用 """ html_str = "" if not (self.title and self.court and self.case_num and self.case_type): return "" html_str += doc_title_html_tag.format(self.title) html_str += doc_info_html_tag.format(self.court) html_str += doc_info_html_tag.format(self.case_type) html_str += doc_info_html_tag.format(self.case_num) for x in range(4, len(self.case_body)): html_str += doc_body_html_tag.format(self.case_body[x]) return html_str def is_judge(s:str) -> bool: if ("审 判 长 " in s or "审判长 " in s or "审 判 员 " in s or "审判员 " in s or "审\u3000判\u3000长 " in s or "审判长 " in s or "审\u3000判\u3000员 " in s or "审判员 " in s or "审 判 长\u3000" in s or "审判长\u3000" in s or "审 判 员\u3000" in s or "审判员\u3000" in s or "审\u3000判\u3000长\u3000" in s or "审判长\u3000" in s or "审\u3000判\u3000员\u3000" in s or "审判员\u3000" in s or "审\u3000判\u3000长\t" in s or "审判长\t" in s or "审\u3000判\u3000员\t" in s or "审判员\t" in s or "审 判 长\t" in s or "审判长\t" in s or "审 判 员\t" in s or "审判员\t" in s): return True else: return False
# pylint: disable=too-many-instance-attributes # number of attributes is reasonable in this case class Skills: def __init__(self): self.acrobatics = Skill() self.animal_handling = Skill() self.arcana = Skill() self.athletics = Skill() self.deception = Skill() self.history = Skill() self.insight = Skill() self.intimidation = Skill() self.investigation = Skill() self.medicine = Skill() self.nature = Skill() self.perception = Skill() self.performance = Skill() self.persuasion = Skill() self.religion = Skill() self.sleight_of_hand = Skill() self.stealth = Skill() self.survival = Skill() class Skill: def __init__(self): self._proficient = False self._modifier = 0 @property def proficient(self): return self._proficient @proficient.setter def proficient(self, proficient): self._proficient = proficient @property def modifier(self): return self._modifier @modifier.setter def modifier(self, modifier): self._modifier = modifier
class TestResult: def __init__(self, test_case) -> None: self.__test_case = test_case self.__failed = False self.__reason = None def record_failure(self, reason: str): self.__reason = reason self.__failed = True def test_case(self) -> str: return type(self.__test_case).__name__ def test_name(self) -> str: return self.__test_case.name() def failed(self) -> bool: return self.__failed def reason(self) -> str: return self.__reason class IReport: def record_test_result(self, test_result: TestResult): raise NotImplementedError def test_results(self) -> dict[str, list]: raise NotImplementedError def run_count(self) -> int: raise NotImplementedError def failure_count(self) -> int: raise NotImplementedError class IFormatter: @classmethod def format(cls, test_report: IReport) -> any: raise NotImplementedError
# -*- coding: utf-8 -*- def get_tokens(line): """tokenize a line""" return line.split() def read_metro_map_file(filename): """read ressources from a metro map input file""" sections = ('[Vertices]', '[Edges]') vertices = dict(); edges = list(); line_number = 0 section = None with open(filename, "r") as input_file: for line in input_file: line_number += 1 tokens = get_tokens(line) if len(tokens) > 0: if tokens[0][:1] == '[': # section keyword, check that it ends with a ']' if tokens[0][-1:] == ']': section = tokens[0] if section in sections: pass else: print("ERROR invalid section name at line {} : {}".format(line_number, line)) else: # in section line if section is None: print("WARNING lines before any section at line {} : {}".format(line_number, line)) elif section == '[Vertices]': # remove leading zeros key = tokens[0].lstrip("0") if key == '': key = '0' if key in vertices: print("ERROR duplicated key at line {} : {}".format(line_number, line)) else: vertices[key] = ' '.join(tokens[1:]) elif section == '[Edges]': duration = float(tokens[2]) edges.append((tokens[0], tokens[1], duration)) else: # kind of section not handled pass # sanity check for source, destination, duration in edges: if source not in vertices: print("ERROR source is not a vertice {} -> {} : {}".format(source, destination, duration)) if destination not in vertices: print("ERROR destination is not a vertice {} -> {} : {}".format(source, destination, duration)) if duration <= 0: print("ERROR invalid duration {} -> {} : {}".format(source, destination, duration)) resources = dict() resources["vertices"] = vertices resources["edges"] = edges return resources
#!/usr/bin/python #-*-coding:utf-8-*- '''This packge contains the UCT algorithem of the UAV searching. The algorithem conform to the standard OperateInterface defined in the PlatForm class.''' __all__ = ['UCTControl', 'UCTSearchTree', 'UCTTreeNode']
# --- Starting python tests --- #Funct def functione(x,y): return x*y # call print(format(functione(2,3)))
# # CLASS MEHTODS # class Employee: # company ="camel" # salary = 100 # location = "mumbai" # def ChangeSalary(self, sal): # self.__class__.salary = sal # # THE EASY METHOD FOR THE ABOVE STATEMENT AND FOR THE CLASS ATTRIBUTE IS # @classmethod # def ChangeSalary(cls, sal): # cls.salary = sal # e = Employee() # print("this is e.salary obj of employee************",e.salary) # print("this is of employee**********", Employee.salary) # e.ChangeSalary(455) # print("this is the e .salary obj after using e.changeSalary method so this is an instance*************", e.salary) # print("This is the same Employee that hasnt been changed even after we use e.chanegSalary************", Employee.salary) # PROPERTY DECORATOR class Employee: company = "Bharat Gas" salary =4500 salaryBonus= 500 # totalSalary = 5000 # ALSO CALLED AS GETTER METHOD @property def totalSalary(self): return self.salary +self.salaryBonus @totalSalary.setter def totalSalary(self, val): self.salaryBonus = val - self.salary e= Employee() print(e.totalSalary) e.totalSalary = 4900 print(e.totalSalary) print(e.salary) print(e.salaryBonus)
# Marcelo Campos de Medeiros # ADS UNIFIP 2020.1 # Patos-PB 17/03/2020 ''' Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: Para homens: (72.7*h) - 58 Para mulheres: (62.1*h) - 44.7 ''' print('='*43) print('PROGRAMA PESO IDEAL PARA MULHERES E HOMENS') print('='*43,'\n') # variável sexo masculino ou feminino print('='*65) sexo = str(input('A que tipo de genero você pertence F(feminino) e M(masculino): ')).strip().upper() # variável altura da pessoa print('='*27) altura = float(input('Qual é sua altura: ')) print('='*27, '\n') # calculo do peso ideal para homens fórmula: (72.7*altura) - 58 if sexo == 'M': peso = (72.7 * altura) - 58 print('*'*50) print(f'Seu peso idela para sua altura de {altura} m é {peso:.2f}kg') print('*'*50) # calculo do peso ideal para mulheres fórmula: (62.1*h) - 44.7 else: peso = (62.1 * altura) - 44.7 print('*' * 50) print(f'Seu peso idela para sua altura de {altura} m é {peso:.2f}kg') print('*' * 50)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def bubble_sort(arr): for n in range(len(arr)-1, 0, -1): for k in range(n): if r[k] > r[k+1]: tmp = r[k] r[k] = r[k+1] r[k+1] = tmp if __name__ == '__main__': r = [5, 4, 2, 3, 1] bubble_sort(r) print(r)
# Let's say you have a dictionary matchinhg your friends' names # with their favorite flowers: fav_flowers = {'Alex': 'field flowers', 'Kate': 'daffodil', 'Eva': 'artichoke flower', 'Daniel': 'tulip'} # Your new friend Alice likes orchid the most: add this info to the # fav_flowers dict and print the dict. # NB: Do not redefine the dictionary itself, just add the new # element to the existing one. fav_flowers['Alice'] = 'orchid' print(fav_flowers)
num1 = float(input("Enter 1st number: ")) op = input("Enter operator: ") num2 = float(input("Enter 2nd number: ")) if op == "+": val = num1 + num2 elif op == "-": val = num1 - num2 elif op == "*" or op == "x": val = num1 * num2 elif op == "/": val = num1 / num2 print(val)
def count_substring(string, sub_string): times = 0 length = len(sub_string) for letter in range(0, len(string)): if string[letter:letter+length] == sub_string: times += 1 return times
#!/usr/bin/pthon3 # Time complexity: O(N) def solution(A): count = {} size_A = len(A) leader = None for i, a in enumerate(A): count[a] = count.get(a, 0) + 1 if count[a] > size_A // 2: leader = a equi_leader = 0 before = 0 for i in range(size_A): if A[i] == leader: before += 1 if (before > (i + 1) // 2) and ((count[leader] - before) > (size_A - i - 1) // 2): equi_leader += 1 return equi_leader
class Solution: def isHappy(self, n): """ :type n: int :rtype: bool """ tried = set() while n not in tried and n != 1: tried.add(n) n2 = 0 while n > 0: n2, n = n2 + (n % 10) ** 2, n // 10 n = n2 return n == 1 if __name__ == "__main__": print(Solution().isHappy(19))
salhora=15 horasT=int(input('Informe quantas horas voce trabalhou esta semana: ')) if horasT<=40: salario = salhora * horasT print('O salário é {0:.2f}'.format(salario)) elif horasT>40: salario = salhora * horasT salarioextra = (horasT-40)*0.5+salario print('O salário é {0:.2f}'.format(salarioextra))
n1 = int(input('digite um valor >>')) n2 = int(input('digite outro vaor >>')) n3 = int(input('digite outro valor >>')) #menor menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 #maior maior = n1 if n2 > n1 and n2 > n3: maior = n2 if n3 > n1 and n3 > n2: maior = n3 print('o maior numero e {}'.format(maior)) print('o menor numero e {}'.format(menor))
def fahrenheit_to_celsius(deg_F): """Convert degrees Fahrenheit to Celsius.""" return (5 / 9) * (deg_F - 32) def celsius_to_fahrenheit(deg_C): """Convert degrees Celsius to Fahrenheit.""" return (9 / 5) * deg_C + 32 def celsius_to_kelvin(deg_C): """Convert degree Celsius to Kelvin.""" return deg_C + 273.15 def fahrenheit_to_kelvin(deg_F): """Convert degree Fahrenheit to Kelvin.""" deg_C = fahrenheit_to_celsius(deg_F) return celsius_to_kelvin(deg_C)
class TypeFactory(object): def __init__(self, client): self.client = client def create(self, transport_type, *args, **kwargs): klass = self.classes[transport_type] cls = klass(*args, **kwargs) cls._client = self.client return cls
# Copyright 2020-present Kensho Technologies, LLC. """Tools for constructing high-performance query interpreters over arbitrary schemas. While GraphQL compiler's database querying capabilities are sufficient for many use cases, there are many types of data querying for which the compilation-based approach is unsuitable. A few examples: - data accessible via a simple API instead of a rich query language, - data represented as a set of files and directories on a local disk, - data produced on-demand by running a machine learning model over some inputs. The data in each of these cases can be described by a valid schema, and users could write well-defined and legal queries against that schema. However, the execution of such queries cannot proceed by compiling them to another query language -- no such target query language exists. Instead, the queries need to be executed using an *interpreter*: a piece of code that executes queries incrementally in a series of steps, such as "fetch the value of this field" or "filter out this data point if its value is less than 5." Some parts of the interpreter (e.g. "fetch the value of this field") obviously need to be aware of the schema and the underlying data source. Other parts (e.g. "filter out this data point") are schema-agnostic -- they work in the same way regardless of the schema and data source. This library provides efficient implementations of all schema-agnostic interpreter components. All schema-aware logic is abstracted into the straightforward, four-method API of the InterpreterAdapter class, which should be subclassed to create a new interpreter over a new dataset. As a result, the development of a new interpreter looks like this: - Construct the schema of the data your new interpreter will be querying. - Construct a subclass InterpreterAdapter class -- let's call it MyCustomAdapter. - Add long-lived interpreter state such as API keys, connection pools, etc. as instance attributes of the MyCustomAdapter class. - Implement the four simple functions that form the InterpreterAdapter API. - Construct an instance of MyCustomAdapter and pass it to the schema-agnostic portion of the interpreter implemented in this library, such as the interpret_ir() function. - You now have a way to execute queries over your schema! Then, profit! For more information, consult the documentation of the items exported below. """
length = float(input("Enter the length of a side of the cube: ")) total_surface_area = 6 * length ** 2 volume = 3 * length ** 2 print("The surface area of the cube is", total_surface_area) print("The volume of the cube is", volume) close = input("Press X to exit") # The above code keeps the program open for the user to see the outcome of the problem.
#========================================================================================= class Task(): """Task is a part of Itinerary """ def __init__(self, aName, aDuration, aMachine): self.name = aName self.duration = aDuration self.machine = aMachine self.taskChanged = False def exportToDict(self): """Serialize information about Task into dictionary""" exData = {} exData['taskName'] = self.name exData['taskMachine'] = self.machine.exportToDict() exData['taskDuration'] = self.duration return exData
""" lec 4, tuple and dictionary """ my_tuple='a','b','c','d','e' print(my_tuple) my_2nd_tuple=('a','b','c','d','e') print(my_2nd_tuple) test='a' print(type(test)) #not a tuple bc no comma Test='a', print(type(Test)) print(my_tuple[1]) print(my_tuple[-1]) print(my_tuple[1:3]) print(my_tuple[1:]) print(my_tuple[:3]) my_car={ 'color':'red', 'maker':'toyota', 'year':2015 } print(my_car['year']) print(my_car.get('year')) my_car['model']='corolla' print(my_car) my_car['year']=2020 print(my_car) print(len(my_car)) print('color'in my_car) print('mile' in my_car)
n = int (input()) for i in range(1,n+1): b = str (input()) if "кот" in b or "Кот": print ("may") else: print("no")
def generate(): class Spam: count = 1 def method(self): print(count) return Spam() generate().method()
def add(a, b): """Adds a and b.""" return a + b if __name__ == '__main__': assert add(2, 5) == 7, '2 and 5 are not 7' assert add(-2, 5) == 3, '-2 and 5 are not 3' print('This executes only if I am main!')
# Title : Generators in python # Author : Kiran raj R. # Date : 31:10:2020 def printNum(): num = 0 while True: yield num num += 1 result = printNum() print(next(result)) print(next(result)) print(next(result)) result = (num for num in range(10000)) print(result) print(next(result)) print(next(result)) print(next(result))
""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. """ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows==0: return [] if numRows==1: return [[1]] if numRows==2: return [[1], [1,1]] result = [[1],[1,1]] for row in range(3,numRows+1): new_row = [] for col in range(row): if col==0: new_row.append(1) elif col==row-1: new_row.append(1) else: new_row.append(result[row-2][col-1]+result[row-2][col]) result.append(new_row) return result if __name__ == "__main__": s = Solution() print(s.generate(1))
def funcion(nums,n): print(nums) res = [] for i in range(len(nums)): suma = 0 aux = [] suma += nums[i] for j in range(i+1,len(nums)): print(i,j) if suma + nums[j] == n: aux.append(nums[i]) aux.append(nums[j]) res.append(aux) else: pass return res def main(): print(funcion([1,2,3,4,5,6,7,-1],6)) main()
class Solution: def findRadius(self, houses, heaters): """ :type houses: List[int] :type heaters: List[int] :rtype: int """ houses.sort() heaters.sort() radius = 0 i = 0 for house in houses: while i < len(heaters) and heaters[i] < house: i += 1 if i == 0: radius = max(radius, heaters[i] - house) elif i == len(heaters): return max(radius, houses[-1] - heaters[-1]) else: radius = max(radius, min(heaters[i]-house, house-heaters[i-1])) return radius """ Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses. Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters. So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters. Note: Numbers of houses and heaters you are given are non-negative and will not exceed 25000. Positions of houses and heaters you are given are non-negative and will not exceed 10^9. As long as a house is in the heaters' warm radius range, it can be warmed. All the heaters follow your radius standard and the warm radius will the same. Example 1: Input: [1,2,3],[2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. """
""" A list of the custom settings used on the site. Many of the external libraries have their own settings, see library documentation for details. """ VAVS_EMAIL_FROM = 'address shown in reply-to field of emails' VAVS_EMAIL_TO = 'list of staff addresses to send reports to' VAVS_EMAIL_SURVEYS = 'address to send surveys to' VAVS_ROOT = 'path to root directory of site' VAVS_DOWNLOAD_DIR = 'path to download directory' VAVS_THUMBNAILS_DIR = 'path tothumbnail directory' VAVS_THUMBNAILS_SIZE = 'size of thumbnails as tuple: (width, height)' FBDATA_LIKES_LIMIT = 'maximum number of likes to show in listings' FBDATA_INITIAL_PERIOD = 'number of days to backdate data collection to' FBDATA_MIN_PERIOD = 'minimum duration, as timedelta, between updates'
class TestHLD: # edges = [ # (0, 1), # (0, 6), # (0, 10), # (1, 2), # (1, 5), # (2, 3), # (2, 4), # (6, 7), # (7, 8), # (7, 9), # (10, 11), # ] # root = 0 # get_lca = lca_hld(edges, root) # print(get_lca(3, 5)) ...
input = """ ok:- #count{V:b(V)}=X, not p(X). b(1). p(2). """ output = """ ok:- #count{V:b(V)}=X, not p(X). b(1). p(2). """
# # PySNMP MIB module OVERLAND-NEXTGEN (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OVERLAND-NEXTGEN # Produced by pysmi-0.3.4 at Wed May 1 14:35:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, ObjectIdentity, ModuleIdentity, NotificationType, iso, Gauge32, IpAddress, Bits, MibIdentifier, TimeTicks, Counter64, Counter32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "ObjectIdentity", "ModuleIdentity", "NotificationType", "iso", "Gauge32", "IpAddress", "Bits", "MibIdentifier", "TimeTicks", "Counter64", "Counter32", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") overlandGlobalRegModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 3351, 1, 1, 1, 1)) if mibBuilder.loadTexts: overlandGlobalRegModule.setLastUpdated('9807090845Z') if mibBuilder.loadTexts: overlandGlobalRegModule.setOrganization('Overland Data, Inc.') if mibBuilder.loadTexts: overlandGlobalRegModule.setContactInfo('Robert Kingsley email: bkingsley@overlanddata.com') if mibBuilder.loadTexts: overlandGlobalRegModule.setDescription('The Overland Data central registration module.') overlandRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1)) overlandReg = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 1)) overlandGeneric = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 2)) overlandProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3)) overlandCaps = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 4)) overlandReqs = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 5)) overlandExpr = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 6)) overlandModules = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 1, 1)) overlandNextGen = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2)) overlandNextGenActions = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 1)) overlandNextGenStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 2)) overlandNextGenState = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3)) overlandNextGenComponents = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 4)) overlandNextGenAttributes = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5)) overlandNextGenEvents = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6)) overlandNextGenGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7)) overlandLoopback = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: overlandLoopback.setStatus('current') if mibBuilder.loadTexts: overlandLoopback.setDescription('Sends or retrieves a loopback string to the target.') overlandActionGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 1)).setObjects(("OVERLAND-NEXTGEN", "overlandLoopback")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overlandActionGroup = overlandActionGroup.setStatus('current') if mibBuilder.loadTexts: overlandActionGroup.setDescription('Current library status which may be queried.') driveStatusTable = MibTable((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1), ) if mibBuilder.loadTexts: driveStatusTable.setStatus('current') if mibBuilder.loadTexts: driveStatusTable.setDescription('Table containing various drive status.') driveStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1), ).setIndexNames((0, "OVERLAND-NEXTGEN", "dstIndex")) if mibBuilder.loadTexts: driveStatusEntry.setStatus('current') if mibBuilder.loadTexts: driveStatusEntry.setDescription('A row in the drive status table.') dstRowValid = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstRowValid.setStatus('current') if mibBuilder.loadTexts: dstRowValid.setDescription('Provides an INVALID indication if no drives are installed or if the drive type is unknown; otherwise, an indication of the drive type is provided.') dstIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: dstIndex.setStatus('current') if mibBuilder.loadTexts: dstIndex.setDescription('Index to drive status fields.') dstState = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("initializedNoError", 0), ("initializedWithError", 1), ("notInitialized", 2), ("notInstalled", 3), ("notInserted", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: dstState.setStatus('current') if mibBuilder.loadTexts: dstState.setDescription('Current state of the drive.') dstMotion = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstMotion.setStatus('current') if mibBuilder.loadTexts: dstMotion.setDescription('ASCII msg describing current drive tape motion.') dstCodeRevDrive = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstCodeRevDrive.setStatus('current') if mibBuilder.loadTexts: dstCodeRevDrive.setDescription('Revision number of the drive code.') dstCodeRevController = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstCodeRevController.setStatus('current') if mibBuilder.loadTexts: dstCodeRevController.setDescription('Revision number of the drive controller code.') dstScsiId = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: dstScsiId.setStatus('current') if mibBuilder.loadTexts: dstScsiId.setDescription('SCSI Id number of drive.') dstSerialNum = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstSerialNum.setStatus('current') if mibBuilder.loadTexts: dstSerialNum.setDescription('Serial number of this drive.') dstCleanRequested = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("cleanNotNeeded", 0), ("cleanNeeded", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: dstCleanRequested.setStatus('current') if mibBuilder.loadTexts: dstCleanRequested.setDescription('The drive heads needs to be cleaned with a cleaning cartridge.') libraryStatusTable = MibTable((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2), ) if mibBuilder.loadTexts: libraryStatusTable.setStatus('current') if mibBuilder.loadTexts: libraryStatusTable.setDescription('Table containing fault code, severity and ACSII error messages displayed on front panel of library.') libraryStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1), ).setIndexNames((0, "OVERLAND-NEXTGEN", "lstIndex")) if mibBuilder.loadTexts: libraryStatusEntry.setStatus('current') if mibBuilder.loadTexts: libraryStatusEntry.setDescription('A row in the library status table.') lstIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1))).setMaxAccess("readonly") if mibBuilder.loadTexts: lstIndex.setStatus('current') if mibBuilder.loadTexts: lstIndex.setDescription('Index to table of library status.') lstConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("standalone", 0), ("multimodule", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: lstConfig.setStatus('current') if mibBuilder.loadTexts: lstConfig.setDescription('Indicates if library is standalone or multi-module.') lstScsiId = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: lstScsiId.setStatus('current') if mibBuilder.loadTexts: lstScsiId.setDescription('Indicates library SCSI bus ID.') lstStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: lstStatus.setStatus('current') if mibBuilder.loadTexts: lstStatus.setDescription('Indication of current library status.') lstChangerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lstChangerStatus.setStatus('current') if mibBuilder.loadTexts: lstChangerStatus.setDescription('Bit-mapped indication of current changer status: bit 0 - cartridge map valid bit 1 - initializing bit 2 - door open bit 3 - front panel mode bit 4 - door closed bit 5 - browser mode bit 6 - master busy') lstLibraryState = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("initializing", 0), ("online", 1), ("offline", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: lstLibraryState.setStatus('current') if mibBuilder.loadTexts: lstLibraryState.setDescription('Indication of current library state.') errorTable = MibTable((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3), ) if mibBuilder.loadTexts: errorTable.setStatus('current') if mibBuilder.loadTexts: errorTable.setDescription('Table containing fault code, severity and ACSII error messages displayed on front panel of library.') errorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1), ).setIndexNames((0, "OVERLAND-NEXTGEN", "errIndex")) if mibBuilder.loadTexts: errorEntry.setStatus('current') if mibBuilder.loadTexts: errorEntry.setDescription('A row in the error info table.') errIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1))).setMaxAccess("readonly") if mibBuilder.loadTexts: errIndex.setStatus('current') if mibBuilder.loadTexts: errIndex.setDescription('Index to table of library error information.') errCode = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: errCode.setStatus('current') if mibBuilder.loadTexts: errCode.setDescription('Hex code unique to the reported error.') errSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("informational", 0), ("mild", 1), ("hard", 2), ("severe", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: errSeverity.setStatus('current') if mibBuilder.loadTexts: errSeverity.setDescription('Indication of how serious the reported error is: 0 = informational error, not very severe 1 = mild error, operator intervention not necessary 2 = hard error, may be corrected remotely 3 = very severe, power cycle required to clear') errMsg = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: errMsg.setStatus('current') if mibBuilder.loadTexts: errMsg.setDescription('ASCII message naming the current error.') errActionMsg = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: errActionMsg.setStatus('current') if mibBuilder.loadTexts: errActionMsg.setDescription('ASCII message providing additional information about current error and possibly some suggestions for correcting it.') overlandStateGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 3)).setObjects(("OVERLAND-NEXTGEN", "errIndex"), ("OVERLAND-NEXTGEN", "errCode"), ("OVERLAND-NEXTGEN", "errSeverity"), ("OVERLAND-NEXTGEN", "errMsg"), ("OVERLAND-NEXTGEN", "errActionMsg"), ("OVERLAND-NEXTGEN", "dstRowValid"), ("OVERLAND-NEXTGEN", "dstIndex"), ("OVERLAND-NEXTGEN", "dstState"), ("OVERLAND-NEXTGEN", "dstMotion"), ("OVERLAND-NEXTGEN", "dstCodeRevDrive"), ("OVERLAND-NEXTGEN", "dstCodeRevController"), ("OVERLAND-NEXTGEN", "dstScsiId"), ("OVERLAND-NEXTGEN", "dstSerialNum"), ("OVERLAND-NEXTGEN", "dstCleanRequested"), ("OVERLAND-NEXTGEN", "lstIndex"), ("OVERLAND-NEXTGEN", "lstConfig"), ("OVERLAND-NEXTGEN", "lstScsiId"), ("OVERLAND-NEXTGEN", "lstStatus"), ("OVERLAND-NEXTGEN", "lstChangerStatus"), ("OVERLAND-NEXTGEN", "lstLibraryState")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overlandStateGroup = overlandStateGroup.setStatus('current') if mibBuilder.loadTexts: overlandStateGroup.setDescription('Current library states which may be queried.') numModules = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 256))).setMaxAccess("readonly") if mibBuilder.loadTexts: numModules.setStatus('current') if mibBuilder.loadTexts: numModules.setDescription('Reads the total number of modules available in the attached library.') numBins = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 256))).setMaxAccess("readonly") if mibBuilder.loadTexts: numBins.setStatus('current') if mibBuilder.loadTexts: numBins.setDescription('Reads the total number of cartridge storage slots available in the attached library.') numDrives = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 128))).setMaxAccess("readonly") if mibBuilder.loadTexts: numDrives.setStatus('current') if mibBuilder.loadTexts: numDrives.setDescription('Reads the total number of drives available in the attached library.') numMailSlots = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: numMailSlots.setStatus('current') if mibBuilder.loadTexts: numMailSlots.setDescription('Returns the total number of mail slots available in the attached library.') moduleGeometryTable = MibTable((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5), ) if mibBuilder.loadTexts: moduleGeometryTable.setStatus('current') if mibBuilder.loadTexts: moduleGeometryTable.setDescription('Table containing library module geometry.') moduleGeometryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1), ).setIndexNames((0, "OVERLAND-NEXTGEN", "modIndex")) if mibBuilder.loadTexts: moduleGeometryEntry.setStatus('current') if mibBuilder.loadTexts: moduleGeometryEntry.setDescription('A row in the library module geometry table.') modDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: modDesc.setStatus('current') if mibBuilder.loadTexts: modDesc.setDescription('If library geometry is valid, an ASCII message desribing the module.') modIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 7), ValueRangeConstraint(8, 8), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: modIndex.setStatus('current') if mibBuilder.loadTexts: modIndex.setDescription('Index to table of library module geometry: 8 = Master or Standalone module 0-7 = Slave Module') modAttached = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("isNotAttached", 0), ("isAttached", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: modAttached.setStatus('current') if mibBuilder.loadTexts: modAttached.setDescription('Indication of whether or not module is attached.') modStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: modStatus.setStatus('current') if mibBuilder.loadTexts: modStatus.setDescription('ASCII message desribing the current status of the module.') modConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("unknown", 0), ("lightning", 1), ("thunder", 2), ("invalid", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: modConfig.setStatus('current') if mibBuilder.loadTexts: modConfig.setDescription("Indication of this module's type.") modFwRev = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modFwRev.setStatus('current') if mibBuilder.loadTexts: modFwRev.setDescription("Indication of this module's firmware revision level.") modNumBins = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modNumBins.setStatus('current') if mibBuilder.loadTexts: modNumBins.setDescription('Indication of the number of bins within this module.') modNumDrives = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modNumDrives.setStatus('current') if mibBuilder.loadTexts: modNumDrives.setDescription('Indication of the number of drives within this module.') modNumMailSlots = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modNumMailSlots.setStatus('current') if mibBuilder.loadTexts: modNumMailSlots.setDescription('Indication of the number of mailslots within this module.') overlandAttributesGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 4)).setObjects(("OVERLAND-NEXTGEN", "numModules"), ("OVERLAND-NEXTGEN", "numBins"), ("OVERLAND-NEXTGEN", "numDrives"), ("OVERLAND-NEXTGEN", "numMailSlots"), ("OVERLAND-NEXTGEN", "modDesc"), ("OVERLAND-NEXTGEN", "modIndex"), ("OVERLAND-NEXTGEN", "modAttached"), ("OVERLAND-NEXTGEN", "modStatus"), ("OVERLAND-NEXTGEN", "modConfig"), ("OVERLAND-NEXTGEN", "modFwRev"), ("OVERLAND-NEXTGEN", "modNumBins"), ("OVERLAND-NEXTGEN", "modNumDrives"), ("OVERLAND-NEXTGEN", "modNumMailSlots")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overlandAttributesGroup = overlandAttributesGroup.setStatus('current') if mibBuilder.loadTexts: overlandAttributesGroup.setDescription('Current library info which may be queried.') eventDoorOpen = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 1)) if mibBuilder.loadTexts: eventDoorOpen.setStatus('current') if mibBuilder.loadTexts: eventDoorOpen.setDescription('A library door has been opened.') eventMailSlotAccessed = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 2)) if mibBuilder.loadTexts: eventMailSlotAccessed.setStatus('current') if mibBuilder.loadTexts: eventMailSlotAccessed.setDescription('A mail slot is being accessed.') eventHardFault = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 3)) if mibBuilder.loadTexts: eventHardFault.setStatus('current') if mibBuilder.loadTexts: eventHardFault.setDescription('The library has posted a hard fault.') eventSlaveFailed = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 4)) if mibBuilder.loadTexts: eventSlaveFailed.setStatus('current') if mibBuilder.loadTexts: eventSlaveFailed.setDescription('A slave module has faulted.') eventPowerSupplyFailed = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 5)) if mibBuilder.loadTexts: eventPowerSupplyFailed.setStatus('current') if mibBuilder.loadTexts: eventPowerSupplyFailed.setDescription('One of the redundant power supplies has failed.') eventRequestDriveClean = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 6)) if mibBuilder.loadTexts: eventRequestDriveClean.setStatus('current') if mibBuilder.loadTexts: eventRequestDriveClean.setDescription('One of the library tape drives has requested a cleaning cycle to ensure continued data reliability.') eventFanStalled = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 7)) if mibBuilder.loadTexts: eventFanStalled.setStatus('current') if mibBuilder.loadTexts: eventFanStalled.setDescription('A tape drive fan has stalled.') eventDriveError = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 8)) if mibBuilder.loadTexts: eventDriveError.setStatus('current') if mibBuilder.loadTexts: eventDriveError.setDescription('A tape drive error has occurred.') eventDriveRemoved = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 9)) if mibBuilder.loadTexts: eventDriveRemoved.setStatus('current') if mibBuilder.loadTexts: eventDriveRemoved.setDescription('A tape drive has been removed from the library.') eventSlaveRemoved = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 10)) if mibBuilder.loadTexts: eventSlaveRemoved.setStatus('current') if mibBuilder.loadTexts: eventSlaveRemoved.setDescription('A slave module has been removed from the library.') eventFailedOver = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 11)) if mibBuilder.loadTexts: eventFailedOver.setStatus('current') if mibBuilder.loadTexts: eventFailedOver.setDescription('The library is failed over to the Secondary Master.') eventLoaderRetriesExcessive = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 12)) if mibBuilder.loadTexts: eventLoaderRetriesExcessive.setStatus('current') if mibBuilder.loadTexts: eventLoaderRetriesExcessive.setDescription('The library has detected excessive loader retries.') overlandNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 7)).setObjects(("OVERLAND-NEXTGEN", "eventDoorOpen"), ("OVERLAND-NEXTGEN", "eventMailSlotAccessed"), ("OVERLAND-NEXTGEN", "eventHardFault"), ("OVERLAND-NEXTGEN", "eventSlaveFailed"), ("OVERLAND-NEXTGEN", "eventPowerSupplyFailed"), ("OVERLAND-NEXTGEN", "eventRequestDriveClean"), ("OVERLAND-NEXTGEN", "eventFanStalled"), ("OVERLAND-NEXTGEN", "eventDriveError"), ("OVERLAND-NEXTGEN", "eventDriveRemoved"), ("OVERLAND-NEXTGEN", "eventSlaveRemoved"), ("OVERLAND-NEXTGEN", "eventFailedOver"), ("OVERLAND-NEXTGEN", "eventLoaderRetriesExcessive")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overlandNotificationGroup = overlandNotificationGroup.setStatus('current') if mibBuilder.loadTexts: overlandNotificationGroup.setDescription('Trap events returned by the browser.') mibBuilder.exportSymbols("OVERLAND-NEXTGEN", modIndex=modIndex, eventSlaveFailed=eventSlaveFailed, driveStatusEntry=driveStatusEntry, dstState=dstState, eventRequestDriveClean=eventRequestDriveClean, modDesc=modDesc, modNumMailSlots=modNumMailSlots, overlandNotificationGroup=overlandNotificationGroup, eventMailSlotAccessed=eventMailSlotAccessed, overlandAttributesGroup=overlandAttributesGroup, dstCleanRequested=dstCleanRequested, overlandProducts=overlandProducts, dstIndex=dstIndex, overlandReqs=overlandReqs, dstCodeRevDrive=dstCodeRevDrive, moduleGeometryTable=moduleGeometryTable, dstScsiId=dstScsiId, numMailSlots=numMailSlots, dstMotion=dstMotion, overlandNextGenEvents=overlandNextGenEvents, overlandNextGenComponents=overlandNextGenComponents, lstScsiId=lstScsiId, overlandActionGroup=overlandActionGroup, overlandLoopback=overlandLoopback, overlandCaps=overlandCaps, lstIndex=lstIndex, errorTable=errorTable, modConfig=modConfig, lstChangerStatus=lstChangerStatus, numDrives=numDrives, errActionMsg=errActionMsg, overlandGeneric=overlandGeneric, errMsg=errMsg, overlandNextGenState=overlandNextGenState, lstConfig=lstConfig, modStatus=modStatus, eventPowerSupplyFailed=eventPowerSupplyFailed, overlandGlobalRegModule=overlandGlobalRegModule, errSeverity=errSeverity, driveStatusTable=driveStatusTable, overlandStateGroup=overlandStateGroup, errIndex=errIndex, moduleGeometryEntry=moduleGeometryEntry, modFwRev=modFwRev, eventFanStalled=eventFanStalled, errCode=errCode, eventDriveError=eventDriveError, eventDoorOpen=eventDoorOpen, dstRowValid=dstRowValid, eventSlaveRemoved=eventSlaveRemoved, eventFailedOver=eventFailedOver, numModules=numModules, overlandReg=overlandReg, lstLibraryState=lstLibraryState, modNumBins=modNumBins, overlandNextGen=overlandNextGen, libraryStatusTable=libraryStatusTable, overlandNextGenAttributes=overlandNextGenAttributes, numBins=numBins, overlandExpr=overlandExpr, dstCodeRevController=dstCodeRevController, dstSerialNum=dstSerialNum, libraryStatusEntry=libraryStatusEntry, errorEntry=errorEntry, modNumDrives=modNumDrives, overlandRoot=overlandRoot, eventLoaderRetriesExcessive=eventLoaderRetriesExcessive, overlandModules=overlandModules, eventDriveRemoved=eventDriveRemoved, PYSNMP_MODULE_ID=overlandGlobalRegModule, overlandNextGenStatistics=overlandNextGenStatistics, lstStatus=lstStatus, modAttached=modAttached, eventHardFault=eventHardFault, overlandNextGenActions=overlandNextGenActions, overlandNextGenGroups=overlandNextGenGroups)
class Solution(object): def XXX(self, x): """ :type x: int :rtype: int """ if x==0: return 0 x = (x//abs(x)) * int(str(abs(x))[::-1]) if -2 ** 31 < x < 2 ** 31 - 1: return x return 0
class Solution: def diStringMatch(self, S: str): l = 0 r = len(S) ret = [] for i in S: if i == "I": ret.append(l) l += 1 else: ret.append(r) r -= 1 ret.append(r) return ret slu = Solution() print(slu.diStringMatch("III"))
#CONSIDER: composable authorizations class Authorization(object): ''' Base authorization class, defaults to full authorization ''' #CONSIDER: how is this notified about filtering, ids, etc def __init__(self, identity, endpoint): self.identity = identity self.endpoint = endpoint def process_queryset(self, queryset): return queryset def is_authorized(self): return True class AuthorizationMixin(object): def make_authorization(self, identity, endpoint): return Authorization(identity, endpoint) def get_identity(self): #TODO delegate return self.request.user def is_authenticated(self): return self.authorization.is_authorized() def handle(self, endpoint, *args, **kwargs): self.identity = self.get_identity() self.authorization = self.make_authorization(self.identity, endpoint) return super(AuthorizationMixin, self).handle(endpoint, *args, **kwargs) class DjangoModelAuthorization(Authorization): ''' Your basic django core permission based authorization ''' def __init__(self, identity, model, endpoint): super(DjangoModelAuthorization, self).__init__(identity, endpoint) self.model = model def is_authorized(self): #print("auth identity:", self.identity) if self.identity.is_superuser: return True #TODO proper lookup of label? if self.endpoint == 'list': return True #TODO in django fashion, you have list if you have add, change, or delete return self.identity.has_perm perm_name = self.model._meta.app_label + '.' if self.endpoint == 'create': perm_name += 'add' elif self.endpoint == 'update': perm_name += 'change' else: #TODO delete_list? update_list? others? perm_name += self.endpoint perm_name += '_' + self.model.__name__ return self.identity.has_perm(perm_name) class ModelAuthorizationMixin(AuthorizationMixin): def make_authorization(self, identity, endpoint): return DjangoModelAuthorization(identity, self.model, endpoint)
# Len of signature in write signed packet SIGNATURE_LEN = 12 # Attribute Protocol Opcodes OP_ERROR = 0x01 OP_MTU_REQ = 0x02 OP_MTU_RESP = 0x03 OP_FIND_INFO_REQ = 0x04 OP_FIND_INFO_RESP = 0x05 OP_FIND_BY_TYPE_REQ = 0x06 OP_FIND_BY_TYPE_RESP= 0x07 OP_READ_BY_TYPE_REQ = 0x08 OP_READ_BY_TYPE_RESP = 0x09 OP_READ_REQ = 0x0A OP_READ_RESP = 0x0B OP_READ_BLOB_REQ = 0x0C OP_READ_BLOB_RESP = 0x0D OP_READ_MULTI_REQ = 0x0E OP_READ_MULTI_RESP = 0x0F OP_READ_BY_GROUP_REQ = 0x10 OP_READ_BY_GROUP_RESP = 0x11 OP_WRITE_REQ = 0x12 OP_WRITE_RESP = 0x13 OP_WRITE_CMD = 0x52 OP_PREP_WRITE_REQ = 0x16 OP_PREP_WRITE_RESP = 0x17 OP_EXEC_WRITE_REQ = 0x18 OP_EXEC_WRITE_RESP = 0x19 OP_HANDLE_NOTIFY = 0x1B OP_HANDLE_IND = 0x1D OP_HANDLE_CNF = 0x1E OP_SIGNED_WRITE_CMD = 0xD2 __STRING_TO_OPCODE = { "ERROR" : 0x01, "MTU_REQ" : 0x02, "MTU_RESP" : 0x03, "FIND_INFO_REQ" : 0x04, "FIND_INFO_RESP" : 0x05, "FIND_BY_TYPE_REQ" : 0x06, "FIND_BY_TYPE_RESP" : 0x07, "READ_BY_TYPE_REQ" : 0x08, "READ_BY_TYPE_RESP" : 0x09, "READ_REQ" : 0x0A, "READ_RESP" : 0x0B, "READ_BLOB_REQ" : 0x0C, "READ_BLOB_RESP" : 0x0D, "READ_MULTI_REQ" : 0x0E, "READ_MULTI_RESP" : 0x0F, "READ_BY_GROUP_REQ" : 0x10, "READ_BY_GROUP_RESP" : 0x11, "WRITE_REQ" : 0x12, "WRITE_RESP" : 0x13, "WRITE_CMD" : 0x52, "PREP_WRITE_REQ" : 0x16, "PREP_WRITE_RESP" : 0x17, "EXEC_WRITE_REQ" : 0x18, "EXEC_WRITE_RESP" : 0x19, "HANDLE_NOTIFY" : 0x1B, "HANDLE_IND" : 0x1D, "HANDLE_CNF" : 0x1E, "SIGNED_WRITE_CMD" : 0xD2, } __OPCODE_TO_STRING = { v: k for k, v in __STRING_TO_OPCODE.items() } def opcodeLookup(opcode): return __OPCODE_TO_STRING[opcode] if opcode in __OPCODE_TO_STRING \ else "unknown" __OP_COMMAND = frozenset((OP_WRITE_CMD, OP_SIGNED_WRITE_CMD)) def isCommand(opcode): return opcode in __OP_COMMAND __OP_REQUEST = frozenset(( OP_MTU_REQ, OP_FIND_INFO_REQ, OP_FIND_BY_TYPE_REQ, OP_READ_BY_TYPE_REQ, OP_READ_REQ, OP_READ_BLOB_REQ, OP_READ_MULTI_REQ, OP_READ_BY_GROUP_REQ, OP_WRITE_REQ, OP_PREP_WRITE_REQ, OP_EXEC_WRITE_REQ, )) def isRequest(opcode): return opcode in __OP_REQUEST __OP_RESPONSE = frozenset(( OP_MTU_RESP, OP_FIND_INFO_RESP, OP_FIND_BY_TYPE_RESP, OP_READ_BY_TYPE_RESP, OP_READ_RESP, OP_READ_BLOB_RESP, OP_READ_MULTI_RESP, OP_READ_BY_GROUP_RESP, OP_WRITE_RESP, OP_PREP_WRITE_RESP, OP_EXEC_WRITE_RESP, )) def isResponse(opcode): return opcode in __OP_RESPONSE # Error codes for Error response PDU ECODE_INVALID_HANDLE = 0x01 ECODE_READ_NOT_PERM = 0x02 ECODE_WRITE_NOT_PERM = 0x03 ECODE_INVALID_PDU = 0x04 ECODE_AUTHENTICATION = 0x05 ECODE_REQ_NOT_SUPP = 0x06 ECODE_INVALID_OFFSET = 0x07 ECODE_AUTHORIZATION = 0x08 ECODE_PREP_QUEUE_FULL = 0x09 ECODE_ATTR_NOT_FOUND = 0x0A ECODE_ATTR_NOT_LONG = 0x0B ECODE_INSUFF_ENCR_KEY_SIZE = 0x0C ECODE_INVAL_ATTR_VALUE_LEN = 0x0D ECODE_UNLIKELY = 0x0E ECODE_INSUFF_ENC = 0x0F ECODE_UNSUPP_GRP_TYPE = 0x10 ECODE_INSUFF_RESOURCES = 0x11 # Application error ECODE_IO = 0x80 ECODE_TIMEOUT = 0x81 ECODE_ABORTED = 0x82 __STRING_TO_ECODE = { "INVALID_HANDLE" : 0x01, "READ_NOT_PERM" : 0x02, "WRITE_NOT_PERM" : 0x03, "INVALID_PDU" : 0x04, "AUTHENTICATION" : 0x05, "REQ_NOT_SUPP" : 0x06, "INVALID_OFFSET" : 0x07, "AUTHORIZATION" : 0x08, "PREP_QUEUE_FULL" : 0x09, "ATTR_NOT_FOUND" : 0x0A, "ATTR_NOT_LONG" : 0x0B, "INSUFF_ENCR_KEY_SIZE" : 0x0C, "INVAL_ATTR_VALUE_LEN" : 0x0D, "UNLIKELY" : 0x0E, "INSUFF_ENC" : 0x0F, "UNSUPP_GRP_TYPE" : 0x10, "INSUFF_RESOURCES" : 0x11, "IO" : 0x80, "TIMEOUT" : 0x81, "ABORTED" : 0x82, } __ECODE_TO_STRING = { v: k for k, v in __STRING_TO_ECODE.items() } def ecodeLookup(ecode): return __ECODE_TO_STRING[ecode] if ecode in __ECODE_TO_STRING else "unknown" MAX_VALUE_LEN = 512 DEFAULT_L2CAP_MTU = 48 DEFAULT_LE_MTU = 23 CID = 4 PSM = 31 # Flags for Execute Write Request Operation CANCEL_ALL_PREP_WRITES = 0x00 WRITE_ALL_PREP_WRITES = 0x01 # Find Information Response Formats FIND_INFO_RESP_FMT_16BIT = 0x01 FIND_INFO_RESP_FMT_128BIT = 0x02
''' Description: ------------ When objects are instantiated, the object itself is passed into the self parameter. The Object is passed into the self parameter so that the object can keep hold of its own data. ''' print(__doc__) print('-'*25) class State(object): def __init__(self): global x x=self.field = 5.0 def add(self, x): self.field += x def mul(self, x): self.field *= x def div(self, x): self.field /= x def sub(self, x): self.field -= x n=int(input('Enter a valued: ')) s = State() print(f"\nAfter intializing the varaiable, the value of variable is: {s.field}") s.add(n) # Self is implicitly passed. print(f"\nAddition of the initalized variable {x} with {n} is: {s.field}") s.mul(n) # Self is implicitly passed. print(f"\nMultiplication of the initalized variable {x} with {n} is: {s.field}") s.div(n) # Self is implicitly passed. print(f"\nSubtraction of the initalized variable {x} with {n} is: {s.field}") s.sub(n) # Self is implicitly passed. print(f"\nDivision of the initalized variable {x} with {n} is: {s.field}")
# -*- coding: utf-8 -*- phrases_map = { 'caro': 'Vicky > Caro', 'vicky': 'Vicky 😍😍😍', 'gracias por venir': '¡Gracias por estar!', 'facho': 'callate zurdito', 'zurdito': 'callate gorilón', 'ayy': 'ayylmaokai', 'lmao': 'ayy', 'al toque': 'TO THE TOUCH', 'distro': 'https://distrowatch.com', 'roger': 'LINUX > TODO AGUANTE OPEN SOURCE DISTROS PARA TODOS Y TODAS', 'birra': 'Walter: "No chicos yo no soy alcohólico"', 'juan': 'chupo cosas', 'intervalo': 'cual? eso no existe.', 'osde': 'chicos yo sé que son jóvenes todavía pero siempre puede ocurrir un accidente', '100% descuento': 'SOLAMENTE EN LOS PRIMEROS 5 PESOS DE TU COMPRA', 'go': '¿Quisiste decir Python?', 'python': '¿Quisiste decir el futuro? Mentira, si es re lento. Por ahí en un par de años.', 'vaso termico': 'No tendremos tantos beneficios como citi, pero tenemos vasos térmicos, y están re piolas.' }
# escreva um programa que leia dois numeros inteiros e compare-os. # mostrando na tela uma mensagem: # o primeiro valor é maior # o segundo valor é maior # não existe valor maior, os dois são iguais n1 = int(input('Dê um número inteiro: ')) n2 = int(input('Dê mais um: ')) if n1 > n2: print('O primeiro valor é maior.') elif n1 < n2: print('O segundo valor é maior.') else: print('Não existe valor maior, os dois são iguais.')
# # @lc app=leetcode id=611 lang=python3 # # [611] Valid Triangle Number # # https://leetcode.com/problems/valid-triangle-number/description/ # # algorithms # Medium (49.73%) # Likes: 1857 # Dislikes: 129 # Total Accepted: 109.5K # Total Submissions: 222.7K # Testcase Example: '[2,2,3,4]' # # Given an integer array nums, return the number of triplets chosen from the # array that can make triangles if we take them as side lengths of a # triangle. # # # Example 1: # # # Input: nums = [2,2,3,4] # Output: 3 # Explanation: Valid combinations are: # 2,3,4 (using the first 2) # 2,3,4 (using the second 2) # 2,2,3 # # # Example 2: # # # Input: nums = [4,2,3,4] # Output: 4 # # # # Constraints: # # # 1 <= nums.length <= 1000 # 0 <= nums[i] <= 1000 # # # # @lc code=start class Solution: def triangleNumber(self, nums: List[int]) -> int: if not nums or len(nums) <= 2: return 0 nums.sort() count = 0 for i in range(len(nums) - 1, 1, -1): delta = self.two_sum_greater(nums, 0, i - 1, nums[i]) count += delta return count def two_sum_greater(self, nums, start, end, target): delta = 0 while start <= end: if nums[start] + nums[end] > target: delta += end - start end -= 1 else: start += 1 return delta # solve using DFS, print out all possible combination def triangleNumber_DFS(self, nums: List[int]) -> int: if not nums or len(nums) < 3: return 0 self.ret = 0 self.tmp = [] self.used = [False for _ in range(len(nums))] nums.sort() self._dfs(nums, 0, []) # print(self.tmp) return self.ret def _dfs(self, nums, start, curr): if len(curr) > 3: return if len(curr) == 3: if curr[0] + curr[1] > curr[2]: self.ret += 1 self.tmp.append(curr[:]) return for i in range(start, len(nums)): self.used[i] = True curr.append(nums[i]) self._dfs(nums, i + 1, curr) curr.pop() self.used[i] = False # @lc code=end
""" Objects dealing with EBUS boundaries for plotting, statistics, etc. Functions --------- - `visual_bounds` : lat/lon bounds for close-up shots of our regions. - `latitude_bounds` : lat bounds for statistical analysis To do ----- - `full_scope_bounds` : regions pulled from Chavez paper for lat/lon to show full system for validation """ def visual_bounds(EBC, std_lon=False): """ Returns the latitude and longitude bounds for plotting a decently large swatch of the EBC. Parameters ---------- EBC : str Identifier for the EBC. 'CalCS': California Current 'HumCS': Humboldt Current 'CanCS': Canary Current 'BenCS': Benguela Current std_lon : boolean (optional) Set to True if you desire -180 to 180 longitude. Returns ------- lon1 : int; minimum lon boundary lon2 : int; maximum lon boundary lat1 : int; minimum lat boundary lat2 : int; maximum lat boundary Examples -------- import esmtools.ebus as ebus x1,x2,y1,y2 = ebus.visual_bounds('CalCS') """ if EBC == 'CalCS': lat1 = 32 lat2 = 45 lon1 = -135 lon2 = -115 elif EBC == 'HumCS': lat1 = -20 lat2 = 0 lon1 = -85 lon2 = -70 elif EBC == 'CanCS': lat1 = 15 lat2 = 35 lon1 = -25 lon2 = -5 elif EBC == 'BenCS': lat1 = -30 lat2 = -15 lon1 = 5 lon2 = 20 else: raise ValueError('\n' + 'Must select from the following EBUS strings:' \ + '\n' + 'CalCS' + '\n' + 'CanCS' + '\n' + 'BenCS' + \ '\n' + 'HumCS') if (std_lon == False) & (EBC != 'BenCS'): lon1 = lon1 + 360 lon2 = lon2 + 360 return lon1,lon2,lat1,lat2 def latitude_bounds(EBC): """ Returns the standard 10 degrees of latitude to be analyzed for each system. For the CalCS, HumCS, and BenCS, this comes from the Chavez 2009 EBUS Comparison paper. For the CanCS, this comes from the Aristegui 2009 CanCS paper. These bounds are used in the EBUS CO2 Flux comparison study to standardize latitude. Parameters ---------- EBC : str Identifier for the boundary current. 'CalCS' : California Current 'HumCS' : Humboldt Current 'CanCS' : Canary Current 'BenCS' : Benguela Current Returns ------- lat1 : int Minimum latitude bound. lat2 : int Maximum latitude bound. Examples -------- import esmtools.ebus as eb y1,y2 = eb.boundaries.latitude_bounds('HumCS') """ if EBC == 'CalCS': lat1 = 34 lat2 = 44 elif EBC == 'HumCS': lat1 = -16 lat2 = -6 elif EBC == 'CanCS': lat1 = 21 lat2 = 31 elif EBC == 'BenCS': lat1 = -28 lat2 = -18 else: raise ValueError('\n' + 'Must select from the following EBUS strings:' + '\n' + 'CalCS' + '\n' + 'CanCS' + '\n' + 'BenCS' + '\n' + 'HumCS') return lat1, lat2
"""from discord.ext import commands import os import discord import traceback import asyncio import random rbtflag = False bot = commands.Bot(command_prefix='.', description='自動でチーム募集をするBOTです') client = discord.Client() token = os.environ['DISCORD_BOT_TOKEN'] recruit_message = {} lastest_recruit_data = {} cache_limit = 300 @bot.event async def on_reaction_add(reaction, user): message = reaction.message if(message.id in recruit_message and not user.bot): emj = str(reaction.emoji) await message.remove_reaction(emj, user) isFull = False if(emj == "⬆️" and user.id != recruit_message[message.id]["writer_id"]): if(recruit_message[message.id]["max_user"] == -1 or len(recruit_message[message.id]["users"]) < recruit_message[message.id]["max_user"]): if(user.id not in recruit_message[message.id]["users"]): recruit_message[message.id]["users"].append(user.id) if(recruit_message[message.id]["max_user"] != -1 and len(recruit_message[message.id]["users"]) >= recruit_message[message.id]["max_user"]): isFull = True elif(emj == "⬇️" and user.id != recruit_message[message.id]["writer_id"] and user.id in recruit_message[message.id]["users"]): recruit_message[message.id]["users"].remove(user.id) elif(emj == "✖" and user.id == recruit_message[message.id]["writer_id"]): isFull = True users_str = "{name} [{id}]".format(name = message.guild.get_member(recruit_message[message.id]["writer_id"]).name, id = str(message.guild.get_member(recruit_message[message.id]["writer_id"]))) if(message.guild.get_member(recruit_message[message.id]["writer_id"]).nick != None): users_str = "{name} [{id}]".format(name = message.guild.get_member(recruit_message[message.id]["writer_id"]).nick, id = str(message.guild.get_member(recruit_message[message.id]["writer_id"]))) if(isFull): users = recruit_message[message.id]["users"] lottery_user = recruit_message[message.id]["lottery_user"] title = recruit_message[message.id]["title"] room = recruit_message[message.id]["room"] writer_id = recruit_message[message.id]["writer_id"] del recruit_message[message.id] if(lottery_user != -1 and len(users) >= lottery_user): users = random.sample(users, lottery_user) full_users = users + [writer_id] for user_id in users: if(bot.get_user(user_id) != None): if(message.guild.get_member(user_id).nick != None): users_str += "\n{name} [{id}]".format(name = message.guild.get_member(user_id).nick, id = str(message.guild.get_member(user_id))) else: users_str += "\n{name} [{id}]".format(name = message.guild.get_member(user_id).name, id = str(message.guild.get_member(user_id))) users_str.rstrip() for user_id in users: if(bot.get_user(user_id) != None): if(user_id not in lastest_recruit_data and len(lastest_recruit_data) >= cache_limit): del lastest_recruit_data[lastest_recruit_data.keys()[0]] lastest_recruit_data[user_id] = { "title" : title, "users" : full_users } if(room != "-1"): await message.guild.get_member(user_id).send("{}の部屋番号は {} です".format(title, room)) if(writer_id not in lastest_recruit_data and len(lastest_recruit_data) >= cache_limit): del lastest_recruit_data[lastest_recruit_data.keys()[0]] lastest_recruit_data[writer_id] = { "title" : title, "users" : full_users } await message.edit(content = (title + " 募集終了\n```\n{} ```".format(users_str))) await message.remove_reaction("⬆️", bot.user) await message.remove_reaction("⬇️", bot.user) await message.remove_reaction("✖", bot.user) else: for user_id in recruit_message[message.id]["users"]: if(bot.get_user(user_id) != None): if(message.guild.get_member(user_id).nick != None): users_str += "\n{name} [{id}]".format(name = message.guild.get_member(user_id).nick, id = str(message.guild.get_member(user_id))) else: users_str += "\n{name} [{id}]".format(name = message.guild.get_member(user_id).name, id = str(message.guild.get_member(user_id))) else: recruit_message[message.id]["users"].remove(user_id) users_str.rstrip() rec_text = "募集中!" if(recruit_message[message.id]["lottery_user"] != -1): rec_text = "募集中!(抽選 {}人->{}人)".format(recruit_message[message.id]["max_user"], recruit_message[message.id]["lottery_user"]) await message.edit(content = (recruit_message[message.id]["title"] + " {rec_text} @{count}人(↑で参加 ↓で退出)\n```\n{str} ```".format(rec_text = rec_text, count = recruit_message[message.id]["max_user"] - len(recruit_message[message.id]["users"]), str = users_str))) recruit_message[message.id]["raw_message"] = message @bot.command() async def r(ctx, room_id = "-1"): sender_id = ctx.message.author.id if(sender_id in lastest_recruit_data and room_id != -1): title = lastest_recruit_data[sender_id]["title"] users = lastest_recruit_data[sender_id]["users"] notify_txt = "" for user_id in users: notify_txt += ctx.message.guild.get_member(user_id).mention + " " if(user_id != sender_id): await ctx.message.guild.get_member(user_id).send("{}の新しい部屋番号は {} です".format(title, room_id)) await ctx.send(notify_txt + "新しい部屋番号を送信しました") await ctx.message.delete() elif(bot.get_user(sender_id) != None): await ctx.send("{} 最後に参加した部屋が存在しないか、古すぎます。".format(bot.get_user(sender_id).mention)) await ctx.message.delete() @bot.command() async def s(ctx, room_id = "-1", title = "", max_user = 2, remain_time = 300): users_str = "{name} [{id}]".format(name = ctx.message.author.name, id = str(ctx.message.author)) if(ctx.message.author.nick != None): users_str = "{name} [{id}]".format(name = ctx.message.author.nick, id = str(ctx.message.author)) users_str.rstrip("") mes = await ctx.send(title + " 募集中! @{count}人(↑で参加 ↓で退出)\n```\n{str} ```".format(count = max_user, str = users_str)) recruit_message[mes.id] = { "room" : room_id, "time" : remain_time, "max_user" : max_user, "writer_id" : ctx.message.author.id, "title" : title, "users" : [], "raw_message" : mes, "lottery_user" : -1 } await ctx.message.delete() await mes.add_reaction("⬆️") await mes.add_reaction("⬇️") await mes.add_reaction("✖") @bot.command() async def l(ctx, room_id = "-1", title = "", max_user = 5, lottery_user = 2, remain_time = 300): users_str = "{name} [{id}]".format(name = ctx.message.author.name, id = str(ctx.message.author)) if(ctx.message.author.nick != None): users_str = "{name} [{id}]".format(name = ctx.message.author.nick, id = str(ctx.message.author)) users_str.rstrip("") mes = await ctx.send(title + " 募集中!(抽選 {max_user}人->{lottery_user}人) @{count}人(↑で参加 ↓で退出)\n```\n{str} ```".format(max_user = max_user, lottery_user = lottery_user, count = max_user, str = users_str)) recruit_message[mes.id] = { "room" : room_id, "time" : 300, "max_user" : max_user, "writer_id" : ctx.message.author.id, "title" : title, "users" : [], "raw_message" : mes, "lottery_user" : lottery_user } await ctx.message.delete() await mes.add_reaction("⬆️") await mes.add_reaction("⬇️") await mes.add_reaction("✖") @bot.command() async def s1(ctx, room_id = "-1", title = ""): users_str = "{name} [{id}]".format(name = ctx.message.author.name, id = str(ctx.message.author)) if(ctx.message.author.nick != None): users_str = "{name} [{id}]".format(name = ctx.message.author.nick, id = str(ctx.message.author)) users_str.rstrip("") mes = await ctx.send(title + " 募集中! @{count}人(↑で参加 ↓で退出)\n```\n{str} ```".format(count = 1, str = users_str)) recruit_message[mes.id] = { "room" : room_id, "time" : 300, "max_user" : 1, "writer_id" : ctx.message.author.id, "title" : title, "users" : [], "raw_message" : mes, "lottery_user" : -1 } await ctx.message.delete() await mes.add_reaction("⬆️") await mes.add_reaction("⬇️") await mes.add_reaction("✖") async def disconnect_timer(): while True: for mes_key in list(recruit_message.keys()): if(mes_key in recruit_message): mes = recruit_message[mes_key]["raw_message"] recruit_message[mes_key]["time"] = recruit_message[mes_key]["time"] - 1 if(recruit_message[mes_key]["time"] <= 0): users = recruit_message[mes_key]["users"] title = recruit_message[mes_key]["title"] room = recruit_message[mes_key]["room"] writer_id = recruit_message[mes_key]["writer_id"] lottery_user = recruit_message[mes_key]["lottery_user"] if(lottery_user != -1 and len(users) >= lottery_user): users = random.sample(users, lottery_user) full_users = users + [writer_id] del recruit_message[mes_key] users_str = "{name} [{id}]".format(name = mes.guild.get_member(writer_id).name, id = str(mes.guild.get_member(writer_id))) if(mes.guild.get_member(writer_id).nick != None): users_str = "{name} [{id}]".format(name = mes.guild.get_member(writer_id).nick, id = str(mes.guild.get_member(writer_id))) for user_id in users: if(bot.get_user(user_id) != None): if(user_id not in lastest_recruit_data and len(lastest_recruit_data) >= cache_limit): del lastest_recruit_data[lastest_recruit_data.keys()[0]] lastest_recruit_data[user_id] = { "title" : title, "users" : full_users } if(room != "-1"): await mes.guild.get_member(user_id).send("{}の部屋番号は {} です".format(title, room)) if(mes.guild.get_member(user_id).nick != None): users_str += "\n{name} [{id}]".format(name = mes.guild.get_member(user_id).nick, id = str(mes.guild.get_member(user_id))) else: users_str += "\n{name} [{id}]".format(name = mes.guild.get_member(user_id).name, id = str(mes.guild.get_member(user_id))) else: users.remove(user_id) users_str.rstrip() if(writer_id not in lastest_recruit_data and len(lastest_recruit_data) >= cache_limit): del lastest_recruit_data[lastest_recruit_data.keys()[0]] lastest_recruit_data[writer_id] = { "title" : title, "users" : full_users } await mes.edit(content = (title + " 募集終了\n```\n{} ```".format(users_str))) await mes.remove_reaction("⬆️", bot.user) await mes.remove_reaction("⬇️", bot.user) await mes.remove_reaction("✖", bot.user) await asyncio.sleep(1) @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') async def startup(): global bot await bot.login(token, bot=True) await bot.connect() bot.clear() async def logout(): global bot await bot.close()""" print("TEST")
#Calcula o volume de uma fossa sépica para estabelecimentos residenciais em conformidade com a NBR 7229/1993 ''' Entre com os dados da Fossa Séptica ''' print(' Dimensionamento de uma Fossa Séptica pra estabelecimentos residenciais em conformidade com a NBR 7229/1993:') N = 1 while N != 0: N = int(input('Digite o número de contribuintes ou 0 (zero) para encerrar:\n ')) if N == 0: print('Você finalizou o programa!') break elif N < 0: print('ERROR! Você digitou um valor inválido!\n Digite um valor maior que zero ou 0 para encerrar') continue else: temperatura = float(input('Digite a temperatura média do local em Graus Celsius:\n ')) limpeza = float(input('Digite o intervalo de limpeza em anos:\n ')) if limpeza < 0 or limpeza > 5: print('ERROR!O intervalo de limpeza deve está entre 1 ano e 5 anos!\n') continue else: padrao = input('Digite o padrão resiencial (a para alto, m para médio ou b para baixo):\n ') if padrao == 'a' or padrao == 'A': C = 160 padrao = 'alto' elif padrao == 'm' or padrao == 'M': C = 130 padrao = 'médio' elif padrao == 'b' or padrao == 'B': C = 100 padrao = 'baixo' else: print('ERROR!Verifique a opção desejada digite apenas a, b ou m!\n') continue if limpeza == 1: if temperatura <= 10: k = 94 elif temperatura > 10 and temperatura <= 20: k = 65 else: k = 57 elif limpeza == 2: if temperatura <= 10: k = 134 elif temperatura > 10 and temperatura <= 20: k = 105 else: k = 97 elif limpeza == 3: if temperatura <= 10: k = 174 elif temperatura > 10 and temperatura <= 20: k = 145 else: k = 137 elif limpeza == 4: if temperatura <= 10: k = 214 elif temperatura > 10 and temperatura <= 20: k = 185 else: k = 177 elif limpeza == 5: if temperatura <= 10: k = 254 elif temperatura > 10 and temperatura <= 20: k = 225 else: k = 217 contribuicao_diaria = N * C if contribuicao_diaria <= 0: print('ERRROR! Não é possível dimensionar o volume da fossa - N e C devem se maior que zero!') elif contribuicao_diaria > 0 and contribuicao_diaria<= 1500: T = T elif contribuicao_diaria > 1500 and contribuicao_diaria <= 3000: T = 0.92 elif contribuicao_diaria > 3000 and contribuicao_diaria <= 4500: T = 0.83 elif contribuicao_diaria > 4500 and contribuicao_diaria <= 6000: T = 0.75 elif contribuicao_diaria >= 6000 and contribuicao_diaria <= 7500: T = 0.67 elif contribuicao_diaria > 7500 and contribuicao_diaria <= 9000: T = 0.58 else: T = 0.50 Lf = 1 print('Tratando apenas de empreendimentos residenciais, conforme NBR 7229/1993 Lf = 1!') V = 1000 + N*(C*T + k*Lf) print('\nMEMÓRIA DE CÁLCULO\n') print(f'Polulação: {N} contribuintes;\nPadrão Residencial: {padrao};\nTemperatura Média: {temperatura}C;\nContribuição Diária (C): {C} Litros;\nTemmpo de Detenção (Td): {T};') print(f'Contribuição de Lodo Fresco (Lf): {Lf};\nIntervalo de Limmpeza {limpeza} anos;\nVolume Útil: {V} Litros\n')
# Computers are fast, so we can implement a brute-force search to directly solve the problem. def compute(): PERIMETER = 1000 for a in range(1, PERIMETER + 1): for b in range(a + 1, PERIMETER + 1): c = PERIMETER - a - b if a * a + b * b == c * c: # It is now implied that b < c, because we have a > 0 return str(a * b * c) if __name__ == "__main__": print(compute())
{ "targets": [ { "target_name": "yolo", "sources": [ "src/yolo.cc" ] } ] }
archivo = open('paises.txt', 'r') """" for pais_y_capital in archivo: print(pais_y_capital) """ #1. Cuente e imprima cuantas ciudades inician con la letra M """ archivo = open('paises.txt', 'r') lista=[] ciudad=[] for i in archivo: a=i.index(":") for r in range(a+2,len(i)): lista.append(i[r]) a="".join(lista) ciudad.append(a) lista=[] for i in ciudad: if(i[0]=="M"): print(i) lista.append(i) print(len(lista)) archivo.close() """ #2. Imprima todos los paises y capitales, cuyo inicio sea con la letra U """ archivo = open('paises.txt', 'r') print("Paises con inicial con la Letra U: ") lista1=[] paises=[] for i in archivo: a=i.index(":") for r in range(0,a): lista1.append(i[r]) a="".join(lista1) paises.append(a) lista1=[] for i in paises: if(i[0]=="U"): print(i) print("Capital con inicial con la Letra U: ") print() archivo = open('paises.txt', 'r') lista2=[] ciudad=[] for i in archivo: a=i.index(":") for r in range(a+2,len(i)): lista2.append(i[r]) a="".join(lista2) ciudad.append(a) lista2=[] for i in ciudad: if(i[0]=="U"): print(i) archivo.close() """ #3. Cuente e imprima cuantos paises que hay en el archivo """ archivo = open('paises.txt', 'r') c=0 lista=[] for i in archivo: lista.append(i) a=" ".join(lista) c=c+1 print(len(lista)) archivo.close() """ #4. Busque e imprima la ciudad de Singapur """ archivo = open('paises.txt', 'r') lista=[] for i in archivo: lista.append(i) a=" ".join(lista) if(a=="Singapur: Singapur\n"): break lista=[] b=a.index(":") lista2=[] for i in range(0,b): lista2.append(a[i]) unir="".join(lista2) print(unir) archivo.close() """ #5. Busque e imprima el pais de Venezuela y su capital """ archivo = open('paises.txt', 'r') lista=[] for i in archivo: lista.append(i) a=" ".join(lista) if(a=="Venezuela: Caracas\n"): break lista=[] print(a) archivo.close() """ #6. Cuente e imprima las ciudades que su pais inicie con la letra E """ archivo = open('paises.txt', 'r') lista=[] paises=[] for i in archivo: a=i.index(":") for r in range(0,a): lista.append(i[r]) a="".join(lista) paises.append(a) lista=[] for i in paises: if(i[0]=="E"): print(i) lista.append(i) print(len(lista)) archivo.close() """ #7. Buesque e imprima la Capiltal de Colombia """ archivo = open('paises.txt', 'r') lista=[] for i in archivo: lista.append(i) a=" ".join(lista) if(a=="Colombia: Bogotá\n"): break lista=[] b=a.index(":") tamaño=len(a) lista2=[] for i in range(b,tamaño): lista2.append(a[i]) unir="".join(lista2) print("La Capital de Colombia es: "+str(unir)) archivo.close() """ #8. imprima la posicion del pais de Uganda """ archivo = open('paises.txt', 'r') c=0 lista=[] for i in archivo: lista.append(i) a=" ".join(lista) c=c+1 if(a=="Uganda: Kampala\n"): break lista=[] print(c) archivo.close() """ #9. imprima la posicion del pais de Mexico """ archivo = open('paises.txt', 'r') lista=[] paises=[] for i in archivo: a=i.index(":") for r in range(0,a): lista.append(i[r]) a="".join(lista) paises.append(a) lista=[] x=paises.index("México")+1 print(x) archivo.close() """ #10. El alcalde de Antananarivo contrato a algunos alumnos de la Universidad Ean #para corregir el archivo de países.txt, ya que la capital de Madagascar NO es rey julien #es Antananarivo, espero que el alcalde se vaya contento por su trabajo. #Utilice un For para cambiar ese Dato """ with open('paise.txt') as archivo: lista=[] for i in archivo: lista.append(i) a=" ".join(lista) if(a=="Madagascar: rey julien\n"): break lista=[] b=a.index(":") tamaño=len(a) lista2=[] for i in range(0,tamaño): lista2.append(a[i]) lista2.remove("b") 2==("Antananarivo") lista2.insert(1,2) print(lista2) archivo.close() """ #11. Agregue un país que no esté en la lista """ archivo = open('paises.txt', 'r') P=0 lista=[] for i in archivo: lista.append(i) a=" ".join(lista) P=P+1 if(a=="Paises\n"): break b=a.index(":") tamaño=len(a) lista2=[] for i in range(0,tamaño): lista2.append(a[i]) lista2.insert(0,"Nabacasgar: Endananariva\n") unir="".join(lista2) print(unir) archivo.close() """
class Docs(object): def __init__(self, conn): self.client = conn.client def size(self): r = self.client.get('/docs/size') return int(r.text) def add(self, name, content): self.client.post('/docs', files={'upload': (name, content)}) def clear(self): self.client.delete('/docs') def get(self, name, stream=False, chunk_size=10240): with self.client.get('/docs/{}'.format(name), stream=stream) as r: yield r.iter_content( chunk_size=chunk_size) if stream else r.content def delete(self, name): self.client.delete('/docs/{}'.format(name))
class SlowDisjointSet: def __init__(self, N): self.N = N self._bubbles = [] for i in range(N): self._bubbles.append({i}) self._operations = 0 self._calls = 0 def _find_i(self, i): """ Find the index of the bubble that holds a particular value in the list of bubbles Parameters ---------- i: int Element we're looking for Returns ------- Index of the bubble containing i """ index = -1 k = 0 while k < len(self._bubbles) and index == -1: for item in self._bubbles[k]: self._operations += 1 if item == i: index = k break k += 1 return index def find(self, i, j): """ Return true if i and j are in the same component, or false otherwise Parameters ---------- i: int Index of first element j: int Index of second element """ self._calls += 1 id_i = self._find_i(i) id_j = self._find_i(j) if id_i == id_j: return True else: return False def union(self, i, j): """ Merge the two sets containing i and j, or do nothing if they're in the same set Parameters ---------- i: int Index of first element j: int Index of second element """ self._calls += 1 idx_i = self._find_i(i) idx_j = self._find_i(j) if idx_i != idx_j: # Merge lists # Decide that bubble containing j will be absorbed into # bubble containing i self._operations += len(self._bubbles[idx_i]) + len(self._bubbles[idx_j]) self._bubbles[idx_i] |= self._bubbles[idx_j] # Remove the old bubble containing j self._bubbles = self._bubbles[0:idx_j] + self._bubbles[idx_j+1::]
# -*- coding: utf-8 -*- class SmsTypes: class Country: RU = '0' # Россия (Russia) UA = '1' # Украина (Ukraine) KZ = '2' # Казахстан (Kazakhstan) CN = '3' # Китай (China) # PH = '4' # Филиппины (Philippines) MM = '5' # Мьянма (Myanmar) # ID = '6' # Индонезия (Indonesia) # MY = '7' # Малайзия (Malaysia) KE = '8' # Кения (Kenya) # TZ = '9' # Танзания (Tanzania) # VN = '10' # Вьетнам (Vietnam) KG = '11' # Кыргызстан (Kyrgyzstan) # US = '12' # США (USA) # IL = '13' # Израиль (Israel) # HK = '14' # Гонконг (Hong Kong) PL = '15' # Польша (Poland) UK = '16' # Великобритания/Англия (United Kingdom) # MG = '17' # Мадагаскар (Madagascar) # CG = '18' # Конго (Congo) NG = '19' # Нигерия (Nigeria) MO = '20' # Макао (Macau) EG = '21' # Египет (Egypt) # IN = '22' # Индия (India) # IE = '23' # Ирландия (Ireland) # KH = '24' # Камбоджа (Cambodia) # LA = '25' # Лаос (Lao) HT = '26' # Гаити (Haiti) CI = '27' # Кот д'Ивуар (Cote d'Ivoire) GM = '28' # Гамбия (Gambia) RS = '29' # Сербия (Serbian) YE = '30' # Йемен (Yemen) # ZA = '31' # ЮАР (South Africa) RO = '32' # Румыния (Romania) # CO = '33' # Колумбия (Colombia) EE = '34' # Эстония (Estonia) AZ = '35' # Азербайджан (Azerbaijan) # CA = '36' # Канада (Canada) # MA = '37' # Марокко (Morocco) GH = '38' # Гана (Ghana) # AR = '39' # Аргентина (Argentina) UZ = '40' # Узбекистан (Uzbekistan) # CM = '41' # Камерун (Cameroon) TG = '42' # Чад (Chad) DE = '43' # Германия (Germany) LT = '44' # Литва (Lithuania) HR = '45' # Хорватия ( Croatia) # ??? IQ = '47' # Ирак (Iraq) NL = '48' # Нидерланды (Netherlands) LV = '49' # Латвия (Latvia) AT = '50' # Австрия (Austria) BY = '51' # Белаурсь (Belarus) # TH = '52' # Таиланд (Thailand) # SA = '53' # Саудовская Аравия (Saudi Arabia) # MX = '54' # Мексика (Mexico) # TW = '55' # Тайвань (Taiwan) # ES = '56' # Испания (Spain) # IR = '57' # Иран (Iran) # DZ = '58' # Алжир (Algeria) SI = '59' # Словения (Slovenia) # BD = '60' # Бангладеш (Bangladesh) # SN = '61' # Сенегал (Senegal) # TR = '62' # Турция (Turkey) CZ = '63' # Чехия (Czechia) # LK = '64' # Шри-Ланка (Sri Lanka) # PE = '65' # Перу (Peru) # PK = '66' # Пакистан (Pakistan) NZ = '67' # Новая Зеландия (New Zealand) GN = '68' # Гвинея (Guinea) ML = '69' # Мали (Mali) # VE = '70' # Венесуэла (Venezuela) # ET = '71' # Эфиопия (Ethiopia) class Status: Cancel = '8' SmsSent = '1' OneMoreCode = '3' End = '6' # AlreadyUsed = '8' class Operator: MTS = 'mts' Beeline = 'beeline' MegaFon = 'megafon' TELE2 = 'tele2' AIVA = 'aiva' MOTIV = 'motiv' Rostelecom = 'rostelecom' SberMobile = 'sber' SimSim = 'simsim' Tinkoff = 'tinkoff' TTK = 'ttk' Yota = 'yota' Kievstar = 'kyivstar' Life = 'life' Utel = 'utel' Vodafone = 'vodafone' Altel = 'altel' ChinaUnicom = 'unicom' Any = 'any'
#!/bin/env python3 option = input("[E]ncryption, [D]ecryption, or [Q]uit -- ") def key_generation(a, b, a1, b1): M = a * b - 1 e = a1 * M + a d = b1 * M + b n = (e * d - 1) / M return int(e), int(d), int(n) def encryption(a, b, a1, b1): e, d, n = key_generation(a, b, a1, b1) print("You may publish your public key (n,e) = (", n, ", ", e, ")") print("and keep your private key (n,d) = (",n, ", ", d, ") secret.") plaintext = input("Plaintext - ") cipher = [] for i in range(len(plaintext)): cipher.append(str((ord(plaintext[i]) * e) % n)) ciphertext = " ".join(cipher) print(ciphertext) def decryption(): private = input("Your private key (n, d), separated by a space or comma -- ").replace(",", " ") n, d = list(map(int, private.split(" "))) ciphertext = input("Ciphertext (integers separated by spaces) -- ") cipher = list(map(int, ciphertext.split(" "))) plain = [] for i in range(len(cipher)): plain.append(str((cipher[i] * d) % n)) print(" ".join(plain)) plaintext = "" for i in range(len(plain)): plaintext += chr(int(plain[i])) print("Plaintext - ", plaintext) def main(): if option.upper() == "E": ints = input("Input 4 integers a, b, a', b' -- ") a, b, a1, b1 = list(map(int, ints.split(" "))) encryption(a, b, a1, b1) elif option.upper() == "D": decryption() else: return if __name__ == "__main__": main()
#!/usr/bin/env python # coding: utf-8 # # Seldon Kafka Integration Example with CIFAR10 Model # # In this example we will run SeldonDeployments for a CIFAR10 Tensorflow model which take their inputs from a Kafka topic and push their outputs to a Kafka topic. We will experiment with both REST and gRPC Seldon graphs. For REST we will load our input topic with Tensorflow JSON requests and for gRPC we will load Tensorflow PredictRequest protoBuffers. # ## Requirements # # * [Install gsutil](https://cloud.google.com/storage/docs/gsutil_install) # # In[ ]: get_ipython().system('pip install -r requirements.txt') # ## Setup Kafka # Install Strimzi on cluster # In[ ]: get_ipython().system('helm repo add strimzi https://strimzi.io/charts/') # In[ ]: get_ipython().system('helm install my-release strimzi/strimzi-kafka-operator') # Set the following to whether you are running a local Kind cluster or a cloud based cluster. # In[ ]: clusterType = "kind" # clusterType="cloud" # In[ ]: if clusterType == "kind": get_ipython().system('kubectl apply -f cluster-kind.yaml') else: get_ipython().system('kubectl apply -f cluster-cloud.yaml') # Get broker endpoint. # In[ ]: if clusterType == "kind": res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -n default -o=jsonpath='{.spec.ports[0].nodePort}'") port = res[0] get_ipython().run_line_magic('env', 'BROKER=172.17.0.2:$port') else: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.status.loadBalancer.ingress[0].hostname}'") if len(res) == 1: hostname = res[0] get_ipython().run_line_magic('env', 'BROKER=$h:9094') else: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.status.loadBalancer.ingress[0].ip}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER=$ip:9094') # In[ ]: get_ipython().run_cell_magic('writefile', 'topics.yaml', 'apiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-rest-input\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-rest-output\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-grpc-input\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-grpc-output\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1') # In[ ]: get_ipython().system('kubectl apply -f topics.yaml') # ## Install Seldon # # * [Install Seldon](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) # * [Follow our docs to intstall the Grafana analytics](https://docs.seldon.io/projects/seldon-core/en/latest/analytics/analytics.html). # ## Download Test Request Data # We have two example datasets containing 50,000 requests in tensorflow serving format for CIFAR10. One in JSON format and one as length encoded proto buffers. # In[ ]: get_ipython().system('gsutil cp gs://seldon-datasets/cifar10/requests/tensorflow/cifar10_tensorflow.json.gz cifar10_tensorflow.json.gz') get_ipython().system('gunzip cifar10_tensorflow.json.gz') get_ipython().system('gsutil cp gs://seldon-datasets/cifar10/requests/tensorflow/cifar10_tensorflow.proto cifar10_tensorflow.proto') # ## Test CIFAR10 REST Model # Upload tensorflow serving rest requests to kafka. This may take some time dependent on your network connection. # In[ ]: get_ipython().system('python ../../../util/kafka/test-client.py produce $BROKER cifar10-rest-input --file cifar10_tensorflow.json') # In[ ]: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.spec.clusterIP}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER_CIP=$ip') # In[ ]: get_ipython().run_cell_magic('writefile', 'cifar10_rest.yaml', 'apiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: tfserving-cifar10\nspec:\n protocol: tensorflow\n transport: rest\n serverType: kafka \n predictors:\n - componentSpecs:\n - spec:\n containers:\n - args: \n - --port=8500\n - --rest_api_port=8501\n - --model_name=resnet32\n - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32\n - --enable_batching\n image: tensorflow/serving\n name: resnet32\n ports:\n - containerPort: 8501\n name: http\n svcOrchSpec:\n env:\n - name: KAFKA_BROKER\n value: BROKER_IP\n - name: KAFKA_INPUT_TOPIC\n value: cifar10-rest-input\n - name: KAFKA_OUTPUT_TOPIC\n value: cifar10-rest-output\n graph:\n name: resnet32\n type: MODEL\n endpoint:\n service_port: 8501\n name: model\n replicas: 1') # In[ ]: get_ipython().system('cat cifar10_rest.yaml | sed s/BROKER_IP/$BROKER_CIP:9094/ | kubectl apply -f -') # Looking at the metrics dashboard for Seldon you should see throughput we are getting. For a single replica on GKE with n1-standard-4 nodes we can see roughly 150 requests per second being processed. # # ![rest](tensorflow-rest-kafka.png) # In[ ]: get_ipython().system('kubectl delete -f cifar10_rest.yaml') # ## Test CIFAR10 gRPC Model # Upload tensorflow serving rest requests to kafka. This is a file of protobuffer `tenserflow.serving.PredictRequest` ([defn](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/apis/predict.proto)). Each binary protobuffer is prefixed by the numbre of bytes. Out test-client python script reads them and sends to our topic. This may take some time dependent on your network connection. # In[ ]: get_ipython().system('python ../../../util/kafka/test-client.py produce $BROKER cifar10-grpc-input --file cifar10_tensorflow.proto --proto_name tensorflow.serving.PredictRequest') # In[ ]: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.spec.clusterIP}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER_CIP=$ip') # In[ ]: get_ipython().run_cell_magic('writefile', 'cifar10_grpc.yaml', 'apiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: tfserving-cifar10\nspec:\n protocol: tensorflow\n transport: grpc\n serverType: kafka \n predictors:\n - componentSpecs:\n - spec:\n containers:\n - args: \n - --port=8500\n - --rest_api_port=8501\n - --model_name=resnet32\n - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32\n - --enable_batching \n image: tensorflow/serving\n name: resnet32\n ports:\n - containerPort: 8500\n name: http\n svcOrchSpec:\n env:\n - name: KAFKA_BROKER\n value: BROKER_IP\n - name: KAFKA_INPUT_TOPIC\n value: cifar10-grpc-input\n - name: KAFKA_OUTPUT_TOPIC\n value: cifar10-grpc-output\n graph:\n name: resnet32\n type: MODEL\n endpoint:\n service_port: 8500\n name: model\n replicas: 2') # In[ ]: get_ipython().system('cat cifar10_grpc.yaml | sed s/BROKER_IP/$BROKER_CIP:9094/ | kubectl apply -f -') # Looking at the metrics dashboard for Seldon you should see throughput we are getting. For a single replica on GKE with n1-standard-4 nodes we can see around 220 requests per second being processed. # # ![grpc](tensorflow-grpc-kafka.png) # In[ ]: get_ipython().system('kubectl delete -f cifar10_grpc.yaml') # In[ ]:
# Code generated by ./release.sh. DO NOT EDIT. """Package version""" __version__ = "0.9.5-dev"
# Creates the file nonsilence_phones.txt which contains # all the phonemes except sil. source = open("slp_lab2_data/lexicon.txt", 'r') phones = [] # Get all the separate phonemes from lexicon.txt. for line in source: line_phones = line.split(' ')[1:] for phone in line_phones: phone = phone.strip(' ') phone = phone.strip('\n') if phone not in phones and phone!='sil': phones.append(phone) source.close() phones.sort() # Write phonemes to the file. wf = open("data/local/dict/nonsilence_phones.txt", 'w') for x in phones: wf.write(x+'\n') wf.close()
""" A basic doubly linked list implementation @author taylor.osmun """ class LinkedList(object): """ Internal object representing a node in the linked list @author taylor.osmun """ class _Node(object): def __init__(self, _data=None, _next=None, _prev=None): self.data = _data self.next = _next self.prev = _prev """ Construct a new linked list """ def __init__(self): self._first = None self._last = None self._size = 0 """ @return True IFF the list is empty """ def empty(self): return len(self) <= 0 """ Adds the given data to the beginning of the list @param data: The data to add """ def add_first(self, data): node = LinkedList._Node(data, _next=self._first) if self._first is None: self._first = node self._last = node else: self._first.prev = node self._first = node self._size += 1 """ Adds the given data to the end of the list @param data: The data to add """ def add_last(self, data): node = LinkedList._Node(data, _prev=self._last) if self._first is None: self._first = node self._last = node else: self._last.next = node self._last = node self._size += 1 """ Removes and returns the first element in the list @return The first element in the list @raise EmptyListException: If the list is empty when removal is attempted """ def remove_first(self): if self.empty(): raise EmptyListException() ret = self._first self._first = ret.next if self._first is not None: self._first.prev = None else: self._last = None self._size -= 1 return ret.data """ Removes and returns the last element in the list @return The last element in the list @raise EmptyListException: If the list is empty when removal is attempted """ def remove_last(self): if self.empty(): raise EmptyListException() ret = self._last self._last = ret.prev if self._last is not None: self._last.next = None else: self._first = None self._size -= 1 return ret.data def __len__(self): return self._size def __iter__(self): node = self._first while node is not None: yield node.data node = node.next def __str__(self): return '[%s]'%(','.join(map(str, self))) """ Thrown when a removal is attempted and the list is empty @author taylor.osmun """ class EmptyListException(IndexError): def __init__(self): super(EmptyListException, self).__init__()
class Computer(): def __init__(self, model, memory): self.mo = model self.me = memory c = Computer('Dell', '500gb') print(c.mo,c.me)
""" add 2 number """ def add(x, y): return x + y """ substract y from x """ def substract(x, y): return y - x
# Hier sehen wir, wie man eine Schleife baut # range macht uns eine Folge von Zahlen for index in range(10): # ab hier wird um 4 Leerzeichen eingerückt, so lange bis die Schleife vorbei ist print(index) # hier kommt alles, was die Schleife tun soll print('Jetzt sind wir fertig') # Bis zu welcher Zahl zählt die Schleife? # Bei welcher Zahl geht es los? # Hast du den Doppelpunkt gesehen? # Jetzt schreibe du eine Schleife, die von 0 bis 19 zählt ###### ###### Alter = 12 print('Mein Alter ist: ' + str(Alter)) # if Schleife # Eine if Schleife fragt eine Bedingung ab, und falls diese erfüllt ist, führt sie den Code danach aus # der : am Ende ist wichtig if Alter > 15: # ab hier wird um 4 Leerzeichen einerückt, so lange bis der Code innen zu Ende ist print('Ich bin älter als 15.') else: # man kann auch Code ausführen, wenn diese Bedingung nicht erfüllt ist print('Ich bin jünger als 15.') # Ändere jetzt das Alter auf 16 und sieh was passiert # es gibt noch eine weitere Art von Schleifen: # while macht etwas so lange, bis die Bedingung nicht mehr erfüllt ist # das heisst man weiß vorher manchmal gar nicht, wie oft die Schleife abläuft # hier müssen wir zuerst etwas wahres definieren: # wahr = True mach_weiter = True while mach_weiter == True: # wir vergleichen den Wert mit einem doppelten == # wir könnten auch vereinfacht sagen # while mach_weiter: print('Dieser Text kommt, bis du EXIT auf der Konsole eintippst') eingabe = input('Tippe hier:') if eingabe == 'EXIT': mach_weiter = False # hier setzen wir mach_weiter auf False (nur ein = zum setzen) # sind dir die Einrückungen aufgefallen? # du kannst da mal was ändern und sehen, dass der Code nicht mehr laufen wird
#!/usr/bin/env python files = [ "dpx_nuke_10bits_rgb.dpx", "dpx_nuke_16bits_rgba.dpx" ] for f in files: command += rw_command (OIIO_TESTSUITE_IMAGEDIR, f) # Additionally, test for regressions for endian issues with 16 bit DPX output # (related to issue #354) command += oiio_app("oiiotool") + " src/input_rgb_mattes.tif -o output_rgb_mattes.dpx >> out.txt;" command += oiio_app("idiff") + " src/input_rgb_mattes.tif output_rgb_mattes.dpx >> out.txt;" # Test reading and writing of stereo DPX (multi-image) #command += (oiio_app("oiiotool") + "--create 80x60 3 --text:x=10 Left " # + "--caption \"view angle: left\" -d uint10 -o L.dpx >> out.txt;") #command += (oiio_app("oiiotool") + "--create 80x60 3 --text:x=10 Right " # + "--caption \"view angle: right\" -d uint10 -o R.dpx >> out.txt;") command += (oiio_app("oiiotool") + "ref/L.dpx ref/R.dpx --siappend -o stereo.dpx >> out.txt;") command += info_command("stereo.dpx", safematch=True, hash=False, extraargs="--stats") command += oiio_app("idiff") + "-a stereo.dpx ref/stereo.dpx >> out.txt;" # Test read/write of 1-channel DPX -- take a color image, make it grey, # write it as 1-channel DPX, then read it again and compare to a reference. # The reference is stored as TIFF rather than DPX just because it has # fantastically better compression. command += oiiotool(OIIO_TESTSUITE_IMAGEDIR+"/dpx_nuke_16bits_rgba.dpx" " -chsum:weight=0.333,0.333,0.333 -chnames Y -ch Y -o grey.dpx") command += info_command("grey.dpx", safematch=True) command += diff_command("grey.dpx", "ref/grey.tif")
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} n # @return {ListNode} def removeNthFromEnd(self, head, n): def removeNthFromEnd_rec(head, n): if not head: return 0 my_pos = removeNthFromEnd_rec(head.next, n) + 1 if my_pos - 1 == n: head.next = head.next.next return my_pos pre_head = ListNode(0) pre_head.next = head first_pos = removeNthFromEnd_rec(pre_head, n) return pre_head.next
def validate_required_kwargs_are_not_empty(args_list, kwargs): """ This function checks whether all passed keyword arguments are present and that they have truthy values. ::args:: args_list - This is a list or tuple that contains all the arguments you want to query for. The arguments are strings seperated by comma. kwargs - A dictionary of keyword arguments you where you want to ascertain that all the keys are present and they have truthy values. """ for arg in args_list: if arg not in kwargs.keys(): raise TypeError(f"{arg} must be provided.") if not kwargs.get(arg): raise TypeError(f"{arg} cannot be empty.") return kwargs
__author__ = 'roeiherz' """ Design a method to find the frequency of occurrences of any given word in a book. What if we were running this algorithm multiplies times. """ def create_hashmap(book): hash_map = {} words = book.split(' ') for word in words: process_word = word.lower().replace(',', '').replace(".", "") if process_word in hash_map: hash_map[process_word] += 1 else: hash_map[process_word] = 1 return hash_map def word_freq_multiplies(hash_map, word=''): """ Keep dict of occurrences for each word """ if word not in hash_map: return None return hash_map[word] def word_freq_single(book, word=''): """ O(n) to go all over the book """ words = book.split(' ') tmp = 0 for wordd in words: process_word = wordd.lower().replace(',', '').replace(".", "") if process_word == word: tmp += 1 return tmp if __name__ == '__main__': book = "hello world" hash_map = create_hashmap(book) word_freq_multiplies(hash_map, word='')
def get_url(): return None result = get_url().text print(result)
myStr = input("Enter a String: ") count = 0 for letter in myStr: count += 1 print (count)
a = 1 b = 2 c = 3 def foo(): a = 1 b = 2 c = 3 foo() print('TEST SUCEEDED')
train = [[1,2],[2,3],[1,1],[2,2],[3,3],[4,2],[2,5],[5,5],[4,1],[4,4]] weights = [1,1,1] def perceptron_predict(inputs, weights): activation = weights[0] for i in range(len(inputs)-1): activation += weights[i+1] * inputs[i] return 1.0 if activation >= 0.0 else 0.0 for inputs in train: print(perceptron_predict(inputs,weights))
def msg_retry(self, buf): print("retry") return buf[1:] MESSAGES = {1: msg_retry}
print("WELCOME!\nTHIS IS A NUMBER GUESSING QUIZ ") num = 30 num_of_guesses = 1 guess = input("ARE YOU A KID?\n") while(guess != num): guess = int(input("ENTER THE NUMBER TO GUESS\n")) if guess > num: print("NOT CORRECT") print("LOWER NUMBER PLEASE!") num_of_guesses += 1 elif guess < num: print("NOT CORRECT") print("HIGHER NUMBER PLEASE!") num_of_guesses += 1 else: print("CONGRATULATION! YOU GUESSED THE NUMBER ") print("THE NUMBER IS ", num) print(num_of_guesses, "ATTEMPTS YOU USED TO ARIVE AT THE NUMBER ")
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? ![Image](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png) Above is a 7 x 3 grid. How many possible unique paths are there? Note: m and n will be at most 100. Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 """ class Solution: def uniquePaths(self, m: int, n: int) -> int: def select(total, down): if down > total - down: down = total - down ret = 1 for i in range(total, total - down, -1): ret *= i for i in range(1, down + 1, 1): ret = ret // i return ret total, down = m + n - 2, n - 1 return select(total, down)
MAX_FOOD_ON_BOARD = 25 # Max food on board EAT_RATIO = 0.50 # Ammount of snake length absorbed FOOD_SPAWN_RATE = 3 # Number of turns per food spawn HUNGER_THRESHOLD = 100 # Turns of inactivity before snake starvation SNAKE_STARTING_LENGTH = 3 # Snake starting size TURNS_PER_GOLD = 20 # Turns between the spawn of each gold food GOLD_VICTORY = 5 # Gold needed to win the game TURNS_PER_WALL = 5 # Turns between the span of each random wall WALL_START_TURN = 50 # The turn at which random walls will begin to spawn HEALTH_DECAY_RATE = 1 # The amount of health you lose each turn FOOD_VALUE = 30 # You gain this much health when you eat food (Advanced mode only)
def trier(Tab): Tri = dict(sorted(Tab.items(), key=lambda item: item[1], reverse=True)) return Tri def afficher(Tab): for Equipe,Score in Tab.items(): print(Equipe," : ",Score) def Tableau(Tab): Tab2=[] for Equipe in Tab: Tab2.append(Equipe[0]) return Tab2 def main(): #Groupe GA=["Italie","Pays de Galles","Turquie","Suisse"] GB=["Belgique","Danemark","Finlande","Russie"] GC=["Autriche","Pays-Bas","Ukraine","Macédoine du Nord"] GD=["Angleterre","Croatie","Rep. Tchèque","Ecosse"] GE=["Pologne","Espagne","Suède","Slovaquie"] GF=["France","Allemagne","Portugal","Hongrie"] #Score TabA={GA[0]:9,GA[1]:4,GA[2]:0,GA[3]:4} TabB={GB[0]:9,GB[1]:3,GB[2]:3,GB[3]:3} TabC={GC[0]:6,GC[1]:9,GC[2]:3,GC[3]:0} TabD={GD[0]:7,GD[1]:4,GD[2]:3,GD[3]:1} TabE={GE[0]:1,GE[1]:5,GE[2]:7,GE[3]:3} TabF={GF[0]:5,GF[1]:4,GF[2]:4,GF[3]:2} #Phase Finale TabFinal=[] #Affichage Tab_A = trier(TabA) ; afficher(Tab_A) print ("="*30) Tab_B = trier(TabB) ; afficher(Tab_B) print ("="*30) Tab_C = trier(TabC) ; afficher(Tab_C) print ("="*30) Tab_D = trier(TabD) ; afficher(Tab_D) print ("="*30) Tab_E = trier(TabE) ; afficher(Tab_E) print ("="*30) Tab_F = trier(TabF) ; afficher(Tab_F) #Selection TabFinal.extend((list(Tab_A.items())[0], list(Tab_A.items())[1])) TabFinal.extend((list(Tab_B.items())[0], list(Tab_B.items())[1])) TabFinal.extend((list(Tab_C.items())[0], list(Tab_C.items())[1])) TabFinal.extend((list(Tab_D.items())[0], list(Tab_D.items())[1])) TabFinal.extend((list(Tab_E.items())[0], list(Tab_E.items())[1])) TabFinal.extend((list(Tab_F.items())[0], list(Tab_F.items())[1])) #3eme TabFinal.append(list(Tab_A.items())[2]) TabFinal.append(list(Tab_D.items())[2]) TabFinal.append(list(Tab_F.items())[2]) TabFinal.append(list(Tab_C.items())[2]) # print (TabFinal) #Phase Finale PhaseFinale = Tableau(TabFinal) # print (PhaseFinale) #8eme de final print () print (PhaseFinale[1], " vs ", PhaseFinale[3]) print (PhaseFinale[0], " vs ", PhaseFinale[5]) print (PhaseFinale[4], " vs ", PhaseFinale[13]) print (PhaseFinale[2], " vs ", PhaseFinale[14]) print (PhaseFinale[7], " vs ", PhaseFinale[9]) print (PhaseFinale[10], " vs ", PhaseFinale[12]) print (PhaseFinale[6], " vs ", PhaseFinale[11]) print (PhaseFinale[8], " vs ", PhaseFinale[15]) print () print ("1/4 de finale") print ("Espagne vs Suisse") print ("Belgique vs Italie") print ("Ukraine vs Angleterre") print ("Rep. Tchèque vs Danemark") print () print ("1/2 finale") print ("Espagne vs Italie") print ("Angleterre vs Danemark") PhaseFinale.remove("Pays de Galles") PhaseFinale.remove("Autriche") PhaseFinale.remove("Pays-Bas") PhaseFinale.remove("Portugal") PhaseFinale.remove("Croatie") PhaseFinale.remove("France") PhaseFinale.remove("Allemagne") PhaseFinale.remove("Suède") PhaseFinale.remove("Suisse") PhaseFinale.remove("Belgique") PhaseFinale.remove("Ukraine") PhaseFinale.remove("Rep. Tchèque") PhaseFinale.remove("Espagne") PhaseFinale.remove("Danemark") print (PhaseFinale) if __name__=="__main__": main() ######################################################### '''>>> dict(sorted(x.items(), key=lambda item: item[1])) {0: 0, 2: 1, 1: 2, 4: 3, 3: 4} Test print (Tab_A.items()) print (list(Tab_A.items())[0] ---------- contacts.items() returns pairs of key-value. In your case, that would be something like (("John", 938477566), ("Jack", 938377264), ("Jill", 947662781)) Except that in python 3 this is like a generator and not a list. So you'd have to do list(contacts.items()) if you wanted to index it, which explains your error message. However, even if you did list(contacts.items())[0], as discussed above, you'd get the first pair of key-value. What you're trying to do is fetch the value of a key if said key exists and contacts.get(key, value_if_key_doesnt_exist) does that for you. contact = 'John' # we use 0 for the default value because it's falsy, # but you'd have to ensure that 0 wouldn't naturally occur in your values # or any other falsy value, for that matter. details = contacts.get(contact, 0) if details: print('Contact details: {} {}'.format(contact, details)) else: print('Contact not found') '''
# https://codeforces.com/problemset/problem/1399/A t = int(input()) for _ in range(t): length_a = int(input()) list_a = [int(x) for x in input().split()] list_a.sort() while True: if len(list_a) == 1: print('YES') break elif abs(list_a[0] - list_a[1]) <= 1: list_a.pop(0) else: print('NO') break
sentence = input().split() latin = "" for word in sentence: latin += word[1:] + word[0]+"ay " print(latin,end="")
modulename = "Help" creator = "YtnomSnrub" sd_structure = {}
class DeBracketifyMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): cleaned = request.GET.copy() for key in cleaned: if key.endswith('[]'): val = cleaned.pop(key) cleaned_key = key.replace('[]', '') cleaned.setlist(cleaned_key, val) request.GET = cleaned return self.get_response(request)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ SER-347 - Joao Felipe Lista-05 Exercício 02. Para criar uma senha na internet, geralmente são aplicados critérios de força da senha. Neste exercício, uma senha forte possui caracteres maiúsculos e minúsculos, e tem pelo menos 8 caracteres. Do contrário, é fraca. Crie um programa que leia uma senha e retorne se ela é forte ou fraca. """ senha = input('Digite sua senha: ') criterio = 0 # Minimo 8 caracteres if len(senha) > 8: criterio +=1 # Pelo menos uma letra maiuscula for letra in senha: if letra.isupper(): criterio +=1 break # Pelo menos uma letra minuscula for letra in senha: if letra.islower(): criterio +=1 break if criterio == 3: print('Senha FORTE.') else: print('Senha FRACA.') # END -----------------------