content
stringlengths
7
1.05M
# The MIT License # # Copyright (c) 2008 James Piechota # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class Error( Exception ): """Base exception class. Contains a string with an optional error message.""" def __init__( self, message ): self._message = message def __str__( self ): return self._message def __repr__( self ): return self._message def __unicode__( self ): return self._message def msg( self ): return self._message class UnitializedError( Error ): """Thrown when an unitialized variable is accessed.""" def __init__( self, message ): Error.__init__( self, message ) class BadArgumentError( Error ): """Thrown when an invalid argument is provided.""" def __init__( self, message ): Error.__init__( self, message ) class OutOfBoundsError( Error ): """Thrown when the value of an argument is outside the allow range.""" def __init__( self, message ): Error.__init__( self, message ) class UnsupportedError( Error ): """Thrown when an implemented feature is invoked.""" def __init__( self, message ): Error.__init__( self, message ) class ThirdPartyError( Error ): """Thrown when a third party library has an error.""" def __init__( self, message ): Error.__init__( self, message ) class SilentError( Error ): """Thrown when an error has occurred but no message should be printed. Either there's none to print or something else has already printed it.""" def __init__( self, message ): Error.__init__( self, message ) class AbortError( Error ): """Thrown when an operation has been aborted either by the user or otherwise.""" def __init__( self, message ): Error.__init__( self, message )
class Solution: def maxPower(self, s: str) -> int: power = [] i, temp = 1, "" for s_char in s: if s_char == temp: i += 1 else: power.append( i ) i = 1 temp = s_char power.append(i) return max(power)
# 共通の要素を取り出す my_frinends = {'A', 'C', 'D'} A_frinends = {'B', 'D', 'E', 'F'} print(my_frinends & A_frinends) # {'D'} # 種類を調べる fruits = ['apple', 'banana', 'apple', 'banana', 'orange'] kind = set(fruits) print(kind) # {'apple', 'banana', 'orange'}
def multiprocess_state_generator(video_frame_generator, stream_sha256): """Returns a packaged dict object for use in frame_process""" for frame in video_frame_generator: yield {'mode': 'video', 'main_sequence': True}
# Used Python for handling large integers for _ in range(int(input())): a,b = list(map(int,input().split())) print(a*b)
def solution(a, b): answer = '' month = {0:0, 1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31} day = {1:'FRI',2:'SAT',3:'SUN', 4:'MON',5:'TUE',6:'WED', 0:'THU'} d = 0 for i in range(0, a): d += month[i] d += b answer = day[(d % 7)] return answer
""" Você deve resolver o clássico exercício das 8 rainhas Nele o usuário lhe passa o tamanho do tabuleiro n (lembrar que tabuleiros são quadrados então o usuário só precisa lhe passar um inteiro) e você deve gerar uma todas as distribuições de n rainhas neste tabuleiro e imprimi-las de uma forma adequada. Veja o livro Beginning Python, na descrição do video para a explicação da solução, ou entre no dropbox para ver a solução comentada Esse exercício não é fácil!! Não se preocupe se você não conseguir """
# Function to calculate median def calcMedian(arr, startIndex, endIndex): index = ( startIndex + endIndex ) // 2 if (endIndex - startIndex + 1) % 2 == 0: # return median for even no of elements return ( arr[index] + arr[index + 1] ) // 2 else: # return median for odd no of elements return arr[index] # Get n n = int(input()) # Get list array X X = list(map(int, input().split())) X.sort() q1 = calcMedian(X, 0, n//2 - 1) q2 = calcMedian(X, 0, n-1) if n % 2 == 0: q3 = calcMedian(X, n//2, n-1) else: q3 = calcMedian(X, n//2 + 1, n-1) # Print result print(q1) print(q2) print(q3)
# -*- coding: utf-8 -*- # Initial permutation matrix PI = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7] # Initial key permutation matrix CP_1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4] # Shifted key permutation matrix to get Ki+1 CP_2 = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32] # Expanded matrix (48bits after expansion) XORed with Ki E = [32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1] # S-BOXES matrix S_BOXES = [ [[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13], ], [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5], [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15], [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9], ], [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7], [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12], ], [[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14], ], [[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9], [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14], [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3], ], [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11], [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8], [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6], [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13], ], [[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1], [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6], [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2], [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12], ], [[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7], [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2], [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8], [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11], ] ] # Permutation matrix following each S-BOX substitution for each round P = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25] # Final permutation matrix of data after the 16 rounds PI_1 = [40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25] # Matrix determining the shift for each round of keys ROUND_KEY_SHIFT = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1] ENCRYPTION = 1 DECRYPTION = 0 def string_to_bit_array(text): """Convert the string into a list of bits.""" array = list() for char in text: bin_val = bin_value(char, 8) # Get value of char in one byte array.extend([int(x) for x in list(bin_val)]) # Add the bits to the list return array def bit_array_to_string(array): """Transform bit array to string.""" result_string = ''.join( [chr(int(i, 2)) for i in [''.join([str(x) for x in s_bytes]) for s_bytes in split_into_n(array, 8)]] ) return result_string def bin_value(val, bit_size): """Return the binary value as a string of the given size.""" bin_val = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:] if len(bin_val) > bit_size: raise "Binary value larger than expected!" while len(bin_val) < bit_size: bin_val = "0" + bin_val # Add 0s to satisfy size return bin_val def split_into_n(s, n): """Split into lists - each of size 'n'.""" return [s[k:k + n] for k in range(0, len(s), n)] class Des: def __init__(self): self.text = None self.passwd = None self.keys = list() def run(self, key, text, action=ENCRYPTION, padding=False): """Run the DES algorithm.""" self.text = text self.passwd = key if padding and action == ENCRYPTION: self.add_padding() elif len(self.text) % 8 != 0: # If not padding specified data size must be multiple of 8 bytes raise "Data size should be multiple of 8" self.generate_keys() # Generate all the keys text_blocks = split_into_n(self.text, 8) # Split the text in blocks of 8 bytes so 64 bits result = list() for block in text_blocks: # Loop over all the blocks of data block = string_to_bit_array(block) # Convert the block in bit array block = self.permutation(block, PI) # Apply the initial permutation L, R = split_into_n(block, 32) # L(LEFT), R(RIGHT) temp = None for i in range(16): # Perform 16 rounds d_e = self.expansion(R, E) # Expand R to 48 bits if action == ENCRYPTION: temp = self.xor(self.keys[i], d_e) # Use the Ki when encrypting else: temp = self.xor(self.keys[15 - i], d_e) # Use the last key when decrypting temp = self.substitute(temp) # Apply the S-BOXES temp = self.permutation(temp, P) temp = self.xor(L, temp) L = R R = temp result += self.permutation(R + L, PI_1) # Perform the last permutation & append the RIGHT to LEFT final_res = bit_array_to_string(result) if padding and action == DECRYPTION: return self.remove_padding(final_res) # Remove the padding if decrypting and padding is used else: return final_res # Return the final string of processed data def substitute(self, d_e): """Substitute bytes using S-BOXES.""" sub_blocks = split_into_n(d_e, 6) # Split bit array into sub_blocks of 6 bits each result = list() for i in range(len(sub_blocks)): # For all the sub_blocks block = sub_blocks[i] row = int(str(block[0]) + str(block[5]), 2) # Find row with the first & last bit column = int(''.join([str(x) for x in block[1:][:-1]]), 2) # Column value based on 2nd, 3rd, 4th & 5th bit val = S_BOXES[i][row][column] # Resulting value in the S-BOX for specific round bin = bin_value(val, 4) # Convert decimal value to binary result += [int(x) for x in bin] # Append the binary to the resulting list return result def permutation(self, block, table): """Perform permutation of the given block using the given table.""" return [block[x - 1] for x in table] def expansion(self, block, table): """Perform expansion of d to mach the size of Ki (48 bits).""" return [block[x - 1] for x in table] def xor(self, t1, t2): """Perform XOR & return the list.""" return [x ^ y for x, y in zip(t1, t2)] def generate_keys(self): """Generate all the keys.""" self.keys = [] key = string_to_bit_array(self.passwd) key = self.permutation(key, CP_1) # Perform initial permutation on the key g, d = split_into_n(key, 28) # Split into g (LEFT) & d (RIGHT) for i in range(16): # Apply the 16 rounds g, d = self.shift(g, d, ROUND_KEY_SHIFT[i]) # Shift the key according to the round tmp = g + d # Merge them self.keys.append(self.permutation(tmp, CP_2)) # Perform the permutation to get the Ki def shift(self, g, d, n): """Shift a list of the given value.""" return g[n:] + g[:n], d[n:] + d[:n] def add_padding(self): """Add padding to the data according to PKCS5 specification.""" pad_len = 8 - (len(self.text) % 8) self.text += pad_len * chr(pad_len) def remove_padding(self, data): """Remove the padding from the data.""" pad_len = ord(data[-1]) return data[:-pad_len] def encrypt(self, key, text, padding=True): """Perform encryption.""" return self.run(key, text, ENCRYPTION, padding) def decrypt(self, key, text, padding=True): """Perform decryption.""" return self.run(key, text, DECRYPTION, padding) if __name__ == '__main__': # des_algorithm.py executed as script print("Nothing to execute!")
""" Classes for IMPACTS P3 Instruments """ class P3(object): """ """ def __init__(self, filepath, date): pass def readfile(self, filepath, ): pass
class Solution: # @param {integer[]} nums # @return {integer} def singleNumber(self, nums): a = set(nums) a = sum(a)*2 singleNumber = a - sum(nums) return singleNumber
#!/usr/bin/env python3 # Transistors. "2N3904" "2SC1815" # NPN? "2SA9012" "2SA1015" # PNP?
# coding: utf-8 __all__ = ['EikonError'] class EikonError(Exception): """ Base class for exceptions specific to Eikon platform. """ def __init__(self, code, message): """ Parameters ---------- code: int message: string Indicate the sort direction. Possible values are 'asc' or 'desc'. The default value is 'asc' """ self.code = code self.message = message def __str__(self): return 'Error code {} | {}'.format(self.code, self.message)
class Car: # constructor def __init__(self,name,fuel,consumption,passengers,capacity): self.name = name self.fuel = fuel self.consumption = consumption self.km = 0.0 self.passengers = passengers self.capacity = capacity # Behavior def print_car(self): print(f'--- Car {self.name} ---\n| km: {self.km}\n| fuel: {self.fuel}\n| Passengers: {self.passengers}') def move(self,km): if( km <= (self.fuel / self.consumption)): ## move self.km += km self.fuel -= km / self.consumption else: # move as fas as car can # calculate max km maxKm = self.fuel / self.consumption self.km += maxKm self.fuel = 0 print(f"Car {self.name} cannot move further. Please go to the nearest gas station!") def get_passenger(self,passanger): if (self.capacity > len(self.passengers)): # get passenger self.passengers.append(passanger) else: # cannot print(f"There is no space for Passenger {passanger}") def get_fuel(self,newFuel): self.fuel += newFuel def get_passengers(self,passengers): if len(passengers) < 2: # warn print("Please use approprate function") else: for passanger in passengers: self.get_passenger(passanger)
name = "pyilmbase" version = "2.1.0" description = \ """ IlmBase Python bindings """ variants = [ ["platform-linux"] ] requires = [ "ilmbase-%s" % (version), "python", "boost" ] uuid = "repository.pyilmbase" def commands(): env.PATH.prepend("{root}/bin") env.LD_LIBRARY_PATH.prepend("{root}/lib") env.PYTHONPATH.append("{root}/lib/python2.7/site-packages")
vector = [{"name": "John Doe", "age": 37}, {"name": "Anna Doe", "age": 35}] # for item in vector: # print(item["name"]) print(list(map(lambda item: item["name"], vector)))
# -*- coding: utf-8 -*- """ Created on Sat Feb 9 19:48:15 2019 @author: Utente """ #Exercises Chapter 3 #3.2 do_four def do_twice(func, arg): func(arg) func(arg) def print_twice(arg): print(arg) print(arg) def do_four(func, arg): do_twice(func, arg) do_twice(func, arg) do_twice(print_twice, 'cazzo vuoi') print('') do_four(print_twice, 'cazzo vuoi') #3.3 grid def re_do_twice(f): f() f() def re_do_four(f): re_do_twice(f) re_do_twice(f) def print_beam(): print('+ - - - -', end=' ') def print_post(): print('| ', end=' ') def print_beams(): re_do_twice(print_beam) print('+') def print_posts(): re_do_twice(print_post) print('|') def print_row(): print_beams() re_do_four(print_posts) def print_grid(): re_do_twice(print_row) print_beams() print_grid() #3.3 grid part two def one_four_one(f, g, h): f() re_do_four(g) h() def print_A(): print('+', end=' ') def print_Z(): print('-', end=' ') def print_C(): print('|', end=' ') def print_O(): print('O', end=' ') def print_end(): print(' ') def nothing(): "do nothing" def print1beam(): one_four_one(nothing, print_Z, print_A) def print1post(): one_four_one(nothing, print_O, print_C) def print4beams(): one_four_one(print_A, print1beam, print_end) def print4posts(): one_four_one(print_C, print1post, print_end) def print_row(): one_four_one(nothing, print4posts, print4beams) def print_grid(): one_four_one(print4beams, print_row, nothing) print_grid()
class FormattedWord: def __init__(self, word, capitalize=False) -> None: self.word = word self.capitalize = capitalize class Sentence(list): def __init__(self, plain_text): for word in plain_text.split(' '): self.append(FormattedWord(word)) def __str__(self) -> str: return ' '.join([ formatted.word.upper() if formatted.capitalize else formatted.word for formatted in self ]) if __name__ == '__main__': sentence = Sentence('hello world') sentence[1].capitalize = True print(sentence)
""" mat data format { 1989: { 'AKS': { 2: (0.0534,0.1453) # age 2 (maturation rate, adult equivalent factor), 3: (0.0534,0.1453), # same format for age 3, 4: (0.0534,0.1453) # same format for age 4 }, ... }, ... } """ def parse_mat(file): years = {} curr_year = None for line in file: if not line.startswith(" "): curr_year = int(line) years[curr_year] = {} else: row = line.split() stock = row[0].replace(",", "") years[curr_year][stock] = { 2: (float(row[1]), float(row[2])), 3: (float(row[3]), float(row[4])), 4: (float(row[5]), float(row[6])), } return years def write_mat(data, file): for yr, stocks in sorted(data.items()): file.write(f"{yr}\n") for name, stock in sorted(stocks.items()): file.write( f" {name}, {stock[2][0]:6.4f} {stock[2][1]:6.4f} {stock[3][0]:6.4f} {stock[3][1]:6.4f} {stock[4][0]:6.4f} {stock[4][1]:6.4f}\n" ) def parse_msc(file): """ format: {'maturation_file': 'input/hanford.mat', 'stocks': [('AKS', 'Alaska Spring'), ('BON', 'Bonneville'), ('CWF', 'Cowlitz Fall'), ('GSH', 'Georgia Strait Hatchery'), ('LRW', 'Lewis River Wild'), ('ORC', 'Oregon Coastal'), ('RBH', 'Robertson Creek Hatchery'), ('RBT', 'WCVI Wild'), ('SPR', 'Spring Creek'), ('URB', 'Columbia River Upriver Bright'), ('WSH', 'Willamette Spring')]} """ msc = {"maturation_file": next(file).split()[0], "stocks": []} for line in file: row = line.split(",") msc["stocks"].append((row[0], row[1].strip())) return msc def write_msc(data, file): file.write(f"{data['maturation_file']} , Name of maturation data file\n") for stock in data["stocks"]: file.write(f"{stock[0]}, {stock[1]}\n")
casa = float(input('Valor da casa: R$')) salario = float(input('Salario do comprador R$')) anos = int(input('Quantos anos de financiamento? ')) prestacao = casa / (anos * 12) minimo = salario * 30 / 100 print('Para pagar uma casa de R${:.2f} em {} anos'.format(casa, anos)) if prestacao < minimo: print('Emprestimo pode ser CONCEDITO!') else: print('Emprestimo NEGADO!')
class AutomatonListHelper: ''' ' Removes repeated elements from a list ' ' @param list array List that will be iterate ' ' @return list ''' @staticmethod def removeDuplicates(array): final_list = [] for num in array: if num not in final_list: final_list.append(num) return final_list ''' ' Returns list element of largest size without elements that have already been visited ' (if all lists have elements visited, returns None) ' If all lists are of size 1, return None and update stack of states to be processed ' ' @param list array List to be iterate ' @param dictionary visited Elements to be ignored ' @param list stackProcess Stack that will be filled if all lists are of size 1 ' ' @return string | int | float | None ''' @staticmethod def largestElementSize_NotVisited(array, visited, stackProcess): if not array: return None highestIndex = 0 highestLength = 0 for i in range(len(array)): equals = False s = '' if len(array[i]) > highestLength: for item in array[i]: s += item if visited.get(s) != None: equals = True if not equals: highestIndex = i highestLength = len(array[i]) elif len(array[i]) == highestLength: s = '' for item in array[i]: s += item if visited.get(s) != None: equals = True if not equals: highestIndex = i highestLength = len(array[i]) if highestLength == 1: for item in array: if item: item = item[0] # If the element is not in the stack and has not been processed, put it in if stackProcess.count(item) == 0 and visited.get(item) == None: stackProcess.append(item) return None elif highestLength == 0: return None else: return array[highestIndex]
#! /usr/bin/python3 def print_sorted_dictionary_pairs(dict): for key in sorted(dict): print(key, dict[key]) def add_or_change_dictionary_value(dict, key, value): dict[key] = value def delete_dictionary_entry(dict, key): if key in dict: del dict[key] else: print(key, 'not found in dictionary') def dictionary_from_file(filename): try: file = open(filename, 'r') except: print('Cannot open file', filename) else: dict = {} for line in file: list = line.split() key = list[0] value = list[1] dict[key] = value file.close() return dict names_emails = dictionary_from_file('names_emails.txt') for key in names_emails: print(key, names_emails[key]) print_sorted_dictionary_pairs(names_emails) print() add_or_change_dictionary_value(names_emails, 'George', 'george@hotmail.com') add_or_change_dictionary_value(names_emails, 'Alan', 'alan.hurley@gmail.com') print('Entries: ', len(names_emails)) print_sorted_dictionary_pairs(names_emails) print() delete_dictionary_entry(names_emails, 'xxxx') delete_dictionary_entry(names_emails, 'George') print_sorted_dictionary_pairs(names_emails) print('Entries:', len(names_emails))
######################################################################## def clamp(value, minimum=0.0, maximum=1.0): return min(maximum, max(minimum, value)) ######################################################################## def find_all_by_name(name, list_entities): name = name.lower() for entity in list_entities: if entity.match(name): yield entity ######################################################################## def double_find_by_name(name, list_entities): """First try to find an exact match, then try to do a less exact match""" name = name.lower() for entity in list_entities: if entity.match_full(name): return entity for entity in list_entities: if entity.match(name): return entity
def printPacket(packet): print(packet.to_json())
''' Tipo: Concepto, Ejercicio, Pregunta... Fuente: libro, curso, ... Este chunk tiene como propósito revisar cocneptos fundamentales. Variable de isntancia Variable de clase Una diferencia importante entre clase e instancia e sla forma de usarse, están fuera del constructor __init__() Método de Instancias Método de Clase Método de Estpatico: Se prefeire e a veces métodos estáticos, la funcioanldiad está estrechamente relacioanda con la clase, se cumple principio de abstracción. Método especiales: __init__(): Los dunder methods. ''' class Persona(): # Variable de clase edad = 18 # Sirve para personalzia la creación de las instancias de las clases. # Podemos trabajr los inmutables # New no necesita self, sino uan referencia a la clase que lo invoca, es un método estático que devuele un objeto. # En teoria va primero, se ejecuta primero. El es el que realmente cra la clase y lo mandar a incialziar def __new__(cls, nombre, nacionalidad): print("New class") # __new__ debe regresar un objeto. Se usa super para regresar una instancia # Si no se retorna nada, la instancia no se inicialzia. return super().__new__(cls) # Constructor, inicializa def __init__(self, nombre, nacionalidad): print("Ininitialization of the instance") self.nombre = nombre self.nacionalidad = nacionalidad # Método de instancia requiere de la variable self. def nadar(self): print("Nada de nada") # Método de clase no posee la variable self. Pero si la variable "cls" # Un método de clase solo funciona con una directiva espcial llamada classsmethod. # Existen diferenters decoradores. Este nos permite no crear un objeto usarse sin instanciar @classmethod def saludar(cls, nombre): print("Hola "+nombre) # Método estático # No requiere de ningún argumento y se usa el decorador staticmethod @staticmethod def brincar(): print("Brincar<!!!") # El área de un círculo puede ser una propiedad no necesariamente un método # Es decir peudo expresarlo como un método de instancia, clase, estático, variable. # Lo correcto será como una propiedad. class Circulo(): def __init__(self, radio): self.radio = radio # Para declarar propeidades usamos el decorador @property # Nos va a permitir acceder a una propiedad de un objeto creado en python. objeto.propiedad @property def area(self): return 3.1416*(self.radio**2) # ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ # La variable de isntancia de instancia son las precedidas del nombre de self.variable_instancia stuff = Persona("José", "México") print(stuff.edad) #18. No necesita crear una nstancia para poder acceder a este. # print(Persona.nombre) #Arroha error, debido a que no está inicialziado el objeto. #Método de clase. Persona.saludar("Pepe") # Método Estático stuff.brincar() # ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ circle = Circulo(10) # 314.15999999999997 # se invoca como una propeidad del objeto instanciado. print(circle.area)
# -*- coding: utf-8 -*- #----------- #@utool.indent_func('[harn]') @profile def test_configurations(ibs, acfgstr_name_list, test_cfg_name_list): r""" Test harness driver function CommandLine: python -m ibeis.expt.harness --exec-test_configurations --verbtd python -m ibeis.expt.harness --exec-test_configurations --verbtd --draw-rank-cdf --show Example: >>> # SLOW_DOCTEST >>> from ibeis.expt.harness import * # NOQA >>> import ibeis >>> ibs = ibeis.opendb('PZ_MTEST') >>> acfgstr_name_list = ut.get_argval(('--aidcfg', '--acfg', '-a'), type_=list, default=['candidacy:qsize=20,dper_name=1,dsize=10', 'candidacy:qsize=20,dper_name=10,dsize=100']) >>> test_cfg_name_list = ut.get_argval('-t', type_=list, default=['custom', 'custom:fg_on=False']) >>> test_configurations(ibs, acfgstr_name_list, test_cfg_name_list) >>> ut.show_if_requested() """ testres_list = run_test_configurations2(ibs, acfgstr_name_list, test_cfg_name_list) for testres in testres_list: if testres is None: return else: experiment_printres.print_results(ibs, testres) experiment_drawing.draw_results(ibs, testres) return testres_list #def get_cmdline_testres(): # ibs, qaids, daids = main_helpers.testdata_expanded_aids(verbose=False) # test_cfg_name_list = ut.get_argval('-t', type_=list, default=['custom', 'custom:fg_on=False']) # testres = run_test_configurations(ibs, qaids, daids, test_cfg_name_list) # return ibs, testres
# # PySNMP MIB module IANA-PWE3-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-PWE3-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:30:09 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") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Gauge32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, IpAddress, iso, ModuleIdentity, mib_2, TimeTicks, Counter32, NotificationType, Bits, ObjectIdentity, MibIdentifier, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "IpAddress", "iso", "ModuleIdentity", "mib-2", "TimeTicks", "Counter32", "NotificationType", "Bits", "ObjectIdentity", "MibIdentifier", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") ianaPwe3MIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 174)) ianaPwe3MIB.setRevisions(('2009-06-11 00:00',)) if mibBuilder.loadTexts: ianaPwe3MIB.setLastUpdated('200906110000Z') if mibBuilder.loadTexts: ianaPwe3MIB.setOrganization('IANA') class IANAPwTypeTC(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32767)) namedValues = NamedValues(("other", 0), ("frameRelayDlciMartiniMode", 1), ("atmAal5SduVcc", 2), ("atmTransparent", 3), ("ethernetTagged", 4), ("ethernet", 5), ("hdlc", 6), ("ppp", 7), ("cem", 8), ("atmCellNto1Vcc", 9), ("atmCellNto1Vpc", 10), ("ipLayer2Transport", 11), ("atmCell1to1Vcc", 12), ("atmCell1to1Vpc", 13), ("atmAal5PduVcc", 14), ("frameRelayPortMode", 15), ("cep", 16), ("e1Satop", 17), ("t1Satop", 18), ("e3Satop", 19), ("t3Satop", 20), ("basicCesPsn", 21), ("basicTdmIp", 22), ("tdmCasCesPsn", 23), ("tdmCasTdmIp", 24), ("frDlci", 25), ("wildcard", 32767)) class IANAPwPsnTypeTC(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6)) namedValues = NamedValues(("mpls", 1), ("l2tp", 2), ("udpOverIp", 3), ("mplsOverIp", 4), ("mplsOverGre", 5), ("other", 6)) class IANAPwCapabilities(TextualConvention, Bits): status = 'current' namedValues = NamedValues(("pwStatusIndication", 0), ("pwVCCV", 1)) mibBuilder.exportSymbols("IANA-PWE3-MIB", IANAPwCapabilities=IANAPwCapabilities, IANAPwPsnTypeTC=IANAPwPsnTypeTC, ianaPwe3MIB=ianaPwe3MIB, IANAPwTypeTC=IANAPwTypeTC, PYSNMP_MODULE_ID=ianaPwe3MIB)
# expected data for tests using FBgn0031208.gff and FBgn0031208.gtf files # list the children and their expected first-order parents for the GFF test file. GFF_parent_check_level_1 = {'FBtr0300690':['FBgn0031208'], 'FBtr0300689':['FBgn0031208'], 'CG11023:1':['FBtr0300689','FBtr0300690'], 'five_prime_UTR_FBgn0031208:1_737':['FBtr0300689','FBtr0300690'], 'CDS_FBgn0031208:1_737':['FBtr0300689','FBtr0300690'], 'intron_FBgn0031208:1_FBgn0031208:2':['FBtr0300690'], 'intron_FBgn0031208:1_FBgn0031208:3':['FBtr0300689'], 'FBgn0031208:3':['FBtr0300689'], 'CDS_FBgn0031208:3_737':['FBtr0300689'], 'CDS_FBgn0031208:2_737':['FBtr0300690'], 'exon:chr2L:8193-8589:+':['FBtr0300690'], 'intron_FBgn0031208:2_FBgn0031208:4':['FBtr0300690'], 'three_prime_UTR_FBgn0031208:3_737':['FBtr0300689'], 'FBgn0031208:4':['FBtr0300690'], 'CDS_FBgn0031208:4_737':['FBtr0300690'], 'three_prime_UTR_FBgn0031208:4_737':['FBtr0300690'], } # and second-level . . . they should all be grandparents of the same gene. GFF_parent_check_level_2 = { 'CG11023:1':['FBgn0031208'], 'five_prime_UTR_FBgn0031208:1_737':['FBgn0031208'], 'CDS_FBgn0031208:1_737':['FBgn0031208'], 'intron_FBgn0031208:1_FBgn0031208:2':['FBgn0031208'], 'intron_FBgn0031208:1_FBgn0031208:3':['FBgn0031208'], 'FBgn0031208:3':['FBgn0031208'], 'CDS_FBgn0031208:3_737':['FBgn0031208'], 'CDS_FBgn0031208:2_737':['FBgn0031208'], 'exon:chr2L:8193-8589:+':['FBgn0031208'], 'intron_FBgn0031208:2_FBgn0031208:4':['FBgn0031208'], 'three_prime_UTR_FBgn0031208:3_737':['FBgn0031208'], 'FBgn0031208:4':['FBgn0031208'], 'CDS_FBgn0031208:4_737':['FBgn0031208'], 'three_prime_UTR_FBgn0031208:4_737':['FBgn0031208'], } # Same thing for GTF test file . . . GTF_parent_check_level_1 = { 'exon:chr2L:7529-8116:+':['FBtr0300689'], 'exon:chr2L:7529-8116:+_1':['FBtr0300690'], 'exon:chr2L:8193-9484:+':['FBtr0300689'], 'exon:chr2L:8193-8589:+':['FBtr0300690'], 'exon:chr2L:8668-9484:+':['FBtr0300690'], 'exon:chr2L:10000-11000:-':['transcript_Fk_gene_1'], 'exon:chr2L:11500-12500:-':['transcript_Fk_gene_2'], 'CDS:chr2L:7680-8116:+':['FBtr0300689'], 'CDS:chr2L:7680-8116:+_1':['FBtr0300690'], 'CDS:chr2L:8193-8610:+':['FBtr0300689'], 'CDS:chr2L:8193-8589:+':['FBtr0300690'], 'CDS:chr2L:8668-9276:+':['FBtr0300690'], 'CDS:chr2L:10000-11000:-':['transcript_Fk_gene_1'], 'FBtr0300689':['FBgn0031208'], 'FBtr0300690':['FBgn0031208'], 'transcript_Fk_gene_1':['Fk_gene_1'], 'transcript_Fk_gene_2':['Fk_gene_2'], 'start_codon:chr2L:7680-7682:+':['FBtr0300689'], 'start_codon:chr2L:7680-7682:+_1':['FBtr0300690'], 'start_codon:chr2L:10000-11002:-':['transcript_Fk_gene_1'], 'stop_codon:chr2L:8611-8613:+':['FBtr0300689'], 'stop_codon:chr2L:9277-9279:+':['FBtr0300690'], 'stop_codon:chr2L:11001-11003:-':['transcript_Fk_gene_1'], } GTF_parent_check_level_2 = { 'exon:chr2L:7529-8116:+':['FBgn0031208'], 'exon:chr2L:8193-9484:+':['FBgn0031208'], 'exon:chr2L:8193-8589:+':['FBgn0031208'], 'exon:chr2L:8668-9484:+':['FBgn0031208'], 'exon:chr2L:10000-11000:-':['Fk_gene_1'], 'exon:chr2L:11500-12500:-':['Fk_gene_2'], 'CDS:chr2L:7680-8116:+':['FBgn0031208'], 'CDS:chr2L:8193-8610:+':['FBgn0031208'], 'CDS:chr2L:8193-8589:+':['FBgn0031208'], 'CDS:chr2L:8668-9276:+':['FBgn0031208'], 'CDS:chr2L:10000-11000:-':['Fk_gene_1'], 'FBtr0300689':[], 'FBtr0300690':[], 'transcript_Fk_gene_1':[], 'transcript_Fk_gene_2':[], 'start_codon:chr2L:7680-7682:+':['FBgn0031208'], 'start_codon:chr2L:10000-11002:-':['Fk_gene_1'], 'stop_codon:chr2L:8611-8613:+':['FBgn0031208'], 'stop_codon:chr2L:9277-9279:+':['FBgn0031208'], 'stop_codon:chr2L:11001-11003:-':['Fk_gene_1'], } expected_feature_counts = { 'gff3':{'gene':3, 'mRNA':4, 'exon':6, 'CDS':5, 'five_prime_UTR':1, 'intron':3, 'pcr_product':1, 'protein':2, 'three_prime_UTR':2}, 'gtf':{ #'gene':3, # 'mRNA':4, 'CDS':6, 'exon':7, 'start_codon':3, 'stop_codon':3} } expected_features = {'gff3':['gene', 'mRNA', 'protein', 'five_prime_UTR', 'three_prime_UTR', 'pcr_product', 'CDS', 'exon', 'intron'], 'gtf':['gene', 'mRNA', 'CDS', 'exon', 'start_codon', 'stop_codon']}
# [FORMATADOR DE NOTAS KINDLE EM PADRÃO ACADÊMICO ABNT DE CITAÇÃO e REFERÊNCIA] # Função de Tratamento das notas def tratamento_arquivo(arquivo): conteudo = [] paginas = [] checador_final = 0 while arquivo != '': # Encontrando strings que caracterizam o início e o fim do texto contido na nota inicio = arquivo.find(" ") inicio +=2 final = arquivo.find(" =") # Encontrando o número das páginas inicio_pagina = arquivo.find("posição ") inicio_pagina = inicio_pagina + 7 fim_pagina = arquivo.find(" |") pagina = arquivo[inicio_pagina+1:fim_pagina] meio_pagina = pagina.find("-") paginas.append(pagina) # Consultando se o arquivo terminou if "=" not in arquivo[inicio:final]: conteudo.append(arquivo[inicio:final]) arquivo = arquivo[final+2:] if " =" not in arquivo: if checador_final == 0: checador_final = 1 else: break return conteudo, paginas # Função Principal de execução if __name__ == "__main__": # input das notas arquivo_bruto = input('Coloque aqui as notas a serem formatadas: ') # Cadastramento de dados que, ou não vem nas notas, ou não são confiáveis (como no caso de pdfs salvos com nomes diferentes do título da obra) while True: nota_formatada = {} nota_formatada['titulo'] = input('Qual é o nome do livro a ser referenciado? ') nota_formatada['autor'] = input('Informe o "SOBRENOME, Autor": ') nota_formatada['editora'] = input('Qual é a editora do livro? ') nota_formatada['edicao'] = input('Qual é a edição do livro? ') nota_formatada['ano'] = input('Qual é o ano do livro? ') # Chamamento e retorno da função arquivo_tratado, paginas_tratadas = tratamento_arquivo(arquivo_bruto) # Listas de conteúdos e páginas adicionados aos seus respectivos campos no dicionário nota_formatada['conteudo'] = arquivo_tratado nota_formatada['pagina'] = paginas_tratadas # Output como as notas formatadas. Obs.: As páginas serão as do e-book, não as do livro físico. try: for i in range(len(nota["conteudo"])): print("\n") print(f' {nota_formatada["conteudo"][i]} ({nota_formatada["autor"]}. {nota_formatada["ano"]}. P. {nota_formatada["pagina"][i]})') except: pass # Output com as referências prontas print(f'Referências:') print(f'{nota_formatada["autor"]}. {nota_formatada["titulo"]}. {nota_formatada["edicao"]} Ed. {nota_formatada["editora"]}, {nota_formatada["ano"]}.') # Consultar sobre nova formatação de notas repetir = input("Deseja formatar outro arquivo? [S/N] ") while repetir not in "SsNn": repetir = input("Resposta inválida. tente novamente. Você deseja formatar outro arquivo? [S/N] ") if repetir in "Ss": continue elif repetir in "Nn": print("Estou feliz por poder ajudar. Até a próxima!") break
# 请用“*”打印出五行五列的等腰直角三角形 N = 5 for i in range(N): for j in range(i + 1): print("*", end="") print()
def user_class(row_series): """ Defines the user class for this trip list. This function takes a single argument, the pandas.Series with person, household and trip_list attributes, and returns a user class string. """ # print row_series if row_series["hh_id"] == "simpson": return "not_real" return "real"
# 1. Even Numbers # Write a program that receives a sequence of numbers (integers), separated by a single space. # It should print a list of only the even numbers. Use filter(). def filter_even(iters): return list(filter(lambda x: x % 2 == 0, iters)) nums = map(int, input().split()) print(filter_even(nums))
class Foo: def __init__(self, id): self.id = id def __str__(self): return 'Foo instance id: {}'.format(self.id) class Bar: def __init__(self, id): self.id = id def __str__(self): return 'Bar instance id: {}'.format(self.id) class Baz: def __init__(self, id): self.id = id def __str__(self): return 'Baz instance id: {}'.format(self.id) foo_1 = Foo("to go") foo_2 = Foo("to clean") foo_3 = Foo("to avoid") foo_4 = Foo("to destroy") bar_1 = Bar("the bathroom") bar_2 = Bar("the kitchen") bar_3 = Bar("the bedroom") bar_4 = Bar("the basement") bar_5 = Bar("the garage") my_dictionary = {Foo: [foo_1, foo_2, foo_3, foo_4], Bar: [bar_1, bar_2, bar_3, bar_4, bar_5]} if Baz in my_dictionary: textBatch = my_dictionary[Baz] else: textBatch = [] my_dictionary[Baz] = textBatch textBatch.append(5) # Pass by reference # test = my_dictionary.get(Foo) # print(test) # retest = my_dictionary[Foo] # print(retest) for model_type in my_dictionary: for entity in my_dictionary[model_type]: print(entity) for unit in my_dictionary: print(unit) if Baz in my_dictionary: del my_dictionary[Baz] for model_type in my_dictionary: for entity in my_dictionary[model_type]: print(entity) # # if Foo in my_dictionary: # # for entity in my_dictionary[Foo]: # # print(entity) # my_dictionary[Foo].append(Foo("to dirty")) # for entity in my_dictionary[Foo]: # print(entity) # # # # if Baz in my_dictionary: # # print("Should not see this") # # for entity in my_dictionary[Baz]: # # print(entity) # # else: # # my_dictionary[Baz] = [Baz("big test")] # # # # # # print("\nNow testing for Baz") # # if Baz in my_dictionary: # # for entity in my_dictionary[Baz]: # # print(entity) for unit in my_dictionary: print(unit)
def cli_progress_bar(completed: int, total_iterations: int, length=40, fill_char='█', padding_char='░', prefix='', suffix='', precision=1, complete_as_percent=True): """ Call in a loop to create terminal progress bar. The loop can't print any other output to stdout. :param completed: number of completed iterations :param total_iterations: total number of iterations in calling loop :param length: length of bar in characters :param fill_char: filled bar character :param padding_char: unfilled bar character :param prefix: prefix string, printed before progress bar :param suffix: suffix string, printed after progress bar :param precision: number of decimals in percent complete :param complete_as_percent: if True, print percent complete, if False print "num_complete of total_num" """ if len(fill_char) != 1: raise ValueError("Invalid fill character") if len(padding_char) != 1: raise ValueError("Invalid padding character") if precision < 1: raise ValueError("Invalid precision parameter") if length < 1: raise ValueError("Invalid length parameter") if total_iterations > 0: # create a string representation of the percent complete complete = f"{100 * (completed / float(total_iterations)):.{precision}f}" # calculate the length of the filled portion of the progress bar filled_length = int(length * completed // total_iterations) else: complete = 0 filled_length = 0 # create a string combining filled and unfilled portions bar = fill_char * filled_length + padding_char * (length - filled_length) if complete_as_percent: complete = f"{complete}%" else: width = len(str(total_iterations)) complete = f"{completed:{width}} of {total_iterations}" # print progress bar, overwriting the current line print(f'\r{prefix}{bar} {complete} {suffix}', end='\r') # print newline once the progress bar is filled if completed == total_iterations: print()
#=========================================================================== # # Convert decoded data to MQTT messages. # #=========================================================================== #=========================================================================== def convert( config, data ): # List of tuples of ( topic, payload ) where payload is a dictionary. msgs = [] if hasattr( data, "battery" ): topic = config.mqttBattery % data.location payload = { "time" : data.time, "battery" : data.battery, } msgs.append( ( topic, payload ) ) if hasattr( data, "signal" ): topic = config.mqttRssi % data.location payload = { "time" : data.time, # Input is 0->1, convert to 0->100 "rssi" : data.signal * 100, } msgs.append( ( topic, payload ) ) if hasattr( data, "humidity" ): topic = config.mqttHumidity % data.location payload = { "time" : data.time, "humidity" : data.humidity, } msgs.append( ( topic, payload ) ) if hasattr( data, "temperature" ): topic = config.mqttTemp % data.location payload = { "time" : data.time, "temperature" : data.temperature, } msgs.append( ( topic, payload ) ) if hasattr( data, "windSpeed" ): topic = config.mqttWindSpeed % data.location payload = { "time" : data.time, "speed" : data.windSpeed, } msgs.append( ( topic, payload ) ) if hasattr( data, "windDir" ): topic = config.mqttWindDir % data.location payload = { "time" : data.time, "direction" : data.windDir, } msgs.append( ( topic, payload ) ) if hasattr( data, "pressure" ): topic = config.mqttBarometer % data.location payload = { "time" : data.time, "pressure" : data.pressure, } msgs.append( ( topic, payload ) ) if hasattr( data, "rainfall" ): topic = config.mqttRain % data.location payload = { "time" : data.time, "rain" : data.rainfall, } msgs.append( ( topic, payload ) ) return msgs #===========================================================================
# -*- coding: UTF-8 -*- # # Binary search works for a sorted array. # The All ▲lgorithms library for python # # Contributed by: Carlos Abraham Hernandez # Github: @abranhe # def binary_search(arr, query): lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (hi + lo) // 2 val = arr[mid] if val == query: return mid elif val < query: lo = mid + 1 else: hi = mid - 1 return None
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ 合并两个列表为一个无重复元素的列表 """ def merge_list(*args): s = set() for arg in args: s = s.union(arg) return list(s) l1 = [12, 2, 4, 2, 56, 2] l2 = [2, 4, 5, 77, 8] print(merge_list(l1, l2))
def special_sort(alphabet, s): a = {c: i for i, c in enumerate(alphabet)} return ''.join(sorted(list(s), key=lambda x: a[x.lower()])) a = 'wvutsrqponmlkjihgfedcbaxyz' t = 'camelCasE' print(special_sort(a, t))
# Transformando módulos em pacotes '''Crie um PACOTE chamado uteis que tenha dois módulos internos chamados moeda e dado. Transfira todas as funções utilizadas nos ex107, ex108 e ex109 para o primeiro pacote e mantenha tudo funcionando''' print() print('\033[1:35m''Nesse exercício não há código para escrever') print()
# Next Greater Element I: https://leetcode.com/problems/next-greater-element-i/ # The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. # You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. # For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. # Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. # The simple solution is to for each i in nums1 search for it in 2 and then find the first largest number after that this will run in o(N^2) and o(N) space as we have to append it to a result # This is quite a tricky mouthful of a solution basically we need to create a dictionary of the next highest value of every number # however to do this we will need to implement a stack. Luckily we can bulid this dict in o(N) time and using o(N) space so it ever so slightly optimized # as we will not be evaluating the same two numbers twice class Solution: def nextGreaterElement(self, nums1, nums2): nextGreater = {} stack = [] for num in nums2: while len(stack) > 0 and num > stack[-1]: nextGreater[stack.pop()] = num stack.append(num) # while len(stack) > 0: # nextGreater[stack.pop()] = -1 result = [] for num in nums1: result.append(nextGreater.get(num, -1)) return result # This is a super simple stack scanning solution because we can always see the number we are at and then you can check if the last n numbers were less than its value # this solution will run in o(M+N) time and space as we will have to iterate through both nums array and store the result in a dict or in result # Score Card # Did I need hints? N # Did you finish within 30 min? 10 # Was the solution optimal? Oh yea # Were there any bugs? None submitted with 0 issue first try # 5 5 5 5 = 5
pt = int(input('Primeiro termo: ')) rz = int(input('Razão: ')) for c in range (pt, (pt + (10-1) * rz)+rz, rz): print(f'{c}', end=" → ") print('ACABOU')
''' Cree un programa en Python que le pida al usuario por pantalla un número (int) ("n"). Luego cree un ciclo que se ejecuta tantas veces como el número "n" recibido anteriormente. Luego dentro del ciclo pida al usuario otro número por pantalla. Si el número recibido es par, sumelo en un acumulador, si no, no lo sume. Al final, muestra la suma total de los pares. ''' n = int(input("Digite el n: ")) acumualador = 0 for i in range(0, n, 1): numero = int(input("Digite un numero: ")) if numero%2==0: acumualador += numero print(acumualador)
''' @Date: 2019-12-22 20:38:38 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors : ywyz @LastEditTime : 2019-12-22 20:52:02 ''' strings = input("Enter the first 12 digits of an ISBN-13 as a string: ") temp = 1 total = 0 for i in strings: if temp % 2 == 0: total += 3 * int(i) else: total += int(i) temp += 1 total = 10 - total % 10 if total == 10: total = 0 strings = strings + str(total) print("The ISBN-13 number is ", strings)
matriz = [[1, 2], [3, 4], [5, 6], [7]] i = 0 x = 0 while i < len(matriz): try: print(matriz[i][x]) x = x + 1 except IndexError: print("O valor mais alto da lista {i} é: {max}".format(i=i, max=max(matriz[i]))) i = i + 1 x = 0
# Generator used for all the Skinned Lanterns lantern variants! lanterns = ["pufferfish", "zombie", "creeper", "skeleton", "wither_skeleton", "bee", "jack_o_lantern", "ghost", "inky", "pinky", "blinky", "clyde", "pacman", "paper_white", "paper_yellow", "paper_orange", "paper_blue", "paper_light_blue", "paper_cyan", "paper_lime", "paper_green", "paper_red", "paper_pink", "paper_brown", "paper_black", "paper_gray", "paper_light_gray", "paper_magenta", "paper_purple", "guardian"] shader_path = "assets/skinnedlanterns/materialmaps/" handheld_path = "assets/skinnedlanterns/lights/item/" material = """ {{ "defaultMaterial": "canvas:{type}_glow", "variants": {{ "facing=north,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=north,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=north,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=north,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=east,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=east,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=east,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=east,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=south,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=south,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=south,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=south,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=west,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=west,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=west,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=west,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=up,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=up,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=up,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=up,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=down,hanging=false,waterlogged=true": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=down,hanging=false,waterlogged=false": {{ "defaultMaterial": "canvas:{type}_glow" }}, "facing=down,hanging=true,waterlogged=true": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }}, "facing=down,hanging=true,waterlogged=false": {{ "defaultMaterial": "swingchain:swinging_{type}_glow" }} }} }} """ normal_light = """ { "intensity": 0.93, "red": 1.0, "green": 1.0, "blue": 0.8, "worksInFluid": false } """ soul_light = """ { "intensity": 0.93, "red": 0.6, "green": 0.8, "blue": 1.0, "worksInFluid": true } """ for lantern in lanterns: normal = open(shader_path + "block/" + lantern + "_lantern_block.json", "w") soul = open(shader_path + "block/" + lantern + "_soul_lantern_block.json", "w") normal_item = open(shader_path + "item/" + lantern + "_lantern_block.json", "w") soul_item = open(shader_path + "item/" + lantern + "_soul_lantern_block.json", "w") normal_handheld = open(handheld_path + lantern + "_lantern_block.json", "w") soul_handheld = open(handheld_path + lantern + "_soul_lantern_block.json", "w") normal.write(material.format(type = "warm")) soul.write(material.format(type = "luminance")) normal_item.write("{}") soul_item.write("{}") normal_handheld.write(normal_light) soul_handheld.write(soul_light) normal.close() soul.close() normal_item.close() soul_item.close() normal_handheld.close() soul_handheld.close() print("Filegen complete!")
def count_up_to(max): count = 1 while count <= max: yield count count += 1 counter = count_up_to(5) for num in counter: print(num)
__strict__ = True class SpotifyOauthError(Exception): pass class SpotifyRepositoryError(Exception): def __init__(self, http_status: int, body: str): self.http_status = http_status self.body = body def __str__(self): return 'http status: {0}, code:{1}'.format(str(self.http_status), self.body)
# program numbers BASIC = 140624 GOTO = 158250875866513204219300194287615 VARIABLES = 6198727823
ENV_NAMES = { "PASSWORD": "DECT_MAIL_EXTRACT_PASSWORD", "USERNAME": "DECT_MAIL_EXTRACT_USER", "SERVER": "DECT_MAIL_EXTRACT_SERVER", }
@customop('numpy') def my_softmax(x, y): probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True)) probs /= numpy.sum(probs, axis=1, keepdims=True) N = x.shape[0] loss = -numpy.sum(numpy.log(probs[numpy.arange(N), y])) / N return loss def my_softmax_grad(ans, x, y): def grad(g): N = x.shape[0] probs = numpy.exp(x - numpy.max(x, axis=1, keepdims=True)) probs /= numpy.sum(probs, axis=1, keepdims=True) probs[numpy.arange(N), y] -= 1 probs /= N return probs return grad my_softmax.def_grad(my_softmax_grad)
__all__ = ( "ELLIPSIS", "truncate", ) ELLIPSIS = "…" """The ellipsis character used for :func:`utils.string.truncate`.""" def truncate(string, length): """ Truncate a string to a given length. Functions as follows: * If length is 0 or less, returns an empty string. * If length is less than the length of the input string, returns the string truncated to length-1 and appends :data:`~utils.string.ELLIPSIS`. * Otherwise, returns the input string. Examples -------- .. code-block:: python3 description = "This is a very long and detailed description." shortened = utils.string.truncate(description, 20) # shortened = "This ia very long…" Parameters ---------- string: str The string to truncate. length: int The maximum length of the string. Any characters past this limit will be removed and the last character is replaced with ``…``. Returns ------- str The truncated string. """ if length <= 0: return "" elif len(string) > length: return string[:length-1] + "…" else: return string def human_join(items, bold=False, code=False, concatenator="and"): r""" Join a list of objects and return human readable representation. Examples -------- .. code-block:: python3 >>> from utils.string import human_join >>> human_join([]) "" >>> human_join([1]) "1" >>> human_join([1, 2]) "1 and 2" >>> human_join([1, 2, 3]) "1, 2 and 3" >>> human_join([1, 2, 3], concatenator="or") "1, 2 or 3" >>> human_join([1, 2], bold=True) "**1** and **2**" >>> human_join([1, 2], code=True) "`1` and `2`" Parameters ---------- items: List[Union[Any]]] A list of strings or other objects to be joined. bold: Optional[bool] Whether to surround items with ``**``. Defaults to ``False``. code: Optional[bool] Whether to surround items with ``\`\```. Defaults to ``False``. concatenator: Optional[str] The concatenator to use for the second last and last item. Returns ------- str The joined list of items. """ fmt = "{}" if code: fmt = f"`{fmt}`" if bold: fmt = f"**{fmt}**" items = [fmt.format(item) for item in items] if len(items) == 0: return "" elif len(items) == 1: return str(items[0]) return "{} {} {}".format( ", ".join(items[:-1]), concatenator, items[-1] )
""" This file was made for exercise 9-11""" class Users: def __init__(self, first_name, last_name, email, username): self.first_name = first_name self.last_name = last_name self.email = email self.username = username self.login_attempts = 0 def describe_user(self): print(f'{self.first_name.title()} {self.last_name.title()}') print(f'- Email: {self.email}') print(f'- Username: {self.username}') def greet_user(self): print(f'Welcome {self.first_name.title()}') def increment_login_attempts(self): self.login_attempts += 1 print(self.login_attempts) def reset_login_attempts(self): self.login_attempts = 0 print(self.login_attempts) class Admin(Users): def __init__(self, first_name, last_name, email, username): super().__init__(first_name, last_name, email, username) self.privileges = Privileges() class Privileges: def __init__(self, privileges=[]): self.privileges = privileges def show_privileges(self): print('ADMIN PRIVILEGES:') if self.privileges: for privilege in self.privileges: print(f'- {privilege.title()}') else: print('No privileges') if __name__ == '__main__': admin1 = Admin('james', 'noria', 'jamesnoria@gmail.com', 'jamesnoria') admin1.describe_user() admin1.privileges.privileges = ['can post', 'can delete'] admin1.privileges.show_privileges()
''' https://leetcode.com/problems/reverse-integer/ 7. Reverse Integer Easy Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ''' class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x<0: return -self.reverse(-x) result=0 while x: result=result*10+x%10 x=x//10 return result if result <= 2**31-1 else 0 print(Solution().reverse(-123)) print(Solution().reverse(28)) print(Solution().reverse(250))
class MdFile(): def __init__(self, file_path, base_name, title, mdlinks): self.uid = 0 self.file_path = file_path self.base_name = base_name self.title = title if title else base_name self.mdlinks = mdlinks def __str__(self): return f'{self.uid}: {self.file_path}, {self.title}, {self.mdlinks}'
#/* *** ODSATag: MinVertex *** */ # Find the unvisited vertex with the smalled distance def minVertex(G, D): v = 0 # Initialize v to any unvisited vertex for i in range(G.nodeCount()): if G.getValue(i) != VISITED: v = i break for i in range(G.nodeCount()): # Now find smallest value if G.getValue(i) != VISITED and D[i] < D[v]: v = i return v #/* *** ODSAendTag: MinVertex *** */ #/* *** ODSATag: GraphDijk1 *** */ # Compute shortest path distances from s, store them in D def Dijkstra(G, s, D): for i in range(G.nodeCount()): # Initialize D[i] = INFINITY D[s] = 0 for i in range(G.nodeCount()): # Process the vertices v = minVertex(G, D) # Find next-closest vertex G.setValue(v, VISITED) if D[v] == INFINITY: return # Unreachable for w in G.neighbors(v): if D[w] > D[v] + G.weight(v, w): D[w] = D[v] + G.weight(v, w) #/* *** ODSAendTag: GraphDijk1 *** */
config = { # -------------------------------------------------------------------------- # Database Connections # -------------------------------------------------------------------------- 'database': { 'default': 'auth', 'connections': { # SQLite # 'auth': { # 'driver': 'sqlite', # 'dialect': None, # 'host': None, # 'port': None, # 'database': ':memory', # 'username': None, # 'password': None, # 'prefix': 'auth_', # }, # MySQL 'auth': { 'driver': 'mysql', 'dialect': 'pymysql', 'host': '127.0.0.1', 'port': 3306, 'database': 'uvicore_test', 'username': 'root', 'password': 'techie', 'prefix': 'auth_', }, }, }, }
data = open('output_dataset_ALL.txt').readlines() original = open('dataset_ALL.txt').readlines() #data = open('dataset.txt').readlines() out = open('output_gcode_merged.gcode', 'w') for j in range(len(data)/4): i = j*4 x = data[i].strip() y = data[i+1].strip() z = original[i+2].strip() e = original[i+3].strip() out.write('G1 X' + x[:-2] + ' Y' + y[:-2] + ' Z' + z[:-2] + ' E' + e + '\n') out.close()
def adder_model(a, b): """ My golden reference model """ return my_adder(a, b) def my_adder(a, b): """ My golden reference model """ return a + b
## # Copyright 2018, Ammar Ali Khan # Licensed under MIT. ## # Application configuration APPLICATION_NAME = '' APPLICATION_VERSION = '1.0.1' # HTTP Port for web streaming HTTP_PORT = 8000 # HTTP page template path HTML_TEMPLATE_PATH = './src/common/package/http/template' # Capturing device index (used for web camera) CAPTURING_DEVICE = 0 # To user Pi Camera USE_PI_CAMERA = True # Capture configuration WIDTH = 640 HEIGHT = 480 RESOLUTION = [WIDTH, HEIGHT] FRAME_RATE = 24 # Storage configuration DATABASE_NAME = 'database.db' STORAGE_DIRECTORY = './dataset/' UNKNOWN_PREFIX = 'unknown' FILE_EXTENSION = '.pgm'
Total_Fuel_Need =0 Data_File = open("Day1_Data.txt") Data_Lines = Data_File.readlines() for i in range(len(Data_Lines)): Data_Lines[i] = int(Data_Lines[i].rstrip('\n')) Total_Fuel_Need += int(Data_Lines[i] / 3) - 2 print(Total_Fuel_Need)
# This sample tests the special-case handling of Self when comparing # two functions whose signatures differ only in the Self scope. class SomeClass: def __str__(self) -> str: ... __repr__ = __str__
lines = open("input").read().strip().splitlines() print("--- Day11 ---") class Seat: directions = [ (dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if (dx, dy) != (0, 0) ] def __init__(self, x, y, dx, dy): self.x = x self.y = y self.dx = dx self.dy = dy def p1(part2=False): G, rows, columns = load_grid(lines) i = 0 while True: i += 1 NG = {} for x in range(rows): for y in range(columns): other = [Seat(x + d[0], y + d[1], *d) for d in Seat.directions] adjacent = 4 if part2: for seat in other: while G.get((seat.x, seat.y)) == ".": seat.x += seat.dx seat.y += seat.dy adjacent = 5 other = [G[s.x, s.y] for s in other if (s.x, s.y) in G] if G[x, y] == "L" and all(s != "#" for s in other): NG[x, y] = "#" elif G[x, y] == "#" and (sum([s == "#" for s in other]) >= adjacent): NG[x, y] = "L" else: NG[x, y] = G[x, y] if G == NG: break G = NG print(sum([cell == "#" for cell in G.values()])) def p2(): p1(part2=True) def load_grid(lines): G = {} first_row = lines[0] for y, line in enumerate(lines): # Check if grid is really a grid. assert len(line) == len(first_row) for x, ch in enumerate(line): G[y, x] = ch rows = len(lines) columns = len(first_row) return G, rows, columns def print_grid(grid, maxx, maxy, zfill_padding=3): header = [" " * zfill_padding, " "] for x in range(maxx): header.append(str(x % 10)) print("".join(header)) for y in range(maxy): row = [str(y).zfill(zfill_padding), " "] for x in range(maxx): row.append(grid[x, y]) print("".join(row)) print("Part1") p1() print("Part2") p2() print("---- EOD ----")
#list = [1,2,3,4,5] arr = list(range(1,6)) count = 0 #print(arr) #for i in arr: #print(i) list = ["a","b","c","d","e"] for index in range(len(arr)): print(f'Phan tu tai vi tri {index} cua arr la : {list[index]}') count += 1 print(count)
""" Auteur = Frédéric Castel Date : Avril 2020 Projet : MOOC Python 3 - France Université Numérique Objectif: Considérons les billets et pièces de valeurs suivantes : 20 euros, 10 euros, 5 euros, 2 euros et 1 euro. Écrire une fonction rendre_monnaie qui reçoit en paramètre un entier prix et cinq valeurs entières x20, x10, x5, x2 et x1, qui représentent le nombre de billets ou de pièces de chaque valeur que donne un client pour l’achat d’un objet dont le prix est mentionné. La fonction doit renvoyer cinq valeurs, représentant le nombre de billets et pièces de chaque sorte qu’il faut rendre au client, dans le même ordre que précédemment. Cette décomposition doit être faite en rendant le plus possible de billets et pièces de grosses valeurs. Si la somme d’argent avancée par le client n’est pas suffisante pour effectuer l’achat, la fonction retournera cinq valeurs None. Consignes: Dans cet exercice, il vous est demandé d’écrire seulement la fonction rendre_monnaie. Le code que vous soumettez à UpyLaB doit donc comporter uniquement la définition de cette fonction, et ne fait en particulier aucun appel à input ou à print. Plus précisément UpyLaB testera d'abord l'existence d'une définition de votre fonction avec le bon nombre de paramètres. Si la fonction existe bien, UpyLaB testera votre fonction : il ajoutera des appels à votre fonction pour vérifier que celle-ci n'effectue aucun print. Ensuite différents tests de votre fonction seront effectués par UpyLaB. Il n’est pas demandé que la fonction rendre_monnaie teste le type des paramètres reçus. On suppose qu’il y a toujours suffisamment de billets et pièces de chaque sorte. Pour retourner cinq valeurs, on pourra utiliser l’instruction return res20, res10, res5, res2, res1. Cela renvoie un tuple de cinq valeurs (apparaissant entre parenthèses lorsqu’on l’affiche). """ def rendre_monnaie(prix, x20, x10, x5, x2, x1): liste_valeur_billet = (20, 10, 5, 2, 1) n = len(liste_valeur_billet) somme = x20 * 20 + x10 * 10 + x5 * 5 + x2 * 2 + x1 * 1 reste = somme - prix if somme <= prix: res20 = None res10 = None res5 = None res2 = None res1 = None else: res20 = reste // 20 reste -= res20 * 20 res10 = reste // 10 reste -= res10 * 10 res5 = reste // 5 reste -= res5 * 5 res2 = reste // 2 reste -= res2 * 2 res1 = reste // 1 return res20, res10, res5, res2, res1 print(rendre_monnaie(52, 2, 2, 2, 3, 3)) rendre_monnaie(80, 2, 2, 2, 3, 3) #doit retourner : (None, None, None, None, None)
def baseline3(X): return ( X['ABS'] | X['INT'] | X['UINT'] | (X['TDEP'] > X['TDEP'].mean()) | (X['FIELD'] > X['FIELD'].mean()) | ((X['UAPI']+X['TUAPI']) > (X['UAPI']+X['TUAPI']).mean()) | (X['EXPCAT'] > 0) | (X['RBFA'] > 0) | (X['CONDCALL'] > 0) | (X['SYNC'] > X['SYNC'].mean()) | (X['AFPR'] > 0) )
def search_in_rotated_array(alist, k, leftix=0, rightix=None): if not rightix: rightix = len(alist) midpoint = (leftix + rightix) / 2 aleft, amiddle = alist[leftix], alist[midpoint] if k == amiddle: return midpoint if k == aleft: return leftix if aleft > amiddle: if amiddle < k and k < aleft: return search_in_rotated_array(alist, k, midpoint+1, rightix) else: return search_in_rotated_array(alist, k, leftix+1, midpoint) elif aleft < k and k < amiddle: return search_in_rotated_array(alist, k, leftix+1, midpoint) else: return search_in_rotated_array(alist, k, midpoint+1, rightix) array = [55, 60, 65, 70, 75, 80, 85, 90, 95, 15, 20, 25, 30, 35, 40, 45] print(search_in_rotated_array(array, 40))
# coding:utf-8 # File Name: decorator_test # Author : yifengyou # Date : 2021/07/18 def funA(fn): print("A") fn() return "hello" @funA def funB(): print("B") print(funB)
""" Program functionalities module """ def create_transaction(day, value, type, description): """ :return: a dictionary that contains the data of a transaction """ return {'day': day, 'value': value, 'type': type, 'description': description} def get_day(transaction): """ :return: the day of the transaction """ return transaction['day'] def get_value(transaction): """ :return: the amount of money of the transaction """ return transaction['value'] def get_type(transaction): """ :return: the type of the transaction """ return transaction['type'] def get_description(transaction): """ :return: the description of the transaction """ return transaction['description'] def set_value(transaction, value): """ modify the amount of money of a existing transaction """ transaction['value'] = value def add_transaction(transactions_list, transaction): transactions_list.append(transaction) def remove_transaction(transactions_list, index): transactions_list.pop(index) def remove_transactions_from_a_day(transactions_list, day): """ removes all the transactions from a speciefied day """ lenght = len(transactions_list) i = 0 while i < lenght: if get_day(transactions_list[i]) == day: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def remove_transactions_from_day1_to_day2(transactions_list, day1, day2): """ removes all the transactions from day1 to day2 """ lenght = len(transactions_list) i = 0 while i < lenght: if day1 <= get_day(transactions_list[i]) <= day2: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def remove_transactions_type(transactions_list, type): """ removes all the transactions of a certain type """ lenght = len(transactions_list) i = 0 while i < lenght: if get_type(transactions_list[i]) == type: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def replace_value_of_transaction(transactions_list, day, type, description, new_value): """ replace the value of a transaction with a new one """ for i in range(0, len(transactions_list)): transaction = transactions_list[i] if get_day(transaction) == day and get_type(transaction) == type and get_description(transaction) == description: set_value(transactions_list[i], new_value) break def transaction_having_type(transactions_list, type): """ returns the list of all the transcations of a certain type """ print_list = [] for i in range(0, len(transactions_list)): if get_type(transactions_list[i]) == type: add_transaction(print_list, transactions_list[i]) return print_list def transactions_having_property_than_value(transactions_list, property, value): """ :param property: = / > / < :returns: all the transactions which respect the property with the respect of the value """ print_list = [] for i in range(0, len(transactions_list)): if property == '=': if get_value(transactions_list[i]) == value: add_transaction(print_list, transactions_list[i]) elif property == '>': if get_value(transactions_list[i]) > value: add_transaction(print_list, transactions_list[i]) elif property == '<': if get_value(transactions_list[i]) < value: add_transaction(print_list, transactions_list[i]) return print_list def transactions_sum_having_type_before_day(transactions_list, type, day): """ transactions_list = the list of transactions type = the type of the transactions 'in'/'out' :return: sum of all type transactions """ s = 0 for i in range(0, len(transactions_list)): if get_day(transactions_list[i]) <= day and get_type(transactions_list[i]) == type: s = s + get_value(transactions_list[i]) return s def account_balance_before_day(transactions_list, day): """ :param transactions_list: the list of transactions :param day: the last day before the balance check :return: account balance before a certain day(including that day) """ sum1 = transactions_sum_having_type_before_day(transactions_list, "in".casefold(), day) sum2 = transactions_sum_having_type_before_day(transactions_list, "out".casefold(), day) account_balance = sum1 - sum2 return account_balance def sum_having_type(transactions_list, type): """ :param transactions_list: a list of transactions :param type: "in"/"out" :return: the sum of all transactions which have type 'type' """ s = 0 for transaction in transactions_list: if get_type(transaction) == type: s = s + get_value(transaction) return s def max_transanction_having_type_from_day(transactions_list, type, day): """ :param transactions_list: a list of transactions :param type: "in"/"out" :param value: the day of the transactions :return: a list of maximum transactions of type 'type' and day 'day' """ maximum = -1 max_list = [] for transaction in transactions_list: if get_type(transaction) == type and get_day(transaction) == day: if get_value(transaction) > maximum: maximum = get_value(transaction) for transaction in transactions_list: if get_type(transaction) == type and get_day(transaction) == day: if get_value(transaction) == maximum: add_transaction(max_list, transaction) return max_list def filter_type(transactions_list, type): """ :param transactions_list: a list of transactions :param type: the type of transactions we want to filter keeps only type trasactions """ if type == "in": remove_transactions_type(transactions_list, "out") else: remove_transactions_type(transactions_list, "in") def filter_type_smaller_than_value(transactions_list, type, value): """ :param transactions_list: a list of transactions :param type: the type of transactions we want to filter :param value: the upper bound of the value of a transaction of type 'type' keeps all 'type' transactions smaller than value(not inclunding it) """ lenght = len(transactions_list) i = 0 while i < lenght: if get_type(transactions_list[i]) != type or get_value(transactions_list[i]) >= value: remove_transaction(transactions_list, i) lenght = lenght - 1 else: i = i + 1 def copy_transactions_list(transactions_list): """ :param transactions_list: a list :return: a copy of that list """ new_list = [] for transaction in transactions_list: day = get_day(transaction) type = get_type(transaction) value = get_value(transaction) description = get_description(transaction) new_transaction = create_transaction(day, value, type, description) new_list.append(new_transaction) return new_list
''' https://www.codingame.com/training/easy/brackets-extreme-edition ''' e = input() d = {')': '(', ']': '[', '}': '{'} s = [] for c in e: if c in d.values(): s.append(c) elif c in d.keys(): if len(s) == 0: print("false") exit(0) else: if d[c] == s.pop(): pass else: print("false") exit(0) if len(s) == 0: print("true") else: print("false")
#!/usr/bin/env python # from .api import SteamAPI class SteamUser(object): def __init__(self, steam_id=None, steam_api=None, **kwargs): self.steam_id = steam_id self.steam_api = steam_api self.__dict__.update(**kwargs) self._friends = None self._games = None self._profile_data = None self._profile_data_items = [ u'steamid', u'primaryclanid', u'realname', u'personaname', u'personastate', u'personastateflags', u'communityvisibilitystate', u'loccountrycode', u'profilestate', u'profileurl', u'timecreated', u'avatar', u'commentpermission', u'avatarfull', u'avatarmedium', u'lastlogoff' ] @property def friends(self, steam_id=None): if self._friends: return self._friends self._friends = self.get_friends_list(steam_id=steam_id) return self._friends def Game(self, app_id): return Game(app_id=app_id, steam_api=self.steam_api, owner=self) @property def games(self): if self._games: return self._games self._games = self.get_games_list() return self._games @property def games_set(self): return set([_.app_id for _ in self.games]) def _profile_property_wrapper(self, profile_data, key): if self._profile_data: return self._profile_data.get(key) self._profile_data = profile_data return self._profile_data.get(key) def __getattr__(self, key): if key in self._profile_data_items: self._profile_data = self.get_profile() return self._profile_data.get(key) return super(SteamUser, self).__getattribute__(key)() def get_profile(self, steam_id=None): if self._profile_data: return self._profile_data if steam_id: self.steam_id = steam_id response_json = self.steam_api.get( 'ISteamUser', 'GetPlayerSummaries', version='v0002', steamids=self.steam_id ) # Make this better return response_json.get('response', {}).get('players', [])[0] def get_friends_list(self, steam_id=None): if steam_id: self.steam_id = steam_id response_json = self.steam_api.get('ISteamUser', 'GetFriendList', steamid=self.steam_id) for friend in response_json.get('friendslist', {}).get('friends', []): yield SteamUser( steam_id=friend.get('steamid'), steam_api=self.steam_api, friend_since=friend.get('friend_since') ) def get_games_list(self, steam_id=None): if steam_id: self.steam_id = steam_id game_list = self.steam_api.get( 'IPlayerService', 'GetOwnedGames', steamid=self.steam_id ) for game in game_list.get('response', {}).get('games', []): yield Game(app_id=game.get('appid'), owner=self) def __repr__(self): return "<SteamUser:{.steam_id}>".format(self)
def parse_map(_map): """ Returns a dictionary where from you can look up which center a given orbiter has """ orbits = {} for orbit in _map.split("\n"): center, orbiter = orbit.split(")") orbits[orbiter] = center return orbits def count_orbits(_map): orbits = parse_map(_map) orbiters = orbits.keys() i = 0 for obj in orbiters: while obj != "COM": obj = orbits[obj] i += 1 return i test_map = """ COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L """.strip("\n \t") assert count_orbits(test_map) == 42 with open("input06.txt", "r") as f: _map = f.read() print(count_orbits(_map))
class Solution: def solve(self, matrix): if matrix[0][0] == 1: return -1 R,C = len(matrix),len(matrix[0]) bfs = deque([[0,0]]) dists = {(0,0): 1} while bfs: r,c = bfs.popleft() if (r,c) == (R-1,C-1): return dists[r,c] for nr,nc in [[r-1,c],[r+1,c],[r,c-1],[r,c+1]]: if 0<=nr<R and 0<=nc<C and (nr,nc) not in dists and matrix[nr][nc] == 0: dists[nr,nc] = dists[r,c] + 1 bfs.append((nr,nc)) return -1
class Solution: def rob(self, nums: list[int]) -> int: if len(nums) == 0: return 0 max_loot: list[int] = [0 for _ in nums] for index, num in enumerate(nums): if index == 0: max_loot[index] = num elif index == 1: max_loot[index] = max(max_loot[index-1], num) else: max_loot[index] = max( max_loot[index-1], num + max_loot[index-2] ) return max_loot[-1] tests = [ ( ([1, 2, 3, 1],), 4, ), ( ([2, 7, 9, 3, 1],), 12, ), ]
async def processEvent(event): # Do event processing here ... return event
#!/usr/bin/env python # coding=utf-8 """ # pyORM : Implementation of managers.py Summary : <summary of module/class being implemented> Use Case : As a <actor> I want <outcome> So that <justification> Testable Statements : Can I <Boolean statement> .... """ __version__ = "0.1" __author__ = 'Tony Flury : anthony.flury@btinternet.com' __created__ = '26 Aug 2017' class Manager: def __init__(self, name='', model=None): self._name = name self._model = model @property def model(self): return self._model @property def name(self): return self._name @name.setter def name(self, new_name): if self.name: raise AttributeError('Cannot change name attribute once set') self._name = new_name # Todo Add all relevant methods to the Manager - including filters etc #Todo write ForiegnKey, One to One and Many to Many Managers
print("\nAverage is being calculated\n") APITimingFile = open("APITiming.txt", "r") APITimingVals = APITimingFile.readlines() sum = 0 for i in APITimingVals: sum += float(i[slice(len(i)-2)]) print("\nThe average time of start providing is " + str(round(sum/len(APITimingVals), 4)) + "\n")
class OrderLog: def __init__(self, size): self.log = list() self.size = size def __repr__(self): return str(self.log) def record(self, order_id): self.log.append(order_id) if len(self.log) > self.size: self.log = self.log[1:] def get_last(self, i): return self.log[-i] log = OrderLog(5) log.record(1) log.record(2) assert log.log == [1, 2] log.record(3) log.record(4) log.record(5) assert log.log == [1, 2, 3, 4, 5] log.record(6) log.record(7) log.record(8) assert log.log == [4, 5, 6, 7, 8] assert log.get_last(4) == 5 assert log.get_last(1) == 8
# # PySNMP MIB module OADHCP-SERVER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OADHCP-SERVER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:22:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Integer32, Unsigned32, iso, NotificationType, Gauge32, ModuleIdentity, TimeTicks, ObjectIdentity, Counter32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, enterprises, MibIdentifier, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Integer32", "Unsigned32", "iso", "NotificationType", "Gauge32", "ModuleIdentity", "TimeTicks", "ObjectIdentity", "Counter32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "enterprises", "MibIdentifier", "Bits") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") class HostName(DisplayString): subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(0, 32) class EntryStatus(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("valid", 1), ("invalid", 2), ("insert", 3)) class ObjectStatus(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("enable", 1), ("disable", 2), ("other", 3)) oaccess = MibIdentifier((1, 3, 6, 1, 4, 1, 6926)) oaManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1)) oaDhcp = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11)) oaDhcpServer = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1)) oaDhcpServerGeneral = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1)) oaDhcpServerStatus = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 1), ObjectStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpServerStatus.setStatus('mandatory') oaDhcpNetbiosNodeType = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("B-node", 2), ("P-node", 3), ("M-node", 4), ("H-node", 5)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpNetbiosNodeType.setStatus('mandatory') oaDhcpDomainName = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 3), HostName()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDomainName.setStatus('mandatory') oaDhcpDefaultLeaseTime = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDefaultLeaseTime.setStatus('mandatory') oaDhcpMaxLeaseTime = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpMaxLeaseTime.setStatus('mandatory') oaDhcpDNSTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2), ) if mibBuilder.loadTexts: oaDhcpDNSTable.setStatus('mandatory') oaDhcpDNSEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpDNSNum")) if mibBuilder.loadTexts: oaDhcpDNSEntry.setStatus('mandatory') oaDhcpDNSNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpDNSNum.setStatus('mandatory') oaDhcpDNSIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDNSIp.setStatus('mandatory') oaDhcpDNSStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 2, 1, 3), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDNSStatus.setStatus('mandatory') oaDhcpNetbiosServersTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3), ) if mibBuilder.loadTexts: oaDhcpNetbiosServersTable.setStatus('mandatory') oaDhcpNetbiosServersEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpNetbiosServerNum")) if mibBuilder.loadTexts: oaDhcpNetbiosServersEntry.setStatus('mandatory') oaDhcpNetbiosServerNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpNetbiosServerNum.setStatus('mandatory') oaDhcpNetbiosServerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpNetbiosServerIp.setStatus('mandatory') oaDhcpNetbiosServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 3, 1, 3), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpNetbiosServerStatus.setStatus('mandatory') oaDhcpSubnetConfigTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4), ) if mibBuilder.loadTexts: oaDhcpSubnetConfigTable.setStatus('mandatory') oaDhcpSubnetConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpInterfaceName"), (0, "OADHCP-SERVER-MIB", "oaDhcpSubnetIp"), (0, "OADHCP-SERVER-MIB", "oaDhcpSubnetMask")) if mibBuilder.loadTexts: oaDhcpSubnetConfigEntry.setStatus('mandatory') oaDhcpInterfaceName = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpInterfaceName.setStatus('mandatory') oaDhcpSubnetIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpSubnetIp.setStatus('mandatory') oaDhcpSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpSubnetMask.setStatus('mandatory') oaDhcpOptionSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpOptionSubnetMask.setStatus('mandatory') oaDhcpIsOptionMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 5), ObjectStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpIsOptionMask.setStatus('mandatory') oaDhcpSubnetConfigStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 4, 1, 6), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpSubnetConfigStatus.setStatus('mandatory') oaDhcpIpRangeTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5), ) if mibBuilder.loadTexts: oaDhcpIpRangeTable.setStatus('mandatory') oaDhcpIpRangeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpIpRangeSubnetIp"), (0, "OADHCP-SERVER-MIB", "oaDhcpIpRangeSubnetMask"), (0, "OADHCP-SERVER-MIB", "oaDhcpIpRangeStart")) if mibBuilder.loadTexts: oaDhcpIpRangeEntry.setStatus('mandatory') oaDhcpIpRangeSubnetIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpIpRangeSubnetIp.setStatus('mandatory') oaDhcpIpRangeSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpIpRangeSubnetMask.setStatus('mandatory') oaDhcpIpRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpIpRangeStart.setStatus('mandatory') oaDhcpIpRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpIpRangeEnd.setStatus('mandatory') oaDhcpIpRangeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 5, 1, 5), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpIpRangeStatus.setStatus('mandatory') oaDhcpDefaultGWTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6), ) if mibBuilder.loadTexts: oaDhcpDefaultGWTable.setStatus('mandatory') oaDhcpDefaultGWEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpDefaultGWSubnetIp"), (0, "OADHCP-SERVER-MIB", "oaDhcpDefaultGWSubnetMask"), (0, "OADHCP-SERVER-MIB", "oaDhcpDefaultGWIp")) if mibBuilder.loadTexts: oaDhcpDefaultGWEntry.setStatus('mandatory') oaDhcpDefaultGWSubnetIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpDefaultGWSubnetIp.setStatus('mandatory') oaDhcpDefaultGWSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpDefaultGWSubnetMask.setStatus('mandatory') oaDhcpDefaultGWIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpDefaultGWIp.setStatus('mandatory') oaDhcpDefaultGWStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 1, 6, 1, 4), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpDefaultGWStatus.setStatus('mandatory') oaDhcpRelay = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2)) oaDhcpRelayGeneral = MibIdentifier((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1)) oaDhcpRelayStatus = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1, 1), ObjectStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpRelayStatus.setStatus('mandatory') oaDhcpRelayClearConfig = MibScalar((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("None", 1), ("ResetConfig", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpRelayClearConfig.setStatus('mandatory') oaDhcpRelayServerTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2), ) if mibBuilder.loadTexts: oaDhcpRelayServerTable.setStatus('mandatory') oaDhcpRelayServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpRelayServerIp")) if mibBuilder.loadTexts: oaDhcpRelayServerEntry.setStatus('mandatory') oaDhcpRelayServerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpRelayServerIp.setStatus('mandatory') oaDhcpRelayServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 2, 1, 2), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpRelayServerStatus.setStatus('mandatory') oaDhcpRelayInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3), ) if mibBuilder.loadTexts: oaDhcpRelayInterfaceTable.setStatus('mandatory') oaDhcpRelayInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1), ).setIndexNames((0, "OADHCP-SERVER-MIB", "oaDhcpRelayIfName")) if mibBuilder.loadTexts: oaDhcpRelayInterfaceEntry.setStatus('mandatory') oaDhcpRelayIfName = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: oaDhcpRelayIfName.setStatus('mandatory') oaDhcpRelayIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6926, 1, 11, 2, 3, 1, 2), EntryStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: oaDhcpRelayIfStatus.setStatus('mandatory') mibBuilder.exportSymbols("OADHCP-SERVER-MIB", oaDhcpDNSNum=oaDhcpDNSNum, oaDhcpDNSIp=oaDhcpDNSIp, oaDhcpNetbiosServerStatus=oaDhcpNetbiosServerStatus, oaDhcpRelayStatus=oaDhcpRelayStatus, oaDhcpIpRangeTable=oaDhcpIpRangeTable, oaDhcpServer=oaDhcpServer, oaDhcpDefaultGWIp=oaDhcpDefaultGWIp, oaDhcpDefaultGWEntry=oaDhcpDefaultGWEntry, oaDhcpDefaultLeaseTime=oaDhcpDefaultLeaseTime, EntryStatus=EntryStatus, oaDhcpNetbiosServersTable=oaDhcpNetbiosServersTable, oaDhcpRelay=oaDhcpRelay, oaDhcpNetbiosServerNum=oaDhcpNetbiosServerNum, oaManagement=oaManagement, oaDhcpNetbiosNodeType=oaDhcpNetbiosNodeType, oaDhcpOptionSubnetMask=oaDhcpOptionSubnetMask, oaDhcpIpRangeStatus=oaDhcpIpRangeStatus, oaDhcpRelayInterfaceEntry=oaDhcpRelayInterfaceEntry, oaDhcpIpRangeSubnetMask=oaDhcpIpRangeSubnetMask, oaccess=oaccess, oaDhcpSubnetConfigEntry=oaDhcpSubnetConfigEntry, oaDhcpRelayServerIp=oaDhcpRelayServerIp, oaDhcpRelayClearConfig=oaDhcpRelayClearConfig, oaDhcpRelayGeneral=oaDhcpRelayGeneral, oaDhcpRelayIfName=oaDhcpRelayIfName, oaDhcpMaxLeaseTime=oaDhcpMaxLeaseTime, oaDhcpServerGeneral=oaDhcpServerGeneral, ObjectStatus=ObjectStatus, oaDhcpDefaultGWStatus=oaDhcpDefaultGWStatus, oaDhcpDefaultGWSubnetIp=oaDhcpDefaultGWSubnetIp, oaDhcpIpRangeEnd=oaDhcpIpRangeEnd, oaDhcpDNSEntry=oaDhcpDNSEntry, oaDhcpSubnetConfigTable=oaDhcpSubnetConfigTable, oaDhcpSubnetConfigStatus=oaDhcpSubnetConfigStatus, oaDhcpDefaultGWTable=oaDhcpDefaultGWTable, oaDhcpDNSStatus=oaDhcpDNSStatus, oaDhcpNetbiosServersEntry=oaDhcpNetbiosServersEntry, oaDhcp=oaDhcp, oaDhcpServerStatus=oaDhcpServerStatus, oaDhcpInterfaceName=oaDhcpInterfaceName, oaDhcpRelayServerTable=oaDhcpRelayServerTable, oaDhcpRelayInterfaceTable=oaDhcpRelayInterfaceTable, oaDhcpSubnetMask=oaDhcpSubnetMask, oaDhcpIpRangeEntry=oaDhcpIpRangeEntry, oaDhcpIsOptionMask=oaDhcpIsOptionMask, oaDhcpDomainName=oaDhcpDomainName, oaDhcpIpRangeSubnetIp=oaDhcpIpRangeSubnetIp, oaDhcpDNSTable=oaDhcpDNSTable, oaDhcpRelayServerStatus=oaDhcpRelayServerStatus, oaDhcpNetbiosServerIp=oaDhcpNetbiosServerIp, oaDhcpDefaultGWSubnetMask=oaDhcpDefaultGWSubnetMask, oaDhcpRelayServerEntry=oaDhcpRelayServerEntry, oaDhcpRelayIfStatus=oaDhcpRelayIfStatus, HostName=HostName, oaDhcpSubnetIp=oaDhcpSubnetIp, oaDhcpIpRangeStart=oaDhcpIpRangeStart)
sample_split=1.0 data_loader_usage = 'Training' training_data = "train_train" evaluate_data = "privatetest"
# This function checks if year is a leap year. def isLeapYear(year): if year%100 == 0: return True if year%400 == 0 else False elif year%4 == 0: return True else: return False # This function returns the number of days in a month def monthDays(year, month): MONTHDAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) if month == 2 and isLeapYear(year): return 29 return MONTHDAYS[month-1] # Returns the next day def nextDay(year, month, day): if day == monthDays(year,month): if month == 12: return year+1, 1, 1 else: return year, month+1, 1 return year, month, day+1 # This is the main function def main(): print("Was", 2017, "a leap year?", isLeapYear(2017)) # False? print("Was", 2016, "a leap year?", isLeapYear(2016)) # True? print("Was", 2000, "a leap year?", isLeapYear(2000)) # True? print("Was", 1900, "a leap year?", isLeapYear(1900)) # False? print("January 2017 had", monthDays(2017, 1), "days") # 31? print("February 2017 had", monthDays(2017, 2), "days") # 28? print("February 2016 had", monthDays(2016, 2), "days") # 29? print("February 2000 had", monthDays(2000, 2), "days") # 29? print("February 1900 had", monthDays(1900, 2), "days") # 28? y, m, d = nextDay(2017, 1, 30) print(y, m, d) # 2017 1 31 ? y, m, d = nextDay(2017, 1, 31) print(y, m, d) # 2017 2 1 ? y, m, d = nextDay(2017, 2, 28) print(y, m, d) # 2017 3 1 ? y, m, d = nextDay(2016, 2, 29) print(y, m, d) # 2016 3 1 ? y, m, d = nextDay(2017, 12, 31) print(y, m, d) # 2018 1 1 ? # call the main function main()
#encoding:utf-8 subreddit = 'wtf' t_channel = '@reddit_wtf' def send_post(submission, r2t): return r2t.send_simple(submission)
programming_languages = ["Python", "Scala", "Haskell", "F#", "C#", "JavaScript"] for lang in programming_languages: if (lang == "Haskell"): continue print("Found Haskell !!!", end='\n') # this statement will never be executed print(lang, end=' ')
inc = 1 num = 1 for x in range (5,0,-1): for y in range(x,0,-1): print(" ",end="") print(str(num)*inc) num += 2 inc += 2
n = int(input()) a = list(map(int, input().split())) k_max = 0 g_max = 0 for k in range(2, max(a) + 1): gcdness = 0 for elem in a: if elem % k == 0: gcdness += 1 if gcdness >= g_max: g_max = gcdness k_max = k print(k_max)
# 326. Power of Three # ttungl@gmail.com # Given an integer, write a function to determine if it is a power of three. # Follow up: # Could you do it without using any loop / recursion? class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ # sol 1: follow-up # runtime: 193ms # Use 3^19 (is 1162261467), bcos 3^20 is bigger than int. return n > 0 and (3**19 % n) == 0 # sol 2: # runtime: 205ms if n <= 0: return False while n % 3==0: n/=3 return n==1
class Solution: def getSmallestString(self, n: int, k: int) -> str: result = "" for index in range(n): digitsLeft = n - index - 1 for c in range(1, 27): if k - c <= digitsLeft * 26: k -= c result += chr(ord('a') + c -1) break return result
a_val = int(input()) b_val = int(input()) def gcd(a, b): if b > a: a, b = b, a if a % b == 0: return b else: return gcd(b, a % b) def reduce_fraction(n, m): divider = gcd(n, m) return int(n / divider), int(m / divider) result = reduce_fraction(a_val, b_val) print(*result)
class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 0 elif n < 0: return (1.0 / x) ** abs(n) else: return x ** n s = Solution() print(s.myPow(2.00000, 10))
MOD = 998244353 r, c, n = map(int, input().split()) dp = [[0] * (1 << c) for _ in range(r + 1)] dp[0][0] = 1 for row in range(r): for bit_prev in range(1 << c): bit_prev <<= 1 for bit in range(1 << c): bit <<= 1 count = 0 for i in range(c + 1): if ((bit_prev >> i) & 1 + (bit_prev >> i + 1) & 1 + (bit >> i) & 1 + (bit >> i + 1) & 1) & 1: count += 1 bit >>= 1 dp[row + 1][bit] += count print(sum(dp[-1]))
array([[ -8.71756106, -1.36180276], [ -8.58324975, -1.6198254 ], [ -8.44660752, -1.87329902], [ -8.30694854, -2.12042891], [ -8.16366778, -2.35941504], [ -8.01626074, -2.58846783], [ -7.8643173 , -2.80576865], [ -7.70752251, -3.0094502 ], [ -7.5458139 , -3.19806094], [ -7.37912158, -3.3697834 ], [ -7.20747945, -3.5226388 ], [ -7.03113284, -3.65485777], [ -6.85017635, -3.76269362], [ -6.66523309, -3.84275185], [ -6.47736681, -3.89099441], [ -6.28828709, -3.90157094], [ -6.10156897, -3.86340302], [ -5.91871331, -3.79305295], [ -5.74014533, -3.69605418], [ -5.56572991, -3.57762694], [ -5.39517681, -3.44210881], [ -5.22781241, -3.29456196], [ -5.06232383, -3.14085048], [ -4.89257735, -2.98799629], [ -4.71966422, -2.83672204], [ -4.54372346, -2.68713228], [ -4.36476778, -2.53940585], [ -4.18276114, -2.39377984], [ -3.99760462, -2.25058361], [ -3.80926438, -2.11016077], [ -3.61765447, -1.97299377], [ -3.4227503 , -1.83963827], [ -3.22466935, -1.71063201], [ -3.02363515, -1.5864963 ], [ -2.8199305 , -1.46774788], [ -2.61386232, -1.3549046 ], [ -2.40573771, -1.24848664], [ -2.19584837, -1.14901525], [ -1.98446111, -1.05701006], [ -1.77181225, -0.97298507], [ -1.55810414, -0.89744287], [ -1.34350217, -0.83086662], [ -1.12813134, -0.77370943], [ -0.91207182, -0.72638078], [ -0.69535387, -0.68923045], [ -0.47795283, -0.66253066], [ -0.25978553, -0.64645761], [ -0.04070946, -0.64107399], [ 0.17947379, -0.64631382], [ 0.40100956, -0.661971 ], [ 0.62417469, -0.68769217], [ 0.84925505, -0.72297438], [ 1.0765168 , -0.7671692 ], [ 1.30617386, -0.81949558], [ 1.53834874, -0.87904872], [ 1.77300538, -0.94474994], [ 2.01004375, -1.0156523 ], [ 2.24941382, -1.09111049], [ 2.49090963, -1.17034172], [ 2.76505053, -1.25699281], [ 3.0392737 , -1.33956764], [ 3.31357819, -1.4173004 ], [ 3.58794949, -1.48951235], [ 3.86235753, -1.55528368], [ 4.13674424, -1.61362995], [ 4.41101533, -1.66379521], [ 4.68503054, -1.70493339], [ 4.95859183, -1.73617318], [ 5.23143608, -1.75675047], [ 5.50323138, -1.76605581], [ 5.77357759, -1.7636462 ], [ 6.04201219, -1.74925505], [ 6.30802249, -1.72280316], [ 6.57106704, -1.6844134 ], [ 6.83061188, -1.63443731], [ 7.0861612 , -1.57343982], [ 7.33719115, -1.50196243], [ 7.58299863, -1.42023179], [ 7.8226528 , -1.32820378], [ 8.0545371 , -1.22514719], [ 8.27658784, -1.11037577], [ 8.48611424, -0.9831958 ], [ 8.67910996, -0.84268891], [ 8.85098102, -0.68873567], [ 8.99611087, -0.52182284], [ 9.10907438, -0.34357458], [ 9.18417432, -0.15630253], [ 9.21305752, 0.03692533], [ 9.1840698 , 0.23008171], [ 9.11910658, 0.4192829 ], [ 9.02164578, 0.60281683], [ 8.8945003 , 0.77935859], [ 8.73948257, 0.94759291], [ 8.5591441 , 1.10658568], [ 8.35621373, 1.25571578], [ 8.13392856, 1.39493299], [ 7.89600098, 1.5249387 ], [ 7.64494533, 1.64617321], [ 7.38361784, 1.75967206], [ 7.11449512, 1.86661923], [ 6.83961129, 1.96821002], [ 6.56059338, 2.06558415], [ 6.27873646, 2.15980551], [ 5.99507103, 2.25185709], [ 5.71041846, 2.34264296], [ 5.42539621, 2.43296897], [ 5.14049084, 2.52356403], [ 4.85570433, 2.61443171], [ 4.57103584, 2.70556915], [ 4.28648169, 2.79696731], [ 4.00217813, 2.88852238], [ 3.72231814, 2.97718081], [ 3.44870505, 3.06108881], [ 3.18310961, 3.13857246], [ 2.92666246, 3.20839957], [ 2.68000575, 3.26968441], [ 2.44342382, 3.32179983], [ 2.21693264, 3.36431422], [ 2.00034546, 3.39694375], [ 1.79331822, 3.41952112], [ 1.59535102, 3.4320146 ], [ 1.40578511, 3.43455695], [ 1.22408879, 3.42711031], [ 1.04965328, 3.40969902], [ 0.88172434, 3.38251449], [ 0.71940866, 3.34591804], [ 0.5619256 , 3.29981197], [ 0.40770804, 3.24544617], [ 0.25548391, 3.18343735], [ 0.10399591, 3.11449499], [ -0.04775527, 3.03962421], [ -0.20018042, 2.96056489], [ -0.35331487, 2.8785744 ], [ -0.52508461, 2.78543704], [ -0.69712913, 2.70164087], [ -0.86954503, 2.63519574], [ -1.04209219, 2.59240169], [ -1.21405958, 2.57909091], [ -1.38377538, 2.60407937], [ -1.55062259, 2.65787841], [ -1.71439338, 2.73536957], [ -1.87529031, 2.83169338], [ -2.03395581, 2.94135403], [ -2.19140835, 3.05794591], [ -2.33805266, 3.16255329], [ -2.48451156, 3.25896796], [ -2.63059232, 3.3426935 ], [ -2.77602606, 3.41054738], [ -2.92043777, 3.46019213], [ -3.06330851, 3.48968652], [ -3.20374051, 3.4957004 ], [ -3.34029351, 3.47415945], [ -3.47007084, 3.41768448], [ -3.59300929, 3.33351807], [ -3.70923634, 3.22566695], [ -3.81889624, 3.09672268], [ -3.92268025, 2.95011367], [ -4.02185397, 2.79022243], [ -4.1178521 , 2.62159416], [ -4.2161323 , 2.46452926], [ -4.31781117, 2.31796144], [ -4.42318035, 2.1831457 ], [ -4.5322453 , 2.06073257], [ -4.64501631, 1.95155647], [ -4.76140997, 1.85631353], [ -4.88126733, 1.77560052], [ -5.00435734, 1.70987926], [ -5.13042301, 1.65962035], [ -5.25938944, 1.62667518], [ -5.39072417, 1.61040595], [ -5.52382922, 1.60897593], [ -5.65849722, 1.62377451], [ -5.79444211, 1.65715234], [ -5.93107153, 1.71528106], [ -6.06746368, 1.79081424], [ -6.20317769, 1.88240466], [ -6.33788905, 1.98864946], [ -6.47136342, 2.10834012], [ -6.60346438, 2.24020588], [ -6.73412053, 2.3831744 ], [ -6.86333984, 2.53617923], [ -6.99113472, 2.69858842], [ -7.12064178, 2.87523527], [ -7.25444618, 3.04299389], [ -7.39243765, 3.20138631], [ -7.53467379, 3.34977808], [ -7.68110851, 3.48788772], [ -7.83182097, 3.61515988], [ -7.98682564, 3.73117341], [ -8.14612629, 3.83548086], [ -8.30966415, 3.92772849], [ -8.47726222, 4.00781042], [ -8.64863214, 4.07585135], [ -8.82344578, 4.13196495], [ -9.0013035 , 4.17638389], [ -9.18202552, 4.20814242], [ -9.36528871, 4.22605346], [ -9.55064213, 4.22773377], [ -9.73708983, 4.20936143], [ -9.92226831, 4.16594795], [-10.10086343, 4.09095817], [-10.26193798, 3.97820376], [-10.38552981, 3.82399663], [-10.47199275, 3.64300549], [-10.52918735, 3.44482848], [-10.5584774 , 3.23235077], [-10.56124879, 3.00791184], [-10.53904816, 2.77357185], [-10.49439476, 2.53143451], [-10.42938497, 2.2831314 ], [-10.34681037, 2.03021889], [-10.24958903, 1.77398657], [-10.14059192, 1.51544409], [-10.02259337, 1.25535648], [ -9.89818344, 0.99427857], [ -9.76968504, 0.73258465], [ -9.63916162, 0.47047985], [ -9.50822 , 0.20830133], [ -9.37711487, -0.05380021], [ -9.24579077, -0.31579848], [ -9.11420368, -0.5776724 ], [ -8.98238041, -0.83943435], [ -8.85033536, -1.10109084], [ -8.71756106, -1.36180276]])
class Solution: """ @param numbersbers : Give an array numbersbers of n integer @return : Find all unique triplets in the array which gives the sum of zero. """ def threeSum(self, numbers): if not numbers or len(numbers) < 3: return set() numbers.sort() triplets = [] seen = set() for idx, val in enumerate(numbers): lo, hi = idx+1, len(numbers)-1 while lo < hi: sol = (val, numbers[lo], numbers[hi]) sums = sum(sol) if sums == 0 and sol not in seen: triplets.append(sol) seen.add(sol) elif sums < 0: lo += 1 else: hi -= 1 return triplets
"""Module containing scheduling algorithms. Each scheduling algorithm receives a specific set of inputs. They output partial mappings when requested using the query method. Implemented scheduling methods: OpenMPStatic, LPT. Methods with interfaces but no implementation: OpenMPDynamic, OpenMPGuided, RecursiveBipartition. """ class Scheduler: """ Basic scheduler class. Attributes ---------- name : string Algorithm's name num_resources : int Number of identical resources """ def __init__(self, num_resources, name='scheduler'): self.name = name self.num_resources = num_resources def __repr__(self): return self.name def query(self, resource_id): """ Provides the next tasks to a given resource. Parameters ---------- resource_id : int Identifier of the resource Returns ------- empty list """ return [] class OpenMPStatic(Scheduler): """ Static scheduler based on the algorithm used for OpenMP. Notes ----- This scheduler requires an additional parameters defining the chunk size. Its initialization method pre-computes the schedule. """ def __init__(self, tasks, num_resources, chunk_size=0): Scheduler.__init__(self, num_resources, name='Static') self.chunk_size = chunk_size # Pre-computes the schedule schedule = [list() for i in range(num_resources)] num_tasks = len(tasks) # Two styles # if chunk size == 0, does a compact mapping if chunk_size == 0: # Size of partitions partition_size = num_tasks // num_resources # Number of resources that will have +1 tasks leftover = num_tasks % num_resources # Starting task identifier task = 0 # Iterates over the resources mapping groups of tasks to them for resource in range(num_resources): # Sets the actual size of the group of tasks to map # to this resource based on the existence of any leftover if leftover > 0: group_size = partition_size + 1 leftover -= 1 else: # No more resources with +1 tasks group_size = partition_size for i in range(group_size): schedule[resource].append(task) task += 1 # next task to map else: # does a round-robin mapping by chunks resource = 0 chunk_counter = 0 for task in range(num_tasks): schedule[resource].append(task) chunk_counter += 1 # if the chunk is full, starts a new one in the next resource if chunk_counter == chunk_size: chunk_counter = 0 resource = (resource + 1) % num_resources # Stores the pre-computed schedule self.schedule = schedule def query(self, resource_id): """ Provides a list of tasks to a resource once. Parameters ---------- resource_id : int Identifier of the resource Returns ------- list of int Pre-computed list of task identifiers, or an empty list """ tasks = self.schedule[resource_id] if tasks: # if they have not been scheduled before # empties the list self.schedule[resource_id] = [] return tasks class LPT(Scheduler): """ Largest Processing Time first scheduler. Notes ----- Its initialization creates an internal list of tasks ordered by load. """ def __init__(self, tasks, num_resources): Scheduler.__init__(self, num_resources, name='LPT') num_tasks = len(tasks) # Orders tasks by non-increasing load tasks_by_priority = [(tasks[i], i) for i in range(num_tasks)] tasks_by_priority.sort(reverse=True) self.tasks = tasks_by_priority def query(self, resource_id): """ Provides a list of one task to a resource. Parameters ---------- resource_id : int Identifier of the resource Returns ------- list of int List with one task identifier """ if self.tasks: load, task_id = self.tasks.pop(0) return [task_id] else: # nothing to return return [] class OpenMPDynamic(Scheduler): """ Dynamic scheduler based on the algorithm used for OpenMP. Notes ----- This scheduler requires an additional parameters defining the chunk size. """ def __init__(self, tasks, num_resources, chunk_size=1): Scheduler.__init__(self, num_resources, name='Dynamic') self.chunk_size = chunk_size # TODO def query(self, resource_id): """ Provides a list of tasks to a resource. Parameters ---------- resource_id : int Identifier of the resource Returns ------- list of int List of task identifiers based on the chunk size, or an empty list """ # TODO class OpenMPGuided(Scheduler): """ Guided scheduler based on the algorithm used for OpenMP. Notes ----- This scheduler requires an additional parameters defining the chunk size. The chunk size gives the minimum size of the list of tasks to return. The size of the list to return is based on the number of remaining tasks to schedule divided by the number of resources in the system. """ def __init__(self, tasks, num_resources, chunk_size=1): Scheduler.__init__(self, num_resources, name='Guided') self.chunk_size = chunk_size # TODO def query(self, resource_id): """ Provides a list of tasks to a resource. Parameters ---------- resource_id : int Identifier of the resource Returns ------- list of int List of task identifiers based on the chunk size, or an empty list """ # TODO class RecursiveBipartition(Scheduler): """ Recursive bipartition scheduler for use when the number of resources is a power of two. Notes ----- Its initialization method pre-computes the schedule. The bipartition should split a sequence of tasks in the place where the load is the most balanced between the two parts. A variation of the algorithm that works with numbers that are not power of two would just have to define different proportions when partitioning For instance, for 5 resources, the algorithm would first split the load at the 2/5-3/5 point and follow recursively from there. """ def __init__(self, tasks, num_resources): Scheduler.__init__(self, num_resources, name='RB') # TODO def query(self, resource_id): """ Provides a list of tasks to a resource once. Parameters ---------- resource_id : int Identifier of the resource Returns ------- list of int Pre-computed list of task identifiers, or an empty list """ tasks = self.schedule[resource_id] if tasks: # if they have not been scheduled before # empties the list self.schedule[resource_id] = [] return tasks
NAME = 'comic.py' ORIGINAL_AUTHORS = [ 'Miguel Boekhold' ] ABOUT = ''' Returns a random comic from xkcd ''' COMMANDS = ''' >>> .comic returns a url of a random comic ''' WEBSITE = ''
def printMyName(myName): print('My name is' + myName) print('Who are you ?') myName = input() printMyName(myName)
def get_version_from_win32_pe(file): # http://windowssdk.msdn.microsoft.com/en-us/library/ms646997.aspx sig = struct.pack("32s", u"VS_VERSION_INFO".encode("utf-16-le")) # This pulls the whole file into memory, so not very feasible for # large binaries. try: filedata = open(file).read() except IOError: return "Unknown" offset = filedata.find(sig) if offset == -1: return "Unknown" filedata = filedata[offset + 32 : offset + 32 + (13*4)] version_struct = struct.unpack("13I", filedata) ver_ms, ver_ls = version_struct[4], version_struct[5] return "%d.%d.%d.%d" % (ver_ls & 0x0000ffff, (ver_ms & 0xffff0000) >> 16, ver_ms & 0x0000ffff, (ver_ls & 0xffff0000) >> 16)
class NodeConfig: def __init__(self, node_name: str, ws_url: str) -> None: self.node_name = node_name self.ws_url = ws_url
#always put a repr in place to explicitly differentiate str from repr class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage def __repr__(self): return '{self.__class__.__name__}({self.color}, {self.mileage})'.format(self=self) def __str__(self): return 'a {self.color} car'.format(self=self)
# -*- coding: utf-8 -*- 'Documentation Comments' __author__ = '吴钦飞' def test(): print('location module') if __name__=='__main__': test()
# #星号表达式 # def drop_first_last(grades): # first, *middle, last = grades # return avg(middle) record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212') name, email, *phone_numbers = record print(name) print(email) print(phone_numbers) #星号表达式用在列表开始的部分 *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3] print(trailing) print(current)
BROKER_URL = "mongodb://arbor/celery" CELERY_RESULT_BACKEND = "mongodb" CELERY_MONGODB_BACKEND_SETTINGS = { "host": "arbor", "database": "celery" }