content
stringlengths
7
1.05M
# Cache bitcode CACHE = False # Save object file for module ASM = False # Write LLVM dump to file DUMP = True # Enable AST debugging dump DEBUG = True # Write dump files to same directory as module? # if False, this will write all dumps to one "debug" file in the main dir DUMP_TO_DIR = False
nome = str(input('Qual é o seu nome: ')) if nome == 'Gustavo': print('Seu nome é legal!') else: print('Seu nome é normal!') print('Bom dia, {}!'.format(nome))
""" Batch processing examples - Griatch 2012 """
''' Common settings for using in a project scope ''' MODEL_ZIP_FILE_NAME_ENV_VAR = 'TF_AWS_MODEL_ZIP_FILE_NAME' MODEL_PROTOBUF_FILE_NAME_ENV_VAR = 'TF_AWS_MODEL_PROTOBUF_FILE_NAME' S3_MODEL_BUCKET_NAME_ENV_VAR = 'TF_AWS_S3_MODEL_BUCKET_NAME'
# Vitauts def is_pangram_en(mytext, a=set('abcdefghijklmnopqrstuvwxyz')): return len(set(mytext.lower()).intersection(a)) == 26 def is_pangram_lv(mytext, a='aābcčdeēfgģhiījkķlļmnņoprsštuūvzž'): return len(set(mytext.lower()).intersection(a)) == 33 def main(): print(is_pangram_en('The quick brown fox jumps over the lazy dog')) # -> true # -> false print(is_pangram_en('The quick brown fox jumps over the dog')) print(is_pangram_en('The five boxing wizards jump quickly') ) # -> true print(is_pangram_lv('Tfū, čeh, džungļos blīkšķ, zvaņģim jācērp!')) # -> true print(is_pangram_lv('Čehu zeņķi ģērbj plīša frakā, mūc džungļos, tēv!')) # -> true print(is_pangram_lv('Parasts teikums, kas nav pangramma.') ) # -> false if __name__ == "__main__": main()
expected_output = { 'pid': 'CISCO3945-CHASSIS', 'os': 'ios', 'platform': 'c3900', 'version': '15.0(1)M7', }
class RobertException(Exception): def __init__(self, message: str = None): message = 'An fatal error has occurred' if message is None else message super().__init__(message) class LanguageNotSupported(RobertException): def __init__(self): super().__init__('That language is not supported') class UnknownSafeSearchType(RobertException): def __init__(self, type): super().__init__(f'Safe search {type} does not exist')
# TODO: Use these simplified dataclasses once support for Python 3.6 is # dropped. Meanwhile we'll use the "polyfill" classes defined below. # # from dataclasses import dataclass, field # # @dataclass # class Client: # user_id: str # user_type: str = field(default="client", init=False) # # # @dataclass # class Team: # user_id: str # user_type: str = field(default="team", init=False) # # # @dataclass # class User: # user_id: str # user_type: str = field(default="user", init=False) class Client: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "client" class Team: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "team" class User: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "user" def asdict(obj): return obj.__dict__
def update_dict(old_dict, values): """ Update dictionary without change the original object """ new_dict = old_dict.copy() new_dict.update(values) return new_dict
add = 3+2 print (add) subtract = 3-2 print (subtract) multiply = 3*2 print (multiply) division = 3/2 print (division) modulus = 3%2 print (modulus) lessThan = 3<2 print (lessThan) greaterThan = 3>2 print(greaterThan) equals = 3==3 print (equals) logicalAnd = (2==2) and (3==3) and (4==4) print (logicalAnd) logicalOr = (2==1) or (2==2) or (2==3) print (logicalOr) logicalNot = not (3==2) print (logicalNot)
#!/usr/bin/env python3 #variable delaration names = [] address = [] age = [] institute = [] dept = [] print('------+++++++Welcome to student info software+++++++------\n') names.insert(0, input('Enter your Full name: ')) address.insert(0, input('Enter your Address: ')) age.insert(0, input('Enter your Age: ')) institute.insert(0, input('Enter your School: ')) dept.insert(0, input('Enter your Departiment: ')) print('\n\n') print('-----+++++Your information is below+++++-----\n') print("Name is: {} \nAddress is: {} \nAge is: {} \nInstitute is: {} \nDept is: {}".format(names,address,age,institute,dept))
def valid_palindrome(str): left, right = 0, len(str) - 1 while left < right: if not str[left].isalnum(): left += 1 elif not str[right].isalnum(): right -= 1 else: if str[left].lower() != str[right].lower(): print('False') return False else: left += 1 right -= 1 print('True') return True test = "A man, a plan, a canal: Panama" valid_palindrome(test)
{ 4 : { "operator" : "aggregation", "numgroups" : 1000000 } }
def get_numbers_between(set_a, set_b): numbers_between = 0 for candidate in range(1, 101): found = True for item in set_a: if candidate % item: found = False break if not found: continue for item in set_b: if item % candidate: found = False break if found: numbers_between += 1 return numbers_between if __name__ == "__main__": n, m = input().strip().split(' ') n, m = [int(n), int(m)] a = list(map(int, input().strip().split(' '))) b = list(map(int, input().strip().split(' '))) total = get_numbers_between(a, b) print(total)
""" For each single peak, set a probability distribution over all the possibile assignment. Given a function phi(p,p') = {1/dist(p, p')} / {\sum_s 1/dist(p, s)} definiamo le probabilità in base allo scarto con il valor medio anzichè assegnare il particolare picco tale per cui lo scarto con il valor medio sia minimo, ovvero che minimizzi la seguente funzione di costo: cost(p,p') = ||csp(i) - avg_csp(i)||, noi definiamo una distribuzione di probabilità P = {1/cost(p, p')} / {\sum_s 1/cost(p, s)} Poi realizziamo gli assegnamenti usando beam-search Quindi aggiorniamo tutte le distribuzioni Ripetiamo la cosa fino a convergenza. """
socket_to_sc = {} # 已建立的安全通道列表 # 不一定是登入状态,只是连接 scs = [] def remove_sc_from_socket_mapping(sc): if sc in scs: scs.remove(sc) if sc.socket in socket_to_sc: del socket_to_sc[sc.socket]
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def python_dependencies_early(): http_archive( name = "rules_python", url = "https://github.com/bazelbuild/rules_python/releases/download/0.0.1/rules_python-0.0.1.tar.gz", sha256 = "aa96a691d3a8177f3215b14b0edc9641787abaaa30363a080165d06ab65e1161", )
# Pow(x, n): https://leetcode.com/problems/powx-n/ # Implement pow(x, n), which calculates x raised to the power n (i.e., xn). # This problem is pretty straight forward we simply iterate over the n times # multiplying the input every time. The only tricky thing is that if we have # a negative number we need to make sure to set it to 1/x before multiplying together class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1.0 if x == 0: return 0 if n < 0: x = 1/x n *= -1 result = 1 for _ in range(n): result *= x return result # The above works! The code runs in o(N) steps and uses o(1) space the problem is this isn't the fastest we can do! # This is based off of the math that 2 ^ 10 == 4 ^ 5 = 4 * 16 ^ 2 = 4 * 256 ^ 1 = 1024 # If you look at the above we can reduce n by half in every single iteration which means that we can have a resulting # o(logn) solution def myPowOptimus(self, x: float, n: int) -> float: if n == 0: return 1.0 if x == 0: return 0 if n < 0: x = 1/x n *= -1 result = 1.0 current = x index = n while index > 0: # If we have an odd number we mutliply the result times the current factor so we can make our factor even # so we can multiply it by itslef to reduce to half if index % 2 == 1: result = result * current # Multiply current by current to reduce exponent in half current = current * current # Make sure our iterator is decreased by half index = index // 2 return result # Score Card # Did I need hints? Yes because I forgot that I switched my index to equal n to make things more clear # Did you finish within 30 min? 20 # Was the solution optimal? Oh yeah this runs in o(logn) and o(1) # Were there any bugs? Yeah i forgot to make my odd exponent check use the right variable # 3 5 5 3 = 4
# User input num1=float(input("Enter the 1st number: ")) num2=float(input("Enter your 2nd number: ")) # Operations the program should perform sum = num1 + num2 difference = num1 - num2 product = num1 * num2 divide = num1 / num2 modulus = num1 % num2 # Computer output print(sum) print(difference) print(product) print(divide) print(modulus)
def main(): print("Iterative:") print("n=0 ->", fibonacci_iterative(0)) print("n=1 ->", fibonacci_iterative(1)) print("n=6 ->", fibonacci_iterative(6)) print() print("Recursive:") print("n=0 ->", fibonacci_recursive(0)) print("n=1 ->", fibonacci_recursive(1)) print("n=6 ->", fibonacci_recursive(6)) def fibonacci_iterative(n): fib = [0, 1] if n < 2: return fib[n] for i in range(n - 1): fib.append(fib[i] + fib[i + 1]) return fib[n] def fibonacci_recursive(n): if n < 2: return n return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1) main()
wanted_income = float(input()) total_income = 0 cocktail = input() while cocktail != "Party!": order = int(input()) cocktail_price = len(cocktail) cocktail_price = order * cocktail_price if cocktail_price % 2 != 0: discount = cocktail_price - (cocktail_price * 0.25) total_income += discount else: total_income += cocktail_price if total_income >= wanted_income: break cocktail = input() if cocktail == "Party!": print(f"We need {wanted_income - total_income:.2f} leva more.") elif total_income >= wanted_income: print("Target acquired.") print(f"Club income - {total_income:.2f} leva.")
#!/usr/bin/env python3 strings = [ "sszojmmrrkwuftyv", "isaljhemltsdzlum", "fujcyucsrxgatisb", "qiqqlmcgnhzparyg", "oijbmduquhfactbc", "jqzuvtggpdqcekgk", "zwqadogmpjmmxijf", "uilzxjythsqhwndh", "gtssqejjknzkkpvw", "wrggegukhhatygfi", "vhtcgqzerxonhsye", "tedlwzdjfppbmtdx", "iuvrelxiapllaxbg", "feybgiimfthtplui", "qxmmcnirvkzfrjwd", "vfarmltinsriqxpu", "oanqfyqirkraesfq", "xilodxfuxphuiiii", "yukhnchvjkfwcbiq", "bdaibcbzeuxqplop", "ivegnnpbiyxqsion", "ybahkbzpditgwdgt", "dmebdomwabxgtctu", "ibtvimgfaeonknoh", "jsqraroxudetmfyw", "dqdbcwtpintfcvuz", "tiyphjunlxddenpj", "fgqwjgntxagidhah", "nwenhxmakxqkeehg", "zdoheaxqpcnlhnen", "tfetfqojqcdzlpbm", "qpnxkuldeiituggg", "xwttlbdwxohahwar", "hjkwzadmtrkegzye", "koksqrqcfwcaxeof", "wulwmrptktliyxeq", "gyufbedqhhyqgqzj", "txpunzodohikzlmj", "jloqfuejfkemcrvu", "amnflshcheuddqtc", "pdvcsduggcogbiia", "yrioavgfmeafjpcz", "uyhbtmbutozzqfvq", "mwhgfwsgyuwcdzik", "auqylgxhmullxpaa", "lgelzivplaeoivzh", "uyvcepielfcmswoa", "qhirixgwkkccuzlp", "zoonniyosmkeejfg", "iayfetpixkedyana", "ictqeyzyqswdskiy", "ejsgqteafvmorwxe", "lhaiqrlqqwfbrqdx", "ydjyboqwhfpqfydc", "dwhttezyanrnbybv", "edgzkqeqkyojowvr", "rmjfdwsqamjqehdq", "ozminkgnkwqctrxz", "bztjhxpjthchhfcd", "vrtioawyxkivrpiq", "dpbcsznkpkaaclyy", "vpoypksymdwttpvz", "hhdlruwclartkyap", "bqkrcbrksbzcggbo", "jerbbbnxlwfvlaiw", "dwkasufidwjrjfbf", "kkfxtjhbnmqbmfwf", "vmnfziwqxmioukmj", "rqxvcultipkecdtu", "fhmfdibhtjzkiqsd", "hdpjbuzzbyafqrpd", "emszboysjuvwwvts", "msyigmwcuybfiooq", "druyksfnbluvnwoh", "fvgstvynnfbvxhsx", "bmzalvducnqtuune", "lzwkzfzttsvpllei", "olmplpvjamynfyfd", "padcwfkhystsvyfb", "wjhbvxkwtbfqdilb", "hruaqjwphonnterf", "bufjobjtvxtzjpmj", "oiedrjvmlbtwyyuy", "sgiemafwfztwsyju", "nsoqqfudrtwszyqf", "vonbxquiiwxnazyl", "yvnmjxtptujwqudn", "rrnybqhvrcgwvrkq", "taktoxzgotzxntfu", "quffzywzpxyaepxa", "rfvjebfiddcfgmwv", "iaeozntougqwnzoh", "scdqyrhoqmljhoil", "bfmqticltmfhxwld", "brbuktbyqlyfpsdl", "oidnyhjkeqenjlhd", "kujsaiqojopvrygg", "vebzobmdbzvjnjtk", "uunoygzqjopwgmbg", "piljqxgicjzgifso", "ikgptwcjzywswqnw", "pujqsixoisvhdvwi", "trtuxbgigogfsbbk", "mplstsqclhhdyaqk", "gzcwflvmstogdpvo", "tfjywbkmimyyqcjd", "gijutvhruqcsiznq", "ibxkhjvzzxgavkha", "btnxeqvznkxjsgmq", "tjgofgauxaelmjoq", "sokshvyhlkxerjrv", "ltogbivktqmtezta", "uduwytzvqvfluyuf", "msuckpthtgzhdxan", "fqmcglidvhvpirzr", "gwztkqpcwnutvfga", "bsjfgsrntdhlpqbx", "xloczbqybxmiopwt", "orvevzyjliomkkgu", "mzjbhmfjjvaziget", "tlsdxuhwdmghdyjb", "atoecyjhwmznaewi", "pyxpyvvipbqibiox", "ajbfmpqqobfsmesj", "siknbzefjblnohgd", "eqfhgewbblwdfkmc", "opylbscrotckkrbk", "lbwxbofgjkzdxkle", "ceixfjstaptdomvm", "hnkrqxifjmmjktie", "aqykzeuzvvetoygd", "fouahjimfcisxima", "prkzhutbqsyrhjzx", "qqwliakathnsbzne", "sayhgqtlcqqidqhj", "ygduolbysehdudra", "zricvxhdzznuxuce", "ucvzakslykpgsixd", "udirhgcttmyspgsb", "yuwzppjzfsjhhdzi", "gtqergjiuwookwre", "xvxexbjyjkxovvwf", "mlpaqhnnkqxrmwmm", "ezuqbrjozwuqafhb", "mcarusdthcbsonoq", "weeguqeheeiigrue", "pngtfugozxofaqxv", "copphvbjcmfspenv", "jiyahihykjjkdaya", "gdqnmesvptuyrfwp", "vbdscfywqmfxbohh", "crtrfuxyjypzubrg", "seihvevtxywxhflp", "fvvpmgttnapklwou", "qmqaqsajmqwhetpk", "zetxvrgjmblxvakr", "kpvwblrizaabmnhz", "mwpvvzaaicntrkcp", "clqyjiegtdsswqfm", "ymrcnqgcpldgfwtm", "nzyqpdenetncgnwq", "cmkzevgacnmdkqro", "kzfdsnamjqbeirhi", "kpxrvgvvxapqlued", "rzskbnfobevzrtqu", "vjoahbfwtydugzap", "ykbbldkoijlvicbl", "mfdmroiztsgjlasb", "quoigfyxwtwprmdr", "ekxjqafwudgwfqjm", "obtvyjkiycxfcdpb", "lhoihfnbuqelthof", "eydwzitgxryktddt", "rxsihfybacnpoyny", "bsncccxlplqgygtw", "rvmlaudsifnzhcqh", "huxwsyjyebckcsnn", "gtuqzyihwhqvjtes", "zreeyomtngvztveq", "nwddzjingsarhkxb", "nuqxqtctpoldrlsh", "wkvnrwqgjooovhpf", "kwgueyiyffudtbyg", "tpkzapnjxefqnmew", "ludwccvkihagvxal", "lfdtzhfadvabghna", "njqmlsnrkcfhtvbb", "cajzbqleghhnlgap", "vmitdcozzvqvzatp", "eelzefwqwjiywbcz", "uyztcuptfqvymjpi", "aorhnrpkjqqtgnfo", "lfrxfdrduoeqmwwp", "vszpjvbctblplinh", "zexhadgpqfifcqrz", "ueirfnshekpemqua", "qfremlntihbwabtb", "nwznunammfexltjc", "zkyieokaaogjehwt", "vlrxgkpclzeslqkq", "xrqrwfsuacywczhs", "olghlnfjdiwgdbqc", "difnlxnedpqcsrdf", "dgpuhiisybjpidsj", "vlwmwrikmitmoxbt", "sazpcmcnviynoktm", "pratafauetiknhln", "ilgteekhzwlsfwcn", "ywvwhrwhkaubvkbl", "qlaxivzwxyhvrxcf", "hbtlwjdriizqvjfb", "nrmsononytuwslsa", "mpxqgdthpoipyhjc", "mcdiwmiqeidwcglk", "vfbaeavmjjemfrmo", "qzcbzmisnynzibrc", "shzmpgxhehhcejhb", "wirtjadsqzydtyxd", "qjlrnjfokkqvnpue", "dxawdvjntlbxtuqc", "wttfmnrievfestog", "eamjfvsjhvzzaobg", "pbvfcwzjgxahlrag", "omvmjkqqnobvnzkn", "lcwmeibxhhlxnkzv", "uiaeroqfbvlazegs", "twniyldyuonfyzqw", "wgjkmsbwgfotdabi", "hnomamxoxvrzvtew", "ycrcfavikkrxxfgw", "isieyodknagzhaxy", "mgzdqwikzullzyco", "mumezgtxjrrejtrs", "nwmwjcgrqiwgfqel", "wjgxmebfmyjnxyyp", "durpspyljdykvzxf", "zuslbrpooyetgafh", "kuzrhcjwbdouhyme", "wyxuvbciodscbvfm", "kbnpvuqwmxwfqtqe", "zddzercqogdpxmft", "sigrdchxtgavzzjh", "lznjolnorbuddgcs", "ycnqabxlcajagwbt", "bnaudeaexahdgxsj", "rlnykxvoctfwanms", "jngyetkoplrstfzt", "tdpxknwacksotdub", "yutqgssfoptvizgr", "lzmqnxeqjfnsxmsa", "iqpgfsfmukovsdgu", "qywreehbidowtjyz", "iozamtgusdctvnkw", "ielmujhtmynlwcfd", "hzxnhtbnmmejlkyf", "ftbslbzmiqkzebtd", "bcwdqgiiizmohack", "dqhfkzeddjzbdlxu", "mxopokqffisxosci", "vciatxhtuechbylk", "khtkhcvelidjdena", "blatarwzfqcapkdt", "elamngegnczctcck", "xeicefdbwrxhuxuf", "sawvdhjoeahlgcdr", "kmdcimzsfkdfpnir", "axjayzqlosrduajb", "mfhzreuzzumvoggr", "iqlbkbhrkptquldb", "xcvztvlshiefuhgb", "pkvwyqmyoazocrio", "ajsxkdnerbmhyxaj", "tudibgsbnpnizvsi", "cxuiydkgdccrqvkh", "cyztpjesdzmbcpot", "nnazphxpanegwitx", "uphymczbmjalmsct", "yyxiwnlrogyzwqmg", "gmqwnahjvvdyhnfa", "utolskxpuoheugyl", "mseszdhyzoyavepd", "ycqknvbuvcjfgmlc", "sknrxhxbfpvpeorn", "zqxqjetooqcodwml", "sesylkpvbndrdhsy", "fryuxvjnsvnjrxlw", "mfxusewqurscujnu", "mbitdjjtgzchvkfv", "ozwlyxtaalxofovd", "wdqcduaykxbunpie", "rlnhykxiraileysk", "wgoqfrygttlamobg", "kflxzgxvcblkpsbz", "tmkisflhativzhde", "owsdrfgkaamogjzd", "gaupjkvkzavhfnes", "wknkurddcknbdleg", "lltviwincmbtduap", "qwzvspgbcksyzzmb", "ydzzkumecryfjgnk", "jzvmwgjutxoysaam", "icrwpyhxllbardkr", "jdopyntshmvltrve", "afgkigxcuvmdbqou", "mfzzudntmvuyhjzt", "duxhgtwafcgrpihc", "tsnhrkvponudumeb", "sqtvnbeiigdzbjgv", "eczmkqwvnsrracuo", "mhehsgqwiczaiaxv", "kaudmfvifovrimpd", "lupikgivechdbwfr", "mwaaysrndiutuiqx", "aacuiiwgaannunmm", "tjqjbftaqitukwzp", "lrcqyskykbjpaekn", "lirrvofbcqpjzxmr", "jurorvzpplyelfml", "qonbllojmloykjqe", "sllkzqujfnbauuqp", "auexjwsvphvikali", "usuelbssqmbrkxyc", "wyuokkfjexikptvv", "wmfedauwjgbrgytl", "sfwvtlzzebxzmuvw", "rdhqxuechjsjcvaf", "kpavhqkukugocsxu", "ovnjtumxowbxduts", "zgerpjufauptxgat", "pevvnzjfwhjxdoxq", "pmmfwxajgfziszcs", "difmeqvaghuitjhs", "icpwjbzcmlcterwm", "ngqpvhajttxuegyh", "mosjlqswdngwqsmi", "frlvgpxrjolgodlu", "eazwgrpcxjgoszeg", "bbtsthgkjrpkiiyk", "tjonoglufuvsvabe", "xhkbcrofytmbzrtk", "kqftfzdmpbxjynps", "kmeqpocbnikdtfyv", "qjjymgqxhnjwxxhp", "dmgicrhgbngdtmjt", "zdxrhdhbdutlawnc", "afvoekuhdboxghvx", "hiipezngkqcnihty", "bbmqgheidenweeov", "suprgwxgxwfsgjnx", "adeagikyamgqphrj", "zzifqinoeqaorjxg", "adhgppljizpaxzld", "lvxyieypvvuqjiyc", "nljoakatwwwoovzn", "fcrkfxclcacshhmx", "ownnxqtdhqbgthch", "lmfylrcdmdkgpwnj", "hlwjfbvlswbzpbjr", "mkofhdtljdetcyvp", "synyxhifbetzarpo", "agnggugngadrcxoc", "uhttadmdmhidpyjw", "ohfwjfhunalbubpr", "pzkkkkwrlvxiuysn", "kmidbxmyzkjrwjhu", "egtitdydwjxmajnw", "civoeoiuwtwgbqqs", "dfptsguzfinqoslk", "tdfvkreormspprer", "zvnvbrmthatzztwi", "ffkyddccrrfikjde", "hrrmraevdnztiwff", "qaeygykcpbtjwjbr", "purwhitkmrtybslh", "qzziznlswjaussel", "dfcxkvdpqccdqqxj", "tuotforulrrytgyn", "gmtgfofgucjywkev", "wkyoxudvdkbgpwhd", "qbvktvfvipftztnn", "otckgmojziezmojb", "inxhvzbtgkjxflay", "qvxapbiatuudseno", "krpvqosbesnjntut", "oqeukkgjsfuqkjbb", "prcjnyymnqwqksiz", "vuortvjxgckresko", "orqlyobvkuwgathr", "qnpyxlnazyfuijox", "zwlblfkoklqmqzkw", "hmwurwtpwnrcsanl", "jzvxohuakopuzgpf", "sfcpnxrviphhvxmx", "qtwdeadudtqhbely", "dbmkmloasqphnlgj", "olylnjtkxgrubmtk", "nxsdbqjuvwrrdbpq", "wbabpirnpcsmpipw", "hjnkyiuxpqrlvims", "enzpntcjnxdpuqch", "vvvqhlstzcizyimn", "triozhqndbttglhv", "fukvgteitwaagpzx", "uhcvukfbmrvskpen", "tizcyupztftzxdmt", "vtkpnbpdzsaluczz", "wodfoyhoekidxttm", "otqocljrmwfqbxzu", "linfbsnfvixlwykn", "vxsluutrwskslnye", "zbshygtwugixjvsi", "zdcqwxvwytmzhvoo", "wrseozkkcyctrmei", "fblgtvogvkpqzxiy", "opueqnuyngegbtnf", "qxbovietpacqqxok", "zacrdrrkohfygddn", "gbnnvjqmkdupwzpq", "qgrgmsxeotozvcak", "hnppukzvzfmlokid", "dzbheurndscrrtcl", "wbgdkadtszebbrcw", "fdmzppzphhpzyuiz", "bukomunhrjrypohj", "ohodhelegxootqbj", "rsplgzarlrknqjyh", "punjjwpsxnhpzgvu", "djdfahypfjvpvibm", "mlgrqsmhaozatsvy", "xwktrgyuhqiquxgn", "wvfaoolwtkbrisvf", "plttjdmguxjwmeqr", "zlvvbwvlhauyjykw", "cigwkbyjhmepikej", "masmylenrusgtyxs", "hviqzufwyetyznze", "nzqfuhrooswxxhus", "pdbdetaqcrqzzwxf", "oehmvziiqwkzhzib", "icgpyrukiokmytoy", "ooixfvwtiafnwkce", "rvnmgqggpjopkihs", "wywualssrmaqigqk", "pdbvflnwfswsrirl", "jeaezptokkccpbuj", "mbdwjntysntsaaby", "ldlgcawkzcwuxzpz", "lwktbgrzswbsweht", "ecspepmzarzmgpjm", "qmfyvulkmkxjncai", "izftypvwngiukrns", "zgmnyjfeqffbooww", "nyrkhggnprhedows", "yykzzrjmlevgffah", "mavaemfxhlfejfki", "cmegmfjbkvpncqwf", "zxidlodrezztcrij", "fseasudpgvgnysjv", "fupcimjupywzpqzp", "iqhgokavirrcvyys", "wjmkcareucnmfhui", "nftflsqnkgjaexhq", "mgklahzlcbapntgw", "kfbmeavfxtppnrxn", "nuhyvhknlufdynvn", "nviogjxbluwrcoec", "tyozixxxaqiuvoys", "kgwlvmvgtsvxojpr", "moeektyhyonfdhrb", "kahvevmmfsmiiqex", "xcywnqzcdqtvhiwd", "fnievhiyltbvtvem", "jlmndqufirwgtdxd", "muypbfttoeelsnbs", "rypxzbnujitfwkou", "ubmmjbznskildeoj", "ofnmizdeicrmkjxp", "rekvectjbmdnfcib", "yohrojuvdexbctdh", "gwfnfdeibynzjmhz", "jfznhfcqdwlpjull", "scrinzycfhwkmmso", "mskutzossrwoqqsi", "rygoebkzgyzushhr", "jpjqiycflqkexemx", "arbufysjqmgaapnl", "dbjerflevtgweeoj", "snybnnjlmwjvhois", "fszuzplntraprmbj", "mkvaatolvuggikvg", "zpuzuqygoxesnuyc", "wnpxvmxvllxalulm", "eivuuafkvudeouwy", "rvzckdyixetfuehr", "qgmnicdoqhveahyx", "miawwngyymshjmpj", "pvckyoncpqeqkbmx", "llninfenrfjqxurv", "kzbjnlgsqjfuzqtp", "rveqcmxomvpjcwte", "bzotkawzbopkosnx", "ktqvpiribpypaymu", "wvlzkivbukhnvram", "uohntlcoguvjqqdo", "ajlsiksjrcnzepkt", "xsqatbldqcykwusd", "ihbivgzrwpmowkop", "vfayesfojmibkjpb", "uaqbnijtrhvqxjtb", "hhovshsfmvkvymba", "jerwmyxrfeyvxcgg", "hncafjwrlvdcupma", "qyvigggxfylbbrzt", "hiiixcyohmvnkpgk", "mmitpwopgxuftdfu", "iaxderqpceboixoa", "zodfmjhuzhnsqfcb", "sthtcbadrclrazsi", "bkkkkcwegvypbrio", "wmpcofuvzemunlhj", "gqwebiifvqoeynro", "juupusqdsvxcpsgv", "rbhdfhthxelolyse", "kjimpwnjfrqlqhhz", "rcuigrjzarzpjgfq", "htxcejfyzhydinks", "sxucpdxhvqjxxjwf", "omsznfcimbcwaxal", "gufmtdlhgrsvcosb", "bssshaqujtmluerz", "uukotwjkstgwijtr", "kbqkneobbrdogrxk", "ljqopjcjmelgrakz", "rwtfnvnzryujwkfb", "dedjjbrndqnilbeh", "nzinsxnpptzagwlb", "lwqanydfirhnhkxy", "hrjuzfumbvfccxno", "okismsadkbseumnp", "sfkmiaiwlktxqvwa", "hauwpjjwowbunbjj", "nowkofejwvutcnui", "bqzzppwoslaeixro", "urpfgufwbtzenkpj", "xgeszvuqwxeykhef", "yxoldvkyuikwqyeq", "onbbhxrnmohzskgg", "qcikuxakrqeugpoa", "lnudcqbtyzhlpers", "nxduvwfrgzaailgl", "xniuwvxufzxjjrwz", "ljwithcqmgvntjdj", "awkftfagrfzywkhs", "uedtpzxyubeveuek", "bhcqdwidbjkqqhzl", "iyneqjdmlhowwzxx", "kvshzltcrrururty", "zgfpiwajegwezupo", "tkrvyanujjwmyyri", "ercsefuihcmoaiep", "ienjrxpmetinvbos", "jnwfutjbgenlipzq", "bgohjmrptfuamzbz", "rtsyamajrhxbcncw", "tfjdssnmztvbnscs", "bgaychdlmchngqlp", "kfjljiobynhwfkjo", "owtdxzcpqleftbvn", "ltjtimxwstvzwzjj", "wbrvjjjajuombokf", "zblpbpuaqbkvsxye", "gwgdtbpnlhyqspdi", "abipqjihjqfofmkx", "nlqymnuvjpvvgova", "avngotmhodpoufzn", "qmdyivtzitnrjuae", "xfwjmqtqdljuerxi", "csuellnlcyqaaamq", "slqyrcurcyuoxquo", "dcjmxyzbzpohzprl", "uqfnmjwniyqgsowb", "rbmxpqoblyxdocqc", "ebjclrdbqjhladem", "ainnfhxnsgwqnmyo", "eyytjjwhvodtzquf", "iabjgmbbhilrcyyp", "pqfnehkivuelyccc", "xgjbyhfgmtseiimt", "jwxyqhdbjiqqqeyy", "gxsbrncqkmvaryln", "vhjisxjkinaejytk", "seexagcdmaedpcvh", "lvudfgrcpjxzdpvd", "fxtegyrqjzhmqean", "dnoiseraqcoossmc", "nwrhmwwbykvwmgep", "udmzskejvizmtlce", "hbzvqhvudfdlegaa", "cghmlfqejbxewskv", "bntcmjqfwomtbwsb", "qezhowyopjdyhzng", "todzsocdkgfxanbz", "zgjkssrjlwxuhwbk", "eibzljqsieriyrzr", "wamxvzqyycrxotjp", "epzvfkispwqynadu", "dwlpfhtrafrxlyie", "qhgzujhgdruowoug", "girstvkahaemmxvh", "baitcrqmxhazyhbl", "xyanqcchbhkajdmc", "gfvjmmcgfhvgnfdq", "tdfdbslwncbnkzyz", "jojuselkpmnnbcbb", "hatdslkgxtqpmavj", "dvelfeddvgjcyxkj", "gnsofhkfepgwltse", "mdngnobasfpewlno", "qssnbcyjgmkyuoga", "glvcmmjytmprqwvn", "gwrixumjbcdffsdl", "lozravlzvfqtsuiq", "sicaflbqdxbmdlch", "inwfjkyyqbwpmqlq", "cuvszfotxywuzhzi", "igfxyoaacoarlvay", "ucjfhgdmnjvgvuni", "rvvkzjsytqgiposh", "jduinhjjntrmqroz", "yparkxbgsfnueyll", "lyeqqeisxzfsqzuj", "woncskbibjnumydm", "lltucklragtjmxtl", "ubiyvmyhlesfxotj", "uecjseeicldqrqww", "xxlxkbcthufnjbnm", "lhqijovvhlffpxga", "fzdgqpzijitlogjz", "efzzjqvwphomxdpd", "jvgzvuyzobeazssc", "hejfycgxywfjgbfw", "yhjjmvkqfbnbliks", "sffvfyywtlntsdsz", "dwmxqudvxqdenrur", "asnukgppdemxrzaz", "nwqfnumblwvdpphx", "kqsmkkspqvxzuket", "cpnraovljzqiquaz", "qrzgrdlyyzbyykhg", "opoahcbiydyhsmqe", "hjknnfdauidjeydr", "hczdjjlygoezadow", "rtflowzqycimllfv", "sfsrgrerzlnychhq", "bpahuvlblcolpjmj", "albgnjkgmcrlaicl", "pijyqdhfxpaxzdex", "eeymiddvcwkpbpux", "rqwkqoabywgggnln", "vckbollyhgbgmgwh", "ylzlgvnuvpynybkm", "hpmbxtpfosbsjixt", "ocebeihnhvkhjfqz", "tvctyxoujdgwayze", "efvhwxtuhapqxjen", "rusksgefyidldmpo", "nkmtjvddfmhirmzz", "whvtsuadwofzmvrt", "iiwjqvsdxudhdzzk", "gucirgxaxgcassyo", "rmhfasfzexeykwmr", "hynlxcvsbgosjbis", "huregszrcaocueen", "pifezpoolrnbdqtv", "unatnixzvdbqeyox", "xtawlpduxgacchfe", "bdvdbflqfphndduf", "xtdsnjnmzccfptyt", "nkhsdkhqtzqbphhg", "aqcubmfkczlaxiyb", "moziflxpsfubucmv", "srdgnnjtfehiimqx", "pwfalehdfyykrohf", "sysxssmvewyfjrve", "brsemdzosgqvvlxe", "bimbjoshuvflkiat", "hkgjasmljkpkwwku", "sbnmwjvodygobpqc", "bbbqycejueruihhd", "corawswvlvneipyc", "gcyhknmwsczcxedh", "kppakbffdhntmcqp", "ynulzwkfaemkcefp", "pyroowjekeurlbii", "iwksighrswdcnmxf", "glokrdmugreygnsg", "xkmvvumnfzckryop", "aesviofpufygschi", "csloawlirnegsssq", "fkqdqqmlzuxbkzbc", "uzlhzcfenxdfjdzp", "poaaidrktteusvyf", "zrlyfzmjzfvivcfr", "qwjulskbniitgqtx", "gjeszjksbfsuejki", "vczdejdbfixbduaq", "knjdrjthitjxluth", "jweydeginrnicirl", "bottrfgccqhyycsl", "eiquffofoadmbuhk", "lbqfutmzoksscswf", "xfmdvnvfcnzjprba", "uvugkjbkhlaoxmyx", "wadlgtpczgvcaqqv", "inzrszbtossflsxk", "dbzbtashaartczrj", "qbjiqpccefcfkvod", "hluujmokjywotvzy", "thwlliksfztcmwzh", "arahybspdaqdexrq", "nuojrmsgyipdvwyx", "hnajdwjwmzattvst", "sulcgaxezkprjbgu", "rjowuugwdpkjtypw", "oeugzwuhnrgiaqga", "wvxnyymwftfoswij", "pqxklzkjpcqscvde", "tuymjzknntekglqj", "odteewktugcwlhln", "exsptotlfecmgehc", "eeswfcijtvzgrqel", "vjhrkiwmunuiwqau", "zhlixepkeijoemne", "pavfsmwesuvebzdd", "jzovbklnngfdmyws", "nbajyohtzfeoiixz", "ciozmhrsjzrwxvhz", "gwucrxieqbaqfjuv", "uayrxrltnohexawc", "flmrbhwsfbcquffm", "gjyabmngkitawlxc", "rwwtggvaygfbovhg", "xquiegaisynictjq", "oudzwuhexrwwdbyy", "lengxmguyrwhrebb", "uklxpglldbgqsjls", "dbmvlfeyguydfsxq", "zspdwdqcrmtmdtsc", "mqfnzwbfqlauvrgc", "amcrkzptgacywvhv", "ndxmskrwrqysrndf", "mwjyhsufeqhwisju", "srlrukoaenyevykt", "tnpjtpwawrxbikct", "geczalxmgxejulcv", "tvkcbqdhmuwcxqci", "tiovluvwezwwgaox", "zrjhtbgajkjqzmfo", "vcrywduwsklepirs", "lofequdigsszuioy", "wxsdzomkjqymlzat", "iabaczqtrfbmypuy", "ibdlmudbajikcncr", "rqcvkzsbwmavdwnv", "ypxoyjelhllhbeog", "fdnszbkezyjbttbg", "uxnhrldastpdjkdz", "xfrjbehtxnlyzcka", "omjyfhbibqwgcpbv", "eguucnoxaoprszmp", "xfpypldgcmcllyzz", "aypnmgqjxjqceelv", "mgzharymejlafvgf", "tzowgwsubbaigdok", "ilsehjqpcjwmylxc", "pfmouwntfhfnmrwk", "csgokybgdqwnduwp", "eaxwvxvvwbrovypz", "nmluqvobbbmdiwwb", "lnkminvfjjzqbmio", "mjiiqzycqdhfietz", "towlrzriicyraevq", "obiloewdvbrsfwjo", "lmeooaajlthsfltw", "ichygipzpykkesrw", "gfysloxmqdsfskvt", "saqzntehjldvwtsx", "pqddoemaufpfcaew", "mjrxvbvwcreaybwe", "ngfbrwfqnxqosoai", "nesyewxreiqvhald", "kqhqdlquywotcyfy", "liliptyoqujensfi", "nsahsaxvaepzneqq", "zaickulfjajhctye", "gxjzahtgbgbabtht", "koxbuopaqhlsyhrp", "jhzejdjidqqtjnwe", "dekrkdvprfqpcqki", "linwlombdqtdeyop", "dvckqqbnigdcmwmx", "yaxygbjpzkvnnebv", "rlzkdkgaagmcpxah", "cfzuyxivtknirqvt", "obivkajhsjnrxxhn", "lmjhayymgpseuynn", "bbjyewkwadaipyju", "lmzyhwomfypoftuu", "gtzhqlgltvatxack", "jfflcfaqqkrrltgq", "txoummmnzfrlrmcg", "ohemsbfuqqpucups", "imsfvowcbieotlok", "tcnsnccdszxfcyde", "qkcdtkwuaquajazz", "arcfnhmdjezdbqku", "srnocgyqrlcvlhkb", "mppbzvfmcdirbyfw", "xiuarktilpldwgwd", "ypufwmhrvzqmexpc", "itpdnsfkwgrdujmj", "cmpxnodtsswkyxkr", "wayyxtjklfrmvbfp", "mfaxphcnjczhbbwy", "sjxhgwdnqcofbdra", "pnxmujuylqccjvjm", "ivamtjbvairwjqwl", "deijtmzgpfxrclss", "bzkqcaqagsynlaer", "tycefobvxcvwaulz", "ctbhnywezxkdsswf", "urrxxebxrthtjvib", "fpfelcigwqwdjucv", "ngfcyyqpqulwcphb", "rltkzsiipkpzlgpw", "qfdsymzwhqqdkykc", "balrhhxipoqzmihj", "rnwalxgigswxomga", "ghqnxeogckshphgr", "lyyaentdizaumnla", "exriodwfzosbeoib", "speswfggibijfejk", "yxmxgfhvmshqszrq", "hcqhngvahzgawjga", "qmhlsrfpesmeksur", "eviafjejygakodla", "kvcfeiqhynqadbzv", "fusvyhowslfzqttg", "girqmvwmcvntrwau", "yuavizroykfkdekz", "jmcwohvmzvowrhxf", "kzimlcpavapynfue", "wjudcdtrewfabppq", "yqpteuxqgbmqfgxh", "xdgiszbuhdognniu", "jsguxfwhpftlcjoh", "whakkvspssgjzxre", "ggvnvjurlyhhijgm", "krvbhjybnpemeptr", "pqedgfojyjybfbzr", "jzhcrsgmnkwwtpdo", "yyscxoxwofslncmp", "gzjhnxytmyntzths", "iteigbnqbtpvqumi", "zjevfzusnjukqpfw", "xippcyhkfuounxqk", "mcnhrcfonfdgpkyh", "pinkcyuhjkexbmzj", "lotxrswlxbxlxufs", "fmqajrtoabpckbnu", "wfkwsgmcffdgaqxg", "qfrsiwnohoyfbidr", "czfqbsbmiuyusaqs", "ieknnjeecucghpoo", "cevdgqnugupvmsge", "gjkajcyjnxdrtuvr", "udzhrargnujxiclq", "zqqrhhmjwermjssg", "ggdivtmgoqajydzz", "wnpfsgtxowkjiivl", "afbhqawjbotxnqpd", "xjpkifkhfjeqifdn", "oyfggzsstfhvticp", "kercaetahymeawxy", "khphblhcgmbupmzt", "iggoqtqpvaebtiol", "ofknifysuasshoya", "qxuewroccsbogrbv", "apsbnbkiopopytgu", "zyahfroovfjlythh", "bxhjwfgeuxlviydq", "uvbhdtvaypasaswa", "qamcjzrmesqgqdiz", "hjnjyzrxntiycyel", "wkcrwqwniczwdxgq", "hibxlvkqakusswkx", "mzjyuenepwdgrkty", "tvywsoqslfsulses", "jqwcwuuisrclircv", "xanwaoebfrzhurct", "ykriratovsvxxasf", "qyebvtqqxbjuuwuo", "telrvlwvriylnder", "acksrrptgnhkeiaa", "yemwfjhiqlzsvdxf", "banrornfkcymmkcc", "ytbhxvaeiigjpcgm", "crepyazgxquposkn", "xlqwdrytzwnxzwzv", "xtrbfbwopxscftps", "kwbytzukgseeyjla", "qtfdvavvjogybxjg", "ytbmvmrcxwfkgvzw", "nbscbdskdeocnfzr", "sqquwjbdxsxhcseg", "ewqxhigqcgszfsuw", "cvkyfcyfmubzwsee", "dcoawetekigxgygd", "ohgqnqhfimyuqhvi", "otisopzzpvnhctte", "bauieohjejamzien", "ewnnopzkujbvhwce", "aeyqlskpaehagdiv", "pncudvivwnnqspxy", "ytugesilgveokxcg", "zoidxeelqdjesxpr", "ducjccsuaygfchzj", "smhgllqqqcjfubfc", "nlbyyywergronmir", "prdawpbjhrzsbsvj", "nmgzhnjhlpcplmui", "eflaogtjghdjmxxz", "qolvpngucbkprrdc", "ixywxcienveltgho", "mwnpqtocagenkxut", "iskrfbwxonkguywx", "ouhtbvcaczqzmpua", "srewprgddfgmdbao", "dyufrltacelchlvu", "czmzcbrkecixuwzz", "dtbeojcztzauofuk", "prrgoehpqhngfgmw", "baolzvfrrevxsyke", "zqadgxshwiarkzwh", "vsackherluvurqqj", "surbpxdulvcvgjbd", "wqxytarcxzgxhvtx", "vbcubqvejcfsgrac", "zqnjfeapshjowzja", "hekvbhtainkvbynx", "knnugxoktxpvoxnh", "knoaalcefpgtvlwm", "qoakaunowmsuvkus", "ypkvlzcduzlezqcb", "ujhcagawtyepyogh", "wsilcrxncnffaxjf", "gbbycjuscquaycrk", "aduojapeaqwivnly", "ceafyxrakviagcjy", "nntajnghicgnrlst", "vdodpeherjmmvbje", "wyyhrnegblwvdobn", "xlfurpghkpbzhhif", "xyppnjiljvirmqjo", "kglzqahipnddanpi", "omjateouxikwxowr", "ocifnoopfglmndcx", "emudcukfbadyijev", "ooktviixetfddfmh", "wtvrhloyjewdeycg", "cgjncqykgutfjhvb", "nkwvpswppeffmwad", "hqbcmfhzkxmnrivg", "mdskbvzguxvieilr", "anjcvqpavhdloaqh", "erksespdevjylenq", "fadxwbmisazyegup", "iyuiffjmcaahowhj", "ygkdezmynmltodbv", "fytneukxqkjattvh", "woerxfadbfrvdcnz", "iwsljvkyfastccoa", "movylhjranlorofe", "drdmicdaiwukemep", "knfgtsmuhfcvvshg", "ibstpbevqmdlhajn", "tstwsswswrxlzrqs", "estyydmzothggudf", "jezogwvymvikszwa", "izmqcwdyggibliet", "nzpxbegurwnwrnca", "kzkojelnvkwfublh", "xqcssgozuxfqtiwi", "tcdoigumjrgvczfv", "ikcjyubjmylkwlwq", "kqfivwystpqzvhan", "bzukgvyoqewniivj", "iduapzclhhyfladn", "fbpyzxdfmkrtfaeg", "yzsmlbnftftgwadz" ] def part1(): def contains_three_vowels(x): n = 0 for c in x: if c in "aeiou": n += 1 return n >= 3 def contains_dubble(x): for i in range(len(x) - 1): if x[i] == x[i + 1]: return True return False def contains_forbidden(x): forbidden = ["ab", "cd", "pq", "xy"] for i in range(len(x) - 1): if x[i] + x[i + 1] in forbidden: return True return False n = 0 for x in strings: if contains_three_vowels(x) and contains_dubble(x) and not contains_forbidden(x): n += 1 print("Number of nice strings: {}".format(n)) def part2(): def contains_pairs(x): for i in range(len(x) - 3): if x.find(x[i] + x[i + 1], i + 2) >= 0: return True return False def contains_dubble(x): for i in range(len(x) - 2): if x[i] == x[i + 2]: return True return False n = 0 for x in strings: if contains_pairs(x) and contains_dubble(x): n += 1 print("Number of nice strings: {}".format(n)) part1() part2()
""" Time Complexity = O(log(N)) Space Complexity = O(1) Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. Example: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. """
#!/usr/bin/python3.6 """ The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 """ def collatz(n): lt = [n] while n != 1: if n%2 == 0: n = n/2 else: n = 3*n + 1 lt.append(n) return lt n = int(input("Enter the number: ")) n1 = n lt = collatz(n) print(f"The collatz sequence with starting number {n1} is") print(lt)
minha_matriz1 = [[1], [2], [3]] minha_matriz2 = [[1, 2, 3], [4, 5, 6]] def imprime_matriz(matriz): for i in matriz: linha = '' for j in i: linha += str(j) print(" ".join(linha), end="") print() # imprime_matriz(minha_matriz1) # imprime_matriz(minha_matriz2)
def get_column(game, col_num): ''' Get the columns ''' col = col_num result = [] for i in range(0, 3): temp = game[i] result.append(temp[col]) return result def print_odd_cubes_to_number(number): ''' Print odds and their cubes ''' if number < 1: print('ERROR: number must be at least 1') else: for i in range(1, number + 1): if i % 2 != 0: print(i, '*', i, '*', i, '=', i ** 3) def print_hundred(nums): ''' Rewrite with while-loop ''' total = 0 i = 0 while total <= 100 and i < len(nums): total = nums[i] + total print(nums[i]) i = i + 1 def my_enumerate(items): ''' Like enumerate() ''' temp = [] for i in range(0, len(items)): temp_1 = (i, items[i]) temp.append(temp_1) return temp def num_rushes(slope_height, rush_height_gain, back_sliding): ''' Use the template ''' current_height = 0 rushes = 0 while current_height < slope_height: current_height = current_height + rush_height_gain rushes = rushes + 1 if current_height >= slope_height: break else: current_height = current_height - back_sliding return rushes def rumbletron(strings): ''' Reserve and capitalize ''' temp = [] for i in range(0, len(strings)): string = strings[i] string = string[::-1] string = string.upper() temp.append(string) return temp
class Transformer(object): mappings = {} value_mappings_functions = {} def __init__(self, initial_data): self.initial_data = initial_data def transform_dict(self, obj: dict): result = {} for k, v in obj.items(): if k in self.mappings.keys(): if k in self.value_mappings_functions.keys(): result[self.mappings.get(k)] = self.value_mappings_functions[k](v) else: result[self.mappings.get(k)] = v return result def transform(self): if type(self.initial_data) == list: return [self.transform_dict(i) for i in self.initial_data] return self.transform_dict(self.initial_data)
# Main driver file for user input and displaying # Also checks legal moves and keep a move log class GameState(): def __init__(self): # Initial board state # Board is 8x8 2d list with each element having 2 characters # First character represents the color: w = white & b = black # Second character represents the type: R = Rook, K = King, etc. # "--" represents a empty space self.board = [ ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"], ["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"], ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"] ] self.moveFunctions = {"p" : self.getPawnMoves, "R" : self.getRookMoves, "N" : self.getKnightMoves, "Q" : self.getQueenMoves, "K" : self.getKingMoves, "B" : self.getBishopMoves} self.whiteToMove = True self.moveLog = [] self.whiteKingLocation = (7, 4) self.blackKingLocation = (0, 4) self.checkMate = False self.stalemate = False self.enpassantPossible = () self.currentCastlingRight = CastleRights(True, True, True, True) self.castleRightsLog = [CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)] #Takes a move as a parameter and executes it, doesn't work for castling, pawn promotion and en-passant def makeMove(self, move): self.board[move.startRow][move.startCol] = "--" self.board[move.endRow][move.endCol] = move.pieceMoved self.moveLog.append(move) # Log the move to see history/undo last move self.whiteToMove = not self.whiteToMove # Switch turn to other player # Updates King's position if moved if move.pieceMoved == "wK": self.whiteKingLocation = (move.endRow, move.endCol) if move.pieceMoved == "bK": self.blackKingLocation = (move.endRow, move.endCol) # Pawn promotion if move.isPawnPromotion: self.board[move.endRow][move.endCol] = move.pieceMoved[0] + move.promotionChoice # En-passant move if move.isEnpassantMove: self.board[move.startRow][move.endCol] = "--" # Update enpassantPossible variable if move.pieceMoved[1] == "p" and abs(move.startRow - move.endRow) == 2: self.enpassantPossible = ((move.startRow + move.endRow) // 2, move.startCol) else: self.enpassantPossible = () # Castle move if move.isCastlingMove: if move.endCol - move.startCol == 2: # Kingside castle self.board[move.endRow][move.endCol-1] = self.board[move.endRow][move.endCol+1] # Moves the rook self.board[move.endRow][move.endCol+1] = "--" else: # Queenside castle self.board[move.endRow][move.endCol+1] = self.board[move.endRow][move.endCol-2] self.board[move.endRow][move.endCol-2] = "--" # Updating Castling rights self.updateCastleRights(move) self.castleRightsLog.append(CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)) def undoMove(self): if len(self.moveLog) != 0: move = self.moveLog.pop() # Gets last move and removes it from movelog self.board[move.startRow][move.startCol] = move.pieceMoved self.board[move.endRow][move.endCol] = move.pieceCaptured self.whiteToMove = not self.whiteToMove # Switches turn back to other player # Updates King's position if moved if move.pieceMoved == "wK": self.whiteKingLocation = (move.startRow, move.startCol) elif move.pieceMoved == "bK": self.blackKingLocation = (move.startRow, move.startCol) if move.isEnpassantMove: self.board[move.endRow][move.endCol] = "--" self.board[move.startRow][move.endCol] = move.pieceCaptured self.enpassantPossible = (move.endRow, move.endCol) if move.pieceMoved[1] == "p" and abs(move.startRow - move.endRow) == 2: self.enpassantPossible = () # Undo-ing castling rights self.castleRightsLog.pop() self.currentCastlingRight = self.castleRightsLog[-1] # Undo-ing castle move if move.isCastlingMove: if move.endCol - move.startCol == 2: # Kingside castle self.board[move.endRow][move.endCol+1] = self.board[move.endRow][move.endCol-1] self.board[move.endRow][move.endCol-1] = "--" else: self.board[move.endRow][move.endCol-2] = self.board[move.endRow][move.endCol+1] self.board[move.endRow][move.endCol+1] = "--" def updateCastleRights(self, move): if move.pieceMoved == "wK": self.currentCastlingRight.wks = False self.currentCastlingRight.wqs = False elif move.pieceMoved == "bK": self.currentCastlingRight.bks = False self.currentCastlingRight.bqs = False elif move.pieceMoved == "wR": if move.startRow == 7: if move.startCol == 0: self.currentCastlingRight.wqs = False elif move.startCol == 7: self.currentCastlingRight.wks = False elif move.pieceMoved == "bR": if move.startRow == 0: if move.startCol == 0: self.currentCastlingRight.bqs = False elif move.startCol == 7: self.currentCastlingRight.bks = False # All posible moves when in check def getValidMoves(self): tempEnpassantPossible = self.enpassantPossible tempCastleRights = CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs) moves = self.getLegalMoves() if self.whiteToMove: self.getCastleMoves(self.whiteKingLocation[0], self.whiteKingLocation[1], moves) else: self.getCastleMoves(self.blackKingLocation[0], self.blackKingLocation[1], moves) for i in range(len(moves)-1, -1, -1): self.makeMove(moves[i]) self.whiteToMove = not self.whiteToMove if self.inCheck(): moves.remove(moves[i]) self.whiteToMove = not self.whiteToMove self.undoMove() if len(moves) == 0: # Either Check Mate of Stalemate if self.inCheck(): self.checkMate = True else: self.stalemate = True self.enpassantPossible = tempEnpassantPossible self.currentCastlingRight = tempCastleRights return moves # Determine if King is under attack def inCheck(self): if self.whiteToMove: return self.squareUnderAttack(self.whiteKingLocation[0], self.whiteKingLocation[1]) else: return self.squareUnderAttack(self.blackKingLocation[0], self.blackKingLocation[1]) # Determine if the enemy can attack a certain square def squareUnderAttack(self, r, c): self.whiteToMove = not self.whiteToMove # switch to opponent to see their moves oppMoves = self.getLegalMoves() self.whiteToMove = not self.whiteToMove for move in oppMoves: if move.endRow == r and move.endCol == c: return True return False # All legal moves without being in check def getLegalMoves(self): moves = [] for r in range(len(self.board)): for c in range(len(self.board[r])): turn = self.board[r][c][0] if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMove): piece = self.board[r][c][1] self.moveFunctions[piece](r, c, moves) # Calls the appropriate move function depending on the piece return moves #Define all possible moves for each piece def getPawnMoves(self, r, c, moves): if self.whiteToMove: # White pawn movement if self.board[r-1][c] == "--": moves.append(Move((r, c), (r-1, c), self.board)) if r == 6 and self.board[r-2][c] == "--": moves.append(Move((r, c), (r-2, c), self.board)) if c-1 >= 0: if self.board[r-1][c-1][0] == "b": moves.append(Move((r, c), (r-1, c-1), self.board)) elif (r-1, c-1) == self.enpassantPossible: moves.append(Move((r, c), (r-1, c-1), self.board, isEnpassantMove=True)) if c+1 <= 7: if self.board[r-1][c+1][0] == "b": moves.append(Move((r, c), (r-1, c+1), self.board)) elif (r-1, c+1) == self.enpassantPossible: moves.append(Move((r, c), (r-1, c+1), self.board, isEnpassantMove=True)) else: # Black pawn movement if self.board[r+1][c] == "--": moves.append(Move((r, c), (r+1, c), self.board)) if r == 1 and self.board[r+2][c] == "--": moves.append(Move((r, c), (r+2, c), self.board)) if c-1 >= 0: if self.board[r+1][c-1][0] == "w": moves.append(Move((r, c), (r+1, c-1), self.board)) elif (r+1, c-1) == self.enpassantPossible: moves.append(Move((r, c), (r+1, c-1), self.board, isEnpassantMove=True)) if c+1 <= 7: if self.board[r+1][c+1][0] == "w": moves.append(Move((r, c), (r+1, c+1), self.board)) elif (r+1, c+1) == self.enpassantPossible: moves.append(Move((r, c), (r+1, c+1), self.board, isEnpassantMove=True)) def getRookMoves(self, r, c, moves): directions = ((-1, 0), (0, -1), (1, 0), (0, 1)) enemyColor = "b" if self.whiteToMove else "w" for d in directions: for i in range(1, 8): endRow = r + d[0] * i endCol = c + d[1] * i if 0 <= endRow < 8 and 0 <= endCol < 8: endPiece = self.board[endRow][endCol] if endPiece == "--": moves.append(Move((r, c), (endRow, endCol), self.board)) elif endPiece[0] == enemyColor: moves.append(Move((r, c), (endRow, endCol), self.board)) break else: break else: break def getBishopMoves(self, r, c, moves): directions = ((-1, -1), (1, -1), (1, 1), (-1, 1)) enemyColor = "b" if self.whiteToMove else "w" for d in directions: for i in range(1, 8): endRow = r + d[0] * i endCol = c + d[1] * i if 0 <= endRow < 8 and 0 <= endCol < 8: endPiece = self.board[endRow][endCol] if endPiece == "--": moves.append(Move((r, c), (endRow, endCol), self.board)) elif endPiece[0] == enemyColor: moves.append(Move((r, c), (endRow, endCol), self.board)) break else: break else: break def getKnightMoves(self, r, c, moves): knightMoves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)) allyColor = "w" if self.whiteToMove else "b" for m in knightMoves: endRow = r + m[0] endCol = c + m[1] if 0 <= endRow < 8 and 0 <= endCol < 8: endPiece = self.board[endRow][endCol] if endPiece[0] != allyColor: moves.append(Move((r, c), (endRow, endCol), self.board)) def getQueenMoves(self, r, c, moves): self.getBishopMoves(r, c, moves) self.getRookMoves(r, c, moves) def getKingMoves(self, r, c, moves): kingMoves = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (1, -1), (1, 1), (1, 0), (0, 1)) allyColor = "w" if self.whiteToMove else "b" for i in range(8): endRow = r + kingMoves[i][0] endCol = c + kingMoves[i][1] if 0 <= endRow < 8 and 0 <= endCol < 8: endPiece = self.board[endRow][endCol] if endPiece[0] != allyColor: moves.append(Move((r, c), (endRow, endCol), self.board)) # Castling handling def getCastleMoves(self, r, c, moves): if self.squareUnderAttack(r, c): return if (self.whiteToMove and self.currentCastlingRight.wks) or (not self.whiteToMove and self.currentCastlingRight.bks): self.getKingSideCastleMoves(r, c, moves) if (self.whiteToMove and self.currentCastlingRight.wqs) or (not self.whiteToMove and self.currentCastlingRight.bqs): self.getQueenSideCastleMoves(r, c, moves) def getKingSideCastleMoves(self, r, c, moves): if self.board[r][c+1] == "--" and self.board[r][c+2] == "--": if not self.squareUnderAttack(r, c+1) and not self.squareUnderAttack(r, c+2): moves.append(Move((r, c), (r, c+2), self.board, isCastlingMove=True, KingSide=True)) def getQueenSideCastleMoves(self, r, c, moves): if self.board[r][c-1] == "--" and self.board[r][c-2] == "--" and self.board[r][c-3] == "--": if not self.squareUnderAttack(r, c-1) and not self.squareUnderAttack(r, c-2): moves.append(Move((r, c), (r, c-2), self.board, isCastlingMove=True, KingSide=False)) class CastleRights(): def __init__(self, wks, bks, wqs, bqs): self.wks = wks self.bks = bks self.wqs = wqs self.bqs = bqs class Move(): # Mapping keys to values ranksToRows = {"1" : 7, "2" : 6, "3" : 5, "4" : 4, "5" : 3, "6" : 2, "7" : 1, "8" : 0} rowsToRanks = {v: k for k, v in ranksToRows.items()} filesToCols = {"h" : 7, "g" : 6, "f" : 5, "e" : 4, "d" : 3, "c" : 2, "b" : 1, "a" : 0} colsToFiles = {v: k for k, v in filesToCols.items()} def __init__(self, startSq, endSq, board, isEnpassantMove=False, isCastlingMove=False, KingSide=False): self.startRow = startSq[0] self.startCol = startSq[1] self.endRow = endSq[0] self.endCol = endSq[1] self.pieceMoved = board[self.startRow][self.startCol] self.pieceCaptured = board[self.endRow][self.endCol] # Pawn promotion self.isPawnPromotion = (self.pieceMoved == "wp" and self.endRow == 0) or (self.pieceMoved == "bp" and self.endRow == 7) self.promotionChoice = "Q" # En-passant self.isEnpassantMove = isEnpassantMove if self.isEnpassantMove: self.pieceCaptured = "wp" if self.pieceMoved == "bp" else "bp" self.isCastlingMove = isCastlingMove self.KingSide = KingSide self.moveID = self.startRow * 1000 + self.startCol * 100 + self.endRow * 10 + self.endCol #Overriding equals method def __eq__(self, other): if isinstance(other, Move): return self.moveID == other.moveID return False def getChessNotation(self): #TODO Disambiguating Moves #TODO Pawn Promotion #TODO Check/Checkmate notation = "" if self.isCastlingMove: if self.KingSide: return "0-0" else: return "0-0-0" if not self.pieceMoved[1] == "p": notation += self.pieceMoved[1] else: if self.pieceCaptured == "--": return self.getRankFile(self.endRow, self.endCol) else: notation = self.getRankFile(self.startRow, self.startCol) return notation[0] + "x" + self.getRankFile(self.endRow, self.endCol) if self.pieceCaptured == "--": return notation + self.getRankFile(self.endRow, self.endCol) else: return notation + "x" + self.getRankFile(self.endRow, self.endCol) def getRankFile(self, r, c): return self.colsToFiles[c] + self.rowsToRanks[r]
"""Directives and roles for documenting traitlets config options. :: .. configtrait:: Application.log_datefmt Description goes here. Cross reference like this: :configtrait:`Application.log_datefmt`. """ def setup(app): app.add_object_type('configtrait', 'configtrait', objname='Config option') metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata
""" Implementation of a vertex, as used in graphs """ ################################################################################ # # # Undirected # # # ################################################################################ class UndirectedVertex(object): def __init__(self, val=None, attrs=None): self._val = val or id(self) self._attrs = attrs or {} self._edges = set() self._has_self_edge = False def __repr__(self): display = (self.val, id(self)) return "Vertex(val=%s, id=%s)" % display def __str__(self): return "V(%s)" % self.val def __contains__(self, e): return e in self._edges @property def val(self): return self._val @property def attrs(self): return self._attrs @property def edges(self): return iter(self._edges) @property def has_self_edge(self): return self._has_self_edge @property def neighbors(self): """ Iterator over vertices adjacent to this vertex """ return iter(set(v for e in self._edges for v in e.vertices if v != self) | (set([self]) if self._has_self_edge else set())) @property def degree(self): """ Number of neighbors this vertex has (+1 if it has a self edge) """ return sum(1 for _ in self._edges) + (1 if self._has_self_edge else 0) def add_edge(self, e): """ Adds an edge to this vertex """ if self not in e.vertices: raise ValueError(str(self) + " is not part of " + str(e) + ".") if e in self: raise ValueError(str(self) + " already has " + str(e) + ".") self._edges.add(e) if e.is_self_edge: self._has_self_edge = True def remove_edge(self, e): """ Removes an edge from this vertex """ self._edges.discard(e) if e.is_self_edge: self._has_self_edge = False def get(self, attr): """ Get an attribute """ return self._attrs.get(attr) def set(self, attr, value): """ Set an attribute """ self._attrs[attr] = value def has_attr(self, attr): """ Check if an attribute exists """ return attr in self._attrs def del_attr(self, attr): """ Delete an attribute """ del self._attrs[attr] ################################################################################ # # # Directed # # # ################################################################################ class DirectedVertex(object): def __init__(self, val=None, attrs=None): self._val = val or id(self) self._attrs = attrs or {} self._edges = set() def __repr__(self): display = (self.val, id(self)) return "Vertex(val=%s, id=%s)" % display def __str__(self): return "V(%s)" % self.val def __contains__(self, e): return e in self._edges @property def val(self): return self._val @property def attrs(self): return self._attrs @property def edges(self): return iter(self._edges) @property def outs(self): """ Iterator over vertices into which this vertex has an edge """ return iter(set(e.v_to for e in self._edges if e.v_from == self)) @property def ins(self): """ Iterator over vertices which have an edge into this vertex """ return iter(set(e.v_from for e in self._edges if e.v_to == self)) @property def out_degree(self): """ Number of vertices into which this vertex has an edge """ return sum(1 for e in self._edges if e.v_from == self) @property def in_degree(self): """ Number of vertices which have an edge into this vertex """ return sum(1 for e in self._edges if e.v_to == self) @property def degree(self): """ Sum of out degree and in degree """ return self.out_degree + self.in_degree def add_edge(self, e): """ Adds an edge to this vertex """ if self != e.v_from and self != e.v_to: raise ValueError(str(self) + " is not part of " + str(e) + ".") if e in self: raise ValueError(str(self) + " already has " + str(e) + ".") self._edges.add(e) def remove_edge(self, e): """ Removes an edge from this vertex """ self._edges.discard(e) def get(self, attr): """ Get an attribute """ return self._attrs.get(attr) def set(self, attr, value): """ Set an attribute """ self._attrs[attr] = value def has_attr(self, attr): """ Check if an attribute exists """ return attr in self._attrs def del_attr(self, attr): """ Delete an attribute """ del self._attrs[attr]
def aumentar(preco,taxa): res = preco * (1 + taxa) return res def diminuir(preco,taxa): res = preco * (1 - taxa) return res def dobro(preco): res = preco * 2 return res def metade(preco): res = preco/2 return res
"""All Lena exceptions are subclasses of :exc:`LenaException` and corresponding Python exceptions (if they exist). """ # pylint: disable=missing-docstring # Most Exceptions here are familiar to Python programmers # and are self-explanatory. class LenaException(Exception): """Base class for all Lena exceptions.""" pass class LenaAttributeError(LenaException, AttributeError): pass class LenaEnvironmentError(LenaException, EnvironmentError): """The base class for exceptions that can occur outside the Python system, like IOError or OSError. """ class LenaIndexError(LenaException, IndexError): pass class LenaKeyError(LenaException, KeyError): pass class LenaNotImplementedError(LenaException, NotImplementedError): pass class LenaRuntimeError(LenaException, RuntimeError): """Raised when an error does not belong to other categories.""" pass class LenaStopFill(LenaException): """Signal that no more fill is accepted. Analogous to StopIteration, but control flow is reversed. """ pass class LenaTypeError(LenaException, TypeError): pass class LenaValueError(LenaException, ValueError): pass class LenaZeroDivisionError(LenaException, ZeroDivisionError): # raised when, for example, mean can't be calculated pass
def ps(uid='-1',det='default',suffix='default',shift=.5,logplot='off',figure_number=999): ''' function to determine statistic on line profile (assumes either peak or erf-profile)\n calling sequence: uid='-1',det='default',suffix='default',shift=.5)\n det='default' -> get detector from metadata, otherwise: specify, e.g. det='eiger4m_single'\n suffix='default' -> _stats1_total / _sum_all, otherwise: specify, e.g. suffix='_stats2_total'\n shift: scale for peak presence (0.5 -> peak has to be taller factor 2 above background)\n figure_number: default=999 -> specify figure number for plot ''' #import datetime #import time #import numpy as np #from PIL import Image #from databroker import db, get_fields, get_images, get_table #from matplotlib import pyplot as pltfrom #from lmfit import Model #from lmfit import minimize, Parameters, Parameter, report_fit #from scipy.special import erf # get the scan information: if uid == '-1': uid=-1 if det == 'default': if db[uid].start.detectors[0] == 'elm' and suffix=='default': intensity_field='elm_sum_all' elif db[uid].start.detectors[0] == 'elm': intensity_field='elm'+suffix elif suffix == 'default': intensity_field= db[uid].start.detectors[0]+'_stats1_total' else: intensity_field= db[uid].start.detectors[0]+suffix else: if det=='elm' and suffix == 'default': intensity_field='elm_sum_all' elif det=='elm': intensity_field = 'elm'+suffix elif suffix == 'default': intensity_field=det+'_stats1_total' else: intensity_field=det+suffix field = db[uid].start.motors[0] #field='dcm_b';intensity_field='elm_sum_all' [x,y,t]=get_data(uid,field=field, intensity_field=intensity_field, det=None, debug=False) #need to re-write way to get data x=np.array(x) y=np.array(y) x = np.nan_to_num(x) y = np.nan_to_num(y) PEAK=x[np.argmax(y)] PEAK_y=np.max(y) COM=np.sum(x * y) / np.sum(y) ### from Maksim: assume this is a peak profile: def is_positive(num): return True if num > 0 else False # Normalize values first: ym = (y - np.min(y)) / (np.max(y) - np.min(y)) - shift # roots are at Y=0 positive = is_positive(ym[0]) list_of_roots = [] for i in range(len(y)): current_positive = is_positive(ym[i]) if current_positive != positive: list_of_roots.append(x[i - 1] + (x[i] - x[i - 1]) / (abs(ym[i]) + abs(ym[i - 1])) * abs(ym[i - 1])) positive = not positive if len(list_of_roots) >= 2: FWHM=abs(list_of_roots[-1] - list_of_roots[0]) CEN=list_of_roots[0]+0.5*(list_of_roots[1]-list_of_roots[0]) ps.fwhm=FWHM ps.cen=CEN #return { # 'fwhm': abs(list_of_roots[-1] - list_of_roots[0]), # 'x_range': list_of_roots, #} else: # ok, maybe it's a step function.. print('no peak...trying step function...') ym = ym + shift def err_func(x, x0, k=2, A=1, base=0 ): #### erf fit from Yugang return base - A * erf(k*(x-x0)) mod = Model( err_func ) ### estimate starting values: x0=np.mean(x) #k=0.1*(np.max(x)-np.min(x)) pars = mod.make_params( x0=x0, k=2, A = 1., base = 0. ) result = mod.fit(ym, pars, x = x ) CEN=result.best_values['x0'] FWHM = result.best_values['k'] ps.cen = CEN ps.fwhm = FWHM ### re-plot results: if logplot=='on': plt.close(figure_number) plt.figure(figure_number) plt.semilogy([PEAK,PEAK],[np.min(y),np.max(y)],'k--',label='PEAK') #plt.hold(True) plt.semilogy([CEN,CEN],[np.min(y),np.max(y)],'r-.',label='CEN') plt.semilogy([COM,COM],[np.min(y),np.max(y)],'g.-.',label='COM') plt.semilogy(x,y,'bo-') plt.xlabel(field);plt.ylabel(intensity_field) plt.legend() plt.title('uid: '+str(uid)+' @ '+str(t)+'\nPEAK: '+str(PEAK_y)[:8]+' @ '+str(PEAK)[:8]+' COM @ '+str(COM)[:8]+ '\n FWHM: '+str(FWHM)[:8]+' @ CEN: '+str(CEN)[:8],size=9) plt.show() else: plt.close(figure_number) plt.figure(figure_number) plt.plot([PEAK,PEAK],[np.min(y),np.max(y)],'k--',label='PEAK') #plt.hold(True) plt.plot([CEN,CEN],[np.min(y),np.max(y)],'r-.',label='CEN') plt.plot([COM,COM],[np.min(y),np.max(y)],'g.-.',label='COM') plt.plot(x,y,'bo-') plt.xlabel(field);plt.ylabel(intensity_field) plt.legend() plt.title('uid: '+str(uid)+' @ '+str(t)+'\nPEAK: '+str(PEAK_y)[:8]+' @ '+str(PEAK)[:8]+' COM @ '+str(COM)[:8]+ '\n FWHM: '+str(FWHM)[:8]+' @ CEN: '+str(CEN)[:8],size=9) plt.show() ### assign values of interest as function attributes: ps.peak=PEAK ps.com=COM
""" Question 38 : Define a function which can generated a list where the values are square of numbers between 1 and 20 (both included). Then the function need to print the last 5 elements in the list. Hints : Use ** operator to get power of a number. Use range() for loop. Use list.append() to add values into a list. Use [n1:n2] to slice a list. """ # Solution : num = int(input("Enter a number : ")) def print_value(): l = list() for i in range(1, num + 1): l.append(i**2) print(l[-5:]) print_value() """ Output : Enter a number : 20 [256, 289, 324, 361, 400] Process finished with exit code 0 """
# Copyright (c) Ville de Montreal. All rights reserved. # Licensed under the MIT license. # See LICENSE file in the project root for full license information. CITYSCAPE_LABELS = [ ('unlabeled', 0, 0, 0, 0), ('ego vehicle', 1, 0, 0, 0), ('rectification border', 2, 0, 0, 0), ('out of roi', 3, 0, 0, 0), ('static', 4, 0, 0, 0), ('dynamic', 5, 111, 74, 0), ('ground', 6, 81, 0, 81), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('parking', 9, 250, 170, 160), ('rail track', 10, 230, 150, 140), ('building', 11, 70, 70, 70), ('wall', 12, 102, 102, 156), ('fence', 13, 190, 153, 153), ('guard rail', 14, 180, 165, 180), ('bridge', 15, 150, 100, 100), ('tunnel', 16, 150, 120, 90), ('pole', 17, 153, 153, 153), ('polegroup', 18, 153, 153, 153), ('traffic light', 19, 250, 170, 30), ('traffic sign', 20, 220, 220, 0), ('vegetation', 21, 107, 142, 35), ('terrain', 22, 152, 251, 152), ('sky', 23, 70, 130, 180), ('person', 24, 220, 20, 60), ('rider', 25, 255, 0, 0), ('car', 26, 0, 0, 142), ('truck', 27, 0, 0, 70), ('bus', 28, 0, 60, 100), ('caravan', 29, 0, 0, 90), ('trailer', 30, 0, 0, 110), ('train', 31, 0, 80, 100), ('motorcycle', 32, 0, 0, 230), ('bicycle', 33, 119, 11, 32), ('license plate', 34, 0, 0, 142)] CARLA_LABELS = [ ('void', 0, 0, 0, 0), ('building', 1, 70, 70, 70), ('fence', 2, 190, 153, 153), ('other', 3, 250, 170, 160), ('pedestrian', 4, 220, 20, 60), ('pole', 5, 153, 153, 153), ('road line', 6, 157, 234, 50), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('vegetation', 9, 107, 142, 35), ('car', 10, 0, 0, 142), ('wall', 11, 102, 102, 156), ('traffic sign', 12, 220, 220, 0)] CGMU_LABELS = [ ('void', 0, 0, 0, 0), ('pole', 1, 255, 189, 176), ('traffic sign', 2, 255, 181, 0), ('vehicle', 3, 247, 93, 195), ('vegetation', 4, 83, 145, 11), ('median strip', 5, 255, 236, 0), ('building', 6, 123, 0, 255), ('private', 7, 255, 0, 0), ('sidewalk', 8, 0, 205, 255), ('road', 9, 14, 0, 255), ('pedestrian', 10, 0, 255, 4), ('structure', 11, 134, 69, 15), ('construction', 12, 255, 99, 0)]
email = input() while True: commands = input().split() command = commands[0] if command == "Complete": break if command == "Make": case = commands[1] if case == "Upper": email = email.upper() elif case == "Lower": email = email.lower() print(email) elif command == "GetDomain": count = int(commands[1]) print(email[-count:]) elif command == "GetUsername": if "@" not in email: print(f"The email {email} doesn't contain the @ symbol.") else: splitted_email = email.split("@") print(f"{splitted_email[0]}") elif command == "Replace": char = commands[1] email = email.replace(char, "-") print(email) elif command == "Encrypt": for s in email: print(ord(s), end=" ")
#tuples are immutable like strings eggs = ('hello', 42, 0.5) eggs[0] 'hello' eggs[1:3] (42, 0.5) print(len(eggs)) type(('hello',)) #class 'tuple' type(('hello')) #class 'str' #Converting Types with the list() and tuple() Functions tuple(['cat', 'dog', 5]) #('cat', 'dog', 5) list(('cat', 'dog', 5)) #['cat', 'dog', 5] list('hello') #['h', 'e', 'l', 'l', 'o']
#!/usr/bin/python class Problem7: ''' 10001st prime Problem 7 104743 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' def solution(self): primes = [] nextPrime = 2 for i in range(10001): print('%d, %d' % (i, nextPrime)) nextPrime = self.getNextPrime(primes) return nextPrime def getNextPrime(self, primes): if (len(primes) == 0): primes.append(2) return 2 if (len(primes) == 1): primes.append(3) return 3 findNewPrime = False nextPrime = primes[-1] + 2 while not findNewPrime: findNewPrime = True for i in primes: if not nextPrime % i: findNewPrime = False break if (findNewPrime): primes.append(nextPrime) break nextPrime += 2 return nextPrime p = Problem7() print(p.solution())
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Contains all abstract class definitions """ __author__ = 'San Kilkis' class AttrDict(dict): """ Nested Attribute Dictionary A class to convert a nested Dictionary into an object with key-values accessibly using attribute notation (AttrDict.attribute) in addition to key notation (Dict["key"]). This class recursively sets Dicts to objects, allowing you to recurse down nested dicts (like: AttrDict.attr.attr) """ def __init__(self, mapping): super(AttrDict, self).__init__() # Initializes the dictionary object w/ mapping for key, value in mapping.items(): self.__setitem__(key, value) def __setitem__(self, key, value): if isinstance(value, dict): # If passed dictionary mapping is a dictionary instead of key, value recurse value = AttrDict(value) super(AttrDict, self).__setitem__(key, value) def __getattr__(self, item): try: return self.__getitem__(item) except KeyError: raise AttributeError(item) __setattr__ = __setitem__
# -*- coding: utf-8 -*- """ Created on Mon Dec 14 13:29:10 2020 @author: Ham """ def locate(ar, target): lft = 0 rgt = len(ar) - 1 while lft <= rgt: mid = (lft + rgt) // 2 if ar[mid] == target: return mid if target < ar[mid]: rgt = mid - 1 else: lft = mid + 1 return -1 #for i,e in enumerate(ar): # if e == target: # return i return -1 ar = range(11, 34) print('locate([],', 20, 'found at', locate(ar, 20)) print('locate([],', 10, 'found at', locate(ar, 10)) print('locate([],', 50, 'found at', locate(ar, 50)) print('locate([],', 11, 'found at', locate(ar, 11)) print('locate([],', 33, 'found at', locate(ar, 33)) print('locate([],', 21, 'found at', locate(ar, 21)) print('locate([],', 22, 'found at', locate(ar, 22)) print('locate([],', 23, 'found at', locate(ar, 23)) print('locate([],', 24, 'found at', locate(ar, 24))
class_ds = \ """A One-Group Light Water Reactor Fuel Cycle Component. This is a daughter class of Reactor1G and a granddaughter of FCComp. Parameters ---------- lib : str, optional The path the the LWR HDF5 data library. This value is set to Reactor1G.libfile and used by Reactor1G.loadlib(). rp : ReactorParameters, optional The physical reactor parameter data to initialize this LWR instance with. If this argument is not provided, default values are taken. n : str, optional The name of this LWR instance. """ desc = { 'docstrings': { 'class': class_ds, 'attrs': {}, 'methods': {}, }, 'attrs': {}, 'extra': {}, } mod = {'LightWaterReactor1G': desc, 'docstring': "Python wrapper for LWR1G.",} desc['docstrings']['methods']['calc_params'] = \ """Along with its own parameter set to track, the LWR model implements its own function to set these parameters. This function is equivalent to the following:: self.params_prior_calc["BUd"] = 0.0 self.params_after_calc["BUd"] = self.BUd self.params_prior_calc["U"] = self.mat_feed_u.mass self.params_after_calc["U"] = self.mat_prod_u.mass self.params_prior_calc["TRU"] = self.mat_feed_tru.mass self.params_after_calc["TRU"] = self.mat_prod_tru.mass self.params_prior_calc["ACT"] = self.mat_feed_act.mass self.params_after_calc["ACT"] = self.mat_prod_act.mass self.params_prior_calc["LAN"] = self.mat_feed_lan.mass self.params_after_calc["LAN"] = self.mat_prod_lan.mass self.params_prior_calc["FP"] = 1.0 - self.mat_feed_act.mass - self.mat_feed_lan.mass """
class Solution: # Top Down DP (Accepted), O(n^2) time, O(1) space def minimumTotal(self, triangle: List[List[int]]) -> int: for i in range(1, len(triangle)): row = triangle[i] row[0] += triangle[i-1][0] row[-1] += triangle[i-1][-1] for j in range(1, len(row)-1): row[j] += min(triangle[i-1][j], triangle[i-1][j-1]) return min(triangle[-1]) # Bottom Up DP (Top Voted), O(n^2) time, O(1) space def minimumTotal(self, triangle: List[List[int]]) -> int: if not triangle: return for i in range(len(triangle)-2, -1, -1): for j in range(len(triangle[i])): triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) return triangle[0][0]
#! /usr/bin/env python #Asking for input until a list of 10 integers given while True: num = input("Enter a list of 10 integers separated by a ',' : ").split(',') l = len(num) try: for i in range(l): num[i] = int(num[i]) p = (l==10) if p: break except: continue #Finding prime numbers prime_num = [] for x in num: if x > 1: for i in range(2,((x//2)+1)): if x % i == 0: break else: prime_num.append(x) elif x == 1: #Number 1 is not considered as prime continue else: #For any negative numbers or 0 continue if len(prime_num) > 0: print(f'Prime numbers from the given list are : {prime_num}') else: print("There were no prime numbers in the given list") print("\nEnd")
#!/usr/bin/env python3 # Lists # Create a list list_1 = [] # Creates an empty list using parantheses list_2 = list() # Creates an empty list using the list() builtin # Lists can accomodate different/multiple data types list_2 = [1, 2, 3] list_3 = ["a", "b", "c"] list_4 = ["a", "hello", 1, "5"] # Lists can accomodate other lists list_5 = [[1, 2, 3], [5, 6, 1]] # Combine a list with an existing list list_6 = list_5.__add__(list_4) # Or list_5 + list_4 print(list_6) print(dir()) # Create a copy of a list # # 1. Use `=` # This is an exact copy, which means any change in one goes in the other # The new list name is just a reference to the same memory address list_copy_1 = list_4 print(id(list_copy_1)) print(id(list_4)) list_copy_1 is list_4 # # 2. Add the elements, rather than assigning the list directly list_copy_2 = list_4[:] print(id(list_copy_1)) print(id(list_4)) list_copy_1 is list_4
class File: def __init__(self, name: str, mode: str): self.file = open(name, mode) def write(self, line: str): self.file.write(line + "\n") def write_dict(self, dict): for key, val in dict.items(): self.write(f"{key}: {val}") def close(self): self.file.close()
""" There are n people, each of them has a unique ID from 0 to n - 1 and each person of them belongs to exactly one group. Given an integer array groupSizes which indicated that the person with ID = i belongs to a group of groupSize[i] persons. Return an array of the groups where ans[j] contains the IDs of the jth group. Each ID should belong to exactly one group and each ID should be present in your answer. Also if a person with ID = i belongs to group j in your answer, then ans[j].length == groupSize[i] should be true. If there is multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input. Example: Input: groupSizes = [3,3,3,3,3,1,3] Output: [[5],[0,1,2],[3,4,6]] Explanation: Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. Example: Input: groupSizes = [2,1,3,3,3,2] Output: [[1],[0,5],[2,3,4]] Constraints: - groupSizes.length == n - 1 <= n <= 500 - 1 <= groupSizes[i] <= n """ #Difficulty: Medium #102 / 102 test cases passed. #Runtime: 72 ms #Memory Usage: 13.7 MB #Runtime: 72 ms, faster than 97.63% of Python3 online submissions for Group the People Given the Group Size They Belong To. #Memory Usage: 13.7 MB, less than 96.74% of Python3 online submissions for Group the People Given the Group Size They Belong To. class Solution: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: groups = {} result = [] for i, n in enumerate(groupSizes): if n not in groups: groups[n] = [] groups[n].append(i) for i in groups.keys(): while groups[i]: result.append(groups[i][:i]) groups[i] = groups[i][i:] return result
query_set = [ "SELECT subscriber.s_id, subscriber.sub_nbr, \ subscriber.bit_1, subscriber.bit_2, subscriber.bit_3, subscriber.bit_4, subscriber.bit_5, subscriber.bit_6, subscriber.bit_7, \ subscriber.bit_8, subscriber.bit_9, subscriber.bit_10, \ subscriber.hex_1, subscriber.hex_2, subscriber.hex_3, subscriber.hex_4, subscriber.hex_5, subscriber.hex_6, subscriber.hex_7, \ subscriber.hex_8, subscriber.hex_9, subscriber.hex_10, \ subscriber.byte2_1, subscriber.byte2_2, subscriber.byte2_3, subscriber.byte2_4, subscriber.byte2_5, \ subscriber.byte2_6, subscriber.byte2_7, subscriber.byte2_8, subscriber.byte2_9, subscriber.byte2_10, \ subscriber.msc_location, subscriber.vlr_location \ FROM subscriber \ WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size>; ",35, # was 35 "SELECT call_forwarding.numberx \ FROM special_facility, call_forwarding \ WHERE \ (special_facility.s_id = <non_uniform_rand_int_subscriber_size> \ AND special_facility.sf_type = <rand_int_1_4> \ AND special_facility.is_active = 1) \ AND (call_forwarding.s_id = special_facility.s_id \ AND call_forwarding.sf_type = special_facility.sf_type) \ AND (call_forwarding.start_time <= <rand_0_8_16> \ AND call_forwarding.end_time >= <rand_1_to_24>);",10, # was 10 "SELECT access_info.data1, access_info.data2, access_info.data3, access_info.data4 \ FROM access_info \ WHERE access_info.s_id = <non_uniform_rand_int_subscriber_size> \ AND access_info.ai_type = <rand_int_1_4>;",35, # was 35 "UPDATE subscriber, special_facility \ SET subscriber.bit_1 = <bit_rand>, special_facility.data_a = <rand_int_1_255> \ WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size> \ AND special_facility.s_id = <non_uniform_rand_int_subscriber_size> \ AND special_facility.sf_type = <rand_int_1_4>;", 2, # Was 2 "UPDATE subscriber \ SET subscriber.vlr_location = <rand_int_1_big> \ WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';",14, # Was 14 "INSERT INTO call_forwarding (call_forwarding.s_id, call_forwarding.sf_type, call_forwarding.start_time, call_forwarding.end_time, call_forwarding.numberx) \ SELECT subscriber.s_id, special_facility.sf_type ,<rand_0_8_16>,<rand_1_to_24>, <non_uniform_rand_int_subscriber_size> \ FROM subscriber \ LEFT OUTER JOIN special_facility ON subscriber.s_id = special_facility.s_id \ WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>' \ ORDER BY RAND() LIMIT 1;",2, # Was 2, but self-conflicting was an issue. "DELETE call_forwarding FROM call_forwarding \ INNER JOIN subscriber ON subscriber.s_id = call_forwarding.s_id \ WHERE call_forwarding.sf_type = <rand_int_1_4> \ AND call_forwarding.start_time = <rand_0_8_16> \ AND subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';",2, # Was 2 ]
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ ## DP dp = [False for _ in range(len(s) + 1)] dp[0] = True for j in range(1, len(s) + 1): for i in range(0, j): if dp[i] and s[i:j] in wordDict: dp[j] = True break return dp[-1] ## recursive solution with memory self.record=set([]) if not wordDict: return False self.r=list(set([len(x) for x in wordDict])) return self.helper(s, wordDict) def helper(self, s, wordDict): if not s: return True if s in self.record: return False if not wordDict: return False # return minLength, maxLength for i in self.r: if s[:i] in wordDict: # if s[:i] in wordDict: if self.helper(s[i:], wordDict): return True self.record.add(s) return False
## https://leetcode.com/problems/find-all-duplicates-in-an-array/ ## pretty simple solution -- use a set to keep track of the numbers ## that have already appeared (because lookup time is O(1) given ## the implementation in python via a hash table). Gives me an O(N) ## runtime ## runetime is 79th percentile; memory is 19th percentile class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: already_appeared = set([]) twice = [] while len(nums): n = nums.pop() if n in already_appeared: twice.append(n) else: already_appeared.add(n) return twice
world_cities = ['Dubai', 'New Orleans', 'Santorini', 'Gaza', 'Seoul'] print('***********') print(world_cities) print('***********') print(sorted(world_cities)) print('***********') print(world_cities) print('***********') print(sorted(world_cities, reverse=True)) print('***********') print(world_cities) print('***********') world_cities.reverse() print('***********') print(world_cities) world_cities.reverse() print('***********') print(world_cities) print('***********') world_cities.sort() print(world_cities)
# Given a non-negative integer num, return the number of steps to reduce it to zero. # If the current number is even, you have to divide it by 2, # otherwise, you have to subtract 1 from it. def count_steps(num): steps = 0 while num != 0: if num % 2 == 1: num -= 1 else: num /= 2 steps += 1 return steps
# https://leetcode.com/problems/is-subsequence/ class Solution: def isSubsequence(self, s: str, t: str) -> bool: if len(s) == 0: return True sIndex = 0 for tIndex, tChar in enumerate(t): if s[sIndex] == tChar: sIndex += 1 if sIndex == len(s): return True return False
# # PySNMP MIB module H3C-FTM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-FTM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:09:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") h3cCommon, = mibBuilder.importSymbols("HUAWEI-3COM-OID-MIB", "h3cCommon") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") MibIdentifier, Gauge32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ModuleIdentity, Counter64, iso, ObjectIdentity, Unsigned32, IpAddress, TimeTicks, Counter32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ModuleIdentity", "Counter64", "iso", "ObjectIdentity", "Unsigned32", "IpAddress", "TimeTicks", "Counter32", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") h3cFtmManMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1)) if mibBuilder.loadTexts: h3cFtmManMIB.setLastUpdated('200401131055Z') if mibBuilder.loadTexts: h3cFtmManMIB.setOrganization('HUAWEI-3COM TECHNOLOGIES.') h3cFtm = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1)) h3cFtmManMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1)) h3cFtmUnitTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1), ) if mibBuilder.loadTexts: h3cFtmUnitTable.setStatus('current') h3cFtmUnitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1), ).setIndexNames((0, "H3C-FTM-MIB", "h3cFtmIndex")) if mibBuilder.loadTexts: h3cFtmUnitEntry.setStatus('current') h3cFtmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 1), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: h3cFtmIndex.setStatus('current') h3cFtmUnitID = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmUnitID.setStatus('current') h3cFtmUnitName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 3), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmUnitName.setStatus('current') h3cFtmUnitRole = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("master", 0), ("slave", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cFtmUnitRole.setStatus('current') h3cFtmNumberMode = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("automatic", 0), ("manual", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cFtmNumberMode.setStatus('current') h3cFtmAuthMode = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("ftm-none", 0), ("ftm-simple", 1), ("ftm-md5", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmAuthMode.setStatus('current') h3cFtmAuthValue = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 3), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmAuthValue.setStatus('current') h3cFtmFabricVlanID = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmFabricVlanID.setStatus('current') h3cFtmFabricType = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("outofStack", 1), ("line", 2), ("ring", 3), ("mesh", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cFtmFabricType.setStatus('current') h3cFtmManMIBNotification = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3)) h3cFtmUnitIDChange = NotificationType((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmIndex"), ("H3C-FTM-MIB", "h3cFtmUnitID")) if mibBuilder.loadTexts: h3cFtmUnitIDChange.setStatus('current') h3cFtmUnitNameChange = NotificationType((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 2)).setObjects(("H3C-FTM-MIB", "h3cFtmIndex"), ("H3C-FTM-MIB", "h3cFtmUnitName")) if mibBuilder.loadTexts: h3cFtmUnitNameChange.setStatus('current') h3cFtmManMIBComformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2)) h3cFtmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1)) h3cFtmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmConfigGroup"), ("H3C-FTM-MIB", "h3cFtmNotificationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cFtmMIBCompliance = h3cFtmMIBCompliance.setStatus('current') h3cFtmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2)) h3cFtmConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmUnitID"), ("H3C-FTM-MIB", "h3cFtmUnitName"), ("H3C-FTM-MIB", "h3cFtmAuthMode"), ("H3C-FTM-MIB", "h3cFtmAuthValue"), ("H3C-FTM-MIB", "h3cFtmFabricVlanID"), ("H3C-FTM-MIB", "h3cFtmFabricType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cFtmConfigGroup = h3cFtmConfigGroup.setStatus('current') h3cFtmNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 2)).setObjects(("H3C-FTM-MIB", "h3cFtmUnitIDChange"), ("H3C-FTM-MIB", "h3cFtmUnitNameChange")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cFtmNotificationGroup = h3cFtmNotificationGroup.setStatus('current') mibBuilder.exportSymbols("H3C-FTM-MIB", h3cFtmUnitID=h3cFtmUnitID, h3cFtmManMIBObjects=h3cFtmManMIBObjects, h3cFtmManMIBNotification=h3cFtmManMIBNotification, h3cFtmFabricVlanID=h3cFtmFabricVlanID, h3cFtmNotificationGroup=h3cFtmNotificationGroup, h3cFtmNumberMode=h3cFtmNumberMode, h3cFtm=h3cFtm, h3cFtmManMIBComformance=h3cFtmManMIBComformance, h3cFtmUnitRole=h3cFtmUnitRole, h3cFtmUnitEntry=h3cFtmUnitEntry, h3cFtmManMIB=h3cFtmManMIB, h3cFtmMIBCompliances=h3cFtmMIBCompliances, h3cFtmMIBCompliance=h3cFtmMIBCompliance, h3cFtmFabricType=h3cFtmFabricType, h3cFtmAuthMode=h3cFtmAuthMode, h3cFtmAuthValue=h3cFtmAuthValue, h3cFtmUnitName=h3cFtmUnitName, PYSNMP_MODULE_ID=h3cFtmManMIB, h3cFtmConfigGroup=h3cFtmConfigGroup, h3cFtmIndex=h3cFtmIndex, h3cFtmMIBGroups=h3cFtmMIBGroups, h3cFtmUnitIDChange=h3cFtmUnitIDChange, h3cFtmUnitTable=h3cFtmUnitTable, h3cFtmUnitNameChange=h3cFtmUnitNameChange)
# Row-by-column representation of the board BOARD_SIZE = 6, 7 # Define size of each cell in the GUI of the game CELL_SIZE = 100 # Define radius of dot RADIUS = (CELL_SIZE // 2) - 5 # Define size of GUI screen GUI_SIZE = (BOARD_SIZE[0] + 1) * CELL_SIZE, (BOARD_SIZE[1]) * CELL_SIZE # Define various colors used on the GUI of the game RED = 255, 0, 0 BLUE = 0, 0, 255 BLACK = 0, 0, 0 WHITE = 255, 255, 255 YELLOW = 255, 255, 0 # Define various players in the Game HUMAN_PLAYER = 0 Q_ROBOT = 1 RANDOM_ROBOT = 2 MINI_MAX_ROBOT = 3 # Define various rewards REWARD_WIN = 1 REWARD_LOSS = -1 REWARD_DRAW = 0.2 REWARD_NOTHING = 0 # Define various modes of the game GAME_NAME = 'CONNECT-4' GAME_MODES = {0: '2 Players', 1: 'vs Computer'} # Define various modes of learning LEARNING_MODES = {'random_agent': 0, 'trained_agent': 1, 'minimax_agent': 2} NO_TOKEN = 0 # Define location of memory file MEM_LOCATION = 'memory/memory.npy' # Define variable to store no. of iterations to train the game robot ITERATIONS = 100 # Define depth of mini-max player MINI_MAX_DEPTH = 5
'''This tnsertion sort algorithm which is shown in most websites and books, is slower than another insertion sort algorithm.''' def insertion_sort_slow(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key #insertionSort(arr) #for i in range(len(arr)): # print ("% d" % arr[i])
"""class krypton_patch: def __init__(self, driver) -> None: self.driver = driver self.js = driver.driver.execute_script driver.driver.execute_script("javascript/index.js") #patch 0.1 def FakeReply(self, korban, pesan, chat_id, MsgId, teks): return self.js(f"return await FakeReply(\"{chat_id}\", \"{MsgId}\", \"{pesan}\", \"{korban}\", \"{teks}\")") def hidetag(self, chat_id, body, msg): return self.js(f"return await HideTagged(\"{chat_id}\", \"{body}\", \"{msg}\")")"""
# Solution for the problem "Cats and a mouse" # https://www.hackerrank.com/challenges/cats-and-a-mouse/problem # Number of test cases numQueries = int(input()) # Running the queries for queryIndex in range(0, numQueries): # Locations of Cat A, Cat B and mouse locCatA, locCatB, locMouse = map(int, input().strip().split(' ')) # Distance between Cat A and mouse distCatA = abs(locCatA - locMouse) # Distance between Cat B and mouse distCatB = abs(locCatB - locMouse) # Mouse escapes if both distances are equal if distCatA == distCatB: print("Mouse C") # Cat A is nearer elif distCatA < distCatB: print("Cat A") # Cat B is nearer else: print("Cat B")
""" DESCRIPTION: Write a code to extract each digit from an integer, in the reverse order EXAMPLE Input: n = 1234 Output: "4 3 2 1" """ def main(n: int) -> str: ret_val: str = "" # Enter the code below return ret_val
# configuration for building the network y_dim = 6 tr_dim = 7 ir_dim = 10 latent_dim = 128 z_dim = 128 batch_size = 128 lr = 0.0002 beta1 = 0.5 # configuration for the supervisor logdir = "./log" sampledir = "./example" max_steps = 30000 sample_every_n_steps = 100 summary_every_n_steps = 1 save_model_secs = 120 checkpoint_basename = "layout" checkpoint_dir = "./checkpoints" filenamequeue = "./dataset/layout_1205.tfrecords" min_after_dequeue = 5000 num_threads = 4
N = int(input()) s = [input() for _ in range(N)] for y in range(N): for x in range(N): print(s[N - 1 - x][y], end='') print('')
class Message(object): """`Message` stores the SMS text and the originating phone number. """ def __init__(self, from_number, text, provider=None, *args, **kwargs): self.from_number = from_number self.text = text self._provider = provider def reply(self, text): self._provider.send(self.from_number, text) def __repr__(self): return '[{} - {}]'.format(self.from_number, self.text)
S = input() def check_even(stri): if len(stri) % 2 !=0: return False else: half = int(len(stri)/2) if stri[:half] == stri[half:]: return True else: return False for i in range(len(S)): if check_even(S[:-(i+1)]): print(len(S)-(i+1)) exit()
N = int(input("Cuantos digitos quiere ingresar? ")) lista = [] lista2 = [] for i in range(N): lista.append(int(input("Digite un numero: "))) print("Su lista es: ", lista) for i in range(N): lista2.append(1*(lista[i]+1)) print("La segunda lista es: ", lista2)
# 各漫画のHTMLを作成 def make_html(output_path, src_path, manga_title): with open(src_path + "/template.html") as f: html = f.read().replace("manga_title", manga_title) with open(output_path + "/" + manga_title + "/index.html", "w") as f: f.write(html)
# @dependency 001-main/002-createrepository.py frontend.json( "repositories", expect={ "repositories": [critic_json] }) frontend.json( "repositories/1", expect=critic_json) frontend.json( "repositories", params={ "name": "critic" }, expect=critic_json) frontend.json( "repositories/4711", expect={ "error": { "title": "No such resource", "message": "Resource not found: Invalid repository id: 4711" }}, expected_http_status=404) frontend.json( "repositories/critic", expect={ "error": { "title": "Invalid API request", "message": "Invalid numeric id: 'critic'" }}, expected_http_status=400) frontend.json( "repositories", params={ "name": "nosuchrepository" }, expect={ "error": { "title": "No such resource", "message": "Resource not found: Invalid repository name: 'nosuchrepository'" }}, expected_http_status=404) frontend.json( "repositories", params={ "filter": "interesting" }, expect={ "error": { "title": "Invalid API request", "message": "Invalid repository filter parameter: 'interesting'" }}, expected_http_status=400)
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # Copyright (C) 2020 Daniel Rodriguez # Use of this source code is governed by the MIT License ############################################################################### __all__ = [ 'SEED_AVG', 'SEED_LAST', 'SEED_SUM', 'SEED_NONE', 'SEED_ZERO', 'SEED_ZFILL', '_INCPERIOD', '_DECPERIOD', '_MINIDX', '_SERIES', '_MPSERIES', '_SETVAL', '_MPSETVAL', ] SEED_AVG = 0 SEED_LAST = 1 SEED_SUM = 2 SEED_NONE = 4 SEED_ZERO = 5 SEED_ZFILL = 6 def _INCPERIOD(x, p=1): ''' Forces an increase `p` in the minperiod of object `x`. Example: `ta-lib` calculates `+DM` a period of 1 too early, but calculates the depending `+DI` from the right starting point. Increasing the period, without changing the underlying already calculated `+DM` values, allows the `+DI` values to be right ''' x._minperiod += p def _DECPERIOD(x, p=1): ''' Forces an increase `p` in the minperiod of object `x`. Example: `ta-lib` calculates `obv` already when the period is `1`, discarding the needed "close" to "previous close" comparison. The only way to take this into account is to decrease the delivery period of the comparison by 1 to start the calculation before (and using a fixed criterion as to what to do in the absence of a valid close to close comparison) ''' x._minperiod -= p def _MINIDX(x, p=0): ''' Delivers the index to an array which corresponds to `_minperiod` offset by `p`. This allow direct manipulation of single values in arrays like in the `obv` scenario in which a seed value is needed for the 1st delivered value (in `ta-lib` mode) because no `close` to `previous close` comparison is possible. ''' return x._minperiod - 1 + p def _SERIES(x): '''Macro like function which makes clear that one is retrieving the actual underlying series and not something a wrapped version''' return x._series def _MPSERIES(x): '''Macro like function which makes clear that one is retrieving the actual underlying series, sliced starting at the MINPERIOD of the series''' return x._series[x._minperiod - 1:] def _SETVAL(x, idx, val): '''Macro like function which makes clear that one is setting a value in the underlying series''' x._series[idx] = val def _MPSETVAL(x, idx, val): '''Macro like function which makes clear that one is setting a value in the underlying series''' x._series[x._minperiod - 1 + idx] = val
##Patterns: E0103 def test(): while True: break ##Err: E0103 break for letter in 'Python': if letter == 'h': continue ##Err: E0103 continue
def checkio(f, g): def call(function, *args, **kwargs): try: return function(*args, **kwargs) except Exception: return None def h(*args, **kwargs): value_f, value_g = call(f, *args, **kwargs), call(g, *args, **kwargs) status = "" if (value_f is None and value_g is None): status = "both_error" elif (value_f is None): status = "f_error" elif (value_g is None): status = "g_error" elif (value_f == value_g): status = "same" else: status = "different" if (value_f is None and value_g is None): return (None, status) elif (value_f is None): return (value_g, status) else: return (value_f, status) return h if __name__ == "__main__": #These "asserts" using only for self-checking and not necessary for auto-testing # (x+y)(x-y)/(x-y) assert checkio(lambda x,y:x+y, lambda x,y:(x**2-y**2)/(x-y))\ (1,3)==(4,"same"), "Function: x+y, first" assert checkio(lambda x,y:x+y, lambda x,y:(x**2-y**2)/(x-y))\ (1,2)==(3,"same"), "Function: x+y, second" assert checkio(lambda x,y:x+y, lambda x,y:(x**2-y**2)/(x-y))\ (1,1.01)==(2.01,"different"), "x+y, third" assert checkio(lambda x,y:x+y, lambda x,y:(x**2-y**2)/(x-y))\ (1,1)==(2,"g_error"), "x+y, fourth" # Remove odds from list f = lambda nums:[x for x in nums if ~x%2] def g(nums): for i in range(len(nums)): if nums[i]%2==1: nums.pop(i) return nums assert checkio(f,g)([2,4,6,8]) == ([2,4,6,8],"same"), "evens, first" assert checkio(f,g)([2,3,4,6,8]) == ([2,4,6,8],"g_error"), "evens, second" # Fizz Buzz assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n), lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\ (6)==("Fizz","same"), "fizz buzz, first" assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n), lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\ (30)==("Fizz Buzz","same"), "fizz buzz, second" assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n), lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\ (7)==("7","different"), "fizz buzz, third"
# -------------- # Code starts here class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio'] class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes'] new_class = class_1+class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses = {'Math':65, 'English':70, 'History':80, 'French': 70, 'Science':60} total = sum(courses.values()) print(total) percentage = total/500*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 60, 'Peter Warden': 75} topper = max(mathematics,key = mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here print('-'*20) first_name = topper.split()[0] last_name = topper.split()[1] full_name = f'{last_name} {first_name}' print(full_name) certificate_name = full_name.upper() print(certificate_name) # Code ends here
N = int(input()) a,b = 1,1 print(0,end=' ') for i in range(1,N-1): if i != N: print(a,end=' ') a,b = b,a+b print(a,end='\n')
# This is a dummy file to allow the automatic loading of modules without error on none. def setup(robot_config): return def say(*args): return def mute(): return def unmute(): return def volume(level): return
class FeeValidator: def __init__(self, specifier) -> None: super().__init__() self.specifier = specifier def validate(self, fee): failed=False try: if fee != 0 and not 1 <= fee <= 100: failed=True except TypeError: failed=True if failed: raise Exception("Fee for {} cannot be {}. Valid values are 0, [1-100]".format(self.specifier, fee))
#!/usr/bin/env python3 """ Get information on the inferface. """ help(gdb) help(gdb.command) help(gdb.events) help(gdb.function)
INSERT_ONE_BY_BYTE = "insert_one_by_byte" INSERT_ONE_BY_PATH = "insert_one_by_path" INSERT_MANY_BY_BYTE = "insert_many_by_byte" INSERT_MANY_BY_DIR = "insert_many_by_dir" INSERT_MANY_BY_PATHS = "insert_many_by_paths" DELETE_ONE_BY_ID = "delete_one_by_id" DELETE_MANY_BY_IDS = "delete_many_by_ids" DELETE_ALL = "delete_all" UPDATE_ONE_BY_ID = "update_one_by_id" UPDATE_MANY_BY_IDS = "update_many_by_ids" RETRIEVE_ONE = "retrieve_one" RETRIEVE_MANY = "retrieve_many" QUERY_NEAREST_BY_CONTENT = "query_nearest_by_content" QUERY_NEAREST_BY_STYLE = "query_nearest_by_style" QUERY_FARTHEST_BY_CONTENT = "query_farthest_by_content" QUERY_FARTHEST_BY_STYLE = "query_farthest_by_style" QUERY_BY_TAG_ALL = "query_by_tag_all" QUERY_BY_TAG_PARTIAL = "query_by_tag_partial" QUERY_RANGE_BY_CONTENT = "query_range_by_content" QUERY_RANGE_BY_STYLE = "query_range_by_style" BROWSE_BY_RANDOM = "browse_by_random" BROWSE_BY_CLUSTER = "browse_by_cluster"
lista = [] lista_par = [] lista_impar = [] while True: n = (int(input('Digite os numeros: '))) lista.append(n) if n % 2 == 0: lista_par.append(n) else: lista_impar.append(n) res = str(input('Quer continuar [S/N] : ')) if res in 'Nn': break print(f'O numeros da lista fora : {lista}') print(f'O numeros pares foram : {lista_par}') print(f'O numeros impares foram : {lista_impar}')
input = """ 1 2 0 0 1 3 0 0 1 4 0 0 1 5 0 0 1 6 0 0 1 7 0 0 1 8 0 0 1 9 0 0 1 10 0 0 1 11 0 0 1 12 0 0 1 13 0 0 1 14 0 0 1 15 0 0 1 16 0 0 1 17 0 0 1 18 1 1 19 1 20 1 1 21 1 22 1 1 23 1 24 1 1 25 1 26 1 1 27 1 28 1 1 29 1 19 1 1 18 1 21 1 1 20 1 23 1 1 22 1 25 1 1 24 1 27 1 1 26 1 29 1 1 28 1 1 1 1 18 2 30 2 0 2 22 20 1 1 1 1 30 2 31 3 0 1 28 26 24 1 32 1 1 31 1 1 1 1 32 2 33 3 0 2 24 20 18 2 34 3 0 3 24 20 18 1 35 2 1 34 33 1 1 1 1 35 2 36 1 0 1 26 1 37 1 1 36 1 1 1 1 37 2 38 2 0 1 28 22 2 39 2 0 2 28 22 1 40 2 1 39 38 1 1 1 1 40 1 1 2 0 20 19 1 1 2 0 22 19 1 1 2 0 24 21 1 1 2 0 24 23 1 1 2 0 26 21 1 1 2 0 26 23 1 1 2 0 28 21 1 1 2 0 28 23 1 1 2 0 20 23 1 1 2 0 22 21 1 1 2 0 24 27 1 1 2 0 24 29 1 1 2 0 26 25 1 1 2 0 26 29 1 1 2 0 28 25 1 1 2 0 28 27 0 2 xsucc(1,2) 3 xsucc(2,3) 18 filled(3,3) 20 filled(3,2) 22 filled(1,2) 24 filled(3,1) 26 filled(2,1) 28 filled(1,1) 4 ysucc(1,2) 5 ysucc(2,3) 19 unfilled(3,3) 21 unfilled(3,2) 23 unfilled(1,2) 25 unfilled(3,1) 27 unfilled(2,1) 29 unfilled(1,1) 12 xvalue(1,0) 13 xvalue(2,2) 14 xvalue(3,1) 6 bottle(1,1,1) 7 bottle(1,2,1) 8 bottle(1,3,1) 9 bottle(1,1,2) 10 bottle(1,3,2) 11 bottle(1,3,3) 15 yvalue(1,1) 16 yvalue(2,0) 17 yvalue(3,2) 0 B+ 0 B- 1 0 1 """ output = """ {xsucc(1,2), xsucc(2,3), ysucc(1,2), ysucc(2,3), bottle(1,1,1), bottle(1,2,1), bottle(1,3,1), bottle(1,1,2), bottle(1,3,2), bottle(1,3,3), xvalue(1,0), xvalue(2,2), xvalue(3,1), yvalue(1,1), yvalue(2,0), yvalue(3,2), filled(3,3), filled(3,2), filled(1,2), unfilled(3,1), unfilled(2,1), unfilled(1,1)} """
test = [11.0, "Alice has a cat", 12, 4, "5"] print("len(test) = " + str(len(test))) print("test[1] = " + str(test[1])) print("test[3:6] = " + str(test[3:6])) print("test[1:6:2] = " + str(test[1:6:2])) print("test[:6] = " + str(test[:6])) print("test[-2] = " + str(test[-2])) test.append(121) test2 = test + [1, 2, 3] print("len(test2) = " + str(len(test2))) test2[0] = "Lodz" test2[6] = 77 print(test2)
class dotStringProperty_t(object): # no doc aName=None aValueString=None FatherId=None ValueStringIteration=None
#!/usr/bin/env python # encoding: utf-8 # The MIT License # # Copyright (c) 2011 Wyss Institute at Harvard University # # 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. # # http://www.opensource.org/licenses/mit-license.php class Modifier(object): """ Modifiers do affect an applied sequence and do not store a sequence themselves. They cause a base changed to another sequence. Modifiers DO NOT affect the length of a strand """ def __init__(self, idx): if self.__class__ == Modifier: e = "Modifier should be subclassed." raise NotImplementedError(e) self._mType = None self._lowIdx = idx self._highIdx = self._lowIdx self._privateSequence = None # end def def length(self): """ This is the length of a sequence that is immutable by the strand """ return self._highIdx - self._lowIdx + 1 def modifierType(self): return self._mtype # end class
# pylint: disable=missing-function-docstring, missing-module-docstring/ @toto # pylint: disable=undefined-variable def f(): pass
class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: An object of TreeNode, denote the root of the binary tree. This method will be invoked first, you should design your own algorithm to serialize a binary tree which denote by a root node to a string which can be easily deserialized by your own "deserialize" method later. """ def serialize(self, root): result = [] self.serializeHelper(root,result) return ",".join(result) def serializeHelper(self,root,result) : if root is None : result.append('$') return result.append(str(root.val)) self.serializeHelper(root.left,result) self.serializeHelper(root.right,result) """ @param data: A string serialized by your serialize method. This method will be invoked second, the argument data is what exactly you serialized at method "serialize", that means the data is not given by system, it's given by your own serialize method. So the format of data is designed by yourself, and deserialize it here as you serialize it in "serialize" method. """ def deserialize(self, data): self.index = 0 return self.deserializeHelper(data.split(',')) def deserializeHelper(self,data): if self.index == len(data) : return None if data[self.index] == '$' : self.index += 1 return None root = TreeNode(data[self.index]) self.index += 1 root.left = self.deserializeHelper(data) root.right = self.deserializeHelper(data) return root
x = 50 def func(x): print('x is',x) x = 2 print('Changed local x to',x) func(x) print('x is still',x)
# -*- coding:UTF-8 -*- # Author:Tiny Snow # Date: Mon, 22 Feb 2021, 13:49 # Project Euler # 045 Triangular, pentagonal, and hexagonal #======================================================================================================Solution def is_pentagon(num): n = int(((2 / 3) * num) ** 0.5) + 1 if n * (3 *n - 1) == 2 * num: return True return False def is_hexagon(num): n = int((num / 2) ** 0.5) + 1 if n * (2 *n - 1) == num: return True return False start = 286 while True: if is_pentagon(start * (start + 1) // 2) == True and is_hexagon(start * (start + 1) // 2) == True: break start += 1 print(start * (start + 1) // 2)
"""Adapters for twisted.vfs. This package provides adapters to hook up systems SFTP and FTP to the IFileSystemLeaf and IFileSystemDirectory interfaces of VFS. """
class WebEncoderException(Exception): pass class InvalidEncodingErrors(WebEncoderException): """Exception raised for errors in the input value of encoding_errors attribute of WebEncoder class. Args: message: explanation of the error """ def __init__(self, message=None): self.message = ( message or "Invalid encoding_errors value. It should be 'strict', 'ignore', 'replace' or 'xmlcharrefreplace'." ) super().__init__(self.message) class InvalidStringType(WebEncoderException): """Exception raised for errors in the input value of _string into _string_to_bytes method of WebEncoder class. Args: message: explanation of the error """ def __init__(self, message=None): self.message = message or "The _string need to be str type." super().__init__(self.message) class InvalidBytesType(WebEncoderException): """Exception raised for errors in the input value of _bytes into methods of WebEncoder class. Args: message: explanation of the error """ def __init__(self, message=None): self.message = message or "The _bytes need to be bytes type." super().__init__(self.message) class InvalidDataType(WebEncoderException): """Exception raised for errors in the input value of data into encode method of WebEncoder class. Args: message: explanation of the error """ def __init__(self, message=None): self.message = message or "The data need to be str type." super().__init__(self.message) class InvalidEncodedDataType(WebEncoderException): """Exception raised for errors in the input value of encoded_data into decode method of WebEncoder class. Args: message: explanation of the error """ def __init__(self, message=None): self.message = message or "The encoded_data need to be str type." super().__init__(self.message) class DataDecodeError(WebEncoderException): """Exception raised for data decoding error in _bytes_to_string of WebEncoder class. Args: message: explanation of the error """ def __init__(self, message=None): self.message = message or "Could not decode the message." super().__init__(self.message) class CannotBeCompressed(WebEncoderException): """Exception raised for errors in the _compress_data method of WebEncoder class. Args: message: explanation of the error """ def __init__(self, message=None): self.message = message or "The data cannot be compressed." super().__init__(self.message) class CannotBeDecompressed(WebEncoderException): """Exception raised for errors in the _decompress_data method of WebEncoder class. Args: message: explanation of the error """ def __init__(self, message=None): self.message = message or "The data cannot be decompressed." super().__init__(self.message)
class Node(): def __init__(self, value="", frequency=0.0): self.frequency = frequency self.value = value self.children = {} self.stop = False def __getitem__(self, key): if key in self.children: return self.children[key] return None def __setitem__(self, key, value): self.children[key] = value def __contains__(self, key): return key in self.children def __str__(self): return self.value def __iter__(self): for key in sorted(self.children.keys()): yield key def __delitem__(self, key): del self.children[key] class Trie: def __init__(self): self.root = Node() def add_word(self, word, frequency): word = word.lower() current_node = self.root for letter in word: if letter not in current_node: current_node[letter] = Node(letter) current_node = current_node[letter] current_node.stop = True current_node.frequency = frequency @staticmethod def get_possible_matches(node, words_list, path): if node.stop: words_list.append((path + node.value, node.frequency)) for letter in node.children: Trie.get_possible_matches(node.children[letter], words_list, path + node.value) def match_suffix(self, word): current_node = self.root for letter in word.lower(): if letter in current_node: current_node = current_node[letter] # word += current_node.value else: return False possible_words = [] self.get_possible_matches(current_node, possible_words, word[:-1]) return possible_words def contains(self, word): current_node = self.root path = "" for letter in word.lower(): if letter not in current_node: return False else: path += letter current_node = current_node[letter] if current_node.stop: return True return False def __contains__(self, key): return self.contains(key) @staticmethod def _print(node, path=""): if node.stop: print(path + node.value, node.frequency) for letter in node.children: Trie._print(node.children[letter], path + node.value) def print_content(self): for letter in self.root.children: self._print(self.root[letter]) if __name__ == "__main__": t = Trie() t.add_word("kaka") t.add_word("kakan") t.add_word("kakor") t.print_content() print("---------------") print(t.contains("kaka"))
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"PairwiseDistance": "00_distance.ipynb", "pairwise_dist_gram": "00_distance.ipynb", "stackoverflow_pairwise_distance": "00_distance.ipynb", "PairwiseDistance.stackoverflow_pairwise_distance": "00_distance.ipynb", "torch_pairwise_distance": "00_distance.ipynb", "PairwiseDistance.torch_pairwise_distance": "00_distance.ipynb", "measure_execution_time": "00_distance.ipynb", "get_time_stats": "00_distance.ipynb", "DistanceMatrixIndexMapper": "00_distance.ipynb", "Hull": "00_distance.ipynb", "to_2dpositions": "00_distance.ipynb", "Hull.to_2dpositions": "00_distance.ipynb", "plot_atoms_and_hull": "00_distance.ipynb"} modules = ["distance.py"] doc_url = "https://eschmidt42.github.io/md/" git_url = "https://github.com/eschmidt42/md/tree/master/" def custom_doc_links(name): return None
class AppUserProfile: types = { 'username': str, 'password': str } def __init__(self): self.username = None # str self.password = None # str
"""Hydra Library Tools & Applications. """ __all__ = ( "app", "hy", "log", "rpc", "test", "util" ) VERSION = "2.6.5"
class Container: def __init__(self, container=None): if container == None or type(container) != dict: self._container = dict() else: self._container = container def __iter__(self): return iter(self._container.items()) def addObject(self, name, object_:object): self._container[name] = object_ def hasObject(self, name): return self._container.get(name) is not None def getObject(self, name) -> object: return self._container.get(name) def delete(self, name) -> object: return self._container.pop(name) def clearAll(self): self._container.clear()
""" Ilustração lista = ['Ian', 80kg] 0 1 """ cadastro = [] dados = [] mai = 0 men = 0 x = 0 resposta = 's' print('----------CADASTRO DE PESSOAS----------') while resposta == 's': resposta = input("Deseja cadastra uma pessoa? [s/n] ") if resposta == 'n': break elif resposta != 's' and resposta != 'n': print('Resposta Inválida') break cadastro.append(str(input("Nome: "))) if cadastro == float: print('Resposta inválida') cadastro.append(float(input("Peso (kg): "))) if x == 0: mai = cadastro[1] men = cadastro[1] else: if cadastro[1] >= mai: mai = cadastro[1] else: men = cadastro[1] dados.append(cadastro[:]) # Ligação entre o cadastro e os dados cadastro.clear x += 1 print(f'O total de pessoas cadastradas foram {x}') print(f'O maior peso foi de {mai}kg, pertencente a ', end='') for d in dados: if d[1] == mai: print(f'e [{d[0]}]', end='') print() print(f'O menor peso foi de {men}kg, pertencente a ') for d in dados: if d[1] == men: print(f'e [{d[0]}]', end='') print()
# -*- coding: utf-8 -*- DESC = "cvm-2017-03-12" INFO = { "CreateImage": { "params": [ { "name": "ImageName", "desc": "Image name" }, { "name": "InstanceId", "desc": "Instance ID used to create an image." }, { "name": "ImageDescription", "desc": "Image description" }, { "name": "ForcePoweroff", "desc": "Whether to force shut down an instance to create an image when a soft shutdown fails" }, { "name": "Sysprep", "desc": "Whether to enable Sysprep when creating a Windows image" }, { "name": "DataDiskIds", "desc": "Specified data disk ID included in the full image created from the instance." }, { "name": "SnapshotIds", "desc": "Specified snapshot ID used to create an image. A system disk snapshot must be included. It cannot be passed together with `InstanceId`." }, { "name": "DryRun", "desc": "Success status of this request, without affecting the resources involved" } ], "desc": "This API is used to create a new image with the system disk of an instance. The image can be used to create new instances." }, "DescribeInstancesStatus": { "params": [ { "name": "InstanceIds", "desc": "Query by instance ID(s). For example, instance ID: `ins-xxxxxxxx`. For the specific format, refer to section `Ids.N` of the API [Introduction](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1). You can query up to 100 instances in each request." }, { "name": "Offset", "desc": "Offset; default value: 0. For more information on `Offset`, see the corresponding section in API [Introduction](https://intl.cloud.tencent.com/document/product/377)." }, { "name": "Limit", "desc": "Number of results returned; default value: 20; maximum: 100. For more information on `Limit`, see the corresponding section in API [Introduction](https://intl.cloud.tencent.com/document/product/377)." } ], "desc": "This API is used to query the status of instances.\n\n* You can query the status of an instance with its `ID`.\n* If no parameter is defined, the status of a certain number of instances under the current account will be returned. The number is specified by `Limit` and is 20 by default." }, "ModifyImageSharePermission": { "params": [ { "name": "ImageId", "desc": "Image ID such as `img-gvbnzy6f`. You can obtain the image IDs in two ways: <br><li>Call [DescribeImages](https://intl.cloud.tencent.com/document/api/213/15715?from_cn_redirect=1) and look for `ImageId` in the response. <br><li>Look for the information in the [Image Console](https://console.cloud.tencent.com/cvm/image). <br>You can only specify an image in the `NORMAL` state. For more information on image states, see [here](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#image_state)." }, { "name": "AccountIds", "desc": "List of account IDs with which an image is shared. For the format of array-type parameters, see [API Introduction](https://intl.cloud.tencent.com/document/api/213/568?from_cn_redirect=1). The account ID is different from the QQ number. You can find the account ID in [Account Information](https://console.cloud.tencent.com/developer). " }, { "name": "Permission", "desc": "Operations. Valid values: `SHARE`, sharing an image; `CANCEL`, cancelling an image sharing. " } ], "desc": "This API is used to modify image sharing information.\n\n* The accounts with which an image is shared can use the shared image to create instances.\n* Each custom image can be shared with up to 50 accounts.\n* You can use a shared image to create instances, but you cannot change its name and description.\n* If an image is shared with another account, the shared image will be in the same region as the original image.\n" }, "DescribeInstancesOperationLimit": { "params": [ { "name": "InstanceIds", "desc": "Query by instance ID(s). You can obtain the instance IDs from the value of `InstanceId` returned by the [DescribeInstances](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) API. For example, instance ID: ins-xxxxxxxx. (For the specific format, refer to section `ids.N` of the API [Introduction](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1).) You can query up to 100 instances in each request." }, { "name": "Operation", "desc": "Operation on the instance(s).\n<li> INSTANCE_DEGRADE: downgrade the instance configurations</li>" } ], "desc": "This API is used to query limitations on operations on an instance.\n\n* Currently you can use this API to query the maximum number of times you can modify the configuration of an instance." }, "DescribeImageSharePermission": { "params": [ { "name": "ImageId", "desc": "The ID of the image to be shared" } ], "desc": "This API is used to query image sharing information." }, "ImportImage": { "params": [ { "name": "Architecture", "desc": "OS architecture of the image to be imported, `x86_64` or `i386`." }, { "name": "OsType", "desc": "OS type of the image to be imported. You can call `DescribeImportImageOs` to obtain the list of supported operating systems." }, { "name": "OsVersion", "desc": "OS version of the image to be imported. You can call `DescribeImportImageOs` to obtain the list of supported operating systems." }, { "name": "ImageUrl", "desc": "Address on COS where the image to be imported is stored." }, { "name": "ImageName", "desc": "Image name" }, { "name": "ImageDescription", "desc": "Image description" }, { "name": "DryRun", "desc": "Dry run to check the parameters without performing the operation" }, { "name": "Force", "desc": "Whether to force import the image. For more information, see [Forcibly Import Image](https://intl.cloud.tencent.com/document/product/213/12849)." } ], "desc": "This API is used to import images. Imported images can be used to create instances. " }, "InquiryPriceRunInstances": { "params": [ { "name": "Placement", "desc": "Location of the instance. You can use this parameter to specify the attributes of the instance, such as its availability zone and project." }, { "name": "ImageId", "desc": "[Image](https://intl.cloud.tencent.com/document/product/213/4940?from_cn_redirect=1) ID in the format of `img-xxx`. There are four types of images: <br/><li>Public images </li><li>Custom images </li><li>Shared images </li><li>Marketplace images </li><br/>You can obtain the available image IDs in the following ways: <br/><li>For IDs of `public images`, `custom images`, and `shared images`, log in to the [console](https://console.cloud.tencent.com/cvm/image?rid=1&imageType=PUBLIC_IMAGE) to query the information; for IDs of `marketplace images`, go to [Cloud Marketplace](https://market.cloud.tencent.com/list). </li><li>Call [DescribeImages](https://intl.cloud.tencent.com/document/api/213/15715?from_cn_redirect=1) and look for `ImageId` in the response.</li>" }, { "name": "InstanceChargeType", "desc": "The instance [billing method](https://intl.cloud.tencent.com/document/product/213/2180?from_cn_redirect=1).<br><li>POSTPAID_BY_HOUR: hourly, pay-as-you-go<br>Default value: POSTPAID_BY_HOUR." }, { "name": "InstanceChargePrepaid", "desc": "Configuration of prepaid instances. You can use the parameter to specify the attributes of prepaid instances, such as the subscription period and the auto-renewal plan. This parameter is required for prepaid instances." }, { "name": "InstanceType", "desc": "The instance model. Different resource specifications are specified for different models. For specific values, call [DescribeInstanceTypeConfigs](https://intl.cloud.tencent.com/document/api/213/15749?from_cn_redirect=1) to retrieve the latest specification list or refer to [Instance Types](https://intl.cloud.tencent.com/document/product/213/11518?from_cn_redirect=1). If the parameter is not specified, `S1.SMALL1` will be used by default." }, { "name": "SystemDisk", "desc": "System disk configuration of the instance. If this parameter is not specified, the default value will be used." }, { "name": "DataDisks", "desc": "The configuration information of the instance data disk. If this parameter is not specified, no data disk will be purchased by default. When purchasing, you can specify 21 data disks, which can contain at most 1 LOCAL_BASIC data disk or LOCAL_SSD data disk, and at most 20 CLOUD_BASIC data disks, CLOUD_PREMIUM data disks, or CLOUD_SSD data disks." }, { "name": "VirtualPrivateCloud", "desc": "VPC configurations. You can use this parameter to specify the VPC ID, subnet ID, etc. If this parameter is not specified, the basic network will be used by default. If a VPC IP is specified in this parameter, the `InstanceCount` parameter can only be 1. " }, { "name": "InternetAccessible", "desc": "Configuration of public network bandwidth. If this parameter is not specified, 0 Mbps will be used by default." }, { "name": "InstanceCount", "desc": "Number of instances to be purchased. Value range: [1, 100]; default value: 1. The specified number of instances to be purchased cannot exceed the remaining quota allowed for the user. For more information on quota, see [CVM instance purchase limit](https://intl.cloud.tencent.com/document/product/213/2664)." }, { "name": "InstanceName", "desc": "Instance name to be displayed.<br><li>If this parameter is not specified, \"Unnamed\" will be displayed by default.</li><li>If you purchase multiple instances at the same time and specify a pattern string `{R:x}`, numbers `[x, x+n-1]` will be generated, where `n` represents the number of instances purchased. For example, you specify a pattern string, `server_{R:3}`. If you only purchase 1 instance, the instance will be named `server_3`; if you purchase 2, they will be named `server_3` and `server_4`. You can specify multiple pattern strings in the format of `{R:x}`.</li><li>If you purchase multiple instances at the same time and do not specify a pattern string, the instance names will be suffixed by `1, 2...n`, where `n` represents the number of instances purchased. For example, if you purchase 2 instances and name them as `server_`, the instance names will be displayed as `server_1` and `server_2`.</li><li>The instance name contains up to 60 characters (including pattern strings)." }, { "name": "LoginSettings", "desc": "Login settings of the instance. You can use this parameter to set the login method, password, and key of the instance or keep the login settings of the original image. By default, a random password will be generated and sent to you via the Message Center." }, { "name": "SecurityGroupIds", "desc": "Security groups to which the instance belongs. To obtain the security group IDs, you can call [DescribeSecurityGroups](https://intl.cloud.tencent.com/document/api/215/15808) and look for the `sgld` fields in the response. If this parameter is not specified, the instance will not be associated with any security group by default." }, { "name": "EnhancedService", "desc": "Enhanced services. You can use this parameter to specify whether to enable services such as Cloud Monitor and Cloud Security. If this parameter is not specified, Cloud Monitor and Cloud Security will be enabled by default." }, { "name": "ClientToken", "desc": "A string used to ensure the idempotency of the request, which is generated by the user and must be unique to each request. The maximum length is 64 ASCII characters. If this parameter is not specified, the idempotency of the request cannot be guaranteed. <br>For more information, see 'How to ensure idempotency'." }, { "name": "HostName", "desc": "Host name of the CVM. <br><li>Periods (.) or hyphens (-) cannot be the start or end of a host name or appear consecutively in a host name.<br><li>For Windows instances, the host name must be 2-15 characters long and can contain uppercase and lowercase letters, numbers, and hyphens (-). It cannot contain periods (.) or contain only numbers. <br><li>For other instances, such as Linux instances, the host name must be 2-30 characters long. It supports multiple periods (.) and allows uppercase and lowercase letters, numbers, and hyphens (-) between any two periods (.)." }, { "name": "TagSpecification", "desc": "The tag description list. This parameter is used to bind a tag to a resource instance. A tag can only be bound to CVM instances." }, { "name": "InstanceMarketOptions", "desc": "The market options of the instance." }, { "name": "HpcClusterId", "desc": "HPC cluster ID." } ], "desc": "This API is used to query the price of creating instances. You can only use this API for instances whose configuration is within the purchase limit. For more information, see [RunInstances](https://intl.cloud.tencent.com/document/api/213/15730?from_cn_redirect=1)." }, "DescribeImages": { "params": [ { "name": "ImageIds", "desc": "List of image IDs, such as `img-gvbnzy6f`. For the format of array-type parameters, see [API Introduction](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1). You can obtain the image IDs in two ways: <br><li>Call [DescribeImages](https://intl.cloud.tencent.com/document/api/213/15715?from_cn_redirect=1) and look for `ImageId` in the response. <br><li>View the image IDs in the [Image Console](https://console.cloud.tencent.com/cvm/image)." }, { "name": "Filters", "desc": "Filters. Each request can have up to 10 `Filters` and 5 `Filters.Values`. You cannot specify `ImageIds` and `Filters` at the same time. Specific filters:\n<li>`image-id` - String - Optional - Filter results by image ID</li>\n<li>`image-type` - String - Optional - Filter results by image type. Valid values:\n PRIVATE_IMAGE: private image created by the current account \n PUBLIC_IMAGE: public image created by Tencent Cloud\n SHARED_IMAGE: image shared with the current account by another account.</li>" }, { "name": "Offset", "desc": "Offset; default value: 0. For more information on `Offset`, see [API Introduction](https://intl.cloud.tencent.com/document/api/213/568?from_cn_redirect=1#.E8.BE.93.E5.85.A5.E5.8F.82.E6.95.B0.E4.B8.8E.E8.BF.94.E5.9B.9E.E5.8F.82.E6.95.B0.E9.87.8A.E4.B9.89)." }, { "name": "Limit", "desc": "Number of results returned; default value: 20; maximum: 100. For more information on `Limit`, see [API Introduction](https://intl.cloud.tencent.com/document/api/213/568?from_cn_redirect=1#.E8.BE.93.E5.85.A5.E5.8F.82.E6.95.B0.E4.B8.8E.E8.BF.94.E5.9B.9E.E5.8F.82.E6.95.B0.E9.87.8A.E4.B9.89)." }, { "name": "InstanceType", "desc": "Instance type, e.g. `S1.SMALL1`" } ], "desc": "This API is used to view the list of images.\n\n* You specify the image ID or set filters to query the details of certain images.\n* You can specify `Offset` and `Limit` to select a certain part of the results. By default, the information on the first 20 matching results is returned." }, "ModifyKeyPairAttribute": { "params": [ { "name": "KeyId", "desc": "Key pair ID in the format of `skey-xxxxxxxx`. <br><br>You can obtain the available key pair IDs in two ways: <br><li>Log in to the [console](https://console.cloud.tencent.com/cvm/sshkey) to query the key pair IDs. <br><li>Call [DescribeKeyPairs](https://intl.cloud.tencent.com/document/api/213/15699?from_cn_redirect=1) and look for `KeyId` in the response." }, { "name": "KeyName", "desc": "New key pair name, which can contain numbers, letters, and underscores, with a maximum length of 25 characters." }, { "name": "Description", "desc": "New key pair description. You can specify any name you like, but its length cannot exceed 60 characters." } ], "desc": "This API is used to modify the attributes of key pairs.\n\n* This API modifies the name and description of the key pair identified by the key pair ID.\n* The name of the key pair must be unique.\n* Key pair ID is the unique identifier of a key pair and cannot be modified." }, "ModifyInstancesAttribute": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. The maximum number of instances in each request is 100." }, { "name": "InstanceName", "desc": "Instance name. You can specify any name you like, but its length cannot exceed 60 characters." }, { "name": "SecurityGroups", "desc": "ID list of security groups of the instance. The instance will be associated with the specified security groups and will be disassociated from the original security groups." } ], "desc": "This API is used to modify the attributes of an instance. Currently you can only use the API to modify the name and the associated security groups of the instance.\n\n* Instance names are used only for users' convenience. Tencent Cloud does not use the name for ticket submission or instance management.\n* Batch operations are supported. The maximum number of instances in each request is 100.\n* When you change the security groups associated with an instance, the original security groups will be disassociated." }, "DescribeRegions": { "params": [], "desc": "This API is used to query regions." }, "InquiryPriceResetInstancesInternetMaxBandwidth": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. The maximum number of instances in each request is 100. When changing the bandwidth of instances with `BANDWIDTH_PREPAID` or `BANDWIDTH_POSTPAID_BY_HOUR` as the network billing method, you can only specify one instance at a time." }, { "name": "InternetAccessible", "desc": "Configuration of public network egress bandwidth. The maximum bandwidth varies among different models. For more information, see the documentation on bandwidth limits. Currently only the `InternetMaxBandwidthOut` parameter is supported." }, { "name": "StartTime", "desc": "Date from which the new bandwidth takes effect. Format: `YYYY-MM-DD`, such as `2016-10-30`. The starting date cannot be earlier than the current date. If the starting date is the current date, the new bandwidth takes effect immediately. This parameter is only valid for prepaid bandwidth. If you specify the parameter for bandwidth with other network billing methods, an error code will be returned." }, { "name": "EndTime", "desc": "Date until which the new bandwidth is effective. Format: `YYYY-MM-DD`, such as `2016-10-30`. The validity period of the new bandwidth covers the end date. The end date cannot be later than the expiration date of a prepaid instance. You can query the expiration time of an instance by calling [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728) and looking for `ExpiredTime` in the response. This parameter is only valid for prepaid bandwidth. If you specify the parameter for bandwidth with other network billing methods, an error code will be returned." } ], "desc": "This API is used to query the price for upgrading the public bandwidth cap of an instance.\n\n* The allowed bandwidth cap varies for different models. For details, see [Purchasing Network Bandwidth](https://intl.cloud.tencent.com/document/product/213/509?from_cn_redirect=1).\n* For bandwidth billed by the `TRAFFIC_POSTPAID_BY_HOUR` method, changing the bandwidth cap through this API takes effect in real time. You can increase or reduce bandwidth within applicable limits." }, "DisassociateInstancesKeyPairs": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). The maximum number of instances in each request is 100. <br><br>You can obtain the available instance IDs in two ways: <br><li>Log in to the [console](https://console.cloud.tencent.com/cvm/index) to query the instance IDs. <br><li>Call [DescribeInstances](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response." }, { "name": "KeyIds", "desc": "List of key pair IDs. The maximum number of key pairs in each request is 100. The key pair ID is in the format of `skey-11112222`. <br><br>You can obtain the available key pair IDs in two ways: <br><li>Log in to the [console](https://console.cloud.tencent.com/cvm/sshkey) to query the key pair IDs. <br><li>Call [DescribeKeyPairs](https://intl.cloud.tencent.com/document/api/213/15699?from_cn_redirect=1) and look for `KeyId` in the response." }, { "name": "ForceStop", "desc": "Whether to force shut down a running instances. It is recommended to manually shut down a running instance before disassociating a key pair from it. Valid values: <br><li>TRUE: force shut down an instance after a normal shutdown fails. <br><li>FALSE: do not force shut down an instance after a normal shutdown fails. <br><br>Default value: FALSE." } ], "desc": "This API is used to unbind one or more key pairs from one or more instances.\n\n* It only supports [`STOPPED`](https://intl.cloud.tencent.com/document/product/213/15753?from_cn_redirect=1#InstanceStatus) Linux instances.\n* After a key pair is disassociated from an instance, you can log in to the instance with password.\n* If you did not set a password for the instance, you will not be able to log in via SSH after the unbinding. In this case, you can call [ResetInstancesPassword](https://intl.cloud.tencent.com/document/api/213/15736?from_cn_redirect=1) to set a login password.\n* Batch operations are supported. The maximum number of instances in each request is 100. If instances not available for the operation are selected, you will get an error code." }, "CreateKeyPair": { "params": [ { "name": "KeyName", "desc": "Name of the key pair, which can contain numbers, letters, and underscores, with a maximum length of 25 characters." }, { "name": "ProjectId", "desc": "The ID of the project to which the new key pair belongs.\nYou can query the project IDs in two ways:\n<li>Query the project IDs in the project list.\n<li>Call `DescribeProject` and look for `projectId` in the response." } ], "desc": "This API is used to create an `OpenSSH RSA` key pair, which you can use to log in to a `Linux` instance.\n\n* You only need to specify a name, and the system will automatically create a key pair and return its `ID` and the public and private keys.\n* The name of the key pair must be unique.\n* You can save the private key to a file and use it as an authentication method for `SSH`.\n* Tencent Cloud does not save users' private keys. Be sure to save it yourself." }, "DescribeInstanceFamilyConfigs": { "params": [], "desc": "This API is used to query a list of model families available to the current user in the current region." }, "DeleteKeyPairs": { "params": [ { "name": "KeyIds", "desc": "Key ID(s). The maximum number of key pairs in each request is 100. <br>You can obtain the available key pair IDs in two ways: <br><li>Log in to the [console](https://console.cloud.tencent.com/cvm/sshkey) to query the key pair IDs. <br><li>Call [DescribeKeyPairs](https://intl.cloud.tencent.com/document/api/213/15699?from_cn_redirect=1) and look for `KeyId` in the response." } ], "desc": "This API is used to delete the key pairs hosted in Tencent Cloud.\n\n* You can delete multiple key pairs at the same time.\n* A key pair used by an instance or image cannot be deleted. Therefore, you need to verify whether all the key pairs have been deleted successfully." }, "CreateDisasterRecoverGroup": { "params": [ { "name": "Name", "desc": "Name of the spread placement group. The name must be 1-60 characters long and can contain both Chinese characters and English letters." }, { "name": "Type", "desc": "Type of the spread placement group. Valid values: <br><li>HOST: physical machine <br><li>SW: switch <br><li>RACK: rack" }, { "name": "ClientToken", "desc": "A string used to ensure the idempotency of the request, which is generated by the user and must be unique to each request. The maximum length is 64 ASCII characters. If this parameter is not specified, the idempotency of the request cannot be guaranteed. <br>For more information, see 'How to ensure idempotency'." } ], "desc": "This API is used to create a [spread placement group](https://intl.cloud.tencent.com/document/product/213/15486?from_cn_redirect=1). After you create one, you can specify it for an instance when you [create the instance](https://intl.cloud.tencent.com/document/api/213/15730?from_cn_redirect=1), " }, "DescribeInstances": { "params": [ { "name": "InstanceIds", "desc": "Query by instance ID(s). For example, instance ID: `ins-xxxxxxxx`. For the specific format, refer to section `Ids.N` of the API [Introduction](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1). You can query up to 100 instances in each request. However, `InstanceIds` and `Filters` cannot be specified at the same time." }, { "name": "Filters", "desc": "Filters.\n<li> `zone` - String - Optional - Filter results by availability zone.</li>\n<li> `project-id` - Integer - Optional - Filter results by project ID. You can call [DescribeProject](https://intl.cloud.tencent.com/document/api/378/4400?from_cn_redirect=1) or log in to the [console](https://console.cloud.tencent.com/cvm/index) to view the list of existing projects. You can also create a new project by calling [AddProject](https://intl.cloud.tencent.com/document/api/378/4398?from_cn_redirect=1).</li>\n<li> `host-id` - String - Optional - Filter results by [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) ID. [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) ID format: `host-xxxxxxxx`.</li>\n</li>`vpc-id` - String - Optional - Filter results by VPC ID. VPC ID format: `vpc-xxxxxxxx`.</li>\n<li> `subnet-id` - String - Optional - Filter results by subnet ID. Subnet ID format: `subnet-xxxxxxxx`.</li>\n</li>`instance-id` - String - Optional - Filter results by instance ID. Instance ID format: `ins-xxxxxxxx`.</li>\n</li>`security-group-id` - String - Optional - Filter results by security group ID. Security group ID format: `sg-8jlk3f3r`.</li>\n</li>`instance-name` - String - Optional - Filter results by instance name.</li>\n</li>`instance-charge-type` - String - Optional - Filter results by instance billing method. `POSTPAID_BY_HOUR`: pay-as-you-go | `CDHPAID`: you are only billed for [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) instances, not the CVMs running on the [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) instances.</li>\n</li>`private-ip-address` - String - Optional - Filter results by the private IP address of the instance's primary ENI.</li>\n</li>`public-ip-address` - String - Optional - Filter results by the public IP address of the instance's primary ENI, including the IP addresses automatically assigned during the instance creation and the EIPs manually associated after the instance creation.</li>\n<li> `tag-key` - String - Optional - Filter results by tag key.</li>\n</li>`tag-value` - String - Optional - Filter results by tag value.</li>\n<li> `tag:tag-key` - String - Optional - Filter results by tag key-value pair. Replace `tag-key` with specific tag keys, as shown in example 2.</li>\nEach request can have up to 10 `Filters` and 5 `Filters.Values`. You cannot specify `InstanceIds` and `Filters` at the same time." }, { "name": "Offset", "desc": "Offset; default value: 0. For more information on `Offset`, see the corresponding section in API [Introduction](https://intl.cloud.tencent.com/document/product/377)." }, { "name": "Limit", "desc": "Number of results returned; default value: 20; maximum: 100. For more information on `Limit`, see the corresponding section in API [Introduction](https://intl.cloud.tencent.com/document/product/377). " } ], "desc": "This API is used to query the details of instances.\n\n* You can filter the query results with the instance `ID`, name, or billing method. See `Filter` for more information.\n* If no parameter is defined, a certain number of instances under the current account will be returned. The number is specified by `Limit` and is 20 by default." }, "ImportKeyPair": { "params": [ { "name": "KeyName", "desc": "Key pair name, which can contain numbers, letters, and underscores, with a maximum length of 25 characters." }, { "name": "ProjectId", "desc": "The ID of the [project](https://intl.cloud.tencent.com/document/product/378/10861?from_cn_redirect=1) to which the created key pair belongs.<br><br>You can retrieve the project ID in two ways:<br><li>Query the project ID in [Project Management](https://console.cloud.tencent.com/project).<br><li>Call [DescribeProject](https://intl.cloud.tencent.com/document/api/378/4400?from_cn_redirect=1) and search for `projectId` in the response.\n\nIf you want to use the default project, specify 0 for the parameter." }, { "name": "PublicKey", "desc": "Content of the public key in the key pair in the `OpenSSH RSA` format." } ], "desc": "This API is used to import key pairs.\n\n* You can use this API to import key pairs to a user account, but the key pairs will not be automatically associated with any instance. You may use [AssociasteInstancesKeyPair](https://intl.cloud.tencent.com/document/api/213/9404?from_cn_redirect=1) to associate key pairs with instances.\n* You need to specify the names of the key pairs and the content of the public keys.\n* If you only have private keys, you can convert them to public keys with the `SSL` tool before importing them." }, "AssociateInstancesKeyPairs": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). The maximum number of instances in each request is 100. <br>You can obtain the available instance IDs in two ways: <br><li>Log in to the [console](https://console.cloud.tencent.com/cvm/index) to query the instance IDs. <br><li>Call [DescribeInstances](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response." }, { "name": "KeyIds", "desc": "Key ID(s). The maximum number of key pairs in each request is 100. The key pair ID is in the format of `skey-3glfot13`. <br>You can obtain the available key pair IDs in two ways: <br><li>Log in to the [console](https://console.cloud.tencent.com/cvm/sshkey) to query the key pair IDs. <br><li>Call [DescribeKeyPairs](https://intl.cloud.tencent.com/document/api/213/15699?from_cn_redirect=1) and look for `KeyId` in the response." }, { "name": "ForceStop", "desc": "Whether to force shut down a running instances. It is recommended to manually shut down a running instance before associating a key pair with it. Valid values: <br><li>TRUE: force shut down an instance after a normal shutdown fails. <br><li>FALSE: do not force shut down an instance after a normal shutdown fails. <br><br>Default value: FALSE." } ], "desc": "This API is used to associate key pairs with instances.\n\n* If the public key of a key pair is written to the `SSH` configuration of the instance, users will be able to log in to the instance with the private key of the key pair.\n* If the instance is already associated with a key, the old key will become invalid.\nIf you currently use a password to log in, you will no longer be able to do so after you associate the instance with a key.\n* Batch operations are supported. The maximum number of instances in each request is 100. If any instance in the request cannot be associated with a key, you will get an error code." }, "RunInstances": { "params": [ { "name": "Placement", "desc": "Location of the instance. You can use this parameter to specify the attributes of the instance, such as its availability zone, project, and CDH. You can specify a CDH for a CVM by creating the CVM on the CDH." }, { "name": "ImageId", "desc": "The [image](https://intl.cloud.tencent.com/document/product/213/4940?from_cn_redirect=1) ID in the format of `img-xxx`. There are four types of images:<br/><li>Public images</li><li>Custom images</li><li>Shared images</li><li>Marketplace images</li><br/>You can retrieve available image IDs in the following ways:<br/><li>For the IDs of `public images`, `custom images`, and `shared images`, log in to the [console](https://console.cloud.tencent.com/cvm/image?rid=1&imageType=PUBLIC_IMAGE) to query the information. For the IDs of `marketplace images`, go to [Cloud Marketplace](https://market.cloud.tencent.com/list). </li><li>Call [DescribeImages](https://intl.cloud.tencent.com/document/api/213/15715?from_cn_redirect=1), pass in `InstanceType` to retrieve the list of images supported by the current model, and then find the `ImageId` in the response.</li>" }, { "name": "InstanceChargeType", "desc": "The instance [billing method](https://intl.cloud.tencent.com/document/product/213/2180?from_cn_redirect=1). Valid values: <br><li>`POSTPAID_BY_HOUR`: hourly, pay-as-you-go<br><li>`CDHPAID`: you are only billed for CDH instances, not the CVMs running on the CDH instances.<br>Default value: POSTPAID_BY_HOUR." }, { "name": "InstanceChargePrepaid", "desc": "Configuration of prepaid instances. You can use the parameter to specify the attributes of prepaid instances, such as the subscription period and the auto-renewal plan. This parameter is required for prepaid instances." }, { "name": "InstanceType", "desc": "The instance model. Different resource specifications are specified for different instance models.\n<br><li>To view specific values for `POSTPAID_BY_HOUR` instances, you can call [DescribeInstanceTypeConfigs](https://intl.cloud.tencent.com/document/api/213/15749?from_cn_redirect=1) or refer to [Instance Types](https://intl.cloud.tencent.com/document/product/213/11518?from_cn_redirect=1). If this parameter is not specified, `S1.SMALL1` will be used by default.<br><li>For `CDHPAID` instances, the value of this parameter is in the format of `CDH_XCXG` based on the number of CPU cores and memory capacity. For example, if you want to create a CDH instance with a single-core CPU and 1 GB memory, specify this parameter as `CDH_1C1G`." }, { "name": "SystemDisk", "desc": "System disk configuration of the instance. If this parameter is not specified, the default value will be used." }, { "name": "DataDisks", "desc": "The configuration information of instance data disks. If this parameter is not specified, no data disk will be purchased by default. When purchasing, you can specify 21 data disks, which can contain at most 1 LOCAL_BASIC data disk or LOCAL_SSD data disk, and at most 20 CLOUD_BASIC data disks, CLOUD_PREMIUM data disks, or CLOUD_SSD data disks." }, { "name": "VirtualPrivateCloud", "desc": "Configuration information of VPC. This parameter is used to specify VPC ID and subnet ID, etc. If this parameter is not specified, the classic network is used by default. If a VPC IP is specified in this parameter, it indicates the primary ENI IP of each instance. The value of parameter InstanceCount must be same as the number of VPC IPs, which cannot be greater than 20." }, { "name": "InternetAccessible", "desc": "Configuration of public network bandwidth. If this parameter is not specified, 0 Mbps will be used by default." }, { "name": "InstanceCount", "desc": "The number of instances to be purchased. Value range: [1, 100]; default value: 1. The specified number of instances to be purchased cannot exceed the remaining quota allowed for the user. For more information on the quota, see [CVM instance purchase limit](https://intl.cloud.tencent.com/document/product/213/2664)." }, { "name": "InstanceName", "desc": "Instance name to be displayed.<br><li>If this parameter is not specified, \"Unnamed\" will be displayed by default.</li><li>If you purchase multiple instances at the same time and specify a pattern string `{R:x}`, numbers `[x, x+n-1]` will be generated, where `n` represents the number of instances purchased. For example, you specify a pattern string, `server_{R:3}`. If you only purchase 1 instance, the instance will be named `server_3`; if you purchase 2, they will be named `server_3` and `server_4`. You can specify multiple pattern strings in the format of `{R:x}`.</li><li>If you purchase multiple instances at the same time and do not specify a pattern string, the instance names will be suffixed by `1, 2...n`, where `n` represents the number of instances purchased. For example, if you purchase 2 instances and name them as `server_`, the instance names will be displayed as `server_1` and `server_2`.</li><li>The instance name contains up to 60 characters (including pattern strings)." }, { "name": "LoginSettings", "desc": "Login settings of the instance. You can use this parameter to set the login method, password, and key of the instance or keep the login settings of the original image. By default, a random password will be generated and sent to you via the Message Center." }, { "name": "SecurityGroupIds", "desc": "Security groups to which the instance belongs. To obtain the security group IDs, you can call [DescribeSecurityGroups](https://intl.cloud.tencent.com/document/api/215/15808) and look for the `sgld` fields in the response. If this parameter is not specified, the instance will be associated with default security groups." }, { "name": "EnhancedService", "desc": "Specifies whether to enable services such as Anti-DDoS and Cloud Monitor. If this parameter is not specified, Cloud Monitor and Anti-DDoS are enabled for public images by default. However, for custom images and images from the marketplace, Anti-DDoS and Cloud Monitor are not enabled by default. The original services in the image will be retained." }, { "name": "ClientToken", "desc": "A string used to ensure the idempotency of the request, which is generated by the user and must be unique to each request. The maximum length is 64 ASCII characters. If this parameter is not specified, the idempotency of the request cannot be guaranteed. <br>For more information, see 'How to ensure idempotency'." }, { "name": "HostName", "desc": "Host name of the CVM. <br><li>Periods (.) or hyphens (-) cannot be the start or end of a host name or appear consecutively in a host name.<br><li>For Windows instances, the host name must be 2-15 characters long and can contain uppercase and lowercase letters, numbers, and hyphens (-). It cannot contain periods (.) or contain only numbers. <br><li>For other instances, such as Linux instances, the host name must be 2-60 characters long. It supports multiple periods (.) and allows uppercase and lowercase letters, numbers, and hyphens (-) between any two periods (.)." }, { "name": "ActionTimer", "desc": "Scheduled tasks. You can use this parameter to specify scheduled tasks for the instance. Only scheduled termination is supported." }, { "name": "DisasterRecoverGroupIds", "desc": "Placement group ID. You can only specify one." }, { "name": "TagSpecification", "desc": "The tag description list. This parameter is used to bind a tag to a resource instance. A tag can only be bound to CVM instances." }, { "name": "InstanceMarketOptions", "desc": "The market options of the instance." }, { "name": "UserData", "desc": "User data provided to the instance, which needs to be encoded in base64 format with the maximum size of 16KB. For more information on how to get the value of this parameter, see the commands you need to execute on startup for [Windows](https://intl.cloud.tencent.com/document/product/213/17526) or [Linux](https://intl.cloud.tencent.com/document/product/213/17525)." }, { "name": "DryRun", "desc": "Whether the request is a dry run only.\ntrue: dry run only. The request will not create instance(s). A dry run can check whether all the required parameters are specified, whether the request format is right, whether the request exceeds service limits, and whether the specified CVMs are available.\nIf the dry run fails, the corresponding error code will be returned.\nIf the dry run succeeds, the RequestId will be returned.\nfalse (default value): send a normal request and create instance(s) if all the requirements are met." }, { "name": "HpcClusterId", "desc": "HPC cluster ID. The HPC cluster must and can only be specified for a high-performance computing instance." } ], "desc": "This API is used to create one or more instances with a specified configuration.\n\n* After an instance is created successfully, it will start up automatically, and the [instance state](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#instance_state) will become \"Running\".\n* If you create a pay-as-you-go instance billed on an hourly basis, an amount equivalent to the hourly rate will be frozen before the creation. Make sure your account balance is sufficient before calling this API.\n* The number of instances you can purchase through this API is subject to the [CVM instance purchase limit](https://intl.cloud.tencent.com/document/product/213/2664?from_cn_redirect=1). Both the instances created through this API and the console will be counted toward the quota.\n* This API is an async API. An instance `ID` list will be returned after you successfully make a creation request. However, it does not mean the creation has been completed. The state of the instance will be `Creating` during the creation. You can use [DescribeInstances](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) to query the status of the instance. If the status changes from `Creating` to `Running`, it means that the instance has been created successfully." }, "DeleteImages": { "params": [ { "name": "ImageIds", "desc": "List of the IDs of the instances to be deleted." } ], "desc": "This API is used to delete images.\n\n* If the [ImageState](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#image_state) of an image is `Creating` or `In Use`, it cannot be deleted. Use [DescribeImages](https://intl.cloud.tencent.com/document/api/213/9418?from_cn_redirect=1) to query the image state.\n* You can only create up to 10 custom images in each region. If you have used up the quota, you can delete images to create new ones.\n* A shared image cannot be deleted." }, "InquiryPriceResizeInstanceDisks": { "params": [ { "name": "InstanceId", "desc": "Instance ID. To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response." }, { "name": "DataDisks", "desc": "The configuration of data disks to be expanded. Currently, you can only use the API to expand non-elastic data disks whose [disk type](https://intl.cloud.tencent.com/document/product/213/15753?from_cn_redirect=1#DataDisk) is `CLOUD_BASIC`, `CLOUD_PREMIUM`, or `CLOUD_SSD`. You can use [`DescribeDisks`](https://intl.cloud.tencent.com/document/api/362/16315?from_cn_redirect=1) to check whether a disk is elastic. If the `Portable` field in the response is `false`, it means that the disk is non-elastic. Data disk capacity unit: GB; minimum increment: 10 GB. For more information about selecting a data disk type, see the product overview on cloud disks. Available data disk types are subject to the instance type (`InstanceType`). In addition, the maximum capacity allowed for expansion varies by data disk type." }, { "name": "ForceStop", "desc": "Whether to force shut down a running instances. It is recommended to manually shut down a running instance before resetting the user password. Valid values: <br><li>TRUE: force shut down an instance after a normal shutdown fails. <br><li>FALSE: do not force shut down an instance after a normal shutdown fails. <br><br>Default value: FALSE. <br><br>A forced shutdown is similar to switching off the power of a physical computer. It may cause data loss or file system corruption. Be sure to only force shut down a CVM when it cannot be shut down normally." } ], "desc": "This API is used to query the price for expanding data disks of an instance.\n\n* Currently, you can only use this API to query the price of non-elastic data disks whose [disk type](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#block_device) is `CLOUD_BASIC`, `CLOUD_PREMIUM`, or `CLOUD_SSD`. You can use [`DescribeDisks`](https://intl.cloud.tencent.com/document/api/362/16315?from_cn_redirect=1) to check whether a disk is elastic. If the `Portable` field in the response is `false`, it means that the disk is non-elastic.\n* Currently, you cannot use this API to query the price for [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) instances. *Also, you can only query the price of expanding one data disk at a time." }, "ModifyInstancesVpcAttribute": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response." }, { "name": "VirtualPrivateCloud", "desc": "VPC configurations. You can use this parameter to specify the VPC ID, subnet ID, VPC IP, etc. If the specified VPC ID and subnet ID (the subnet must be in the same availability zone as the instance) are different from the VPC where the specified instance resides, the instance will be migrated to a subnet of the specified VPC. You can use `PrivateIpAddresses` to specify the VPC subnet IP. If you want to specify the subnet IP, you will need to specify a subnet IP for each of the specified instances, and each `InstanceIds` will match a `PrivateIpAddresses`. If `PrivateIpAddresses` is not specified, the VPC subnet IP will be assigned randomly." }, { "name": "ForceStop", "desc": "Whether to force shut down a running instances. Default value: TRUE." }, { "name": "ReserveHostName", "desc": "Whether to keep the host name. Default value: FALSE." } ], "desc": "This API is used to modify the VPC attributes of an instance, such as the VPC IP address.\n* By default, the instances will shut down when you perform this operation and restart upon completion.\n* If the specified VPC ID and subnet ID (the subnet must be in the same availability zone as the instance) are different from the VPC where the specified instance resides, the instance will be migrated to a subnet of the specified VPC. Before performing this operation, make sure that the specified instance is not bound with an [ENI](https://intl.cloud.tencent.com/document/product/576?from_cn_redirect=1) or [CLB](https://intl.cloud.tencent.com/document/product/214?from_cn_redirect=1)." }, "InquiryPriceResetInstance": { "params": [ { "name": "InstanceId", "desc": "Instance ID. To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response." }, { "name": "ImageId", "desc": "[Image](https://intl.cloud.tencent.com/document/product/213/4940?from_cn_redirect=1) ID in the format of `img-xxx`. There are four types of images: <br/><li>Public images </li><li>Custom images </li><li>Shared images </li><li>Marketplace images </li><br/>You can obtain the available image IDs in the following ways: <br/><li>For IDs of `public images`, `custom images`, and `shared images`, log in to the [console](https://console.cloud.tencent.com/cvm/image?rid=1&imageType=PUBLIC_IMAGE) to query the information; for IDs of `marketplace images`, go to [Cloud Marketplace](https://market.cloud.tencent.com/list). </li><li>Call [DescribeImages](https://intl.cloud.tencent.com/document/api/213/15715?from_cn_redirect=1) and look for `ImageId` in the response.</li>" }, { "name": "SystemDisk", "desc": "Configuration of the system disk of the instance. For instances with a cloud disk as the system disk, you can expand the system disk by using this parameter to specify the new capacity after reinstallation. If the parameter is not specified, the system disk capacity remains unchanged by default. You can only expand the capacity of the system disk; reducing its capacity is not supported. When reinstalling the system, you can only modify the capacity of the system disk, not the type." }, { "name": "LoginSettings", "desc": "Login settings of the instance. You can use this parameter to set the login method, password, and key of the instance or keep the login settings of the original image. By default, a random password will be generated and sent to you via the Message Center." }, { "name": "EnhancedService", "desc": "Enhanced services. You can use this parameter to specify whether to enable services such as Cloud Monitor and Cloud Security. If this parameter is not specified, Cloud Monitor and Cloud Security will be enabled by default." } ], "desc": "This API is used to query the price for reinstalling an instance.\n\n* If you have specified the `ImageId` parameter, the price query is performed with the specified image. Otherwise, the image used by the current instance is used.\n* You can only query the price for reinstallation caused by switching between Linux and Windows OS. And the [system disk type](https://intl.cloud.tencent.com/document/api/213/15753?from_cn_redirect=1#SystemDisk) of the instance must be `CLOUD_BASIC`, `CLOUD_PREMIUM`, or `CLOUD_SSD`.\n* Currently, this API only supports instances in Mainland China regions." }, "DescribeDisasterRecoverGroupQuota": { "params": [], "desc": "This API is used to query the quota of [spread placement groups](https://intl.cloud.tencent.com/document/product/213/15486?from_cn_redirect=1)." }, "ResetInstancesPassword": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. The maximum number of instances in each request is 100." }, { "name": "Password", "desc": "Login password of the instance. The rule of password complexity varies with operating systems:\nFor a Linux instance, the password must be 8 to 30 characters in length; password with more than 12 characters is recommended. It cannot begin with \"/\", and must contain at least three types of the following:<br><li>Lowercase letters: [a-z]<br><li>Uppercase letters: [A-Z]<br><li>Numbers: 0-9<br><li>Special characters: ()\\`~!@#$%^&\\*-+=\\_|{}[]:;'<>,.?/\nFor a Windows CVM, the password must be 12 to 30 characters in length. It cannot begin with \"/\" or contain your username. It must contain at least three types of the following:<br><li>Lowercase letters: [a-z]<br><li>Uppercase letters: [A-Z]<br><li>Numbers: 0-9<br><li>Special characters: ()\\`~!@#$%^&\\*-+=\\_|{}[]:;' <>,.?/<li>If the specified instances include both `Linux` and `Windows` instances, you need to follow the password requirements for `Windows` instances." }, { "name": "UserName", "desc": "Username of the instance operating system for which the password needs to be reset. This parameter is limited to 64 characters." }, { "name": "ForceStop", "desc": "Whether to force shut down a running instances. It is recommended to manually shut down a running instance before resetting the user password. Valid values: <br><li>TRUE: force shut down an instance after a normal shutdown fails. <br><li>FALSE: do not force shut down an instance after a normal shutdown fails. <br><br>Default value: FALSE. <br><br>A forced shutdown is similar to switching off the power of a physical computer. It may cause data loss or file system corruption. Be sure to only force shut down a CVM when it cannot be shut down normally." } ], "desc": "This API is used to reset the password of the operating system instances to a user-specified password.\n\n* To modify the password of the administrator account: the name of the administrator account varies with the operating system. In Windows, it is `Administrator`; in Ubuntu, it is `ubuntu`; in Linux, it is `root`.\n* To reset the password of a running instance, you need to set the parameter `ForceStop` to `True` for a forced shutdown. If not, only passwords of stopped instances can be reset.\n* Batch operations are supported. You can reset the passwords of up to 100 instances to the same value once.\n* You can call the [DescribeInstances](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1#.E7.A4.BA.E4.BE.8B3-.E6.9F.A5.E8.AF.A2.E5.AE.9E.E4.BE.8B.E7.9A.84.E6.9C.80.E6.96.B0.E6.93.8D.E4.BD.9C.E6.83.85.E5.86.B5) API and find the result of the operation in the response parameter `LatestOperationState`. If the value is `SUCCESS`, the operation is successful." }, "PurchaseReservedInstancesOffering": { "params": [ { "name": "InstanceCount", "desc": "The number of the Reserved Instance you are purchasing." }, { "name": "ReservedInstancesOfferingId", "desc": "The ID of the Reserved Instance." }, { "name": "DryRun", "desc": "Dry run" }, { "name": "ClientToken", "desc": "A unique string supplied by the client to ensure that the request is idempotent. Its maximum length is 64 ASCII characters. If this parameter is not specified, the idempotency of the request cannot be guaranteed.<br>For more information, see Ensuring Idempotency." }, { "name": "ReservedInstanceName", "desc": "Reserved instance name.<br><li>The RI name defaults to “unnamed” if this parameter is left empty.</li><li>You can enter any name within 60 characters (including the pattern string).</li>" } ], "desc": "This API is used to purchase one or more specific Reserved Instances." }, "ResizeInstanceDisks": { "params": [ { "name": "InstanceId", "desc": "Instance ID. To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response." }, { "name": "DataDisks", "desc": "Configuration of data disks to be expanded. Currently you can only use the API to expand non-elastic data disks whose [disk type](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#block_device) is `CLOUD_BASIC`, `CLOUD_PREMIUM`, or `CLOUD_SSD`. You can use [`DescribeDisks`](https://intl.cloud.tencent.com/document/api/362/16315?from_cn_redirect=1) to check whether a disk is elastic. If the `Portable` field in the response is `false`, it means that the disk is not elastic. Data disk capacity unit: GB; minimum increment: 10 GB. For more information on selecting the data disk type, see the [product overview on cloud disks](https://intl.cloud.tencent.com/document/product/362/2353?from_cn_redirect=1). Available data disk types are subject to the instance type (`InstanceType`). In addition, the maximum capacity allowed for expansion varies by data disk type." }, { "name": "ForceStop", "desc": "Whether to force shut down a running instances. It is recommended to manually shut down a running instance before resetting the user password. Valid values: <br><li>TRUE: force shut down an instance after a normal shutdown fails. <br><li>FALSE: do not force shut down an instance after a normal shutdown fails. <br><br>Default value: FALSE. <br><br>A forced shutdown is similar to switching off the power of a physical computer. It may cause data loss or file system corruption. Be sure to only force shut down a CVM when it cannot be shut down normally." } ], "desc": "This API (ResizeInstanceDisks) is used to expand the data disks of an instance.\n\n* Currently, you can only use the API to expand non-elastic data disks whose [disk type](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#block_device) is `CLOUD_BASIC`, `CLOUD_PREMIUM`, or `CLOUD_SSD`. You can use [`DescribeDisks`](https://intl.cloud.tencent.com/document/api/362/16315?from_cn_redirect=1) to check whether a disk is elastic. If the `Portable` field in the response is `false`, it means that the disk is non-elastic.\n* Currently, this API does not support [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) instances.\n* Currently, only one data disk can be expanded at a time." }, "DescribeReservedInstances": { "params": [ { "name": "DryRun", "desc": "Dry run. The default is false." }, { "name": "Offset", "desc": "Offset. The default value is 0. For more information on `Offset`, see the relevant sections in API [Overview](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1)." }, { "name": "Limit", "desc": "Number of returned results. The default value is 20. The maximum is 100. For more information on `Limit`, see the relevant sections in API [Overview](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1)." }, { "name": "Filters", "desc": "<li><strong>zone</strong></li>\n<p style=\"padding-left: 30px;\">Filters by <strong>availability zone</strong> in which the reserved instances can be purchased, such as ap-guangzhou-1.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: please see <a href=\"https://intl.cloud.tencent.com/document/product/213/6091?from_cn_redirect=1\">Availability Zones</a></p>\n<li><strong>duration</strong></li>\n<p style=\"padding-left: 30px;\">Filters by the <strong>validity</strong> of the reserved instance, in seconds. For example, `31536000`.</p><p style=\"padding-left: 30px;\">Type: Integer</p><p style=\"padding-left: 30px;\">Unit: second</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: 31536000 (1 year) | 94608000 (3 years)</p>\n<li><strong>instance-type</strong></li>\n<p style=\"padding-left: 30px;\">Filters by <strong>reserved instance specification</strong>, such as `S3.MEDIUM4`.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: please see <a href=\"https://intl.cloud.tencent.com/document/product/213/11518?from_cn_redirect=1\">Reserved Instance Specifications</a></p>\n<li><strong>instance-family</strong></li>\n<p style=\"padding-left: 30px;\">Filters by <strong>type of the reserved instance</strong>, such as `S3`.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: please see <a href=\"https://intl.cloud.tencent.com/document/product/213/11518?from_cn_redirect=1\">Reserved Instance Types</a></p>\n<li><strong>offering-type</strong></li>\n<li><strong>offering-type</strong></li>\n<p style=\"padding-left: 30px;\">Filters by <strong>payment method</strong>, such as `All Upfront`.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid value: All Upfront</p>\n<li><strong>product-description</strong></li>\n<p style=\"padding-left: 30px;\">Filters by the <strong>platform description</strong> (operating system) of the reserved instance, such as `linux`.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid value: linux</p>\n<li><strong>reserved-instances-id</strong></li>\n<p style=\"padding-left: 30px;\">Filters by <strong>reserved instance ID</strong> in the form of 650c138f-ae7e-4750-952a-96841d6e9fc1.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p>\n<li><strong>state</strong></li>\n<p style=\"padding-left: 30px;\">Filters by <strong>reserved instance status</strong>. For example, “active”.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required</p><p style=\"padding-left: 30px;\">Valid values: active (created) | pending (waiting to be created) | retired (expired)</p>\nEach request can have up to 10 `Filters` and 5 `Filter.Values`." } ], "desc": "This API is used to list reserved instances the user has purchased." }, "DescribeZones": { "params": [], "desc": "This API is used to query availability zones." }, "DescribeImageQuota": { "params": [], "desc": "This API is used to query the image quota of an user account." }, "AssociateSecurityGroups": { "params": [ { "name": "SecurityGroupIds", "desc": "ID of the security group to be associated, such as `sg-efil73jd`. Only one security group can be associated." }, { "name": "InstanceIds", "desc": "ID of the instance bound in the format of ins-lesecurk. You can specify up to 100 instances in each request." } ], "desc": "This API is used to associate security groups with specified instances." }, "ResetInstancesType": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). You can obtain the instance IDs from the value of `InstanceId` returned by the [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) API. The maximum number of instances for each request is 1." }, { "name": "InstanceType", "desc": "Instance model. Different resource specifications are specified for different models. For specific values, call [DescribeInstanceTypeConfigs](https://intl.cloud.tencent.com/document/api/213/15749?from_cn_redirect=1) to get the latest specification list or refer to [Instance Types](https://intl.cloud.tencent.com/document/product/213/11518?from_cn_redirect=1)." }, { "name": "ForceStop", "desc": "Forced shutdown of a running instances. We recommend you firstly try to shut down a running instance manually. Valid values: <br><li>TRUE: forced shutdown of an instance after a normal shutdown fails.<br><li>FALSE: no forced shutdown of an instance after a normal shutdown fails.<br><br>Default value: FALSE.<br><br>A forced shutdown is similar to switching off the power of a physical computer. It may cause data loss or file system corruption. Be sure to only force a CVM to shut off if the normal shutdown fails." } ], "desc": "This API is used to change the model of an instance.\n* You can only use this API to change the models of instances whose [system disk type](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#block_device) is `CLOUD_BASIC`, `CLOUD_PREMIUM`, or `CLOUD_SSD`.\n* Currently, you cannot use this API to change the models of [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) instances." }, "ModifyImageAttribute": { "params": [ { "name": "ImageId", "desc": "Image ID such as `img-gvbnzy6f`. You can obtain the image IDs in two ways: <br><li>Call [DescribeImages](https://intl.cloud.tencent.com/document/api/213/15715?from_cn_redirect=1) and look for `ImageId` in the response. <br><li>Look for the information in the [Image Console](https://console.cloud.tencent.com/cvm/image)." }, { "name": "ImageName", "desc": "New image name, which must meet the following requirements: <br> <li>No more than 20 characters. <br> <li>Must be unique." }, { "name": "ImageDescription", "desc": "New image description, which must meet the following requirement: <br> <li> No more than 60 characters." } ], "desc": "This API is used to modify image attributes.\n\n* Attributes of shared images cannot be modified." }, "DescribeReservedInstancesConfigInfos": { "params": [ { "name": "Filters", "desc": "zone\nFilters by the availability zones in which the reserved instance can be purchased, such as `ap-guangzhou-1`.\nType: String\nRequired: no\nValid values: list of regions/availability zones\n\nproduct-description\nFilters by the platform description (operating system) of the reserved instance, such as `linux`.\nType: String\nRequired: no\nValid value: linux\n\nduration\nFilters by the **validity** of the reserved instance, which is the purchased usage period. For example, `31536000`.\nType: Integer\nUnit: second\nRequired: no\nValid values: 31536000 (1 year), 94608000 (3 years)" } ], "desc": "This API is used to describe reserved instance (RI) offerings. Currently, RIs are only offered to beta users." }, "InquiryPriceResetInstancesType": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). You can obtain the instance IDs from the value of `InstanceId` returned by the [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) API. The maximum number of instances in each request is 1." }, { "name": "InstanceType", "desc": "Instance model. Resources vary with the instance model. Specific values can be found in the tables of [Instance Types] (https://intl.cloud.tencent.com/document/product/213/11518?from_cn_redirect=1) or in the latest specifications via the [DescribeInstanceTypeConfigs] (https://intl.cloud.tencent.com/document/product/213/15749?from_cn_redirect=1) API." } ], "desc": "This API is used to query the price for adjusting the instance model.\n\n* Currently, you can only use this API to query the prices of instances whose [system disk type](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#block_device) is `CLOUD_BASIC`, `CLOUD_PREMIUM`, or `CLOUD_SSD`.\n* Currently, you cannot use this API to query the prices of [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) instances." }, "StopInstances": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. The maximum number of instances in each request is 100." }, { "name": "ForceStop", "desc": "Whether to force shut down an instance after a normal shutdown fails. Valid values: <br><li>TRUE: force shut down an instance after a normal shutdown fails <br><li>FALSE: do not force shut down an instance after a normal shutdown fails <br><br>Default value: FALSE." }, { "name": "StopType", "desc": "Instance shutdown mode. Valid values: <br><li>SOFT_FIRST: perform a soft shutdown first, and force shut down the instance if the soft shutdown fails <br><li>HARD: force shut down the instance directly <br><li>SOFT: soft shutdown only <br>Default value: SOFT." }, { "name": "StoppedMode", "desc": "Billing method of a pay-as-you-go instance after shutdown.\nValid values: <br><li>KEEP_CHARGING: billing continues after shutdown <br><li>STOP_CHARGING: billing stops after shutdown <br>Default value: KEEP_CHARGING.\nThis parameter is only valid for some pay-as-you-go instances using cloud disks. For more information, see [No charges when shut down for pay-as-you-go instances](https://intl.cloud.tencent.com/document/product/213/19918)." } ], "desc": "This API is used to shut down instances.\n\n* You can only perform this operation on instances whose status is `RUNNING`.\n* The instance status will become `STOPPING` when the API is called successfully and `STOPPED` when the instance is successfully shut down.\n* Forced shutdown is supported. A forced shutdown is similar to switching off the power of a physical computer. It may cause data loss or file system corruption. Be sure to only force shut down a CVM when it cannot be sht down normally.\n* Batch operations are supported. The maximum number of instances in each request is 100." }, "ModifyHostsAttribute": { "params": [ { "name": "HostIds", "desc": "CDH instance ID(s)." }, { "name": "HostName", "desc": "CDH instance name to be displayed. You can specify any name you like, but its length cannot exceed 60 characters." }, { "name": "RenewFlag", "desc": "Auto renewal flag. Valid values: <br><li>NOTIFY_AND_AUTO_RENEW: notify upon expiration and renew automatically <br><li>NOTIFY_AND_MANUAL_RENEW: notify upon expiration but do not renew automatically <br><li>DISABLE_NOTIFY_AND_MANUAL_RENEW: neither notify upon expiration nor renew automatically <br><br>If this parameter is specified as NOTIFY_AND_AUTO_RENEW, the instance will be automatically renewed on a monthly basis if the account balance is sufficient." }, { "name": "ProjectId", "desc": "Project ID. You can create a project by using the [AddProject](https://intl.cloud.tencent.com/doc/api/403/4398?from_cn_redirect=1) API and obtain its ID from the response parameter `projectId` of the [`DescribeProject`](https://intl.cloud.tencent.com/document/product/378/4400?from_cn_redirect=1) API. Subsequently, the project ID can be used to filter results when you query instances by calling the [DescribeHosts](https://intl.cloud.tencent.com/document/api/213/16474?from_cn_redirect=1) API." } ], "desc": "This API is used to modify the attributes of a CDH instance, such as instance name and renewal flag. One of the two parameters, HostName and RenewFlag, must be set, but you cannot set both of them at the same time." }, "DescribeImportImageOs": { "params": [], "desc": "This API is used to query the list of supported operating systems of imported images." }, "InquirePricePurchaseReservedInstancesOffering": { "params": [ { "name": "InstanceCount", "desc": "The number of the reserved instances you are purchasing." }, { "name": "ReservedInstancesOfferingId", "desc": "The ID of the reserved instance offering." }, { "name": "DryRun", "desc": "Dry run." }, { "name": "ClientToken", "desc": "A unique string supplied by the client to ensure that the request is idempotent. Its maximum length is 64 ASCII characters. If this parameter is not specified, the idempotency of the request cannot be guaranteed.<br>For more information, see Ensuring Idempotency." }, { "name": "ReservedInstanceName", "desc": "Reserved instance name.<br><li>The RI name defaults to “unnamed” if this parameter is left empty.</li><li>You can enter any name within 60 characters (including the pattern string).</li>" } ], "desc": "This API is used to query the price of reserved instances. It only supports querying purchasable reserved instance offerings. Currently, RIs are only offered to beta users." }, "DescribeInstanceVncUrl": { "params": [ { "name": "InstanceId", "desc": "Instance ID. To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response." } ], "desc": "This API is used to query the Virtual Network Console (VNC) URL of an instance for its login to the VNC.\n\n* It does not support `STOPPED` CVMs.\n* A VNC URL is only valid for 15 seconds. If you do not access the URL within 15 seconds, it will become invalid and you have to query a URL again.\n* Once the VNC URL is accessed, it will become invalid and you have to query a URL again if needed.\n* If the connection is interrupted, you can make up to 30 reconnection attempts per minute.\n* After getting the value `InstanceVncUrl`, you need to append `InstanceVncUrl=xxxx` to the end of the link <https://img.qcloud.com/qcloud/app/active_vnc/index.html?>.\n\n - `InstanceVncUrl`: its value will be returned after the API is successfully called.\n\n The final URL is in the following format:\n\n```\nhttps://img.qcloud.com/qcloud/app/active_vnc/index.html?InstanceVncUrl=wss%3A%2F%2Fbjvnc.qcloud.com%3A26789%2Fvnc%3Fs%3DaHpjWnRVMFNhYmxKdDM5MjRHNlVTSVQwajNUSW0wb2tBbmFtREFCTmFrcy8vUUNPMG0wSHZNOUUxRm5PMmUzWmFDcWlOdDJIbUJxSTZDL0RXcHZxYnZZMmRkWWZWcEZia2lyb09XMzdKNmM9\n```\n" }, "ResetInstance": { "params": [ { "name": "InstanceId", "desc": "Instance ID. To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response." }, { "name": "ImageId", "desc": "Specified effective [image](https://intl.cloud.tencent.com/document/product/213/4940?from_cn_redirect=1) ID in the format of `img-xxx`. There are four types of images:<br/><li>Public images</li><li>Custom images</li><li>Shared images</li><li>Marketplace images </li><br/>You can obtain the available image IDs in the following ways:<br/><li>for IDs of `public images`, `custom images`, and `shared images`, log in to the [CVM console](https://console.cloud.tencent.com/cvm/image?rid=1&imageType=PUBLIC_IMAGE); for IDs of `marketplace images`, go to [Cloud Marketplace](https://market.cloud.tencent.com/list).</li><li>Call the API [DescribeImages](https://intl.cloud.tencent.com/document/api/213/15715?from_cn_redirect=1) and look for `ImageId` in the response.</li>\n<br>Default value: current image." }, { "name": "SystemDisk", "desc": "System disk configurations in the instance. For instances with a cloud disk as the system disk, you can expand the capacity of the system disk to the specified value after re-installation by using this parameter. If the parameter is not specified, lower system disk capacity will be automatically expanded to the image size, and extra disk costs are generated. You can only expand but cannot reduce the system disk capacity. By re-installing the system, you only modify the system disk capacity, but not the type." }, { "name": "LoginSettings", "desc": "Login settings of the instance. You can use this parameter to set the login method, password, and key of the instance or keep the login settings of the original image. By default, a random password will be generated and sent to you via the Message Center." }, { "name": "EnhancedService", "desc": "Enhanced services. You can use this parameter to specify whether to enable services such as Cloud Monitor and Cloud Security. If this parameter is not specified, Cloud Monitor and Cloud Security will be enabled by default." }, { "name": "HostName", "desc": "Host name of the CVM, editable during the system reinstallation. <br><li>Periods (.) or hyphens (-) cannot be the start or end of a host name or appear consecutively in a host name.<br><li>For Windows instances, the host name must consist of 2-15 characters , including uppercase and lowercase letters, numbers, or hyphens (-). It cannot contain periods (.) or contain only numbers.<br><li>For other instances, such as Linux instances, the host name must consist of 2-60 characters, including multiple periods (.), and allows uppercase and lowercase letters, numbers, or hyphens (-) between any two periods (.)." } ], "desc": "This API is used to reinstall the operating system of the specified instance.\n\n* If you specify an `ImageId`, the specified image is used. Otherwise, the image used by the current instance is used.\n* The system disk will be formatted and reset. Therefore, make sure that no important files are stored on the system disk.\n* If the operating system switches between `Linux` and `Windows`, the system disk `ID` of the instance will change, and the snapshots that are associated with the system disk can no longer be used to roll back and restore data.\n* If no password is specified, you will get a random password via internal message.\n* You can only use this API to switch the operating system between `Linux` and `Windows` for instances whose [system disk type](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#SystemDisk) is `CLOUD_BASIC`, `CLOUD_PREMIUM`, or `CLOUD_SSD`.\n* Currently, this API only supports instances in Mainland China regions." }, "SyncImages": { "params": [ { "name": "ImageIds", "desc": "List of image IDs. You can obtain the image IDs in two ways: <br><li>Call [DescribeImages](https://intl.cloud.tencent.com/document/api/213/15715?from_cn_redirect=1) and look for `ImageId` in the response. <br><li>Look for the information in the [Image Console](https://console.cloud.tencent.com/cvm/image). <br>The specified images must meet the following requirements: <br><li>The images must be in the `NORMAL` state. <br><li>The image size must be smaller than 50 GB. <br>For more information on image states, see [here](https://intl.cloud.tencent.com/document/api/213/9452?from_cn_redirect=1#image_state)." }, { "name": "DestinationRegions", "desc": "List of destination regions for synchronization. A destination region must meet the following requirements: <br><li>It cannot be the source region. <br><li>It must be valid. <br><li>Currently some regions do not support image synchronization. <br>For specific regions, see [Region](https://intl.cloud.tencent.com/document/product/213/6091?from_cn_redirect=1)." } ], "desc": "This API is used to sync a custom image to other regions.\n\n* Each API call syncs a single image.\n* This API supports syncing an image to multiple regions.\n* Each account can have up to 10 custom images in each region. " }, "DeleteDisasterRecoverGroups": { "params": [ { "name": "DisasterRecoverGroupIds", "desc": "ID list of spread placement groups, obtainable via the [DescribeDisasterRecoverGroups](https://intl.cloud.tencent.com/document/api/213/17810?from_cn_redirect=1) API. You can operate up to 100 spread placement groups in each request." } ], "desc": "This API is used to delete a [spread placement group](https://intl.cloud.tencent.com/document/product/213/15486?from_cn_redirect=1). Only empty placement groups can be deleted. To delete a non-empty group, you need to terminate all the CVM instances in it first. Otherwise, the deletion will fail." }, "TerminateInstances": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. The maximum number of instances in each request is 100." } ], "desc": "This API is used to return instances.\n\n* Use this API to return instances that are no longer required.\n* Pay-as-you-go instances can be returned directly through this API.\n* When this API is called for the first time, the instance will be moved to the recycle bin. When this API is called for the second time, the instance will be terminated and cannot be recovered.\n* Batch operations are supported. The allowed maximum number of instances in each request is 100." }, "DescribeZoneInstanceConfigInfos": { "params": [ { "name": "Filters", "desc": "Filters.\n\n<li> `zone` - String - Optional - Filter results by availability zone.</li>\n\n<li>`instance-family` - String - Optional - Filter results by instance model family, such as `S1`, `I1`, and `M1`.</li>\n\n<li>`instance-type` - String - Optional - Filter results by model. Different instance models have different configurations. You can call `DescribeInstanceTypeConfigs` to query the latest configuration list or refer to the documentation on instance types. If this parameter is not specified, `S1.SMALL1` will be used by default.</li>\n\n<li>`instance-charge-type` - String - Optional - Filter results by instance billing method. `POSTPAID_BY_HOUR`: pay-as-you-go | `CDHPAID`: you are only billed for CDH instances, not the CVMs running on the CDH instances.</li>" } ], "desc": "This API is used to query the configurations of models in an availability zone." }, "ResetInstancesInternetMaxBandwidth": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. The maximum number of instances in each request is 100. When changing the bandwidth of instances with `BANDWIDTH_PREPAID` or `BANDWIDTH_POSTPAID_BY_HOUR` as the network billing method, you can only specify one instance at a time." }, { "name": "InternetAccessible", "desc": "Configuration of public network egress bandwidth. The maximum bandwidth varies among different models. For more information, see the documentation on bandwidth limits. Currently only the `InternetMaxBandwidthOut` parameter is supported." }, { "name": "StartTime", "desc": "Date from which the new bandwidth takes effect. Format: `YYYY-MM-DD`, such as `2016-10-30`. The starting date cannot be earlier than the current date. If the starting date is the current date, the new bandwidth takes effect immediately. This parameter is only valid for prepaid bandwidth. If you specify the parameter for bandwidth with other network billing methods, an error code will be returned." }, { "name": "EndTime", "desc": "Date until which the new bandwidth is effective. Format: `YYYY-MM-DD`, such as `2016-10-30`. The validity period of the new bandwidth covers the end date. The end date cannot be later than the expiration date of a prepaid instance. You can query the expiration time of an instance by calling [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728) and looking for `ExpiredTime` in the response. This parameter is only valid for prepaid bandwidth. If you specify the parameter for bandwidth with other network billing methods, an error code will be returned." } ], "desc": "This API is used to change the public bandwidth cap of an instance.\n\n* The allowed bandwidth cap varies for different models. For details, see [Purchasing Network Bandwidth](https://intl.cloud.tencent.com/document/product/213/509?from_cn_redirect=1).\n* For bandwidth billed by the `TRAFFIC_POSTPAID_BY_HOUR` method, changing the bandwidth cap through this API takes effect in real time. Users can increase or reduce bandwidth within applicable limits." }, "StartInstances": { "params": [ { "name": "InstanceIds", "desc": "Instance ID(s). To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. The maximum number of instances in each request is 100." } ], "desc": "This API is used to start instances.\n\n* You can only perform this operation on instances whose status is `STOPPED`.\n* The instance status will become `STARTING` when the API is called successfully and `RUNNING` when the instance is successfully started.\n* Batch operations are supported. The maximum number of instances in each request is 100." }, "DescribeDisasterRecoverGroups": { "params": [ { "name": "DisasterRecoverGroupIds", "desc": "ID list of spread placement groups. You can operate up to 100 spread placement groups in each request." }, { "name": "Name", "desc": "Name of a spread placement group. Fuzzy match is supported." }, { "name": "Offset", "desc": "Offset; default value: 0. For more information on `Offset`, see the corresponding section in API [Introduction](https://intl.cloud.tencent.com/document/product/377)." }, { "name": "Limit", "desc": "Number of results returned; default value: 20; maximum: 100. For more information on `Limit`, see the corresponding section in API [Introduction](https://intl.cloud.tencent.com/document/product/377). " } ], "desc": "This API is used to query the information on [spread placement groups](https://intl.cloud.tencent.com/document/product/213/15486?from_cn_redirect=1)." }, "DescribeKeyPairs": { "params": [ { "name": "KeyIds", "desc": "Key pair ID(s) in the format of `skey-11112222`. This API supports using multiple IDs as filters at the same time. For more information on the format of this parameter, see the `id.N` section in [API Introduction](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1). You cannot specify `KeyIds` and `Filters` at the same time. You can log in to the [console](https://console.cloud.tencent.com/cvm/index) to query the key pair IDs." }, { "name": "Filters", "desc": "Filters.\n<li> `project-id` - Integer - Optional - Filter results by project ID. To view the list of project IDs, you can go to [Project Management](https://console.cloud.tencent.com/project), or call [DescribeProject](https://intl.cloud.tencent.com/document/api/378/4400?from_cn_redirect=1) and look for `projectId` in the response. </li>\n<li> `key-name` - String - Optional - Filter results by key pair name. </li> You cannot specify `KeyIds` and `Filters` at the same time." }, { "name": "Offset", "desc": "Offset; default value: 0. For more information on `Offset`, see the corresponding sections in API [Introduction](https://intl.cloud.tencent.com/document/product/377). Number of results returned; default value: 20; maximum: 100. For more information on `Limit`, see the corresponding section in API [Introduction](https://intl.cloud.tencent.com/document/product/377). " }, { "name": "Limit", "desc": "Number of results returned; default value: 20; maximum: 100. For more information on `Limit`, see the corresponding section in API [Introduction](https://intl.cloud.tencent.com/document/product/377). " } ], "desc": "This API is used to query key pairs.\n\n* A key pair is a pair of keys generated by an algorithm in which the public key is available to the public and the private key is available only to the user. You can use this API to query the public key but not the private key." }, "DescribeReservedInstancesOfferings": { "params": [ { "name": "DryRun", "desc": "Dry run. Default value: false." }, { "name": "Offset", "desc": "The offset. Default value: 0. For more information on `Offset`, see the relevant sections in API [Introduction](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1)." }, { "name": "Limit", "desc": "The number of returned results. Default value: 20. Maximum value: 100. For more information on `Limit`, see the relevant sections in API [Introduction](https://intl.cloud.tencent.com/document/api/213/15688?from_cn_redirect=1)." }, { "name": "MaxDuration", "desc": "The maximum duration as a filter, \nin seconds.\nDefault value: 94608000." }, { "name": "MinDuration", "desc": "The minimum duration as a filter, \nin seconds.\nDefault value: 2592000." }, { "name": "Filters", "desc": "<li><strong>zone</strong></li>\n<p style=\"padding-left: 30px;\">Filters by the <strong>availability zones</strong> in which the Reserved Instances can be purchased, such as ap-guangzhou-1.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: please see <a href=\"https://intl.cloud.tencent.com/document/product/213/6091?from_cn_redirect=1\">Availability Zones</a></p>\n<li><strong>duration</strong></li>\n<p style=\"padding-left: 30px;\">Filters by the <strong>duration</strong> of the Reserved Instance, in seconds. For example, 31536000.</p><p style=\"padding-left: 30px;\">Type: Integer</p><p style=\"padding-left: 30px;\">Unit: second</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: 31536000 (1 year) | 94608000 (3 years)</p>\n<li><strong>instance-type</strong></li>\n<p style=\"padding-left: 30px;\">Filters by <strong>type of the Reserved Instance</strong>, such as `S3.MEDIUM4`.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: please see <a href=\"https://intl.cloud.tencent.com/document/product/213/11518?from_cn_redirect=1\">Instance Types</a></p>\n<li><strong>offering-type</strong></li>\n<p style=\"padding-left: 30px;\">Filters by **<strong>payment term</strong>**, such as `All Upfront`.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid value: All Upfront</p>\n<li><strong>product-description</strong></li>\n<p style=\"padding-left: 30px;\">Filters by the <strong>platform description</strong> (operating system) of the Reserved Instance, such as `linux`.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid value: linux</p>\n<li><strong>reserved-instances-offering-id</strong></li>\n<p style=\"padding-left: 30px;\">Filters by <strong>Reserved Instance ID</strong>, in the form of 650c138f-ae7e-4750-952a-96841d6e9fc1.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p>\nEach request can have up to 10 `Filters` and 5 `Filter.Values`." } ], "desc": "This API is used to describe Reserved Instance offerings that are available for purchase." }, "DescribeHosts": { "params": [ { "name": "Filters", "desc": "<li><strong>zone</strong></li>\n<p style=\"padding-left: 30px;\">Filter results by **<strong>availability zones</strong>**. For example, availability zone: ap-guangzhou-1;</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: <a href=\"https://intl.cloud.tencent.com/document/product/213/6091?from_cn_redirect=1\">list of availability zones</a></p>\n<li><strong>project-id</strong></li>\n<p style=\"padding-left: 30px;\">Filter results by **<strong>project ID</strong>**. You can query the existing project list through the [DescribeProject](https://intl.cloud.tencent.com/document/api/378/4400?from_cn_redirect=1) API or [CVM console](https://console.cloud.tencent.com/cvm/index), or create a project by calling the [AddProject](https://intl.cloud.tencent.com/document/api/378/4398?from_cn_redirect=1) API. For example, project ID: 1002189;</p><p style=\"padding-left: 30px;\">Type: Integer</p><p style=\"padding-left: 30px;\">Required: no</p>\n<li><strong>host-id</strong></li>\n<p style=\"padding-left: 30px;\">Filter results by **<strong>[CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) ID</strong>**. For example, [CDH](https://intl.cloud.tencent.com/document/product/416?from_cn_redirect=1) ID: host-xxxxxxxx;</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p>\n<li><strong>state</strong></li>\n<p style=\"padding-left: 30px;\">Filter results by **<strong>CDH instance name</strong>**. </p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p>\n<li><strong>state</strong></li>\n<p style=\"padding-left: 30px;\">Filter results by **<strong>CDH instance status </strong>**. (PENDING: creating | LAUNCH_FAILURE: creation failed | RUNNING: running | EXPIRED: expired)</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p>\nEach request can have up to 10 `Filters` and 5 `Filters.Values`." }, { "name": "Offset", "desc": "Offset; default value: 0." }, { "name": "Limit", "desc": "Number of results returned; default value: 20; maximum: 100." } ], "desc": "This API is used to query the details of CDH instances." }, "ModifyDisasterRecoverGroupAttribute": { "params": [ { "name": "DisasterRecoverGroupId", "desc": "Spread placement group ID, which can be obtained by calling the [DescribeDisasterRecoverGroups](https://intl.cloud.tencent.com/document/api/213/17810?from_cn_redirect=1) API." }, { "name": "Name", "desc": "Name of a spread placement group. The name must be 1-60 characters long and can contain both Chinese characters and English letters." } ], "desc": "This API is used to modify the attributes of [spread placement groups](https://intl.cloud.tencent.com/document/product/213/15486?from_cn_redirect=1)." }, "DescribeInternetChargeTypeConfigs": { "params": [], "desc": "This API is used to query the network billing methods." }, "RebootInstances": { "params": [ { "name": "InstanceIds", "desc": "Instance IDs. To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. You can operate up to 100 instances in each request." }, { "name": "ForceReboot", "desc": "Whether to force restart an instance after a normal restart fails. Valid values: <br><li>TRUE: force restart an instance after a normal restart fails <br><li>FALSE: do not force restart an instance after a normal restart fails <br><br>Default value: FALSE." }, { "name": "StopType", "desc": "Shutdown type. Valid values: <br><li>SOFT: soft shutdown<br><li>HARD: hard shutdown<br><li>SOFT_FIRST: perform a soft shutdown first, and perform a hard shutdown if the soft shutdown fails<br><br>Default value: SOFT." } ], "desc": "This API is used to restart instances.\n\n* You can only perform this operation on instances whose status is `RUNNING`.\n* If the API is called successfully, the instance status will become `REBOOTING`. After the instance is restarted, its status will become `RUNNING` again.\n* Forced restart is supported. A forced restart is similar to switching off the power of a physical computer and starting it again. It may cause data loss or file system corruption. Be sure to only force start a CVM when it cannot be restarted normally.\n* Batch operations are supported. The maximum number of instances in each request is 100." }, "DescribeInstanceTypeConfigs": { "params": [ { "name": "Filters", "desc": "<li><strong>zone</strong></li>\n<p style=\"padding-left: 30px;\">Filter results by **<strong>availability zones</strong>**. For example, availability zone: ap-guangzhou-1.</p><p style=\"padding-left: 30px;\">Type: String</p><p style=\"padding-left: 30px;\">Required: no</p><p style=\"padding-left: 30px;\">Valid values: <a href=\"https://intl.cloud.tencent.com/document/product/213/6091?from_cn_redirect=1\">list of availability zones</a></p>\n<li><strong>instance-family</strong></li>\n<p style=\"padding-left: 30px;\">Filter results by **<strong>instance models</strong>**. For example, instance models: S1, I1 and M1.</p><p style=\"padding-left: 30px;\">Type: Integer</p><p style=\"padding-left: 30px;\">Required: no</p>\nEach request can have up to 10 `Filters` and 1 `Filters.Values`." } ], "desc": "This API is used to query the model configuration of an instance.\n\n* You can filter the query results with `zone` or `instance-family`. For more information on filtering conditions, see [`Filter`](https://intl.cloud.tencent.com/document/api/213/15753?from_cn_redirect=1#Filter).\n* If no parameter is defined, the model configuration of all the instances in the specified region will be returned." }, "ModifyInstancesProject": { "params": [ { "name": "InstanceIds", "desc": "Instance IDs. To obtain the instance IDs, you can call [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) and look for `InstanceId` in the response. You can operate up to 100 instances in each request." }, { "name": "ProjectId", "desc": "Project ID. You can create a project by using the [AddProject](https://intl.cloud.tencent.com/doc/api/403/4398?from_cn_redirect=1) API and obtain its ID from the response parameter `projectId` of the [`DescribeProject`](https://intl.cloud.tencent.com/document/product/378/4400?from_cn_redirect=1) API. Subsequently, the project ID can be used to filter results when you query instances by calling the [DescribeInstances](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) API." } ], "desc": "This API is used to change the project to which an instance belongs.\n\n* Project is a virtual concept. You can create multiple projects under one account, manage different resources in each project, and assign different instances to different projects. You may use the [`DescribeInstances`](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1) API to query instances and use the project ID to filter results.\n* You cannot modify the project of an instance that is bound to a load balancer. You need to firstly unbind the load balancer from the instance by using the [`DeregisterInstancesFromLoadBalancer`](https://intl.cloud.tencent.com/document/api/214/1258?from_cn_redirect=1) API.\n[^_^]: # (If you modify the project of an instance, security groups associated with the instance will be automatically disassociated. You can use the [`ModifyInstancesAttribute`](https://intl.cloud.tencent.com/document/api/213/15739?from_cn_redirect=1) API to associate the instance with the security groups again.\n* Batch operations are supported. You can operate up to 100 instances in each request.\n* You can call the [DescribeInstances](https://intl.cloud.tencent.com/document/api/213/15728?from_cn_redirect=1#.E7.A4.BA.E4.BE.8B3-.E6.9F.A5.E8.AF.A2.E5.AE.9E.E4.BE.8B.E7.9A.84.E6.9C.80.E6.96.B0.E6.93.8D.E4.BD.9C.E6.83.85.E5.86.B5) API and find the result of the operation in the response parameter `LatestOperationState`. If the value is `SUCCESS`, the operation is successful." }, "DisassociateSecurityGroups": { "params": [ { "name": "SecurityGroupIds", "desc": "ID of the security group to be disassociated, such as `sg-efil73jd`. Only one security group can be disassociated." }, { "name": "InstanceIds", "desc": "ID(s) of the instance(s) to be disassociated,such as `ins-lesecurk`. You can specify multiple instances." } ], "desc": "This API is used to disassociate security groups from instances." }, "AllocateHosts": { "params": [ { "name": "Placement", "desc": "Instance location. This parameter is used to specify the attributes of an instance, such as its availability zone and project." }, { "name": "ClientToken", "desc": "A string used to ensure the idempotency of the request." }, { "name": "HostChargePrepaid", "desc": "Configuration of prepaid instances. You can use the parameter to specify the attributes of prepaid instances, such as the subscription period and the auto-renewal plan. This parameter is required for prepaid instances." }, { "name": "HostChargeType", "desc": "Instance billing model, only monthly or yearly subscription supported. Default value: `PREPAID'." }, { "name": "HostType", "desc": "CDH instance model. Default value: `HS1`." }, { "name": "HostCount", "desc": "Quantity of CDH instances purchased. Default value: 1." }, { "name": "TagSpecification", "desc": "Tag description. You can specify the parameter to associate a tag with an instance." } ], "desc": "This API is used to create CDH instances with specified configuration.\n* When HostChargeType is PREPAID, the HostChargePrepaid parameter must be specified." }, "DescribeSpotTypeConfig": { "params": [], "desc": "This API is used to query spot instances that are available for purchase." } }
# Numeral System Converter """ TODO 1. Convert from any system to decimal """ def binary_to_decimal(bin_string:str) -> int: bin_string = str(bin_string).strip() if not bin_string: raise ValueError("Empty string was passed to the function") is_negative = bin_string[0] == "-" if is_negative: bin_string = bin_string[1:] if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") decimal_number = 0 for char in bin_string: decimal_number = 2 * decimal_number + int(char) return -decimal_number if is_negative else decimal_number def to_dec(num:int) -> int: pass def main(): print(binary_to_decimal(2)) pass if __name__ == "__main__": main()
class AcousticParam(object): def __init__( self, sampling_rate: int = 24000, pad_second: float = 0, threshold_db: float = None, frame_period: int = 5, order: int = 8, alpha: float = 0.466, f0_floor: float = 71, f0_ceil: float = 800, fft_length: int = 1024, dtype: str = 'float32', ) -> None: self.sampling_rate = sampling_rate self.pad_second = pad_second self.threshold_db = threshold_db self.frame_period = frame_period self.order = order self.alpha = alpha self.f0_floor = f0_floor self.f0_ceil = f0_ceil self.fft_length = fft_length self.dtype = dtype def _asdict(self): return self.__dict__
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 11 12:52:32 2018 @author: cyril-kubu """
def print_vars(obj): """ Prints all non-private attributes variables (does not start with '_' and not method) :param obj: :return: """ for attr in dir(obj): if attr[0] is "_" or callable(getattr(obj,attr)): continue print(attr, ":", getattr(obj, attr)) def print_methods(obj): """ Prints all non-private attributes methods (does not start with '_' and not method) :param obj: :return: """ for attr in dir(obj): if attr[0] is "_" or not callable(getattr(obj,attr)): continue print(attr, ":", getattr(obj, attr)) def print_attr(obj): """ Prints all non-private attributes :param obj: :return: """ for attr in dir(obj): if attr[0] is "_": continue print(attr, ":", getattr(obj, attr))
""" Class for storing method parameters. """ class JavaMethodParameter: def __init__(self, identifier, parameter_type): self.__identifier = identifier self.__type = parameter_type @property def identifier(self): return self.__identifier @property def parameter_type(self): return self.__type
def get_headers(text): list_a = text.split("\n")[1:] list_headers = [] for i in list_a: if not i: break list_headers.append(i.split(": ")) return dict(list_headers)
#WAP to find, a given number is prime or not num = int(input("enter number")) if num>1: #check for factors for i in range(2,num): if(num / i) == 0: print(num," is not prime number") break else: print(num," is not a prime number")
# Description: Print the B-factors of a residue. # Source: placeHolder """ cmd.do('remove element h; iterate resi ${1: 1:13}, print(resi, name,b);') """ cmd.do('remove element h; iterate resi 1:13, print(resi, name,b);')