content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python # -*- coding:utf-8 -*- name = "popcorntime" source = "https://aur.archlinux.org/popcorntime-bin.git" def pre_build(): for line in edit_file("PKGBUILD"): if line.startswith("pkgname="): print("pkgname=popcorntime") else: print(line)
name = 'popcorntime' source = 'https://aur.archlinux.org/popcorntime-bin.git' def pre_build(): for line in edit_file('PKGBUILD'): if line.startswith('pkgname='): print('pkgname=popcorntime') else: print(line)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: return self.scanTree(root, None, None) def scanTree(self, root, minEnd, maxEnd): outcome = True if root.left != None: if root.left.val >= root.val: outcome = False if minEnd != None and root.left.val <= minEnd: outcome = False if maxEnd != None and root.left.val >= maxEnd: outcome = False if not self.scanTree(root.left, minEnd, root.val): outcome = False if outcome == True and root.right != None: if root.right.val <= root.val: outcome = False if minEnd != None and root.right.val <= minEnd: outcome = False if maxEnd != None and root.right.val >= maxEnd: outcome = False if not self.scanTree(root.right, root.val, maxEnd): outcome = False return outcome
class Solution: def is_valid_bst(self, root: TreeNode) -> bool: return self.scanTree(root, None, None) def scan_tree(self, root, minEnd, maxEnd): outcome = True if root.left != None: if root.left.val >= root.val: outcome = False if minEnd != None and root.left.val <= minEnd: outcome = False if maxEnd != None and root.left.val >= maxEnd: outcome = False if not self.scanTree(root.left, minEnd, root.val): outcome = False if outcome == True and root.right != None: if root.right.val <= root.val: outcome = False if minEnd != None and root.right.val <= minEnd: outcome = False if maxEnd != None and root.right.val >= maxEnd: outcome = False if not self.scanTree(root.right, root.val, maxEnd): outcome = False return outcome
for c in range(10, -1, -1): print(c) print('FOGOOOOOS !!!')
for c in range(10, -1, -1): print(c) print('FOGOOOOOS !!!')
class Animal: def __init__(self,*args,**kwargs): animalArgs = args[0] animalArgs.update(kwargs) self.__dict__.update(animalArgs) def update(self,val): self.__dict__.update(val) def get(self): print(self) return vars(self) def addSponsor(self,sponsor): self.sponsor = sponsor @classmethod def fromDict(cls,inst,animDict): if "_id" in animDict: _id = animDict['_id'] del animDict["_id"] anim = inst(*animDict.values()) anim._id = _id return anim
class Animal: def __init__(self, *args, **kwargs): animal_args = args[0] animalArgs.update(kwargs) self.__dict__.update(animalArgs) def update(self, val): self.__dict__.update(val) def get(self): print(self) return vars(self) def add_sponsor(self, sponsor): self.sponsor = sponsor @classmethod def from_dict(cls, inst, animDict): if '_id' in animDict: _id = animDict['_id'] del animDict['_id'] anim = inst(*animDict.values()) anim._id = _id return anim
# -*- coding: utf-8 -*- """ Created on Thu Jun 20 16:17:26 2019 @author: Administrator """ class Solution: def trailingZeroes(self, n: int) -> int: # ans = [] # for num in n: # res = 1 # for k in range(1, num+1): # res = res * k # tmp = 0 # while res%10 == 0: # tmp += 1 # res //= 10 # ans.append(tmp) # return ans # ans = 0 # while n: # ans += n//5 # n //= 5 # return ans ans = 0 while n: n //= 5 ans += n return ans solu = Solution() n = 3 n = 5 n = 10 n = 30 n = 200 #n = 100 #n = [200] #n = [100] #n = 10000 #n = list(range(0,1000+1)) #n = list(range(0,200+1)) print(solu.trailingZeroes(n))
""" Created on Thu Jun 20 16:17:26 2019 @author: Administrator """ class Solution: def trailing_zeroes(self, n: int) -> int: ans = 0 while n: n //= 5 ans += n return ans solu = solution() n = 3 n = 5 n = 10 n = 30 n = 200 print(solu.trailingZeroes(n))
# Copyright (c) 2015-2019 Patricio Cubillos and contributors. # MC3 is open-source software under the MIT license (see LICENSE). # MC3 Version: MC3_VER = 3 # Major version MC3_MIN = 0 # Minor version MC3_REV = 0 # Revision __version__ = '{}.{}.{}'.format(MC3_VER, MC3_MIN, MC3_REV)
mc3_ver = 3 mc3_min = 0 mc3_rev = 0 __version__ = '{}.{}.{}'.format(MC3_VER, MC3_MIN, MC3_REV)
class FactorUniverseSelectionModel(): def __init__(self, algorithm): self.algorithm = algorithm def SelectCoarse(self, coarse): # self.algorithm.Log("Generating universe...") universe = self.FilterDollarPriceVolume(coarse) return [c.Symbol for c in universe] def SelectFine(self, fine): universe = self.FilterFactor(self.FilterFinancials(fine)) # self.algorithm.Log(f"Universe consists of {len(universe)} securities") self.algorithm.securities = universe return [f.Symbol for f in universe] def FilterDollarPriceVolume(self, coarse): filter_dollar_price = [c for c in coarse if c.Price > 1] sorted_dollar_volume = sorted([c for c in filter_dollar_price if c.HasFundamentalData], key=lambda c: c.DollarVolume, reverse=True) return sorted_dollar_volume[:1000] def FilterFinancials(self, fine): filter_financials = [f for f in fine if f.AssetClassification.MorningstarSectorCode != MorningstarSectorCode.FinancialServices] return filter_financials def FilterFactor(self, fine): filter_factor = sorted(fine, key=lambda f: f.ValuationRatios.CashReturn, reverse=True) return filter_factor[:50] + filter_factor[-50:]
class Factoruniverseselectionmodel: def __init__(self, algorithm): self.algorithm = algorithm def select_coarse(self, coarse): universe = self.FilterDollarPriceVolume(coarse) return [c.Symbol for c in universe] def select_fine(self, fine): universe = self.FilterFactor(self.FilterFinancials(fine)) self.algorithm.securities = universe return [f.Symbol for f in universe] def filter_dollar_price_volume(self, coarse): filter_dollar_price = [c for c in coarse if c.Price > 1] sorted_dollar_volume = sorted([c for c in filter_dollar_price if c.HasFundamentalData], key=lambda c: c.DollarVolume, reverse=True) return sorted_dollar_volume[:1000] def filter_financials(self, fine): filter_financials = [f for f in fine if f.AssetClassification.MorningstarSectorCode != MorningstarSectorCode.FinancialServices] return filter_financials def filter_factor(self, fine): filter_factor = sorted(fine, key=lambda f: f.ValuationRatios.CashReturn, reverse=True) return filter_factor[:50] + filter_factor[-50:]
"Day 25: Combo Breaker" def find_loop_size_of(key: int) -> int: """Determine loop size from public key.""" value = 1 subject = 7 loop = 0 while value != key: value *= subject value = value % 20201227 loop += 1 return loop def calculate_encryption(first_key: int, second_key: int) -> int: """Calculate encryption key with loop size and other device's public key.""" value = 1 for _ in range(find_loop_size_of(second_key)): value *= first_key value = value % 20201227 return value def main(): key_card = 11562782 key_door = 18108497 # part one encryption = calculate_encryption(key_card, key_door) print(f"The encryption key is {encryption}.") if __name__ == "__main__": main()
"""Day 25: Combo Breaker""" def find_loop_size_of(key: int) -> int: """Determine loop size from public key.""" value = 1 subject = 7 loop = 0 while value != key: value *= subject value = value % 20201227 loop += 1 return loop def calculate_encryption(first_key: int, second_key: int) -> int: """Calculate encryption key with loop size and other device's public key.""" value = 1 for _ in range(find_loop_size_of(second_key)): value *= first_key value = value % 20201227 return value def main(): key_card = 11562782 key_door = 18108497 encryption = calculate_encryption(key_card, key_door) print(f'The encryption key is {encryption}.') if __name__ == '__main__': main()
def isAnagram(string1, string2): """Checks if two strings are an anagram An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. This implementation ignores spaces and case. @param string1 The first word or phrase @param string2 The second word or phrase @return A boolean representing if the strings are an anagram or not """ # Remove spaces str1_nospace = string1.replace(" ", "") str2_nospace = string2.replace(" ", "") # Convert to lowercase and sort list1 = list(str1_nospace.lower()) list1.sort() list2 = list(str2_nospace.lower()) list2.sort() # Check for equality return (list1 == list2) # Test cases assert isAnagram('chair', 'archi') == True assert isAnagram('Elbow', 'Below') == True assert isAnagram('More', 'Moore') == False assert isAnagram('Johnathan', 'Jonathan') == False assert isAnagram('Dormitory', 'Dirty Room') == True assert isAnagram('Conversation', 'Voices rant on') == True
def is_anagram(string1, string2): """Checks if two strings are an anagram An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. This implementation ignores spaces and case. @param string1 The first word or phrase @param string2 The second word or phrase @return A boolean representing if the strings are an anagram or not """ str1_nospace = string1.replace(' ', '') str2_nospace = string2.replace(' ', '') list1 = list(str1_nospace.lower()) list1.sort() list2 = list(str2_nospace.lower()) list2.sort() return list1 == list2 assert is_anagram('chair', 'archi') == True assert is_anagram('Elbow', 'Below') == True assert is_anagram('More', 'Moore') == False assert is_anagram('Johnathan', 'Jonathan') == False assert is_anagram('Dormitory', 'Dirty Room') == True assert is_anagram('Conversation', 'Voices rant on') == True
# # PySNMP MIB module MITEL-IPFILTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-IPFILTER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:03:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Integer32, IpAddress, MibIdentifier, Bits, TimeTicks, Unsigned32, enterprises, NotificationType, iso, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Counter64, Counter32, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "IpAddress", "MibIdentifier", "Bits", "TimeTicks", "Unsigned32", "enterprises", "NotificationType", "iso", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Counter64", "Counter32", "ModuleIdentity") TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus") mitelIpGrpFilterGroup = ModuleIdentity((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1)) mitelIpGrpFilterGroup.setRevisions(('2003-03-24 09:25', '1999-03-01 00:00',)) if mibBuilder.loadTexts: mitelIpGrpFilterGroup.setLastUpdated('200303240925Z') if mibBuilder.loadTexts: mitelIpGrpFilterGroup.setOrganization('MITEL Corporation') mitel = MibIdentifier((1, 3, 6, 1, 4, 1, 1027)) mitelProprietary = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4)) mitelPropIpNetworking = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 8)) mitelIpNetRouter = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1)) mitelRouterIpGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1)) mitelIdentification = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1)) mitelIdCallServers = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 2)) mitelIdCsIpera1000 = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 2, 4)) mitelFltGrpAccessRestrictEnable = MibScalar((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelFltGrpAccessRestrictEnable.setStatus('current') mitelFltGrpLogicalTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 2), ) if mibBuilder.loadTexts: mitelFltGrpLogicalTable.setStatus('current') mitelFltGrpLogicalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: mitelFltGrpLogicalEntry.setStatus('current') mitelLogTableAccessDef = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("filter", 1), ("forward", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelLogTableAccessDef.setStatus('current') mitelLogTableAllowSrcRouting = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelLogTableAllowSrcRouting.setStatus('current') mitelFltGrpAccessRestrictTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3), ) if mibBuilder.loadTexts: mitelFltGrpAccessRestrictTable.setStatus('current') mitelFltGrpAccessRestrictEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1), ).setIndexNames((0, "MITEL-IPFILTER-MIB", "mitelAccResTableIfIndex"), (0, "MITEL-IPFILTER-MIB", "mitelAccResTableOrder")) if mibBuilder.loadTexts: mitelFltGrpAccessRestrictEntry.setStatus('current') mitelAccResTableIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mitelAccResTableIfIndex.setStatus('current') mitelAccResTableOrder = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mitelAccResTableOrder.setStatus('current') mitelAccResTableType = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("filter", 1), ("forward", 2), ("neither", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableType.setStatus('current') mitelAccResTableSrcAddrFrom = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableSrcAddrFrom.setStatus('current') mitelAccResTableSrcAddrTo = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 5), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableSrcAddrTo.setStatus('current') mitelAccResTableSrcAddrOutsideRange = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableSrcAddrOutsideRange.setStatus('current') mitelAccResTableDstAddrFrom = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 7), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableDstAddrFrom.setStatus('current') mitelAccResTableDstAddrTo = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 8), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableDstAddrTo.setStatus('current') mitelAccResTableDstAddrOutsideRange = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableDstAddrOutsideRange.setStatus('current') mitelAccResTableProtocolFrom = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableProtocolFrom.setStatus('current') mitelAccResTableProtocolTo = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableProtocolTo.setStatus('current') mitelAccResTableProtocolOutsideRange = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableProtocolOutsideRange.setStatus('current') mitelAccResTableSrcPortFrom = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableSrcPortFrom.setStatus('current') mitelAccResTableSrcPortTo = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableSrcPortTo.setStatus('current') mitelAccResTableSrcPortOutsideRange = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableSrcPortOutsideRange.setStatus('current') mitelAccResTableDstPortFrom = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 16), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableDstPortFrom.setStatus('current') mitelAccResTableDstPortTo = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableDstPortTo.setStatus('current') mitelAccResTableDstPortOutsideRange = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableDstPortOutsideRange.setStatus('current') mitelAccResTableTcpSyn = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("any", 1), ("zero", 2), ("one", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableTcpSyn.setStatus('current') mitelAccResTableTcpAck = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("any", 1), ("zero", 2), ("one", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableTcpAck.setStatus('current') mitelAccResTableTcpFin = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("any", 1), ("zero", 2), ("one", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableTcpFin.setStatus('current') mitelAccResTableTcpRst = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("any", 1), ("zero", 2), ("one", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableTcpRst.setStatus('current') mitelAccResTableMatchIn = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableMatchIn.setStatus('current') mitelAccResTableMatchOut = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableMatchOut.setStatus('current') mitelAccResTableLog = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableLog.setStatus('current') mitelAccResTableTrap = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mitelAccResTableTrap.setStatus('current') mitelAccResTableStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 27), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mitelAccResTableStatus.setStatus('current') mitelAccResTableCount = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 28), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mitelAccResTableCount.setStatus('current') mitelIpera1000Notifications = NotificationGroup((1, 3, 6, 1, 4, 1, 1027, 1, 2, 4, 0)).setObjects(("MITEL-IPFILTER-MIB", "mitelAccResTableTrapped")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mitelIpera1000Notifications = mitelIpera1000Notifications.setStatus('current') mitelAccResTableTrapped = NotificationType((1, 3, 6, 1, 4, 1, 1027, 1, 2, 4, 0, 402)).setObjects(("MITEL-IPFILTER-MIB", "mitelAccResTableIfIndex"), ("MITEL-IPFILTER-MIB", "mitelAccResTableOrder")) if mibBuilder.loadTexts: mitelAccResTableTrapped.setStatus('current') mibBuilder.exportSymbols("MITEL-IPFILTER-MIB", mitelAccResTableDstPortOutsideRange=mitelAccResTableDstPortOutsideRange, mitelIdCsIpera1000=mitelIdCsIpera1000, mitelAccResTableMatchIn=mitelAccResTableMatchIn, mitelAccResTableProtocolOutsideRange=mitelAccResTableProtocolOutsideRange, mitelAccResTableDstPortFrom=mitelAccResTableDstPortFrom, mitelAccResTableDstAddrFrom=mitelAccResTableDstAddrFrom, mitelAccResTableTrap=mitelAccResTableTrap, mitelAccResTableTcpSyn=mitelAccResTableTcpSyn, mitelFltGrpLogicalTable=mitelFltGrpLogicalTable, mitelAccResTableOrder=mitelAccResTableOrder, mitelAccResTableTrapped=mitelAccResTableTrapped, mitelAccResTableDstAddrTo=mitelAccResTableDstAddrTo, mitelAccResTableCount=mitelAccResTableCount, mitel=mitel, mitelIpNetRouter=mitelIpNetRouter, mitelAccResTableIfIndex=mitelAccResTableIfIndex, mitelAccResTableProtocolFrom=mitelAccResTableProtocolFrom, mitelAccResTableTcpRst=mitelAccResTableTcpRst, mitelPropIpNetworking=mitelPropIpNetworking, PYSNMP_MODULE_ID=mitelIpGrpFilterGroup, mitelIdCallServers=mitelIdCallServers, mitelAccResTableSrcPortTo=mitelAccResTableSrcPortTo, mitelAccResTableDstPortTo=mitelAccResTableDstPortTo, mitelProprietary=mitelProprietary, mitelAccResTableStatus=mitelAccResTableStatus, mitelFltGrpAccessRestrictEntry=mitelFltGrpAccessRestrictEntry, mitelAccResTableProtocolTo=mitelAccResTableProtocolTo, mitelFltGrpAccessRestrictTable=mitelFltGrpAccessRestrictTable, mitelAccResTableTcpFin=mitelAccResTableTcpFin, mitelAccResTableDstAddrOutsideRange=mitelAccResTableDstAddrOutsideRange, mitelAccResTableType=mitelAccResTableType, mitelFltGrpLogicalEntry=mitelFltGrpLogicalEntry, mitelLogTableAccessDef=mitelLogTableAccessDef, mitelRouterIpGroup=mitelRouterIpGroup, mitelAccResTableTcpAck=mitelAccResTableTcpAck, mitelIpera1000Notifications=mitelIpera1000Notifications, mitelAccResTableSrcAddrOutsideRange=mitelAccResTableSrcAddrOutsideRange, mitelIpGrpFilterGroup=mitelIpGrpFilterGroup, mitelAccResTableSrcAddrTo=mitelAccResTableSrcAddrTo, mitelAccResTableMatchOut=mitelAccResTableMatchOut, mitelLogTableAllowSrcRouting=mitelLogTableAllowSrcRouting, mitelAccResTableLog=mitelAccResTableLog, mitelAccResTableSrcPortFrom=mitelAccResTableSrcPortFrom, mitelAccResTableSrcAddrFrom=mitelAccResTableSrcAddrFrom, mitelAccResTableSrcPortOutsideRange=mitelAccResTableSrcPortOutsideRange, mitelIdentification=mitelIdentification, mitelFltGrpAccessRestrictEnable=mitelFltGrpAccessRestrictEnable)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion') (if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (integer32, ip_address, mib_identifier, bits, time_ticks, unsigned32, enterprises, notification_type, iso, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, counter64, counter32, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'IpAddress', 'MibIdentifier', 'Bits', 'TimeTicks', 'Unsigned32', 'enterprises', 'NotificationType', 'iso', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'Counter64', 'Counter32', 'ModuleIdentity') (textual_convention, display_string, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString', 'RowStatus') mitel_ip_grp_filter_group = module_identity((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1)) mitelIpGrpFilterGroup.setRevisions(('2003-03-24 09:25', '1999-03-01 00:00')) if mibBuilder.loadTexts: mitelIpGrpFilterGroup.setLastUpdated('200303240925Z') if mibBuilder.loadTexts: mitelIpGrpFilterGroup.setOrganization('MITEL Corporation') mitel = mib_identifier((1, 3, 6, 1, 4, 1, 1027)) mitel_proprietary = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4)) mitel_prop_ip_networking = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 8)) mitel_ip_net_router = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1)) mitel_router_ip_group = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1)) mitel_identification = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1)) mitel_id_call_servers = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 2)) mitel_id_cs_ipera1000 = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 2, 4)) mitel_flt_grp_access_restrict_enable = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelFltGrpAccessRestrictEnable.setStatus('current') mitel_flt_grp_logical_table = mib_table((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 2)) if mibBuilder.loadTexts: mitelFltGrpLogicalTable.setStatus('current') mitel_flt_grp_logical_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 2, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex')) if mibBuilder.loadTexts: mitelFltGrpLogicalEntry.setStatus('current') mitel_log_table_access_def = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 2, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('filter', 1), ('forward', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelLogTableAccessDef.setStatus('current') mitel_log_table_allow_src_routing = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone(2)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelLogTableAllowSrcRouting.setStatus('current') mitel_flt_grp_access_restrict_table = mib_table((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3)) if mibBuilder.loadTexts: mitelFltGrpAccessRestrictTable.setStatus('current') mitel_flt_grp_access_restrict_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1)).setIndexNames((0, 'MITEL-IPFILTER-MIB', 'mitelAccResTableIfIndex'), (0, 'MITEL-IPFILTER-MIB', 'mitelAccResTableOrder')) if mibBuilder.loadTexts: mitelFltGrpAccessRestrictEntry.setStatus('current') mitel_acc_res_table_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mitelAccResTableIfIndex.setStatus('current') mitel_acc_res_table_order = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mitelAccResTableOrder.setStatus('current') mitel_acc_res_table_type = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('filter', 1), ('forward', 2), ('neither', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableType.setStatus('current') mitel_acc_res_table_src_addr_from = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 4), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableSrcAddrFrom.setStatus('current') mitel_acc_res_table_src_addr_to = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 5), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableSrcAddrTo.setStatus('current') mitel_acc_res_table_src_addr_outside_range = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone(2)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableSrcAddrOutsideRange.setStatus('current') mitel_acc_res_table_dst_addr_from = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 7), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableDstAddrFrom.setStatus('current') mitel_acc_res_table_dst_addr_to = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 8), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableDstAddrTo.setStatus('current') mitel_acc_res_table_dst_addr_outside_range = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone(2)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableDstAddrOutsideRange.setStatus('current') mitel_acc_res_table_protocol_from = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableProtocolFrom.setStatus('current') mitel_acc_res_table_protocol_to = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 11), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableProtocolTo.setStatus('current') mitel_acc_res_table_protocol_outside_range = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone(2)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableProtocolOutsideRange.setStatus('current') mitel_acc_res_table_src_port_from = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 13), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableSrcPortFrom.setStatus('current') mitel_acc_res_table_src_port_to = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 14), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableSrcPortTo.setStatus('current') mitel_acc_res_table_src_port_outside_range = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 15), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone(2)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableSrcPortOutsideRange.setStatus('current') mitel_acc_res_table_dst_port_from = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 16), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableDstPortFrom.setStatus('current') mitel_acc_res_table_dst_port_to = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 17), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableDstPortTo.setStatus('current') mitel_acc_res_table_dst_port_outside_range = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 18), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone(2)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableDstPortOutsideRange.setStatus('current') mitel_acc_res_table_tcp_syn = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 19), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('any', 1), ('zero', 2), ('one', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableTcpSyn.setStatus('current') mitel_acc_res_table_tcp_ack = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('any', 1), ('zero', 2), ('one', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableTcpAck.setStatus('current') mitel_acc_res_table_tcp_fin = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 21), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('any', 1), ('zero', 2), ('one', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableTcpFin.setStatus('current') mitel_acc_res_table_tcp_rst = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 22), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('any', 1), ('zero', 2), ('one', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableTcpRst.setStatus('current') mitel_acc_res_table_match_in = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 23), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableMatchIn.setStatus('current') mitel_acc_res_table_match_out = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 24), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableMatchOut.setStatus('current') mitel_acc_res_table_log = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 25), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableLog.setStatus('current') mitel_acc_res_table_trap = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 26), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mitelAccResTableTrap.setStatus('current') mitel_acc_res_table_status = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 27), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: mitelAccResTableStatus.setStatus('current') mitel_acc_res_table_count = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 8, 1, 1, 1, 3, 1, 28), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mitelAccResTableCount.setStatus('current') mitel_ipera1000_notifications = notification_group((1, 3, 6, 1, 4, 1, 1027, 1, 2, 4, 0)).setObjects(('MITEL-IPFILTER-MIB', 'mitelAccResTableTrapped')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mitel_ipera1000_notifications = mitelIpera1000Notifications.setStatus('current') mitel_acc_res_table_trapped = notification_type((1, 3, 6, 1, 4, 1, 1027, 1, 2, 4, 0, 402)).setObjects(('MITEL-IPFILTER-MIB', 'mitelAccResTableIfIndex'), ('MITEL-IPFILTER-MIB', 'mitelAccResTableOrder')) if mibBuilder.loadTexts: mitelAccResTableTrapped.setStatus('current') mibBuilder.exportSymbols('MITEL-IPFILTER-MIB', mitelAccResTableDstPortOutsideRange=mitelAccResTableDstPortOutsideRange, mitelIdCsIpera1000=mitelIdCsIpera1000, mitelAccResTableMatchIn=mitelAccResTableMatchIn, mitelAccResTableProtocolOutsideRange=mitelAccResTableProtocolOutsideRange, mitelAccResTableDstPortFrom=mitelAccResTableDstPortFrom, mitelAccResTableDstAddrFrom=mitelAccResTableDstAddrFrom, mitelAccResTableTrap=mitelAccResTableTrap, mitelAccResTableTcpSyn=mitelAccResTableTcpSyn, mitelFltGrpLogicalTable=mitelFltGrpLogicalTable, mitelAccResTableOrder=mitelAccResTableOrder, mitelAccResTableTrapped=mitelAccResTableTrapped, mitelAccResTableDstAddrTo=mitelAccResTableDstAddrTo, mitelAccResTableCount=mitelAccResTableCount, mitel=mitel, mitelIpNetRouter=mitelIpNetRouter, mitelAccResTableIfIndex=mitelAccResTableIfIndex, mitelAccResTableProtocolFrom=mitelAccResTableProtocolFrom, mitelAccResTableTcpRst=mitelAccResTableTcpRst, mitelPropIpNetworking=mitelPropIpNetworking, PYSNMP_MODULE_ID=mitelIpGrpFilterGroup, mitelIdCallServers=mitelIdCallServers, mitelAccResTableSrcPortTo=mitelAccResTableSrcPortTo, mitelAccResTableDstPortTo=mitelAccResTableDstPortTo, mitelProprietary=mitelProprietary, mitelAccResTableStatus=mitelAccResTableStatus, mitelFltGrpAccessRestrictEntry=mitelFltGrpAccessRestrictEntry, mitelAccResTableProtocolTo=mitelAccResTableProtocolTo, mitelFltGrpAccessRestrictTable=mitelFltGrpAccessRestrictTable, mitelAccResTableTcpFin=mitelAccResTableTcpFin, mitelAccResTableDstAddrOutsideRange=mitelAccResTableDstAddrOutsideRange, mitelAccResTableType=mitelAccResTableType, mitelFltGrpLogicalEntry=mitelFltGrpLogicalEntry, mitelLogTableAccessDef=mitelLogTableAccessDef, mitelRouterIpGroup=mitelRouterIpGroup, mitelAccResTableTcpAck=mitelAccResTableTcpAck, mitelIpera1000Notifications=mitelIpera1000Notifications, mitelAccResTableSrcAddrOutsideRange=mitelAccResTableSrcAddrOutsideRange, mitelIpGrpFilterGroup=mitelIpGrpFilterGroup, mitelAccResTableSrcAddrTo=mitelAccResTableSrcAddrTo, mitelAccResTableMatchOut=mitelAccResTableMatchOut, mitelLogTableAllowSrcRouting=mitelLogTableAllowSrcRouting, mitelAccResTableLog=mitelAccResTableLog, mitelAccResTableSrcPortFrom=mitelAccResTableSrcPortFrom, mitelAccResTableSrcAddrFrom=mitelAccResTableSrcAddrFrom, mitelAccResTableSrcPortOutsideRange=mitelAccResTableSrcPortOutsideRange, mitelIdentification=mitelIdentification, mitelFltGrpAccessRestrictEnable=mitelFltGrpAccessRestrictEnable)
def title(string, rng, color=0): """ --> Function to create a title in the project. :param string: Written part of the title. :param rng: Title range. :param color: Title color. (30 = White; 31 = Red; 32 = Green; 33 = Yellow; 34 = Blue; 35 = Purple; 36 = Cyan; 37 = Grey) :return: Nothing. """ print(f'\033[{color}m-' * rng) print(f'{string:^{rng}}') print(f'\033[{color}m-\033[m' * rng) def inputInt(string=''): """ --> Function to read a int number. :param string: Written part. :return: The int number. """ a = input(string) while True: try: int(a) except ValueError: a = input(f'\033[31m[ERROR]\033[m {string}') except KeyboardInterrupt: print('The user chooses not to provide all data.') return 0 else: break return int(a) def inputFloat(string=''): """ --> Function to read a float number. :param string: Written part. :return: The float number. """ a = input(string) while True: a = a.replace(',', '.') try: float(a) except ValueError: a = input(f'\033[31m[ERROR]\033[m {string}') except KeyboardInterrupt: print('The user chooses not to provide all data.') return 0 else: break return float(a) def inputName(string=''): """ --> Function to read a person's name. :param string: Written part. :return: The name. """ a = input(string) while not a.replace(' ', '').isalpha(): a = input(f'\033[31m[ERROR]\033[m {string}') return a.title().strip() def menu(lst, ttl='MENU', rng=50, color=0, numColor=33, itColor=34): """ --> Function to create a menu in the program. :param lst: List with the options. :param ttl: Title. :param rng: Title range. :param numColor: Color of the numbers. :param itColor: Color of the options. :param color: Title color. (30 = White; 31 = Red; 32 = Green; 33 = Yellow; 34 = Blue; 35 = Purple; 36 = Cyan; 37 = Grey) :return: Nothing """ title(ttl, rng, color) c = 1 for items in lst: print(f'\033[{numColor}m{c} - \033[{itColor}m{items}\033[m') c += 1 print(f'\033[{color}m-\033[m'*rng) def readArch(name): """ --> Function to read a .txt archive. :param name: Archive name. :return: Nothing. """ try: a = open(name, 'rt') except FileNotFoundError: print('\033[31mArchive not found!\033[m') else: print(a.read()) a.close()
def title(string, rng, color=0): """ --> Function to create a title in the project. :param string: Written part of the title. :param rng: Title range. :param color: Title color. (30 = White; 31 = Red; 32 = Green; 33 = Yellow; 34 = Blue; 35 = Purple; 36 = Cyan; 37 = Grey) :return: Nothing. """ print(f'\x1b[{color}m-' * rng) print(f'{string:^{rng}}') print(f'\x1b[{color}m-\x1b[m' * rng) def input_int(string=''): """ --> Function to read a int number. :param string: Written part. :return: The int number. """ a = input(string) while True: try: int(a) except ValueError: a = input(f'\x1b[31m[ERROR]\x1b[m {string}') except KeyboardInterrupt: print('The user chooses not to provide all data.') return 0 else: break return int(a) def input_float(string=''): """ --> Function to read a float number. :param string: Written part. :return: The float number. """ a = input(string) while True: a = a.replace(',', '.') try: float(a) except ValueError: a = input(f'\x1b[31m[ERROR]\x1b[m {string}') except KeyboardInterrupt: print('The user chooses not to provide all data.') return 0 else: break return float(a) def input_name(string=''): """ --> Function to read a person's name. :param string: Written part. :return: The name. """ a = input(string) while not a.replace(' ', '').isalpha(): a = input(f'\x1b[31m[ERROR]\x1b[m {string}') return a.title().strip() def menu(lst, ttl='MENU', rng=50, color=0, numColor=33, itColor=34): """ --> Function to create a menu in the program. :param lst: List with the options. :param ttl: Title. :param rng: Title range. :param numColor: Color of the numbers. :param itColor: Color of the options. :param color: Title color. (30 = White; 31 = Red; 32 = Green; 33 = Yellow; 34 = Blue; 35 = Purple; 36 = Cyan; 37 = Grey) :return: Nothing """ title(ttl, rng, color) c = 1 for items in lst: print(f'\x1b[{numColor}m{c} - \x1b[{itColor}m{items}\x1b[m') c += 1 print(f'\x1b[{color}m-\x1b[m' * rng) def read_arch(name): """ --> Function to read a .txt archive. :param name: Archive name. :return: Nothing. """ try: a = open(name, 'rt') except FileNotFoundError: print('\x1b[31mArchive not found!\x1b[m') else: print(a.read()) a.close()
# Name: Yahya Eldarieby # Course: CS30 # Date: 01/10/2019 # Description: RPG Pseudocode # A text based game following the demo at: https://www.youtube.com/watch?v=higMRrO5AkU # Start # Display a welcoming branding image # Pick an intial location for snake # Pick an initial location for fruits and obstacles # Forever Loop # x = Get user input # if(x) = Key A then press enter then the snake will move left # if(x) = Key D then press enter then the snake will move right # if(x) = Key W then press enter then the snake will move up # if(x) = Key S then press enter then the snake will move down # if(x) = Key Q then press enter to quit the whole system # if(x) = Key H then press enter to restart the whole game # If new location has a fruit, then score increases by 10 # If new location has a obstacle, then the snake dies and the system quits the whole game. # End of forever loop # End of program # The following is a description of the game rules to be displayed at the start of the game print ("# Explanation of game") print ("The game works by you being a snake and that same snake has to eat fruits to increase your score and there will be obstacles in your way to make you lose.") print ("# How will you survive") print ("You will survive the game by avoiding the obstacles and by avoiding hitting the boarders.") print ("# How to play the game") print ("You simply just use the keys W, A, S, D to move up, down, right and left.") print ("# How will you win the game") print ("You will win the game by reaching the GOAL box." ) print ("# How does the game end") print ("The game will be over if you hit the boarders and if any of the obstacles hit you.") print ("# How do you enjoy the game") print ("To enjoy the game you have to try to focus on what steps you're taking to reach your goal.") print ("# System Quit") print ("To quit the whole system press the key Q then hit enter to quit the whole system.")
print('# Explanation of game') print('The game works by you being a snake and that same snake has to eat fruits to increase your score and there will be obstacles in your way to make you lose.') print('# How will you survive') print('You will survive the game by avoiding the obstacles and by avoiding hitting the boarders.') print('# How to play the game') print('You simply just use the keys W, A, S, D to move up, down, right and left.') print('# How will you win the game') print('You will win the game by reaching the GOAL box.') print('# How does the game end') print('The game will be over if you hit the boarders and if any of the obstacles hit you.') print('# How do you enjoy the game') print("To enjoy the game you have to try to focus on what steps you're taking to reach your goal.") print('# System Quit') print('To quit the whole system press the key Q then hit enter to quit the whole system.')
class NotAllowedException(Exception): pass class CannotDeleteLoadedItem(Exception): pass class UnknownUserException(Exception): pass class UnknownLoanItemException(Exception): pass class InitialAdminRoleException(Exception): pass class InvalidTokenException(Exception): pass class InvalidRequestException(Exception): pass class UserAlreadyExistsException(Exception): pass
class Notallowedexception(Exception): pass class Cannotdeleteloadeditem(Exception): pass class Unknownuserexception(Exception): pass class Unknownloanitemexception(Exception): pass class Initialadminroleexception(Exception): pass class Invalidtokenexception(Exception): pass class Invalidrequestexception(Exception): pass class Useralreadyexistsexception(Exception): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- MESSAGE_INDENT_NUM = 'indent steps must be {} multiples' MESSAGE_DUPLICATED_SPACE = 'too many spaces' MESSAGE_COMMA_HEAD = 'comma must be head of line' MESSAGE_COMMA_END = 'comma must be end of line' MESSAGE_WHITESPACE_AFTER_COMMA = 'whitespace must be after comma: ,' MESSAGE_WHITESPACE_BEFORE_COMMA = 'whitespace must not be before comma: ,' MESSAGE_WHITESPACE_AFTER_BRACKET = 'whitespace must not be after bracket: (' MESSAGE_WHITESPACE_BEFORE_BRACKET = 'whitespace must not be before bracket: )' MESSAGE_WHITESPACE_AFTER_OPERATOR = 'whitespace must be after binary operator' MESSAGE_WHITESPACE_BEFORE_OPERATOR = 'whitespace must be after binary operator' MESSAGE_KEYWORD_UPPER = 'reserved keywords must be upper case' MESSAGE_KEYWORD_LOWER = 'reserved keywords must be lower case' MESSAGE_JOIN_TABLE = 'table_name must be at the same line as join context' MESSAGE_JOIN_CONTEXT = 'join context must be [left outer join], [inner join] or [cross join]' MESSAGE_BREAK_LINE = 'break line at \'and\', \'or\', \'on\''
message_indent_num = 'indent steps must be {} multiples' message_duplicated_space = 'too many spaces' message_comma_head = 'comma must be head of line' message_comma_end = 'comma must be end of line' message_whitespace_after_comma = 'whitespace must be after comma: ,' message_whitespace_before_comma = 'whitespace must not be before comma: ,' message_whitespace_after_bracket = 'whitespace must not be after bracket: (' message_whitespace_before_bracket = 'whitespace must not be before bracket: )' message_whitespace_after_operator = 'whitespace must be after binary operator' message_whitespace_before_operator = 'whitespace must be after binary operator' message_keyword_upper = 'reserved keywords must be upper case' message_keyword_lower = 'reserved keywords must be lower case' message_join_table = 'table_name must be at the same line as join context' message_join_context = 'join context must be [left outer join], [inner join] or [cross join]' message_break_line = "break line at 'and', 'or', 'on'"
def max_sum(d): res = d[0] max_i = 0 max_j = 1 i = 0 j = 0 max_count = 0 for item in d: max_count += item j += 1 if max_count > res: res = max_count max_i, max_j = i, j if max_count <= 0: max_count = 0 i = j return res, max_i, max_j if __name__ == '__main__': print(max_sum([-2, 11, -4, 13, -5, -2]))
def max_sum(d): res = d[0] max_i = 0 max_j = 1 i = 0 j = 0 max_count = 0 for item in d: max_count += item j += 1 if max_count > res: res = max_count (max_i, max_j) = (i, j) if max_count <= 0: max_count = 0 i = j return (res, max_i, max_j) if __name__ == '__main__': print(max_sum([-2, 11, -4, 13, -5, -2]))
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/Analog.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/Digital.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/IOStates.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/RobotStateRTMsg.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/MasterboardDataMsg.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/RobotModeDataMsg.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/ToolDataMsg.msg" services_str = "/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/srv/SetPayload.srv;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/srv/SetSpeedSliderFraction.srv;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/srv/SetIO.srv" pkg_name = "ur_msgs" dependencies_str = "std_msgs;geometry_msgs" langs = "gencpp;geneus;genlisp;gennodejs;genpy" dep_include_paths_str = "ur_msgs;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg;std_msgs;/opt/ros/melodic/share/std_msgs/cmake/../msg;geometry_msgs;/opt/ros/melodic/share/geometry_msgs/cmake/../msg" PYTHON_EXECUTABLE = "/usr/bin/python2" package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = "/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
messages_str = '/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/Analog.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/Digital.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/IOStates.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/RobotStateRTMsg.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/MasterboardDataMsg.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/RobotModeDataMsg.msg;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg/ToolDataMsg.msg' services_str = '/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/srv/SetPayload.srv;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/srv/SetSpeedSliderFraction.srv;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/srv/SetIO.srv' pkg_name = 'ur_msgs' dependencies_str = 'std_msgs;geometry_msgs' langs = 'gencpp;geneus;genlisp;gennodejs;genpy' dep_include_paths_str = 'ur_msgs;/home/krzysztof/Repos/ur3e-ird435-rg2/catkin_ws/src/fmauch_universal_robot/ur_msgs/msg;std_msgs;/opt/ros/melodic/share/std_msgs/cmake/../msg;geometry_msgs;/opt/ros/melodic/share/geometry_msgs/cmake/../msg' python_executable = '/usr/bin/python2' package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = '/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py'
""" Utilities for working with arrays of timestamps Generally, i = index, T = array of ordered timestamps, t = timestamp """ def get_closest_index(i1, i2, T, t0): """ Returns the index i such that abs(T[i]-t0) is minimum for i1,i2 """ if abs(T[i1]-t0) <= abs(T[i2]-t0): return i1 else: return i2 def get_interval(T, i, n): """ Returns a 3-tuple (T[i], T[i+n], bounds_exceeded) where -inf < n < inf and bounds_exceeded is -1 or +1 if exceeded left or right respectively. """ bounds_exceeded = 0 last_T_idx = len(T)-1 if i+n > last_T_idx: bounds_exceeded = 1 elif i+n < 0: bounds_exceeded = -1 if n >= 0: return (T[i], T[min(i+n,last_T_idx)], bounds_exceeded) else: return (T[max(0,i+n)], T[i], bounds_exceeded) def combine_intervals(I1, I2): """ Return a 2-tuple of timestamps (I1[0], I2[1]). """ return (I1[0], I2[1])
""" Utilities for working with arrays of timestamps Generally, i = index, T = array of ordered timestamps, t = timestamp """ def get_closest_index(i1, i2, T, t0): """ Returns the index i such that abs(T[i]-t0) is minimum for i1,i2 """ if abs(T[i1] - t0) <= abs(T[i2] - t0): return i1 else: return i2 def get_interval(T, i, n): """ Returns a 3-tuple (T[i], T[i+n], bounds_exceeded) where -inf < n < inf and bounds_exceeded is -1 or +1 if exceeded left or right respectively. """ bounds_exceeded = 0 last_t_idx = len(T) - 1 if i + n > last_T_idx: bounds_exceeded = 1 elif i + n < 0: bounds_exceeded = -1 if n >= 0: return (T[i], T[min(i + n, last_T_idx)], bounds_exceeded) else: return (T[max(0, i + n)], T[i], bounds_exceeded) def combine_intervals(I1, I2): """ Return a 2-tuple of timestamps (I1[0], I2[1]). """ return (I1[0], I2[1])
def FordFulkerson(graph,start,end): n = len(graph) GPrime = [[None]*n for _ in range(n)] for v in range(n): for u, w in graph[v]: GPrime[v][u] = w for v in range(n): for u in range(n): if GPrime[v][u] != None and GPrime[u][v] == None: GPrime[u][v] = 0 def dfs(): stop = [False] minimum = [float("inf")] visited = [False]*n def _dfs(current): if current == end: stop[0] = True return visited[current] = True mini = minimum[0] for i, w in enumerate(GPrime[current]): if w != None and not visited[i] and w != 0: minimum[0] = min(minimum[0],w) _dfs(i) if not stop[0]: minimum[0] = mini else: GPrime[current][i] -= minimum[0] GPrime[i][current] += minimum[0] break _dfs(start) return minimum[0], stop[0] peakFlow = 0 while True: minCapacity, wasReached = dfs() if not wasReached: break peakFlow += minCapacity return peakFlow #graph, _ = readAdjl("FordFullkerson.txt",weighted=True) graph = [[(1, 16), (3, 13)], [(2, 12), (3, 10)], [(3, 9), (5, 20)], [(1, 4), (4, 14)], [(2, 7), (5, 4)], []] print(FordFulkerson(graph,0,5))
def ford_fulkerson(graph, start, end): n = len(graph) g_prime = [[None] * n for _ in range(n)] for v in range(n): for (u, w) in graph[v]: GPrime[v][u] = w for v in range(n): for u in range(n): if GPrime[v][u] != None and GPrime[u][v] == None: GPrime[u][v] = 0 def dfs(): stop = [False] minimum = [float('inf')] visited = [False] * n def _dfs(current): if current == end: stop[0] = True return visited[current] = True mini = minimum[0] for (i, w) in enumerate(GPrime[current]): if w != None and (not visited[i]) and (w != 0): minimum[0] = min(minimum[0], w) _dfs(i) if not stop[0]: minimum[0] = mini else: GPrime[current][i] -= minimum[0] GPrime[i][current] += minimum[0] break _dfs(start) return (minimum[0], stop[0]) peak_flow = 0 while True: (min_capacity, was_reached) = dfs() if not wasReached: break peak_flow += minCapacity return peakFlow graph = [[(1, 16), (3, 13)], [(2, 12), (3, 10)], [(3, 9), (5, 20)], [(1, 4), (4, 14)], [(2, 7), (5, 4)], []] print(ford_fulkerson(graph, 0, 5))
class AbstractCodeGen(object): def genCode(self, ast, symbolTable, **kwargs): raise NotImplementedError() def genIndex(self, mibsMap, **kwargs): raise NotImplementedError()
class Abstractcodegen(object): def gen_code(self, ast, symbolTable, **kwargs): raise not_implemented_error() def gen_index(self, mibsMap, **kwargs): raise not_implemented_error()
z = 100 while z > 10: a, b = input().split(" ") a = int(a) b = int(b) if a < b : print("Crescente") elif b < a: print("Decrescente") elif a == b: exit()
z = 100 while z > 10: (a, b) = input().split(' ') a = int(a) b = int(b) if a < b: print('Crescente') elif b < a: print('Decrescente') elif a == b: exit()
def main(): palindrome = [it1*it2 for it1 in range(100,1000) for it2 in range(it1,1000) if str(it1*it2)==str(it1*it2)[::-1]] for tc in range(int(input())): N = int(input()) print(max(filter(lambda x: x<N,palindrome))) if __name__=="__main__": main()
def main(): palindrome = [it1 * it2 for it1 in range(100, 1000) for it2 in range(it1, 1000) if str(it1 * it2) == str(it1 * it2)[::-1]] for tc in range(int(input())): n = int(input()) print(max(filter(lambda x: x < N, palindrome))) if __name__ == '__main__': main()
""" This uses test262 to test the interpreter """ # pylint: disable=relative-beyond-top-level, protected-access, no-self-use, missing-function-docstring, missing-class-docstring class Test262: def test_one(self): assert True, "This parses!"
""" This uses test262 to test the interpreter """ class Test262: def test_one(self): assert True, 'This parses!'
print("Starting adding") total = [1] base = 2 power = 1000 for i in range(0, power): for i in range(0, len(total)): total[i] *= base carrier = 0 for i in range(0, len(total)): total[i] += carrier head = total[i] % 10 carrier = (total[i] - head) / 10 total[i] = int(head) while carrier != 0: head = carrier % 10; carrier = (carrier - head) / 10 total.append(int(head)) totalTemp = total[::-1] print("Inbetween sum: ", end="") for i in range(0, len(totalTemp)): print(totalTemp[i], end="") print() totalSum = 0 for c in total: totalSum += c print(totalSum)
print('Starting adding') total = [1] base = 2 power = 1000 for i in range(0, power): for i in range(0, len(total)): total[i] *= base carrier = 0 for i in range(0, len(total)): total[i] += carrier head = total[i] % 10 carrier = (total[i] - head) / 10 total[i] = int(head) while carrier != 0: head = carrier % 10 carrier = (carrier - head) / 10 total.append(int(head)) total_temp = total[::-1] print('Inbetween sum: ', end='') for i in range(0, len(totalTemp)): print(totalTemp[i], end='') print() total_sum = 0 for c in total: total_sum += c print(totalSum)
# LC 735 class Solution: def collide(self, a: int, b:int) -> int: if abs(a) == abs(b): return None res = max(abs(a),abs(b)) if abs(a) < abs(b): res *= (b // abs(b)) else: res *= (a // abs(a)) return res def asteroidCollision(self, asteroids: List[int]) -> List[int]: if not len(asteroids): return asteroids stack = [] for i in asteroids: if not stack: stack.append(i) else: if stack[-1] ^ i > 0: stack.append(i) # no collision else: curr = i while stack and stack[-1] ^ curr < 0: if stack[-1] < curr: break curr = self.collide(i, stack.pop(-1)) if not curr: break if curr: stack.append(curr) return stack
class Solution: def collide(self, a: int, b: int) -> int: if abs(a) == abs(b): return None res = max(abs(a), abs(b)) if abs(a) < abs(b): res *= b // abs(b) else: res *= a // abs(a) return res def asteroid_collision(self, asteroids: List[int]) -> List[int]: if not len(asteroids): return asteroids stack = [] for i in asteroids: if not stack: stack.append(i) elif stack[-1] ^ i > 0: stack.append(i) else: curr = i while stack and stack[-1] ^ curr < 0: if stack[-1] < curr: break curr = self.collide(i, stack.pop(-1)) if not curr: break if curr: stack.append(curr) return stack
with open('c:\\mine\\No.txt') as noTxt: with open('c:\\mine\\number.txt','w') as numberTxt: for line in noTxt: nos = line.split(',') start,end = int(nos[0]), int(nos[1]) for i in range(start, end): numberTxt.write(str(i) + '\n')
with open('c:\\mine\\No.txt') as no_txt: with open('c:\\mine\\number.txt', 'w') as number_txt: for line in noTxt: nos = line.split(',') (start, end) = (int(nos[0]), int(nos[1])) for i in range(start, end): numberTxt.write(str(i) + '\n')
lines = open("input").read().strip().splitlines() # lines = """ # ..##....... # #...#...#.. # .#....#..#. # ..#.#...#.# # .#...##..#. # ..#.##..... # .#.#.#....# # .#........# # #.##...#... # #...##....# # .#..#...#.# # """.strip().splitlines() def p1(): TREE = "#" pos = [0, 0] trees = 0 while True: pos[0] += 3 pos[1] += 1 x, y = pos try: if lines[y][x % len(lines[0])] == TREE: trees += 1 except IndexError: break print(trees) p1() def p2(): TREE = "#" ans = 1 for slope in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]: pos = [0, 0] trees = 0 while True: pos[0] += slope[0] pos[1] += slope[1] x, y = pos try: if lines[y][x % len(lines[0])] == TREE: trees += 1 except IndexError: print(x, y, trees) break ans *= trees print(ans) p2()
lines = open('input').read().strip().splitlines() def p1(): tree = '#' pos = [0, 0] trees = 0 while True: pos[0] += 3 pos[1] += 1 (x, y) = pos try: if lines[y][x % len(lines[0])] == TREE: trees += 1 except IndexError: break print(trees) p1() def p2(): tree = '#' ans = 1 for slope in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]: pos = [0, 0] trees = 0 while True: pos[0] += slope[0] pos[1] += slope[1] (x, y) = pos try: if lines[y][x % len(lines[0])] == TREE: trees += 1 except IndexError: print(x, y, trees) break ans *= trees print(ans) p2()
#!/usr/bin/env python #------------------------------------------------------------------------------- # # Shared utilities # # Author: Martin Paces <martin.paces@eox.at> # #------------------------------------------------------------------------------- # Copyright (C) 2016 EOX IT Services GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies of this Software or works derived from this Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #------------------------------------------------------------------------------- class Progress(object): """ Simple CLI progress indicator. """ # pylint: disable=too-few-public-methods PROGRES_STRING = [ '0', '.', '.', '.', '10', '.', '.', '.', '20', '.', '.', '.', '30', '.', '.', '.', '40', '.', '.', '.', '50', '.', '.', '.', '60', '.', '.', '.', '70', '.', '.', '.', '80', '.', '.', '.', '90', '.', '.', '.', '100\n' ] def __init__(self, fout, final=100): self._fout = fout # output file-stream self._final = final # final progress limit self._scale = (len(self.PROGRES_STRING) - 1) / float(final) self._current = 0 # current progress self._strpos = 0 # position in the progress string def update(self, increment=1): """ Update the progress output. """ self._current = min(self._final, self._current + increment) new_strpos = 1 + int(round(self._current * self._scale)) self._fout.write("".join(self.PROGRES_STRING[self._strpos:new_strpos])) self._fout.flush() self._strpos = new_strpos class FormatOptions(dict): """ Helper class holding GDAL format options. """ def __init__(self, options=None): dict.__init__(self, options) def set_option(self, option): """ Parse and set one option. """ key, val = option.split("=") self[key.strip()] = val.strip() def set_options(self, options): """ Parse and set multiple options. """ for option in options: self.set_option(option) @property def options(self): """ Parse and set multiple options. """ return ["%s=%s" % (key, val) for key, val in self.iteritems()]
class Progress(object): """ Simple CLI progress indicator. """ progres_string = ['0', '.', '.', '.', '10', '.', '.', '.', '20', '.', '.', '.', '30', '.', '.', '.', '40', '.', '.', '.', '50', '.', '.', '.', '60', '.', '.', '.', '70', '.', '.', '.', '80', '.', '.', '.', '90', '.', '.', '.', '100\n'] def __init__(self, fout, final=100): self._fout = fout self._final = final self._scale = (len(self.PROGRES_STRING) - 1) / float(final) self._current = 0 self._strpos = 0 def update(self, increment=1): """ Update the progress output. """ self._current = min(self._final, self._current + increment) new_strpos = 1 + int(round(self._current * self._scale)) self._fout.write(''.join(self.PROGRES_STRING[self._strpos:new_strpos])) self._fout.flush() self._strpos = new_strpos class Formatoptions(dict): """ Helper class holding GDAL format options. """ def __init__(self, options=None): dict.__init__(self, options) def set_option(self, option): """ Parse and set one option. """ (key, val) = option.split('=') self[key.strip()] = val.strip() def set_options(self, options): """ Parse and set multiple options. """ for option in options: self.set_option(option) @property def options(self): """ Parse and set multiple options. """ return ['%s=%s' % (key, val) for (key, val) in self.iteritems()]
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ if not root: return root if L <= root.val <= R: root.left = self.trimBST(root.left,L,R) root.right = self.trimBST(root.right,L,R) elif root.val < L: root = self.trimBST(root.right,L,R) elif root.val > R: root = self.trimBST(root.left,L,R) return root if __name__ == '__main__': s = Solution()
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def trim_bst(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ if not root: return root if L <= root.val <= R: root.left = self.trimBST(root.left, L, R) root.right = self.trimBST(root.right, L, R) elif root.val < L: root = self.trimBST(root.right, L, R) elif root.val > R: root = self.trimBST(root.left, L, R) return root if __name__ == '__main__': s = solution()
def GLSL_type(a): if(isinstance(a, str)): return "int["+str(len(a))+"]" elif(isinstance(a, list)): return GLSL_type(a)+"["+str(len(a))+"]" elif(type(a) == bool): return "bool"
def glsl_type(a): if isinstance(a, str): return 'int[' + str(len(a)) + ']' elif isinstance(a, list): return glsl_type(a) + '[' + str(len(a)) + ']' elif type(a) == bool: return 'bool'
{ "targets": [ { "target_name": "roo", "sources": [ "./src/c/roo/roo.c", "./src/c/roo/roo_node.c", "./src/c/roo/callbacks.c", "./src/c/roo/startup.c", "./src/c/roo/interface.c", "./src/c/roo/log.c", "./src/c/roo/plugin.c", "./src/c/roo/map.c", "./src/c/roo/lane.c", "./src/c/roo/operations.c"], "libraries": ["-ljack", "-lcarla_standalone2", "-llilv-0"], "include_dirs": ["/usr/include/carla", "/usr/include/carla/includes"] } ] }
{'targets': [{'target_name': 'roo', 'sources': ['./src/c/roo/roo.c', './src/c/roo/roo_node.c', './src/c/roo/callbacks.c', './src/c/roo/startup.c', './src/c/roo/interface.c', './src/c/roo/log.c', './src/c/roo/plugin.c', './src/c/roo/map.c', './src/c/roo/lane.c', './src/c/roo/operations.c'], 'libraries': ['-ljack', '-lcarla_standalone2', '-llilv-0'], 'include_dirs': ['/usr/include/carla', '/usr/include/carla/includes']}]}
""" Defines an instance of stock which is cut to produce needed pieces.""" class Stock(object): """ Defines a piece of stock, including planned cuts """ def __init__(self, length): self.pieces = [] self.length = length self.remaining_length = length def __str__(self): pieces = ", ".join([str(p.length) for p in self.pieces]) return "Stock: len={0}, remaining:{1} pieces: {2}".format( self.length, self.remaining_length, pieces) @property def used_length(self): """ Returns the length of stock already assigned for cuts.""" return self.length - self.remaining_length def cut(self, piece, loss=0.0): """ Cut given amount from this stock """ if (loss + piece.length) > self.remaining_length: raise ValueError("Stock too small to cut piece") self.pieces.append(piece) self.remaining_length -= (loss + piece.length) return self.remaining_length def shrink(self, new_length): """ Attempt to reduce stock size, to minimize waste when possible. """ if new_length < self.used_length: return None self.remaining_length = new_length - self.used_length self.length = new_length return new_length
""" Defines an instance of stock which is cut to produce needed pieces.""" class Stock(object): """ Defines a piece of stock, including planned cuts """ def __init__(self, length): self.pieces = [] self.length = length self.remaining_length = length def __str__(self): pieces = ', '.join([str(p.length) for p in self.pieces]) return 'Stock: len={0}, remaining:{1} pieces: {2}'.format(self.length, self.remaining_length, pieces) @property def used_length(self): """ Returns the length of stock already assigned for cuts.""" return self.length - self.remaining_length def cut(self, piece, loss=0.0): """ Cut given amount from this stock """ if loss + piece.length > self.remaining_length: raise value_error('Stock too small to cut piece') self.pieces.append(piece) self.remaining_length -= loss + piece.length return self.remaining_length def shrink(self, new_length): """ Attempt to reduce stock size, to minimize waste when possible. """ if new_length < self.used_length: return None self.remaining_length = new_length - self.used_length self.length = new_length return new_length
"""Factories for the leapmotion app.""" # import factory # from ..models import YourModel
"""Factories for the leapmotion app."""
num = 1 for i in range(16): print(num<<i, end=', ') print(); print() for i in range(16): print('0x%x'%(num<<i), end=',')
num = 1 for i in range(16): print(num << i, end=', ') print() print() for i in range(16): print('0x%x' % (num << i), end=',')
x=[] for i in range(20): val=int(input()) x.append(val) x.reverse() for k in range(20): print("N[{}] = {}".format(k,x[k]))
x = [] for i in range(20): val = int(input()) x.append(val) x.reverse() for k in range(20): print('N[{}] = {}'.format(k, x[k]))
def swap(a, b): #function logic print("Original: ",a, b) if (a > b or a < b): #doing the swap when the two numbers aren't equal temp = a a = b b = temp print("Swapped: ",a, b) else: #just returning the numbers in same order b/c they're equal, no need to swap print("No swap: ",a, b) def driver(): # setting parameters for different decisions by function swap(10, 1) swap(5,5) swap(3,7) swap("aaa", "aaa") swap("aaa", "bbb") swap("bbb", "aaa") if __name__ == "__main__": driver()
def swap(a, b): print('Original: ', a, b) if a > b or a < b: temp = a a = b b = temp print('Swapped: ', a, b) else: print('No swap: ', a, b) def driver(): swap(10, 1) swap(5, 5) swap(3, 7) swap('aaa', 'aaa') swap('aaa', 'bbb') swap('bbb', 'aaa') if __name__ == '__main__': driver()
def rank(graph, res): rank_page= {} for page in res.keys(): word_count=res[page] ingoing=graph.ingoing_links(page) num_links=len(ingoing) num_in_links=0 for link in ingoing: if link in res.keys(): num_in_links+=res[link] rank_page[page]=int(word_count+num_links*0.6 +num_in_links*0.2) #4print(rank_page) return rank_page
def rank(graph, res): rank_page = {} for page in res.keys(): word_count = res[page] ingoing = graph.ingoing_links(page) num_links = len(ingoing) num_in_links = 0 for link in ingoing: if link in res.keys(): num_in_links += res[link] rank_page[page] = int(word_count + num_links * 0.6 + num_in_links * 0.2) return rank_page
class Student(object): """docstring for Student""" def __init__(self, name,score,*age): self.__name = name self.__score = score def print_score(self): print('%s: %s'% (self.__name,self.__score)) def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self,score): if 0 <= score <= 100: self.__score = score else: raise ValueError('bad score') def get_grade(self): if self.__score >= 90: return 'A' elif self.__score >= 60: return 'B' else: return 'C' bart = Student('Bart Simpson',59,9) bart.age = 8 print(bart.age) lisa = Student('Lisa Simpson',87) bart.print_score() lisa.print_score() print(bart.get_grade()) print(lisa.get_score()) lisa.__name = 'New Name' print(lisa.get_name())
class Student(object): """docstring for Student""" def __init__(self, name, score, *age): self.__name = name self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self, score): if 0 <= score <= 100: self.__score = score else: raise value_error('bad score') def get_grade(self): if self.__score >= 90: return 'A' elif self.__score >= 60: return 'B' else: return 'C' bart = student('Bart Simpson', 59, 9) bart.age = 8 print(bart.age) lisa = student('Lisa Simpson', 87) bart.print_score() lisa.print_score() print(bart.get_grade()) print(lisa.get_score()) lisa.__name = 'New Name' print(lisa.get_name())
# Write a program which replaces all vowels in the string with '*' str=input('enter the string : ') str2='aeiou' str3='AEIOU' l=len(str) str4='' for x in str: if x in str2 or x in str3: str4=str4+'*' else: str4=str4+x print(str4)
str = input('enter the string : ') str2 = 'aeiou' str3 = 'AEIOU' l = len(str) str4 = '' for x in str: if x in str2 or x in str3: str4 = str4 + '*' else: str4 = str4 + x print(str4)
## CONSTRUCTING GRAPH v, e = map(int, raw_input().split()) grafo = [[] for i in range(v+1)] for i in range(e): v1, v2, w = map(int, raw_input().split()) # save edges that are getting in me, not edges from me to another v grafo[v2].append((v1, w)) ## INITIALIZING beginning = input() dp = [[float('inf') for i in range(v+1)] for j in range(v+1)] for i in range(v+1): dp[i][beginning] = 0 ## BELLMAN-FORD MAIN for i in range(1, v+1, 1): for j in range(1, v+1, 1): sub_paths = [float('inf')] for adj in grafo[j]: adj_index = adj[0] adj_weigth = adj[1] sub_paths.append( dp[i-1][adj_index] + adj_weigth ) min_weigth_sub_path = min(sub_paths) dp[i][j] = min(dp[i-1][j], min_weigth_sub_path)
(v, e) = map(int, raw_input().split()) grafo = [[] for i in range(v + 1)] for i in range(e): (v1, v2, w) = map(int, raw_input().split()) grafo[v2].append((v1, w)) beginning = input() dp = [[float('inf') for i in range(v + 1)] for j in range(v + 1)] for i in range(v + 1): dp[i][beginning] = 0 for i in range(1, v + 1, 1): for j in range(1, v + 1, 1): sub_paths = [float('inf')] for adj in grafo[j]: adj_index = adj[0] adj_weigth = adj[1] sub_paths.append(dp[i - 1][adj_index] + adj_weigth) min_weigth_sub_path = min(sub_paths) dp[i][j] = min(dp[i - 1][j], min_weigth_sub_path)
LINE_COLORS = [ (255, 127, 127), (255, 127, 182), (102, 51, 73), (214, 127, 255), (85, 51, 102), (161, 127, 255), (63, 51, 102), (127, 146, 255), (51, 58, 102), (127, 201, 255), (51, 80, 102), (127, 255, 197), (51, 102, 78), (127, 255, 142), (51, 102, 56), (165, 255, 127), (66, 102, 51), (218, 255, 127), (87, 102, 51), (255, 233, 127), (102, 92, 51), (255, 178, 127), (102, 70, 51), (178, 89, 89), (102, 51, 51), (210, 210, 210), (100, 100, 100), (0, 127, 127), (0, 127, 70), (178, 89, 127), (148, 89, 178), (111, 89, 178), (89, 102, 178), (89, 141, 178), (89, 178, 136), (89, 178, 99), (116, 178, 89), (153, 178, 89), (178, 162, 89), (178, 123, 89), (160, 160, 160)]
line_colors = [(255, 127, 127), (255, 127, 182), (102, 51, 73), (214, 127, 255), (85, 51, 102), (161, 127, 255), (63, 51, 102), (127, 146, 255), (51, 58, 102), (127, 201, 255), (51, 80, 102), (127, 255, 197), (51, 102, 78), (127, 255, 142), (51, 102, 56), (165, 255, 127), (66, 102, 51), (218, 255, 127), (87, 102, 51), (255, 233, 127), (102, 92, 51), (255, 178, 127), (102, 70, 51), (178, 89, 89), (102, 51, 51), (210, 210, 210), (100, 100, 100), (0, 127, 127), (0, 127, 70), (178, 89, 127), (148, 89, 178), (111, 89, 178), (89, 102, 178), (89, 141, 178), (89, 178, 136), (89, 178, 99), (116, 178, 89), (153, 178, 89), (178, 162, 89), (178, 123, 89), (160, 160, 160)]
class BadSetting(Exception): """ Exception raised when an invalid value is provided for one or more settings when updating settings. """ class UnknownSetting(Exception): """ Exception raised when attempting to access a setting that does not exist. """
class Badsetting(Exception): """ Exception raised when an invalid value is provided for one or more settings when updating settings. """ class Unknownsetting(Exception): """ Exception raised when attempting to access a setting that does not exist. """
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(inventory) del inventory['pears'] # deletes a <key,value> print(inventory) inventory['apples'] = 10 # change value associated with key apples print(inventory) inventory['bananas'] = inventory['bananas'] * 2 print(inventory) num_items = len(inventory) print("Items in inventory: ", num_items)
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(inventory) del inventory['pears'] print(inventory) inventory['apples'] = 10 print(inventory) inventory['bananas'] = inventory['bananas'] * 2 print(inventory) num_items = len(inventory) print('Items in inventory: ', num_items)
"""Helper enum for defining possible states of tagging in a chat.""" class TagMode: """Helper enum for defining possible states of tagging in a chat.""" STICKER_SET = 'sticker_set' RANDOM = 'random' SINGLE_STICKER = 'single_sticker'
"""Helper enum for defining possible states of tagging in a chat.""" class Tagmode: """Helper enum for defining possible states of tagging in a chat.""" sticker_set = 'sticker_set' random = 'random' single_sticker = 'single_sticker'
# # PHASE: collect jars # # DOCUMENT THIS # load( "@io_bazel_rules_scala//scala/private:rule_impls.bzl", "collect_jars_from_common_ctx", ) def phase_scalatest_collect_jars(ctx, p): args = struct( base_classpath = p.scalac_provider.default_classpath + [ctx.attr._scalatest], extra_runtime_deps = [ ctx.attr._scalatest_reporter, ctx.attr._scalatest_runner, ], ) return _phase_default_collect_jars(ctx, p, args) def phase_repl_collect_jars(ctx, p): args = struct( base_classpath = p.scalac_provider.default_repl_classpath, ) return _phase_default_collect_jars(ctx, p, args) def phase_macro_library_collect_jars(ctx, p): args = struct( base_classpath = p.scalac_provider.default_macro_classpath, ) return _phase_default_collect_jars(ctx, p, args) def phase_junit_test_collect_jars(ctx, p): args = struct( extra_deps = [ ctx.attr._junit, ctx.attr._hamcrest, ctx.attr.suite_label, ctx.attr._bazel_test_runner, ], ) return _phase_default_collect_jars(ctx, p, args) def phase_library_for_plugin_bootstrapping_collect_jars(ctx, p): args = struct( unused_dependency_checker_mode = "off", ) return _phase_default_collect_jars(ctx, p, args) def phase_common_collect_jars(ctx, p): return _phase_default_collect_jars(ctx, p) def _phase_default_collect_jars(ctx, p, _args = struct()): return _phase_collect_jars( ctx, _args.base_classpath if hasattr(_args, "base_classpath") else p.scalac_provider.default_classpath, _args.extra_deps if hasattr(_args, "extra_deps") else [], _args.extra_runtime_deps if hasattr(_args, "extra_runtime_deps") else [], _args.unused_dependency_checker_mode if hasattr(_args, "unused_dependency_checker_mode") else p.unused_deps_checker, ) def _phase_collect_jars( ctx, base_classpath, extra_deps, extra_runtime_deps, unused_dependency_checker_mode): return collect_jars_from_common_ctx( ctx, base_classpath, extra_deps, extra_runtime_deps, unused_dependency_checker_mode == "off", )
load('@io_bazel_rules_scala//scala/private:rule_impls.bzl', 'collect_jars_from_common_ctx') def phase_scalatest_collect_jars(ctx, p): args = struct(base_classpath=p.scalac_provider.default_classpath + [ctx.attr._scalatest], extra_runtime_deps=[ctx.attr._scalatest_reporter, ctx.attr._scalatest_runner]) return _phase_default_collect_jars(ctx, p, args) def phase_repl_collect_jars(ctx, p): args = struct(base_classpath=p.scalac_provider.default_repl_classpath) return _phase_default_collect_jars(ctx, p, args) def phase_macro_library_collect_jars(ctx, p): args = struct(base_classpath=p.scalac_provider.default_macro_classpath) return _phase_default_collect_jars(ctx, p, args) def phase_junit_test_collect_jars(ctx, p): args = struct(extra_deps=[ctx.attr._junit, ctx.attr._hamcrest, ctx.attr.suite_label, ctx.attr._bazel_test_runner]) return _phase_default_collect_jars(ctx, p, args) def phase_library_for_plugin_bootstrapping_collect_jars(ctx, p): args = struct(unused_dependency_checker_mode='off') return _phase_default_collect_jars(ctx, p, args) def phase_common_collect_jars(ctx, p): return _phase_default_collect_jars(ctx, p) def _phase_default_collect_jars(ctx, p, _args=struct()): return _phase_collect_jars(ctx, _args.base_classpath if hasattr(_args, 'base_classpath') else p.scalac_provider.default_classpath, _args.extra_deps if hasattr(_args, 'extra_deps') else [], _args.extra_runtime_deps if hasattr(_args, 'extra_runtime_deps') else [], _args.unused_dependency_checker_mode if hasattr(_args, 'unused_dependency_checker_mode') else p.unused_deps_checker) def _phase_collect_jars(ctx, base_classpath, extra_deps, extra_runtime_deps, unused_dependency_checker_mode): return collect_jars_from_common_ctx(ctx, base_classpath, extra_deps, extra_runtime_deps, unused_dependency_checker_mode == 'off')
#!/usr/bin/env python3 # https://abc059.contest.atcoder.jp/tasks/abc059_b a = int(input()) b = int(input()) if a == b: print('EQUAL') elif a < b: print('LESS') else: print('GREATER')
a = int(input()) b = int(input()) if a == b: print('EQUAL') elif a < b: print('LESS') else: print('GREATER')
# noinspection DuplicatedCode class InsertConflictException(Exception): pass class OptimisticLockException(Exception): pass class UnexpectedStorageException(Exception): pass class UnsupportedCriteriaException(UnexpectedStorageException): pass class UnsupportedComputationException(UnexpectedStorageException): pass class UnsupportedStraightColumnException(UnexpectedStorageException): pass class NoFreeJoinException(UnexpectedStorageException): pass class NoCriteriaForUpdateException(UnexpectedStorageException): pass class UnsupportedSortMethodException(UnexpectedStorageException): pass class EntityNotFoundException(Exception): pass class TooManyEntitiesFoundException(Exception): pass
class Insertconflictexception(Exception): pass class Optimisticlockexception(Exception): pass class Unexpectedstorageexception(Exception): pass class Unsupportedcriteriaexception(UnexpectedStorageException): pass class Unsupportedcomputationexception(UnexpectedStorageException): pass class Unsupportedstraightcolumnexception(UnexpectedStorageException): pass class Nofreejoinexception(UnexpectedStorageException): pass class Nocriteriaforupdateexception(UnexpectedStorageException): pass class Unsupportedsortmethodexception(UnexpectedStorageException): pass class Entitynotfoundexception(Exception): pass class Toomanyentitiesfoundexception(Exception): pass
N, K, S = map(int, input().split()) str_S = str(S) str_S1 = str(S+1) ans = [] for _ in range(K): ans.append(str_S) for _ in range(N-K): if S != 1000000000: ans.append(str_S1) else: ans.append('1') print(' '.join(ans))
(n, k, s) = map(int, input().split()) str_s = str(S) str_s1 = str(S + 1) ans = [] for _ in range(K): ans.append(str_S) for _ in range(N - K): if S != 1000000000: ans.append(str_S1) else: ans.append('1') print(' '.join(ans))
def epu_calib_gr1800_Aug2019(dets = [sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') yield from gcdiag.diode # srs settings for diode = SRS settings: 5 x1 uA/v , time = 1.0 yield from mv(m1_simple_fbk,0) yield from mv(m3_simple_fbk,0) # PHASE = 0 mm yield from mv(epu1.phase, 0) yield from mv(epu1.table,1) yield from sleep(30) #yield from mv(feslt.hg,2.0) #yield from mv(feslt.vg,2.0) #yield from bp.mv(pgm.cff,5.2707) for i in range(250,1351,50): yield from mv(pgm.en,i) yield from sleep(5) start_gap = epu1.gap.readback.value yield from mv(epu1.gap,start_gap-1.5) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,3,31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] -1) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,101) # PHASE = 28.5 mm yield from mv(epu1.phase, 28.5) yield from mv(epu1.table,3) yield from sleep(30) yield from mv(pgm.en,850) yield from beamline_align_v2() yield from mv(m1_simple_fbk,0) yield from mv(m3_simple_fbk,0) yield from mv(pgm.en,350) yield from sleep(5) yield from mv(epu1.gap,18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,31) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,1,51) for i in range(400,1351,50): yield from mv(pgm.en,i) yield from sleep(5) start_gap = epu1.gap.readback.value yield from mv(epu1.gap,start_gap-1) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] -1) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,101) # LEAVING THE BEAMLINE READY FOR NEXT TEST yield from mv(epu1.phase, 0) yield from mv(epu1.table,1) yield from sleep(30) yield from mv(pgm.en,530) yield from beamline_align_v2() def epu_calib_gr500(dets = [sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode # srs settings for diode = SRS settings: 5 x10 uA/v , time = 1.0 #yield from mv(feslt.hg,2.0) #yield from mv(feslt.vg,2.0) #yield from bp.mv(pgm.cff,2.32) yield from mv(extslt.hg,300) yield from mv(extslt.vg,30) #180 eV yield from mv(pgm.en,180) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets,epu1.gap,0,1.5,76) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,1.5,76) for i in range(200,1351,50): calc_gap=e2g(i) yield from mv(pgm.en,i) yield from sleep(5) yield from mv(epu1.gap,calc_gap-2) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,6,31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] -1) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,101) yield from sleep(100) #800-1600 eV, 3rd harmonic for i in range(800,1601,50): calc_gap=e2g(i/3) yield from mv(pgm.en,i) yield from sleep(5) yield from mv(epu1.gap,calc_gap-2) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,4,41) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0]-0.5) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,1.0,76) calc_gap=e2g(850) yield from mv(pgm.en,850) yield from sleep(5) yield from mv(epu1.gap,39.387) yield from mv(shutterb,'close') print('\n\n WARNING WARNING WARNING:\n\t EPU Table/Interpolation disabled!!!!') print('\n\n WARNING WARNING WARNING:\n\t M1 Feedback disabled!!!!') def epu_calib_gr1800(dets = [sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode # srs settings for diode = SRS settings: 5 x1 uA/v , time = 1.0 yield from mv(epu1.phase, 0) #yield from mv(feslt.hg,2.0) #yield from mv(feslt.vg,2.0) #yield from bp.mv(pgm.cff,5.2707) for i in range(250,1351,50): calc_gap=e2g(i) yield from mv(pgm.en,i) yield from sleep(5) yield from mv(epu1.gap,calc_gap-2) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,6,31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] -1) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,101) yield from sleep(100) #800-1550 eV, 3rd harmonic #for i in range(800,2001,50): #calc_gap=e2g(i/3) #yield from mv(pgm.en,i) #yield from sleep(5) #yield from mv(epu1.gap,calc_gap-2) #yield from sleep(10) #yield from rel_scan(dets, epu1.gap,0,4,41) #yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0]-0.5) #yield from sleep(10) #yield from rel_scan(dets, epu1.gap,0,1.0,76) calc_gap=e2g(850) yield from mv(pgm.en,850) yield from sleep(5) yield from mv(epu1.gap,calc_gap) def epu_calib_ph28p5_gr500(dets = [sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode yield from mv(extslt.hg,300) yield from mv(extslt.vg,30) # srs settings for diode = SRS settings: 5 x10 uA/v , time = 1.0 # Current gap limit is 18mm yield from mv(epu1.phase, 28.5) #yield from mv(feslt.hg,2.0) #yield from mv(feslt.vg,2.0) #yield from bp.mv(pgm.cff,2.24) #1st Harmonic at 320 eV #yield from mv(pgm.en,320,epu1.gap,17.05) #yield from sleep(10) #yield from rel_scan(dets,epu1.gap,0,1,30) #yield from mv(epu1.gap,17.05) #yield from sleep(10) #yield from rel_scan(dets,epu1.gap,0,1,50) #1st Harmonic for i in range(400,451,50): calc_gap=e2g(i) yield from mv(pgm.en,i,epu1.gap,calc_gap-1.4-7.8 -(i-350)*0.0067) yield from sleep(10) yield from rel_scan(dets,epu1.gap,0,3,30) yield from mv(epu1.gap,peaks['max']['sclr_channels_chan2'][0]-1) yield from sleep(10) yield from rel_scan(dets,epu1.gap,0,2,100) for i in range(500,1351,50): calc_gap=e2g(i) yield from mv(pgm.en,i,epu1.gap,calc_gap-3-7.8 -(i-350)*0.0067) yield from sleep(10) yield from rel_scan(dets,epu1.gap,0,6,30) yield from mv(epu1.gap,peaks['max']['sclr_channels_chan2'][0]-1) yield from sleep(10) yield from rel_scan(dets,epu1.gap,0,2,100) yield from sleep(100) #3rd Harmonic for i in range(1100,1601,50): calc_gap=e2g(i/3) yield from mv(pgm.en,i,epu1.gap,calc_gap-0.5-8-(i-1000)*0.0027) yield from sleep(10) yield from rel_scan(dets,epu1.gap,0,2,30) yield from mv(epu1.gap,peaks['max']['sclr_channels_chan2'][0]-0.5) yield from sleep(10) yield from rel_scan(dets,epu1.gap,0,1.0,75) yield from mv(pgm.en,931.6) yield from sleep(5) yield from mv(epu1.gap,29.56) yield from mv(shutterb,'close') def epu_calib_ph28p5_gr1800(dets = [sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode # srs settings for diode = SRS settings: 5 x1 uA/v # Current gap limit is 18mm yield from mv(epu1.phase, 28.5) #yield from mv(feslt.hg,2.0) #yield from mv(feslt.vg,2.0) #yield from bp.mv(pgm.cff,5.2707) yield from mv(pgm.en,350) yield from sleep(5) yield from mv(epu1.gap,18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,31) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,1,51) for i in range(400,451,50): calc_gap=e2g(i) yield from mv(pgm.en,i) yield from sleep(5) yield from mv(epu1.gap,calc_gap-1.4-7.8 -(i-350)*0.0067) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,3,31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] -1) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,101) for i in range(500,1351,50): calc_gap=e2g(i) yield from mv(pgm.en,i) yield from sleep(5) yield from mv(epu1.gap,calc_gap-2-7.8 -(i-350)*0.0067) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,3,31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] -1) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,101) yield from sleep(30) #800-1550 eV, 3rd harmonic #for i in range(1100,2001,50): #calc_gap=e2g(i/3) #yield from mv(pgm.en,i) #yield from sleep(5) #yield from mv(epu1.gap,calc_gap-8.5-(i-1000)*0.0027) #yield from sleep(10) #yield from rel_scan(dets, epu1.gap,0,2,31) #yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0]-0.5) #yield from sleep(10) #yield from rel_scan(dets, epu1.gap,0,1.0,76) calc_gap=e2g(850) yield from mv(pgm.en,530) yield from sleep(5) yield from mv(epu1.phase,0) yield from mv(epu1.gap,28.01) yield from mv(shutterb,'close') print('\n\n WARNING WARNING WARNING:\n\t EPU Table/Interpolation disabled!!!!') print('\n\n WARNING WARNING WARNING:\n\t M1 Feedback disabled!!!!') def epu_calib_ph28p5_gr1800_v2(dets = [sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode # srs settings for diode = SRS settings: 5 x1 uA/v # Current gap limit is 18mm yield from mv(epu1.phase, 28.5) #yield from mv(feslt.hg,2.0) #yield from mv(feslt.vg,2.0) #yield from bp.mv(pgm.cff,5.2707) yield from sleep(30) #800-1550 eV, 3rd harmonic for i in range(1100,2001,50): calc_gap=e2g(i/3) yield from mv(pgm.en,i) yield from sleep(5) yield from mv(epu1.gap,calc_gap-8.5-(i-1000)*0.0027) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,2,31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0]-0.5) yield from sleep(10) yield from rel_scan(dets, epu1.gap,0,1.0,76) calc_gap=e2g(850) yield from mv(pgm.en,850) yield from sleep(5) yield from mv(epu1.gap,28.01) yield from mv(shutterb,'close') print('\n\n WARNING WARNING WARNING:\n\t EPU Table/Interpolation disabled!!!!') print('\n\n WARNING WARNING WARNING:\n\t M1 Feedback disabled!!!!')
def epu_calib_gr1800__aug2019(dets=[sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') yield from gcdiag.diode yield from mv(m1_simple_fbk, 0) yield from mv(m3_simple_fbk, 0) yield from mv(epu1.phase, 0) yield from mv(epu1.table, 1) yield from sleep(30) for i in range(250, 1351, 50): yield from mv(pgm.en, i) yield from sleep(5) start_gap = epu1.gap.readback.value yield from mv(epu1.gap, start_gap - 1.5) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 3, 31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 101) yield from mv(epu1.phase, 28.5) yield from mv(epu1.table, 3) yield from sleep(30) yield from mv(pgm.en, 850) yield from beamline_align_v2() yield from mv(m1_simple_fbk, 0) yield from mv(m3_simple_fbk, 0) yield from mv(pgm.en, 350) yield from sleep(5) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 31) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 1, 51) for i in range(400, 1351, 50): yield from mv(pgm.en, i) yield from sleep(5) start_gap = epu1.gap.readback.value yield from mv(epu1.gap, start_gap - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 101) yield from mv(epu1.phase, 0) yield from mv(epu1.table, 1) yield from sleep(30) yield from mv(pgm.en, 530) yield from beamline_align_v2() def epu_calib_gr500(dets=[sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode yield from mv(extslt.hg, 300) yield from mv(extslt.vg, 30) yield from mv(pgm.en, 180) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 1.5, 76) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 1.5, 76) for i in range(200, 1351, 50): calc_gap = e2g(i) yield from mv(pgm.en, i) yield from sleep(5) yield from mv(epu1.gap, calc_gap - 2) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 6, 31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 101) yield from sleep(100) for i in range(800, 1601, 50): calc_gap = e2g(i / 3) yield from mv(pgm.en, i) yield from sleep(5) yield from mv(epu1.gap, calc_gap - 2) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 4, 41) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 0.5) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 1.0, 76) calc_gap = e2g(850) yield from mv(pgm.en, 850) yield from sleep(5) yield from mv(epu1.gap, 39.387) yield from mv(shutterb, 'close') print('\n\n WARNING WARNING WARNING:\n\t EPU Table/Interpolation disabled!!!!') print('\n\n WARNING WARNING WARNING:\n\t M1 Feedback disabled!!!!') def epu_calib_gr1800(dets=[sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode yield from mv(epu1.phase, 0) for i in range(250, 1351, 50): calc_gap = e2g(i) yield from mv(pgm.en, i) yield from sleep(5) yield from mv(epu1.gap, calc_gap - 2) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 6, 31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 101) yield from sleep(100) calc_gap = e2g(850) yield from mv(pgm.en, 850) yield from sleep(5) yield from mv(epu1.gap, calc_gap) def epu_calib_ph28p5_gr500(dets=[sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode yield from mv(extslt.hg, 300) yield from mv(extslt.vg, 30) yield from mv(epu1.phase, 28.5) for i in range(400, 451, 50): calc_gap = e2g(i) yield from mv(pgm.en, i, epu1.gap, calc_gap - 1.4 - 7.8 - (i - 350) * 0.0067) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 3, 30) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 100) for i in range(500, 1351, 50): calc_gap = e2g(i) yield from mv(pgm.en, i, epu1.gap, calc_gap - 3 - 7.8 - (i - 350) * 0.0067) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 6, 30) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 100) yield from sleep(100) for i in range(1100, 1601, 50): calc_gap = e2g(i / 3) yield from mv(pgm.en, i, epu1.gap, calc_gap - 0.5 - 8 - (i - 1000) * 0.0027) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 30) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 0.5) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 1.0, 75) yield from mv(pgm.en, 931.6) yield from sleep(5) yield from mv(epu1.gap, 29.56) yield from mv(shutterb, 'close') def epu_calib_ph28p5_gr1800(dets=[sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode yield from mv(epu1.phase, 28.5) yield from mv(pgm.en, 350) yield from sleep(5) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 31) yield from mv(epu1.gap, 18.01) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 1, 51) for i in range(400, 451, 50): calc_gap = e2g(i) yield from mv(pgm.en, i) yield from sleep(5) yield from mv(epu1.gap, calc_gap - 1.4 - 7.8 - (i - 350) * 0.0067) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 3, 31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 101) for i in range(500, 1351, 50): calc_gap = e2g(i) yield from mv(pgm.en, i) yield from sleep(5) yield from mv(epu1.gap, calc_gap - 2 - 7.8 - (i - 350) * 0.0067) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 3, 31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 1) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 101) yield from sleep(30) calc_gap = e2g(850) yield from mv(pgm.en, 530) yield from sleep(5) yield from mv(epu1.phase, 0) yield from mv(epu1.gap, 28.01) yield from mv(shutterb, 'close') print('\n\n WARNING WARNING WARNING:\n\t EPU Table/Interpolation disabled!!!!') print('\n\n WARNING WARNING WARNING:\n\t M1 Feedback disabled!!!!') def epu_calib_ph28p5_gr1800_v2(dets=[sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') print('\n\n WARNING WARNING WARNING:\n\t this assumes epu interpolation table is DISABLED!!!!') yield from gcdiag.diode yield from mv(epu1.phase, 28.5) yield from sleep(30) for i in range(1100, 2001, 50): calc_gap = e2g(i / 3) yield from mv(pgm.en, i) yield from sleep(5) yield from mv(epu1.gap, calc_gap - 8.5 - (i - 1000) * 0.0027) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 2, 31) yield from mv(epu1.gap, peaks['max']['sclr_channels_chan2'][0] - 0.5) yield from sleep(10) yield from rel_scan(dets, epu1.gap, 0, 1.0, 76) calc_gap = e2g(850) yield from mv(pgm.en, 850) yield from sleep(5) yield from mv(epu1.gap, 28.01) yield from mv(shutterb, 'close') print('\n\n WARNING WARNING WARNING:\n\t EPU Table/Interpolation disabled!!!!') print('\n\n WARNING WARNING WARNING:\n\t M1 Feedback disabled!!!!')
#!/usr/bin/python3.6 """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. """ def numbers(n): tot = 0 for i in range(1, n): if n%i == 0: tot = tot + i if tot == n: print(f"{n} is a perfect number.") elif tot > n: print(f"{n} is a abundant number") elif tot < n: print(f"{n} is a deficient number") return None n = int(input("Enter a number: ")) numbers(n)
""" A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. """ def numbers(n): tot = 0 for i in range(1, n): if n % i == 0: tot = tot + i if tot == n: print(f'{n} is a perfect number.') elif tot > n: print(f'{n} is a abundant number') elif tot < n: print(f'{n} is a deficient number') return None n = int(input('Enter a number: ')) numbers(n)
def duplicate(s): if(len(s)<=1): return s if s[0]==s[1]: return duplicate(s[1:]) return s[0]+duplicate(s[1:]) s = input() print(duplicate(s))
def duplicate(s): if len(s) <= 1: return s if s[0] == s[1]: return duplicate(s[1:]) return s[0] + duplicate(s[1:]) s = input() print(duplicate(s))
# %% ####################################### def access_nested_dict(thedict: dict): """Demo of how to access a nested dictionary with a two dictionary comprehensions Examples: >>> a_dictionary = { ... "1-2017": { ... "Win7": "0.47", ... "Vista": "0.2", ... "NT*": "0.09", ... "WinXP": "0.06", ... "Linux": "0.17", ... "Mac": "0.04", ... "Mobile": "0.26", ... }, ... "2-2017": { ... "Win7": "0.48", ... "Vista": "0.28", ... "NT*": "0.07", ... "WinXP": "0.09", ... "Linux": "0.16", ... "Mac": "0.03", ... "Mobile": "0.27", ... }, ... "3-2017": { ... "Win7": "0.41", ... "Vista": "0.25", ... "NT*": "0.05", ... "WinXP": "0.05", ... "Linux": "0.1", ... "Mac": "0.04", ... "Mobile": "0.27", ... }, ... } >>> access_nested_dict(a_dictionary)\n {'1-2017': {('NT*', '0.09'), ('Vista', '0.2'), ('WinXP', '0.06')}, '2-2017': {('NT*', '0.07'), ('Vista', '0.28'), ('WinXP', '0.09')}, '3-2017': {('NT*', '0.05'), ('Vista', '0.25'), ('WinXP', '0.05')}} References: https://stackoverflow.com/questions/17915117/nested-dictionary-comprehension-python """ comprehension = { outer_k: { (inner_k, inner_v) for inner_k, inner_v in outer_v.items() if inner_k in ["Vista", "NT*", "WinXP"] } for outer_k, outer_v in thedict.items() } return comprehension
def access_nested_dict(thedict: dict): """Demo of how to access a nested dictionary with a two dictionary comprehensions Examples: >>> a_dictionary = { ... "1-2017": { ... "Win7": "0.47", ... "Vista": "0.2", ... "NT*": "0.09", ... "WinXP": "0.06", ... "Linux": "0.17", ... "Mac": "0.04", ... "Mobile": "0.26", ... }, ... "2-2017": { ... "Win7": "0.48", ... "Vista": "0.28", ... "NT*": "0.07", ... "WinXP": "0.09", ... "Linux": "0.16", ... "Mac": "0.03", ... "Mobile": "0.27", ... }, ... "3-2017": { ... "Win7": "0.41", ... "Vista": "0.25", ... "NT*": "0.05", ... "WinXP": "0.05", ... "Linux": "0.1", ... "Mac": "0.04", ... "Mobile": "0.27", ... }, ... } >>> access_nested_dict(a_dictionary) {'1-2017': {('NT*', '0.09'), ('Vista', '0.2'), ('WinXP', '0.06')}, '2-2017': {('NT*', '0.07'), ('Vista', '0.28'), ('WinXP', '0.09')}, '3-2017': {('NT*', '0.05'), ('Vista', '0.25'), ('WinXP', '0.05')}} References: https://stackoverflow.com/questions/17915117/nested-dictionary-comprehension-python """ comprehension = {outer_k: {(inner_k, inner_v) for (inner_k, inner_v) in outer_v.items() if inner_k in ['Vista', 'NT*', 'WinXP']} for (outer_k, outer_v) in thedict.items()} return comprehension
linhas = int(input('Quantas linhas vai querer?: ')) colunas = int(input('quantas colunas vai querer?: ')) m = [] n = [] for l in range(linhas): ln = [] lon = 0 for c in range(colunas): t = int(input(f'qual o valor de [{l},{c}]?: ')) ln.append(t) lon += t m.append(ln) n.append(lon) for lin in range(linhas): print(n[lin],end='\n') for lin in range(linhas): for col in range(colunas): print(f'{m[lin][col]}*{n[lin]}',end='\t',) print()
linhas = int(input('Quantas linhas vai querer?: ')) colunas = int(input('quantas colunas vai querer?: ')) m = [] n = [] for l in range(linhas): ln = [] lon = 0 for c in range(colunas): t = int(input(f'qual o valor de [{l},{c}]?: ')) ln.append(t) lon += t m.append(ln) n.append(lon) for lin in range(linhas): print(n[lin], end='\n') for lin in range(linhas): for col in range(colunas): print(f'{m[lin][col]}*{n[lin]}', end='\t') print()
# coding=utf-8 # *** WARNING: this file was generated by crd2pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** SNAKE_TO_CAMEL_CASE_TABLE = { "access_token_secret": "accessTokenSecret", "api_version": "apiVersion", "destroy_on_finalize": "destroyOnFinalize", "env_secrets": "envSecrets", "expect_no_refresh_changes": "expectNoRefreshChanges", "git_auth_secret": "gitAuthSecret", "last_attempted_commit": "lastAttemptedCommit", "last_successful_commit": "lastSuccessfulCommit", "last_update": "lastUpdate", "project_repo": "projectRepo", "repo_dir": "repoDir", "retry_on_update_conflict": "retryOnUpdateConflict", "secrets_provider": "secretsProvider", } CAMEL_TO_SNAKE_CASE_TABLE = { "accessTokenSecret": "access_token_secret", "apiVersion": "api_version", "destroyOnFinalize": "destroy_on_finalize", "envSecrets": "env_secrets", "expectNoRefreshChanges": "expect_no_refresh_changes", "gitAuthSecret": "git_auth_secret", "lastAttemptedCommit": "last_attempted_commit", "lastSuccessfulCommit": "last_successful_commit", "lastUpdate": "last_update", "projectRepo": "project_repo", "repoDir": "repo_dir", "retryOnUpdateConflict": "retry_on_update_conflict", "secretsProvider": "secrets_provider", }
snake_to_camel_case_table = {'access_token_secret': 'accessTokenSecret', 'api_version': 'apiVersion', 'destroy_on_finalize': 'destroyOnFinalize', 'env_secrets': 'envSecrets', 'expect_no_refresh_changes': 'expectNoRefreshChanges', 'git_auth_secret': 'gitAuthSecret', 'last_attempted_commit': 'lastAttemptedCommit', 'last_successful_commit': 'lastSuccessfulCommit', 'last_update': 'lastUpdate', 'project_repo': 'projectRepo', 'repo_dir': 'repoDir', 'retry_on_update_conflict': 'retryOnUpdateConflict', 'secrets_provider': 'secretsProvider'} camel_to_snake_case_table = {'accessTokenSecret': 'access_token_secret', 'apiVersion': 'api_version', 'destroyOnFinalize': 'destroy_on_finalize', 'envSecrets': 'env_secrets', 'expectNoRefreshChanges': 'expect_no_refresh_changes', 'gitAuthSecret': 'git_auth_secret', 'lastAttemptedCommit': 'last_attempted_commit', 'lastSuccessfulCommit': 'last_successful_commit', 'lastUpdate': 'last_update', 'projectRepo': 'project_repo', 'repoDir': 'repo_dir', 'retryOnUpdateConflict': 'retry_on_update_conflict', 'secretsProvider': 'secrets_provider'}
def maxSubsetSumNoAdjacent(array): # Write your code here. if not array: return 0 if len(array) < 3: return max(array) dp = [0]*len(array) dp[0] = array[0] dp[1] = max(array[1], dp[0]) for i in range(2, len(array)): dp[i] = max(dp[i - 1], array[i] + dp[i - 2]) return max(dp)
def max_subset_sum_no_adjacent(array): if not array: return 0 if len(array) < 3: return max(array) dp = [0] * len(array) dp[0] = array[0] dp[1] = max(array[1], dp[0]) for i in range(2, len(array)): dp[i] = max(dp[i - 1], array[i] + dp[i - 2]) return max(dp)
# Check if string is palindrom or not....using in-built fxn a = str(input("Input String")) b = a.reverse if a==b: print("string is palindrome") else: print("String is not palindrome")
a = str(input('Input String')) b = a.reverse if a == b: print('string is palindrome') else: print('String is not palindrome')
__all__ = ['batch_tasks'] def batch_tasks(n_batches, n_tasks=None, arr=None, args=None, start_idx=0, include_idx=True): """Split tasks into some number of batches to send out to workers. By default, returns index ranges that split the number of tasks into the specified number of batches. If an array is passed in via ``arr``, it splits the array directly along ``axis=0`` into the specified number of batches. Parameters ---------- n_batches : int The number of batches to split the tasks into. Often, you may want to do ``n_batches=pool.size`` for equal sharing amongst MPI workers. n_tasks : int (optional) The total number of tasks to divide. arr : iterable (optional) Instead of returning indices that specify the batches, you can also directly split an array into batches. args : iterable (optional) Other arguments to add to each task. start_idx : int (optional) What index in the tasks to start from? include_idx : bool (optional) If passing an array in, this determines whether to include the indices of each batch with each task. """ if args is None: args = tuple() args = tuple(args) if ((n_tasks is None and arr is None) or (n_tasks is not None and arr is not None)): raise ValueError("you must pass one of n_tasks or arr (not both)") elif n_tasks is None: n_tasks = len(arr) if n_batches <= 0 or n_tasks <= 0: raise ValueError("n_batches and n_tasks must be > 0") if n_batches > n_tasks: # TODO: add a warning? n_batches = n_tasks # Chunk by the number of batches, often the pool size base_batch_size = n_tasks // n_batches rmdr = n_tasks % n_batches i1 = start_idx indices = [] for i in range(n_batches): i2 = i1 + base_batch_size if i < rmdr: i2 += 1 indices.append((i1, i2)) i1 = i2 # Add args, possible slice input array: tasks = [] for idx in indices: if arr is not None and not args and not include_idx: tasks.append(arr[idx[0]:idx[1]]) continue extra = list() if arr is not None: extra.append(arr[idx[0]:idx[1]]) if args: extra.extend(args) if extra and include_idx: tasks.append(tuple([idx] + extra)) elif extra and not include_idx: tasks.append(extra) else: tasks.append(idx) return tasks
__all__ = ['batch_tasks'] def batch_tasks(n_batches, n_tasks=None, arr=None, args=None, start_idx=0, include_idx=True): """Split tasks into some number of batches to send out to workers. By default, returns index ranges that split the number of tasks into the specified number of batches. If an array is passed in via ``arr``, it splits the array directly along ``axis=0`` into the specified number of batches. Parameters ---------- n_batches : int The number of batches to split the tasks into. Often, you may want to do ``n_batches=pool.size`` for equal sharing amongst MPI workers. n_tasks : int (optional) The total number of tasks to divide. arr : iterable (optional) Instead of returning indices that specify the batches, you can also directly split an array into batches. args : iterable (optional) Other arguments to add to each task. start_idx : int (optional) What index in the tasks to start from? include_idx : bool (optional) If passing an array in, this determines whether to include the indices of each batch with each task. """ if args is None: args = tuple() args = tuple(args) if n_tasks is None and arr is None or (n_tasks is not None and arr is not None): raise value_error('you must pass one of n_tasks or arr (not both)') elif n_tasks is None: n_tasks = len(arr) if n_batches <= 0 or n_tasks <= 0: raise value_error('n_batches and n_tasks must be > 0') if n_batches > n_tasks: n_batches = n_tasks base_batch_size = n_tasks // n_batches rmdr = n_tasks % n_batches i1 = start_idx indices = [] for i in range(n_batches): i2 = i1 + base_batch_size if i < rmdr: i2 += 1 indices.append((i1, i2)) i1 = i2 tasks = [] for idx in indices: if arr is not None and (not args) and (not include_idx): tasks.append(arr[idx[0]:idx[1]]) continue extra = list() if arr is not None: extra.append(arr[idx[0]:idx[1]]) if args: extra.extend(args) if extra and include_idx: tasks.append(tuple([idx] + extra)) elif extra and (not include_idx): tasks.append(extra) else: tasks.append(idx) return tasks
def orf_single(seq): startss = [] stopss = [] starts_ = [] stop_s = [] start = 0 sslen = 0 s_len1 = 0 s_len2 = 0 newseq = seq newseq_6 = [] max_l = len(seq) l = len(seq) for i in range(len(seq)): if (seq[i:i+3]=="ATG"): start = 1 # has start codon for j in range(int((len(seq)-(i+3))/3)): if (seq[i+3+3*j:i+3+3*j+3]=="TAA") or (seq[i+3+3*j:i+3+3*j+3]=="TAG") or (seq[i+3+3*j:i+3+3*j+3]=="TGA"): startss.append(i) stopss.append(i+3+3*j+3) break if len(startss)==0 : starts_.append(i) if start == 0: for k in range(len(seq)): if (seq[k:k+3]=="TAA") or (seq[k:k+3]=="TAG") or (seq[k:k+3]=="TGA"): stop_s.append(k+3) if len(startss)!=0: startss = np.array(startss) stopss = np.array(stopss) coding_len = stopss-startss max_len_position = np.argmax(coding_len) sslen = coding_len[max_len_position] newseq = seq[(startss[max_len_position]):(stopss[max_len_position])] max_l = sslen if (startss[max_len_position]-3)>=0 and (startss[max_len_position]+5)<l: newseq_6 = seq[(startss[max_len_position]-3): (startss[max_len_position])]+seq[(startss[max_len_position]+3):(startss[max_len_position]+6)] elif len(starts_)!=0: starts_ = np.array(starts_) s_len1 = len(seq)-starts_[0] newseq = seq[(starts_[0]):len(seq)] max_l = s_len1 if (starts_[0]-3)>=0 and (starts_[0]+5)<l: newseq_6 = seq[(starts_[0]-3):(starts_[0])]+seq[(starts_[0]+3):(starts_[0]+6)] elif len(stop_s)!=0: stop_s = np.array(stop_s) s_len1 = stop_s[-1] newseq = seq[0:(stop_s[-1])] max_l = s_len1 orf_feature = (sslen/len(seq),s_len1/len(seq)) return orf_feature,max_l,newseq,newseq_6 def orf_feature(seq): orf = [] max_l = [] newseq = [] newseq_nu6 = [] for i in range(len(seq)): orfsin,max_lsin,newseqsin,newseq_nu6sin = orf_single(seq[i]) orf.append(orfsin) max_l.append(max_lsin) newseq.append(newseqsin) newseq_nu6.append(newseq_nu6sin) orf = np.array(orf) max_l = np.array(max_l) return orf,max_l,newseq,newseq_nu6
def orf_single(seq): startss = [] stopss = [] starts_ = [] stop_s = [] start = 0 sslen = 0 s_len1 = 0 s_len2 = 0 newseq = seq newseq_6 = [] max_l = len(seq) l = len(seq) for i in range(len(seq)): if seq[i:i + 3] == 'ATG': start = 1 for j in range(int((len(seq) - (i + 3)) / 3)): if seq[i + 3 + 3 * j:i + 3 + 3 * j + 3] == 'TAA' or seq[i + 3 + 3 * j:i + 3 + 3 * j + 3] == 'TAG' or seq[i + 3 + 3 * j:i + 3 + 3 * j + 3] == 'TGA': startss.append(i) stopss.append(i + 3 + 3 * j + 3) break if len(startss) == 0: starts_.append(i) if start == 0: for k in range(len(seq)): if seq[k:k + 3] == 'TAA' or seq[k:k + 3] == 'TAG' or seq[k:k + 3] == 'TGA': stop_s.append(k + 3) if len(startss) != 0: startss = np.array(startss) stopss = np.array(stopss) coding_len = stopss - startss max_len_position = np.argmax(coding_len) sslen = coding_len[max_len_position] newseq = seq[startss[max_len_position]:stopss[max_len_position]] max_l = sslen if startss[max_len_position] - 3 >= 0 and startss[max_len_position] + 5 < l: newseq_6 = seq[startss[max_len_position] - 3:startss[max_len_position]] + seq[startss[max_len_position] + 3:startss[max_len_position] + 6] elif len(starts_) != 0: starts_ = np.array(starts_) s_len1 = len(seq) - starts_[0] newseq = seq[starts_[0]:len(seq)] max_l = s_len1 if starts_[0] - 3 >= 0 and starts_[0] + 5 < l: newseq_6 = seq[starts_[0] - 3:starts_[0]] + seq[starts_[0] + 3:starts_[0] + 6] elif len(stop_s) != 0: stop_s = np.array(stop_s) s_len1 = stop_s[-1] newseq = seq[0:stop_s[-1]] max_l = s_len1 orf_feature = (sslen / len(seq), s_len1 / len(seq)) return (orf_feature, max_l, newseq, newseq_6) def orf_feature(seq): orf = [] max_l = [] newseq = [] newseq_nu6 = [] for i in range(len(seq)): (orfsin, max_lsin, newseqsin, newseq_nu6sin) = orf_single(seq[i]) orf.append(orfsin) max_l.append(max_lsin) newseq.append(newseqsin) newseq_nu6.append(newseq_nu6sin) orf = np.array(orf) max_l = np.array(max_l) return (orf, max_l, newseq, newseq_nu6)
numerotabuada = int(input("Escreva um numero e veja sua tabuada: ")) tabuada = [] for x in range(1,10+1): mult = numerotabuada * x tabuada.append(mult) print(tabuada)
numerotabuada = int(input('Escreva um numero e veja sua tabuada: ')) tabuada = [] for x in range(1, 10 + 1): mult = numerotabuada * x tabuada.append(mult) print(tabuada)
""" mpiece.renderer ~~~~~~~~~~~~~~~~~~~~~~~~~ Renderer Classes. :license: BSD, see LICENSE for details. :author: David Casado Martinez <dcasadomartinez@gmail.com> """ class Renderer(object): """ Base renderer class. All renderer classes should be subclasses of this class. This class and their subclass are used in the ``mpiece.markdown()`` function or in the ``mpiece.core.MPiece.parse()`` method. """ def __init__(self): self.all_render_funcs = {} for item in dir(self): if item.startswith('render_'): self.all_render_funcs[item[7:]] = getattr(self, item) def render__only_text(self, text): return text def post_process_text(self, text): """ Process the rendered text. :param str text: Rendered text :return str: """ return text class HtmlRenderer(Renderer): """ Transform the lexer results in html code. :param bool use_underline: - ``True``: The markdown ``_text_`` will transform in ``<ins>text</ins>`` - ``False``: The markdown ``_text_`` will transform in ``<em>text</em>`` :param bool use_paragraph: - ``True``: The new line in the markdown text will transform in ``<p></p>`` html tag. - ``False``: The new line in the markdown text will transform in ``<br>`` html tag. :param bool escape_html: - ``True``: Escape the html tag in the markdown text. - ``False``: No escape the html tag in the markdown text. """ #: Blacklist of link schemes scheme_blacklist = ('javascript', 'data', 'vbscript') def __init__(self, use_underline=True, use_paragraph=True, escape_html=True): super(HtmlRenderer, self).__init__() self.use_underline = use_underline self.use_paragraph = use_paragraph self.escape_html = escape_html def escape(self, text): """ Escape dangerous html characters. :param str text: Html text without escape. :return: Html text escaped. """ if not self.escape_html or text is None: return text return ( text.replace('&', '&amp;').replace('<', '&lt;') .replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;') ) def escape_args(self, *args): """ Escape html characters of all arguments :param [str] \*args: List of html text without escape. :return: list of all arguments escaped. """ return tuple((self.escape(arg) for arg in args)) def escape_link(self, link, smart_amp=True): """ Check if a link has an invalid scheme. Also transform the ``&`` character in ``&amp;`` character. :param str link: Link checked. :param bool smart_amp: Transform the '&' characters in '&amp;' characters. :return: Return the link if the scheme is valid. If not return an empty string. """ data = link.split(':', 1) scheme = data[0] if scheme in self.scheme_blacklist: return '' if smart_amp: return link.replace('&', '&amp;') return link # # Render functions # def render_escape_backslash(self, text): return self.escape(text) def render_bold(self, text): return '<strong>%s</strong>' % self.escape(text) def render_italic(self, text): return '<em>%s</em>' % self.escape(text) def render_underline(self, text): if self.use_underline: return '<ins>%s</ins>' % self.escape(text) else: return self.use_italic(text) def render_strike(self, text): return '<del>%s</del>' % self.escape(text) def render_code_inline(self, code): return '<code>%s</code>' % self.escape(code) def render_link(self, text, href, title=''): text = self.escape(text) href = self.escape_link(href) if title: return '<a href="%s" title="%s">%s</a>' % (href, self.escape(title), text) return '<a href="%s">%s</a>' % (href, text) def render_image(self, src, alt, title=''): alt = self.escape(alt) src = self.escape_link(src) if title: title = self.escape(title) return '<img src="%s" alt="%s" title="%s">' % (src, alt, title) return '<img src="%s" alt="%s">' % (src, alt) def render_new_line(self, text): if self.use_paragraph: return '<p>%s</p>' % self.escape(text) if text else '' else: return '%s<br/>' % self.escape(text) if text else '' def render_olist(self, text, start): # text, start = self.escape_args(text, start) text = self.escape(text) return '<ol start="%d">%s</ol>' % (start, text) def render_olist_item(self, text): return '<li>%s</li>' % self.escape(text) def render_ulist(self, text, start): return '<ul>%s</ul>' % self.escape(text) def render_ulist_item(self, text): return '<li>%s</li>' % self.escape(text) def render_blockquote(self, text): return '<blockquote>%s</blockquote>' % self.escape(text) def render_header(self, text, level): return '<h{level}>{text}</h{level}>'.format(level=level, text=self.escape(text)) def render_fenced_code(self, code, lang='', title=''): return '<pre>%s</pre>' % self.escape(code) def render_break_line(self, symbol): return '<hr/>' def render_table(self, text): return '<table>%s</table>' % text def render_table_header(self, text): return '<thead><tr>%s</tr></thead>' % text def render_table_header_cell(self, text): return '<th>%s</th>' % text def render_table_body(self, text): return '<tbody>%s</tbody>' % text def render_table_body_row(self, text): return '<tr>%s</tr>' % text def render_table_body_cell(self, text, align=''): if align and align != 'left': return '<td style="text-align:%s;">%s</td>' % (align, text) else: return '<td>%s</td>' % text
""" mpiece.renderer ~~~~~~~~~~~~~~~~~~~~~~~~~ Renderer Classes. :license: BSD, see LICENSE for details. :author: David Casado Martinez <dcasadomartinez@gmail.com> """ class Renderer(object): """ Base renderer class. All renderer classes should be subclasses of this class. This class and their subclass are used in the ``mpiece.markdown()`` function or in the ``mpiece.core.MPiece.parse()`` method. """ def __init__(self): self.all_render_funcs = {} for item in dir(self): if item.startswith('render_'): self.all_render_funcs[item[7:]] = getattr(self, item) def render__only_text(self, text): return text def post_process_text(self, text): """ Process the rendered text. :param str text: Rendered text :return str: """ return text class Htmlrenderer(Renderer): """ Transform the lexer results in html code. :param bool use_underline: - ``True``: The markdown ``_text_`` will transform in ``<ins>text</ins>`` - ``False``: The markdown ``_text_`` will transform in ``<em>text</em>`` :param bool use_paragraph: - ``True``: The new line in the markdown text will transform in ``<p></p>`` html tag. - ``False``: The new line in the markdown text will transform in ``<br>`` html tag. :param bool escape_html: - ``True``: Escape the html tag in the markdown text. - ``False``: No escape the html tag in the markdown text. """ scheme_blacklist = ('javascript', 'data', 'vbscript') def __init__(self, use_underline=True, use_paragraph=True, escape_html=True): super(HtmlRenderer, self).__init__() self.use_underline = use_underline self.use_paragraph = use_paragraph self.escape_html = escape_html def escape(self, text): """ Escape dangerous html characters. :param str text: Html text without escape. :return: Html text escaped. """ if not self.escape_html or text is None: return text return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;') def escape_args(self, *args): """ Escape html characters of all arguments :param [str] \\*args: List of html text without escape. :return: list of all arguments escaped. """ return tuple((self.escape(arg) for arg in args)) def escape_link(self, link, smart_amp=True): """ Check if a link has an invalid scheme. Also transform the ``&`` character in ``&amp;`` character. :param str link: Link checked. :param bool smart_amp: Transform the '&' characters in '&amp;' characters. :return: Return the link if the scheme is valid. If not return an empty string. """ data = link.split(':', 1) scheme = data[0] if scheme in self.scheme_blacklist: return '' if smart_amp: return link.replace('&', '&amp;') return link def render_escape_backslash(self, text): return self.escape(text) def render_bold(self, text): return '<strong>%s</strong>' % self.escape(text) def render_italic(self, text): return '<em>%s</em>' % self.escape(text) def render_underline(self, text): if self.use_underline: return '<ins>%s</ins>' % self.escape(text) else: return self.use_italic(text) def render_strike(self, text): return '<del>%s</del>' % self.escape(text) def render_code_inline(self, code): return '<code>%s</code>' % self.escape(code) def render_link(self, text, href, title=''): text = self.escape(text) href = self.escape_link(href) if title: return '<a href="%s" title="%s">%s</a>' % (href, self.escape(title), text) return '<a href="%s">%s</a>' % (href, text) def render_image(self, src, alt, title=''): alt = self.escape(alt) src = self.escape_link(src) if title: title = self.escape(title) return '<img src="%s" alt="%s" title="%s">' % (src, alt, title) return '<img src="%s" alt="%s">' % (src, alt) def render_new_line(self, text): if self.use_paragraph: return '<p>%s</p>' % self.escape(text) if text else '' else: return '%s<br/>' % self.escape(text) if text else '' def render_olist(self, text, start): text = self.escape(text) return '<ol start="%d">%s</ol>' % (start, text) def render_olist_item(self, text): return '<li>%s</li>' % self.escape(text) def render_ulist(self, text, start): return '<ul>%s</ul>' % self.escape(text) def render_ulist_item(self, text): return '<li>%s</li>' % self.escape(text) def render_blockquote(self, text): return '<blockquote>%s</blockquote>' % self.escape(text) def render_header(self, text, level): return '<h{level}>{text}</h{level}>'.format(level=level, text=self.escape(text)) def render_fenced_code(self, code, lang='', title=''): return '<pre>%s</pre>' % self.escape(code) def render_break_line(self, symbol): return '<hr/>' def render_table(self, text): return '<table>%s</table>' % text def render_table_header(self, text): return '<thead><tr>%s</tr></thead>' % text def render_table_header_cell(self, text): return '<th>%s</th>' % text def render_table_body(self, text): return '<tbody>%s</tbody>' % text def render_table_body_row(self, text): return '<tr>%s</tr>' % text def render_table_body_cell(self, text, align=''): if align and align != 'left': return '<td style="text-align:%s;">%s</td>' % (align, text) else: return '<td>%s</td>' % text
class Sense: def __init__(self, short: str, ident: int): self.ident = ident self.short = short self.pref_label = '' self.alt_labels = [] def add_pref_label(self, pref_label: str): self.__check_pref_label_not_set(pref_label) self.pref_label = pref_label def add_alt_label(self, alt_label: str): if alt_label not in self.alt_labels: self.alt_labels.append(alt_label) def __check_pref_label_not_set(self, pref_label: str): if self.pref_label != '': raise ValueError(f"{pref_label} of {self.short} was already set to {self.pref_label}") def check_pref_label_was_set(self): if self.pref_label == '': raise ValueError(f"pref_label of {self.short} was not set") def get_dict_rep(self) -> dict: return { "ident": self.ident, "pref_label": self.pref_label, "alt_labels": self.alt_labels }
class Sense: def __init__(self, short: str, ident: int): self.ident = ident self.short = short self.pref_label = '' self.alt_labels = [] def add_pref_label(self, pref_label: str): self.__check_pref_label_not_set(pref_label) self.pref_label = pref_label def add_alt_label(self, alt_label: str): if alt_label not in self.alt_labels: self.alt_labels.append(alt_label) def __check_pref_label_not_set(self, pref_label: str): if self.pref_label != '': raise value_error(f'{pref_label} of {self.short} was already set to {self.pref_label}') def check_pref_label_was_set(self): if self.pref_label == '': raise value_error(f'pref_label of {self.short} was not set') def get_dict_rep(self) -> dict: return {'ident': self.ident, 'pref_label': self.pref_label, 'alt_labels': self.alt_labels}
""" TFIDF + SGD Model for text classification """ class GloveRNNModel(object): """Recurrent Neural Network Model for text classification""" def __init__(self, data_dir): super(GloveRNNModel, self).__init__() self.data_dir = data_dir def get_details(self): """ Get a dictionary of attributes about the model to expose to end users for documentations purposes """ return { "embedder": "GloVe", "algorithm": "RNN-LSTM" } def train(self, training_data): raise NotImplementedError('This model is not yet implemented') def predict(self, samples): raise NotImplementedError('This model is not yet implemented')
""" TFIDF + SGD Model for text classification """ class Glovernnmodel(object): """Recurrent Neural Network Model for text classification""" def __init__(self, data_dir): super(GloveRNNModel, self).__init__() self.data_dir = data_dir def get_details(self): """ Get a dictionary of attributes about the model to expose to end users for documentations purposes """ return {'embedder': 'GloVe', 'algorithm': 'RNN-LSTM'} def train(self, training_data): raise not_implemented_error('This model is not yet implemented') def predict(self, samples): raise not_implemented_error('This model is not yet implemented')
# Test the connection to the database def test_ping(client): response = client.get("/ping") assert response.status_code == 200 assert response.json() == {"ping": "pong!"} def test_root(client): response = client.get("/") assert response.status_code == 200 assert response.json() == {"Message": "Try /docs or /redoc"}
def test_ping(client): response = client.get('/ping') assert response.status_code == 200 assert response.json() == {'ping': 'pong!'} def test_root(client): response = client.get('/') assert response.status_code == 200 assert response.json() == {'Message': 'Try /docs or /redoc'}
def power(a,b): if b==0: return 1 elif b%2 == 0: val = power(a,int(b/2)) return val*val else: oddval = power(a,b-1) return a*oddval # take base a = int(input()) #take exponent b = int(input()) # to find a^b we divide b in two halves recursively. answer=power(a,b) print(answer)
def power(a, b): if b == 0: return 1 elif b % 2 == 0: val = power(a, int(b / 2)) return val * val else: oddval = power(a, b - 1) return a * oddval a = int(input()) b = int(input()) answer = power(a, b) print(answer)
senha = int(input()) while senha != 2002: print("Senha Invalida") senha = int(input()) print("Acesso Permitido")
senha = int(input()) while senha != 2002: print('Senha Invalida') senha = int(input()) print('Acesso Permitido')
""" Practising classes and OOPs """ class Robot: def __init__(self, name=None, build_year=None) -> None: self.name = name self.build_year = build_year def say_hi(self): if self.name: print(f"Hi i am {self.name}") else: print("Robot without name") if self.build_year: print(f"I was built in {self.build_year}") else: print("year unknown") def set_name(self, name): self.name = name def get_name(self): return self.name def set_build_year(self, build_year): self.build_year = build_year def get_build_year(self): return self.build_year # example of duck typing def __len__(self): return 90101 x = Robot("Henry", 2020) y = Robot() print(x.get_name(), x.get_build_year()) print(y.get_name(), y.get_build_year()) y.set_name('Marvin') x.say_hi() y.say_hi() print(len(x))
""" Practising classes and OOPs """ class Robot: def __init__(self, name=None, build_year=None) -> None: self.name = name self.build_year = build_year def say_hi(self): if self.name: print(f'Hi i am {self.name}') else: print('Robot without name') if self.build_year: print(f'I was built in {self.build_year}') else: print('year unknown') def set_name(self, name): self.name = name def get_name(self): return self.name def set_build_year(self, build_year): self.build_year = build_year def get_build_year(self): return self.build_year def __len__(self): return 90101 x = robot('Henry', 2020) y = robot() print(x.get_name(), x.get_build_year()) print(y.get_name(), y.get_build_year()) y.set_name('Marvin') x.say_hi() y.say_hi() print(len(x))
#body_x = 120 body_x = 140 body_y = 160 bottom_z = 15 bottom_wall_thikness = 1.5 dist_between_whells = 90
body_x = 140 body_y = 160 bottom_z = 15 bottom_wall_thikness = 1.5 dist_between_whells = 90
DARKEST_GREEN = (15, 56, 15) DARK_GREEN = (48, 98, 48) LIGHT_GREEN = (111, 135, 12) LIGHTEST_GREEN = (155, 188, 15) DARKEST_GREEN_VAL = 3 DARK_GREEN_VAL = 2 LIGHT_GREEN_VAL = 1 LIGHTEST_GREEN_VAL = 0
darkest_green = (15, 56, 15) dark_green = (48, 98, 48) light_green = (111, 135, 12) lightest_green = (155, 188, 15) darkest_green_val = 3 dark_green_val = 2 light_green_val = 1 lightest_green_val = 0
RUN_CONFIGURATIONS = { "Python.DjangoServer": [ ] } class RunConfiguration: pass # workspace.xml # <?xml version="1.0" encoding="UTF-8"?> # <project version="4"> # <component name="RunManager" selected="npm.build-prod"> # <configuration name="Worker" type="Python.DjangoServer" factoryName="Django server"> # <module name="CKDemo" /> # <option name="INTERPRETER_OPTIONS" value="" /> # <option name="PARENT_ENVS" value="true" /> # <envs> # <env name="PYTHONUNBUFFERED" value="1" /> # <env name="DJANGO_SETTINGS_MODULE" value="pycharm" /> # </envs> # <option name="SDK_HOME" value="$USER_HOME$/.virtualenvs/CKDemo/bin/python" /> # <option name="WORKING_DIRECTORY" value="" /> # <option name="IS_MODULE_SDK" value="false" /> # <option name="ADD_CONTENT_ROOTS" value="true" /> # <option name="ADD_SOURCE_ROOTS" value="true" /> # <option name="launchJavascriptDebuger" value="false" /> # <option name="host" value="" /> # <option name="additionalOptions" value="-Q celery" /> # <option name="browserUrl" value="" /> # <option name="runTestServer" value="false" /> # <option name="runNoReload" value="false" /> # <option name="useCustomRunCommand" value="true" /> # <option name="customRunCommand" value="worker" /> # <method v="2" /> # </configuration>
run_configurations = {'Python.DjangoServer': []} class Runconfiguration: pass
# DEBUG ERROR="\033[31mERROR\033[0m" SUCCESS="\033[32mSUCCESS\033[0m" #ALGORITHM CONFIGS NUM_ATTRS = 8 NUM_TARGETS = 1 NORMALIZE_TARGETS = False TRAIN_RATIO = (2.0/3.0) INPUT_DELIMITER = ',' HAS_HEADER=False NUM_DIGITS = 5 NUM_NEIGHBOURS = 5 EXCLUDE_ATTRS= [] PREDICT_TARGET = 8 NUM_NEURONS_HIDDEN_LAYER = 9 LEARNING_RATE = 0.2 NUM_EPOCHS = 40
error = '\x1b[31mERROR\x1b[0m' success = '\x1b[32mSUCCESS\x1b[0m' num_attrs = 8 num_targets = 1 normalize_targets = False train_ratio = 2.0 / 3.0 input_delimiter = ',' has_header = False num_digits = 5 num_neighbours = 5 exclude_attrs = [] predict_target = 8 num_neurons_hidden_layer = 9 learning_rate = 0.2 num_epochs = 40
CLIENT_ID_ENV_VAR = 'SPOTIFY_CLIENT_ID' CLIENT_SECRET_ENV_VAR = 'SPOTIFY_CLIENT_SECRET' USERNAME_ENV_VAR = 'SPOTIFY_USERNAME' SPOTIFY_API_SCOPE = 'playlist-modify-private,playlist-read-private,user-library-modify,user-library-read' DEFAULT_REDIRECT_URL = 'http://localhost:8888/callback'
client_id_env_var = 'SPOTIFY_CLIENT_ID' client_secret_env_var = 'SPOTIFY_CLIENT_SECRET' username_env_var = 'SPOTIFY_USERNAME' spotify_api_scope = 'playlist-modify-private,playlist-read-private,user-library-modify,user-library-read' default_redirect_url = 'http://localhost:8888/callback'
class Data: #Class Data is designed to hold an object in a tree # name: the name of the node, generally more for the leaves and root # length: the length of the branch from its top node def __init__( self, name, length, id = 0 ): self.name = name self.length = length self.id = id def __str__( self ): return "["+self.name+", "+ str( self.length ) + "]" def Name( self ): return self.name def Length( self ): return self.length def Match( self, to_match ): return to_match == self.name class Node: #Class Node has # data: holding the node's current data # sub: a list of the node's subordinate nodes def __init__( self ): self.data = Data("","0") self.sub = [] self.parent = 0 def leaf( self, data ): self.data = data self.sub = [] def internal( self, data, sub ): self.sub = sub for item in self.sub: item.parent = self self.data = data def children( self ): return len( self.sub ) def __str__( self ): total = "" total = self.data.__str__() if len( self.sub ) > 0: total = total + "->(" for item in self.sub: total = total + item.__str__() + "," total = total[:len(total)-1] + ")" return total #Search current node and subordinate nodes for the node with data.name equal to name def Search_For_Name( self, name ): for item in self.sub: if item.data.name == name: return item else: to_return = item.Search_For_Name( name ) if( to_return != 0 ): return to_return return 0 #Find the longest branch distance below this node def Longest_Branch( self ): current_x = self.data.Length() middle_x = 0 for each_item in self.sub: newest_x = each_item.Longest_Branch() if middle_x < newest_x: middle_x = newest_x returning = current_x + middle_x return returning #Return a list of the gi's found subordinate to this node def GI_List( self ): gi_list = [] if(len(self.sub)>0): for item in self.sub: if item.data.name != '': gi_list.append(item.data.name) else: gi_list = gi_list + item.GI_List() else: gi_list.append( self.data.name ) return gi_list #Wrapper class to hold a node class Tree: def __init__(self, node): self.node = node #Find the longest branch in the tree. If root_node is not 0, it is the star point def Longest_Branch(self, root_node=0): if( root_node == 0 ): root_node = self.node current_x = root_node.data.Length() middle_x = 0 for each_item in root_node.sub: newest_x = self.Longest_Branch(each_item) if middle_x < newest_x: middle_x = newest_x returning = current_x + middle_x return returning #Search for a node given a name def Get_Node_By_Name( self, name ): if self.node.data.name == name: return root else: return self.node.Search_For_Name( name )
class Data: def __init__(self, name, length, id=0): self.name = name self.length = length self.id = id def __str__(self): return '[' + self.name + ', ' + str(self.length) + ']' def name(self): return self.name def length(self): return self.length def match(self, to_match): return to_match == self.name class Node: def __init__(self): self.data = data('', '0') self.sub = [] self.parent = 0 def leaf(self, data): self.data = data self.sub = [] def internal(self, data, sub): self.sub = sub for item in self.sub: item.parent = self self.data = data def children(self): return len(self.sub) def __str__(self): total = '' total = self.data.__str__() if len(self.sub) > 0: total = total + '->(' for item in self.sub: total = total + item.__str__() + ',' total = total[:len(total) - 1] + ')' return total def search__for__name(self, name): for item in self.sub: if item.data.name == name: return item else: to_return = item.Search_For_Name(name) if to_return != 0: return to_return return 0 def longest__branch(self): current_x = self.data.Length() middle_x = 0 for each_item in self.sub: newest_x = each_item.Longest_Branch() if middle_x < newest_x: middle_x = newest_x returning = current_x + middle_x return returning def gi__list(self): gi_list = [] if len(self.sub) > 0: for item in self.sub: if item.data.name != '': gi_list.append(item.data.name) else: gi_list = gi_list + item.GI_List() else: gi_list.append(self.data.name) return gi_list class Tree: def __init__(self, node): self.node = node def longest__branch(self, root_node=0): if root_node == 0: root_node = self.node current_x = root_node.data.Length() middle_x = 0 for each_item in root_node.sub: newest_x = self.Longest_Branch(each_item) if middle_x < newest_x: middle_x = newest_x returning = current_x + middle_x return returning def get__node__by__name(self, name): if self.node.data.name == name: return root else: return self.node.Search_For_Name(name)
nested = {} for i, v in mut.iterrows(): if i not in nested: nested[i] = {} sample = v['Tumor_Sample_Barcode'] if sample not in nested[i]: nested[i][sample] = {} mut_type = v['Variant_Classification'] if mut_type not in nested[i][sample]: nested[i][sample][mut_type] = [] hgvsp = v['HGVSp_Short'] nested[i][sample][mut_type].append(hgvsp) if len(nested[i][sample][mut_type]) > 1: print(i) print(nested[i][sample][mut_type]) transformed_arrs = {} for i, v in mut.iterrows(): variant = v['Variant_Classification'] gene_idx = i + ' ' + variant sample = v['Tumor_Sample_Barcode'] if gene_idx not in transformed_arrs: transformed_arrs[gene_idx] = {} transformed_arrs[gene_idx]['Gene symbol'] = i transformed_arrs[gene_idx]['Variant_Classification'] = variant for s in mut_samples: s_fixed = s.split('_')[0] if s_fixed not in transformed_arrs[gene_idx]: transformed_arrs[gene_idx][s_fixed] = 0 if s == sample: transformed_arrs[gene_idx][s_fixed] += 1 print(transformed_arrs)
nested = {} for (i, v) in mut.iterrows(): if i not in nested: nested[i] = {} sample = v['Tumor_Sample_Barcode'] if sample not in nested[i]: nested[i][sample] = {} mut_type = v['Variant_Classification'] if mut_type not in nested[i][sample]: nested[i][sample][mut_type] = [] hgvsp = v['HGVSp_Short'] nested[i][sample][mut_type].append(hgvsp) if len(nested[i][sample][mut_type]) > 1: print(i) print(nested[i][sample][mut_type]) transformed_arrs = {} for (i, v) in mut.iterrows(): variant = v['Variant_Classification'] gene_idx = i + ' ' + variant sample = v['Tumor_Sample_Barcode'] if gene_idx not in transformed_arrs: transformed_arrs[gene_idx] = {} transformed_arrs[gene_idx]['Gene symbol'] = i transformed_arrs[gene_idx]['Variant_Classification'] = variant for s in mut_samples: s_fixed = s.split('_')[0] if s_fixed not in transformed_arrs[gene_idx]: transformed_arrs[gene_idx][s_fixed] = 0 if s == sample: transformed_arrs[gene_idx][s_fixed] += 1 print(transformed_arrs)
# Config for automato # WTF config WTF_CSRF_ENABLED = True SECRET_KEY = 'the_very_secure_secret_security_key_that_no_will_ever_guess' # MySQL Config SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:alpine@127.0.0.1/automato' SQLALCHEMY_TRACK_MODIFICATIONS = False RABBITMQ_HOST = "localhost" WEBDRIVER_PATH = r"C:\Users\padam\Downloads\chromedriver_win32\chromedriver.exe" TESTING = False
wtf_csrf_enabled = True secret_key = 'the_very_secure_secret_security_key_that_no_will_ever_guess' sqlalchemy_database_uri = 'mysql+pymysql://root:alpine@127.0.0.1/automato' sqlalchemy_track_modifications = False rabbitmq_host = 'localhost' webdriver_path = 'C:\\Users\\padam\\Downloads\\chromedriver_win32\\chromedriver.exe' testing = False
def rmtree(root): """ Function to remove a directory and its contents :param root: The root directory :type root: pathlib.Path """ for p in root.iterdir(): if p.is_dir(): rmtree(p) else: p.unlink() root.rmdir()
def rmtree(root): """ Function to remove a directory and its contents :param root: The root directory :type root: pathlib.Path """ for p in root.iterdir(): if p.is_dir(): rmtree(p) else: p.unlink() root.rmdir()
class Solution: def fourSum(self, nums, target): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() results = [] self.findNsum(nums, target, 4, [], results) return results def findNsum(self, sorted_nums, target, N, result, results): n = len(sorted_nums) if N == 2: L = 0 R = n - 1 while L < R: A = sorted_nums[L] B = sorted_nums[R] s = A + B if s < target: L += 1 elif s > target: R -= 1 else: results.append(result + [A, B]) while L + 1 < n and A == sorted_nums[L]: L += 1 while R > 0 and B == sorted_nums[R]: R -= 1 else: for i in range(n-N+1): if target < sorted_nums[i] * N or target > sorted_nums[-1] * N: break if (i == 0) or (i > 0 and sorted_nums[i] != sorted_nums[i-1]): self.findNsum(sorted_nums[i+1:], target-sorted_nums[i], N-1, result+[sorted_nums[i]], results) if __name__ == '__main__': s = Solution() print(s.fourSum([1, 0, -1, 0, -2, 2], 0)) # print(s.fourSum([-1,0,1,2,-1,-4])) # print(s.threeSum([-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0])) # print(s.threeSum([-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6])) # print(s.threeSum([13,4,-6,-7,-15,-1,0,-1,0,-12,-12,9,3,-14,-2,-5,-6,7,8,2,-4,6,-5,-10,-4,-9,-14,-14,12,-13,-7,3,7,2,11,7,9,-4,13,-6,-1,-14,-12,9,9,-6,-11,10,-14,13,-2,-11,-4,8,-6,0,7,-12,1,4,12,9,14,-4,-3,11,10,-9,-8,8,0,-1,1,3,-15,-12,4,12,13,6,10,-4,10,13,12,12,-2,4,7,7,-15,-4,1,-15,8,5,3,3,11,2,-11,-12,-14,5,-1,9,0,-12,6,-1,1,1,2,-3])) # print(s.threeSum([-4,-8,7,13,10,1,-14,-13,0,8,6,-13,-5,-4,-12,2,-11,7,-5,0,-9,-14,-8,-9,2,-7,-13,-3,13,9,-14,-6,8,1,14,-5,-13,8,-10,-5,1,11,-11,3,14,-8,-10,-12,6,-8,-5,13,-15,2,11,-5,10,6,-1,1,0,0,2,-7,8,-6,3,3,-13,8,5,-5,-3,9,5,-4,-14,11,-8,7,10,-6,-3,11,12,-14,-9,-1,7,5,-15,14,12,-5,-8,-2,4,2,-14,-2,-12,6,8,0,0,-2,3,-7,-14,2,7,12,12,12,0,9,13,-2,-15,-3,10,-14,-4,7,-12,3,-10]))
class Solution: def four_sum(self, nums, target): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() results = [] self.findNsum(nums, target, 4, [], results) return results def find_nsum(self, sorted_nums, target, N, result, results): n = len(sorted_nums) if N == 2: l = 0 r = n - 1 while L < R: a = sorted_nums[L] b = sorted_nums[R] s = A + B if s < target: l += 1 elif s > target: r -= 1 else: results.append(result + [A, B]) while L + 1 < n and A == sorted_nums[L]: l += 1 while R > 0 and B == sorted_nums[R]: r -= 1 else: for i in range(n - N + 1): if target < sorted_nums[i] * N or target > sorted_nums[-1] * N: break if i == 0 or (i > 0 and sorted_nums[i] != sorted_nums[i - 1]): self.findNsum(sorted_nums[i + 1:], target - sorted_nums[i], N - 1, result + [sorted_nums[i]], results) if __name__ == '__main__': s = solution() print(s.fourSum([1, 0, -1, 0, -2, 2], 0))
# Copyright 2017 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. DEPS = [ 'raw_io', 'step', ] def RunSteps(api): # Read command's stdout and stderr. step_result = api.step('echo', ['echo', 'Hello World'], stdout=api.raw_io.output(), stderr=api.raw_io.output()) # Pass stuff to command's stdin, read it from stdout. step_result = api.step('cat', ['cat'], stdin=api.raw_io.input_text(data='hello'), stdout=api.raw_io.output('out')) # Example of auto-mocking stdout. '\n' appended to mock 'echo' behavior. step_result = api.step( 'automock', ['echo', 'huh'], stdout=api.raw_io.output('out'), step_test_data=( lambda: api.raw_io.test_api.stream_output('huh\n'))) assert step_result.stdout == 'huh\n' def GenTests(api): yield api.test('basic')
deps = ['raw_io', 'step'] def run_steps(api): step_result = api.step('echo', ['echo', 'Hello World'], stdout=api.raw_io.output(), stderr=api.raw_io.output()) step_result = api.step('cat', ['cat'], stdin=api.raw_io.input_text(data='hello'), stdout=api.raw_io.output('out')) step_result = api.step('automock', ['echo', 'huh'], stdout=api.raw_io.output('out'), step_test_data=lambda : api.raw_io.test_api.stream_output('huh\n')) assert step_result.stdout == 'huh\n' def gen_tests(api): yield api.test('basic')
numbers = [int(i) for i in input().split()] average = sum(numbers) / len(numbers) all_greater_than_average = [greater for greater in numbers if greater > average] top_five = [] for j in range(5): if len(all_greater_than_average) == 0: break top_five.append(str(max(all_greater_than_average))) all_greater_than_average.remove(max(all_greater_than_average)) if len(top_five) == 0: print("No") else: print(" ".join(top_five))
numbers = [int(i) for i in input().split()] average = sum(numbers) / len(numbers) all_greater_than_average = [greater for greater in numbers if greater > average] top_five = [] for j in range(5): if len(all_greater_than_average) == 0: break top_five.append(str(max(all_greater_than_average))) all_greater_than_average.remove(max(all_greater_than_average)) if len(top_five) == 0: print('No') else: print(' '.join(top_five))
""" @author: acfromspace """ def unique_chars_in_string(input_string): return len(set(input_string)) == len(input_string) input_string = str(input("Input a string: ")) print("unique_chars_in_string():", unique_chars_in_string(input_string))
""" @author: acfromspace """ def unique_chars_in_string(input_string): return len(set(input_string)) == len(input_string) input_string = str(input('Input a string: ')) print('unique_chars_in_string():', unique_chars_in_string(input_string))
class Solution: def maxRepeating(self, sequence: str, word: str) -> int: mx = len(sequence) // len(word) for repeat in range(1, mx + 2): sub = word * repeat if sub not in sequence: return repeat - 1 return 0
class Solution: def max_repeating(self, sequence: str, word: str) -> int: mx = len(sequence) // len(word) for repeat in range(1, mx + 2): sub = word * repeat if sub not in sequence: return repeat - 1 return 0
class Node(object): """simple node for a linked list""" def __init__(self, e): self.next_ = None self.e = e class LinkedList(object): """linked list with simple built-in iterator""" def __init__(self): self.first = None self.last = None self.current = None self.size = 0 def next_(self): self.current = self.current.next_ def reset(self): self.current = self.first def is_empty(self): if self.size == 0: return True else: return False def add_e(self, e): node = Node(e) self.add_node(node) def add_node(self, node): if self.is_empty(): # our first node self.first = node self.last = node self.current = node else: self.last.next_ = node self.last = node self.size += 1
class Node(object): """simple node for a linked list""" def __init__(self, e): self.next_ = None self.e = e class Linkedlist(object): """linked list with simple built-in iterator""" def __init__(self): self.first = None self.last = None self.current = None self.size = 0 def next_(self): self.current = self.current.next_ def reset(self): self.current = self.first def is_empty(self): if self.size == 0: return True else: return False def add_e(self, e): node = node(e) self.add_node(node) def add_node(self, node): if self.is_empty(): self.first = node self.last = node self.current = node else: self.last.next_ = node self.last = node self.size += 1
"""Export2D - Export Fusion 360 model faces as PDF or DXF files""" __version__ = '0.1.0' __author__ = 'Patrick Rainsberry <patrick.rainsberry@autodesk.com>' __all__ = []
"""Export2D - Export Fusion 360 model faces as PDF or DXF files""" __version__ = '0.1.0' __author__ = 'Patrick Rainsberry <patrick.rainsberry@autodesk.com>' __all__ = []
test = { 'name': 'q2a', 'points': 1, 'suites': [ { 'cases': [ {'code': '>>> 600 < num_schools < 700\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> # Come back to this, not sure if it works;\n>>> num_schools == 659\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
test = {'name': 'q2a', 'points': 1, 'suites': [{'cases': [{'code': '>>> 600 < num_schools < 700\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> # Come back to this, not sure if it works;\n>>> num_schools == 659\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
__all__ = ['__name__', '__version__', '__author__', '__author_email__', '__description__'] __name__ = 'ssec' __version__ = '2.0.0' __author__ = 'Justin Baudisch' __author_email__ = 'baudischjustin1995@gmail.com' __description__ = 'Yet another client library for server-sent events (sse).'
__all__ = ['__name__', '__version__', '__author__', '__author_email__', '__description__'] __name__ = 'ssec' __version__ = '2.0.0' __author__ = 'Justin Baudisch' __author_email__ = 'baudischjustin1995@gmail.com' __description__ = 'Yet another client library for server-sent events (sse).'
# calculate the hamming distance between two numbers # count the number of 1 after xor operation of two number # citation: https://leetcode.com/articles/hamming-distance/ # approach 1: using library function def hamming_distance_using_library(x, y): xor = x ^ y return bin(xor).count('1') # approach 2: using bit shifting def hamming_distance_bit_shift(x, y): xor = x ^ y distance = 0 while xor: if xor & 1: # found 1 distance = distance + 1 xor = xor >> 1 return distance # approach 3: Brian Kernighan's Algorithm # approach 3 is faster than apporach 2 def hamming_distance_brian_kernighan(x, y): xor = x ^ y distance = 0 while xor: xor = xor & (xor - 1) # clears the right most set bit distance = distance + 1 return distance
def hamming_distance_using_library(x, y): xor = x ^ y return bin(xor).count('1') def hamming_distance_bit_shift(x, y): xor = x ^ y distance = 0 while xor: if xor & 1: distance = distance + 1 xor = xor >> 1 return distance def hamming_distance_brian_kernighan(x, y): xor = x ^ y distance = 0 while xor: xor = xor & xor - 1 distance = distance + 1 return distance
# -*- coding: utf-8 -*- __version__ = '1.4.0' default_app_config = 'djangocms_translations.apps.DjangocmsTranslationsConfig'
__version__ = '1.4.0' default_app_config = 'djangocms_translations.apps.DjangocmsTranslationsConfig'
_base_ = './tood_r50_fpn_1x_coco.py' model = dict( bbox_head=dict( anchor_type='anchor_based' ) )
_base_ = './tood_r50_fpn_1x_coco.py' model = dict(bbox_head=dict(anchor_type='anchor_based'))
# https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent def array_strings_are_equal(word1, word2): return ''.join(word1) == ''.join(word2)
def array_strings_are_equal(word1, word2): return ''.join(word1) == ''.join(word2)
A=[list(map(int,input().split())) for i in range(4)] flag=0 for x in range(4): for y in range(3): if A[x][y]==A[x][y+1] or A[y][x]==A[y+1][x]:flag=1 print("CONTINUE" if flag==1 else "GAMEOVER")
a = [list(map(int, input().split())) for i in range(4)] flag = 0 for x in range(4): for y in range(3): if A[x][y] == A[x][y + 1] or A[y][x] == A[y + 1][x]: flag = 1 print('CONTINUE' if flag == 1 else 'GAMEOVER')
#!/usr/bin/env python3 def betolt(file): megallok = [] with open(file, "rt") as f: for sor in f: megallok.append(sor.rstrip("\n")) return megallok def metszi_e(alista, blista): for elem in alista: if elem in blista: return elem return None def main(): print(metszi_e(betolt("4_m2.txt"), betolt("4_m4.txt"))) main()
def betolt(file): megallok = [] with open(file, 'rt') as f: for sor in f: megallok.append(sor.rstrip('\n')) return megallok def metszi_e(alista, blista): for elem in alista: if elem in blista: return elem return None def main(): print(metszi_e(betolt('4_m2.txt'), betolt('4_m4.txt'))) main()
''' 994. Rotting Oranges Medium In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. Example 1: Input: [[2,1,1],[1,1,0],[0,1,1]] Output: 4 Example 2: Input: [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. Example 3: Input: [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. Note: 1 <= grid.length <= 10 1 <= grid[0].length <= 10 grid[i][j] is only 0, 1, or 2. ''' def orangesRotting(self, grid: List[List[int]]) -> int: days = 0 while(True): if self.elapseMinute(grid) == 0: # Check if fresh oranges remain (edge case) # Impossible to infect all fresh oranges if self.isFreshOranges(grid): return -1 # No more infections, exit loop break; else: # Infection present, add to day count days+=1 # Return days return days # returns number of oranges infected this minute def elapseMinute(self, grid): # Tracks already seen rotten oranges seen_oranges = {} # Initialize infected orange count to 0 infected_min_count = 0 # Loop through entire grid for i in range(len(grid)): for j in range(len(grid[0])): # Check for rotten orange cell AND # If we have not infected this orange this same minute if grid[i][j] == 2 and (i, j) not in seen_oranges: # Rotten orange, infect adj oranges infected_min_count+=self.infect_adj(grid, i, j, seen_oranges) # return the number of infected oranges for this minute return infected_min_count # Infect adjacent cells # Returns number of oranges infected def infect_adj(self, grid, i, j, seen_oranges): infected_adj_count = 0 # Infect the orange grid[i][j] = 2 _i = i + 1 _j = j infected_adj_count+=self.infect_orange(_i, _j, grid, seen_oranges) _i = i - 1 _j = j infected_adj_count+=self.infect_orange(_i, _j, grid, seen_oranges) _i = i _j = j + 1 infected_adj_count+=self.infect_orange(_i, _j, grid, seen_oranges) _i = i _j = j - 1 infected_adj_count+=self.infect_orange(_i, _j, grid, seen_oranges) return infected_adj_count # Returns 1 if infected, else 0 def infect_orange(self, _i, _j, grid, seen_oranges): # Check range if (0 <= _i < len(grid)) and (0 <= _j < len(grid[0])): # Check for fresh orange if grid[_i][_j] == 1: # Infect into rotten orange grid[_i][_j] = 2 # Note this rotten orange has been seen seen_oranges[(_i,_j)] = 1 return 1 return 0 # Returns true if grid has fresh at least 1 fresh orange def isFreshOranges(self, grid): for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: return True return False
""" 994. Rotting Oranges Medium In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. Example 1: Input: [[2,1,1],[1,1,0],[0,1,1]] Output: 4 Example 2: Input: [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. Example 3: Input: [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. Note: 1 <= grid.length <= 10 1 <= grid[0].length <= 10 grid[i][j] is only 0, 1, or 2. """ def oranges_rotting(self, grid: List[List[int]]) -> int: days = 0 while True: if self.elapseMinute(grid) == 0: if self.isFreshOranges(grid): return -1 break else: days += 1 return days def elapse_minute(self, grid): seen_oranges = {} infected_min_count = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 2 and (i, j) not in seen_oranges: infected_min_count += self.infect_adj(grid, i, j, seen_oranges) return infected_min_count def infect_adj(self, grid, i, j, seen_oranges): infected_adj_count = 0 grid[i][j] = 2 _i = i + 1 _j = j infected_adj_count += self.infect_orange(_i, _j, grid, seen_oranges) _i = i - 1 _j = j infected_adj_count += self.infect_orange(_i, _j, grid, seen_oranges) _i = i _j = j + 1 infected_adj_count += self.infect_orange(_i, _j, grid, seen_oranges) _i = i _j = j - 1 infected_adj_count += self.infect_orange(_i, _j, grid, seen_oranges) return infected_adj_count def infect_orange(self, _i, _j, grid, seen_oranges): if 0 <= _i < len(grid) and 0 <= _j < len(grid[0]): if grid[_i][_j] == 1: grid[_i][_j] = 2 seen_oranges[_i, _j] = 1 return 1 return 0 def is_fresh_oranges(self, grid): for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: return True return False
""" Algorithm (BFS): 1. Collect all positions of the zombies into a queue. Then we will use this queue for collecting positions of humans only. 2. Find adjacent humans around each enqueued position. 3. Convert them into zombies. 4. Add their positions into a turned-into-zombie queue. 5. Increase number of the hours. 6. Repeat from 2 until all humans on the matrix will be found and processed. """ def minHour(rows, columns, grid): """ This function calculates the minimum hours to infect all humans. Args: rows: number of rows of the grid columns: number of columns of the grid grid: a 2D grid, each cell is either a zombie 1 or a human 0 Returns: minimum hours to infect all humans To use: grid=[[0, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0]] minHour(4,5,grid) Output: 2 Explanation: At the end of the 1st hour, the status of the grid: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 0, 1, 1], [1, 1, 1, 0, 1]] At the end of the 2nd hour, the status of the grid: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] """ # return 0 hour as there is no zombie if not rows or not columns: return 0 # Create a queue and collect all positions of the zombies into a queue q = [[i,j] for i in range(rows) for j in range(columns) if grid[i][j]==1] print("Original q:",q) # zombies can move to down, up, right, left directions = [[1,0],[-1,0],[0,1],[0,-1]] time = 0 while True: new = [] # Turn human into zombies every hour for [i,j] in q: for d in directions: ni = i + d[0] nj = j + d[1] # Find adjacent humans around each enqueued position if 0 <= ni < rows and 0 <= nj < columns and grid[ni][nj] == 0: # Convert them into zombies grid[ni][nj] = 1 # Add their positions into a new queue of zombies new.append([ni,nj]) print("\nAt the end of the ",time+1," hour, the status of the grid:") print(grid) q = new print("q:",q) # Repeat until all humans on the matrix will be found and processed # Empty queue, already turn all humans into zombies if not q: break #Increase number of the hours time += 1 return time grid=[[0, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0]] print("\nMinimum hours to infect all humans:",minHour(4,5,grid))
""" Algorithm (BFS): 1. Collect all positions of the zombies into a queue. Then we will use this queue for collecting positions of humans only. 2. Find adjacent humans around each enqueued position. 3. Convert them into zombies. 4. Add their positions into a turned-into-zombie queue. 5. Increase number of the hours. 6. Repeat from 2 until all humans on the matrix will be found and processed. """ def min_hour(rows, columns, grid): """ This function calculates the minimum hours to infect all humans. Args: rows: number of rows of the grid columns: number of columns of the grid grid: a 2D grid, each cell is either a zombie 1 or a human 0 Returns: minimum hours to infect all humans To use: grid=[[0, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0]] minHour(4,5,grid) Output: 2 Explanation: At the end of the 1st hour, the status of the grid: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 0, 1, 1], [1, 1, 1, 0, 1]] At the end of the 2nd hour, the status of the grid: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] """ if not rows or not columns: return 0 q = [[i, j] for i in range(rows) for j in range(columns) if grid[i][j] == 1] print('Original q:', q) directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] time = 0 while True: new = [] for [i, j] in q: for d in directions: ni = i + d[0] nj = j + d[1] if 0 <= ni < rows and 0 <= nj < columns and (grid[ni][nj] == 0): grid[ni][nj] = 1 new.append([ni, nj]) print('\nAt the end of the ', time + 1, ' hour, the status of the grid:') print(grid) q = new print('q:', q) if not q: break time += 1 return time grid = [[0, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0]] print('\nMinimum hours to infect all humans:', min_hour(4, 5, grid))
def sort(nums): for i in range(len(nums)-1, 0, -1): for j in range (i): if nums[j] > nums[j + 1]: temp = nums[j] nums[j] = nums[j + 1] nums[j + 1] = temp nums = [2,6,4,1,8,7] sort(nums) print(nums)
def sort(nums): for i in range(len(nums) - 1, 0, -1): for j in range(i): if nums[j] > nums[j + 1]: temp = nums[j] nums[j] = nums[j + 1] nums[j + 1] = temp nums = [2, 6, 4, 1, 8, 7] sort(nums) print(nums)
counter=1 def setup(): size(500,500) smooth() def draw(): global counter noStroke() fill (10, 50) rect (-1,-1, width//2 +1, height +1) ny = sin( counter ) *100+200 nx = counter *10 stroke (250) strokeWeight (20) line(nx , ny , nx , ny) counter = counter + 0.1 if(nx > width): counter = 0 def keyPressed (): if (key =='s'): saveFrame("myProcessing.png")
counter = 1 def setup(): size(500, 500) smooth() def draw(): global counter no_stroke() fill(10, 50) rect(-1, -1, width // 2 + 1, height + 1) ny = sin(counter) * 100 + 200 nx = counter * 10 stroke(250) stroke_weight(20) line(nx, ny, nx, ny) counter = counter + 0.1 if nx > width: counter = 0 def key_pressed(): if key == 's': save_frame('myProcessing.png')
class Calc: """Simple calculator.""" def __init__(self, a, b): self.a = a self.b = b def do(self): """Perform calculation.""" return self.a + self.b
class Calc: """Simple calculator.""" def __init__(self, a, b): self.a = a self.b = b def do(self): """Perform calculation.""" return self.a + self.b
#!/usr/bin/env python3 # -*- coding:utf-8 -*- class WikiBase(object): WikiLineSep = '\r\n' def __init__(self, wikiId, client): self.client = client self.wikiPage = client.wiki(wikiId) def writeWikiPage(self, content, mailNotify=False): wikiName = self.wikiPage['name'] params = { 'name': wikiName, 'content': content, 'mailNotify': str(mailNotify).lower() } self.client.update_wiki(self.wikiPage['id'], params) if __name__ == '__main__': pass
class Wikibase(object): wiki_line_sep = '\r\n' def __init__(self, wikiId, client): self.client = client self.wikiPage = client.wiki(wikiId) def write_wiki_page(self, content, mailNotify=False): wiki_name = self.wikiPage['name'] params = {'name': wikiName, 'content': content, 'mailNotify': str(mailNotify).lower()} self.client.update_wiki(self.wikiPage['id'], params) if __name__ == '__main__': pass
# The final segments are shown by calling the property ``t_masked`` which returns the # target data as an ndarray with NaN values for areas not found to be segments. plt.figure(figsize=(15,3)) # doctest: +SKIP plt.plot(s.t_masked.T) # doctest: +SKIP plt.xlabel("time in s") # doctest: +SKIP plt.ylabel("ECG in mV") # doctest: +SKIP plt.tight_layout() # doctest: +SKIP plt.show() # doctest: +SKIP
plt.figure(figsize=(15, 3)) plt.plot(s.t_masked.T) plt.xlabel('time in s') plt.ylabel('ECG in mV') plt.tight_layout() plt.show()
def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] # python3 #return ["Hello World"] # python2 # uwsgi --http :8000 --wsgi-file test.py # uwsgi --http :8000 --home /home/ubuntu/venv --chdir /home/ubuntu/ShirtGeeks/src/ --module conf.wsgi
def application(env, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return [b'Hello World']
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Initialization module for NAAS. Sets version """ __version__ = "0.6.2" __base_response__ = {"app": "naas", "version": __version__}
""" Initialization module for NAAS. Sets version """ __version__ = '0.6.2' __base_response__ = {'app': 'naas', 'version': __version__}
def count_bags(balls, diff): count = 0 target = diff while balls >= target: print(f"Target {target} Balls {balls}") count += 1 balls -= target target += diff return count if __name__ == '__main__': bags, balls, diff = map(int, input().split()) print(bags - count_bags(balls, diff))
def count_bags(balls, diff): count = 0 target = diff while balls >= target: print(f'Target {target} Balls {balls}') count += 1 balls -= target target += diff return count if __name__ == '__main__': (bags, balls, diff) = map(int, input().split()) print(bags - count_bags(balls, diff))
class AddrStats: """A simple class detailing stats on the read addresses ... Keeps track of address info AND writes to the results file specified, no parsing in this class""" # Constructor def __init__(self, resultsFile='results.txt', hasOffset=True, debug=False, debugAll=False): self.hasOffset = hasOffset # excel offset self.resultsFile = resultsFile # city write file self.badAddress = 0 # count of bad address strings self.goodAddress = 0 # count of good address strings if hasOffset: self.currentAddrIndex = 4 else: self.currentAddrIndex = 0 self.resultsStream = open(resultsFile, 'w') # write stream self.debug = debug self.debugAll = debugAll # Write no city to results file def writeNoCity(self): self.badAddress = self.badAddress + 1 self.resultsStream.write('\n') # Write city to results file def writeCity(self, city): self.goodAddress = self.goodAddress + 1 self.resultsStream.write(city + '\n') # increment addr index def incrCurrentIndex(self): self.currentAddrIndex = self.currentAddrIndex + 1 # a print function for debugging def debugPrint(self, addrElements, distr='NO_District', key='NoKEY',correctCity=''): if self.debugAll or (self.debug and key == 'noValidCity' or key == 'tooShort'): if isinstance(addrElements, list): print(self.currentAddrIndex, distr, correctCity, key + '\t: ', " ".join(addrElements)) else: print(self.currentAddrIndex, distr, key + '\t: ', correctCity, addrElements) # display resulting good and bad address counts def dispCityResults(self): print('\nTotal: {}'.format(self.goodAddress + self.badAddress)) print('Good: {}'.format(self.goodAddress)) print('Bad: {}'.format(self.badAddress)) print('Ratio: {}\n'.format(self.goodAddress / (self.goodAddress + self.badAddress))) print(f'All cities identified have been written to {self.resultsFile}') print('All invalid addresses have a blank line instead')
class Addrstats: """A simple class detailing stats on the read addresses ... Keeps track of address info AND writes to the results file specified, no parsing in this class""" def __init__(self, resultsFile='results.txt', hasOffset=True, debug=False, debugAll=False): self.hasOffset = hasOffset self.resultsFile = resultsFile self.badAddress = 0 self.goodAddress = 0 if hasOffset: self.currentAddrIndex = 4 else: self.currentAddrIndex = 0 self.resultsStream = open(resultsFile, 'w') self.debug = debug self.debugAll = debugAll def write_no_city(self): self.badAddress = self.badAddress + 1 self.resultsStream.write('\n') def write_city(self, city): self.goodAddress = self.goodAddress + 1 self.resultsStream.write(city + '\n') def incr_current_index(self): self.currentAddrIndex = self.currentAddrIndex + 1 def debug_print(self, addrElements, distr='NO_District', key='NoKEY', correctCity=''): if self.debugAll or (self.debug and key == 'noValidCity' or key == 'tooShort'): if isinstance(addrElements, list): print(self.currentAddrIndex, distr, correctCity, key + '\t: ', ' '.join(addrElements)) else: print(self.currentAddrIndex, distr, key + '\t: ', correctCity, addrElements) def disp_city_results(self): print('\nTotal: {}'.format(self.goodAddress + self.badAddress)) print('Good: {}'.format(self.goodAddress)) print('Bad: {}'.format(self.badAddress)) print('Ratio: {}\n'.format(self.goodAddress / (self.goodAddress + self.badAddress))) print(f'All cities identified have been written to {self.resultsFile}') print('All invalid addresses have a blank line instead')