content
stringlengths
7
1.05M
if True: pass else: x = 3
print("Welcome to the Band Name Generator.") city_name =input("What's name of the city you grew up in?\n") pet_name =input("What's your pet's name?\n") print("Your band name could be Bristole Rabbit")
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: """ abcabcbb i j {} """ seen = set() best = 0 i = 0 for j in range(0, len(s)): end_char = s[j] while end_char in seen: start_char = s[i] seen.remove(start_char) i += 1 seen.add(end_char) best = max(best, len(seen)) return best
#!/usr/bin/env python # encoding: utf-8 __title__ = "Arithmatic Coding" __author__ = "Waleed Yaser ([email protected])" __version__ = "1.0" """ Arithmatic Coding ~~~~~~~~~~~~~~~~~ A class for implementing Arithmatic coding. constructor takes 3 parameters: *symbols list *probalities list *terminator charachter There are 2 calable methods: *Compress: take the word to compress and return code. *Decompress: takes the compressed code and return word. require: *python 2.7 """ class ArithmaticCoding: def __init__(self, symbols, probs, terminator): """ Construct the probability range table in dictionaries data type. """ self.symbols = symbols self.probs = probs self.__InitRangeTable() self.terminator = terminator # End of word. def __InitRangeTable(self): """ Complete the probability range table ============================================= Symbol | Probability | Range low | Range high ============================================= | | | ============================================= """ self.rangeLow = {} self.rangeHigh = {} rangeStart = 0 for i in xrange(len(self.symbols)): s = self.symbols[i] self.rangeLow[s] = rangeStart rangeStart += self.probs[i] self.rangeHigh[s] = rangeStart def Compress(self, word): """ Compress given word into Arimatic code and return code. """ lowOld = 0.0 highOld = 1.0 _range = 1.0 # Iterate through the word to find the final range. for c in word: low = lowOld + _range * self.rangeLow[c] high = lowOld + _range * self.rangeHigh[c] _range = high - low # Updete old low & hihh lowOld = low highOld = high # Generating code word for encoder. code = ["0", "."] # Binary fractional number k = 2 # kth binary fraction bit value = self.__GetBinaryFractionValue("".join(code)) while(value < low): # Assign 1 to the kth binary fraction bit code.append('1') value = self.__GetBinaryFractionValue("".join(code)) if (value > high): # Replace the kth bit by 0 code[k] = '0' value = self.__GetBinaryFractionValue("".join(code)) k += 1 return value def Decompress(self, code): """ Uncompress given Arimatic code and return word. """ s = "" # flag to stop the while loop result = "" while (s != self.terminator): # find the key which has low <= code and high > code for key, value in self.rangeLow.iteritems(): if (code >= self.rangeLow[key] and code < self.rangeHigh[key]): result += key # Append key to the result # update low, high, code low = self.rangeLow[key] high = self.rangeHigh[key] _range = high - low code = (code - low)/_range # chech for the terminator if (key == self.terminator): s = key break return result def __GetBinaryFractionValue(self, binaryFraction): """ Compute the binary fraction value using the formula of: (2^-1) * 1st bit + (2^-2) * 2nd bit + ... """ value = 0 power = 1 # Git the fraction bits after "." fraction = binaryFraction.split('.')[1] # Compute the formula value for i in fraction: value += ((2 ** (-power)) * int(i)) power += 1 return value
class Settings: info = { "version": "0.2.0", "description": "Python library which allows to read, modify, create and run EnergyPlus files and simulations." } groups = { 'simulation_parameters': [ 'Timestep', 'Version', 'SimulationControl', 'ShadowCalculations', 'SurfaceConvectionAlgorithm:Outside', 'SurfaceConvectionAlgorithm:Inside' 'GlobalGeometryRules', 'HeatBalanceAlgorithm' ], 'building': [ 'Site:Location', 'Building' ], 'climate': [ 'SizingPeriod:DesignDay', 'Site:GroundTemperature:BuildingSurface', ], 'schedules': [ 'ScheduleTypeLimits', 'ScheduleDayHourly', 'ScheduleDayInterval', 'ScheduleWeekDaily', 'ScheduleWeekCompact', 'ScheduleConstant', 'ScheduleFile', 'ScheduleDayList', 'ScheduleYear', 'ScheduleCompact' ], 'construction': [ 'Material', 'Material:NoMass', 'Material:AirGap', 'WindowMaterial:SimpleGlazingSystem', 'WindowMaterial:Glazing', 'WindowMaterial:Gas', 'WindowMaterial:Gap', 'Construction' ], 'internal_gains': [ 'People', 'Lights', 'ElectricEquipment', ], 'airflow': [ 'ZoneInfiltration:DesignFlowRate', 'ZoneVentilation:DesignFlowRate' ], 'zone': [ 'BuildingSurface:Detailed', ], 'zone_control': [ 'ZoneControl:Thermostat', 'ThermostatSetpoint:SingleHeating', 'ThermostatSetpoint:SingleCooling', 'ThermostatSetpoint:SingleHeatingOrCooling', 'ThermostatSetpoint:DualSetpoint', ], 'systems': [ 'Zone:IdealAirLoadsSystem', 'HVACTemplate:Zone:IdealLoadsAirSystem' ], 'outputs': [ 'Output:SQLite', 'Output:Table:SummaryReports' ] }
DEBUG = False SECRET_KEY = '3tJhmR0XFbSOUG02Wpp7' CSRF_ENABLED = True CSRF_SESSION_LKEY = 'e8uXRmxo701QarZiXxGf'
#SALÁRIO E AUMENTO | IF: OU ELSE: salário = float(input('Qual é o salário do funcionário? R$')) if salário <= 1250: novosalário = salário + (salário * 15 / 100) #Aumento de 15% else: novosalário = salário + (salário * 10 / 100) #Aumento de 10% print('Quem ganhava R${:.2f} passa a ganhar {:.2f}.'.format(salário, novosalário))
''' Statement Given a month - an integer from 1 to 12, print the number of days in it in the year 2017. Example input #1 1 (January) Example output #1 31 Example input #2 2 (February) Example output #2 28 ''' month = int(input()) if month == 2: print(28) elif month < 8: if month % 2 == 0: print(30) else: print(31) else: if month % 2 == 0: print(31) else: print(30)
# Challenge No 9 Intermediate # https://www.reddit.com/r/dailyprogrammer/comments/pu1y6/2172012_challenge_9_intermediate/ # Take a string, scan file for string, and replace with another string def main(): pass def f_r(): fn = input('Please input filename: ') sstring = input('Please input string to search: ') rstring = input('Please input string to replace: ') with open(fn, 'r') as f: filedata = f.read() filedata = filedata.replace(sstring, rstring) with open(fn, 'w') as f: f.write(filedata) # To print line by line: # with open('*.txt', 'r') as f: # for line in f: # print(line) if __name__ == '__main__': main()
list1=[2,3,8,5,9,2,7,4] i=0 print("before list",list1) while i<len(list1): j=0 while j<i: if list1[i]<list1[j]: temp=list1[i] list1[i]=list1[j] list1[j]=temp j+=1 i+=1 print("after",list1)
class TimezoneTool: @classmethod def tzdb2abbreviation(cls, tzdb): if tzdb == "Asia/Seoul": return "KST" if tzdb == "America/Los_Angeles": return "ET" raise NotImplementedError({"tzdb":tzdb})
# == Parameters == # β = 1 / 1.05 ρ, mg = .7, .35 A = eye(2) A[0, :] = ρ, mg * (1-ρ) C = np.zeros((2, 1)) C[0, 0] = np.sqrt(1 - ρ**2) * mg / 10 Sg = np.array((1, 0)).reshape(1, 2) Sd = np.array((0, 0)).reshape(1, 2) Sb = np.array((0, 2.135)).reshape(1, 2) Ss = np.array((0, 0)).reshape(1, 2) economy = Economy(β=β, Sg=Sg, Sd=Sd, Sb=Sb, Ss=Ss, discrete=False, proc=(A, C)) T = 50 path = compute_paths(T, economy) gen_fig_1(path)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jan 6 13:43:13 2017 @author: ktt """ def flatten(py_list): flat = [] for k in py_list: if k not in [None, (), [], {}]: if isinstance(k, list): flat.extend(flatten(k)) else: flat.append(k) return flat
def shortest_path(sx, sy, maze): w = len(maze[0]) h = len(maze) board = [[None for i in range(w)] for i in range(h)] board[sx][sy] = 1 arr = [(sx, sy)] while arr: x, y = arr.pop(0) for i in [[1, 0], [-1, 0], [0, -1], [0, 1]]: nx, ny = x + i[0], y + i[1] if 0 <= nx < h and 0 <= ny < w: if board[nx][ny] is None: board[nx][ny] = board[x][y] + 1 if maze[nx][ny] == 1: continue arr.append((nx, ny)) return board def solution(maze): w = len(maze[0]) h = len(maze) tb = shortest_path(0, 0, maze) bt = shortest_path(h-1, w-1, maze) board = [] ans = 2 ** 32-1 for i in range(h): for j in range(w): if tb[i][j] and bt[i][j]: ans = min(tb[i][j] + bt[i][j] - 1, ans) return ans
def contador(i, f, p): """ => Faz uma contagem e mosta na tela. :param i: início da contagem :param f: fim da contagem :param p: passo da contagem :return:sem retorno """ c = i while c <= f: print(f"{c}", end="...") c += p print("FIM!") # Programa principal contador(2, 20, 2) help(contador)
# ----------------------------------------------------------------------------- # Copyright (c) 2013-2022, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt, distributed with this software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) # ----------------------------------------------------------------------------- # numpy._pytesttester is unconditionally imported by numpy.core, thus we can not exclude _pytesttester (which would be # preferred). Anyway, we can avoid importing pytest, which pulls in anotehr 150+ modules. See # https://github.com/numpy/numpy/issues/17183 excludedimports = ["pytest"]
# Este programa resuelve el siguiente problema: # Link: https://www.spoj.com/problems/INTEST/ # Input: # La entrada comienza con dos números enteros positivos n k (n, k<=10^7). Las siguientes n líneas de # entrada contienen un entero positivo t, no mayor de 10^9, cada uno # Output: # Escriba un solo entero a la salida, denotando cuántos enteros t, son divisibles por k def exercise01(): n = int(input("> ")) k = int(input("> ")) count = 0 for i in range(n): t = int(input("> ")) if(t % k == 0): count += 1 print(count) exercise01()
def bytes(b): """ Print bytes in a humanized way """ def humanize(b, base, suffices=[]): bb = int(b) for suffix in suffices: if bb < base: break bb /= float(base) return "%.2f %s" % (bb, suffix) print("Base 1024: ", humanize( b, 1024, ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'])) print("Base 1000: ", humanize( b, 1000, ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']))
try: f=open("no.py","r") print(f.read()) except BaseException as msg:#打印具体的异常信息 print(msg) #正常情况下 f=open("baidu.py","r") print(f.read()) ''' 异常try except 与else和finally的配合使用 ''' try: print("异常测试") except BaseException as msg: print(msg) else: print("运行正常,无报错") finally: print("不管有无异常。都执行") ''' 可以抛出异常的raise ,与Java的throw类似 raise 只能使用python提供的异常类 ''' def mustImpleMethod(): raise NotImplementedError("没有实现") print(mustImpleMethod())
""" Merge Sort Algorithm: Divide and Conquer Algorithm""" """Implementation: Merging two sorted arrays""" def merge_sort(arr1, arr2): n1 = len(arr1) n2 = len(arr2) index1, index2 = 0, 0 while index1 < n1 and index2 < n2: if arr1[index1] <= arr2[index2]: print(arr1[index1], end=" ") index1 += 1 else: print(arr2[index2], end=" ") index2 += 1 while index1 < n1: print(arr1[index1], end=" ") index1 += 1 while index2 < n2: print(arr2[index2], end=" ") index2 += 1 """ Merge function of merge sort """ def merge_func(arr, low, mid, high) -> list: n1 = mid - low + 1 n2 = high - mid left = [0] * n1 right = [0] * n2 for i in range(n1): left[i] = arr[low+i] for j in range(n2): right[j] = arr[mid+j+1] index1, index2, index3 = 0, 0, 0 while index1 < n1 and index2 < n2: if left[index1] <= right[index2]: arr[index3] = left[index1] index1 += 1 else: arr[index3] = right[index2] index2 += 1 index3 += 1 while index1 < n1: arr[index3] = left[index1] index3 += 1 index1 += 1 while index2 < n2: arr[index3] = right[index2] index3 += 1 index2 += 1 return arr def main(): arr_input = [1, 2, 5, 10] arr_input2 = [3, 4, 8, 9] arr_input3 = [5, 8, 12, 14, 7] #merge_sort(arr_input, arr_input2) print("") a2 = merge_func(arr_input3, 0, 3, 4) print(a2) # Using the special variable # __name__ if __name__ == "__main__": main()
#!/usr/bin/env python """ generated source for module Mapping """ class Mapping(object): """ generated source for class Mapping """ key = [] def __init__(self): """ generated source for method __init__ """ self.key = ["#"]*26 @classmethod def fromTranslation(self, cipher, translation): """ generated source for method __init___0 """ newKey = ["#"]*26 for i in range(len(translation)): newKey[ord(cipher[i]) - ord('A')] = translation[i] return newKey[:] def getKey(self): """ generated source for method getKey """ return self.key def setKey(self, newKey): """ generated source for method setKey """ self.key = newKey
# 1 # Answer: Programming language # 2 # Answer: B # 3 print("Hi") # 4 # Answer: quit() # 5 # Answer: 6 # 6 # Answer: B # 7 # Answer: - 10 + # 8 # Answer: >>> 1 / 0 # 9 # Answer: A # 10 # Answer: 15.0 # 11 # Answer: 3 # 12 # Answer: A # 13 # Answer: \"something\" # 14 # Answer: input # 15 # Answer: "World" # 16 # Answer: D # 17 # Answer: 777 # 18 # Answer: A # 19 # Answer: A # 20 # Answer: B # 21 # Answer: 7 # 22 # Answer: A # 23 # Answer: 20 # 24 # Answer: 12 # 25 # Answer: aaa # 26 # Answer: A # 27 # Answer: C # 28 # Answer: B # 29 # Answer: 82 # 30 # Answer: 2
#!/usr/bin/env python3 # vim: set fileencoding=utf-8 fileformat=unix expandtab : """__setup__.py -- metadata for xdwlib, A DocuWorks library for Python. Copyright (C) 2010 HAYASHI Hideki <[email protected]> All rights reserved. This software is subject to the provisions of the Zope Public License, Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. """ __author__ = "HAYASHI Hideki" __copyright__ = "Copyright (C) 2010 HAYASHI Hideki <[email protected]>" __license__ = "ZPL 2.1" __version__ = "3.9.6.1" __email__ = "[email protected]" __status__ = "Beta" __all__ = ("__author__", "__copyright__", "__license__", "__version__", "__email__", "__status__")
#!/usr/bin/env python NAME = 'BIG-IP Local Traffic Manager (F5 Networks)' def is_waf(self): if self.matchcookie(r'^BIGipServer'): return True elif self.matchheader(('X-Cnection', r'^close$'), attack=True): return True else: return False
print("ma petite chaine en or", end='')
# function for insertion sort def Insertion_Sort(list): for i in range(1, len(list)): temp = list[i] j = i - 1 while j >= 0 and list[j] > temp: list[j + 1] = list[j] j -= 1 list[j + 1] = temp # function to print list def Print_list(list): for i in range(0, len(list)): print(list[i],end=" ") print() num = int(input()) list = [] for i in range(0, num): list.append(int(input())) Insertion_Sort(list) Print_list(list) ''' Input : num = 6 array = [1, 6, 3, 3, 5, 2] Output : [1, 2, 3, 3, 5, 6] '''
def cleanupFile(file_path): with open(file_path,'r') as f: with open("data/transactions.csv",'w') as f1: next(f) # skip header line for line in f: f1.write(line) def getDateParts(date_string): year = '' month = '' day = '' date_parts = date_string.split('-') if (len(date_parts) > 2): year = date_parts[0] month = date_parts[1] day = date_parts[2] return year, month, day def dollarStringToNumber(dollar_string): numeric_value = 0.0 # float conversion doesn't like commas so remove them dollar_string = dollar_string.replace(',', '') # remove $ and any leading +/- character parts = dollar_string.split('$') if (len(parts) > 1): value_string = parts[1] numeric_value = float(value_string) return numeric_value
#calculation of power using recursion def exponentOfNumber(base,power): if power == 0: return 1 else: return base * exponentOfNumber(base,power-1) print("Enter only positive numbers below: ",) print("Enter a base: ") number = int(input()) print("Enter a power: ") exponent = int(input()) result = exponentOfNumber(number,exponent) print(number,"raised to the power of",exponent,"is",result)
def sma(): pass def ema(): pass
dict1={'Influenza':['Relenza','B 0 D'],'Swine Flu':['Symmetrel','B L D'],'Cholera':['Ciprofloxacin','B 0 D'],'Typhoid':['Azithromycin','B L D'],'Sunstroke':['Barbiturates','0 0 D'],'Common cold':['Ibuprufen','B 0 D'],'Whooping Cough':['Erthromycin','B 0 D'],'Gastroentritis':['Gelusil','B 0 D'],'Conjunctivitus':['Romycin','B 0 D'],'Dehydration':['ORS','B L D'],'Asthama':['Terbutaline','B L D'],'Cardiac arrest':['Adrenaline','B 0 D'],'Malaria':['Doxycyline','B L D'],'Anaemia':['Hydroxyurea','B 0 D'],'Pneumonia':['Ibuprofen','B 0 D'],'Arthritis':['Lubrijoint 750','B 0 D'],'Depression':['Sleeping Pills','B L D'],'Food poisoning':['Norflox','B 0 D'],'Migraine':['Crocin','B 0 D'],'Insomnia':['Sleeping Pills','B 0 D']} {'Influenza':'Relenza','Swine Flu':'Symmetrel','Cholera':'Ciprofloxacin','Typhoid':'Azithromycin','Sunstroke':'Barbiturates','Common cold':'Ibuprufen','Whooping Cough':'Erthromycin','Gastroentritis':'Gelusil','Conjunctivitus':'Romycin','Dehydration':'ORS','Asthama':'Terbutaline','Cardiac arrest':'Adrenaline','Malaria':'Doxycyline','Anaemia':'Hydroxyurea','Pneumonia':'Ibuprofen','Arthritis':'Lubrijoint 750','Depression':'Sleeping Pills','Food poisoning':'Norflox','Migraine':'Crocin','Insomnia':'Sleeping Pills'} dict1={'Influenza':['Relenza','After Breakfast 0 After Dinner'],'Swine Flu':['Symmetrel','After Breakfast After Lunch After Dinner'],'Cholera':['Ciprofloxacin','After Breakfast 0 After Dinner'],'Typhoid':['Azithromycin','After Breakfast After Lunch After Dinner'],'Sunstroke':['After Breakfastarbiturates','0 0 After Dinner'],'Common cold':['Ibuprufen','After Breakfast 0 After Dinner'],'Whooping Cough':['Erthromycin','After Breakfast 0 After Dinner'],'Gastroentritis':['Gelusil','After Breakfast 0 After Dinner'],'Conjunctivitus':['Romycin','After Breakfast 0 After Dinner'],'Dehydration':['ORS','After Breakfast After Lunch After Dinner'],'Asthama':['Terbutaline','After Breakfast After Lunch After Dinner'],'Cardiac arrest':['Adrenaline','After Breakfast 0 After Dinner'],'Malaria':['Doxycyline','B After Lunch After Dinner'],'Anaemia':['Hydroxyurea','After Breakfast 0 After Dinner'],'Pneumonia':['Ibuprofen','After Breakfast 0 After Dinner'],'Arthritis':['Lubrijoint 750','After Breakfast 0 After Dinner'],'Depression':['Sleeping Pills','After Breakfast After Lunch After Dinner'],'Food poisoning':['Norflox','After Breakfast 0 After Dinner'],'Migraine':['Crocin','After Breakfast 0 After Dinner'],'Insomnia':['Sleeping Pills','After Breakfast 0 After Dinner']}
''' Created on 2016年1月21日 @author: Darren ''' def countGreater(nums): def sort(enum): half = len(enum) // 2 if half: left, right = sort(enum[:half]), sort(enum[half:]) for i in range(len(enum))[::-1]: if not right or left and left[-1][1] < right[-1][1]: smaller[left[-1][0]] += len(right) enum[i] = left.pop() else: enum[i] = right.pop() return enum smaller = [0] * len(nums) sort(list(enumerate(nums))) return smaller # Complete the function below. def countGreaterNumbers( a, b): d={} for num in a: if num not in d: d[num]=0 d[num]+=1 sortedKey=sorted(d.keys(),reverse=True) print(d) print(sortedKey) preValue=0 for index in range(len(sortedKey)): temp=d[sortedKey[index]] if index==0: d[sortedKey[index]]=0 else: d[sortedKey[index]]=d[sortedKey[index-1]]+preValue preValue=temp print(d) res=[] for num in b: res.append(d[a[num-1]]) return res a=[3,4,1,2,4,6] b=[1,2,3,4,5,6] print(countGreaterNumbers(a,b))
""" The Program receives from the USER a university EVALUATION in LETTERS (for example: A+, C-, F, etc.) and returns (displaying it) the corresponding evaluation in POINTS. """ # START Definition of FUNCTIONS def letterGradeValida(letter): if len(letter) == 1: if (65 <= ord(letter[0].upper()) <= 68) or (letter[0].upper() == "F"): return True elif len(letter) == 2: if (65 <= ord(letter[0].upper()) <= 68): if (letter[1] == "+") or (letter[1] == "-"): return True return False def letterGradeToPoints(letter): letterGrade = {"A+": 4.0, "A": 4.0, "A-": 3.7, "B+": 3.3, "B": 3.0, "B-": 2.7, "C+": 2.3, "C": 2.0, "C-": 1.7, "D+": 1.3, "D": 1.0, "F": 0} return letterGrade.get(letter.upper()) # END Definition of FUNCTIONS # Acquisition and Control of the DATA entered by the USER letter = input("Enter the LETTER GRADE (A, A+, A-, etc): ") letterGradeValidated = letterGradeValida(letter) while not(letterGradeValidated): print("Incorrect entry. Try again.") letter = input("Enter the LETTER GRADE (A, A+, A-, etc): ") letterGradeValidated = letterGradeValida(letter) # Identification LETTER GRADE -> GRADE POINTS gradePoints = letterGradeToPoints(letter) # Displaying the RESULTS print("The GRADE POINTS of the letter grade \"" + letter.upper() + "\" is " + str(gradePoints))
def solve(captcha, step): result = 0 for i in range(len(captcha)): if captcha[i] == captcha[(i + step) % len(captcha)]: result += int(captcha[i]) return result if __name__ == '__main__': solve_part1 = lambda captcha: solve(captcha, 1) solve_part2 = lambda captcha: solve(captcha, len(captcha) // 2) with open('day1.in') as file: captcha = file.read() print(f'Solution to Part 1: {solve_part1(captcha)}') print(f'Solution to Part 2: {solve_part2(captcha)}')
print ('{0:.3f}'.format(1.0/3)) print('{0} / {1} = {2:.3f}'.format(3, 4,3/4 )) # fill with underscores (_) with the text centered # (^) to 11 width '___hello___' print ('{0:_^9}'.format('hello')) def variable(name=''): print('{0:*^12}'.format(name)) variable() print('{0:*^12}'.format('sendra')) variable() # keyword-based print ('{name} read {book} now.'.format(name='My Lovely Friend Sendra', book='A Byte of Python'))
INH = "Inherent" # The 'address' is inherent in the opcode. e.g. ABX INT = "Interregister" # An pseudo-addressing for an immediate operand which specified registers for the EXG and TFR instructions IMM = "Immediate" # Operand immediately follows the opcode. A literal. Could be 8-bit (LDA), 16-bit (LDD), or 32-bit (LDQ) DIR = "PageDirect" # An 8-bit offset pointer from the base of the direct page, as defined by the DP register. Also known as just 'Direct'. IDX = "Indexed" # Relative to the address in a base register (an index register or stack pointer) EXT = "ExtendedDirect" # A 16-bit pointer to a memory location. Also known as just 'Extended'. REL8 = "Relative8 8-bit" # Program counter relative REL16 = "Relative8 16-bit" # Program counter relative # What about what Leventhal calls 'Register Addressing'. e.g. EXG X,U
"""Question 3: Accept string from a user and display only those characters which are present at an even index number.""" def evenIndexNumber(palabra): print("Printing only even index chars") for i in range(0, len(palabra), 2): print("index[", i, "]", palabra[i:i+1]) word=input("Enter String ") print("Original String is", word) evenIndexNumber(word)
''' Given a number A. Find the fatorial of the number. Problem Constraints 1 <= A <= 100 ''' def factorial(A: int) -> int: if A <= 1: return 1 return (A * factorial(A-1)) if __name__ == "__main__": A = 3 print(factorial(A))
i = 125874 while True: if sorted(str(i)) == sorted(str(i * 2)) == sorted(str(i * 3)) == sorted(str(i * 4)) == sorted(str(i * 5)) == sorted(str(i * 6)): break else: i += 1 print(i)
#!/usr/bin/env python3 a = ["uno", "dos", "tres"] b = [f"{i:#04d} {e}" for i,e in enumerate(a)] print(b)
def test_app_is_created(app): assert app.name == 'care_api.app' def test_request_returns_404(client): assert client.get('/url_not_found').status_code == 404
def pi_nks(limit: int) -> float: pi: float = 3.0 s: int = 1 for i in range(2, limit, 2): pi += (s*4/(i*(i+1)*(i+2))) s = s*(-1) return pi def pi_gls(limit: int) -> float: pi: float = 0.0 s: int = 1 for i in range(1, limit, 2): pi += (s*(4/i)) s = s*(-1) return pi if __name__ == "__main__": LIMIT: int = 100 print(f"NKS: {pi_nks(limit=LIMIT):.13f}") print(f"GLS: {pi_gls(limit=LIMIT):.13f}")
# # Script for converting collected NR data into # the format for comparison with the simulations # def clean_and_save(file1, file2, cx, cy, ech): ''' Remove rows with character ech from the data in file1 column cy and corresponding rows in cx, then save to file2. Column numbering starts with 0. ''' with open(file1, 'r') as fin, open(file2, 'w') as fout: # Skip the header next(fin) for line in fin: temp = line.strip().split() if temp[cy] == ech: continue else: fout.write((' ').join([temp[cx], temp[cy], '\n'])) # Input data_file = 'input_data/New_Rochelle_covid_data.txt' no_entry_mark = '?' # Number of active cases clean_and_save(data_file, 'output/real_active_w_time.txt', 1, 2, no_entry_mark) # Total number of cases clean_and_save(data_file, 'output/real_tot_cases_w_time.txt', 1, 3, no_entry_mark) # Number of deaths in the county clean_and_save(data_file, 'output/real_tot_deaths_county_w_time.txt', 1, 4, no_entry_mark)
# Set to 1 or 2 to show what we send and receive from the SMTP server SMTP_DEBUG = 0 SMTP_HOST = '' SMTP_PORT = 465 SMTP_FROM_ADDRESSES = () SMTP_TO_ADDRESS = '' # these two can also be set by the environment variables with the same name SMTP_USERNAME = '' SMTP_PASSWORD = '' IMAP_HOSTNAME = '' IMAP_USERNAME = '' IMAP_PASSWORD = '' IMAP_LIST_FOLDER = 'INBOX' CHECK_ACCEPT_AGE_SECONDS = 3600
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # CAM签名/鉴权错误。 AUTHFAILURE = 'AuthFailure' # 操作失败。 FAILEDOPERATION = 'FailedOperation' # 内部错误。 INTERNALERROR = 'InternalError' # 创建私有域失败。 INTERNALERROR_CREATEPRIVATEZONE = 'InternalError.CreatePrivateZone' # 创建私有域记录失败。 INTERNALERROR_CREATEPRIVATEZONERECORD = 'InternalError.CreatePrivateZoneRecord' # 数据库错误。 INTERNALERROR_DBERROR = 'InternalError.DbError' # 删除私有域记录失败。 INTERNALERROR_DELETEPRIVATEZONERECORD = 'InternalError.DeletePrivateZoneRecord' # 查询vpc私有解析状态失败。 INTERNALERROR_DESCRIBEINTERNALENDPOINTDNSSTATUS = 'InternalError.DescribeInternalEndpointDnsStatus' # 查询私有域列表失败。 INTERNALERROR_DESCRIBEPRIVATEZONELIST = 'InternalError.DescribePrivateZoneList' # 查询私有域记录列表失败。 INTERNALERROR_DESCRIBEPRIVATEZONERECORDLIST = 'InternalError.DescribePrivateZoneRecordList' # 查询开白vpc列表失败。 INTERNALERROR_DESCRIBEPRIVATEZONESERVICELIST = 'InternalError.DescribePrivateZoneServiceList' # 目标冲突。 INTERNALERROR_ERRCONFLICT = 'InternalError.ErrConflict' # 目标不存在。 INTERNALERROR_ERRNOTEXIST = 'InternalError.ErrNotExist' # 鉴权失败。 INTERNALERROR_ERRUNAUTHORIZED = 'InternalError.ErrUnauthorized' # 资源已存在。 INTERNALERROR_ERRORCONFLICT = 'InternalError.ErrorConflict' # 资源超过配额。 INTERNALERROR_ERROROVERLIMIT = 'InternalError.ErrorOverLimit' # Tcr实例内部错误。 INTERNALERROR_ERRORTCRINTERNAL = 'InternalError.ErrorTcrInternal' # Tcr实例请求无效的Hearder类型。 INTERNALERROR_ERRORTCRINVALIDMEDIATYPE = 'InternalError.ErrorTcrInvalidMediaType' # Tcr实例资源冲突。 INTERNALERROR_ERRORTCRRESOURCECONFLICT = 'InternalError.ErrorTcrResourceConflict' # 没有Tcr操作权限。 INTERNALERROR_ERRORTCRUNAUTHORIZED = 'InternalError.ErrorTcrUnauthorized' # 修改vpc与私有域关联关系失败。 INTERNALERROR_MODIFYPRIVATEZONEVPC = 'InternalError.ModifyPrivateZoneVpc' # 未知错误。 INTERNALERROR_UNKNOWN = 'InternalError.Unknown' # 参数错误。 INVALIDPARAMETER = 'InvalidParameter' # 用户请求中的信息与其namespace不匹配。 INVALIDPARAMETER_ERRNSMISMATCH = 'InvalidParameter.ErrNSMisMatch' # 命名空间名称已经存在。 INVALIDPARAMETER_ERRNAMESPACEEXIST = 'InvalidParameter.ErrNamespaceExist' # 命名空间已被占用。 INVALIDPARAMETER_ERRNAMESPACERESERVED = 'InvalidParameter.ErrNamespaceReserved' # 无效的参数,仓库已存在。 INVALIDPARAMETER_ERRREPOEXIST = 'InvalidParameter.ErrRepoExist' # 触发器名称已存在。 INVALIDPARAMETER_ERRTRIGGEREXIST = 'InvalidParameter.ErrTriggerExist' # 用户已经存在。 INVALIDPARAMETER_ERRUSEREXIST = 'InvalidParameter.ErrUserExist' # 实例名称已存在。 INVALIDPARAMETER_ERRORNAMEEXISTS = 'InvalidParameter.ErrorNameExists' # 实例名称非法。 INVALIDPARAMETER_ERRORNAMEILLEGAL = 'InvalidParameter.ErrorNameIllegal' # 实例名称已保留。 INVALIDPARAMETER_ERRORNAMERESERVED = 'InvalidParameter.ErrorNameReserved' # 实例名称非法,格式不正确或者已保留。 INVALIDPARAMETER_ERRORREGISTRYNAME = 'InvalidParameter.ErrorRegistryName' # 云标签超过10个上线。 INVALIDPARAMETER_ERRORTAGOVERLIMIT = 'InvalidParameter.ErrorTagOverLimit' # 无效的TCR请求。 INVALIDPARAMETER_ERRORTCRINVALIDPARAMETER = 'InvalidParameter.ErrorTcrInvalidParameter' # 该地域不支持创建实例。 INVALIDPARAMETER_UNSUPPORTEDREGION = 'InvalidParameter.UnsupportedRegion' # 用户命名空间达到配额。 LIMITEXCEEDED_ERRNAMESPACEMAXLIMIT = 'LimitExceeded.ErrNamespaceMaxLimit' # 用户仓库已经达到最大配额。 LIMITEXCEEDED_ERRREPOMAXLIMIT = 'LimitExceeded.ErrRepoMaxLimit' # 触发器达到配额。 LIMITEXCEEDED_ERRTRIGGERMAXLIMIT = 'LimitExceeded.ErrTriggerMaxLimit' # 缺少参数错误。 MISSINGPARAMETER = 'MissingParameter' # 缺少参数。 MISSINGPARAMETER_MISSINGPARAMETER = 'MissingParameter.MissingParameter' # 操作被拒绝。 OPERATIONDENIED = 'OperationDenied' # 实例状态异常。 RESOURCEINSUFFICIENT_ERRORINSTANCENOTRUNNING = 'ResourceInsufficient.ErrorInstanceNotRunning' # Vpc dsn解析状态异常或未删除。 RESOURCEINSUFFICIENT_ERRORVPCDNSSTATUS = 'ResourceInsufficient.ErrorVpcDnsStatus' # 资源不存在。 RESOURCENOTFOUND = 'ResourceNotFound' # 用户没有创建命名空间。 RESOURCENOTFOUND_ERRNONAMESPACE = 'ResourceNotFound.ErrNoNamespace' # 仓库不存在。 RESOURCENOTFOUND_ERRNOREPO = 'ResourceNotFound.ErrNoRepo' # tag不存在。 RESOURCENOTFOUND_ERRNOTAG = 'ResourceNotFound.ErrNoTag' # 触发器不存在。 RESOURCENOTFOUND_ERRNOTRIGGER = 'ResourceNotFound.ErrNoTrigger' # 用户不存在(未注册)。 RESOURCENOTFOUND_ERRNOUSER = 'ResourceNotFound.ErrNoUser' # Tcr实例中的资源未找到。 RESOURCENOTFOUND_TCRRESOURCENOTFOUND = 'ResourceNotFound.TcrResourceNotFound' # 未授权操作。 UNAUTHORIZEDOPERATION = 'UnauthorizedOperation' # 未知参数错误。 UNKNOWNPARAMETER = 'UnknownParameter' # 操作不支持。 UNSUPPORTEDOPERATION = 'UnsupportedOperation'
""" Messages dictionary ================== This module takes care of logging, using levels ERROR|DEBUG. Other levels could be added in the future This is to make it easier to translate the language of this tool and to centralize the logging behavior > Ignacio Tamayo, TSP, 2016 > Version 1.4 > Date: Sept 2016 """ """ ..licence:: vIOS (vCDN Infrastructure Optimization Simulator) Copyright (c) 2016 Telecom SudParis - RST Department 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. """ AdminPageTitle = 'vIOSimulator - DB Management' Errors_updating_POPs = "There were some errors while updating the POPs" Errors_updating_Metrics = "There were some errors while updating the Metrics from the POPs" Error_building_Topologie = "There were some errors while building the Topologie graph" Errors_random_links = "There were some errors while creating random Links" ERROR_creating_Demands = "ERROR creating random demands" ERROR_consuming_Demands = "ERROR calculating capacity consumed by demands" Exception_drawing_Topologie = "Exception ocurred while drawing the Topologie" ERROR_creating_Demands = "ERROR creating random demands" ERROR_optimizing = "ERROR while optimizing" Updated_Topo_Random = "Topologie updated with random links" Updated_Graph = "Updated graph" Created_Demands = "Demands generated randomly" Updated_POPs = "Information updated from OpenStack Controllers" Optimized = "Optimal migrations calculated" Missing_Elements_to_Build_Model = "Missing elements to build an OMAC/HMAC Model (Locations and Network Links)" NoPOPs = "There are no POPs found in the DB" NovCDNs = "There are no vCDNs found in the DB" POP_not_found = "POP not found in DB" vCDN_not_found = "vCDN not found in DB" NoDemands = "There are no demands registered in the DB" NoNetworkLinks = "There are no Network Links registered in the DB" Error_executing = "Error executing the selected operations" Executing = "Executing the operations in background" QoE_reset = "QoE Value was reset, no change was done to the Demands" Adjusted_Demands = "The Demands' BW were adjusted for the QoE value" ERROR_adjusting_Demands = "Unable to adjust the Demands' BW for the QoE value" ### ### Optimizer.py ### Create_Random_Topologie = "Creating a Random Topologie" Consuming_Demands = "Consuming Demands BW on topologie capacity" Random_Graph_Created = "A Random Topologie Graph has been created" Updated_NetworkLinks = "The Network Links have been replaced by the random topologie" Updated_ClientLocations = "The Client Groups have been distributed in the new topologie" Exception_updating_Infrastructure = "Exception ocurred while updating the Infrastructure Topologie" Exception_updating_Demand = "Exception ocurred while creating random Demands" Exception_optimizing = "Exception ocurred while executing the Optimization" CreatingRandomDemands_D_probaF_amplitudeD = "Creating random %d Demands, p=%f, amplitude=%d " Created_D_Demands = "Created %d random demands " Updated__D_OpenStack_Metrics = "Updated OpenStack Metrics for %d instances" Invalid_Demand_Client_S_vCDN_S_POP_S = "Invalid demand from ClientGroup '%s' for vCDN '%s' at POP '%s' " No_OMAC_Optimize = "Unable to perform OMAC optimization" Deleted_Demands = "Demands deleted from the DB" Deleted_Migrations = "Migrations deleted from the DB" Updated_Demands_QosBW = "Updated the demanded QoSBW based on vCDN information" HMAC_optimized = "Finished running HMAC" OMAC_optimized = "Created OMAC CPLEX data file" Optimized_F = "Optimization executed in %f seconds" Exception_Building_Model = "Exception ocurred while building the OMAC/HMAC Model" Updated_MigrationCost_MigrationId_D = "Migration cost updated for Migration %d" Create_Random_Demands = "Creating Random Demands" Updating_OpenStack = "Updating the OpenStack POP information" Updating_OpenStack_Metrics = "Updating the OpenStack Metrics information for all Tenants" Connected_POP_S = "Connected to POP '%s'" Optimizating = "Running the Optimization algorithm" Exception_Model_POPS = "Exception ocurred while placing the POPs in the OMAC/HMAC Model" NoClients = "There are no ClientGroups found in the DB" Exception_Model_Clients = "Exception ocurred while placing the Clients in the OMAC/HMAC Model" Exception_updating_Topologie = "Exception ocurred while updating the Topologie" Exception_Metrics_Tenant_S_POP_S = "Unable to get Metrics for Tenant %s in POP %s " Created_Hypervisor_S_POP_S = " Created hypervisor '%s' for POP '%s' " Created_Flavor_S_POP_S = " Created flavor '%s' for POP '%s' " Updated_Hypervisor_S_POP_S = " Updated hypervisor %s for POP %s" Updated_Flavor_S_POP_S = " Updated flavor %s for Pop %s" Exception_Update_Hypervisor_S_POP_S = "Exception ocurred while updating the hypervisor '%s' on POP '%s'" Exception_Update_vCDN_S_POP_S = "Exception ocurred while updating the vCDN '%s' on POP '%s'" Exception_Update_Flavor_S_POP_S = "Exception ocurred while updating the flavors '%s' on POP '%s' " Getting_Metric_Pop_D_tenant_S = "Obtaining metrics from POP '%s' for vCDN '%s'" NoConnect_Pop_S = "Unable to connect and login to POP '%s' " Exception_Simulating = "Exception occured while running the simulation" Updated_Pop_S = "Updated information from POP '%s'" Updated_Tenants_Pop_S = "Updated Tenants instances from POP '%s' " Updated_Metrics_Pop_S = "Updated Tenants metrics from POP '%s'" Updated_Metric_Instance_D = "Updated Metrics of Instance ID %s" Added_Metric_Instance_D = "Added Metrics for Instance ID %s" Found_Instance_S_at_POP_S_LimitsInstances_D = "Found instance of %s at Pop %s with %d VMs " Deleted_Instance_S_at_POP_S = "Deleted instance of %s at Pop %s " Added_Instance_S_at_POP_S = "Added instance of %s at Pop %s " Updated_Instance_S_at_POP_S = "Updated instance of %s at Pop %s" NoModel = "There is no Model to work with" NoInstances = "No Instances were found" NoMigrations = "No Migrations were found" NoRedirectsSelected = "No Redirections selected" NoMigrationsSelected = "No Migrations selected" NoInstantiationsSelected = "No Instantiations selected" ConnectDB_S = "Connecting to DB with url '%s' " Simulate_Migration_vCDN_S_from_POP_S_to_POP_S = "Simulate Migration of vcdn '%s' from POP '%s' to POP '%s'" Simulate_Redirection_vCDN_S_from_POP_S_to_POP_S = "Simulate Redirection of vcdn '%s' from POP '%s' to POP '%s'" Simulate_Instantiation_vCDN_S_on_POP_S = "Simulate Instantiation of vcdn '%s' on POP '%s' " Simulating_Instantiations = "Simulating the Instantiations" Simulated_D_Instantiations = "Simulated %d Instantiations in the Model" Simulating_Redirections = "Simulating the Redirections" Simulated_D_Redirections = "Simulated %d Redirections in the Model" Simulating_Migrations = "Simulating the Migrations" Simulated_D_Migrations = "Simulated %d Migrations in the Model" Adjusting_Instances_Demands = "Adjusting the Instances and Demands to the selected changes" Adjusting_Model = "Adjusting the Model's Graph to reflect the simulated Instances" Running_Demands = "Running the simulated Demands" Deleted_Redirections = "Deleted the previous Redirections" Executing_D_Migrations = "Executing %d Migrations" Executing_D_Instantiations = "Executing %d Instantiations" Migrating_vCDN_S_fromPOP_S_toPOP_S = "Migrating vCDN '%s' from POP '%s' to POP '%s'" Migrating_Server_S_vCDN_S_POP_S = "Migrating Server '%s' of vCDN '%s 'from POP '%s'" Unable_Thread = "Unable to create Thread for the operation" NoInstanceForvCDN = "There are no Instances of the vCDN to clone" NoInstanceForvCDN_S = "There are no Instances of vCDN '%s' to clone from" Created_Snapshot_Server_S_POP_S = "Created an Snapshot of Server '%s' in POP '%s'" Created_Server_S_vCDN_S_POP_S = "Created server '%s' of vCDN '%s' in POP '%s' " Deleted_Server_S_vCDN_S_POP_S = "Deleted server '%s' of vCDN '%s' in POP '%s' " QuotaLimit = "Servers quota full, not allowed to start more servers." NotDeleted_Server_S_vCDN_S_POP_S = "Server '%s' of vCDN '%s' in POP '%s' was not deleted after Migration " NotResumed_Server_S_POP_S = "Server '%s' in POP '%s' was not resumed after snapshpt " downloadedImageFile_S = "Downloaded the IMG file in '%s' " uploadedImageFile_S = "Uploaded the IMG file in '%s' " Exception_Cloning_Server_S_POP_S_POP_S = "Exception occured when cloning server '%s' from POP '%s' to POP '%s'" Error_migrating = "Unable to gather Migrations Information to execute" Error_instantiating = "Unable to gather Instantiation Information to execute" Invalid_QoE_Value = "Invalid QoE value" Invalid_QoE_Model = "Invalid QoE model" QoE_outOfModel = "The QoE value is out of the Model boundaries" Updating_Demand_BW_QoE_F = "Updating the Demands BW to match a QoE = %f " Updating_Demand_BW_x_F = "Updating the Demands BW by a factor of %f " Updated_Demand_BW = "Updated the Demands BW " ### ### OptimizationModels.py ### Building_Model = "Building a new Model" Added_Node_S = "Added node %s " Added_Link_S_to_S_of_D = "Added link from %s to %s, %d Mbps" Added_Pop_S_in_S = "Added pop %s to node %s" Added_Client_S_in_S = "Added clientGroup %s to node %s" Draw_File_S = "Graph drawn to file %s" Client_S_requests_S_from_S_BW_D = "Demand from ClientGroup at %s requesting vCDN %s from Pop %s with BW %d" Migration_to_POP_S = "Migration to Pop %s" NeedeBW_D_more_LinkBW_D = "The needed BW %d Mbps is more than the available link %d Mbps" Built_Model_D_locations_D_links = "A new model was built with %d locations and %d links " Added_D_POPs = "Added %d POPs to the Model" Added_D_Clients = "Added %d ClientGroups to the Model" RandomGraph_locationsD_maxCapaD = "Creating random Graph for %d locations with maxCapacity=%d " RandomGraph_locationsD = "Created random Graph of %d nodes" Migration_condition_BWNeeded_D_GomuriCap_D_PopCap_PopCanHost_S = "Migration condition: DemandedBW=%d LinkBW=%d PopBW=%d PopCanHost=%s" ShortestPath_S = "The SPT for this demand is '%s' " Migrate_vCDN_S_srcPOP_S_dstPOP_S = "Migrate vCDN '%s' from POP '%s' to POP '%s' " Migrate_vCDN_S_srcPOP_S_dstPOP_S_RedirectionBW = "Migrating vCDN '%s' from POP '%s' to POP '%s' would cause Redirections that saturate the link " HMAC_optimized_D_migrations_D_invalidDemands = "HMAC optimization determined %d migrations and %d invalid demands" ClientLocation_S_requests_S_from_S_TotalBW_F = "Clients located in '%s' request vCDN '%s' from POP '%s', needing %.2f Mbps of BW" Migration_path_D_Hops_F_BW = "Migration path of %d hops and %.2f Mbps minimal BW" Migration_Condition_Hold_B_NetCapacity_D_Mbps = "The Migration was rejected because HoldvCDN = %s and Remaining BW in POP is %d Mbps" Scale_Condition_NetCapacity_D_Mbps = "The Scaling was rejected because Remaining BW in POP is %d Mbps" Migration_check_PopSrc_S_PopDts_S = "Checking possible migration from POP '%s' to POP '%s'" Graph_Topologie_Consume_Demands = "Consuming a Topologie Graph with a set of demands" Graph_Capacity_Consume_Demands = "Consuming a Capacity Graph with a set of demands" Graph_Consume_D_Demands = "Consumed %d Demands from the Graph" Exception_Consuming_Demand_D_Graph = "Exception while consuming Demand %d on a Topologie Graph" Exception_Removing_Demand_D_Graph = "Exception while returning Demand %d on a Topologie Graph" Exception_Migrating_vCDN_S_PopSrc_S_PopDts_S = "Exception occured while calculating migration of vCDN '%s' from POP '%s' to POP '%s'" Redirect_Demand_Client_S_vCDN_S_srcPOP_S_dstPOP_S = "Scale-out and redirect Demands of clientGroup '%s' for vCDN '%s' from POP '%s' to POP '%s'" Demand_id_D_isValid = "Demand %d has a valid Instace, unable to simulate an Instantiation" Redirect_D_invalid = "Redirect %d is invalid; could be a Migration" Errors_simulating = "Some error occured while executing the simulation" Removing_Simulated_Redirects = "Removing the Demands from the previous path before redirection" Consuming_Simulated_Redirects = "Adding the Demands on the simulated path after redirection" Exception_Consuming_Fake_Demand = "Exception occured while Consuming a simulated Demand" ClientLocation_S_requests_from_S_TotalBW_F = "Consuming fake Demand of ClientGroup at '%s' to POP '%s' with BW '%.2f'" Deleted_Fake_Instace_POP_S_vCDN_S = "Deleting Fake Instance in POP '%s' of vCDN '%s'" Added_Fake_Instace_POP_S_vCDN_S = "Adding Fake Instance in POP '%s' of vCDN '%s'" Update_Fake_Demand_fromPOP_S_toPOP_S = "Update of Demand from POP '%s' to POP '%s'" Unable_Write_File_S = "Unable to write the file '%s'" OMAC_DAT_S = "OMAC .dat file was created in '%s'" ### ### OpenStackConnection.py ### AuthOS_url_S_user_s_tenant_S = "Authenticating to URL %s as User '%s' of Tenant '%s'" AuthOS_region_S = "Authenticating to Region '%s'" Exception_Nova_url_S_region_S_user_S_tenant_S = "Unable to authenticate to Nova Service via URL %s in Region '%s' as User '%s' of Tenant '%s'" Exception_Ceilometer_url_S_region_S_user_S_tenant_S = "Unable to authenticate to Ceilometer Service via URL %s in Region '%s' as User '%s' of Tenant '%s'" Exception_Glance_url_S_region_S_user_S_tenant_S = "Unable to authenticate to Glance Service via URL %s in Region '%s' as User '%s' of Tenant '%s'" LastSample_S_at_S = "Last sample of meter '%s' at '%s' " CollectSamples_S_since_S = "Collecting stats of meter '%s' since '%s' " Meter_Stats_minD_maxD_avgD = "Values collected are: Min=%d Max=%d Avg=%d " NoMetrics_Meter_S = "No Metric collected for meter '%s' " Authenticated = "Authenticated" Migrating_Instance_vCDN_S_POP_S_POP_S = "Migrating Instance of vCDN %s from POP %s to POP %s" Instantiating_Instance_vCDN_S_POP_S = "Instantiating vCDN %s on POP %s" Instantiation_ended_Instance_vCDN_S_POP_S = "Instantiation of vCDN %s on POP %s has finished" Migration_ended_Instance_vCDN_S_POP_S_POP_S = "Migration of vCDN %s from POP %s to POP %s has finished" Exception_Migrating_Server_S_POP_S_POP_S = "Exception occured while migrating a Server Id %s from POP %s to POP %s" NoConnect_Pops = "Unable to connect to the POPs to perform the Migration" NoDownload_ImgFile_S = "Unable to download the image file %s" NoUpload_ImgFile_S = "Unable to upload the image file %s" NoWritable_S = "The location %s is not writable" NoServerCreated_vCDN_S_POP_S = "Unable to start a new Server in POP '%s' for vCDN '%s'" Invalid_Server_Parameters_S = "Invalid parameters for creating a Server: %s" ServerId_S_NotFound = "Unable to find a server with id = '%s'" ImageId_S_NotFound = "Unable to find an image with id = '%s'"
#Si se nombra un método de esta manera: "__init__", no será un método regular, será un constructor. #Si una clase tiene un constructor, este se invoca automática e implícitamente # cuando se instancia el objeto de la clase. #El constructor: #Esta obligado a tener el parámetro "self" (se configura automáticamente). #Pudiera (pero no necesariamente) tener mas parámetros que solo "self"; si esto sucede, # la forma en que se usa el nombre de la clase para crear el objeto debe tener la definición "__init__". #Se puede utilizar para configurar el objeto, es decir, inicializa adecuadamente su estado interno, # crea variables de instancia, crea instancias de cualquier otro objeto si es necesario, etc. #No puede retornar un valor, ya que está diseñado para devolver un objeto recién creado y nada más. #No se puede invocar directamente desde el objeto o desde dentro de la clase class conClase: def __init__(self, valor): self.var = valor obj1 = conClase("objeto") print(obj1.var) print() #Como "__init__" es un método, y un método es una función, # puedes hacer los mismos trucos con constructores y métodos que con las funciones ordinarias. #Definir un constructor con un valor de argumento predeterminado: class conClase2: def __init__(self, valor = None): self.var = valor obj2 = conClase2("objeto") obj3 = conClase2() print(obj2.var) print(obj3.var) print()
class Memorability_Prediction: def mem_calculation(frame1): #print ("Inside mem_calculation function") start_time1 = time.time() resized_image = caffe.io.resize_image(frame1,[227,227]) net1.blobs['data'].data[...] = transformer1.preprocess('data', resized_image) value = net1.forward() value = value['fc8-euclidean'] end_time1 = time.time() execution_time1 = end_time1 - start_time1 #print ("*********** \t Execution Time in Memobarility = ", execution_time1, " secs \t***********") return value[0][0]
# # PySNMP MIB module ZYXEL-OAM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-OAM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:45:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") ModuleIdentity, NotificationType, Counter64, TimeTicks, iso, Counter32, Gauge32, ObjectIdentity, IpAddress, MibIdentifier, Unsigned32, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "NotificationType", "Counter64", "TimeTicks", "iso", "Counter32", "Gauge32", "ObjectIdentity", "IpAddress", "MibIdentifier", "Unsigned32", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt") zyxelOam = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56)) if mibBuilder.loadTexts: zyxelOam.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelOam.setOrganization('Enterprise Solution ZyXEL') zyxelOamSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1)) zyOamState = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyOamState.setStatus('current') zyxelOamPortTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2), ) if mibBuilder.loadTexts: zyxelOamPortTable.setStatus('current') zyxelOamPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: zyxelOamPortEntry.setStatus('current') zyOamPortFunctionsSupported = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 56, 1, 2, 1, 1), Bits().clone(namedValues=NamedValues(("unidirectionalSupport", 0), ("loopbackSupport", 1), ("eventSupport", 2), ("variableSupport", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyOamPortFunctionsSupported.setStatus('current') mibBuilder.exportSymbols("ZYXEL-OAM-MIB", zyxelOam=zyxelOam, zyOamState=zyOamState, PYSNMP_MODULE_ID=zyxelOam, zyxelOamPortEntry=zyxelOamPortEntry, zyxelOamSetup=zyxelOamSetup, zyxelOamPortTable=zyxelOamPortTable, zyOamPortFunctionsSupported=zyOamPortFunctionsSupported)
def to_xyz(self): """Performs the corrdinate change and stores the resulting field in a VectorField object. Parameters ---------- self : VectorField a VectorField object Returns ------- a VectorField object """ # Dynamic import to avoid loop module = __import__("SciDataTool.Classes.VectorField", fromlist=["VectorField"]) VectorField = getattr(module, "VectorField") if "comp_x" in self.components or "comp_y" in self.components: return self.copy() else: # Coordinate transform arg_list = [ axis.name if axis.name in ["freqs", "wavenumber"] else axis.name + "[smallestperiod]" for axis in self.components["radial"].axes ] result = self.get_xyz_along(*arg_list, is_squeeze=False) # Store in new VectorField comp_dict = dict() Comp_x = self.components["radial"].copy() Comp_x.name = ( self.components["radial"].name.lower().replace("radial ", "") + " along x-axis" ) Comp_x.symbol = self.components["radial"].symbol.replace("_r", "_x") Comp_x.values = result["comp_x"] comp_dict["comp_x"] = Comp_x Comp_y = self.components["radial"].copy() Comp_y.name = ( self.components["radial"].name.lower().replace("radial ", "") + " along y-axis" ) Comp_y.symbol = self.components["radial"].symbol.replace("_r", "_y") Comp_y.values = result["comp_y"] comp_dict["comp_y"] = Comp_y if "axial" in self.components: Comp_z = self.components["axial"].copy() comp_dict["comp_z"] = Comp_z return VectorField(name=self.name, symbol=self.symbol, components=comp_dict)
class ToolVariables: @classmethod def ExcheckUpdate(cls): cls.INTAG = "ExCheck" return cls
test = { 'name': 'q1_2', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> mean_based_estimator(np.array([1, 2, 3])) is not None True """, 'hidden': False, 'locked': False }, { 'code': r""" >>> int(np.round(mean_based_estimator(np.array([1, 2, 3])))) 4 """, 'hidden': False, 'locked': False } ], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest' } ] }
class ScheduleItem: def __init__(item, task): item.task = task item.start_time = None item.end_time = None item.child_start_time = None item.pred_task = None item.duration = task.duration item.total_effort = None item.who = '' class Schedule: def __init__(schedule, target, schedule_items, critical_path, items_by_resource): schedule.target = target if isinstance(target, ScheduleItem) else schedule_items[target.__qualname__] schedule.items = schedule_items schedule.critical_path = critical_path schedule.items_by_resource = items_by_resource schedule.duration = schedule.target.end_time schedule.outdir = None
#%% class Book: def __init__(self,author,name,pageNum): self.__author = author self.__name = name self.__pageNum = pageNum def getAuthor(self): return self.__author def getName(self): return self.__name def getPageNum(self): return self.__pageNum def __str__(self): return "Author is: " + self.__author + " book name: " + self.__name + " number of pages: " + str(self.__pageNum) def __len__(self): return self.__pageNum def __del__(self): print("The book {} has deleted!".format(self.__name)) x = Book("Jon Duckett","HTML & CSS",460) print(x) del x #%%
# --------------------------------------------------------------------------------------------- # Copyright (c) Akash Nag. All rights reserved. # Licensed under the MIT License. See LICENSE.md in the project root for license information. # --------------------------------------------------------------------------------------------- # This module implements the CursorPosition abstraction class CursorPosition: def __init__(self, y, x): self.y = y self.x = x # returns a string representation of the cursor position for the user def __str__(self): return "(" + str(self.y+1) + "," + str(self.x+1) + ")" # returns the string representation for internal use def __repr__(self): return "(" + str(self.y) + "," + str(self.x) + ")"
lista = [] mai = 0 men = 0 for c in range(0,5): lista.append( int(input(f'Digite um Valor para Posição {c}: '))) if c == 0: mai = men = lista[0] else: if lista[c] > mai: mai = lista[c] if lista[c] < men : men = lista[c] print('-='*30) print(f'Sua Lista é {lista}') print(f'O Maior Valoe é {mai} e o Menor Valor é {men}')
N = int(input()) M = int(input()) res = list() for x in range(N, M+1): cnt = 0 if x > 1: for i in range(2, x): if x % i == 0: cnt += 1 break if cnt == 0: res.append(x) if len(res) > 0: print(sum(res)) print(min(res)) else: print(-1)
# Application settings # Flask settings DEBUG = False # Flask-restplus settings RESTPLUS_MASK_SWAGGER = False SWAGGER_UI_DOC_EXPANSION = 'none' # API metadata API_TITLE = 'MAX Breast Cancer Mitosis Detector' API_DESC = 'Predict the probability of the input image containing mitosis.' API_VERSION = '0.1' # default model MODEL_NAME = 'MAX Breast Cancer Mitosis Detector' DEFAULT_MODEL_PATH = 'assets/deep_histopath_model.hdf5' MODEL_LICENSE = "Custom" # TODO - what are we going to release this as? MODEL_META_DATA = { 'id': '{}'.format(MODEL_NAME.lower()), 'name': '{} Keras Model'.format(MODEL_NAME), 'description': '{} Keras model trained on TUPAC16 data to detect mitosis'.format(MODEL_NAME), 'type': 'image_classification', 'license': '{}'.format(MODEL_LICENSE) }
# -*- coding: utf-8 -*- """ Created on Tue Aug 24 10:17:54 2021 @author: User """ #%% nombre = 'Naranja' cajones = 100 precio = 91.1 print(f'{nombre:>10s} {cajones:>10d} {precio:>10.2f}') #%% # Formato a diccionarios s = { 'nombre': 'Naranja', 'cajones': 100, 'precio': 91.1 } print('{nombre:>10s} {cajones:10d} {precio:10.2f}'.format_map(s)) #%% # El método format() print('{nombre:>10s} {cajones:10d} {precio:10.2f}'.format(nombre='Naranja', cajones=100, precio=91.1)) #%% print('{:10s} {:10d} {:10.2f}'.format('Naranja', 100, 91.1)) #%% # Formato estilo C print('The value is %d' % 3) #%% # Tiene la dificultad de que hay que contar posiciones y todas las variables van juntas al final. print('%5d %-5d %10d' % (3,4,5)) #%% # Ejercicio 3.12: Formato de números value = 42863.1 print(value) print(f'{value:>16.2f}') print(f'{value:<16.2f}') print(f'{value:*>16,.2f}') #%% print('%0.4f' % value) print('%16.2f' % value) #%% # podés simplemente asignarlo a una variable f = '%0.4f' % value print(f) #%%
def notas(* notas, sit = False): """ --> Recebe n notas de alunos e retorna um dicionário com Quantidade de notas, A maior nota, A menor nota, A média da turma e a situação. :param notas: Recebe n notas passadas na função, não recebe lista :param sit: Parametro opcional para mostrar a situação do aluno. :return: retorna um dicionário, total, maior, menor, média e situação (opcional) """ total = maior = menor = media = 0 dict_notas = dict() for x in notas: total += 1 if total == 1: maior = menor = x if x > maior: maior = x if x < menor: menor = x media += x media /= total dict_notas['total'] = total dict_notas['maior'] = maior dict_notas['menor'] = menor dict_notas['media'] = media if sit: if media < 5: dict_notas['situação'] = 'RUIM' elif media < 7: dict_notas['situação'] = 'RAZOÁVEL' else: dict_notas['situação'] = 'BOA' return dict_notas # Programa principal resp = notas(9.5, 9, 6.5, sit=True) print(resp) help(notas)
# # @lc app=leetcode id=1431 lang=python3 # # [1431] Kids With the Greatest Number of Candies # # @lc code=start class Solution: def kidsWithCandies(self, candies: List[int], extra_candies: int) -> List[bool]: max_candies = max(candies) return [i + extra_candies >= max_candies for i in candies] # @lc code=end
""" This module contains all files for a django deployment 'site'. When called via the manage.py command, this folder is used as regular django setup. """
''' Exercício Python 087: Aprimore o desafio anterior, mostrando no final: A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha. ''' matriz = [[0,0,0], [0,0,0], [0,0,0]] maior = somapar = terceira_coluna = 0 for l in range(0,3): for c in range(0,3): matriz[l][c] = int(input(f'Digite o número: [{l}, {c}]: ')) print('-'*30) for l in range(0,3): for c in range(0,3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2 == 0: somapar += matriz[l][c] if c == 2: terceira_coluna += matriz[l][2] if l == 1: maior = max(matriz[1]) print() print('-'*30) print(f'a) A soma dos valores pares é {somapar}') print(f'b) A soma dos valores da terceira coluna é: {terceira_coluna}') print(f'c) Maior valor da segunda linha: {maior}')
# -*- coding: utf-8 -*- """ This package implements various parameterisations of properties from the litterature with relevance in chemistry. """
def repeated_n_times(nums): # nums.length == 2 * n n = len(nums) // 2 for num in nums: if nums.count(num) == n: return num print(repeated_n_times([1, 2, 3, 3])) print(repeated_n_times([2, 1, 2, 5, 3, 2])) print(repeated_n_times([5, 1, 5, 2, 5, 3, 5, 4]))
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) # See: # https://docs.microsoft.com/en-us/windows/win32/eventlog/event-types # https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-reporteventa#parameters # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-even/1ed850f9-a1fe-4567-a371-02683c6ed3cb # # However, event viewer & the C api do not show the constants from above, but rather return these: # https://docs.microsoft.com/en-us/windows/win32/wes/eventmanifestschema-leveltype-complextype#remarks EVENT_TYPES = { 'success': 4, 'error': 2, 'warning': 3, 'information': 4, 'success audit': 4, 'failure audit': 2, }
# Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. user_input = int(input('Введите трехзначное число: ')) hundreds = user_input // 100 dozens = user_input % 100 // 10 units = user_input % 10 summary = hundreds + dozens + units multiplication = hundreds * dozens * units print(f'Результат суммирования: {summary}') print(f'Результат перемножения: {multiplication}')
@outputSchema('vals: {(val:chararray)}') def convert(the_input): # This converts the indeterminate number of vals into a bag. out = [] for map in the_input: out.append(map) return out
"""Settings for depicting LaTex figures""" class Figure: """Figure class for depicting HTML and LaTeX. :param path: The path to an image :type path: str :param title: The caption of the figure :param title: str :param label: The label of the label :param label: str """ def __init__(self, path: str, title: str, label: str) -> None: self.path: str = path self.title: str = title self.label: str = label def _repr_html_(self) -> str: return f'<img src="{self.path}" height="264" width="391" />' def _repr_latex_(self) -> str: return '\n'.join(( r'\begin{figure}[H]', r' \centering', r' \adjustimage{max size={0.9\linewidth}{0.9\paperheight}}' f'{{{self.path}}}', fr' \caption{{{self.title}}}\label{{fig:{self.label}}}', r'\end{figure}', ))
class Solution: def recurse(self, n, stack, cur_open) : if n == 0 : self.ans.append(stack+')'*cur_open) return for i in range(cur_open+1) : self.recurse(n-1, stack+(')'*i)+'(', cur_open-i+1) # @param A : integer # @return a list of strings def generateParenthesis(self, A): if A <= 0 : return [] self.ans = [] self.recurse(A, "", 0) return self.ans
class Solution: def rangeBitwiseAnd(self, left: int, right: int) -> int: i = 0 # how many bit right shifted while left != right: left >>= 1 right >>= 1 i += 1 return left << i # TESTS for left, right, expected in [ (5, 7, 4), (0, 1, 0), (26, 30, 24), ]: sol = Solution() actual = sol.rangeBitwiseAnd(left, right) print("Bitwise AND of all numbers in range", f"[{left}, {right}] ->", actual) assert actual == expected
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"plot_sequence": "10_core_overview.ipynb", "plot_sequence_1d": "10_core_overview.ipynb", "get_alphabet": "11_core_elements.ipynb", "get_element_counts": "11_core_elements.ipynb", "get_first_positions": "11_core_elements.ipynb", "get_element_frequency": "11_core_elements.ipynb", "plot_element_counts": "11_core_elements.ipynb", "get_subsequences": "12_core_subsequences.ipynb", "get_ndistinct_subsequences": "12_core_subsequences.ipynb", "get_unique_ngrams": "13_core_ngrams.ipynb", "get_all_ngrams": "13_core_ngrams.ipynb", "get_ngram_universe": "13_core_ngrams.ipynb", "get_ngram_counts": "13_core_ngrams.ipynb", "plot_ngram_counts": "13_core_ngrams.ipynb", "get_transitions": "14_core_transitions.ipynb", "get_ntransitions": "14_core_transitions.ipynb", "get_transition_matrix": "14_core_transitions.ipynb", "plot_transition_matrix": "14_core_transitions.ipynb", "get_spells": "15_core_spells.ipynb", "get_longest_spell": "15_core_spells.ipynb", "get_spell_durations": "15_core_spells.ipynb", "is_recurrent": "16_core_statistics.ipynb", "get_entropy": "16_core_statistics.ipynb", "get_turbulence": "16_core_statistics.ipynb", "get_complexity": "16_core_statistics.ipynb", "get_routine": "16_core_statistics.ipynb", "plot_sequences": "20_multi_overview.ipynb", "are_recurrent": "21_multi_attributes.ipynb", "get_summary_statistic": "21_multi_attributes.ipynb", "get_routine_scores": "21_multi_attributes.ipynb", "get_synchrony": "21_multi_attributes.ipynb", "get_sequence_frequencies": "21_multi_attributes.ipynb", "get_motif": "22_multi_derivatives.ipynb", "get_modal_state": "22_multi_derivatives.ipynb", "get_optimal_distance": "23_multi_edit_distances.ipynb", "get_levenshtein_distance": "23_multi_edit_distances.ipynb", "get_hamming_distance": "23_multi_edit_distances.ipynb", "get_combinatorial_distance": "24_multi_nonalignment.ipynb"} modules = ["core/__init__.py", "core/elements.py", "core/subsequences.py", "core/ngrams.py", "core/transitions.py", "core/spells.py", "core/statistics.py", "multi/__init__.py", "multi/attributes.py", "multi/derivatives.py", "multi/editdistances.py", "multi/nonalignment.py"] doc_url = "https://pysan-dev.github.io/pysan/" git_url = "https://github.com/pysan-dev/pysan/tree/master/" def custom_doc_links(name): return None
print("Challenges 38: WAF program to print the number of prime numbers which are less than or equal to a given integer.") n = 7 nums = range(2, n+1) num_of_divisors = 0 counter = 0 for x in nums: for i in range(1, x+1): if x % i == 0: num_of_divisors += 1 if num_of_divisors == 2: counter += 1 num_of_divisors = 0 print(counter)
def n_to_triangularno_stevilo(n): stevilo = 0 a = 1 for i in range(n): stevilo += a a += 1 return stevilo def prvo_triangularno_stevilo_Z_vec_kot_k_delitelji(k): j = 0 n = 0 stevilo_deliteljev = 0 while stevilo_deliteljev <= k: stevilo_deliteljev = 0 j += 1 n = n_to_triangularno_stevilo(j) i = 1 while i <= n**0.5: if n % i == 0: stevilo_deliteljev += 1 i += 1 stevilo_deliteljev *= 2 return n print(prvo_triangularno_stevilo_Z_vec_kot_k_delitelji(500))
# mock.py # Test tools for mocking and patching. # Copyright (C) 2007 Michael Foord # E-mail: fuzzyman AT voidspace DOT org DOT uk # mock 0.3.1 # http://www.voidspace.org.uk/python/mock.html # Released subject to the BSD License # Please see http://www.voidspace.org.uk/python/license.shtml # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml # Comments, suggestions and bug reports welcome. __all__ = ( 'Mock', 'patch', 'sentinel', '__version__' ) __version__ = '0.3.1' class Mock(object): def __init__(self, methods=None, spec=None, name=None, parent=None): self._parent = parent self._name = name if spec is not None and methods is None: methods = [member for member in dir(spec) if not (member.startswith('__') and member.endswith('__'))] self._methods = methods self.reset() def reset(self): self.called = False self.return_value = None self.call_args = None self.call_count = 0 self.call_args_list = [] self.method_calls = [] self._children = {} def __call__(self, *args, **keywargs): self.called = True self.call_count += 1 self.call_args = (args, keywargs) self.call_args_list.append((args, keywargs)) parent = self._parent name = self._name while parent is not None: parent.method_calls.append((name, args, keywargs)) if parent._parent is None: break name = parent._name + '.' + name parent = parent._parent return self.return_value def __getattr__(self, name): if self._methods is not None and name not in self._methods: raise AttributeError("object has no attribute '%s'" % name) if name not in self._children: self._children[name] = Mock(parent=self, name=name) return self._children[name] def _importer(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def patch(target, attribute, new=None): if isinstance(target, basestring): target = _importer(target) def patcher(func): original = getattr(target, attribute) if hasattr(func, 'restore_list'): func.restore_list.append((target, attribute, original)) func.patch_list.append((target, attribute, new)) return func func.restore_list = [(target, attribute, original)] func.patch_list = [(target, attribute, new)] def patched(*args, **keywargs): for target, attribute, new in func.patch_list: if new is None: new = Mock() args += (new,) setattr(target, attribute, new) try: return func(*args, **keywargs) finally: for target, attribute, original in func.restore_list: setattr(target, attribute, original) patched.__name__ = func.__name__ return patched return patcher class SentinelObject(object): def __init__(self, name): self.name = name def __repr__(self): return '<SentinelObject "%s">' % self.name class Sentinel(object): def __init__(self): self._sentinels = {} def __getattr__(self, name): return self._sentinels.setdefault(name, SentinelObject(name)) sentinel = Sentinel()
# coding=utf-8 """ :Copyright: © 2022 Advanced Control Systems, Inc. All Rights Reserved. @Author: Darren Liang @Date : 2022-02-28 """ class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree(object): def __init__(self): self.root = None def insert(self, value): new_node = Node(value) if self.root == None: self.root = new_node return True temp = self.root while (True): if new_node.value == temp.value: return False if new_node.value < temp.value: if temp.left == None: temp.left = new_node return True temp = temp.left else: # if new_node.value > temp.value: if temp.right == None: temp.right = new_node return True temp = temp.right def contains(self, value): temp = self.root while temp != None: if value > temp.value: temp = temp.right elif value < temp.value: temp = temp.left else: return True return False def get_min_value_node(self, current_node): while current_node.left != None: current_node = current_node.left return current_node if __name__ == "__main__": tree = BinarySearchTree() # tree.insert(2) # tree.insert(1) # tree.insert(3) # print(tree.root.value) # print(tree.root.left.value) # print(tree.root.right.value) # print(tree.get_min_value_node(tree.root).value) tree.insert(47) tree.insert(21) tree.insert(76) tree.insert(18) tree.insert(27) tree.insert(52) tree.insert(82) print(tree.contains(27)) print(tree.contains(17)) print(tree.get_min_value_node(tree.root).value)
"""Decorators used for adding functionality to the library.""" def downcast_field(property_name, default_value = None): """A decorator function for handling downcasting.""" def store_downcast_field_value(class_reference): """Store the key map.""" setattr(class_reference, "__deserialize_downcast_field__", property_name) setattr(class_reference, "__deserialize_downcast_field_default_value__", default_value) return class_reference return store_downcast_field_value def _get_downcast_field(class_reference): """Get the downcast field name if set, None otherwise.""" return getattr(class_reference, "__deserialize_downcast_field__", None) def _get_downcast_field_default_value(class_reference): """Get the defualt value used for downcast field, None by default.""" return getattr(class_reference, "__deserialize_downcast_field_default_value__", None) def downcast_identifier(super_class, identifier): """A decorator function for storing downcast identifiers.""" def store_key_map(class_reference): """Store the downcast map.""" if not hasattr(super_class, "__deserialize_downcast_map__"): setattr(super_class, "__deserialize_downcast_map__", {}) super_class.__deserialize_downcast_map__[identifier] = class_reference return class_reference return store_key_map def _get_downcast_class(super_class, identifier): """Get the downcast identifier for the given class and super class, returning None if not set""" if not hasattr(super_class, "__deserialize_downcast_map__"): return None return super_class.__deserialize_downcast_map__.get(identifier) def allow_downcast_fallback(): """A decorator function for setting that downcast fallback to dicts is allowed.""" def store(class_reference): """Store the allowance flag.""" setattr(class_reference, "__deserialize_downcast_allow_fallback__", True) return class_reference return store def _allows_downcast_fallback(super_class): """Get the whether downcast can fallback to a dict or not""" return getattr(super_class, "__deserialize_downcast_allow_fallback__", False) def downcast_proxy(source_property, target_property): """A decorator function for setting up a downcasting proxy, source_property will be used as downcast_field for target_property.""" def store_downcast_proxy(class_reference): """Create downcast proxy mapping and add the properties mapping to it.""" if not hasattr(class_reference, "__deserialize_downcast_proxy_map__"): setattr(class_reference, "__deserialize_downcast_proxy_map__", {}) class_reference.__deserialize_downcast_proxy_map__[target_property] = source_property return store_downcast_proxy def _get_downcast_proxy(class_reference, property): """Get downcast proxy for property in class_reference, None if not set.""" if not hasattr(class_reference, "__deserialize_downcast_proxy_map__"): return None return class_reference.__deserialize_downcast_proxy_map__.get(property, None)
a = 10 def f(): global a a = 100 def ober(): b = 100 def unter(): nonlocal b b = 1000 def unterunter(): nonlocal b b = 10000 unterunter() unter() print(b) ober() def xyz(x): return x * x z = lambda x: x * x print(z(3)) myList = [10,20,30,40,50] def s(x): return -x myList = sorted(myList,key= lambda x:-x) print(myList)
# Responsible for giving targets to the Quadrocopter control lopp class HighLevelLogic: def __init__(self, control_loop, state_provider): self.controllers self.flightmode = FlightModeLanded() self.control_loop = control_loop state_provider.registerListener(self) # Tells all systems that time has passed. # timeDelta is the time since the last update call in seconds def update(self, timedelta): # check if we need to change the flight mode newmode = self.flightmode.update(timedelta) if newmode.name != self.flightmode.name: print("HighLevelLogic: changing FlightMode from %s to %s" % (self.flightmode.name, newmode.name)) self.flightmode = newmode # TODO: do we need to update the control loop? # will be called by State Provider whenever a new sensor reading is ready # timeDelta is the time since the last newState call in seconds def new_sensor_reading(self, timedelta, state): target_state = self.flightmode.calculate_target_state(state) self.control_loop.setTargetState(target_state) class FlightMode: def __init__(self): self.timeInState = 0 def update(self, time_delta): self.timeInState += time_delta return self._update(time_delta) class FlightModeLanded(FlightMode): def __init__(self): self.name = "FlightModeLanded" def _update(self, timedelta): if self.timeInState > 2.0: return FlightModeRiseTo1m() return self def calculate_target_state(self, current_state): # no need to react to anything return self class FlightModeRiseTo1m(FlightMode): def __init__(self): # TODO: start motors self.name = "FlightModeRiseTo1m" def _update(self, timedelta): if self.timeInState > 3.0: return FlightModeHover() return self def calculate_target_state(self, current_state): # no need to react to anything return self class FlightModeHover(FlightMode): def __init__(self): self.name = "FlightModeHover" def _update(self, timedelta): if self.timeInState > 5.0: return FlightModeGoDown() return self def calculate_target_state(self, current_state): # no need to react to anything return self class FlightModeGoDown(FlightMode): def __init__(self): self.name = "FlightModeGoDown" def _update(self, timedelta): if self.timeInState > 7.0: return FlightModeLanded() return self def calculate_target_state(self, current_state): # no need to react to anything return self
keyb = '`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;\'ZXCVBNM,./' while True: try: frase = input() decod = '' for c in frase: if c == ' ': decod += c else: decod += keyb[keyb.index(c)-1] print(decod) except EOFError: break
outputs = [] ## Test Constructor output = """PROFILING Command: ['./testConstructor '] PrecisionTuner: MODE PROFILING PrecisionTuner: MODE PROFILING """ outputs.append(output) output = """Error no callstacks\n""" outputs.append(output) output = """Strategy Command: ['./testConstructor '] Strategy: 1, STEP reached: NoOccurence No more strategy to test.\n""" outputs.append(output) ## Test Exp output = """PROFILING Command: ['./testExp '] PrecisionTuner: MODE PROFILING SUCCESS: 23.1039\n\n""" outputs.append(output) output = """No more strategy to generate. """ outputs.append(output) output = """Strategy Command: ['./testExp '] Strategy: 1, STEP reached: NoOccurence No more strategy to test. """ outputs.append(output) ## Test Header output = """PROFILING Command: ['./testHeader '] PrecisionTuner: MODE PROFILING """ outputs.append(output) output = """Error no callstacks """ outputs.append(output) output = """Strategy Command: ['./testHeader '] Strategy: 1, STEP reached: NoOccurence No more strategy to test. """ outputs.append(output) ## Test MathFunctions output = """PROFILING Command: ['./testMathFunctions '] PrecisionTuner: MODE PROFILING THRESHOLD=0.100000, reference=1911391536333.537109 a=1911391536333.537109 SUCCESS """ outputs.append(output) output = """No more strategy to generate. """ outputs.append(output) output = """Strategy Command: ['./testMathFunctions '] Strategy: 1, STEP reached: NoOccurence No more strategy to test.\n""" outputs.append(output)
# Bubble Sort def bubble_sort(array: list) -> tuple: """"will return the sorted array, and number of swaps""" total_swaps = 0 for i in range(len(array)): swaps = 0 for j in range(len(array) - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] swaps += 1 total_swaps += 1 if swaps == 0: break return array, total_swaps _ = int(input()) array = list(map(int, input().split())) array, total_swaps = bubble_sort(array) print(f'Array is sorted in {total_swaps} swaps.') print(f'First Element: {array[0]}') print(f'Last Element: {array[-1]}')
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A helper library for coverage_test.py - coverage is added to this library.""" def simple_func(a): return 2 * a def if_func(a): x = a if x: return 2 else: return 3 def cmp_less(a, b): return a < b def cmp_greater(a, b): return a > b def cmp_const_less(a): return 1 < a def cmp_const_less_inverted(a): return a < 1 def regex_match(re_obj, a): re_obj.match(a)
def fun(n): fact = 1 for i in range(1,n+1): fact = fact * i return fact n= int(input()) k = fun(n) j = fun(n//2) l = j//(n//2) print(((k//(j**2))*(l**2))//2)
palavras = ("Aprender", "Programar", "Linguagem", "Python", "Curso", "Gratis", "Estudar", "Praticar", "Trabalhar ", "Mercado", "Programar", "Futuro") for vol in palavras: print(f"\nNa palavra {vol.upper()} temos", end=" ") for letra in vol: if letra.lower() in "aeiou": print(letra, end=" ")
# a = int(input('Numerador: ')) # se tentarmos colocar uma letra aqui vai da erro de valor ValueError # b = int(input('Denominador: ')) # se colocar 0 aqui vai acontecer uma excecao ZeroDivisionError - divisao por zero # r = a/b # print(f'A divisao de {a} por {b} vale = {r}') # para tratar erros a gente usa o comando try, except, else try: # o python vai tentar realizar este comando a = int(input('Numerador: ')) b = int(input('Denominador: ')) r = a / b # caso aconteca qualquer erro de valor ou divisao por 0, etc.. Ele vai pular para o comando except except Exception as erro: # poderia colocar apenas except: , porem criou uma variavel para demonstrar o erro que ta aparecendo print(f'Erro encontrado = {erro.__class__}') # mostrar a classe do erro else: # Se a operacao de try der certo ele vai realizar o comando else tambem, comando opcional print(f'O resultado foi = {r}') finally: print('Volte sempre! Obrigado!') # o finally vai acontecer sempre independente de o try der certo ou errado, comando opcional
## ## Programación en Python ## =========================================================================== ## ## La columna 3 del archivo `data.csv` contiene una fecha en formato ## `YYYY-MM-DD`. Imprima la cantidad de registros por cada mes separados ## por comas, tal como se muestra a continuación. ## ## Rta/ ## 01,3 ## 02,4 ## 03,2 ## 04,4 ## 05,3 ## 06,3 ## 07,5 ## 08,6 ## 09,3 ## 10,2 ## 11,2 ## 12,3 ## ## >>> Escriba su codigo a partir de este punto <<< ## with open('data.csv', 'r') as f: lineas = f.readlines() filas = [line.split('\t') for line in lineas] fechas = [c[2].split('-')[1] for c in filas] mes = set(fechas) for i in sorted(mes): print(i + ',' + str(fechas.count(i)))
print("Estou aprendendo Python") nome = input("Qual o seu nome?") idade = int(input("Qual sua idade?")) peso = float(input("Qual o seu peso?")) result = f""" Seu Nome é: {nome} Sua idade é: {idade} E seu Peso é: {peso} """ print(result)
class Color(APIObject, IDisposable): """ Represents a color in Autodesk Revit. Color(red: Byte,green: Byte,blue: Byte) """ def Dispose(self): """ Dispose(self: APIObject,A_0: bool) """ pass def ReleaseManagedResources(self, *args): """ ReleaseManagedResources(self: APIObject) """ pass def ReleaseUnmanagedResources(self, *args): """ ReleaseUnmanagedResources(self: APIObject) """ pass def __enter__(self, *args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self, *args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self, red, green, blue): """ __new__(cls: type,red: Byte,green: Byte,blue: Byte) """ pass Blue = property(lambda self: object(), lambda self, v: None, lambda self: None) """Get the blue channel of the color. Setting a channel is obsolete in Autodesk Revit 2013. Please create a new color instead. Get: Blue(self: Color) -> Byte Set: Blue(self: Color)=value """ Green = property(lambda self: object(), lambda self, v: None, lambda self: None) """Get the green channel of the color. Setting a channel is obsolete in Autodesk Revit 2013. Please create a new color instead. Get: Green(self: Color) -> Byte Set: Green(self: Color)=value """ IsValid = property(lambda self: object(), lambda self, v: None, lambda self: None) """Identifies if the color represents a valid color,or an uninitialized/invalid value. Get: IsValid(self: Color) -> bool """ Red = property(lambda self: object(), lambda self, v: None, lambda self: None) """Get the red channel of the color. Setting a channel is obsolete in Autodesk Revit 2013. Please create a new color instead. Get: Red(self: Color) -> Byte Set: Red(self: Color)=value """ InvalidColorValue = None
class Solution: def numTilings(self, n: int) -> int: mod = 1_000_000_000 + 7 f = [[0 for i in range(1 << 2)] for i in range(2)] f[0][(1 << 2) - 1] = 1 o0 = 0 o1 = 1 for i in range(n): f[o1][0] = f[o0][(1 << 2) - 1] f[o1][1] = (f[o0][0] + f[o0][2]) % mod f[o1][2] = (f[o0][0] + f[o0][1]) % mod f[o1][(1 << 2) - 1] = (f[o0][0] + f[o0][1] + f[o0][2] + f[o0][(1 << 2) - 1]) % mod o0 = o1 o1 ^= 1 return f[o0][(1 << 2) - 1]
"""Constants that define time formats""" F1 = '%Y-%m-%dT%H:%M:%S' F2 = '%Y-%m-%d'
def escreva(texto): tam = len(texto) + 4 print('~' * tam) print(f' {texto}') print('~' * tam) escreva(str(input('Digite um texto: ')))
"""Media files location specifications.""" def workflow_step_media_location(instance, filename): """Return the location of a stored media file for a Workflow Step.""" workflow_id = instance.workflow_step.workflow.id step_id = instance.workflow_step_id ui_identifier = instance.ui_identifier file_extension = filename.rpartition(".")[2] return f"workflow_system/workflows/{workflow_id}/steps/{step_id}/{ui_identifier}.{file_extension}" def collection_image_location(instance, filename): """Return the location of a stored media file for a Workflow Collection.""" collection_id = instance.id image_type = instance.type file_extension = filename.rpartition(".")[2] return f"workflow_system/collections/{collection_id}/{image_type}.{file_extension}" def workflow_image_location(instance, filename): """Return the location of a stored media file for a Workflow.""" workflow_id = instance.id image_type = instance.type file_extension = filename.rpartition(".")[2] return f"workflow_system/workflows/{workflow_id}/{image_type}.{file_extension}" def author_media_location(instance, filename): """Return the location of a stored media file for an Author.""" author_id = instance.id image_type = filename.rpartition(".")[2] return f"workflow_system/authors/{author_id}/profileImage.{image_type}"
# -*- coding: utf-8 -*- stations = {4349: 'Мусоргского (на Керамику)', 3426: 'Пионерская (на 1-й км)', 3461: 'Техучилище (на 1-й км)', 3380: 'Каменные палатки (на Комсомольскую)', 3348: 'Г-ца Исеть (на Шарташскую)', 3362: 'Декабристов (к Большакова)', 963627: 'Бульвар Малахова (на Фучика)', 3502: 'Фрезеровщиков', 4274: 'Техническая (на 7 ключей)', 963233: 'Кушвинская', 3421: 'Пед. университет (от метро Уралмаш)', 961850: 'Куйбышева (на Дворец спорта)', 961845: 'Серафимы Дерябиной (на ВИЗ)', 3341: 'Ж.Д.Вокзал (на Челюскинцев, Пионерскую)', 1173: 'Ельцина (на Папанина)', 4277: 'Техническая (от 7 ключей)', 3394: 'Кузнецова (к Пл.1 пятилетки)', 3428: 'Пионерская (с 1-го км)', 3452: 'Сварщиков (на Лукиных)', 4279: 'Ватутина (с 7 ключей)', 3429: 'Пионерская (с Кондукторской)', 961866: 'Московская (от Белореченской)', 3410: 'Московская (на ТК Алатырь)', 3475: 'Цирк (с Декабристов)', 3418: 'Папанина (на Шейнкмана)', 3336: 'Викулова (на Волгоградскую)', 3984: 'Юго-западная (на Московскую)', 3535: 'Кондукторская (на Блюхера)', 3325: 'Блюхера (с Шарташа)', 3412: 'Московская (с ТК Алатырь)', 3320: 'Белинского (к Куйбыш.-Лунач.)', 4064: 'Малый конный (на ВИЗ)', 3504: 'Шарташ', 3368: 'Заводская (на ВИЗ)', 3327: 'Блюхера (на Пионерскую)', 3391: 'Крылова (на ВИЗ бульвар)', 4353: 'Ляпустина (на Керамику)', 3397: 'Куйбыш.-Луначарск. (на Декабристов)', 4007: 'Автовокзал (на Фрунзе)', 4237: 'Таганский ряд (от 7 ключей)', 3357: 'Пер. Рижский (на Ювелирную)', 3488: 'Энтузиастов (с Эльмаша)', 961840: 'Победы (к Индустрии)', 3486: 'Энтузиастов (с Краснофлотцев)', 3433: 'Пл. Коммунаров (с Московской)', 3382: 'Киностудия (к кольцу г-це Исеть)', 3403: 'ТЦ Алатырь (на Московскую)', 3983: 'Юго-западная (на Белореченскую)', 963630: 'Бульвар Малахова (на м. Ботаническая)', 3361: 'Дворец Молодежи (на ВИЗ бульвар)', 4283: 'Расточная (от 7 ключей)', 3345: 'Ворошиловская (на Электриков)', 3472: 'Цирк (на Белинского)', 3463: 'Уральский федеральный университет (к Восточной)', 3436: 'Бак. комиссаров (на Уральских рабочих)', 3337: 'Викулова (с Волгоградской)', 3389: 'Краснофлотцев (на Фронтовых бригад)', 3442: 'Профессорская (на Гагарина)', 3476: 'Челюскинцев (на Вокзал, Пионерскую)', 3370: 'Ильича (на ДК Лаврова)', 3398: 'Куйбыш.-Луначарск. (от Декабристов)', 3411: 'Московская (на Юго-Западную)', 3392: 'Крылова (на Кирова)', 4305: 'Сухоложская (от Южной)', 4352: 'Эскадронная (от Керамики)', 3364: 'Декабристов (на Куйбыш.-Луначарск.)', 963284: 'Уральский федеральный университет (на Гагарина)', 3415: 'Новгородцевой (на Сиреневый Бульвар)', 3451: 'Сварщиков (на Автомагистральную)', 961841: 'Учителей (на Блюхера)', 3334: 'Карнавал (на ВИЗ)', 3384: 'Кировградская (на Уральских рабочих)', 3473: 'Цирк (на Декабристов)', 4163: 'Донбасская (к Кировградской)', 4307: 'Братская (от Южной)', 3405: 'Метро Уралмаш (к Кузнецова)', 3351: 'Гагарина (на Уральский федеральный университет)', 3321: 'Белинского (к Цирк)', 961851: 'Новомосковская (на ВИЗ)', 3456: 'Сиреневый бульвар (на Новгородцевой)', 3366: 'Дом кино (к Киностудии)', 3406: 'Метро Уралмаш (к Пед. институт)', 3466: 'Управ. дороги (на Вокзал)', 3820: 'Восточная (к Уральский федеральный университет)', 3349: 'Г-ца Исеть (к кольцу г-це Исеть)', 3457: 'Студенческая (к ТК Современник)', 4350: 'Мусоргского (от Керамики)', 3527: 'Учителей (на Кондукторскую)', 4285: 'Кишиневская (на 7 ключей)', 3910: 'Слесарей', 3374: 'ТК Буревестник (на Волгоградскую)', 3316: 'Автомагистральная (на Пехотинцев)', 3819: 'Бажова (на Вост)', 963681: 'Фучика (на бульвар Малахова)', 3419: 'Папанина (на Управ. дороги)', 4052: 'Разъезд (на Зел. остров)', 4238: 'Донская (от Эльмаша)', 3381: 'Каменные палатки (на Новгородцевой)', 4348: 'Новосибирская (от Керамики)', 3314: 'Диагностический центр (на 40 лет Октября)', 1172: 'Ельцина (к Управ. дороги)', 4275: 'ДК ВОС (от 7 ключей)', 3482: 'Шейнкмана (к дв. Молодежи)', 3379: 'Калининская (на Техучилище)', 963149: 'Ост.Пл.1 Пятилетки (на конечную)', 3469: 'Фрунзе (на Автовокзал, в депо)', 3367: 'Дом кино (к Куйбыш.-Лунач.)', 4367: 'Пехотинцев (на Бебеля)', 961849: 'Куйбышева (от Дворца спорта)', 3529: 'Кондукторская (на Пионерскую)', 3449: 'Сахалинская (на Студенческую)', 3826: 'Дворец Молодежи (к Шейнкмана)', 4057: 'Малый конный (на Зел. остров)', 961852: 'Новомосковская (на Волгоградскую)', 3400: 'Лукиных (на Библиотеку)', 4175: 'Уральских рабочих (к Кировградской)', 4321: 'Ферганская (к Керамике)', 961844: 'Плотников (на ВИЗ с Зеленого острова)', 3352: 'Гурзуфская (к Волгоградской)', 4045: 'Металлургов (на ВИЗ)', 3823: 'Восточная (на Бажова)', 1169: '1-й км (на Техучилище)', 3371: 'Ильича (на Индустрии)', 3338: 'Войкова (на Фрезеровщиков)', 3329: 'Большакова (к Фрунзе)', 4268: 'Керамическая', 3955: 'Тверитина (от ЦПКиО)', 3439: 'Театр музыкальной комедии (на Пл. 1905 г.)', 3344: 'Ворошиловская (на Фронтовых бригад)', 3480: 'Шевченко (на Протез-ортопед. предприятие)', 3437: 'Бакинских комиссаров (на Победы)', 3438: 'Театр музыкальной комедии (на Оперный театр)', 3491: 'Южная (на Автовокзал)', 3369: 'Заводская (с ВИЗа)', 3479: 'Шарташская (на Шевченко)', 3360: 'Дв. Спорта', 3947: 'Тверитина (на ЦПКиО)', 4050: 'Рабочих (на Зел. остров)', 961839: 'Кузнецова (от пл.1 пят. к м.Уралмаш)', 3386: 'Колмогорова (с Кирова)', 3481: 'Шевченко (на Шарташскую)', 3484: 'Электриков (на Ворошиловскую)', 3459: 'Татищева (на ВИЗ)', 3414: 'Новгородцевой (на Каменные палатки)', 3416: 'Оперный театр (на Площадь 1905 г)', 4372: 'Таганский ряд (с ВИЗа)', 3450: 'Сахалинская (на Шарташ)', 4287: 'Дружининская (на 7 ключей)', 4118: 'Верх-Исет. рынок (с Колмогорова)', 963680: 'Фучика (с бульвара Малахова)', 3387: 'Комсомольская (на Профессорскую)', 4119: 'Верх-Исет. рынок (на Колмогорова)', 961904: 'Уральский федеральный университет (на Первомайскую)', 4162: 'Библиотека (от Лукиных)', 4297: 'Школа им. С.В. Рахманинова (от 7 ключей)', 4282: 'Расточная (на 7 ключей)', 4306: 'Сухоложская (к Южной)', 3383: 'Кировградская (на Донбасскую)', 3458: 'Студенческая (на Сахалинскую)', 3355: 'ДК Лаврова (на Кузнецова)', 3827: 'Пл. коммунаров (от Шейнк)', 4347: 'Новосибирская (на Керамику)', 4371: 'Таганский ряд (на 7 ключей)', 3470: 'Фрунзе (на Большакова, в депо)', 3404: 'ТЦ Алатырь (с Московской)', 3340: 'Ж.Д.Вокзал (на Управ. дороги)', 3434: 'Пл. Обороны (к Декабристов)', 3444: 'Радищева (на Московскую)', 3440: 'Протезно-орт. предпр. (на Челюскинцев)', 4286: 'Дружининская (от 7 ключей)', 3495: 'Волгоградская (конечная)', 3396: 'Куйбыш.-Луначарск. (к Дому кино)', 4117: 'Колмогорова (на Кирова)', 3431: 'Пл. 1905 г. (к пл.Коммунаров)', 961847: 'Волгоградская (к ТК Буревестник)', 1170: '40 лет Октября (на Автомагазин)', 963621: 'Метро Ботаническая', 4062: 'Зеленый остров', 3326: 'Блюхера-Уральская ( на Уральский федеральный университет)', 3445: 'Радищева (с Московской)', 3467: 'Фронтовых бригад (на Ворошиловскую)', 3468: 'Фронтовых бригад (на Краснофлотцев)', 3390: 'Краснофлотцев (на Энтузиастов)', 4253: 'Посадская (на Дворец спорта)', 4069: 'Разъезд (на ВИЗ)', 961848: 'Волгоградская (от ТК Буревестник)', 963698: 'Московская (от Дворца Спорта) (от Дворца Спорта)', 4174: 'Уральских рабочих (к Бакинских комиссаров)', 3460: 'Татищева (с ВИЗа)', 3483: 'Шейнкмана (на Папанина)', 3736: 'Донская (на Эльмаш)', 3393: 'Кузнецова (к Метро Уралмаш)', 3333: 'Верх-Исет. бульвар (с Крылова)', 3375: 'ТК Буревестник (с Волгоградской)', 3448: 'Сакко и Ванцетти (на пл. Коммунаров)', 3432: 'Пл. Коммунаров (с Ленина)', 3372: 'Индустрии (на Ильича)', 3447: 'Фармацевтический колледж (от Карнавала)', 3339: 'Войкова (на Энтузиастов)', 4090: 'Ухтомская (на Серафимы Дерябиной)', 3496: 'Южная', 3420: 'Пед. университет (к метро Уралмаш)', 4354: 'Ляпустина (от Керамики)', 3485: 'Электриков (на Пед. институт)', 3388: 'Комсомольская (от Профессорскй)', 1168: '1-й км (на Пионерскую)', 3441: 'Протезно-орт.пред. (на Шевченко)', 3960: 'Кирова (на ВИЗ)', 4369: 'Бебеля (на Пехотинцев)', 3487: 'Энтузиастов (с Фрезеровщиков)', 4192: 'Пионерская (на Кондукторскую)', 3354: 'ДК Лаврова (на Ильича)', 4049: 'Плотников (на Зел. остров)', 4271: 'Пер. Теплоходный (от 7 ключей)', 4373: 'Таганский ряд (на ВИЗ)', 4008: 'Автовокзал (на Южную)', 3474: 'Цирк (с Белинского)', 3465: 'Управ. дороги (на Ельцина)', 3399: 'Куйбыш.-Луначарск. (от Дома кино)', 4107: 'Кирова (на Колмогорова)', 1171: '40 лет Октября (на Машиностроителей)', 4553: 'Победы (к Бак. комиссаров)', 3497: '40 лет ВЛКСМ', 4252: 'Посадская (отДворца спорта)', 4026: 'Завод РТИ (к Южной)', 4308: 'Братская (к Южной)', 3505: 'Эльмаш', 3455: 'Сиреневый бульвар (на 40 лет ВЛКСМ)', 3322: 'Белореченская (на Волгоградскую)', 4296: 'Школа им. С.В. Рахманинова (на 7 ключей)', 961843: 'ТК Современник (на Студенческую)', 3501: 'Пл. 1 Пятилетки', 3350: 'Гагарина (на Профессорскую)', 3417: 'Оперный театр (к гостинице Исеть)', 3330: 'Шварца (на Ювелирную)', 3373: 'Индустрии (на Победы)', 3356: 'Пер. Рижский (на ВТЧМ)', 3409: 'Московская к Дворцу Спорта (к Дворцу спорта)', 3323: 'Белореченская (с Волгоградской)', 3430: 'Пл. 1905 г. (к г.Исеть)', 4278: 'Маневровая (на 7 ключей)', 3539: 'Советская (на Блюхера)', 3490: 'Ювелирная (на пер. Рижский)', 3422: 'Пед.университет (на Электриков)', 4269: 'Вторчермет', 3499: 'ВИЗ', 3324: 'Блюхера (на Шарташ)', 4370: 'Бебеля (от Пехотинцев)', 4025: 'Завод РТИ (от Южной)', 3376: 'ТК Современник (на Мира)', 4071: 'Рабочих (на ВИЗ)', 4320: 'Ферганская (от Керамики)', 3363: 'Декабристов (к Цирк)', 3378: 'Калининская (на Пед. институт)', 3500: 'Машиностроителей', 4091: 'Ухтомская (на ВИЗ)', 3489: 'Ювелирная (на Шварца)', 3492: 'Южная (на Шварца)', 3424: 'Первомайская (на Блюхера)', 3331: 'Шварца (на Южную)', 3477: 'Челюскинцев (на Протез-ортопед. предприятие)', 3335: 'Карнавал (с ВИЗа)', 3317: 'Автомагистральная (на Сварщиков)', 4301: 'Маневровая (от 7 ключей)', 4046: 'Металлургов (на Волгоградскую)', 3315: 'Диагностический центр (на Лукиных)', 3332: 'Верх-Исет. бульвар (на Крылова)', 3478: 'Шарташская (на Г-ца Исеть)', 3446: 'Фармацевтический колледж (на Карнавал)', 3402: 'Лукиных (на Сварщиков)', 3443: 'Профессорская (на Комсомольскую)', 3401: 'Лукиных (на Диагностический центр)', 3425: 'Первомайская (на Уральский федеральный университет)', 3353: 'Гурзуфская (от Волгоградской)', 3423: 'Пед.университет (с Электриков)', 4284: 'Кишиневская (от 7 ключей)', 3503: 'ЦПКиО', 3702: 'Кирова (на Крылова)', 4351: 'Эскадронная (на Керамику)', 3525: 'Советская (от Блюхера)', 4173: 'Библиотека (к Лукиных)', 4172: 'Донбасская (к Библиотеке)', 3408: 'Мира (на ТК Современник)', 3462: 'Техучилище (на Калининскую)', 4079: 'Плотников (на ВИЗ с Волгоградской)', 3365: 'Декабристов (на Пл. Обороны)', 4134: 'Пехотинцев (на Автомагистральную)', 4270: 'Пер. Теплоходный (на 7 ключей)', 3825: 'Бажова (к кольцу г-цы Исеть)', 4272: 'ДК ВОС (на 7 ключей)', 4078: 'Плотников (на Волгоградскую)', 3328: 'Большакова (к Декабристов)', 3395: 'Кузнецова (к Победе)', 4276: 'Ватутина (на 7 ключей)', 3435: 'Пл. Обороны (на Тверитина)', 3407: 'Мира (на Блюхера)', 961846: 'Серафимы Дерябиной (на Волгоградскую)', 3498: '7 ключей'} invert_stations = sorted(list(dict((v, k) for k, v in stations.items()).items()))
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # normal recursive solution # this recursive solution will call more methods which cause Time Limit Exceed class Solution1: # @param {TreeNode} root # @return {integer} def maxDepth(self, root): if root is None: return 0 if self.left is None and self.right is None: return 1 elif self.left is not None and self.right is not None: return self.maxDepth(self.left) + 1 if self.maxDepth(self.left) > \ self.maxDepth(self.right) else self.maxDepth(self.right) + 1 elif self.left is not None: return self.maxDepth(self.left) + 1 elif self.rigith is not None: return self.maxDepth(self.right) + 1 # recursive solution with only two methods call # This is a cleaner solution with only two methods # This is passed in the leetcode class Solution2: # @param {TreeNode} root # @return {integer} def maxDepth(self, root): if root is None: return 0 leftDepth = self.maxDepth(root.left) rightDepth = self.maxDepth(root.right) return leftDepth + 1 if leftDepth > rightDepth else rightDepth + 1
url = 'http://127.0.0.1:3001/post' dapr_url = "http://localhost:3500/v1.0/invoke/dp-61c2cb20562850d49d47d1c7-executorapp/method/health" # dapr_url = "http://localhost:3500/v1.0/healthz" # res = requests.post(dapr_url, json.dumps({'a': random.random() * 1000})) # res = requests.get(dapr_url, ) # # # # print(res.text) # print(res.status_code) # INFO[0000] *----/v1.0/invoke/{id}/method/{method:*} # INFO[0000] GET----/v1.0/state/{storeName}/{key} # INFO[0000] DELETE----/v1.0/state/{storeName}/{key} # INFO[0000] PUT----/v1.0/state/{storeName} # INFO[0000] PUT----/v1.0/state/{storeName}/bulk # INFO[0000] PUT----/v1.0/state/{storeName}/transaction # INFO[0000] POST----/v1.0/state/{storeName} # INFO[0000] POST----/v1.0/state/{storeName}/bulk # INFO[0000] POST----/v1.0/state/{storeName}/transaction # INFO[0000] POST----/v1.0-alpha1/state/{storeName}/query # INFO[0000] PUT----/v1.0-alpha1/state/{storeName}/query # INFO[0000] GET----/v1.0/secrets/{secretStoreName}/bulk # INFO[0000] GET----/v1.0/secrets/{secretStoreName}/{key} # INFO[0000] POST----/v1.0/publish/{pubsubname}/{topic:*} # INFO[0000] PUT----/v1.0/publish/{pubsubname}/{topic:*} # INFO[0000] POST----/v1.0/bindings/{name} # INFO[0000] PUT----/v1.0/bindings/{name} # INFO[0000] GET----/v1.0/healthz # INFO[0000] GET----/v1.0/healthz/outbound # INFO[0000] GET----/v1.0/actors/{actorType}/{actorId}/method/{method} # INFO[0000] GET----/v1.0/actors/{actorType}/{actorId}/state/{key} # INFO[0000] GET----/v1.0/actors/{actorType}/{actorId}/reminders/{name} # INFO[0000] POST----/v1.0/actors/{actorType}/{actorId}/state # INFO[0000] POST----/v1.0/actors/{actorType}/{actorId}/method/{method} # INFO[0000] POST----/v1.0/actors/{actorType}/{actorId}/reminders/{name} # INFO[0000] POST----/v1.0/actors/{actorType}/{actorId}/timers/{name} # INFO[0000] PUT----/v1.0/actors/{actorType}/{actorId}/state # INFO[0000] PUT----/v1.0/actors/{actorType}/{actorId}/method/{method} # INFO[0000] PUT----/v1.0/actors/{actorType}/{actorId}/reminders/{name} # INFO[0000] PUT----/v1.0/actors/{actorType}/{actorId}/timers/{name} # INFO[0000] DELETE----/v1.0/actors/{actorType}/{actorId}/method/{method} # INFO[0000] DELETE----/v1.0/actors/{actorType}/{actorId}/reminders/{name} # INFO[0000] DELETE----/v1.0/actors/{actorType}/{actorId}/timers/{name} # INFO[0000] *----/{method:*} # INFO[0000] GET----/v1.0/metadata # INFO[0000] PUT----/v1.0/metadata/{key} # INFO[0000] POST----/v1.0/shutdown
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_c_float_v_floatarray.tif test_splineinverse_c_float_v_floatarray") command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_c_float_u_floatarray.tif test_splineinverse_c_float_u_floatarray") command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_c_float_c_floatarray.tif test_splineinverse_c_float_c_floatarray") outputs.append ("splineinverse_c_float_v_floatarray.tif") outputs.append ("splineinverse_c_float_u_floatarray.tif") outputs.append ("splineinverse_c_float_c_floatarray.tif") command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_u_float_v_floatarray.tif test_splineinverse_u_float_v_floatarray") command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_u_float_u_floatarray.tif test_splineinverse_u_float_u_floatarray") command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_u_float_c_floatarray.tif test_splineinverse_u_float_c_floatarray") outputs.append ("splineinverse_u_float_v_floatarray.tif") outputs.append ("splineinverse_u_float_u_floatarray.tif") outputs.append ("splineinverse_u_float_c_floatarray.tif") command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_v_float_v_floatarray.tif test_splineinverse_v_float_v_floatarray") command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_v_float_u_floatarray.tif test_splineinverse_v_float_u_floatarray") command += testshade("-t 1 -g 64 64 --center -od uint8 -o Fout splineinverse_v_float_c_floatarray.tif test_splineinverse_v_float_c_floatarray") outputs.append ("splineinverse_v_float_v_floatarray.tif") outputs.append ("splineinverse_v_float_u_floatarray.tif") outputs.append ("splineinverse_v_float_c_floatarray.tif") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_c_float_v_floatarray.tif test_deriv_splineinverse_c_float_v_floatarray") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_c_float_u_floatarray.tif test_deriv_splineinverse_c_float_u_floatarray") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_c_float_c_floatarray.tif test_deriv_splineinverse_c_float_c_floatarray") outputs.append ("deriv_splineinverse_c_float_v_floatarray.tif") outputs.append ("deriv_splineinverse_c_float_u_floatarray.tif") outputs.append ("deriv_splineinverse_c_float_c_floatarray.tif") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_u_float_v_floatarray.tif test_deriv_splineinverse_u_float_v_floatarray") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_u_float_u_floatarray.tif test_deriv_splineinverse_u_float_u_floatarray") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_u_float_c_floatarray.tif test_deriv_splineinverse_u_float_c_floatarray") outputs.append ("deriv_splineinverse_u_float_v_floatarray.tif") outputs.append ("deriv_splineinverse_u_float_u_floatarray.tif") outputs.append ("deriv_splineinverse_u_float_c_floatarray.tif") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_v_float_v_floatarray.tif test_deriv_splineinverse_v_float_v_floatarray") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_v_float_u_floatarray.tif test_deriv_splineinverse_v_float_u_floatarray") command += testshade("--vary_udxdy --vary_vdxdy -t 1 -g 64 64 --center -od uint8 -o ValDxDyOut deriv_splineinverse_v_float_c_floatarray.tif test_deriv_splineinverse_v_float_c_floatarray") outputs.append ("deriv_splineinverse_v_float_v_floatarray.tif") outputs.append ("deriv_splineinverse_v_float_u_floatarray.tif") outputs.append ("deriv_splineinverse_v_float_c_floatarray.tif") # expect a few LSB failures failthresh = 0.008 failpercent = 3
# src: https://github.com/dchest/tweetnacl-js/blob/acab4d4883e7a0be0b230df7b42c0bbd25210d39/nacl.js __pragma__("js", "{}", r""" (function(nacl) { 'use strict'; // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. // Public domain. // // Implementation derived from TweetNaCl version 20140427. // See for details: http://tweetnacl.cr.yp.to/ var u64 = function(h, l) { this.hi = h|0 >>> 0; this.lo = l|0 >>> 0; }; var gf = function(init) { var i, r = new Float64Array(16); if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; return r; }; // Pluggable, initialized in high-level API below. var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; var _0 = new Uint8Array(16); var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(), gf1 = gf([1]), _121665 = gf([0xdb41, 1]), D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); function L32(x, c) { return (x << c) | (x >>> (32 - c)); } function ld32(x, i) { var u = x[i+3] & 0xff; u = (u<<8)|(x[i+2] & 0xff); u = (u<<8)|(x[i+1] & 0xff); return (u<<8)|(x[i+0] & 0xff); } function dl64(x, i) { var h = (x[i] << 24) | (x[i+1] << 16) | (x[i+2] << 8) | x[i+3]; var l = (x[i+4] << 24) | (x[i+5] << 16) | (x[i+6] << 8) | x[i+7]; return new u64(h, l); } function st32(x, j, u) { var i; for (i = 0; i < 4; i++) { x[j+i] = u & 255; u >>>= 8; } } function ts64(x, i, u) { x[i] = (u.hi >> 24) & 0xff; x[i+1] = (u.hi >> 16) & 0xff; x[i+2] = (u.hi >> 8) & 0xff; x[i+3] = u.hi & 0xff; x[i+4] = (u.lo >> 24) & 0xff; x[i+5] = (u.lo >> 16) & 0xff; x[i+6] = (u.lo >> 8) & 0xff; x[i+7] = u.lo & 0xff; } function vn(x, xi, y, yi, n) { var i,d = 0; for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; return (1 & ((d - 1) >>> 8)) - 1; } function crypto_verify_16(x, xi, y, yi) { return vn(x,xi,y,yi,16); } function crypto_verify_32(x, xi, y, yi) { return vn(x,xi,y,yi,32); } function core(out,inp,k,c,h) { var w = new Uint32Array(16), x = new Uint32Array(16), y = new Uint32Array(16), t = new Uint32Array(4); var i, j, m; for (i = 0; i < 4; i++) { x[5*i] = ld32(c, 4*i); x[1+i] = ld32(k, 4*i); x[6+i] = ld32(inp, 4*i); x[11+i] = ld32(k, 16+4*i); } for (i = 0; i < 16; i++) y[i] = x[i]; for (i = 0; i < 20; i++) { for (j = 0; j < 4; j++) { for (m = 0; m < 4; m++) t[m] = x[(5*j+4*m)%16]; t[1] ^= L32((t[0]+t[3])|0, 7); t[2] ^= L32((t[1]+t[0])|0, 9); t[3] ^= L32((t[2]+t[1])|0,13); t[0] ^= L32((t[3]+t[2])|0,18); for (m = 0; m < 4; m++) w[4*j+(j+m)%4] = t[m]; } for (m = 0; m < 16; m++) x[m] = w[m]; } if (h) { for (i = 0; i < 16; i++) x[i] = (x[i] + y[i]) | 0; for (i = 0; i < 4; i++) { x[5*i] = (x[5*i] - ld32(c, 4*i)) | 0; x[6+i] = (x[6+i] - ld32(inp, 4*i)) | 0; } for (i = 0; i < 4; i++) { st32(out,4*i,x[5*i]); st32(out,16+4*i,x[6+i]); } } else { for (i = 0; i < 16; i++) st32(out, 4 * i, (x[i] + y[i]) | 0); } } function crypto_core_salsa20(out,inp,k,c) { core(out,inp,k,c,false); return 0; } function crypto_core_hsalsa20(out,inp,k,c) { core(out,inp,k,c,true); return 0; } var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); // "expand 32-byte k" function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; if (!b) return 0; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; if (m) mpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; } return 0; } function crypto_stream_salsa20(c,cpos,d,n,k) { return crypto_stream_salsa20_xor(c,cpos,null,0,d,n,k); } function crypto_stream(c,cpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); return crypto_stream_salsa20(c,cpos,d,n.subarray(16),s); } function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,n.subarray(16),s); } function add1305(h, c) { var j, u = 0; for (j = 0; j < 17; j++) { u = (u + ((h[j] + c[j]) | 0)) | 0; h[j] = u & 255; u >>>= 8; } } var minusp = new Uint32Array([ 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252 ]); function crypto_onetimeauth(out, outpos, m, mpos, n, k) { var s, i, j, u; var x = new Uint32Array(17), r = new Uint32Array(17), h = new Uint32Array(17), c = new Uint32Array(17), g = new Uint32Array(17); for (j = 0; j < 17; j++) r[j]=h[j]=0; for (j = 0; j < 16; j++) r[j]=k[j]; r[3]&=15; r[4]&=252; r[7]&=15; r[8]&=252; r[11]&=15; r[12]&=252; r[15]&=15; while (n > 0) { for (j = 0; j < 17; j++) c[j] = 0; for (j = 0; (j < 16) && (j < n); ++j) c[j] = m[mpos+j]; c[j] = 1; mpos += j; n -= j; add1305(h,c); for (i = 0; i < 17; i++) { x[i] = 0; for (j = 0; j < 17; j++) x[i] = (x[i] + (h[j] * ((j <= i) ? r[i - j] : ((320 * r[i + 17 - j])|0))) | 0) | 0; } for (i = 0; i < 17; i++) h[i] = x[i]; u = 0; for (j = 0; j < 16; j++) { u = (u + h[j]) | 0; h[j] = u & 255; u >>>= 8; } u = (u + h[16]) | 0; h[16] = u & 3; u = (5 * (u >>> 2)) | 0; for (j = 0; j < 16; j++) { u = (u + h[j]) | 0; h[j] = u & 255; u >>>= 8; } u = (u + h[16]) | 0; h[16] = u; } for (j = 0; j < 17; j++) g[j] = h[j]; add1305(h,minusp); s = (-(h[16] >>> 7) | 0); for (j = 0; j < 17; j++) h[j] ^= s & (g[j] ^ h[j]); for (j = 0; j < 16; j++) c[j] = k[j + 16]; c[16] = 0; add1305(h,c); for (j = 0; j < 16; j++) out[outpos+j] = h[j]; return 0; } function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { var x = new Uint8Array(16); crypto_onetimeauth(x,0,m,mpos,n,k); return crypto_verify_16(h,hpos,x,0); } function crypto_secretbox(c,m,d,n,k) { var i; if (d < 32) return -1; crypto_stream_xor(c,0,m,0,d,n,k); crypto_onetimeauth(c, 16, c, 32, d - 32, c); for (i = 0; i < 16; i++) c[i] = 0; return 0; } function crypto_secretbox_open(m,c,d,n,k) { var i; var x = new Uint8Array(32); if (d < 32) return -1; crypto_stream(x,0,32,n,k); if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; crypto_stream_xor(m,0,c,0,d,n,k); for (i = 0; i < 32; i++) m[i] = 0; return 0; } function set25519(r, a) { var i; for (i = 0; i < 16; i++) r[i] = a[i]|0; } function car25519(o) { var c; var i; for (i = 0; i < 16; i++) { o[i] += 65536; c = Math.floor(o[i] / 65536); o[(i+1)*(i<15?1:0)] += c - 1 + 37 * (c-1) * (i===15?1:0); o[i] -= (c * 65536); } } function sel25519(p, q, b) { var t, c = ~(b-1); for (var i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); p[i] ^= t; q[i] ^= t; } } function pack25519(o, n) { var i, j, b; var m = gf(), t = gf(); for (i = 0; i < 16; i++) t[i] = n[i]; car25519(t); car25519(t); car25519(t); for (j = 0; j < 2; j++) { m[0] = t[0] - 0xffed; for (i = 1; i < 15; i++) { m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); m[i-1] &= 0xffff; } m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); b = (m[15]>>16) & 1; m[14] &= 0xffff; sel25519(t, m, 1-b); } for (i = 0; i < 16; i++) { o[2*i] = t[i] & 0xff; o[2*i+1] = t[i]>>8; } } function neq25519(a, b) { var c = new Uint8Array(32), d = new Uint8Array(32); pack25519(c, a); pack25519(d, b); return crypto_verify_32(c, 0, d, 0); } function par25519(a) { var d = new Uint8Array(32); pack25519(d, a); return d[0] & 1; } function unpack25519(o, n) { var i; for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); o[15] &= 0x7fff; } function A(o, a, b) { var i; for (i = 0; i < 16; i++) o[i] = (a[i] + b[i])|0; } function Z(o, a, b) { var i; for (i = 0; i < 16; i++) o[i] = (a[i] - b[i])|0; } function M(o, a, b) { var i, j, t = new Float64Array(31); for (i = 0; i < 31; i++) t[i] = 0; for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { t[i+j] += a[i] * b[j]; } } for (i = 0; i < 15; i++) { t[i] += 38 * t[i+16]; } for (i = 0; i < 16; i++) o[i] = t[i]; car25519(o); car25519(o); } function S(o, a) { M(o, a, a); } function inv25519(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 253; a >= 0; a--) { S(c, c); if(a !== 2 && a !== 4) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function pow2523(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 250; a >= 0; a--) { S(c, c); if(a !== 1) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function crypto_scalarmult(q, n, p) { var z = new Uint8Array(32); var x = new Float64Array(80), r, i; var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); for (i = 0; i < 31; i++) z[i] = n[i]; z[31]=(n[31]&127)|64; z[0]&=248; unpack25519(x,p); for (i = 0; i < 16; i++) { b[i]=x[i]; d[i]=a[i]=c[i]=0; } a[0]=d[0]=1; for (i=254; i>=0; --i) { r=(z[i>>>3]>>>(i&7))&1; sel25519(a,b,r); sel25519(c,d,r); A(e,a,c); Z(a,a,c); A(c,b,d); Z(b,b,d); S(d,e); S(f,a); M(a,c,a); M(c,b,e); A(e,a,c); Z(a,a,c); S(b,a); Z(c,d,f); M(a,c,_121665); A(a,a,d); M(c,c,a); M(a,d,f); M(d,b,x); S(b,e); sel25519(a,b,r); sel25519(c,d,r); } for (i = 0; i < 16; i++) { x[i+16]=a[i]; x[i+32]=c[i]; x[i+48]=b[i]; x[i+64]=d[i]; } var x32 = x.subarray(32); var x16 = x.subarray(16); inv25519(x32,x32); M(x16,x16,x32); pack25519(q,x16); return 0; } function crypto_scalarmult_base(q, n) { return crypto_scalarmult(q, n, _9); } function crypto_box_keypair(y, x) { randombytes(x, 32); return crypto_scalarmult_base(y, x); } function crypto_box_beforenm(k, y, x) { var s = new Uint8Array(32); crypto_scalarmult(s, x, y); return crypto_core_hsalsa20(k, _0, s, sigma); } var crypto_box_afternm = crypto_secretbox; var crypto_box_open_afternm = crypto_secretbox_open; function crypto_box(c, m, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_afternm(c, m, d, n, k); } function crypto_box_open(m, c, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_open_afternm(m, c, d, n, k); } function add64() { var a = 0, b = 0, c = 0, d = 0, m16 = 65535, l, h, i; for (i = 0; i < arguments.length; i++) { l = arguments[i].lo; h = arguments[i].hi; a += (l & m16); b += (l >>> 16); c += (h & m16); d += (h >>> 16); } b += (a >>> 16); c += (b >>> 16); d += (c >>> 16); return new u64((c & m16) | (d << 16), (a & m16) | (b << 16)); } function shr64(x, c) { return new u64((x.hi >>> c), (x.lo >>> c) | (x.hi << (32 - c))); } function xor64() { var l = 0, h = 0, i; for (i = 0; i < arguments.length; i++) { l ^= arguments[i].lo; h ^= arguments[i].hi; } return new u64(h, l); } function R(x, c) { var h, l, c1 = 32 - c; if (c < 32) { h = (x.hi >>> c) | (x.lo << c1); l = (x.lo >>> c) | (x.hi << c1); } else if (c < 64) { h = (x.lo >>> c) | (x.hi << c1); l = (x.hi >>> c) | (x.lo << c1); } return new u64(h, l); } function Ch(x, y, z) { var h = (x.hi & y.hi) ^ (~x.hi & z.hi), l = (x.lo & y.lo) ^ (~x.lo & z.lo); return new u64(h, l); } function Maj(x, y, z) { var h = (x.hi & y.hi) ^ (x.hi & z.hi) ^ (y.hi & z.hi), l = (x.lo & y.lo) ^ (x.lo & z.lo) ^ (y.lo & z.lo); return new u64(h, l); } function Sigma0(x) { return xor64(R(x,28), R(x,34), R(x,39)); } function Sigma1(x) { return xor64(R(x,14), R(x,18), R(x,41)); } function sigma0(x) { return xor64(R(x, 1), R(x, 8), shr64(x,7)); } function sigma1(x) { return xor64(R(x,19), R(x,61), shr64(x,6)); } var K = [ new u64(0x428a2f98, 0xd728ae22), new u64(0x71374491, 0x23ef65cd), new u64(0xb5c0fbcf, 0xec4d3b2f), new u64(0xe9b5dba5, 0x8189dbbc), new u64(0x3956c25b, 0xf348b538), new u64(0x59f111f1, 0xb605d019), new u64(0x923f82a4, 0xaf194f9b), new u64(0xab1c5ed5, 0xda6d8118), new u64(0xd807aa98, 0xa3030242), new u64(0x12835b01, 0x45706fbe), new u64(0x243185be, 0x4ee4b28c), new u64(0x550c7dc3, 0xd5ffb4e2), new u64(0x72be5d74, 0xf27b896f), new u64(0x80deb1fe, 0x3b1696b1), new u64(0x9bdc06a7, 0x25c71235), new u64(0xc19bf174, 0xcf692694), new u64(0xe49b69c1, 0x9ef14ad2), new u64(0xefbe4786, 0x384f25e3), new u64(0x0fc19dc6, 0x8b8cd5b5), new u64(0x240ca1cc, 0x77ac9c65), new u64(0x2de92c6f, 0x592b0275), new u64(0x4a7484aa, 0x6ea6e483), new u64(0x5cb0a9dc, 0xbd41fbd4), new u64(0x76f988da, 0x831153b5), new u64(0x983e5152, 0xee66dfab), new u64(0xa831c66d, 0x2db43210), new u64(0xb00327c8, 0x98fb213f), new u64(0xbf597fc7, 0xbeef0ee4), new u64(0xc6e00bf3, 0x3da88fc2), new u64(0xd5a79147, 0x930aa725), new u64(0x06ca6351, 0xe003826f), new u64(0x14292967, 0x0a0e6e70), new u64(0x27b70a85, 0x46d22ffc), new u64(0x2e1b2138, 0x5c26c926), new u64(0x4d2c6dfc, 0x5ac42aed), new u64(0x53380d13, 0x9d95b3df), new u64(0x650a7354, 0x8baf63de), new u64(0x766a0abb, 0x3c77b2a8), new u64(0x81c2c92e, 0x47edaee6), new u64(0x92722c85, 0x1482353b), new u64(0xa2bfe8a1, 0x4cf10364), new u64(0xa81a664b, 0xbc423001), new u64(0xc24b8b70, 0xd0f89791), new u64(0xc76c51a3, 0x0654be30), new u64(0xd192e819, 0xd6ef5218), new u64(0xd6990624, 0x5565a910), new u64(0xf40e3585, 0x5771202a), new u64(0x106aa070, 0x32bbd1b8), new u64(0x19a4c116, 0xb8d2d0c8), new u64(0x1e376c08, 0x5141ab53), new u64(0x2748774c, 0xdf8eeb99), new u64(0x34b0bcb5, 0xe19b48a8), new u64(0x391c0cb3, 0xc5c95a63), new u64(0x4ed8aa4a, 0xe3418acb), new u64(0x5b9cca4f, 0x7763e373), new u64(0x682e6ff3, 0xd6b2b8a3), new u64(0x748f82ee, 0x5defb2fc), new u64(0x78a5636f, 0x43172f60), new u64(0x84c87814, 0xa1f0ab72), new u64(0x8cc70208, 0x1a6439ec), new u64(0x90befffa, 0x23631e28), new u64(0xa4506ceb, 0xde82bde9), new u64(0xbef9a3f7, 0xb2c67915), new u64(0xc67178f2, 0xe372532b), new u64(0xca273ece, 0xea26619c), new u64(0xd186b8c7, 0x21c0c207), new u64(0xeada7dd6, 0xcde0eb1e), new u64(0xf57d4f7f, 0xee6ed178), new u64(0x06f067aa, 0x72176fba), new u64(0x0a637dc5, 0xa2c898a6), new u64(0x113f9804, 0xbef90dae), new u64(0x1b710b35, 0x131c471b), new u64(0x28db77f5, 0x23047d84), new u64(0x32caab7b, 0x40c72493), new u64(0x3c9ebe0a, 0x15c9bebc), new u64(0x431d67c4, 0x9c100d4c), new u64(0x4cc5d4be, 0xcb3e42b6), new u64(0x597f299c, 0xfc657e2a), new u64(0x5fcb6fab, 0x3ad6faec), new u64(0x6c44198c, 0x4a475817) ]; function crypto_hashblocks(x, m, n) { var z = [], b = [], a = [], w = [], t, i, j; for (i = 0; i < 8; i++) z[i] = a[i] = dl64(x, 8*i); var pos = 0; while (n >= 128) { for (i = 0; i < 16; i++) w[i] = dl64(m, 8*i+pos); for (i = 0; i < 80; i++) { for (j = 0; j < 8; j++) b[j] = a[j]; t = add64(a[7], Sigma1(a[4]), Ch(a[4], a[5], a[6]), K[i], w[i%16]); b[7] = add64(t, Sigma0(a[0]), Maj(a[0], a[1], a[2])); b[3] = add64(b[3], t); for (j = 0; j < 8; j++) a[(j+1)%8] = b[j]; if (i%16 === 15) { for (j = 0; j < 16; j++) { w[j] = add64(w[j], w[(j+9)%16], sigma0(w[(j+1)%16]), sigma1(w[(j+14)%16])); } } } for (i = 0; i < 8; i++) { a[i] = add64(a[i], z[i]); z[i] = a[i]; } pos += 128; n -= 128; } for (i = 0; i < 8; i++) ts64(x, 8*i, z[i]); return n; } var iv = new Uint8Array([ 0x6a,0x09,0xe6,0x67,0xf3,0xbc,0xc9,0x08, 0xbb,0x67,0xae,0x85,0x84,0xca,0xa7,0x3b, 0x3c,0x6e,0xf3,0x72,0xfe,0x94,0xf8,0x2b, 0xa5,0x4f,0xf5,0x3a,0x5f,0x1d,0x36,0xf1, 0x51,0x0e,0x52,0x7f,0xad,0xe6,0x82,0xd1, 0x9b,0x05,0x68,0x8c,0x2b,0x3e,0x6c,0x1f, 0x1f,0x83,0xd9,0xab,0xfb,0x41,0xbd,0x6b, 0x5b,0xe0,0xcd,0x19,0x13,0x7e,0x21,0x79 ]); function crypto_hash(out, m, n) { var h = new Uint8Array(64), x = new Uint8Array(256); var i, b = n; for (i = 0; i < 64; i++) h[i] = iv[i]; crypto_hashblocks(h, m, n); n %= 128; for (i = 0; i < 256; i++) x[i] = 0; for (i = 0; i < n; i++) x[i] = m[b-n+i]; x[n] = 128; n = 256-128*(n<112?1:0); x[n-9] = 0; ts64(x, n-8, new u64((b / 0x20000000) | 0, b << 3)); crypto_hashblocks(h, x, n); for (i = 0; i < 64; i++) out[i] = h[i]; return 0; } function add(p, q) { var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); Z(a, p[1], p[0]); Z(t, q[1], q[0]); M(a, a, t); A(b, p[0], p[1]); A(t, q[0], q[1]); M(b, b, t); M(c, p[3], q[3]); M(c, c, D2); M(d, p[2], q[2]); A(d, d, d); Z(e, b, a); Z(f, d, c); A(g, d, c); A(h, b, a); M(p[0], e, f); M(p[1], h, g); M(p[2], g, f); M(p[3], e, h); } function cswap(p, q, b) { var i; for (i = 0; i < 4; i++) { sel25519(p[i], q[i], b); } } function pack(r, p) { var tx = gf(), ty = gf(), zi = gf(); inv25519(zi, p[2]); M(tx, p[0], zi); M(ty, p[1], zi); pack25519(r, ty); r[31] ^= par25519(tx) << 7; } function scalarmult(p, q, s) { var b, i; set25519(p[0], gf0); set25519(p[1], gf1); set25519(p[2], gf1); set25519(p[3], gf0); for (i = 255; i >= 0; --i) { b = (s[(i/8)|0] >> (i&7)) & 1; cswap(p, q, b); add(q, p); add(p, p); cswap(p, q, b); } } function scalarbase(p, s) { var q = [gf(), gf(), gf(), gf()]; set25519(q[0], X); set25519(q[1], Y); set25519(q[2], gf1); M(q[3], X, Y); scalarmult(p, q, s); } function crypto_sign_keypair(pk, sk, seeded) { var d = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()]; var i; if (!seeded) randombytes(sk, 32); crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; scalarbase(p, d); pack(pk, p); for (i = 0; i < 32; i++) sk[i+32] = pk[i]; return 0; } var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); function modL(r, x) { var carry, i, j, k; for (i = 63; i >= 32; --i) { carry = 0; for (j = i - 32, k = i - 12; j < k; ++j) { x[j] += carry - 16 * x[i] * L[j - (i - 32)]; carry = (x[j] + 128) >> 8; x[j] -= carry * 256; } x[j] += carry; x[i] = 0; } carry = 0; for (j = 0; j < 32; j++) { x[j] += carry - (x[31] >> 4) * L[j]; carry = x[j] >> 8; x[j] &= 255; } for (j = 0; j < 32; j++) x[j] -= carry * L[j]; for (i = 0; i < 32; i++) { x[i+1] += x[i] >> 8; r[i] = x[i] & 255; } } function reduce(r) { var x = new Float64Array(64), i; for (i = 0; i < 64; i++) x[i] = r[i]; for (i = 0; i < 64; i++) r[i] = 0; modL(r, x); } // Note: difference from C - smlen returned, not passed as argument. function crypto_sign(sm, m, n, sk) { var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); var i, j, x = new Float64Array(64); var p = [gf(), gf(), gf(), gf()]; crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; var smlen = n + 64; for (i = 0; i < n; i++) sm[64 + i] = m[i]; for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; crypto_hash(r, sm.subarray(32), n+32); reduce(r); scalarbase(p, r); pack(sm, p); for (i = 32; i < 64; i++) sm[i] = sk[i]; crypto_hash(h, sm, n + 64); reduce(h); for (i = 0; i < 64; i++) x[i] = 0; for (i = 0; i < 32; i++) x[i] = r[i]; for (i = 0; i < 32; i++) { for (j = 0; j < 32; j++) { x[i+j] += h[i] * d[j]; } } modL(sm.subarray(32), x); return smlen; } function unpackneg(r, p) { var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); set25519(r[2], gf1); unpack25519(r[1], p); S(num, r[1]); M(den, num, D); Z(num, num, r[2]); A(den, r[2], den); S(den2, den); S(den4, den2); M(den6, den4, den2); M(t, den6, num); M(t, t, den); pow2523(t, t); M(t, t, num); M(t, t, den); M(t, t, den); M(r[0], t, den); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) M(r[0], r[0], I); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) return -1; if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); M(r[3], r[0], r[1]); return 0; } function crypto_sign_open(m, sm, n, pk) { var i, mlen; var t = new Uint8Array(32), h = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; mlen = -1; if (n < 64) return -1; if (unpackneg(q, pk)) return -1; for (i = 0; i < n; i++) m[i] = sm[i]; for (i = 0; i < 32; i++) m[i+32] = pk[i]; crypto_hash(h, m, n); reduce(h); scalarmult(p, q, h); scalarbase(q, sm.subarray(32)); add(p, q); pack(t, p); n -= 64; if (crypto_verify_32(sm, 0, t, 0)) { for (i = 0; i < n; i++) m[i] = 0; return -1; } for (i = 0; i < n; i++) m[i] = sm[i + 64]; mlen = n; return mlen; } var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; nacl.lowlevel = { crypto_core_hsalsa20: crypto_core_hsalsa20, crypto_stream_xor: crypto_stream_xor, crypto_stream: crypto_stream, crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, crypto_stream_salsa20: crypto_stream_salsa20, crypto_onetimeauth: crypto_onetimeauth, crypto_onetimeauth_verify: crypto_onetimeauth_verify, crypto_verify_16: crypto_verify_16, crypto_verify_32: crypto_verify_32, crypto_secretbox: crypto_secretbox, crypto_secretbox_open: crypto_secretbox_open, crypto_scalarmult: crypto_scalarmult, crypto_scalarmult_base: crypto_scalarmult_base, crypto_box_beforenm: crypto_box_beforenm, crypto_box_afternm: crypto_box_afternm, crypto_box: crypto_box, crypto_box_open: crypto_box_open, crypto_box_keypair: crypto_box_keypair, crypto_hash: crypto_hash, crypto_sign: crypto_sign, crypto_sign_keypair: crypto_sign_keypair, crypto_sign_open: crypto_sign_open, crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, crypto_sign_BYTES: crypto_sign_BYTES, crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, crypto_hash_BYTES: crypto_hash_BYTES }; /* High-level API */ function checkLengths(k, n) { if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); } function checkBoxLengths(pk, sk) { if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); } function checkArrayTypes() { for (var i = 0; i < arguments.length; i++) { if (!(arguments[i] instanceof Uint8Array)) throw new TypeError('unexpected type, use Uint8Array'); } } function cleanup(arr) { for (var i = 0; i < arr.length; i++) arr[i] = 0; } nacl.randomBytes = function(n) { var b = new Uint8Array(n); randombytes(b, n); return b; }; nacl.secretbox = function(msg, nonce, key) { checkArrayTypes(msg, nonce, key); checkLengths(key, nonce); var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); var c = new Uint8Array(m.length); for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; crypto_secretbox(c, m, m.length, nonce, key); return c.subarray(crypto_secretbox_BOXZEROBYTES); }; nacl.secretbox.open = function(box, nonce, key) { checkArrayTypes(box, nonce, key); checkLengths(key, nonce); var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); var m = new Uint8Array(c.length); for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; if (c.length < 32) return null; if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; return m.subarray(crypto_secretbox_ZEROBYTES); }; nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; nacl.scalarMult = function(n, p) { checkArrayTypes(n, p); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult(q, n, p); return q; }; nacl.scalarMult.base = function(n) { checkArrayTypes(n); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult_base(q, n); return q; }; nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; nacl.box = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox(msg, nonce, k); }; nacl.box.before = function(publicKey, secretKey) { checkArrayTypes(publicKey, secretKey); checkBoxLengths(publicKey, secretKey); var k = new Uint8Array(crypto_box_BEFORENMBYTES); crypto_box_beforenm(k, publicKey, secretKey); return k; }; nacl.box.after = nacl.secretbox; nacl.box.open = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox.open(msg, nonce, k); }; nacl.box.open.after = nacl.secretbox.open; nacl.box.keyPair = function() { var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); crypto_box_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.box.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); crypto_scalarmult_base(pk, secretKey); return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; nacl.box.nonceLength = crypto_box_NONCEBYTES; nacl.box.overheadLength = nacl.secretbox.overheadLength; nacl.sign = function(msg, secretKey) { checkArrayTypes(msg, secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); crypto_sign(signedMsg, msg, msg.length, secretKey); return signedMsg; }; nacl.sign.open = function(signedMsg, publicKey) { checkArrayTypes(signedMsg, publicKey); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var tmp = new Uint8Array(signedMsg.length); var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); if (mlen < 0) return null; var m = new Uint8Array(mlen); for (var i = 0; i < m.length; i++) m[i] = tmp[i]; return m; }; nacl.sign.detached = function(msg, secretKey) { var signedMsg = nacl.sign(msg, secretKey); var sig = new Uint8Array(crypto_sign_BYTES); for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; return sig; }; nacl.sign.detached.verify = function(msg, sig, publicKey) { checkArrayTypes(msg, sig, publicKey); if (sig.length !== crypto_sign_BYTES) throw new Error('bad signature size'); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var sm = new Uint8Array(crypto_sign_BYTES + msg.length); var m = new Uint8Array(crypto_sign_BYTES + msg.length); var i; for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); }; nacl.sign.keyPair = function() { var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); crypto_sign_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.sign.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.sign.keyPair.fromSeed = function(seed) { checkArrayTypes(seed); if (seed.length !== crypto_sign_SEEDBYTES) throw new Error('bad seed size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); for (var i = 0; i < 32; i++) sk[i] = seed[i]; crypto_sign_keypair(pk, sk, true); return {publicKey: pk, secretKey: sk}; }; nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; nacl.sign.seedLength = crypto_sign_SEEDBYTES; nacl.sign.signatureLength = crypto_sign_BYTES; nacl.hash = function(msg) { checkArrayTypes(msg); var h = new Uint8Array(crypto_hash_BYTES); crypto_hash(h, msg, msg.length); return h; }; nacl.hash.hashLength = crypto_hash_BYTES; nacl.verify = function(x, y) { checkArrayTypes(x, y); // Zero length arguments are considered not equal. if (x.length === 0 || y.length === 0) return false; if (x.length !== y.length) return false; return (vn(x, 0, y, 0, x.length) === 0) ? true : false; }; nacl.setPRNG = function(fn) { randombytes = fn; }; (function() { // Initialize PRNG if environment provides CSPRNG. // If not, methods calling randombytes will throw. var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; if (crypto && crypto.getRandomValues) { // Browsers. var QUOTA = 65536; nacl.setPRNG(function(x, n) { var i, v = new Uint8Array(n); for (i = 0; i < n; i += QUOTA) { crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); } for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } else if (typeof require !== 'undefined') { // Node.js. crypto = require('crypto'); if (crypto && crypto.randomBytes) { nacl.setPRNG(function(x, n) { var i, v = crypto.randomBytes(n); for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } } })(); })(typeof module !== 'undefined' && module.exports ? module.exports : (self._nacl = self._nacl || {})); """) __pragma__("js", "{}",""" export const api = self._nacl; """)
""" N : 1 * 2 * 3 * .... * N """ def factorial(n: int) -> int: result = 1 for i in range(1, n + 1): result *= i return result """ nPr = n! / (n - r)! """ def permutation(n: int, r: int) -> int: return factorial(n) // factorial(n - r) # return 24 // factorial(n - r) # return 24 // factorial(2) # return 24 // 2 # return 12 # nCr = nPr / r! def combination(n: int, r: int) -> int: return permutation(n, r) // factorial(r) print(combination(4, 0)) print(combination(4, 1)) print(combination(4, 2)) print(combination(4, 3)) print(combination(4, 4))
''' Example: import dk cfg = dk.load_config(config_path='~/donkeycar/donkeycar/parts/RLConfig.py') print(cfg.CAMERA_RESOLUTION) ''' MODE_COMPLEX_LANE_FOLLOW = 0 MODE_SIMPLE_LINE_FOLLOW = 1 MODE_STEER_THROTTLE = MODE_COMPLEX_LANE_FOLLOW # MODE_STEER_THROTTLE = MODE_SIMPLE_LINE_FOLLOW PARTIAL_NN_CNT = 45000 # SWITCH_TO_NN = 45000 # SWITCH_TO_NN = 15000 # SWITCH_TO_NN = 9000 # SWITCH_TO_NN = 6000 # SWITCH_TO_NN = 300 # SWITCH_TO_NN = 10 # SWITCH_TO_NN = 100 # SWITCH_TO_NN = 150 # SWITCH_TO_NN = 7500 # SWITCH_TO_NN = 3000 SWITCH_TO_NN = 1000 UPDATE_NN = 1000 # UPDATE_NN = 100 SAVE_NN = 1000 THROTTLE_CONSTANT = 0 # THROTTLE_CONSTANT = .3 STATE_EMERGENCY_STOP = 0 STATE_NN = 1 STATE_OPENCV = 2 STATE_MODEL_TRANSFER_STARTED = 3 STATE_MODEL_PREPARE_NN = 4 STATE_MODEL_WEIGHTS_SET = 5 STATE_PARTIAL_NN = 6 STATE_TRIAL_NN = 7 EMERGENCY_STOP = 0.000001 SIM_EMERGENCY_STOP = -1000 # DISABLE_EMERGENCY_STOP = True DISABLE_EMERGENCY_STOP = False # USE_COLOR = False USE_COLOR = True # HSV # Note: The YELLOW/WHITE parameters are longer used and are now dynamically computed # from simulation: # line_color_y: [[84, 107, 148], [155, 190, 232]] # line_color_w: [[32, 70, 101], [240, 240, 248]] # COLOR_YELLOW = [[20, 80, 100], [35, 255, 255]] # COLOR_YELLOW = [[20, 0, 100], [30, 255, 255]] # COLOR_YELLOW = [[20, 40, 70], [70, 89, 95]] COLOR_YELLOW = [[84, 107, 148], [155, 190, 232]] # COLOR_YELLOW = 50, 75, 83 # using saturation 40 for WHITE # COLOR_WHITE = [[0,0,255-40],[255,40,255]] # COLOR_WHITE = [[50,0,80],[155,10,100]] COLOR_WHITE = [[32, 70, 101], [240, 240, 248]] # COLOR_WHITE = 72,2, 90] TURNADJ = .02 # DESIREDPPF = 35 DESIREDPPF = 20 # MAXBATADJ = .10 # BATADJ = .001 MAXBATADJ = .000 # simulation doesn't have battery BATADJ = .000 # simulation doesn't have battery RL_MODEL_PATH = "~/d2/models/rlpilot" RL_STATE_PATH = "~/d2/models/" MAXBATCNT = 1000 # MINMINTHROT = 0.035 # for Sim MINMINTHROT = 0.05 # for Sim # OPTFLOWTHRESH = 0.75 # for Sim OPTFLOWTHRESH = 0.14 # for Sim OPTFLOWINCR = 0.01 # for Sim # OPTFLOWINCR = 0.01 # for Sim # MINMINTHROT = 25 # real car # MINMINTHROT = 29 # real car # OPTFLOWTHRESH = 0.40 # real # OPTFLOWINCR = 0.001 # MAX_ACCEL = 10 MAX_ACCEL = 3 # CHECK_THROTTLE_THRESH = 20 CHECK_THROTTLE_THRESH = 40 MAXLANEWIDTH = 400 # should be much smaller MIN_DIST_FROM_CENTER = 20 # client to server MSG_NONE = -1 MSG_GET_WEIGHTS = 1 MSG_STATE_ANGLE_THROTTLE_REWARD_ROI = 2 # server to client MSG_RESULT = 4 MSG_WEIGHTS = 5 MSG_EMERGENCY_STOP = 6 # control1 to control2 MSG_ROI = 7 # control2 to control1 MSG_ANGLE_THROTTLE_REWARD = 8 # RLPi States RLPI_READY1 = 1 RLPI_READY2 = 2 RLPI_OPENCV = 1 RLPI_TRIAL_NN = 2 RLPI_NN = 3 # PORT_RLPI = "10.0.0.5:5557" # PORT_RLPI = "localhost:5557" # PORT_CONTROLPI = "localhost:5558" PORT_RLPI = 5557 PORT_CONTROLPI = 5558 PORT_CONTROLPI2 = None PORT_CONTROLPI2RL = None # PORT_CONTROLPI2 = 5556 # PORT_CONTROLPI2RL = 5555 # Original reward for throttle was too high. Reduce. # THROTTLE_INCREMENT = .4 # THROTTLE_BOOST = .1 THROTTLE_INCREMENT = .3 THROTTLE_BOOST = .05 REWARD_BATCH_MIN = 3 REWARD_BATCH_MAX = 10 REWARD_BATCH_END = 50 REWARD_BATCH_BEGIN = 500 # pass angle bin back and forth; based on 15 bins ANGLE_INCREMENT = (1/15) SAVE_MOVIE = False # SAVE_MOVIE = True TEST_TUB = "/home/ros/d2/data/tub_18_18-08-18" MOVIE_LOC = "/tmp/movie4" # to make movie from jpg in MOVIE_LOC use something like: # ffmpeg -framerate 4 -i /tmp/movie4/1%03d_cam-image_array_.jpg -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p output.mp4 # INIT_STEER_FRAMES = 25 INIT_STEER_FRAMES = 125 # For PPO Q_LEN_THRESH = 200 Q_LEN_MAX = 250 # Almost all initial batches were under 20 Q_FIT_BATCH_LEN_THRESH = 50 # Very short batches to compute rewards are likely "car resets" # maybe should be 5 Q_MIN_ACTUAL_BATCH_LEN = 4 RWD_LOW = 10 RWD_HIGH = 500 RWD_HIGH_THRESH = 3 DISCOUNT_FACTOR = .8
def build_filter(args): return Filter(args) class Filter: def __init__(self, args): pass def file_data_filter(self, file_data): file_ctx = file_data["file_ctx"] if not file_ctx.isbinary(): file_data["data"] = file_data["data"].replace(b"\r\n", b"\n")