content
stringlengths
7
1.05M
""" Part 1 Solution: 580 Part 2 Solution: 81972 """ # Basically a Sum function def solve_day1_part1(): fname = "data_day1.txt" frequency = 0 with open(fname) as fp: line = fp.readline().rstrip("\n") while line: i = int(line) frequency += i # print("{} => {} = {}".format(line, i, total)) # print("{}".format(frequency)) line = fp.readline().rstrip("\n") return frequency """ # Notes - Must read the data several times until we find a repeated frequency. - Maybe I should read the data in a list once for performance but what if we have billions of numbers? """ def solve_day1_part2(frequency, frequency_count): fname = "data_day1.txt" # total_count["-17"] = 3 with open(fname) as fp: line = fp.readline().rstrip("\n") while line: i = int(line) frequency += i key = str(frequency) if key not in frequency_count: frequency_count[key] = 1 # print("Adding T={}\n".format(key)) else: print("Dup T={}".format(key)) # print("Frequency table: 1".format(total_count)) return key # print("{} => {} = {}".format(line, i, total)) line = fp.readline().rstrip("\n") # print("Once more") return solve_day1_part2(frequency, frequency_count) total = solve_day1_part1() print("Sum={}".format(total)) # frequency_count = {} first_repeat = solve_day1_part2(0, {}) print("first repeated ={}".format(first_repeat))
a=int(input("enter first number:")) b=int(input("enter second number:")) sum=0 for i in range (a,b+1): sum=sum+i print(sum)
# contains bunch of buggy examples # taken from https://hackernoon.com/10-common-security-gotchas-in-python # -and-how-to-avoid-them-e19fbe265e03 def transcode_file(filename): """Input injection""" command = 'ffmpeg -i "{source}" output_file.mpg'.format(source=filename) return command # a bad idea! def access_function(user): """Assert statements""" assert user.is_admin, 'user does not have access' # secure code... class RunBinSh(): """Pickles""" def __reduce__(self): return
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {integer[]} preorder # @param {integer[]} inorder # @return {TreeNode} def buildTree(self, preorder, inorder): if not preorder or not inorder: return None n1,n2 = len(preorder), len(inorder) if n1!=n2 or n1 == 0: return None root = TreeNode(0) st = [root] i = 0 j = 0 last_pop= root while(i < n1): num = preorder[i] node = TreeNode(num) if last_pop != None: last_pop.right = node st.append(node) last_pop = None else: last = st[-1] last.left = node st.append(node) while(j < n1 and st[-1].val == inorder[j]): last_pop = st.pop() j += 1 i+=1 return root.right
while 1: a = 1 break print(a) # pass
class Solution: def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ start = self.binarySearch(nums, target) if start == -1: return [-1, -1] end = self.binarySearch(nums, target, True) return [start, end] def binarySearch(self, nums, target, getRight=False): if len(nums) == 0: return -1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = int(start + (end - start) / 2) if nums[mid] == target: if getRight: start = mid else: end = mid elif nums[mid] < target: start = mid + 1 else: end = mid - 1 if getRight: if nums[end] == target: return end elif nums[start] == target: return start else: if nums[start] == target: return start elif nums[end] == target: return end return -1
# Migration removed because it depends on models which have been removed def run(): return False
""" Program to determine whether a given number is a Harshad number Harshad number A number is said to be the Harshad number if it is divisible by the sum of its digit. For example, if number is 156, then sum of its digit will be 1 + 5 + 6 = 12. Since 156 is divisible by 12. So, 156 is a Harshad number. Some of the other examples of Harshad number are 8, 54, 120, etc. To find whether the given number is a Harshad number or not, calculate the sum of the digit of the number then, check whether the given number is divisible by the sum of its digit. If yes, then given number is a Harshad number.""" num = int(input("Enter a number: ")); rem = sum = 0; #Make a copy of num and store it in variable n n = num; #Calculates sum of digits while(num > 0): rem = num%10; sum = sum + rem; num = num//10; #Checks whether the number is divisible by the sum of digits if(n%sum == 0): print(str(n) + " is a harshad number"); else: print(str(n) + " is not a harshad number");
#-----------------------------------------------------------------# #! Python3 # Author : NK # Month, Year : March, 2019 # Info : Program to get Squares of numbers upto 25, using return # Desc : An example program to show usage of return #-----------------------------------------------------------------# def nextSquare(x): return x*x def main(): for x in range(25): print(nextSquare(x)) if __name__ == '__main__': main()
# Reference: http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf#G24646 BASE_OF_SYLLABLES = 0xAC00 BASE_OF_LEADING_CONSONANTS = 0x1100 BASE_OF_VOWELS = 0x1161 BASE_OF_TRAILING_CONSONANTS = 0x11A7 # one less than the beginning of the range of trailing consonants (0x11A8) NUMBER_OF_LEADING_CONSONANTS = 19 NUMBER_OF_VOWELS = 21 NUMBER_OF_TRAILING_CONSONANTS = 28 # one more than the number of trailing consonants NUMBER_OF_SYLLABLES_FOR_EACH_LEADING_CONSONANT = NUMBER_OF_VOWELS * NUMBER_OF_TRAILING_CONSONANTS # 가-깋 + 1 NUMBER_OF_SYLLABLES = NUMBER_OF_LEADING_CONSONANTS * NUMBER_OF_SYLLABLES_FOR_EACH_LEADING_CONSONANT LEADING_CONSONANTS = ['ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'] INDEX_BY_LEADING_CONSONANT = { leading_consonant: index for index, leading_consonant in enumerate(LEADING_CONSONANTS) } VOWELS = ['ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ'] INDEX_BY_VOWEL = { vowel: index for index, vowel in enumerate(VOWELS) } TRAILING_CONSONANTS = [None, 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'] INDEX_BY_TRAILING_CONSONANT = { trailing_consonant: index for index, trailing_consonant in enumerate(TRAILING_CONSONANTS) }
def get_planet_name(id): tmp = { 1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars", 5: "Jupiter", 6: "Saturn", 7: "Uranus", 8: "Neptune" } return tmp[id]
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions = [(val, idx) for idx, val in enumerate(potions)] potions.sort() spells = [(val, idx) for idx, val in enumerate(spells)] spells.sort() left = 0 right = len(potions) - 1 res = [0] * len(spells) while left < len(spells): while right >= 0 and spells[left][0] * potions[right][0] >= success: right -= 1 res[spells[left][1]] = max(res[left], len(potions) - right - 1) left += 1 return res
# # PySNMP MIB module SONOMASYSTEMS-SONOMA-IPAPPS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-IPAPPS-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:09:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Unsigned32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Gauge32, Counter32, Integer32, IpAddress, iso, Counter64, ObjectIdentity, TimeTicks, MibIdentifier, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Gauge32", "Counter32", "Integer32", "IpAddress", "iso", "Counter64", "ObjectIdentity", "TimeTicks", "MibIdentifier", "NotificationType") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") sonomaApplications, = mibBuilder.importSymbols("SONOMASYSTEMS-SONOMA-MIB", "sonomaApplications") ipApplications = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1)) bootpGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1)) pingGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2)) class DisplayString(OctetString): pass tftpFileServerIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 1), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tftpFileServerIpAddress.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileServerIpAddress.setDescription('The IP Address of the file server to use for image and parameter file downloads and uploads.') tftpFileName = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tftpFileName.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileName.setDescription('The path and name of the file to be uploaded or downloaded. This string is 128 charachters long, any longer causes problems fro Windown NT or Windows 95. This length is recommended in RFC 1542.') tftpImageNumber = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("image1", 1), ("image2", 2), ("image3", 3), ("image4", 4), ("image5", 5), ("image6", 6), ("image7", 7), ("image8", 8))).clone('image1')).setMaxAccess("readwrite") if mibBuilder.loadTexts: tftpImageNumber.setStatus('mandatory') if mibBuilder.loadTexts: tftpImageNumber.setDescription('The Image number (1 - 8) for the operational image file to be downloaded to. In the case of BOOTP the image will be stored in the BOOTP/ directory in flash') tftpFileAction = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("noAction", 1), ("startBootPImageDownload", 2), ("startTFTPImageDownload", 3), ("startPrimaryImageTFTPDownload", 4), ("startSecondaryImageTFTPDownload", 5), ("startTFTPParameterBinDownload", 6), ("startTFTPParameterTextDownload", 7), ("startTFTPParameterBinUpload", 8), ("startTFTPParameterTextUpload", 9), ("startTFTPProfileDownload", 10))).clone('noAction')).setMaxAccess("readwrite") if mibBuilder.loadTexts: tftpFileAction.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileAction.setDescription("This object is used to initiate file transfer between this unit and the file server identified by tftpFileServerIpAddress. A download indicates that the file transfer is from the file server (down) to the device. An upload indicates a file transfer from the device (up) to the server. This object can be used to initiate either image or parameter file downloads and a parameter file upload. There is no image file upload feature. An image file can be downloaded via either a BootP request (where the image filename and the BootP server's IP Address is unknown) or via a TFTP request where the user has configured the tftpFileName object with the path and name of the file. BootP cannot be used to download or upload a parameter file. An attempt to set this object to one of the following values: startTFTPImageDownload, startTFTPParameterDownload or startTFTPParameterUpload, will fail if either the tftpFileName or tftpFileServerIpAddress object has not bee configured. The tftpFileName and tftpFileServerIpAddress objects are ignored for BootP requests. A value of noAction is always returned to a GetRequest. Seting this object with a value of noAction has no effect. The startPrimaryImageTFTPDownload is used to initiate the download of the primary boot image. This image is only downloaded when there is a new revision of the basic boot mechanism or changes to the flash or CMOS sub-systems.") tftpFileTransferStatus = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18))).clone(namedValues=NamedValues(("idle", 1), ("downloading", 2), ("uploading", 3), ("programmingflash", 4), ("failBootpNoServer", 5), ("failTFTPNoFile", 6), ("errorServerResponse", 7), ("failTFTPInvalidFile", 8), ("failNetworkTimeout", 9), ("failFlashProgError", 10), ("failFlashChksumError", 11), ("errorServerData", 12), ("uploadResultUnknown", 13), ("uploadSuccessful", 14), ("downloadSuccessful", 15), ("generalFailure", 16), ("failCannotOverwriteActiveImage", 17), ("failCannotOverwriteActiveParam", 18)))).setMaxAccess("readonly") if mibBuilder.loadTexts: tftpFileTransferStatus.setStatus('mandatory') if mibBuilder.loadTexts: tftpFileTransferStatus.setDescription('This is the current status of the file transfer process.') pingIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 1), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pingIpAddress.setStatus('mandatory') if mibBuilder.loadTexts: pingIpAddress.setDescription(' The IP Address to Ping') pingTimeout = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pingTimeout.setStatus('mandatory') if mibBuilder.loadTexts: pingTimeout.setDescription('This is the timeout, in seconds, for a ping.') pingRetries = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 3), Integer32().clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: pingRetries.setStatus('mandatory') if mibBuilder.loadTexts: pingRetries.setDescription(' This value indicates the number of times, to ping. A value of 1 is the default and insicates that the unit will send one pingp. 0 means no action.') pingStatus = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("readonly") if mibBuilder.loadTexts: pingStatus.setStatus('mandatory') if mibBuilder.loadTexts: pingStatus.setDescription(' A text string which indicates the result or status of the last ping which the unit sent.') pingAction = MibScalar((1, 3, 6, 1, 4, 1, 2926, 25, 8, 1, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("start", 1), ("stop", 2), ("noAction", 3))).clone('noAction')).setMaxAccess("readwrite") if mibBuilder.loadTexts: pingAction.setStatus('mandatory') if mibBuilder.loadTexts: pingAction.setDescription('Indicates whether to stop or start a ping. This always returns the value noAction to a Get Request.') mibBuilder.exportSymbols("SONOMASYSTEMS-SONOMA-IPAPPS-MIB", tftpFileTransferStatus=tftpFileTransferStatus, tftpImageNumber=tftpImageNumber, pingRetries=pingRetries, pingGroup=pingGroup, ipApplications=ipApplications, tftpFileAction=tftpFileAction, tftpFileServerIpAddress=tftpFileServerIpAddress, pingTimeout=pingTimeout, pingAction=pingAction, pingStatus=pingStatus, pingIpAddress=pingIpAddress, bootpGroup=bootpGroup, DisplayString=DisplayString, tftpFileName=tftpFileName)
#!/usr/bin/env python3 '''Iterate over multiple sequences in parallel using zip() function NOET: zip() stops when the shortest sequence is done ''' # Init days = ['Monday', 'Tuesday', 'Wednesday'] fruits = ['banana', 'orange', 'peach'] drinks = ['coffee', 'tea', 'beer'] desserts = ['tiramisu', 'ice cream', 'pie', 'pudding'] for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts) : print(day, ': drink', drink, '- eat', fruit, '- enjoy', dessert)
"""One To Many. ...is used to mark that an instance of a class can be associated with many instances of another class. For example, on a blog engine, an instance of the Article class could be associated with many instances of the Comment class. In this case, we would map the mentioned classes and its relation as follows: """ class Article(Base): __tablename__ = "articles" id = Column(Integer, primary_key=True) comments = relationship("Comment") class Comment(Base): __tablename__ = "comments" id = Column(Integer, primary_key=True) article_id = Column(Integer, ForeignKey("articles.id"))
name=input("Please input my daughter's name:") while name!="Nina" and name!="Anime": print("I'm sorry, but the name is not valid.") name=input("Please input my daughter's name:") print("Yes."+name+"is my daughter.")
cases = [ ('pmt -s 1 -n 20 populations, use seed so same run each time', 'pmt -s 1 -n 20 populations'), ('pmt -s 2 -n 6 populations, use seed so same run each time', 'pmt -s 2 -n 6 -r 3 populations') ]
{ "hawq": { "master": "localhost", "standby": "", "port": 5432, "user": "johnsaxon", "password": "test", "database": "postgres" }, "data_config": { "schema": "public", "table": "elec_tiny", "features": [ { "name": "id", "type": "categorical", "cates": [ "2019-01-20", "2019-03-01", "2019-04-20", "2018-09-10", "2018-12-01", "2019-01-01", "2019-02-20", "2019-04-10", "2018-09-20", "2018-10-01", "2019-02-01", "2018-10-20", "2018-11-10", "2018-12-10", "2018-12-20", "2019-01-10", "2019-03-10", "2019-04-01", "2018-10-10", "2018-11-01", "2018-11-20", "2019-02-10", "2019-03-20", "2018-09-01" ] }, { "name": "stat_date", "type": "n", "cates": [] }, { "name": "meter_id", "type": "n", "cates": [] }, { "name": "energy_mean", "type": "n", "cates": [] }, { "name": "energy_max", "type": "n", "cates": [] }, { "name": "energy_min", "type": "n", "cates": [] }, { "name": "energy_sum", "type": "n", "cates": [] }, { "name": "energy_std", "type": "n", "cates": [] }, { "name": "power_mean", "type": "n", "cates": [] }, { "name": "power_max", "type": "n", "cates": [] }, { "name": "power_min", "type": "n", "cates": [] }, { "name": "power_std", "type": "n", "cates": [] }, { "name": "cur_mean", "type": "n", "cates": [] }, { "name": "cur_max", "type": "n", "cates": [] }, { "name": "cur_min", "type": "n", "cates": [] }, { "name": "cur_std", "type": "n", "cates": [] }, { "name": "vol_mean", "type": "n", "cates": [] }, { "name": "vol_max", "type": "n", "cates": [] }, { "name": "vol_min", "type": "n", "cates": [] }, { "name": "vol_std", "type": "n", "cates": [] }, { "name": "x", "type": "n", "cates": [] }, { "name": "avg_h8", "type": "n", "cates": [] }, { "name": "avg_t_8", "type": "n", "cates": [] }, { "name": "avg_ws_h", "type": "n", "cates": [] }, { "name": "avg_wd_h", "type": "n", "cates": [] }, { "name": "max_h8", "type": "n", "cates": [] }, { "name": "max_t_8", "type": "n", "cates": [] }, { "name": "max_ws_h", "type": "n", "cates": [] }, { "name": "min_h8", "type": "n", "cates": [] }, { "name": "min_t_8", "type": "n", "cates": [] }, { "name": "min_ws_h", "type": "n", "cates": [] }, { "name": "avg_irradiance", "type": "n", "cates": [] }, { "name": "max_irradiance", "type": "n", "cates": [] }, { "name": "min_irradiance", "type": "n", "cates": [] } ], "label": { "name": "load", "type": "n", "cates": [] } }, "task": { "type": 1, "algorithm": 1, "warm_start": false, "estimators": 3, "incre": 1, "batch": 1000 } }
class Solution: def decodeString(self, s: str) -> str: stack_mul = [] stack_char = [] mul = 0 strr = '' for char in s: if char.isdigit(): mul = 10*mul + int(char) elif char.isalpha(): strr += char elif char == '[': stack_mul.append(mul) stack_char.append(strr) mul = 0 strr = '' elif char == ']': m = stack_mul.pop() strr = stack_char.pop() + strr * m return strr # 遇到'[' 记录之前的strr 和 muli_num # 遇到']' 将目前的strr 与 之前的mul_num相乘 在加上之前的strr
# 这就是一个简单的节点了,相当的简单哈!!! def main(): print('Hi from python my_package.') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Editor: Zhao Xinlu School: BUPT Date: 2018-03-24 算法思想:双指针 """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ slow = head fast = head for i in range(n): fast = fast.next if fast == None: return head.next while fast.next != None: slow = slow.next fast = fast.next slow.next = slow.next.next return head
"""New retry v2 handlers. This package obsoletes the ibm_botocore/retryhandler.py module and contains new retry logic. """
""" 38. User-registered management commands The ``manage.py`` utility provides a number of useful commands for managing a Django project. If you want to add a utility command of your own, you can. The user-defined command ``dance`` is defined in the management/commands subdirectory of this test application. It is a simple command that responds with a printed message when invoked. For more details on how to define your own ``manage.py`` commands, look at the ``django.core.management.commands`` directory. This directory contains the definitions for the base Django ``manage.py`` commands. """ __test__ = {'API_TESTS': """ >>> from django.core import management # Invoke a simple user-defined command >>> management.call_command('dance', style="Jive") I don't feel like dancing Jive. # Invoke a command that doesn't exist >>> management.call_command('explode') Traceback (most recent call last): ... CommandError: Unknown command: 'explode' # Invoke a command with default option `style` >>> management.call_command('dance') I don't feel like dancing Rock'n'Roll. """}
# -*- coding: utf-8 -*- ''' Python内建的filter()函数用于过滤序列。 和map()类似,filter()也接收一个函数和一个序列。和map()不同的是, filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 ''' #在一个list中,删掉偶数,只保留奇数,可以这么写 def is_odd(n): return n%2==1 print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))) #回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数: def is_palindrome(n): s = str(n) return s == s[::-1] output = filter(lambda x:str(x)==str(x)[::-1], range(1, 1000)) print('1~1000:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('测试成功!') else: print('测试失败!')
{ "targets": [{ "target_name": "findGitRepos", "dependencies": [ "vendor/openpa/openpa.gyp:openpa" ], "sources": [ "cpp/src/FindGitRepos.cpp", "cpp/src/Queue.cpp" ], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")", "cpp/includes" ], "defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"], "conditions": [ ["OS=='win'", { "msvs_settings": { "VCCLCompilerTool": { "DisableSpecificWarnings": [ "4506", "4538", "4793" ] }, "VCLinkerTool": { "AdditionalOptions": [ "/ignore:4248" ] }, }, "defines": [ "OPA_HAVE_NT_INTRINSICS=1", "_opa_inline=__inline" ], "conditions": [ ["target_arch=='x64'", { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:X64", ], }, }, { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:x86", ], }, }], ] }], ["OS=='mac'", { "cflags+": ["-fvisibility=hidden"], "xcode_settings": { "GCC_SYMBOLS_PRIVATE_EXTERN": "YES" } }], ["OS=='mac' or OS=='linux'", { "defines": [ "OPA_HAVE_GCC_INTRINSIC_ATOMICS=1", "HAVE_STDDEF_H=1", "HAVE_STDLIB_H=1", "HAVE_UNISTD_H=1" ] }], ["target_arch=='x64' or target_arch=='arm64'", { "defines": [ "OPA_SIZEOF_VOID_P=8" ] }], ["target_arch=='ia32' or target_arch=='armv7'", { "defines": [ "OPA_SIZEOF_VOID_P=4" ] }] ], }] }
def define_actions( action ): """ Define the list of actions we are using. Args action: String with the passed action. Could be "all" Returns actions: List of strings of actions Raises ValueError if the action is not included in H3.6M """ actions = ["walking", "eating", "smoking", "discussion", "directions", "greeting", "phoning", "posing", "purchases", "sitting", "sittingdown", "takingphoto", "waiting", "walkingdog", "walkingtogether"] if action in actions: return [action] if action == "all": return actions if action == "all_srnn": return ["walking", "eating", "smoking", "discussion"] raise( ValueError, "Unrecognized action: %d" % action )
# Withdrawal Request amount must be non-negative non_negative_amount = \ """ ALTER TABLE ledger_withdrawalrequest DROP CONSTRAINT IF EXISTS non_negative_amount; ALTER TABLE ledger_withdrawalrequest ADD CONSTRAINT non_negative_amount CHECK ("amount" >= 0); ALTER TABLE ledger_withdrawalrequest VALIDATE CONSTRAINT non_negative_amount; """
# Using hash table # Time Complexity: O(n) class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: checkDict =dict() final = list() for i in nums1: if i not in checkDict: checkDict[i] = 1 else: checkDict[i] += 1 for i in nums2: if i in checkDict: if checkDict[i] > 0: final.append(i) checkDict[i] -= 1 return final # Time Complexity: O(m + n) def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: final = list() if len(nums1) < len(nums2): sl = nums1 ll = nums2 else: sl = nums2 ll = nums1 for i in range(len(sl)): new = sl[i] if new in ll: ll.remove(new) final.append(new) return final # Using sorted list # Time Complexity: O(n*logn) def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: i, j = 0, 0 intersection = list() nums1.sort() nums2.sort() # Handle empty array if len(nums1) == 0: return intersection while i < len(nums1) and j < len(nums2): if nums1[i] == nums2[j]: # Check for unique elements if nums1[i] != nums1[i-1] or i == 0: intersection.append(nums1[i]) i += 1 j += 1 elif nums1[i] < nums2[j]: i += 1 else: j += 1 return intersection
# using factorial, reduced the time complexity # of program from O(2^N) to O(N) def factorial(n): if n < 2: return 1 else: return n * factorial(n - 1) def computeCoefficient(col, row): return factorial(row) // (factorial(col) * factorial(row - col)) # Recusrive method to create the series def computePascal(col, row): if col == row or col == 0: return 1 else: return computeCoefficient(col, row) # Method to create the triangle for `N` row def printTriangle(num): for r in range(num): for c in range(r + 1): print(str(computePascal(c, r)), end=" ") print("\n") printTriangle(10) """ Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 """
#!/usr/bin/env python # -*- coding: utf-8 -*- class Names(): Chemical_Elemnts = ["Yb", "Pb", "Ca", "Ti", "Mo", "Sn", "Cd", "Ag", "La", "Cs", "W", "Sb", "Ta", "V", "Fe", "Bi", "Ce", "Nb", "Cu", "I", "B", "Te", "Al", "Zr", "Gd", "Na", "Ga", "Cl", "S", "Si", "O", "F", "Mn", "Ba", "K", "Zn", "N", "Li", "Ge", "Y", "Sr", "P", "Mg", "Er", "As"] ''' Chemical_Compounds = ['Ag2O', 'Al2O3', 'As2O3', 'As2O5', 'B2O3', 'BaO', 'Bi2O3', 'CaO', 'CdO', 'Ce2O3', 'CeO2', 'Cl', 'Cs2O', 'Cu2O', 'CuO', 'Er2O3', 'F', 'Fe2O3', 'Fe3O4', 'FeO', 'Ga2O3', 'Gd2O3', 'GeO', 'GeO2', 'I', 'K2O', 'La2O3', 'Li2O', 'MgO', 'Mn2O3', 'Mn2O7', 'Mn3O4', 'MnO', 'MnO2', 'Mo2O3', 'Mo2O5', 'MoO', 'MoO2', 'MoO3', 'N', 'N2O5', 'NO2', 'Na2O', 'Nb2O3', 'Nb2O5', 'P2O3', 'P2O5', 'Pb3O4', 'PbO', 'PbO2', 'SO2', 'SO3', 'Sb2O3', 'Sb2O5', 'SbO2', 'SiO', 'SiO2', 'Sn2O3', 'SnO', 'SnO2', 'SrO', 'Ta2O3', 'Ta2O5', 'TeO2', 'TeO3', 'Ti2O3', 'TiO', 'TiO2', 'V2O3', 'V2O5', 'VO2', 'VO6', 'WO3', 'Y2O3', 'Yb2O3', 'ZnO', 'ZrO2'] ''' Chemical_Compounds = ['Ag2O', 'Al2O3', 'As2O3', 'As2O5', 'B2O3', 'BaO', 'Bi2O3', 'CaO', 'CdO', 'Ce2O3', 'CeO2', 'Cl', 'Cs2O', 'Cu2O', 'CuO', 'Er2O3', 'F', 'Fe2O3', 'Fe3O4', 'FeO', 'Ga2O3', 'Gd2O3', 'GeO2', 'I', 'K2O', 'La2O3', 'Li2O', 'MgO', 'Mn2O3', 'Mn2O7', 'Mn3O4', 'MnO', 'MnO2', 'Mo2O3', 'Mo2O5', 'MoO', 'MoO2', 'MoO3', 'N', 'N2O5', 'NO2', 'Na2O', 'Nb2O3', 'Nb2O5', 'P2O3', 'P2O5', 'Pb3O4', 'PbO', 'PbO2', 'SO2', 'SO3', 'Sb2O3', 'Sb2O5', 'SbO2', 'SiO2', 'Sn2O3', 'SnO', 'SnO2', 'SrO', 'Ta2O3', 'Ta2O5', 'TeO3', 'Ti2O3', 'TiO', 'TiO2', 'V2O3', 'V2O5', 'VO2', 'VO6', 'WO3', 'Y2O3', 'Yb2O3', 'ZnO', 'ZrO2']
# Build a Boolean mask to filter out all the 'LAX' departure flights: mask mask = df['Destination Airport'] == 'LAX' # Use the mask to subset the data: la la = df[mask] # Combine two columns of data to create a datetime series: times_tz_none times_tz_none = pd.to_datetime( la['Date (MM/DD/YYYY)'] + ' ' + la['Wheels-off Time'] ) # Localize the time to US/Central: times_tz_central times_tz_central = times_tz_none.dt.tz_localize('US/Central') # Convert the datetimes from US/Central to US/Pacific times_tz_pacific = times_tz_central.dt.tz_convert('US/Pacific')
""" Write a Python program to find the second most repeated word in a given string. """ def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 counts_x = sorted(counts.items(), key=lambda kv:kv) return counts_x[-2] print(word_count("both of these by issues fixed by postponding of of annotations."))
# -*- coding: utf-8 -*- """ Created on Sat Jan 19 10:52:04 2019 @author: Nihar """ marks=int(input("Enter Marks: ")) if marks >=70: print("Congrats!Distinction for you") elif 70 > marks >= 60: print("Well done! First Class !!") elif 60 > marks >= 40: print("You got Second Class") else: print("Sorry! You failed!")
''' Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. ''' class Solution(object): def findNumberOfLIS(self, nums): length = [1]*len(nums) count = [1]*len(nums) result = 0 for end, num in enumerate(nums): for start in range(end): if num > nums[start]: if length[start] >= length[end]: length[end] = 1+length[start] count[end] = count[start] elif length[start] + 1 == length[end]: count[end] += count[start] for index, max_subs in enumerate(count): if length[index] == max(length): result += max_subs return result
# python3 def solve(n, v): #if sum(v) % 3 != 0: # return False res = [] values = [] s = sum(v)//3 for i in range(2**n): bit = [0 for i in range(n)] k = i p = n-1 while k!=0: bit[p] = (k%2) k = k//2 p -= 1 #print(bit) val = [a*b for a, b in zip(v, bit)] #print(val) if sum(val) == s: res.append(bit) values.append(i) #print(res) #print(values) if len(res)<3: return False for i in range(len(values)-2): for j in range(i+1, len(values)-1): for k in range(i+2, len(values)): a = values[i] b = values[j] c = values[k] if a^b^c == (2**n-1): return True return False if __name__ == '__main__': n = int(input()) v = [int(i) for i in input().split()] if solve(n, v): print("1") else: print("0")
# create string and dictionary lines = "" occurrences = {} # prompt for lines line = input("Enter line: ") while line: lines += line + " " line = input("Enter line: ") # iterate through each color and store count for word in set(lines.split()): occurrences[word] = lines.split().count(word) # print results for word in sorted(occurrences): print(word, occurrences[word])
""" Demonstrates swapping the values of two variables """ number1 = 65 #Declares a variable named number1 and assigns it the value 65 number2 = 27 #Declares a variable named number2 and assigns it the value 27 temp_number = number1 #Copies the reference of number1 to temp_number number1 = number2 #Copies the reference of number2 to number1 number2 = temp_number #Copies the reference of temp_number to number2 print(number1) #Prints the value referenced by number1 print(number2) #Prints the value referenced by number2
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root is None: return '[]' queue = [root] index = 0 while index < len(queue): node = queue[index] if node is not None: queue.append(node.left) queue.append(node.right) index += 1 while (len(queue) > 0 and queue[-1] is None): queue.pop() nodes = ['#' if n is None else str(n.val) for n in queue] return '[%s]' % (','.join(nodes)) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '[]': return None nodes = data[1: -1].split(',') root = TreeNode(int(nodes[0])) queue = [root] isLeft = True for i in range(1, len(nodes)): if nodes[i] != '#': child = TreeNode(int(nodes[i])) if isLeft: queue[0].left = child else: queue[0].right = child queue.append(child) if not isLeft: queue.pop(0) isLeft = not isLeft return root # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
num = int(input('Digite um número: ')) total = 0 for c in range(1, num + 1): if num % c == 0: total += 1 print('{}'.format(c), end=' ') print('\nO número {} foi divisivel {} vezes'.format(num, total)) if total == 2: print('É número {} é primo'.format(num)) else: print('É número {} é composto'.format(num))
# python3 n, m = map(int, input().split()) clauses = [ list(map(int, input().split())) for i in range(m) ] # This solution tries all possible 2^n variable assignments. # It is too slow to pass the problem. # Implement a more efficient algorithm here. def isSatisfiable(): for mask in range(1<<n): result = [ (mask >> i) & 1 for i in range(n) ] formulaIsSatisfied = True for clause in clauses: clauseIsSatisfied = False if result[abs(clause[0]) - 1] == (clause[0] < 0): clauseIsSatisfied = True if result[abs(clause[1]) - 1] == (clause[1] < 0): clauseIsSatisfied = True if not clauseIsSatisfied: formulaIsSatisfied = False break if formulaIsSatisfied: return result return None result = isSatisfiable() if result is None: print("UNSATISFIABLE") else: print("SATISFIABLE"); print(" ".join(str(-i-1 if result[i] else i+1) for i in range(n)))
""" sentence span mapping to special concepts in amr like name,date-entity,etc. """ class Span(object): def __init__(self,start,end,words,entity_tag): self.start = start self.end = end self.entity_tag = entity_tag self.words = words def set_entity_tag(self,entity_tag): self.entity_tag = entity_tag def __str__(self): return '%s: start: %s, end: %s , tag:%s'%(self.__class__.__name__,self.start,self.end,self.entity_tag) def __repr__(self): return '%s: start: %s, end: %s , tag:%s'%(self.__class__.__name__,self.start,self.end,self.entity_tag) def __eq__(self,other): return other.start == self.start and other.end == self.end def contains(self,other_span): if other_span.start >= self.start and other_span.end <= self.end and not (other_span.start == self.start and other_span.end == self.end): return True else: return False
class FlPosition: def __init__(self, position_data, column_labels, timestamps, conversion): self.position_data = position_data self.column_labels = column_labels self.timestamps = timestamps self.conversion = conversion
class Recipe: def __init__(self, name, ingredients, yt_link): self.name = name self.ingredients = ingredients self.yt_link = yt_link self.similarity = 0 self.leftChild = None self.rightChild = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, recipe): if not self.root: self.root = recipe else: self.insertNode(recipe, self.root) def insertNode(self, recipe, node): if recipe.similarity < node.similarity: if node.leftChild: self.insertNode(recipe, node.leftChild) else: node.leftChild = recipe else: if node.rightChild: self.insertNode(recipe, node.rightChild) else: node.rightChild = recipe
#!/usr/bin/env python3 """ Poisson distribution """ class Poisson: """ Class to represent a Poisson distribution """ e = 2.7182818285 def __init__(self, data=None, lambtha=1.): """ Poisson Constructor data is a list of the data to be used to estimate the distribution lambtha is the expected number of occurences in a given time frame """ if data is None: if lambtha <= 0: raise ValueError('lambtha must be a positive value') self.lambtha = float(lambtha) else: if type(data) is not list: raise TypeError('data must be a list') if len(data) < 2: raise ValueError('data must contain multiple values') self.lambtha = float(sum(data) / len(data)) @staticmethod def factorial(n): """ Calculates the factorial of n """ fn = 1 for i in range(2, n + 1): fn *= i return fn def pmf(self, k): """ Probability mass function Calculates the value of the PMF for a given number of “successes” k is the number of “successes” """ k = int(k) if k < 0: return 0 return Poisson.e ** -self.lambtha * self.lambtha ** k \ / Poisson.factorial(k) def cdf(self, k): """ Cumulative distribution function Calculates the value of the CDF for a given number of “successes” k is the number of “successes” """ k = int(k) if k < 0: return 0 return Poisson.e ** -self.lambtha * \ sum([(self.lambtha ** i) / Poisson.factorial(i) for i in range(k + 1)])
######################################################################## # Useful classes for implementing quantum heterostructures behavior # # author: Thiago Melo # # creation: 2018-11-09 # # update: 2018-11-09 # class Device(object): def __init__(self): pass
def deco(func): def temp(): print("-"*60) func() print("-"*60) return temp @deco def print_h1(): print("body") def main(): print_h1() if __name__ == "__main__": main()
# linear search on sorted list def search(L, e): for i in range(len(L)): if L[i] == e: return True if L[i] > e: # sorted return False return False # O(n) for the loop and O(1) for the lookup to test if e == L[i] # overall complexity is O(n) where n is len(L)
def CheckPypi(auth, project): projectInfo = auth.GetJson("https://pypi.org/pypi/" + project + "/json") return projectInfo["info"]["version"]
#!/usr/bin/env python3 IMG_FOLDER = '/home/tho/.scripts/ws_imgs' WS_CONFIG = [ { #'name': '', 'img': ['firefox.png', 'firefox.png'], 'num': 1, 'key': 1, 'static': False }, { #'name': '2', 'img': ['moon.png', 'moon.png'], 'num': 2, 'key': 2, 'static': True }, { #'name': '3', 'img': ['water.png', 'water.png'], 'num': 3, 'key': 3, 'static': True }, { #'name': '4', 'img': ['tiger.png', 'tiger.png'], 'num': 4, 'key': 4, 'static': True }, { #'name': '5', 'img': ['satellite.png', 'satellite.png'], 'num': 5, 'key': 5, 'static': True }, { #'name': '6', 'img': ['ufo.png', 'ufo.png'], 'num': 6, 'key': '6', 'static': True }, { #'name': '7', 'img': ['bear.png', 'bear.png'], 'num': 7, 'key': '7', 'static': True }, { #'name': '8', 'img': ['horse.png', 'horse.png'], 'num': 8, 'key': '8', 'static': True }, { #'name': '', 'img': ['coding.png', 'coding.png'], 'num': 11, 'key': 'i', 'static': True }, { 'name': '', 'num': 12, 'key': 'm', 'static': True } ]
# Exercise 3: # # In this exercise we will create a program that identifies whether someone can # enter a super secret club. # Below are the people that are allowed in the club. # If your name is Bill Gates, Steve Jobs or Jesus, you should be allowed in the # club. # If your name is not one of the above, but your name is Maria and you are less # than 30 years old, then you should be allowed in the club. # If you don't fulfill the conditions above, but you are older than 100 years # ol,d you should also be allowed. # If none of the conditions are met, you shouldn't be allowed in the club. print("What's your name?") name = raw_input() # The raw_input() function allows you to get user input, # don't worry about functions now. print("What's your age?") age = input() if name == "Bill Gates" or name == "Steve Jobs" or name == "Jesus": # print something saying that the guest was allowed in the club # don't forget indentation. print("You are welcomed in our fancy club!") elif name == 'Maria' and age < 30: print("You are welcomed in our fancy club!") elif age > 100: print("You are welcomed in our fancy club!") else: print("Get out! This club is only for special people!") # print something saying that the guest was not allowed in the club # # Test out your program and see if it works as it is supposed to.
N, K = [int(a) for a in input().split()] h = [] for _ in range(N): h.append(int(input())) sortedh = sorted(h) min_ = 1e9 for i in range(N-K+1): diff = sortedh[i+K-1] - sortedh[i] min_ = min(min_, diff) print(min_)
# slow version dp class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ sLength, pLength = len(s), len(p) matrix = [[False] * (pLength+1) for i in range(sLength+1)] matrix[0][0] = True for i in range(sLength+1): for j in range(1, pLength+1): matrix[i][j] = matrix[i][j - 2] or (i > 0 and (s[i - 1] == p[j - 2] or p[j - 2] == '.') and matrix[i - 1][j])\ if p[j - 1] == '*' else i > 0 and matrix[i - 1][j - 1] and (s[i - 1] == p[j - 1] or p[j - 1] == '.') return matrix[-1][-1]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by AKM_FAN@163.com on 2017/11/6 if __name__ == '__main__': pass
# -*- coding: utf-8 -*- """ Created on Tue May 19 08:27:42 2020 @author: Shivadhar SIngh """ def histogram(seq): count = dict() for elem in seq: if elem not in count: count[elem] = 1 else: count[elem] += 1 return count
"""Errors raised by mailmerge.""" class MailmergeError(Exception): """Top level exception raised by mailmerge functions.""" class MailmergeRateLimitError(MailmergeError): """Reuse to send message because rate limit exceeded."""
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Constants for fever data.""" VERIFIABLE = 'VERIFIABLE' NOT_VERIFIABLE = 'NOT VERIFIABLE' # Classes used for claim classification and labeling which evidence # support/refute the claim NOT_ENOUGH_INFO = 'NOT ENOUGH INFO' REFUTES = 'REFUTES' SUPPORTS = 'SUPPORTS' FEVER_CLASSES = [REFUTES, SUPPORTS, NOT_ENOUGH_INFO] # Classes used for scoring candidate evidence relevance MATCHING = 'MATCHING' NOT_MATCHING = 'NOT_MATCHING' EVIDENCE_MATCHING_CLASSES = [NOT_MATCHING, MATCHING] UKP_WIKI = 'ukp_wiki' UKP_PRED = 'ukp_pred' UKP_TYPES = [UKP_PRED, UKP_WIKI] DRQA = 'drqa' LUCENE = 'lucene' DOC_TYPES = [UKP_WIKI, UKP_PRED, DRQA, LUCENE]
Dakota = {"Tipo": "Perro", "Dueño": "Miguel", "Descripcion": "Esta gorda y bien bonita"} Momo = {"Tipo": "Lemur", "Dueño": "Aang", "Descripcion": "No estoy seguro que sea un lemur, pero vuela"} Rufus = {"Tipo": "Nutria", "Dueño": "Ron", "Descripcion": "Es pequeño, feo y muestra inteligencia"} Chimuelo = {"Tipo": "Dragon", "Dueño": "Hipo", "Descripcion": "Dragon pequeño, color negro que es bien chido"} Mascotas = [Dakota,Momo,Rufus,Chimuelo] for i in range(0,len(Mascotas)): print(Mascotas[i])
# !/usr/bin/python # -*- coding: utf-8 -*- class Friends(object): def __init__(self, connections): super(Friends, self).__init__() self._data = {} self._add_connections(connections) def add(self, connection): is_exists = self.is_exists(connection) self._add_connection(connection) return (not is_exists) def remove(self, connection): is_exists = self.is_exists(connection) if (not is_exists): return False self._remove_connection(connection) return True def names(self): return self._data.keys() def connected(self, name): if (name not in self._data): return set() return self._data[name] def is_exists(self, connection): copy = connection.copy() first, second = copy.pop(), copy.pop() return (first in self._data and second in self._data[first]) def _add_connection(self, connection): copy = connection.copy() first, second = copy.pop(), copy.pop() add = lambda i, x: self._data[i].add(x) if i in self._data else self._data.update({i: {x}}) add(first, second) add(second, first) def _add_connections(self, connections): for connection in connections: self._add_connection(connection) def _remove_connection(self, connection): copy = connection.copy() first, second = copy.pop(), copy.pop() removeValue = lambda i, x: self._data[i].remove(x) if True else None removeKey = lambda i: self._data.pop(i) if not len(self._data[i]) else None removeValue(first, second) removeValue(second, first) removeKey(first) removeKey(second) if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing letter_friends = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) digit_friends = Friends([{"1", "2"}, {"3", "1"}]) assert letter_friends.add({"c", "d"}) is True, "Add" assert letter_friends.add({"c", "d"}) is False, "Add again" assert letter_friends.remove({"c", "d"}) is True, "Remove" assert digit_friends.remove({"c", "d"}) is False, "Remove non exists" assert letter_friends.names() == {"a", "b", "c"}, "Names" assert letter_friends.connected("d") == set(), "Non connected name" assert letter_friends.connected("a") == {"b", "c"}, "Connected name"
def table_service(*args): text, client, current_channel = args if text.lower().startswith("tables"): number = int(text.split()[-1]) result = "" for i in range(1, 11): result += f"{number} X {i} = {number*i}\n" client.chat_postMessage(channel=current_channel, text=result)
class Parameters: def __init__(self, **kwargs): self.__dict__.update(kwargs) def info(self): print("The parameters, and data-type are: ") for key,values in self.__dict__.items(): print("{} = {}, {}\n".format(key, values, type(values)))
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) max_val = max(arr) while(max_val in arr): arr.remove(max_val) print(max(arr))
CHECKSUM_TAG = 'CHECKSUM_TAG' AVSCAN_TAG = 'AVSCAN_TAG' MAILER_TAG = 'MAILER_TAG' UNPACK_TAG = 'UNPACK_TAG' ARKADE5_TAG = 'ARKADE5_TAG' ARTIFACT_WRITER_TAG = 'ARTIFACT_WRITER_TAG' class ContainerTagParams: """ Parameter class containing dictionaries of {parameter names: image tags} for containers used during argo workflows """ def __init__(self, checksum: str, avscan: str, mailer: str, unpack: str, arkade5: str, artifact_writer_tag: str): self.checksum = {CHECKSUM_TAG: checksum} self.avscan = {AVSCAN_TAG: avscan} self.mailer = {MAILER_TAG: mailer} self.unpack = {UNPACK_TAG: unpack} self.arkade5 = {ARKADE5_TAG: arkade5} self.artifact_writer_tag = {ARTIFACT_WRITER_TAG: artifact_writer_tag} def __eq__(self, other): if isinstance(other, ContainerTagParams): return self.checksum == other.checksum and \ self.avscan == other.avscan and \ self.mailer == other.mailer and \ self.unpack == other.unpack and \ self.arkade5 == other.arkade5 and \ self.artifact_writer_tag == other.artifact_writer_tag
def miFuncion(): print("Mi primera función") miFuncion() def imprimirDato(dato): print(dato) imprimirDato("a") def imprimirDatos(*datos): print(datos) imprimirDatos("Uno", "Dos", "Tres") def nombreCompleto(apellido, nombre): print(nombre, apellido) nombreCompleto(nombre="Emmanuelle", apellido="Laguna") def imprmirNombreCompleto(**nombreCompleto): print(nombreCompleto["nombre"], nombreCompleto["apellido"]) imprmirNombreCompleto(nombre="Emmanuelle", apellido="Laguna") def imprmirArgumento(argumento="Sin datos de entrada"): print(argumento) imprmirArgumento() imprmirArgumento("Con datos de entrada")
def solution(A): curSlice = float('-inf') maxSlice = float('-inf') for num in A: curSlice = max(num, curSlice+num) maxSlice = max(curSlice, maxSlice) return maxSlice if __name__ == '__main__': print(solution([3,2,-6,4,0])) print(solution([-10]))
# -*- coding: utf-8 -*- """ File Name: countDigitOne.py Author : jynnezhang Date: 2020/4/29 7:38 下午 Description: 从1到n,所有数字含有1的个数 https://leetcode-cn.com/problems/number-of-digit-one/ """ class Solution: def countDigitOne(self, n: int) -> int: number = 0 for i in range(1, n+1): number += number_of_1(i) return number def countDigitOne2(self, n: int) -> int: if n <= 0: return 0 num_s = str(n) high = int(num_s[0]) Pow = 10 ** (len(num_s) - 1) last = n - high * Pow if high == 1: return self.countDigitOne2(Pow - 1) + self.countDigitOne2(last) + last + 1 else: return Pow + high * self.countDigitOne2(Pow - 1) + self.countDigitOne2(last) def number_of_1(n): """ n这个数字中出现1的次数 :param n: 输入的整数 """ num = 0 while n > 0: # 获得余数,若余数为1,则次数加1 if n % 10 == 1: num += 1 n = n // 10 return num print(Solution().countDigitOne2(99))
class Solution: def XXX(self, head: ListNode) -> ListNode: o = head p = None while head is not None: if p is not None and head.val == p.val: p.next = head.next else: p = head head = head.next return o
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ living """ __version__ = '4.0' content = { 'boymechanic_ankeiler': ['Having fun <#,odd_action#> while <#odd_action#>.'], 'odd_action': [ '<#odd_verbs_gerund#> <#article,odd_descriptor#> <#odd_noun#>', '<#odd_verbs_gerund#> <#article,odd_noun#> with some <#odd_material#>', '<#odd_verbs_gerund#> <#article,odd_noun#> with <#article,odd_noun#> and some <#odd_material#>', '<#odd_verbs_gerund#> <#article,odd_noun#> without <#odd_moreverbs_gerund#> it', ], 'odd_adj': [ 'embossed', 'atmospheric', 'electric', 'broken', 'photovoltaic', 'stained', 'tarnished', ], 'odd_descriptor': [ 'homemade', 'homemade', 'homemade', 'homemade', 'homemade', 'digital', 'live', 'dead', '<#odd_adj#>', ], 'odd_material': [ 'glass', 'wood', 'flatiron', 'felt', 'tin', 'wool', 'cotton', 'leather', 'string', ], 'odd_moreverbs_gerund': [ 'relieving ', 'inflating ', 'closing', 'baking', 'reducing', 'advertising', 'fish scaling', 'mixing', 'preventing', ], 'odd_noun': [ 'acid', 'siphon', 'alarm', 'record box', 'combination lathe', 'applications', 'toy balloon', 'air pressure', 'sleepwalker', 'fuse wire', 'guide', 'principle', 'idea', 'model boat', 'amperage', 'hammer', 'small wound', 'bread', 'ball-clasp purse', 'broom', 'camera', 'radio', 'box', 'container', 'bottle', 'sulphuric acid', 'itch', 'limb', 'calcium deposit', 'stain', 'brush', 'splinter', 'organ', ], 'odd_thing': [ '<#odd_descriptor#> <#odd_noun#> for <#article,odd_adj#> <#odd_noun#>', '<#odd_verbs_gerund#> <#odd_noun#> for <#odd_descriptor#> <#odd_noun#>', '<#odd_verbs_gerund#> <#odd_noun#> with <#odd_descriptor#> <#odd_noun#>', '<#odd_verbs_gerund#> <#odd_noun#> with <#article,odd_descriptor#> <#odd_noun#>', '<#article, odd_adj#> <#odd_noun#>, <#odd_verbs_gerund#>', ], 'odd_topics': [ 'ways to keep home accounts', 'acid siphon', 'how to make advertising lantern slides', 'model boat with aerial propeller', 'aeroplane kite', 'air pencil to make embossed letters', 'relieving air pressure when closing record boxes', 'alarm for sleepwalker', 'amateur mechanic’s combination lathe', 'reducing amperage of fuse wire', 'applications for small wounds', 'atmospheric thermo engine', 'baking bread in hot sand', 'repairing a broken ball-clasp purse', 'inflating toy balloons', 'electric-light bulb as barometer', 'removing basketball from closed-bottom receptacle', 'preserving dry batteries', 'bearings for model work', 'how to make a continuously ringing bell', 'adjustable bench stop', 'mechanical bicycle horn', 'lantern slide binding machine', 'removing black deposits on bathtubs', 'ruling blank books', 'automatic blowpipe', 'boats-an oar holder', 'bobsled, inexpensive', 'boiling cracked eggs', 'ear repair on bucket', 'Mile-O-View camera', 'camp stoves', 'ro repair leak in canoe', 'one-piece casting rod', 'cherry-pitter', 'electric chime clock', 'how to clean jewelry', 'electric chime clock', 'reading date of worn coin', 'callar fasteners', 'comb cleaner', 'cooking food in paper', 'removing cork from bottle', 'how to make a costumer', 'cover for bottle', 'croquet playing at night', 'homemade dibble', 'exerciser for chained dog', 'dowel turning tool', 'paper drinking cup', 'homemade electric bed warmer', 'electric flatiron', 'electric light mystery', 'electric time light', 'electrical apparatus', 'electrically operated doorknob', 'how to make falling blocks', 'mending break in felt', 'laborotry force filter', 'attractor for fish. game', 'electric fishing signal', 'homemade floor polisher', 'frosting glass', 'fountain pen, homemade', 'furniture- jarndiniere pedestal', 'D’Arsonval galvanometer', 'game played on ice', 'centering gauge', 'grape arbor built of poles', 'kraut and root grinder', 'polishing gunstocks', ], 'odd_verb': [ 'repair', 'fix', 'open', 'close', 'clean', 'use', 'make', 'inflate', 'bake', ], 'odd_verbs_gerund': [ 'repairing', 'fixing', 'removing', 'cleaning', 'using', 'making', '<#odd_moreverbs_gerund#>', ], }
def taxicab_distance(a, b): """ Returns the Manhattan distance of the given points """ n = len(a) d = 0 for i in range(n): d += abs(a[i] - b[i]) return d PERIOD = 2 # the period of the sequence def sequ(): """ Generates the sequence corresponding to the number of steps to take at each turn when traversing memory """ step = 0 val = 1 while True: if step == PERIOD: step = 0 val += 1 yield val step += 1 # movements def right(pos): """ Move right """ return (pos[0]+1, pos[1]) def left(pos): """ Move left """ return (pos[0]-1, pos[1]) def up(pos): """ Move up """ return (pos[0], pos[1]+1) def down(pos): """ Move down """ return (pos[0], pos[1]-1) PORT_NUM = 1 # address of sole I/O port def coordinates(n): """ Returns the co-ordinates of the given address in memory """ if n == PORT_NUM: # orient ourselves w.r.t. to I/O port return (0, 0) pos = (0, 0) seq = sequ() diff = n - 1 while diff > 0: if diff == 0: # are we there yet? return pos # right branch branch_length = next(seq) for i in range(branch_length): if diff == 0: # are we there yet? return pos pos = right(pos) diff -= 1 # decrement difference # up branch branch_length = next(seq) for i in range(branch_length): if diff == 0: # are we there yet? return pos pos = up(pos) diff -= 1 # decrement difference # left branch branch_length = next(seq) for i in range(branch_length): if diff == 0: # are we there yet? return pos pos = left(pos) diff -= 1 # decrement difference # down branch branch_length = next(seq) for i in range(branch_length): if diff == 0: # are we there yet? return pos pos = down(pos) diff -= 1 # decrement difference return pos def distance(n): """ Returns the Manhattan distance from the I/O port to the given address """ port_loc = coordinates(PORT_NUM) n_loc = coordinates(n) return taxicab_distance(port_loc, n_loc) def num_steps(n): """ Returns the number of steps required to get from the given address to the I/O port """ if n == PORT_NUM: return 0 pos = coordinates(n) return distance(n) """ # tests print(num_steps(1)) # 0 print(num_steps(12)) # 3 print(num_steps(23)) # 2 print(num_steps(1024)) # 31 """ INPUT_FILE_PATH = "input.txt" def main(): with open(INPUT_FILE_PATH) as f: n = int(f.readline()) print(num_steps(n))
#!/usr/bin/env python3 ######################################################################################################################## ##### INFORMATION ###################################################################################################### ### @PROJECT_NAME: SPLAT: Speech Processing and Linguistic Analysis Tool ### ### @VERSION_NUMBER: ### ### @PROJECT_SITE: github.com/meyersbs/SPLAT ### ### @AUTHOR_NAME: Benjamin S. Meyers ### ### @CONTACT_EMAIL: ben@splat-library.org ### ### @LICENSE_TYPE: MIT ### ######################################################################################################################## ######################################################################################################################## """ This package contains the following files: [01] POSTagger.py Provides the functionality to tokenize the given input with punctuation as separate tokens, and then does a dictionary lookup to determine the part-of-speech for each token. """
# coding=utf-8 class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ # DP # f[x][y] = true 表示 s[x:y+1]为回文 # 初始化 left = 0 right = 1 length = len(s) f = [[False for j in range(length)] for i in range(length)] for i in range(length): # 单个字母是回文 f[i][i] = True # 两个字母相同是回文,注意两个字母的回文答案 if i < length - 1: if s[i] == s[i+1]: f[i][i+1] = True left = i right = i + 2 # j表示回文长度 for j in range(3, length+1): # i表示回文起始坐标,则截止坐标为i+j-1 for i in range(length-j+1): # f[x][y]为回文的需求是s[x]==s[y]并且f[x+1][y-1]=True if f[i + 1][i+j-1-1] and s[i] == s[i+j-1]: f[i][i+j-1] = True # 该DP后面的总是大于前面的,所以每次有答案就覆盖 left = i right = i + j return s[left:right] # test instance = Solution() print(instance.longestPalindrome("babad"))
def start(): return def stop(): return def apply_command(self, c, e, command, arguments): pass def on_welcome(self, c, e): pass def on_invite(self, c, e): pass def on_join(self, c, e): pass def on_namreply(self, c, e): pass def on_pubmsg(self, c, e): pass def on_privmsg(self, c, e): pass
# Code Challenge 13 open_list = ["[", "{", "("] close_list = ["]", "}", ")"] def validate_brackets(str): stack=[] for i in str: if i in open_list: stack.append(i) elif i in close_list: x = close_list.index(i) if ((len(stack) > 0) and (open_list[x] == stack[len(stack) - 1])): stack.pop() else: return False if len(stack) == 0: return True else: return False
tail = input() body = input() head = input() meerkat = [tail, body, head] meerkat.reverse() print(meerkat)
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. a<995 b<996 c<997 They tell us there is only one, so we only need to test for existence, not uniqueness. We have 2 equations: a2+b2=c2 a+b+c=1000 """ # Lets test all three cases for all numbers until we get the answer. # The problem told us it was unique, so we can exit. for a in range(1,1000): for b in range(1,1000): for c in range(1,1000): if a<b<c and a+b+c==1000 and a**2+b**2==c**2: print("answer:", a*b*c) exit(0)
num = int(input()) for i in range(num): s = input() t = input() p = input()
graus = [0,10,20,40,100] for T in graus: print("A temperatura é: ",T) print("a Lista de temperaturas tem ", len(graus), 'elementos')
def peopleneeded(Smax, S): needed = 0 for s in range(Smax+1): if sum(S[:s+1])<s+1: needed += s+1-sum(S[:s+1]) S[s] += s+1-sum(S[:s+1]) return needed def get_output(instance): inputdata = open(instance + ".in", 'r') output = open(instance+ ".out", 'w') T = int(inputdata.readline()) for t in range(T): Smax, S = inputdata.readline().split() Smax = int(Smax) S = [int(i) for i in list(S)] output.write('Case #' + str(t+1) +': ' + str(peopleneeded(Smax, S)) + "\n") return None
class Solution: def isValidSerialization(self, preorder: str) -> bool: degree = 1 # outDegree (children) - inDegree (parent) for node in preorder.split(','): degree -= 1 if degree < 0: return False if node != '#': degree += 2 return degree == 0
""" Tests as were previously formatted. Leaving here in case I want to revert to more disparate testing. """ def test_vehicle_info(client): mock_file = 'mock_vehicleinfo.json' output_file = 'output_vehicleinfo.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get(url_for('endpoints.get_vehicle_info', id=ID_GOOD)) assert response.json == correct_output def test_security_info(client): mock_file = 'mock_securityinfo.json' output_file = 'output_securityinfo.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = response = client.get('/vehicles/' + str(ID_GOOD) + '/doors') assert response.json == correct_output def test_fuel(client): mock_file = 'mock_fuelbattery.json' output_file = 'output_fuel.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get('/vehicles/' + str(ID_GOOD) + '/fuel') assert response.json == correct_output def test_battery(client): mock_file = 'mock_fuelbattery.json' output_file = 'output_battery.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.get('/vehicles/' + str(ID_GOOD) + '/battery', ) assert response.json == correct_output def test_start_stop(client): mock_file = 'mock_engine.json' output_file = 'output_engine.json' mock_response, correct_output = mocktest_setup(mock_file, output_file) headers = { 'Content-Type': 'application/json' } parameters = { "action": "START" } with patch('server.requests.post') as mock_get: mock_get.return_value.json.return_value = mock_response response = client.post('/vehicles/' + str(ID_GOOD) + '/engine', headers=headers, data=json.dumps(parameters)) assert response.json == correct_output
''' 字符大小写排序 中文English 给定一个只包含字母的字符串,按照先小写字母后大写字母的顺序进行排序。 一招partiton 走天下 '''
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # 该请求账户未通过资格审计。 ACCOUNTQUALIFICATIONRESTRICTIONS = 'AccountQualificationRestrictions' # CVM接口调用失败。 CALLCVMERROR = 'CallCvmError' # 未生成伸缩活动。 FAILEDOPERATION_NOACTIVITYTOGENERATE = 'FailedOperation.NoActivityToGenerate' # 内部错误。 INTERNALERROR = 'InternalError' # Cmq 接口调用失败。 INTERNALERROR_CALLCMQERROR = 'InternalError.CallCmqError' # 内部接口调用失败。 INTERNALERROR_CALLERROR = 'InternalError.CallError' # LB 接口调用失败。 INTERNALERROR_CALLLBERROR = 'InternalError.CallLbError' # Monitor接口调用失败。 INTERNALERROR_CALLMONITORERROR = 'InternalError.CallMonitorError' # 通知服务接口调用失败。 INTERNALERROR_CALLNOTIFICATIONERROR = 'InternalError.CallNotificationError' # STS 接口调用失败。 INTERNALERROR_CALLSTSERROR = 'InternalError.CallStsError' # Tag 接口调用失败。 INTERNALERROR_CALLTAGERROR = 'InternalError.CallTagError' # Tvpc 接口调用失败。 INTERNALERROR_CALLTVPCERROR = 'InternalError.CallTvpcError' # VPC接口调用失败。 INTERNALERROR_CALLVPCERROR = 'InternalError.CallVpcError' # 调用其他服务异常。 INTERNALERROR_CALLEEERROR = 'InternalError.CalleeError' # 内部请求错误。 INTERNALERROR_REQUESTERROR = 'InternalError.RequestError' # 未找到该镜像。 INVALIDIMAGEID_NOTFOUND = 'InvalidImageId.NotFound' # 无效的启动配置。 INVALIDLAUNCHCONFIGURATION = 'InvalidLaunchConfiguration' # 启动配置ID无效。 INVALIDLAUNCHCONFIGURATIONID = 'InvalidLaunchConfigurationId' # 参数错误。 INVALIDPARAMETER = 'InvalidParameter' # 参数冲突,指定的多个参数冲突,不能同时存在。 INVALIDPARAMETER_CONFLICT = 'InvalidParameter.Conflict' # 主机名参数不适用于该镜像。 INVALIDPARAMETER_HOSTNAMEUNAVAILABLE = 'InvalidParameter.HostNameUnavailable' # 在特定场景下的不合法参数。 INVALIDPARAMETER_INSCENARIO = 'InvalidParameter.InScenario' # 无效的参数组合。 INVALIDPARAMETER_INVALIDCOMBINATION = 'InvalidParameter.InvalidCombination' # 指定的负载均衡器在当前伸缩组中没有找到。 INVALIDPARAMETER_LOADBALANCERNOTINAUTOSCALINGGROUP = 'InvalidParameter.LoadBalancerNotInAutoScalingGroup' # 参数缺失,两种参数之中必须指定其中一个。 INVALIDPARAMETER_MUSTONEPARAMETER = 'InvalidParameter.MustOneParameter' # 部分参数存在互斥应该删掉。 INVALIDPARAMETER_PARAMETERMUSTBEDELETED = 'InvalidParameter.ParameterMustBeDeleted' # 指定的两个参数冲突,不能同时存在。 INVALIDPARAMETERCONFLICT = 'InvalidParameterConflict' # 参数取值错误。 INVALIDPARAMETERVALUE = 'InvalidParameterValue' # 指定的基础容量过大,需小于等于最大实例数。 INVALIDPARAMETERVALUE_BASECAPACITYTOOLARGE = 'InvalidParameterValue.BaseCapacityTooLarge' # 在应当指定传统型负载均衡器的参数中,错误地指定了一个非传统型的负载均衡器。 INVALIDPARAMETERVALUE_CLASSICLB = 'InvalidParameterValue.ClassicLb' # 通知接收端类型冲突。 INVALIDPARAMETERVALUE_CONFLICTNOTIFICATIONTARGET = 'InvalidParameterValue.ConflictNotificationTarget' # 定时任务指定的Cron表达式无效。 INVALIDPARAMETERVALUE_CRONEXPRESSIONILLEGAL = 'InvalidParameterValue.CronExpressionIllegal' # CVM参数校验异常。 INVALIDPARAMETERVALUE_CVMCONFIGURATIONERROR = 'InvalidParameterValue.CvmConfigurationError' # CVM参数校验异常。 INVALIDPARAMETERVALUE_CVMERROR = 'InvalidParameterValue.CvmError' # 提供的应用型负载均衡器重复。 INVALIDPARAMETERVALUE_DUPLICATEDFORWARDLB = 'InvalidParameterValue.DuplicatedForwardLb' # 指定的子网重复。 INVALIDPARAMETERVALUE_DUPLICATEDSUBNET = 'InvalidParameterValue.DuplicatedSubnet' # 定时任务设置的结束时间在开始时间。 INVALIDPARAMETERVALUE_ENDTIMEBEFORESTARTTIME = 'InvalidParameterValue.EndTimeBeforeStartTime' # 无效的过滤器。 INVALIDPARAMETERVALUE_FILTER = 'InvalidParameterValue.Filter' # 在应当指定应用型负载均衡器的参数中,错误地指定了一个非应用型的负载均衡器。 INVALIDPARAMETERVALUE_FORWARDLB = 'InvalidParameterValue.ForwardLb' # 伸缩组名称重复。 INVALIDPARAMETERVALUE_GROUPNAMEDUPLICATED = 'InvalidParameterValue.GroupNameDuplicated' # 主机名不合法。 INVALIDPARAMETERVALUE_HOSTNAMEILLEGAL = 'InvalidParameterValue.HostNameIllegal' # 指定的镜像不存在。 INVALIDPARAMETERVALUE_IMAGENOTFOUND = 'InvalidParameterValue.ImageNotFound' # 设置的实例名称不合法。 INVALIDPARAMETERVALUE_INSTANCENAMEILLEGAL = 'InvalidParameterValue.InstanceNameIllegal' # 实例机型不支持。 INVALIDPARAMETERVALUE_INSTANCETYPENOTSUPPORTED = 'InvalidParameterValue.InstanceTypeNotSupported' # 伸缩活动ID无效。 INVALIDPARAMETERVALUE_INVALIDACTIVITYID = 'InvalidParameterValue.InvalidActivityId' # 伸缩组ID无效。 INVALIDPARAMETERVALUE_INVALIDAUTOSCALINGGROUPID = 'InvalidParameterValue.InvalidAutoScalingGroupId' # 通知ID无效。 INVALIDPARAMETERVALUE_INVALIDAUTOSCALINGNOTIFICATIONID = 'InvalidParameterValue.InvalidAutoScalingNotificationId' # 告警策略ID无效。 INVALIDPARAMETERVALUE_INVALIDAUTOSCALINGPOLICYID = 'InvalidParameterValue.InvalidAutoScalingPolicyId' # 为CLB指定的地域不合法。 INVALIDPARAMETERVALUE_INVALIDCLBREGION = 'InvalidParameterValue.InvalidClbRegion' # 过滤条件无效。 INVALIDPARAMETERVALUE_INVALIDFILTER = 'InvalidParameterValue.InvalidFilter' # 镜像ID无效。 INVALIDPARAMETERVALUE_INVALIDIMAGEID = 'InvalidParameterValue.InvalidImageId' # 实例ID无效。 INVALIDPARAMETERVALUE_INVALIDINSTANCEID = 'InvalidParameterValue.InvalidInstanceId' # 实例机型无效。 INVALIDPARAMETERVALUE_INVALIDINSTANCETYPE = 'InvalidParameterValue.InvalidInstanceType' # 输入的启动配置无效。 INVALIDPARAMETERVALUE_INVALIDLAUNCHCONFIGURATION = 'InvalidParameterValue.InvalidLaunchConfiguration' # 启动配置ID无效。 INVALIDPARAMETERVALUE_INVALIDLAUNCHCONFIGURATIONID = 'InvalidParameterValue.InvalidLaunchConfigurationId' # 生命周期挂钩ID无效。 INVALIDPARAMETERVALUE_INVALIDLIFECYCLEHOOKID = 'InvalidParameterValue.InvalidLifecycleHookId' # 指定的通知组 ID 不是数值字符串格式。 INVALIDPARAMETERVALUE_INVALIDNOTIFICATIONUSERGROUPID = 'InvalidParameterValue.InvalidNotificationUserGroupId' # 定时任务ID无效。 INVALIDPARAMETERVALUE_INVALIDSCHEDULEDACTIONID = 'InvalidParameterValue.InvalidScheduledActionId' # 定时任务名称包含无效字符。 INVALIDPARAMETERVALUE_INVALIDSCHEDULEDACTIONNAMEINCLUDEILLEGALCHAR = 'InvalidParameterValue.InvalidScheduledActionNameIncludeIllegalChar' # 快照ID无效。 INVALIDPARAMETERVALUE_INVALIDSNAPSHOTID = 'InvalidParameterValue.InvalidSnapshotId' # 子网ID无效。 INVALIDPARAMETERVALUE_INVALIDSUBNETID = 'InvalidParameterValue.InvalidSubnetId' # 启动配置名称重复。 INVALIDPARAMETERVALUE_LAUNCHCONFIGURATIONNAMEDUPLICATED = 'InvalidParameterValue.LaunchConfigurationNameDuplicated' # 找不到指定启动配置。 INVALIDPARAMETERVALUE_LAUNCHCONFIGURATIONNOTFOUND = 'InvalidParameterValue.LaunchConfigurationNotFound' # 负载均衡器项目不一致。 INVALIDPARAMETERVALUE_LBPROJECTINCONSISTENT = 'InvalidParameterValue.LbProjectInconsistent' # 生命周期挂钩名称重复。 INVALIDPARAMETERVALUE_LIFECYCLEHOOKNAMEDUPLICATED = 'InvalidParameterValue.LifecycleHookNameDuplicated' # 取值超出限制。 INVALIDPARAMETERVALUE_LIMITEXCEEDED = 'InvalidParameterValue.LimitExceeded' # 无资源权限。 INVALIDPARAMETERVALUE_NORESOURCEPERMISSION = 'InvalidParameterValue.NoResourcePermission' # 提供的值不是浮点字符串格式。 INVALIDPARAMETERVALUE_NOTSTRINGTYPEFLOAT = 'InvalidParameterValue.NotStringTypeFloat' # 账号仅支持VPC网络。 INVALIDPARAMETERVALUE_ONLYVPC = 'InvalidParameterValue.OnlyVpc' # 项目ID不存在。 INVALIDPARAMETERVALUE_PROJECTIDNOTFOUND = 'InvalidParameterValue.ProjectIdNotFound' # 取值超出指定范围。 INVALIDPARAMETERVALUE_RANGE = 'InvalidParameterValue.Range' # 告警策略名称重复。 INVALIDPARAMETERVALUE_SCALINGPOLICYNAMEDUPLICATE = 'InvalidParameterValue.ScalingPolicyNameDuplicate' # 定时任务名称重复。 INVALIDPARAMETERVALUE_SCHEDULEDACTIONNAMEDUPLICATE = 'InvalidParameterValue.ScheduledActionNameDuplicate' # 伸缩组最大数量、最小数量、期望实例数取值不合法。 INVALIDPARAMETERVALUE_SIZE = 'InvalidParameterValue.Size' # 定时任务设置的开始时间在当前时间之前。 INVALIDPARAMETERVALUE_STARTTIMEBEFORECURRENTTIME = 'InvalidParameterValue.StartTimeBeforeCurrentTime' # 子网信息不合法。 INVALIDPARAMETERVALUE_SUBNETIDS = 'InvalidParameterValue.SubnetIds' # 负载均衡器四层监听器的后端端口重复。 INVALIDPARAMETERVALUE_TARGETPORTDUPLICATED = 'InvalidParameterValue.TargetPortDuplicated' # 指定的阈值不在有效范围。 INVALIDPARAMETERVALUE_THRESHOLDOUTOFRANGE = 'InvalidParameterValue.ThresholdOutOfRange' # 时间格式错误。 INVALIDPARAMETERVALUE_TIMEFORMAT = 'InvalidParameterValue.TimeFormat' # 取值过多。 INVALIDPARAMETERVALUE_TOOLONG = 'InvalidParameterValue.TooLong' # 输入参数值的长度小于最小值。 INVALIDPARAMETERVALUE_TOOSHORT = 'InvalidParameterValue.TooShort' # UserData格式错误。 INVALIDPARAMETERVALUE_USERDATAFORMATERROR = 'InvalidParameterValue.UserDataFormatError' # UserData长度过长。 INVALIDPARAMETERVALUE_USERDATASIZEEXCEEDED = 'InvalidParameterValue.UserDataSizeExceeded' # 用户组不存在。 INVALIDPARAMETERVALUE_USERGROUPIDNOTFOUND = 'InvalidParameterValue.UserGroupIdNotFound' # 指定的可用区与地域不匹配。 INVALIDPARAMETERVALUE_ZONEMISMATCHREGION = 'InvalidParameterValue.ZoneMismatchRegion' # 账户不支持该操作。 INVALIDPERMISSION = 'InvalidPermission' # 超过配额限制。 LIMITEXCEEDED = 'LimitExceeded' # 绑定指定的负载均衡器后,伸缩组绑定的负载均衡器总数超过了最大值。 LIMITEXCEEDED_AFTERATTACHLBLIMITEXCEEDED = 'LimitExceeded.AfterAttachLbLimitExceeded' # 伸缩组数量超过限制。 LIMITEXCEEDED_AUTOSCALINGGROUPLIMITEXCEEDED = 'LimitExceeded.AutoScalingGroupLimitExceeded' # 期望实例数超出限制。 LIMITEXCEEDED_DESIREDCAPACITYLIMITEXCEEDED = 'LimitExceeded.DesiredCapacityLimitExceeded' # 特定过滤器的值过多。 LIMITEXCEEDED_FILTERVALUESTOOLONG = 'LimitExceeded.FilterValuesTooLong' # 启动配置配额不足。 LIMITEXCEEDED_LAUNCHCONFIGURATIONQUOTANOTENOUGH = 'LimitExceeded.LaunchConfigurationQuotaNotEnough' # 最大实例数大于限制。 LIMITEXCEEDED_MAXSIZELIMITEXCEEDED = 'LimitExceeded.MaxSizeLimitExceeded' # 最小实例数低于限制。 LIMITEXCEEDED_MINSIZELIMITEXCEEDED = 'LimitExceeded.MinSizeLimitExceeded' # 当前剩余配额不足。 LIMITEXCEEDED_QUOTANOTENOUGH = 'LimitExceeded.QuotaNotEnough' # 定时任务数量超过限制。 LIMITEXCEEDED_SCHEDULEDACTIONLIMITEXCEEDED = 'LimitExceeded.ScheduledActionLimitExceeded' # 缺少参数错误。 MISSINGPARAMETER = 'MissingParameter' # 在特定场景下缺少参数。 MISSINGPARAMETER_INSCENARIO = 'MissingParameter.InScenario' # 竞价计费类型缺少对应的 InstanceMarketOptions 参数。 MISSINGPARAMETER_INSTANCEMARKETOPTIONS = 'MissingParameter.InstanceMarketOptions' # 伸缩组正在执行伸缩活动。 RESOURCEINUSE_ACTIVITYINPROGRESS = 'ResourceInUse.ActivityInProgress' # 伸缩组处于禁用状态。 RESOURCEINUSE_AUTOSCALINGGROUPNOTACTIVE = 'ResourceInUse.AutoScalingGroupNotActive' # 伸缩组内尚有正常实例。 RESOURCEINUSE_INSTANCEINGROUP = 'ResourceInUse.InstanceInGroup' # 指定的启动配置仍在伸缩组中使用。 RESOURCEINUSE_LAUNCHCONFIGURATIONIDINUSE = 'ResourceInUse.LaunchConfigurationIdInUse' # 超过伸缩组最大实例数。 RESOURCEINSUFFICIENT_AUTOSCALINGGROUPABOVEMAXSIZE = 'ResourceInsufficient.AutoScalingGroupAboveMaxSize' # 少于伸缩组最小实例数。 RESOURCEINSUFFICIENT_AUTOSCALINGGROUPBELOWMINSIZE = 'ResourceInsufficient.AutoScalingGroupBelowMinSize' # 伸缩组内实例数超过最大实例数。 RESOURCEINSUFFICIENT_INSERVICEINSTANCEABOVEMAXSIZE = 'ResourceInsufficient.InServiceInstanceAboveMaxSize' # 伸缩组内实例数低于最小实例数。 RESOURCEINSUFFICIENT_INSERVICEINSTANCEBELOWMINSIZE = 'ResourceInsufficient.InServiceInstanceBelowMinSize' # 伸缩组不存在。 RESOURCENOTFOUND_AUTOSCALINGGROUPNOTFOUND = 'ResourceNotFound.AutoScalingGroupNotFound' # 通知不存在。 RESOURCENOTFOUND_AUTOSCALINGNOTIFICATIONNOTFOUND = 'ResourceNotFound.AutoScalingNotificationNotFound' # 指定的 CMQ queue 不存在。 RESOURCENOTFOUND_CMQQUEUENOTFOUND = 'ResourceNotFound.CmqQueueNotFound' # 指定的实例不存在。 RESOURCENOTFOUND_INSTANCESNOTFOUND = 'ResourceNotFound.InstancesNotFound' # 目标实例不在伸缩组内。 RESOURCENOTFOUND_INSTANCESNOTINAUTOSCALINGGROUP = 'ResourceNotFound.InstancesNotInAutoScalingGroup' # 指定的启动配置不存在。 RESOURCENOTFOUND_LAUNCHCONFIGURATIONIDNOTFOUND = 'ResourceNotFound.LaunchConfigurationIdNotFound' # 生命周期挂钩对应实例不存在。 RESOURCENOTFOUND_LIFECYCLEHOOKINSTANCENOTFOUND = 'ResourceNotFound.LifecycleHookInstanceNotFound' # 无法找到指定生命周期挂钩。 RESOURCENOTFOUND_LIFECYCLEHOOKNOTFOUND = 'ResourceNotFound.LifecycleHookNotFound' # 指定的Listener不存在。 RESOURCENOTFOUND_LISTENERNOTFOUND = 'ResourceNotFound.ListenerNotFound' # 找不到指定负载均衡器。 RESOURCENOTFOUND_LOADBALANCERNOTFOUND = 'ResourceNotFound.LoadBalancerNotFound' # 指定的负载均衡器在当前伸缩组中没有找到。 RESOURCENOTFOUND_LOADBALANCERNOTINAUTOSCALINGGROUP = 'ResourceNotFound.LoadBalancerNotInAutoScalingGroup' # 指定的Location不存在。 RESOURCENOTFOUND_LOCATIONNOTFOUND = 'ResourceNotFound.LocationNotFound' # 告警策略不存在。 RESOURCENOTFOUND_SCALINGPOLICYNOTFOUND = 'ResourceNotFound.ScalingPolicyNotFound' # 指定的定时任务不存在。 RESOURCENOTFOUND_SCHEDULEDACTIONNOTFOUND = 'ResourceNotFound.ScheduledActionNotFound' # TDMQ-CMQ 队列不存在。 RESOURCENOTFOUND_TDMQCMQQUEUENOTFOUND = 'ResourceNotFound.TDMQCMQQueueNotFound' # TDMQ-CMQ 主题不存在。 RESOURCENOTFOUND_TDMQCMQTOPICNOTFOUND = 'ResourceNotFound.TDMQCMQTopicNotFound' # 伸缩组状态异常。 RESOURCEUNAVAILABLE_AUTOSCALINGGROUPABNORMALSTATUS = 'ResourceUnavailable.AutoScalingGroupAbnormalStatus' # 伸缩组被停用。 RESOURCEUNAVAILABLE_AUTOSCALINGGROUPDISABLED = 'ResourceUnavailable.AutoScalingGroupDisabled' # 伸缩组正在活动中。 RESOURCEUNAVAILABLE_AUTOSCALINGGROUPINACTIVITY = 'ResourceUnavailable.AutoScalingGroupInActivity' # 指定的 CMQ Topic 无订阅者。 RESOURCEUNAVAILABLE_CMQTOPICHASNOSUBSCRIBER = 'ResourceUnavailable.CmqTopicHasNoSubscriber' # 实例和伸缩组Vpc不一致。 RESOURCEUNAVAILABLE_CVMVPCINCONSISTENT = 'ResourceUnavailable.CvmVpcInconsistent' # 指定的实例正在活动中。 RESOURCEUNAVAILABLE_INSTANCEINOPERATION = 'ResourceUnavailable.InstanceInOperation' # 实例不支持关机不收费。 RESOURCEUNAVAILABLE_INSTANCENOTSUPPORTSTOPCHARGING = 'ResourceUnavailable.InstanceNotSupportStopCharging' # 实例已存在于伸缩组中。 RESOURCEUNAVAILABLE_INSTANCESALREADYINAUTOSCALINGGROUP = 'ResourceUnavailable.InstancesAlreadyInAutoScalingGroup' # 启动配置状态异常。 RESOURCEUNAVAILABLE_LAUNCHCONFIGURATIONSTATUSABNORMAL = 'ResourceUnavailable.LaunchConfigurationStatusAbnormal' # CLB实例的后端地域与AS服务所在地域不一致。 RESOURCEUNAVAILABLE_LBBACKENDREGIONINCONSISTENT = 'ResourceUnavailable.LbBackendRegionInconsistent' # 负载均衡器项目不一致。 RESOURCEUNAVAILABLE_LBPROJECTINCONSISTENT = 'ResourceUnavailable.LbProjectInconsistent' # 负载均衡器VPC与伸缩组不一致。 RESOURCEUNAVAILABLE_LBVPCINCONSISTENT = 'ResourceUnavailable.LbVpcInconsistent' # 生命周期动作已经被设置。 RESOURCEUNAVAILABLE_LIFECYCLEACTIONRESULTHASSET = 'ResourceUnavailable.LifecycleActionResultHasSet' # LB 在指定的伸缩组内处于活动中。 RESOURCEUNAVAILABLE_LOADBALANCERINOPERATION = 'ResourceUnavailable.LoadBalancerInOperation' # 项目不一致。 RESOURCEUNAVAILABLE_PROJECTINCONSISTENT = 'ResourceUnavailable.ProjectInconsistent' # 关机实例不允许添加到伸缩组。 RESOURCEUNAVAILABLE_STOPPEDINSTANCENOTALLOWATTACH = 'ResourceUnavailable.StoppedInstanceNotAllowAttach' # TDMQ-CMQ 主题无订阅者。 RESOURCEUNAVAILABLE_TDMQCMQTOPICHASNOSUBSCRIBER = 'ResourceUnavailable.TDMQCMQTopicHasNoSubscriber' # 指定的可用区不可用。 RESOURCEUNAVAILABLE_ZONEUNAVAILABLE = 'ResourceUnavailable.ZoneUnavailable'
""" Space : O(n) Time : O(n) """ class Solution: def rob(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] if len(nums) == 0: return 0 ans = 0 leng = len(nums)-1 one, two = [0] * leng, [0] * leng # 1st iteration for idx in range(leng): if idx < 2: one[idx] = nums[idx] else: one[idx] = nums[idx] + max(one[idx-2], one[idx-3]) ans = max(ans, one[idx]) # 2nd iteration for idx in range(leng): if idx < 2: two[idx] = nums[idx+1] else: two[idx] = nums[idx+1] + max(two[idx-2], two[idx-3]) ans = max(ans, two[idx]) return ans
class ZoneFilter: def __init__(self, rules): self.rules = rules def filter(self, record): # TODO Dummy implementation return [record]
class HyperparameterGrid(): def __init__(self): DEFAULT_HYPERPARAMETER_GRID = { 'lr': { 'C': [0.001, 0.01, 0.1, 1], 'penalty': ['l1', 'l2'], 'solver': ['liblinear'], 'intercept_scaling': [1, 1000], 'max_iter': [1000] }, 'dt': { 'criterion': ['gini', 'entropy'], 'max_depth': [3, 5, 10, None], 'min_samples_leaf': [0.01, 0.02, 0.05], }, 'rf': { 'n_estimators': [100, 500, 1000], 'criterion': ['gini','entropy'], 'max_depth': [3, 5, 10, None], 'min_samples_leaf': [0.01, 0.02, 0.05], }, 'xgb': { 'max_depth': [2, 3, 4, 5, 6], 'eta': [.1, .3, .5], 'eval_metric': ['auc'], 'min_child_weight': [1, 3, 5, 7, 9], 'gamma':[0], 'scale_pos_weight': [1], 'bsample': [0.8], 'n_jobs': [4], 'n_estimators': [100], 'colsample_bytree': [0.8], 'objective': ['binary:logistic'], } } self.param_grids = DEFAULT_HYPERPARAMETER_GRID
def uniqueElements(myList): uniqList = [] for _var in myList: if _var not in uniqList: uniqList.append(_var) else: return "Not Unique" return "Unique" print(uniqueElements([2,99,99,12,3,11,223]))
def magic_square(square): size_square = len(square) is_magic = True wanted_sum = 0 for index in range(0, size_square): wanted_sum += square[0][index] for row in range(0, size_square): current_sum = 0 for col in range(0, size_square): current_sum += square[row][col] if current_sum != wanted_sum: is_magic = False break for col in range(0, size_square): current_sum = 0 for row in range(0, size_square): current_sum += square[row][col] if current_sum != wanted_sum: is_magic = False break current_sum = 0 row = 0 col = 0 while row < size_square and col < size_square: current_sum += square[row][col] row += 1 col += 1 if current_sum != wanted_sum: is_magic = False current_sum = 0 row = 0 col = size_square - 1 while row < size_square and col >= 0: current_sum += square[row][col] row += 1 col -= 1 if current_sum != wanted_sum: is_magic = False return is_magic square1 = [ [23, 28, 21], [22, 24, 26], [27, 20, 25] ] square2 = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print (magic_square(square1)) print (magic_square(square2))
def f(x): y=1 x=x+y return x x=3 y=2 z=f(x) print("x="+str(x)) print("y="+str(y)) print("z="+str(z))
__all__ = [ "mock_generation_data_frame", "test_get_monthly_net_generation", "test_rate_limit", "test_retry", ]
test = { 'name': 'q1_2', 'points': 1, 'suites': [ { 'cases': [ {'code': ">>> assert trending_vids.shape[0] == '40379'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 0] == '25231'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 4] == 'Inside Edition'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[0, 'views'] == 542677.0\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[2, 'likes'] == 11390.0\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.loc[3, 'dislikes'] == 175.0\n", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
# -*- coding: utf-8 -*- """ Created on Tue Apr 6 10:35:39 2021 @author: ELCOT """ """ Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] """ class Solution: def generate(self,n): res = [[1]] if n == 1: return res for i in range(2,n+1): r = [1] for j in range(2,i): #print(i,j) s = (r[-1] * (i-(j-1))) / (j-1) r.append(int(s)) r.append(1) res.append(r) print(res) Solution().generate(5)
class Income: def __init__(self): self.tranId = "" self.tradeId = "" self.symbol = "" self.incomeType = "" self.income = 0.0 self.asset = "" self.time = 0 @staticmethod def json_parse(json_data): result = Income() result.tranId = json_data.get_string("tranId") result.tradeId = json_data.get_string("tradeId") result.symbol = json_data.get_string("symbol") result.incomeType = json_data.get_string("incomeType") result.income = json_data.get_float("income") result.asset = json_data.get_string("asset") result.time = json_data.get_int("time") return result
def game(input,max_turns): memory = {} turncounter = 1 most_recent_number = int(input[-1]) for i in range(len(input)): memory[int(input[i])] = [turncounter,-1] turncounter += 1 while turncounter <= max_turns: if memory[most_recent_number][1] == -1: most_recent_number = 0 else: most_recent_number = memory[most_recent_number][0] - memory[most_recent_number][1] if most_recent_number in memory: memory[most_recent_number] = [turncounter,memory[most_recent_number][0]] else: memory[most_recent_number] = [turncounter,-1] turncounter +=1 return str(most_recent_number) def main(filepath): with open(filepath) as file: rows = [x.strip() for x in file.readlines()] input = rows[0].split(",") print("Part a solution: "+game(input,2020)) print("Part b solution: "+game(input,30000000)) #takes a while to run, but less than 1 minute
# Copyright 2020 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. VALID_META_KEYS = ["cpu", "memory", "gpu"] def post_process(metadata): # memory should be in MB if "memory" in metadata: memory = metadata.pop("memory") metadata["mem"] = memory return metadata def meta(**kwargs): """ fiber.meta API allows you to decorate your function and provide some hints to Fiber. Currently this is mainly used for specify the resource usage of user functions. Currently, support keys are: | key | Type | Default | Notes | | --------------------- |:------|:-----|:------| | cpu | int | None | The number of CPU cores that this function needs | | memory | int | None | The size of memory space in MB this function needs | | gpu | int | None | The number of GPUs that this function needs. For how to setup Fiber with GPUs, check out [here](advanced.md#using-fiber-with-gpus) | Example usage: ```python @fiber.meta(cpu=4, memory=1000, gpu=1) def func(): do_something() ``` """ for k in kwargs: assert k in VALID_META_KEYS, "Invalid meta argument \"{}\"".format(k) def decorator(func): meta = post_process(kwargs) func.__fiber_meta__ = meta return func return decorator
def is_krampus(n): p = str(n**2) l_p = len(p) for i in range(1, l_p - 1): p_1 = int(p[:i]) p_2 = int(p[i:]) if p_1 and p_2 and p_1 + p_2 == n: return True return False def test_is_krampus(): assert is_krampus(45) assert not is_krampus(100) if __name__ == '__main__': s = 0 for n in open('input/09').readlines(): n = int(n.strip()) if is_krampus(n): s += n print(s)
def adjacentElementsProduct(inputArray): first, second = 0, 1 lp = inputArray[first]*inputArray[second] for index in range(2, len(inputArray)): first = second second = index new_lp = inputArray[first]*inputArray[second] if new_lp > lp: lp = new_lp return lp
def y(): pass def x(): y() for i in range(10): x()
INSTALLED_APPS = ( 'vkontakte_api', 'vkontakte_places', 'vkontakte_users', 'vkontakte_groups', 'vkontakte_comments', 'm2m_history', ) SOCIAL_API_TOKENS_STORAGES = []
# # PySNMP MIB module AcAlarm (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AcAlarm # Produced by pysmi-0.3.4 at Wed May 1 11:33:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # AcAlarmEventType, AcAlarmProbableCause, AcAlarmSeverity = mibBuilder.importSymbols("AC-FAULT-TC", "AcAlarmEventType", "AcAlarmProbableCause", "AcAlarmSeverity") OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") SnmpEngineID, SnmpAdminString = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpEngineID", "SnmpAdminString") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") TimeTicks, enterprises, ModuleIdentity, iso, Bits, NotificationType, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, IpAddress, Counter32, Gauge32, Counter64, ObjectIdentity, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "enterprises", "ModuleIdentity", "iso", "Bits", "NotificationType", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "IpAddress", "Counter32", "Gauge32", "Counter64", "ObjectIdentity", "Integer32") TimeStamp, DateAndTime, DisplayString, RowStatus, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "DateAndTime", "DisplayString", "RowStatus", "TruthValue", "TextualConvention") audioCodes = MibIdentifier((1, 3, 6, 1, 4, 1, 5003)) acFault = MibIdentifier((1, 3, 6, 1, 4, 1, 5003, 11)) acAlarm = ModuleIdentity((1, 3, 6, 1, 4, 1, 5003, 11, 1)) acAlarm.setRevisions(('2003-12-18 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: acAlarm.setRevisionsDescriptions(('4.4. Dec. 18, 2003. Made these changes: o Initial version',)) if mibBuilder.loadTexts: acAlarm.setLastUpdated('200312180000Z') if mibBuilder.loadTexts: acAlarm.setOrganization('Audiocodes') if mibBuilder.loadTexts: acAlarm.setContactInfo('Postal: Support AudioCodes LTD 1 Hayarden Street Airport City Lod 70151, ISRAEL Tel: 972-3-9764000 Fax: 972-3-9764040 Email: support@audiocodes.com Web: www.audiocodes.com') if mibBuilder.loadTexts: acAlarm.setDescription('This MIB defines the enterprise-specific objects needed to support fault management of Audiocodes products. The MIB consists of: o Active alarm table o Alarm history table o Alarm notification varbinds') acActiveAlarm = MibIdentifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1)) acActiveAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1), ) if mibBuilder.loadTexts: acActiveAlarmTable.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTable.setDescription('Table of active alarms.') acActiveAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1), ).setIndexNames((0, "AcAlarm", "acActiveAlarmSequenceNumber")) if mibBuilder.loadTexts: acActiveAlarmEntry.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmEntry.setDescription('A conceptual row in the acActiveAlarmTable') acActiveAlarmSequenceNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmSequenceNumber.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSequenceNumber.setDescription('The sequence number of the alarm raise trap.') acActiveAlarmSysuptime = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 2), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmSysuptime.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSysuptime.setDescription('The value of sysuptime at the time the alarm raise trap was sent') acActiveAlarmTrapOID = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmTrapOID.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTrapOID.setDescription('The OID of the notification trap') acActiveAlarmDateAndTime = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 4), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmDateAndTime.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmDateAndTime.setDescription('The date and time at the time the alarm raise trap was sent.') acActiveAlarmName = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmName.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmName.setDescription('The name of the alarm that was raised. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') acActiveAlarmTextualDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 6), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmTextualDescription.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmTextualDescription.setDescription('Text that descries the alarm condition.') acActiveAlarmSource = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 7), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmSource.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSource.setDescription('The component in the system which raised the alarm.') acActiveAlarmSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 8), AcAlarmSeverity()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmSeverity.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmSeverity.setDescription('The severity of the alarm.') acActiveAlarmEventType = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 9), AcAlarmEventType()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmEventType.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmEventType.setDescription('The event type of the alarm.') acActiveAlarmProbableCause = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 10), AcAlarmProbableCause()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmProbableCause.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmProbableCause.setDescription('The probable cause of the alarm.') acActiveAlarmAdditionalInfo1 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 11), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') acActiveAlarmAdditionalInfo2 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 12), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') acActiveAlarmAdditionalInfo3 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 1, 1, 1, 13), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acActiveAlarmAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2)) acAlarmHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1), ) if mibBuilder.loadTexts: acAlarmHistoryTable.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTable.setDescription('A table of all raise-alarm and clear-alarm traps sent by the system. Internal to the system, this table of traps is a fixed size. Once the table reaches this size, older traps are removed to make room for new traps. The size of the table is the value of the nlmConfigLogEntryLimit (NOTIFICATION-LOG-MIB).') acAlarmHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1), ).setIndexNames((0, "AcAlarm", "acAlarmHistorySequenceNumber")) if mibBuilder.loadTexts: acAlarmHistoryEntry.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryEntry.setDescription('A conceptual row in the acAlarmHistoryTable') acAlarmHistorySequenceNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistorySequenceNumber.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySequenceNumber.setDescription('The sequence number of the alarm raise or clear trap.') acAlarmHistorySysuptime = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 2), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistorySysuptime.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySysuptime.setDescription('The value of sysuptime at the time the alarm raise or clear trap was sent') acAlarmHistoryTrapOID = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryTrapOID.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTrapOID.setDescription('The OID of the notification trap') acAlarmHistoryDateAndTime = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 4), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryDateAndTime.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryDateAndTime.setDescription('The date and time at the time the alarm raise or clear trap was sent.') acAlarmHistoryName = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryName.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryName.setDescription('The name of the alarm that was raised or cleared. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') acAlarmHistoryTextualDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 6), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryTextualDescription.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryTextualDescription.setDescription('Text that descries the alarm condition.') acAlarmHistorySource = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 7), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistorySource.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySource.setDescription('The component in the system which raised or cleared the alarm.') acAlarmHistorySeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 8), AcAlarmSeverity()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistorySeverity.setStatus('current') if mibBuilder.loadTexts: acAlarmHistorySeverity.setDescription('The severity of the alarm. A severity of warning, minor, major or critical indicates a raise trap. A severity of cleared indicates a clear trap.') acAlarmHistoryEventType = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 9), AcAlarmEventType()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryEventType.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryEventType.setDescription('The event type of the alarm.') acAlarmHistoryProbableCause = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 10), AcAlarmProbableCause()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryProbableCause.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryProbableCause.setDescription('The probable cause of the alarm.') acAlarmHistoryAdditionalInfo1 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 11), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmHistoryAdditionalInfo2 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 12), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmHistoryAdditionalInfo3 = MibTableColumn((1, 3, 6, 1, 4, 1, 5003, 11, 1, 2, 1, 1, 13), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acAlarmHistoryAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmVarbinds = MibIdentifier((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3)) acAlarmVarbindsSequenceNumber = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 1), Unsigned32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsSequenceNumber.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSequenceNumber.setDescription('The sequence number of the alarm raise or clear trap.') acAlarmVarbindsDateAndTime = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 2), DateAndTime()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsDateAndTime.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsDateAndTime.setDescription('The date and time at the time the alarm raise or clear trap was sent.') acAlarmVarbindsAlarmName = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 3), Unsigned32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsAlarmName.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAlarmName.setDescription('The name of the alarm that was raised or cleared. This actually in the form of a number. Each kind of alarm has a unique number associated with it.') acAlarmVarbindsTextualDescription = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 4), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsTextualDescription.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsTextualDescription.setDescription('Text that descries the alarm condition.') acAlarmVarbindsSource = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 5), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsSource.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSource.setDescription('The component in the system which raised or cleared the alarm.') acAlarmVarbindsSeverity = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 6), AcAlarmSeverity()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsSeverity.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsSeverity.setDescription('The severity of the alarm. A severity of warning, minor, major or critical indicates a raise trap. A severity of cleared indicates a clear trap.') acAlarmVarbindsEventType = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 7), AcAlarmEventType()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsEventType.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsEventType.setDescription('The event type of the alarm.') acAlarmVarbindsProbableCause = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 8), AcAlarmProbableCause()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsProbableCause.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsProbableCause.setDescription('The probable cause of the alarm.') acAlarmVarbindsAdditionalInfo1 = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 9), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo1.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo1.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmVarbindsAdditionalInfo2 = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 10), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo2.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo2.setDescription('Additional miscellaneous info regarding this alarm.') acAlarmVarbindsAdditionalInfo3 = MibScalar((1, 3, 6, 1, 4, 1, 5003, 11, 1, 3, 11), SnmpAdminString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo3.setStatus('current') if mibBuilder.loadTexts: acAlarmVarbindsAdditionalInfo3.setDescription('Additional miscellaneous info regarding this alarm.') mibBuilder.exportSymbols("AcAlarm", acAlarmVarbinds=acAlarmVarbinds, acActiveAlarmSource=acActiveAlarmSource, acActiveAlarmSeverity=acActiveAlarmSeverity, audioCodes=audioCodes, acAlarmHistorySequenceNumber=acAlarmHistorySequenceNumber, acAlarmVarbindsSource=acAlarmVarbindsSource, acAlarmHistory=acAlarmHistory, acActiveAlarmEventType=acActiveAlarmEventType, acAlarmHistoryEventType=acAlarmHistoryEventType, acActiveAlarmTable=acActiveAlarmTable, acActiveAlarmSysuptime=acActiveAlarmSysuptime, acAlarmVarbindsDateAndTime=acAlarmVarbindsDateAndTime, acAlarmVarbindsSeverity=acAlarmVarbindsSeverity, acAlarmVarbindsTextualDescription=acAlarmVarbindsTextualDescription, acActiveAlarmName=acActiveAlarmName, acAlarmVarbindsEventType=acAlarmVarbindsEventType, acActiveAlarmSequenceNumber=acActiveAlarmSequenceNumber, acActiveAlarm=acActiveAlarm, acAlarmHistoryAdditionalInfo2=acAlarmHistoryAdditionalInfo2, acActiveAlarmTextualDescription=acActiveAlarmTextualDescription, acAlarmHistoryProbableCause=acAlarmHistoryProbableCause, acAlarmHistoryAdditionalInfo3=acAlarmHistoryAdditionalInfo3, acActiveAlarmTrapOID=acActiveAlarmTrapOID, acAlarmVarbindsSequenceNumber=acAlarmVarbindsSequenceNumber, acAlarmVarbindsAlarmName=acAlarmVarbindsAlarmName, acAlarmVarbindsAdditionalInfo2=acAlarmVarbindsAdditionalInfo2, acAlarmHistoryTrapOID=acAlarmHistoryTrapOID, acActiveAlarmDateAndTime=acActiveAlarmDateAndTime, acAlarmHistoryDateAndTime=acAlarmHistoryDateAndTime, acAlarmHistoryEntry=acAlarmHistoryEntry, acAlarm=acAlarm, acAlarmHistoryName=acAlarmHistoryName, acActiveAlarmProbableCause=acActiveAlarmProbableCause, acActiveAlarmAdditionalInfo2=acActiveAlarmAdditionalInfo2, acAlarmHistorySource=acAlarmHistorySource, acActiveAlarmEntry=acActiveAlarmEntry, acAlarmHistoryTable=acAlarmHistoryTable, acActiveAlarmAdditionalInfo3=acActiveAlarmAdditionalInfo3, acAlarmHistoryAdditionalInfo1=acAlarmHistoryAdditionalInfo1, acAlarmVarbindsAdditionalInfo1=acAlarmVarbindsAdditionalInfo1, acAlarmVarbindsAdditionalInfo3=acAlarmVarbindsAdditionalInfo3, PYSNMP_MODULE_ID=acAlarm, acActiveAlarmAdditionalInfo1=acActiveAlarmAdditionalInfo1, acAlarmVarbindsProbableCause=acAlarmVarbindsProbableCause, acFault=acFault, acAlarmHistoryTextualDescription=acAlarmHistoryTextualDescription, acAlarmHistorySysuptime=acAlarmHistorySysuptime, acAlarmHistorySeverity=acAlarmHistorySeverity)
"""Set up dependency to tensorflow pip package.""" def _find_tf_include_path(repo_ctx): exec_result = repo_ctx.execute( [ "python3", "-c", "import tensorflow as tf; import sys; " + "sys.stdout.write(tf.sysconfig.get_include())", ], quiet = True, ) if exec_result.return_code != 0: fail("Could not locate tensorflow. Please install TensorFlow pip package first.") return exec_result.stdout.splitlines()[-1] def _find_tf_lib_path(repo_ctx): exec_result = repo_ctx.execute( [ "python3", "-c", "import tensorflow as tf; import sys; " + "sys.stdout.write(tf.sysconfig.get_lib())", ], quiet = True, ) if exec_result.return_code != 0: fail("Could not locate tensorflow. Please install TensorFlow pip package first.") return exec_result.stdout.splitlines()[-1] def _tensorflow_includes_repo_impl(repo_ctx): tf_include_path = _find_tf_include_path(repo_ctx) repo_ctx.symlink(tf_include_path, "tensorflow_includes") repo_ctx.file( "BUILD", content = """ cc_library( name = "includes", hdrs = glob(["tensorflow_includes/**/*.h", "tensorflow_includes/third_party/eigen3/**"]), includes = ["tensorflow_includes"], deps = ["@absl_includes//:includes", "@eigen_archive//:includes", "@protobuf_archive//:includes", "@zlib_includes//:includes",], visibility = ["//visibility:public"], ) """, executable = False, ) def _tensorflow_solib_repo_impl(repo_ctx): tf_lib_path = _find_tf_lib_path(repo_ctx) repo_ctx.symlink(tf_lib_path, "tensorflow_solib") repo_ctx.file( "BUILD", content = """ cc_library( name = "framework_lib", srcs = ["tensorflow_solib/libtensorflow_framework.so.2"], visibility = ["//visibility:public"], ) """, ) def tf_configure(): """Autoconf pre-installed tensorflow pip package.""" make_tfinc_repo = repository_rule( implementation = _tensorflow_includes_repo_impl, ) make_tfinc_repo(name = "tensorflow_includes") make_tflib_repo = repository_rule( implementation = _tensorflow_solib_repo_impl, ) make_tflib_repo(name = "tensorflow_solib")
''' Processing of data via :py:mod:`.json_io`. Utilities for Excel conversion in :py:mod:`.convert` and :py:mod:`.service_sheet`. Example code in :py:mod:`.cli_examples` and :py:mod:`.plots`. '''